Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

Import the games and add the NumPlay launcher

Mason363a181d62c308f
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..a643c30b
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,7 @@
+build/
+tools/.fonts/
+__pycache__/
+*.pyc
+.DS_Store
+games/tetris/*/target/
+games/tetris/tetris/src/data/image.nppm
diff --git a/Makefile b/Makefile
new file mode 100644
index 00000000..2ba7e444
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,161 @@
+# NumPlay: one launcher app with every game, plus each game on its own.
+#
+# make build/NumPlay.nwa and build/apps/*.nwa (the release files)
+# make check link NumPlay.nwa like the calculator does, print sizes, check RAM
+# make sim build/NumPlay.nwb for the Epsilon simulator
+# make emu run NumPlay.nwa in the ARM emulator (tools/emu.py)
+# make clean
+#
+# Needs arm-none-eabi-gcc (with newlib), Node.js for nwlink, Python 3 with
+# Pillow, and Rust with the thumbv7em-none-eabihf target for Tetris.
+
+NWLINK ?= npx --yes -- [email protected]
+ARM_CC = arm-none-eabi-gcc
+ARM_LD = arm-none-eabi-ld
+ARM_OBJCOPY = arm-none-eabi-objcopy
+PY ?= python3
+CARGO ?= cargo
+B = build
+RAM_LIMIT = 153676
+
+EADK_CFLAGS := $(shell $(NWLINK) eadk-cflags-device)
+EADK_SIM_CFLAGS := $(shell $(NWLINK) eadk-cflags-simulator)
+
+.SECONDEXPANSION:
+
+# Per-game facts (order, screenshots) come from games/games.json.
+$(B)/games.mk: games/games.json tools/games_mk.py | $(B)
+ $(PY) tools/games_mk.py $< > $@
+-include $(B)/games.mk
+
+LAUNCHER_SRC = $(wildcard launcher/src/*.c)
+LAUNCHER_H = $(wildcard launcher/src/*.h)
+ARM_CFLAGS = -std=gnu11 $(EADK_CFLAGS) -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno \
+ -fno-tree-loop-distribute-patterns -ffunction-sections -fdata-sections -Ilauncher/src
+ARM_LINK = -nostartfiles --specs=nano.specs -Wl,--relocatable -Wl,--gc-sections -Wl,-e,main \
+ -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+
+.PHONY: all nwa apps check sim emu clean FORCE
+all: nwa apps
+nwa: $(B)/NumPlay.nwa
+
+$(B):
+ mkdir -p $(B)/modules $(B)/gen $(B)/arm $(B)/apps $(B)/sim
+
+# ------------------------------------------------------------------ modules
+# Each game builds itself as a partially linked object (its own Makefile's
+# `module` target), then becomes a NumPlay module: one block of flash, its RAM
+# moved into the shared arena, `main` renamed np_<game>_main.
+MOD_numdash = games/numdash/build/module.o
+MOD_crossyroad = games/crossyroad/output/module.o
+MOD_numdrive = games/numdrive/output/device/module.o
+MOD_chess = games/chess/output/module.o
+MOD_tetris = $(B)/tetris/raw.o
+ENTRY = main
+ENTRY_tetris = np_tetris_main
+
+$(B)/tetris/raw.o: FORCE | $(B)
+ mkdir -p $(B)/tetris
+ cd games/tetris/tetris && NWLINK="$(NWLINK)" $(CARGO) build --release --quiet
+ $(ARM_LD) -r --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)
+ @if [ "$*" != tetris ]; then $(MAKE) --no-print-directory -C games/$* module NWLINK="$(NWLINK)"; \
+ else $(MAKE) --no-print-directory $(MOD_tetris); fi
+ $(ARM_LD) -r -d -T tools/module.ld $(MOD_$*) -o $(B)/modules/$*.1.o
+ $(ARM_OBJCOPY) --keep-global-symbol=$(or $(ENTRY_$*),$(ENTRY)) $(B)/modules/$*.1.o $(B)/modules/$*.2.o
+ $(PY) tools/npmodule.py $(B)/modules/$*.2.o $@ --game $* --index $(INDEX_$*) \
+ --entry $(or $(ENTRY_$*),$(ENTRY)) --json $(B)/modules/$*.json
+
+MODULES = $(foreach g,$(GAMES),$(B)/modules/$(g).o)
+
+# ------------------------------------------------------------------ generated glue
+$(B)/gen/gametable.c: games/games.json tools/gen_games.py $(MODULES)
+ $(PY) tools/gen_games.py games/games.json $(B)/modules $(B)/gen
+
+$(B)/gen/shots_%.c: games/games.json tools/shots.py $$(SHOTS_$$*) | $(B)
+ cd games/$* && $(PY) ../../tools/shots.py --id $* --index $(INDEX_$*) $(COLORS_$*) ../../$@ $(SHOTS_REL_$*)
+
+# ------------------------------------------------------------------ NumPlay.nwa
+ARM_OBJS = $(patsubst launcher/src/%.c,$(B)/arm/%.o,$(LAUNCHER_SRC)) $(B)/arm/gametable.o $(B)/arm/arena.o \
+ $(B)/arm/marks.o $(foreach g,$(GAMES),$(B)/arm/shots_$(g).o)
+
+$(B)/arm/%.o: launcher/src/%.c $(LAUNCHER_H) | $(B)
+ $(ARM_CC) $(ARM_CFLAGS) -flto -c $< -o $@
+$(B)/arm/gametable.o: $(B)/gen/gametable.c launcher/src/np.h
+ $(ARM_CC) $(ARM_CFLAGS) -c $< -o $@
+$(B)/arm/shots_%.o: $(B)/gen/shots_%.c launcher/src/np.h
+ $(ARM_CC) $(ARM_CFLAGS) -c $< -o $@
+$(B)/arm/arena.o $(B)/arm/marks.o: $(B)/arm/%.o: $(B)/gen/gametable.c
+ $(ARM_CC) $(EADK_CFLAGS) -c $(B)/gen/$*.s -o $@
+$(B)/icon.o: launcher/assets/icon.png | $(B)
+ $(NWLINK) png-icon-o $< $@
+
+$(B)/NumPlay.nwa: $(ARM_OBJS) $(MODULES) $(B)/icon.o
+ $(ARM_CC) $(ARM_CFLAGS) $(ARM_LINK) -Wl,-T,$(B)/gen/numplay.ld -flinker-output=nolto-rel \
+ $(ARM_OBJS) $(MODULES) $(B)/icon.o -lm -lgcc -o $@
+ arm-none-eabi-strip --strip-unneeded $@
+ @$(PY) tools/sizes.py $@ $(B)/modules
+
+check: $(B)/NumPlay.nwa
+ $(NWLINK) nwa-bin --ram-length $(RAM_LIMIT) $< $(B)/NumPlay.bin
+ @echo "NumPlay.nwa installs as $$(wc -c < $(B)/NumPlay.bin) bytes; its RAM fits in $(RAM_LIMIT) bytes"
+
+# ------------------------------------------------------------------ games on their own
+APP_numdash = games/numdash/build/numdash.nwa:NumDash.nwa
+APP_crossyroad = games/crossyroad/output/crossyroad.nwa:CrossyRoad.nwa
+APP_numdrive = games/numdrive/output/device/numdrive.nwa:NumDrive.nwa
+APP_chess = games/chess/output/chess.nwa:NumChess.nwa
+APP_tetris = games/tetris/tetris/target/thumbv7em-none-eabihf/release/tetris:Tetris.nwa
+
+apps: | $(B)
+ $(MAKE) -C games/numdash build NWLINK="node node_modules/nwlink/bin/nwlink"
+ $(MAKE) -C games/crossyroad NWLINK="$(NWLINK)"
+ $(MAKE) -C games/numdrive NWLINK="$(NWLINK)"
+ $(MAKE) -C games/chess build NWLINK="$(NWLINK)"
+ cd games/tetris/tetris && NWLINK="$(NWLINK)" $(CARGO) build --release --quiet
+ cp $(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)))
+ cp $(word 1,$(subst :, ,$(APP_numdrive))) $(B)/apps/$(word 2,$(subst :, ,$(APP_numdrive)))
+ 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)))
+ arm-none-eabi-strip --strip-unneeded $(B)/apps/Tetris.nwa
+
+# ------------------------------------------------------------------ simulator
+SIM_numdash = games/numdash/build/sim-module.o
+SIM_crossyroad = games/crossyroad/output/sim-module.o
+SIM_numdrive = games/numdrive/output/npsim/sim-module.o
+SIM_chess = games/chess/output/sim-module.o
+SIM_tetris = $(B)/sim/tetris.o
+SIM_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 \
+ games/tetris/tetris/target/aarch64-apple-darwin/release/libtetris.a -o $@
+
+$(B)/sim/%.mod: FORCE | $(B)
+ @if [ "$*" != tetris ]; then $(MAKE) --no-print-directory -C games/$* sim-module NWLINK="$(NWLINK)"; \
+ else $(MAKE) --no-print-directory $(SIM_tetris); fi
+
+$(B)/sim/gen/gametable.c: games/games.json tools/gen_games.py $(MODULES)
+ $(PY) tools/gen_games.py games/games.json $(B)/modules $(B)/sim/gen --simulator
+
+sim: $(B)/NumPlay.nwb
+$(B)/NumPlay.nwb: $(LAUNCHER_SRC) $(LAUNCHER_H) $(B)/sim/gen/gametable.c $(foreach g,$(GAMES),$(B)/gen/shots_$(g).c) \
+ $(foreach g,$(GAMES),$(B)/sim/$(g).mod)
+ cc $(SIM_CFLAGS) -shared -undefined dynamic_lookup $(LAUNCHER_SRC) launcher/sim/*.c $(B)/sim/gen/gametable.c \
+ $(foreach g,$(GAMES),$(B)/gen/shots_$(g).c) $(foreach g,$(GAMES),$(SIM_$(g))) -o $@
+
+# ------------------------------------------------------------------ tools
+emu: $(B)/NumPlay.nwa
+ $(PY) tools/emu.py $< --ms 4000 --shots 3000 --out $(B)/emu
+
+clean:
+ rm -rf $(B)
+ -$(MAKE) -C games/numdash clean
+ -$(MAKE) -C games/crossyroad clean
+ -$(MAKE) -C games/numdrive clean
+ -$(MAKE) -C games/chess clean
+ -cd games/tetris/tetris && $(CARGO) clean
diff --git a/games/chess/.gitignore b/games/chess/.gitignore
new file mode 100644
index 00000000..fd6aad7f
--- /dev/null
+++ b/games/chess/.gitignore
@@ -0,0 +1,2 @@
+output/
+__pycache__/
diff --git a/games/chess/Makefile b/games/chess/Makefile
new file mode 100644
index 00000000..ae73f824
--- /dev/null
+++ b/games/chess/Makefile
@@ -0,0 +1,62 @@
+# NumChess — chess for the NumWorks calculator.
+# make build output/chess.nwa
+# make run install on a connected calculator
+# make check link the app like the calculator does (output/chess.bin)
+# make test run engine tests on the host
+Q ?= @
+CC = arm-none-eabi-gcc
+NWLINK = npx --yes -- [email protected]
+BUILD_DIR = output
+SRC = src/main.c src/chess.c src/libc.c
+
+CFLAGS = -std=c99 $(shell $(NWLINK) eadk-cflags-device)
+CFLAGS += -Os -Wall -fno-math-errno -fno-tree-loop-distribute-patterns -fno-reorder-functions -flto-partition=one
+CFLAGS += -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+.PHONY: build run check test clean
+build: $(BUILD_DIR)/chess.nwa
+
+run: $(BUILD_DIR)/chess.nwa
+ @echo "INSTALL $<"
+ $(Q) $(NWLINK) install-nwa $<
+
+check: $(BUILD_DIR)/chess.nwa
+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/chess.bin
+ @echo "BIN $(BUILD_DIR)/chess.bin: $$(wc -c < $(BUILD_DIR)/chess.bin) bytes"
+
+$(BUILD_DIR)/chess.nwa: $(SRC) src/chess.h src/sprites.h $(BUILD_DIR)/icon.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(SRC) $(BUILD_DIR)/icon.o -o $@
+ $(Q) arm-none-eabi-strip --strip-unneeded $@
+ $(Q) arm-none-eabi-size $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+test: | $(BUILD_DIR)
+ $(Q) cc -O2 -DPLATFORM_DEVICE=1 $(shell $(NWLINK) eadk-cflags-simulator) test/perft.c -o $(BUILD_DIR)/perft
+ $(Q) $(BUILD_DIR)/perft
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR)
+
+# NumPlay launcher: the game as a module (see ../../tools/npmodule.py) for the
+# calculator, and as a relocatable object for the simulator build.
+.PHONY: module sim-module
+module: $(BUILD_DIR)/module.o
+$(BUILD_DIR)/module.o: $(SRC) src/chess.h src/sprites.h | $(BUILD_DIR)
+ $(Q) $(CC) $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel $(SRC) -o $@
+
+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) \
+ -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/README.md b/games/chess/README.md
new file mode 100644
index 00000000..8787e9e3
--- /dev/null
+++ b/games/chess/README.md
@@ -0,0 +1,178 @@
+<p align="center">
+ <img src="docs/icon.png" width="84" alt="NumChess icon">
+</p>
+
+<h1 align="center">NumChess</h1>
+
+<p align="center">
+ <b>Chess for the NumWorks N0120 calculator.</b><br>
+ 12 bots, endless puzzles and a two-player clock, in a native app of about 20 KB.
+</p>
+
+<p align="center">
+ <a href="https://github.com/Mason363/NumChess/releases/latest"><img src="https://img.shields.io/github/v/release/Mason363/NumChess?label=release&color=81b64c" alt="Latest release"></a>
+ <a href="https://github.com/Mason363/NumChess/actions/workflows/build.yml"><img src="https://github.com/Mason363/NumChess/actions/workflows/build.yml/badge.svg" alt="Build status"></a>
+ <img src="https://img.shields.io/badge/installed%20size-20%20KB-3a3835" alt="Installed size: 20 KB">
+</p>
+
+<p align="center">
+ <a href="https://github.com/Mason363/NumChess/releases/latest/download/chess.nwa"><b>Download chess.nwa</b></a>
+ &nbsp;·&nbsp; <a href="#install">Install</a>
+ &nbsp;·&nbsp; <a href="#controls">Controls</a>
+ &nbsp;·&nbsp; <a href="#build">Build</a>
+</p>
+
+<p align="center">
+ <img src="docs/hero.gif" width="640" alt="Choosing a bot and playing the Italian Game against Nova">
+</p>
+
+## Highlights
+
+* **12 bots**, from Pip (150) to Atlas (2100), most of them at the beginner end.
+* **Endless puzzles** created on the calculator: mate in 1, 2 or 3, or find the one winning move. A rating and a streak track your progress.
+* **Two-player mode** with a chess clock. The board turns to face whoever is to move.
+* **Fast and small:** about 20 KB installed. The piece set takes 658 bytes, and there's no puzzle database.
+
+<table>
+ <tr>
+ <td align="center"><img src="docs/menu.png" width="390" alt="Main menu"><br><sub>Main menu</sub></td>
+ <td align="center"><img src="docs/italian.png" width="390" alt="A game in progress"><br><sub>A game against Nova</sub></td>
+ </tr>
+</table>
+
+## Play the bots
+
+Pick an opponent and a color (White, random or Black), then play. Each bot beats the one below it in bot-vs-bot matches. The Elo numbers are rough estimates.
+
+<p align="center">
+ <img src="docs/roster.png" width="640" alt="All 12 bots with their Elo ratings">
+</p>
+
+<table>
+ <tr>
+ <td align="center"><img src="docs/bots.gif" width="390" alt="Scrolling through the bots"><br><sub>Choose a bot and your color</sub></td>
+ <td align="center"><img src="docs/bots.png" width="390" alt="Atlas selected"><br><sub>Atlas, the strongest bot, thinks up to 2.5 s per move</sub></td>
+ </tr>
+ <tr>
+ <td align="center"><img src="docs/select.png" width="390" alt="Legal moves shown as dots and capture rings"><br><sub>Legal moves as dots, captures as rings</sub></td>
+ <td align="center"><img src="docs/check.png" width="390" alt="King in check glowing red"><br><sub>Check glow, last-move highlight, captured pieces with material count</sub></td>
+ </tr>
+ <tr>
+ <td align="center"><img src="docs/promotion.png" width="390" alt="Promotion picker"><br><sub>Promotion picker</sub></td>
+ <td align="center"><img src="docs/gameover.png" width="390" alt="Game over card"><br><sub>Result card with rematch</sub></td>
+ </tr>
+ <tr>
+ <td align="center"><img src="docs/pause.png" width="390" alt="Pause menu"><br><sub>Back opens the pause menu: undo, flip, resign</sub></td>
+ <td></td>
+ </tr>
+</table>
+
+## Puzzles
+
+Every puzzle is generated on the calculator. It plays a quick game between a careful side and a blunder-prone side, then stops at a position with a forced mate or a single winning move. Puzzles never run out, and the app stores none of them.
+
+<p align="center">
+ <img src="docs/puzzle.gif" width="640" alt="Solving a mate in 2 puzzle">
+</p>
+
+* **Modes:** Mix, Mate in 1, Mate in 2, Mate in 3 and Best move.
+* **Opening move:** each puzzle starts by playing the opponent's last move, which is the mistake you punish.
+* **Accepted solutions:** any move that still forces the mate counts. The opponent defends as stubbornly as possible.
+* **Rating:** it goes up or down after each puzzle, and Mix and Best move pick puzzles near it. A streak counts your solves in a row.
+* **Pause menu:** Hint highlights the piece to move, Solution plays the answer, and Next skips.
+* **Speed:** the next puzzle is prepared while you look at the solved one.
+
+<table>
+ <tr>
+ <td align="center"><img src="docs/puzzle-menu.png" width="390" alt="Puzzle modes"><br><sub>Puzzle modes</sub></td>
+ <td align="center"><img src="docs/puzzle-mate1.png" width="390" alt="Mate in 1"><br><sub>Mate in 1: the pill shows who is to move</sub></td>
+ </tr>
+ <tr>
+ <td align="center"><img src="docs/puzzle-mate3.png" width="390" alt="Mate in 3 as Black"><br><sub>Mate in 3 as Black: the board flips for you</sub></td>
+ <td align="center"><img src="docs/puzzle-best.png" width="390" alt="Best move puzzle"><br><sub>Best move: find the knight fork</sub></td>
+ </tr>
+ <tr>
+ <td align="center"><img src="docs/puzzle-hint.png" width="390" alt="Hint highlight"><br><sub>Hint</sub></td>
+ <td align="center"><img src="docs/puzzle-wrong.png" width="390" alt="Wrong move"><br><sub>Wrong move: it's taken back and your rating drops</sub></td>
+ </tr>
+ <tr>
+ <td align="center"><img src="docs/puzzle-solved.png" width="390" alt="Solved"><br><sub>Solved</sub></td>
+ <td align="center"><img src="docs/puzzle-pause.png" width="390" alt="Puzzle pause menu"><br><sub>Hint, solution, next</sub></td>
+ </tr>
+</table>
+
+## Two players
+
+Play over the board with a chess clock. After every move the board turns to face the next player. If you prefer a fixed board, use Flip in the pause menu.
+
+<p align="center">
+ <img src="docs/clock.gif" width="640" alt="Two players with a 3+2 clock">
+</p>
+
+<table>
+ <tr>
+ <td align="center"><img src="docs/time.png" width="260" alt="Time controls"><br><sub>1+0 to 30+0, or no clock</sub></td>
+ <td align="center"><img src="docs/clock.png" width="260" alt="Clocks"><br><sub>The active clock is lit</sub></td>
+ <td align="center"><img src="docs/clock-low.png" width="260" alt="Low time"><br><sub>Under 10 s it turns red and shows tenths</sub></td>
+ </tr>
+</table>
+
+All the rules are included: castling, en passant, underpromotion, and draws by stalemate, threefold repetition, the 50-move rule or insufficient material. You can also agree to a draw or resign.
+
+## Controls
+
+| Key | Action |
+|---|---|
+| Arrows | Move the cursor (it wraps around the edges) |
+| OK or EXE | Select a piece, then play a move |
+| Back | Deselect, open the pause menu, or go back a screen |
+| ⌫ | Undo |
+| Home | Quit |
+
+## Install
+
+1. Download **[chess.nwa](https://github.com/Mason363/NumChess/releases/latest/download/chess.nwa)** from the [latest release](https://github.com/Mason363/NumChess/releases/latest).
+2. Plug the calculator into your computer and open **[my.numworks.com/apps](https://my.numworks.com/apps)** in Chrome or Edge.
+3. Upload `chess.nwa`. **Chess** appears at the end of the calculator's home screen.
+
+If you're building from source, `make run` builds and installs in one step.
+
+## Small by design
+
+<p align="center">
+ <img src="docs/pieces.png" width="640" alt="The piece set, zoomed 4x">
+</p>
+
+| | |
+|---|---|
+| Installed size | about 20 KB (20,074 bytes of code and data) |
+| Piece set | 658 bytes: 3-bit anti-aliased sprites, and symmetric pieces store only half |
+| Puzzle data | none: every puzzle is generated live |
+| RAM | about 52 KB, all static, no heap |
+
+* **Engine** (`src/chess.c`):
+ * 0x88 board with incremental hashing and evaluation.
+ * PeSTO piece-square tables, mirrored and packed into 384 bytes.
+ * Alpha-beta search with PVS, a transposition table, null-move pruning, late-move reductions, killer moves and history heuristics.
+ * A mate solver.
+ * Bots get weaker through search depth, evaluation noise and occasional random moves.
+* **Graphics** (`src/main.c`):
+ * Each board square is drawn in one pass: highlights, check glow, move hints and the piece, all blended in RGB565.
+ * Rounded cards and circles are anti-aliased.
+ * Moves animate with an ease-out curve.
+ * Text uses the calculator's own fonts.
+* **Pieces** are drawn as signed-distance shapes by `tools/pieces.py` and rendered to sprites. `tools/icon.py` makes the app icon the same way.
+* **Build:** `-Os`, LTO, and small replacements for the libc routines.
+
+## Build
+
+Requirements: the ARM embedded toolchain (`arm-none-eabi-gcc`) and Node.js, which `make` uses to fetch NumWorks' `nwlink` SDK.
+
+```sh
+make # output/chess.nwa
+make check # link it the way the calculator does and print the installed size
+make test # engine tests on the host: perft on six positions, hashing, search benchmark
+make run # install on a connected calculator
+```
+
+Every push is built by GitHub Actions. Pushing a `v*` tag publishes a release with `chess.nwa` attached.
diff --git a/games/chess/docs/bots.gif b/games/chess/docs/bots.gif
new file mode 100644
index 00000000..d5bc49e1
Binary files /dev/null and b/games/chess/docs/bots.gif differ
diff --git a/games/chess/docs/bots.png b/games/chess/docs/bots.png
new file mode 100644
index 00000000..560115b7
Binary files /dev/null and b/games/chess/docs/bots.png differ
diff --git a/games/chess/docs/check.png b/games/chess/docs/check.png
new file mode 100644
index 00000000..ee732089
Binary files /dev/null and b/games/chess/docs/check.png differ
diff --git a/games/chess/docs/clock-low.png b/games/chess/docs/clock-low.png
new file mode 100644
index 00000000..987a5544
Binary files /dev/null and b/games/chess/docs/clock-low.png differ
diff --git a/games/chess/docs/clock.gif b/games/chess/docs/clock.gif
new file mode 100644
index 00000000..5a8610d2
Binary files /dev/null and b/games/chess/docs/clock.gif differ
diff --git a/games/chess/docs/clock.png b/games/chess/docs/clock.png
new file mode 100644
index 00000000..ca5cb6b9
Binary files /dev/null and b/games/chess/docs/clock.png differ
diff --git a/games/chess/docs/gameover.png b/games/chess/docs/gameover.png
new file mode 100644
index 00000000..3e1253fe
Binary files /dev/null and b/games/chess/docs/gameover.png differ
diff --git a/games/chess/docs/hero.gif b/games/chess/docs/hero.gif
new file mode 100644
index 00000000..bc0070c9
Binary files /dev/null and b/games/chess/docs/hero.gif differ
diff --git a/games/chess/docs/icon.png b/games/chess/docs/icon.png
new file mode 100644
index 00000000..c4de3844
Binary files /dev/null and b/games/chess/docs/icon.png differ
diff --git a/games/chess/docs/italian.png b/games/chess/docs/italian.png
new file mode 100644
index 00000000..f72c7a23
Binary files /dev/null and b/games/chess/docs/italian.png differ
diff --git a/games/chess/docs/menu.png b/games/chess/docs/menu.png
new file mode 100644
index 00000000..3c0b5b19
Binary files /dev/null and b/games/chess/docs/menu.png differ
diff --git a/games/chess/docs/pause.png b/games/chess/docs/pause.png
new file mode 100644
index 00000000..a5021e1a
Binary files /dev/null and b/games/chess/docs/pause.png differ
diff --git a/games/chess/docs/pieces.png b/games/chess/docs/pieces.png
new file mode 100644
index 00000000..c97d26dd
Binary files /dev/null and b/games/chess/docs/pieces.png differ
diff --git a/games/chess/docs/promotion.png b/games/chess/docs/promotion.png
new file mode 100644
index 00000000..0d92c459
Binary files /dev/null and b/games/chess/docs/promotion.png differ
diff --git a/games/chess/docs/puzzle-best.png b/games/chess/docs/puzzle-best.png
new file mode 100644
index 00000000..4bccdcf9
Binary files /dev/null and b/games/chess/docs/puzzle-best.png differ
diff --git a/games/chess/docs/puzzle-hint.png b/games/chess/docs/puzzle-hint.png
new file mode 100644
index 00000000..4499060f
Binary files /dev/null and b/games/chess/docs/puzzle-hint.png differ
diff --git a/games/chess/docs/puzzle-mate1.png b/games/chess/docs/puzzle-mate1.png
new file mode 100644
index 00000000..643135a2
Binary files /dev/null and b/games/chess/docs/puzzle-mate1.png differ
diff --git a/games/chess/docs/puzzle-mate3.png b/games/chess/docs/puzzle-mate3.png
new file mode 100644
index 00000000..be38ede6
Binary files /dev/null and b/games/chess/docs/puzzle-mate3.png differ
diff --git a/games/chess/docs/puzzle-menu.png b/games/chess/docs/puzzle-menu.png
new file mode 100644
index 00000000..e5592ac6
Binary files /dev/null and b/games/chess/docs/puzzle-menu.png differ
diff --git a/games/chess/docs/puzzle-pause.png b/games/chess/docs/puzzle-pause.png
new file mode 100644
index 00000000..00224c71
Binary files /dev/null and b/games/chess/docs/puzzle-pause.png differ
diff --git a/games/chess/docs/puzzle-solved.png b/games/chess/docs/puzzle-solved.png
new file mode 100644
index 00000000..1fef6957
Binary files /dev/null and b/games/chess/docs/puzzle-solved.png differ
diff --git a/games/chess/docs/puzzle-wrong.png b/games/chess/docs/puzzle-wrong.png
new file mode 100644
index 00000000..9c757479
Binary files /dev/null and b/games/chess/docs/puzzle-wrong.png differ
diff --git a/games/chess/docs/puzzle.gif b/games/chess/docs/puzzle.gif
new file mode 100644
index 00000000..f4796942
Binary files /dev/null and b/games/chess/docs/puzzle.gif differ
diff --git a/games/chess/docs/roster.png b/games/chess/docs/roster.png
new file mode 100644
index 00000000..806995a4
Binary files /dev/null and b/games/chess/docs/roster.png differ
diff --git a/games/chess/docs/select.png b/games/chess/docs/select.png
new file mode 100644
index 00000000..9ee09574
Binary files /dev/null and b/games/chess/docs/select.png differ
diff --git a/games/chess/docs/time.png b/games/chess/docs/time.png
new file mode 100644
index 00000000..a6449da2
Binary files /dev/null and b/games/chess/docs/time.png differ
diff --git a/games/chess/src/chess.c b/games/chess/src/chess.c
new file mode 100644
index 00000000..8c28bfc1
--- /dev/null
+++ b/games/chess/src/chess.c
@@ -0,0 +1,736 @@
+#include "chess.h"
+#include <eadk.h>
+#include <string.h>
+
+Pos P;
+Undo H[MAXGAME + MAXPLY];
+int hp;
+uint32_t nodes;
+
+static uint64_t Z[16 * 64 + 25];
+#define ZP(pc, s) Z[(pc) * 64 + (s)]
+#define Zc (Z + 1024)
+#define Zep (Z + 1040)
+#define Zside Z[1048]
+
+/* PeSTO piece-square tables (Ronald Friederich), mirrored across the
+ * d/e files and halved to fit in int8. Rows run rank 8 -> rank 1. */
+static const int8_t PST[12][32] = {
+ {0,0,0,0,22,42,47,41,-6,8,21,24,-9,8,5,11,-13,2,0,7,-9,7,0,-2,-14,9,1,-9,0,0,0,0},
+ {0,0,0,0,91,85,73,70,45,46,35,31,12,10,4,1,3,3,-3,-3,-1,2,-3,0,2,3,2,6,0,0,0,0},
+ {-68,-26,-33,3,-22,-8,34,15,-1,33,42,37,3,9,22,23,-5,6,9,10,-10,4,7,7,-12,-17,2,-1,-32,-10,-21,-12},
+ {-39,-25,-10,-15,-19,-8,-12,-3,-16,-10,0,2,-9,3,8,11,-9,0,8,10,-11,-6,-1,6,-21,-11,-7,-2,-23,-25,-10,-9},
+ {-9,3,-31,-15,-18,9,10,4,-4,19,23,19,-1,3,14,22,0,6,6,15,3,8,11,7,1,12,9,2,-13,-10,-6,-8},
+ {-9,-9,-5,-4,-5,-2,-1,-4,2,-2,2,-1,0,3,6,6,-4,0,6,7,-7,-2,3,6,-10,-8,-4,1,-10,-3,-10,-3},
+ {19,18,10,29,18,15,31,36,3,20,18,13,-11,-5,11,13,-15,-5,-5,2,-19,-7,-4,-3,-29,-5,-2,-2,-11,-12,2,8},
+ {5,5,8,7,4,5,4,2,1,1,1,2,2,1,4,1,-2,-1,1,0,-5,-2,-4,-2,-2,-4,-2,-2,-7,2,-2,-1},
+ {4,11,18,18,8,-3,13,-4,11,8,16,9,-6,-7,0,-4,-3,-6,-3,-3,-2,4,-2,-2,-8,-3,7,3,-13,-12,-8,-1},
+ {3,8,10,14,-4,13,14,25,-3,6,11,24,10,20,16,26,1,17,13,20,-3,-4,8,4,-13,-15,-13,-8,-18,-12,-13,-12},
+ {-13,6,-4,-18,0,-10,-6,-4,-8,12,2,-9,-13,-8,-9,-14,-25,-8,-18,-21,-10,-7,-13,-22,2,4,-6,-27,0,15,-4,-11},
+ {-23,-8,-1,-7,0,10,13,9,6,15,17,9,-1,12,14,13,-7,1,11,13,-7,1,7,11,-11,-4,2,7,-24,-14,-9,-10},
+};
+static const int16_t VMG[7] = {0, 82, 337, 365, 477, 1025, 0};
+static const int16_t VEG[7] = {0, 94, 281, 297, 512, 936, 0};
+static const uint8_t PHASE[7] = {0, 0, 1, 1, 2, 4, 0};
+
+static const int8_t KN[8] = {33, 31, 18, 14, -33, -31, -18, -14};
+static const int8_t KG[8] = {1, -1, 16, -16, 17, 15, -17, -15};
+
+#define SQ64(s) (((s) + ((s) & 7)) >> 1)
+#define OFF(s) ((s) & 0x88)
+#define LAST(s) ((unsigned)((s) - 16) >= 96)
+
+static void upd(int sq, int pc, int sign) {
+ int t = TYPE(pc), f = sq & 7, r = sq >> 4;
+ if (f > 3) f = 7 - f;
+ if (!COLOR(pc)) r = 7 - r;
+ int i = r * 4 + f;
+ int mg = VMG[t] + 2 * PST[t * 2 - 2][i], eg = VEG[t] + 2 * PST[t * 2 - 1][i];
+ if (COLOR(pc) ^ (sign < 0)) mg = -mg, eg = -eg;
+ P.mg += mg;
+ P.eg += eg;
+ P.phase += sign * PHASE[t];
+ P.cnt[pc] += sign;
+ P.hash ^= ZP(pc, SQ64(sq));
+}
+
+static void put(int sq, int pc) {
+ P.b[sq] = pc;
+ upd(sq, pc, 1);
+ if (TYPE(pc) == KING) P.king[COLOR(pc)] = sq;
+}
+
+static void del(int sq) {
+ upd(sq, P.b[sq], -1);
+ P.b[sq] = 0;
+}
+
+static uint64_t rng64(void) {
+ static uint64_t s = 0x9E3779B97F4A7C15ull;
+ s ^= s >> 12, s ^= s << 25, s ^= s >> 27;
+ return s * 0x2545F4914F6CDD1Dull;
+}
+
+void ch_init(void) {
+ for (int i = 0; i < 16 * 64 + 25; i++) Z[i] = rng64();
+}
+
+void ch_reset(void) {
+ static const uint8_t back[8] = {ROOK, KNIGHT, BISHOP, QUEEN, KING, BISHOP, KNIGHT, ROOK};
+ memset(&P, 0, sizeof P);
+ hp = 0;
+ for (int f = 0; f < 8; f++) {
+ put(f, back[f]);
+ put(16 + f, PAWN);
+ put(0x60 + f, BLACK | PAWN);
+ put(0x70 + f, BLACK | back[f]);
+ }
+ P.castle = 15;
+ P.ep = NOSQ;
+ P.hash ^= Zc[15];
+}
+
+static int attacked(int sq, int by) {
+ int c = by << 3;
+ for (int i = 15; i <= 17; i += 2) {
+ int s = by ? sq + i : sq - i;
+ if (!OFF(s) && P.b[s] == (c | PAWN)) return 1;
+ }
+ for (int i = 0; i < 8; i++) {
+ int s = sq + KN[i];
+ if (!OFF(s) && P.b[s] == (c | KNIGHT)) return 1;
+ s = sq + KG[i];
+ if (!OFF(s) && P.b[s] == (c | KING)) return 1;
+ for (; !OFF(s); s += KG[i]) {
+ int p = P.b[s];
+ if (p) {
+ if (COLOR(p) == by && (TYPE(p) == QUEEN || TYPE(p) == (i < 4 ? ROOK : BISHOP))) return 1;
+ break;
+ }
+ }
+ }
+ return 0;
+}
+
+int in_check(void) { return attacked(P.king[P.side], !P.side); }
+
+static int left_in_check(void) { return attacked(P.king[P.side ^ 1], P.side); }
+
+static Move *addp(Move *ml, int f, int t, int caps) {
+ if (!LAST(t)) *ml++ = MOVE(f, t, 0);
+ else for (int p = 3; p >= (caps ? 3 : 0); p--) *ml++ = MOVE(f, t, p);
+ return ml;
+}
+
+/* Pseudo-legal moves (castling is fully checked). caps: captures and queen promotions only. */
+static int gen(Move *ml0, int caps) {
+ Move *ml = ml0;
+ int us = P.side;
+ for (int sq = 0; sq < 120; sq++) {
+ int p = P.b[sq];
+ if (OFF(sq) || !p || COLOR(p) != us) continue;
+ int t = TYPE(p);
+ if (t == PAWN) {
+ int fwd = us ? -16 : 16, s = sq + fwd;
+ if (!P.b[s]) {
+ if (LAST(s) || !caps) ml = addp(ml, sq, s, caps);
+ if (!caps && ((sq >> 4) == (us ? 6 : 1)) && !P.b[s + fwd]) *ml++ = MOVE(sq, s + fwd, 0);
+ }
+ for (int d = -1; d <= 1; d += 2) {
+ int c = s + d;
+ if (!OFF(c) && ((P.b[c] && COLOR(P.b[c]) != us) || c == P.ep)) ml = addp(ml, sq, c, caps);
+ }
+ continue;
+ }
+ const int8_t *dir = t == KNIGHT ? KN : KG + (t == BISHOP) * 4;
+ int nd = (t == BISHOP || t == ROOK) ? 4 : 8, slide = t != KNIGHT && t != KING;
+ for (int i = 0; i < nd; i++) {
+ for (int s = sq + dir[i]; !OFF(s); s += dir[i]) {
+ int q = P.b[s];
+ if (q) {
+ if (COLOR(q) != us) *ml++ = MOVE(sq, s, 0);
+ break;
+ }
+ if (!caps) *ml++ = MOVE(sq, s, 0);
+ if (!slide) break;
+ }
+ }
+ }
+ if (!caps) {
+ int k = us ? 0x74 : 0x04;
+ if (P.king[us] == k && (P.castle & (us ? 12 : 3)) && !attacked(k, !us)) {
+ if ((P.castle & (us ? 4 : 1)) && !P.b[k + 1] && !P.b[k + 2] && !attacked(k + 1, !us))
+ *ml++ = MOVE(k, k + 2, 0);
+ if ((P.castle & (us ? 8 : 2)) && !P.b[k - 1] && !P.b[k - 2] && !P.b[k - 3] && !attacked(k - 1, !us))
+ *ml++ = MOVE(k, k - 2, 0);
+ }
+ }
+ return ml - ml0;
+}
+
+static int crmask(int s) {
+ static const uint8_t sq[6] = {0x00, 0x04, 0x07, 0x70, 0x74, 0x77}, mk[6] = {2, 3, 1, 8, 12, 4};
+ for (int i = 0; i < 6; i++)
+ if (s == sq[i]) return mk[i];
+ return 0;
+}
+
+void make(Move m) {
+ int f = MFROM(m), t = MTO(m), p = P.b[f], us = P.side;
+ Undo *u = &H[hp++];
+ u->hash = P.hash, u->m = m, u->pc = p, u->castle = P.castle, u->ep = P.ep, u->fifty = P.fifty;
+ u->cap = P.b[t];
+ P.fifty++;
+ if (TYPE(p) == PAWN) {
+ P.fifty = 0;
+ if (t == P.ep) {
+ int cs = t + (us ? 16 : -16);
+ u->cap = P.b[cs];
+ del(cs);
+ }
+ }
+ if (P.b[t]) del(t), P.fifty = 0;
+ del(f);
+ if (TYPE(p) == PAWN && LAST(t)) p = (us << 3) | (MPROMO(m) + KNIGHT);
+ put(t, p);
+ if (TYPE(p) == KING && (t - f == 2 || f - t == 2)) {
+ int rf = t > f ? f + 3 : f - 4;
+ del(rf);
+ put((f + t) >> 1, (us << 3) | ROOK);
+ }
+ P.hash ^= Zc[P.castle];
+ P.castle &= ~(crmask(f) | crmask(t));
+ P.hash ^= Zc[P.castle];
+ if (P.ep != NOSQ) P.hash ^= Zep[P.ep & 7];
+ P.ep = NOSQ;
+ if (TYPE(p) == PAWN && (t - f == 32 || f - t == 32)) P.ep = (f + t) >> 1, P.hash ^= Zep[P.ep & 7];
+ P.side ^= 1;
+ P.hash ^= Zside;
+}
+
+void unmake(void) {
+ Undo *u = &H[--hp];
+ int m = u->m, f = MFROM(m), t = MTO(m), us = P.side ^= 1;
+ if (m) {
+ del(t);
+ put(f, u->pc);
+ if (u->cap) put(TYPE(u->pc) == PAWN && t == u->ep ? t + (us ? 16 : -16) : t, u->cap);
+ if (TYPE(u->pc) == KING && (t - f == 2 || f - t == 2)) {
+ del((f + t) >> 1);
+ put(t > f ? f + 3 : f - 4, (us << 3) | ROOK);
+ }
+ }
+ P.castle = u->castle, P.ep = u->ep, P.fifty = u->fifty, P.hash = u->hash;
+}
+
+static void make_null(void) {
+ Undo *u = &H[hp++];
+ u->hash = P.hash, u->m = 0, u->castle = P.castle, u->ep = P.ep, u->fifty = P.fifty;
+ if (P.ep != NOSQ) P.hash ^= Zep[P.ep & 7];
+ P.ep = NOSQ;
+ P.side ^= 1;
+ P.hash ^= Zside;
+}
+
+int legal(Move *out) {
+ int n = gen(out, 0), k = 0;
+ for (int i = 0; i < n; i++) {
+ make(out[i]);
+ if (!left_in_check()) out[k++] = out[i];
+ unmake();
+ }
+ return k;
+}
+
+int is_legal(Move m) {
+ Move ml[256];
+ int n = legal(ml);
+ while (n--)
+ if (ml[n] == m) return 1;
+ return 0;
+}
+
+int gives_check(Move m) {
+ make(m);
+ int c = in_check();
+ unmake();
+ return c;
+}
+
+static int reps(void) {
+ int r = 0;
+ for (int i = hp - 2; i >= 0 && i >= hp - P.fifty; i -= 2) r += H[i].hash == P.hash;
+ return r;
+}
+
+static int insufficient(void) {
+ uint8_t *c = P.cnt;
+ if (c[PAWN] | c[ROOK] | c[QUEEN] | c[8 | PAWN] | c[8 | ROOK] | c[8 | QUEEN]) return 0;
+ return c[KNIGHT] + c[BISHOP] + c[8 | KNIGHT] + c[8 | BISHOP] <= 1;
+}
+
+int status(void) {
+ Move ml[256];
+ if (!legal(ml)) return in_check() ? CHECKMATE : STALEMATE;
+ if (P.fifty >= 100 || hp >= MAXGAME) return FIFTY;
+ if (reps() >= 2) return REPETITION;
+ if (insufficient()) return MATERIAL;
+ return ONGOING;
+}
+
+void san(Move m, char *o) {
+ int f = MFROM(m), t = MTO(m), p = P.b[f], ty = TYPE(p);
+ Move ml[256];
+ if (ty == KING && (t - f == 2 || f - t == 2)) {
+ const char *c = t > f ? "O-O" : "O-O-O";
+ while (*c) *o++ = *c++;
+ } else {
+ int cap = P.b[t] || (ty == PAWN && t == P.ep);
+ if (ty != PAWN) {
+ *o++ = " PNBRQK"[ty];
+ int n = legal(ml), amb = 0, sf = 0, sr = 0;
+ while (n--) {
+ int mf = MFROM(ml[n]);
+ if (MTO(ml[n]) == t && mf != f && P.b[mf] == p) {
+ amb = 1;
+ sf |= (mf & 7) == (f & 7);
+ sr |= (mf >> 4) == (f >> 4);
+ }
+ }
+ if (amb && (!sf || sr)) *o++ = 'a' + (f & 7);
+ if (amb && sf) *o++ = '1' + (f >> 4);
+ } else if (cap) {
+ *o++ = 'a' + (f & 7);
+ }
+ if (cap) *o++ = 'x';
+ *o++ = 'a' + (t & 7);
+ *o++ = '1' + (t >> 4);
+ if (ty == PAWN && LAST(t)) *o++ = '=', *o++ = "NBRQ"[MPROMO(m)];
+ }
+ make(m);
+ if (in_check()) *o++ = legal(ml) ? '+' : '#';
+ unmake();
+ *o = 0;
+}
+
+/* ---------------------------------------------------------------- Eval */
+
+int eval(void) {
+ int ph = P.phase > 24 ? 24 : P.phase;
+ int s = (P.mg * ph + P.eg * (24 - ph)) / 24;
+ uint8_t *c = P.cnt;
+ s += 30 * ((c[BISHOP] >= 2) - (c[8 | BISHOP] >= 2));
+ for (int w = 0; w < 2; w++) {
+ int sg = w ? -1 : 1, o = w << 3, x = 8 - o;
+ if (s * sg <= 0) continue;
+ if (!c[o | PAWN] && !c[o | ROOK] && !c[o | QUEEN] && c[o | KNIGHT] + c[o | BISHOP] <= 1) {
+ s /= 8;
+ } else if (!(c[x | PAWN] | c[x | KNIGHT] | c[x | BISHOP] | c[x | ROOK] | c[x | QUEEN])) {
+ /* Mop-up: drive the lone king to the edge and bring ours closer. */
+ int k = P.king[!w], K = P.king[w], kf = k & 7, kr = k >> 4;
+ int cd = (kf < 4 ? 3 - kf : kf - 4) + (kr < 4 ? 3 - kr : kr - 4);
+ int df = kf - (K & 7), dr = kr - (K >> 4);
+ s += sg * (300 + cd * 20 + (14 - (df < 0 ? -df : df) - (dr < 0 ? -dr : dr)) * 8);
+ }
+ }
+ return (P.side ? -s : s) + 8;
+}
+
+/* -------------------------------------------------------------- Search */
+
+#define TTN 2048
+typedef struct {
+ uint16_t key;
+ Move m;
+ int16_t s;
+ uint8_t d, f;
+} TTE;
+enum { T_EXACT = 1, T_LOWER, T_UPPER };
+static TTE tt[TTN];
+static Move killers[MAXPLY][2];
+static int16_t hist[16 * 64];
+#define MSN 3000
+static Move mstack[MSN];
+static int16_t mscore[MSN];
+static int msp;
+static uint64_t deadline;
+static int stopped;
+int think_depth, think_score;
+
+void ui_tick(void);
+
+static int tick(void) {
+ if ((++nodes & 1023) == 0) {
+ ui_tick();
+ if (eadk_timing_millis() > deadline) stopped = 1;
+ }
+ return stopped;
+}
+
+static void score_moves(Move *ml, int16_t *sc, int n, Move ttm, int ply) {
+ for (int i = 0; i < n; i++) {
+ Move m = ml[i];
+ int f = MFROM(m), t = MTO(m), p = P.b[f], v = P.b[t], s;
+ if (m == ttm) s = 30000;
+ else if (v || (TYPE(p) == PAWN && t == P.ep)) s = 20000 + TYPE(v ? v : PAWN) * 16 - TYPE(p);
+ else if (TYPE(p) == PAWN && LAST(t)) s = MPROMO(m) == 3 ? 19000 : -1000;
+ else if (m == killers[ply][0]) s = 18000;
+ else if (m == killers[ply][1]) s = 17990;
+ else s = hist[p * 64 + SQ64(t)];
+ sc[i] = s;
+ }
+}
+
+static Move pick(Move *ml, int16_t *sc, int n, int i) {
+ int b = i;
+ for (int j = i + 1; j < n; j++)
+ if (sc[j] > sc[b]) b = j;
+ Move m = ml[b];
+ int16_t s = sc[b];
+ ml[b] = ml[i], sc[b] = sc[i], ml[i] = m, sc[i] = s;
+ return m;
+}
+
+static int qs(int alpha, int beta, int ply) {
+ if (tick()) return 0;
+ int best = eval();
+ if (best >= beta || ply >= MAXPLY - 1 || msp > MSN - 256) return best;
+ if (best > alpha) alpha = best;
+ Move *ml = mstack + msp;
+ int16_t *sc = mscore + msp;
+ int n = gen(ml, 1);
+ msp += n;
+ score_moves(ml, sc, n, 0, ply);
+ for (int i = 0; i < n; i++) {
+ Move m = pick(ml, sc, n, i);
+ make(m);
+ if (left_in_check()) {
+ unmake();
+ continue;
+ }
+ int s = -qs(-beta, -alpha, ply + 1);
+ unmake();
+ if (s > best) {
+ best = s;
+ if (s > alpha) {
+ alpha = s;
+ if (s >= beta) break;
+ }
+ }
+ }
+ msp -= n;
+ return best;
+}
+
+int search(int depth, int alpha, int beta, int ply) {
+ if (ply && (P.fifty >= 100 || reps())) return 0;
+ int check = in_check();
+ if (check) depth++;
+ if (depth <= 0) return qs(alpha, beta, ply);
+ if (tick()) return 0;
+ if (ply >= MAXPLY - 1 || msp > MSN - 256) return eval();
+ if (alpha < -MATE + ply) alpha = -MATE + ply;
+ if (beta > MATE - ply - 1) beta = MATE - ply - 1;
+ if (alpha >= beta) return alpha;
+
+ TTE *e = &tt[P.hash & (TTN - 1)];
+ uint16_t key = P.hash >> 48;
+ Move ttm = 0;
+ if (e->key == key) {
+ ttm = e->m;
+ if (ply && e->d >= depth) {
+ int s = e->s;
+ if (s > MATE - 200) s -= ply;
+ else if (s < -MATE + 200) s += ply;
+ if (e->f == T_EXACT || (e->f == T_LOWER && s >= beta) || (e->f == T_UPPER && s <= alpha)) return s;
+ }
+ }
+ int pv = beta - alpha > 1, us = P.side << 3;
+ if (!pv && !check && depth >= 3 && ply &&
+ (P.cnt[us | KNIGHT] | P.cnt[us | BISHOP] | P.cnt[us | ROOK] | P.cnt[us | QUEEN]) && eval() >= beta) {
+ make_null();
+ int s = -search(depth - 3, -beta, -beta + 1, ply + 1);
+ unmake();
+ if (stopped) return 0;
+ if (s >= beta) return s > MATE - 200 ? beta : s;
+ }
+
+ Move *ml = mstack + msp;
+ int16_t *sc = mscore + msp;
+ int n = gen(ml, 0);
+ msp += n;
+ score_moves(ml, sc, n, ttm, ply);
+ int best = -INF, legalc = 0, a0 = alpha;
+ Move bm = 0;
+ for (int i = 0; i < n; i++) {
+ Move m = pick(ml, sc, n, i);
+ int p = P.b[MFROM(m)], t = MTO(m);
+ int quiet = !P.b[t] && !(TYPE(p) == PAWN && (t == P.ep || LAST(t)));
+ make(m);
+ if (left_in_check()) {
+ unmake();
+ continue;
+ }
+ legalc++;
+ int s, nd = depth - 1;
+ if (legalc == 1) {
+ s = -search(nd, -beta, -alpha, ply + 1);
+ } else {
+ int r = depth >= 3 && legalc > 3 && quiet && sc[i] < 17000 && !check && !in_check() ? 1 + (legalc > 8) : 0;
+ s = -search(nd - r, -alpha - 1, -alpha, ply + 1);
+ if (r && s > alpha) s = -search(nd, -alpha - 1, -alpha, ply + 1);
+ if (s > alpha && s < beta) s = -search(nd, -beta, -alpha, ply + 1);
+ }
+ unmake();
+ if (stopped) break;
+ if (s > best) {
+ best = s, bm = m;
+ if (s > alpha) {
+ alpha = s;
+ if (s >= beta) {
+ if (quiet) {
+ if (killers[ply][0] != m) killers[ply][1] = killers[ply][0], killers[ply][0] = m;
+ int16_t *h = &hist[p * 64 + SQ64(t)];
+ *h = *h + depth * depth > 16000 ? 16000 : *h + depth * depth;
+ }
+ break;
+ }
+ }
+ }
+ }
+ msp -= n;
+ if (stopped) return 0;
+ if (!legalc) return check ? -MATE + ply : 0;
+ int s = best;
+ if (s > MATE - 200) s += ply;
+ else if (s < -MATE + 200) s -= ply;
+ e->key = key, e->m = bm, e->s = s, e->d = depth;
+ e->f = best >= beta ? T_LOWER : best > a0 ? T_EXACT : T_UPPER;
+ return best;
+}
+
+static void limit(int ms) {
+ deadline = eadk_timing_millis() + ms;
+ stopped = 0;
+ msp = 0;
+}
+
+Move think(int maxd, int ms, int *score) {
+ Move root[256];
+ int n = legal(root), bs = 0;
+ if (!n) return 0;
+ limit(ms);
+ nodes = 0;
+ uint64_t t0 = eadk_timing_millis();
+ memset(killers, 0, sizeof killers);
+ for (int i = 0; i < 16 * 64; i++) hist[i] >>= 2;
+ think_depth = 0;
+ for (int d = 1; d <= maxd; d++) {
+ int alpha = -INF, cur = -INF;
+ for (int i = 0; i < n; i++) {
+ make(root[i]);
+ int s;
+ if (!i) {
+ s = -search(d - 1, -INF, INF, 1);
+ } else {
+ s = -search(d - 1, -alpha - 1, -alpha, 1);
+ if (s > alpha && !stopped) s = -search(d - 1, -INF, -alpha, 1);
+ }
+ unmake();
+ if (stopped) break;
+ if (s > alpha) {
+ Move m = root[i];
+ memmove(root + 1, root, i * sizeof(Move));
+ root[0] = m;
+ alpha = cur = s;
+ }
+ }
+ if (cur > -INF) bs = cur;
+ if (stopped) break;
+ think_depth = d;
+ if (MATE - (bs < 0 ? -bs : bs) <= d) break;
+ if ((eadk_timing_millis() - t0) * 2 > (uint64_t)ms) break;
+ }
+ if (score) *score = bs;
+ think_score = bs;
+ return root[0];
+}
+
+/* Score of one root move at a given depth, using a (alpha, beta) window. */
+int score_move(Move m, int depth, int alpha, int beta) {
+ make(m);
+ int s = -search(depth - 1, -beta, -alpha, 1);
+ unmake();
+ return s;
+}
+
+static int noise(int n) { return n ? (int)(eadk_random() % (n + 1) + eadk_random() % (n + 1)) - n : 0; }
+
+Move bot_move(int depth, int nz, int blunder, int ms) {
+ Move ml[256];
+ int n = legal(ml), bs;
+ if (n <= 1) return n ? ml[0] : 0;
+ if ((int)(eadk_random() % 100) < blunder) return ml[eadk_random() % n];
+ if (!nz && hp < 8) nz = 12, depth = depth < 4 ? depth : 4; /* opening variety */
+ Move best = think(depth, nz ? 60000 : ms, &bs);
+ if (!nz) return best;
+ int d = think_depth ? think_depth : 1, bv = -INF;
+ limit(60000);
+ for (int i = 0; i < n; i++) {
+ int s = ml[i] == best ? bs : score_move(ml[i], d, bs - 2 * nz, INF);
+ s += noise(nz);
+ if (s > bv) bv = s, best = ml[i];
+ }
+ return best;
+}
+
+/* ---------------------------------------------------------- Mate search */
+
+static int all_mated(int n, int co);
+static Move mate_first;
+
+/* Can the side to move force mate in at most n moves? co: attacker only checks. */
+int mate_in(int n, int co) {
+ Move *ml = mstack + msp;
+ int k = gen(ml, 0), found = 0;
+ msp += k;
+ for (int pass = 0; pass < 2 && !found; pass++) {
+ if (pass && (co || n == 1)) break;
+ for (int i = 0; i < k && !found; i++) {
+ make(ml[i]);
+ if (!left_in_check() && in_check() == !pass) found = all_mated(n - 1, co);
+ unmake();
+ if (found) mate_first = ml[i];
+ }
+ }
+ msp -= k;
+ return found;
+}
+
+/* Defender to move: does every reply lose to mate within n moves? */
+static int all_mated(int n, int co) {
+ Move *ml = mstack + msp;
+ int k = gen(ml, 0), any = 0, ok = 1;
+ msp += k;
+ for (int i = 0; i < k && ok; i++) {
+ make(ml[i]);
+ if (!left_in_check()) {
+ any = 1;
+ if (!n || !mate_in(n, co)) ok = 0;
+ }
+ unmake();
+ }
+ msp -= k;
+ return any ? ok : in_check();
+}
+
+int mated_within(int n) {
+ msp = 0;
+ return all_mated(n, 0);
+}
+
+int mate_len(int max, int co) {
+ msp = 0;
+ for (int n = 1; n <= max; n++)
+ if (mate_in(n, co)) return n;
+ return 0;
+}
+
+/* First move of a mate in at most n, or 0. */
+Move mate_move(int n) {
+ return mate_len(n, 1) || mate_len(n, 0) ? mate_first : 0;
+}
+
+/* Defender to move: the reply that postpones mate the longest. */
+Move defend(int n) {
+ Move ml[256];
+ int k = legal(ml), best = -1;
+ Move bm = ml[0];
+ for (int i = 0; i < k; i++) {
+ make(ml[i]);
+ int l = mate_len(n, 0);
+ unmake();
+ if (!l) l = 99;
+ if (l > best || (l == best && eadk_random() % 3 == 0)) best = l, bm = ml[i];
+ }
+ return bm;
+}
+
+/* ------------------------------------------------------------- Puzzles */
+
+Puzzle PZ;
+#define PMARGIN 180
+
+static int is_quiet(Move m) { return !P.b[MTO(m)] && !gives_check(m); }
+
+/* Is m the only good move here (every other move scores at least PMARGIN less)? */
+static int unique(Move b, int s) {
+ Move ml[256];
+ int n = legal(ml), d = think_depth;
+ for (int i = 0; i < n; i++)
+ if (ml[i] != b && score_move(ml[i], d, s - PMARGIN - 1, s - PMARGIN) > s - PMARGIN) return 0;
+ return 1;
+}
+
+static int tactic(void) {
+ int s, r, k = 0, made = 0;
+ Move ml[256], b = think(5, 60000, &s);
+ if (s < 200 || s > MATE - 200 || !unique(b, s)) return 0;
+ int df = 1;
+ while (df < 5 && think(df, 60000, &r) != b) df++;
+ PZ.sol[k++] = b;
+ make(b), made++;
+ while (k < 5 && legal(ml)) {
+ Move rep = think(4, 60000, &r);
+ make(rep), made++;
+ Move b2 = think(5, 60000, &r);
+ if (r < 200 || r > MATE - 200 || !unique(b2, r)) break;
+ PZ.sol[k++] = rep, PZ.sol[k++] = b2;
+ make(b2), made++;
+ }
+ while (made--) unmake();
+ PZ.nsol = k;
+ PZ.mate = 0;
+ PZ.rating = 450 + 150 * df + 120 * (k >> 1) + 150 * is_quiet(b) - 200 * (MTO(b) == MTO(H[hp - 1].m)) +
+ eadk_random() % 80;
+ return 1;
+}
+
+void puzzle_gen(int kind, int target) {
+ for (int tries = 0;;) {
+ ch_reset();
+ int solver = eadk_random() & 1, prev = 0, s;
+ for (int ply = 0; ply < 100; ply++) {
+ Move ml[256];
+ if (!legal(ml) || P.fifty > 30) break;
+ if (P.side == solver) {
+ if (ply >= 8) {
+ int n = mate_len(3, 1), ok = 0;
+ if (n && (kind == 0 || kind == n) && !(n == 3 && mate_len(2, 0))) {
+ PZ.sol[0] = mate_move(n);
+ PZ.nsol = 1, PZ.mate = n;
+ PZ.rating = 250 + n * 400 + 150 * is_quiet(PZ.sol[0]) + eadk_random() % 100;
+ ok = 1;
+ } else if (!n && (kind == 0 || kind == 4)) {
+ think(2, 60000, &s);
+ if (s >= 250 && s < MATE - 200 && s - prev >= 250) ok = tactic();
+ }
+ int dr = PZ.rating - target;
+ if (ok && !(kind & 3) && (dr < 0 ? -dr : dr) > 200 + 60 * tries++) ok = 0;
+ if (ok) {
+ PZ.pre = H[hp - 1].m;
+ unmake();
+ PZ.start = P;
+ return;
+ }
+ }
+ ui_tick();
+ make(bot_move(1, 40, 0, 60000));
+ } else {
+ Move m = eadk_random() % 8 ? bot_move(1, 110, 0, 60000) : (think(1, 60000, 0), ml[eadk_random() % legal(ml)]);
+ prev = -think_score;
+ make(m);
+ }
+ }
+ }
+}
diff --git a/games/chess/src/chess.h b/games/chess/src/chess.h
new file mode 100644
index 00000000..236e0758
--- /dev/null
+++ b/games/chess/src/chess.h
@@ -0,0 +1,80 @@
+#ifndef CHESS_H
+#define CHESS_H
+
+#include <stdint.h>
+
+enum { EMPTY, PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING };
+#define BLACK 8
+#define COLOR(p) ((p) >> 3)
+#define TYPE(p) ((p) & 7)
+#define NOSQ 0x80
+
+/* 0x88 squares: sq = rank * 16 + file */
+typedef uint16_t Move; /* from | to << 7 | promo << 14 (promo: 0 N, 1 B, 2 R, 3 Q) */
+#define MFROM(m) ((m) & 127)
+#define MTO(m) (((m) >> 7) & 127)
+#define MPROMO(m) ((m) >> 14)
+#define MOVE(f, t, p) ((Move)((f) | (t) << 7 | (p) << 14))
+
+#define MATE 30000
+#define INF 32000
+#define MAXPLY 64
+#define MAXGAME 600
+
+typedef struct {
+ uint8_t b[128];
+ uint8_t side, castle, ep, fifty;
+ uint8_t king[2];
+ uint8_t cnt[16];
+ int16_t mg, eg, phase;
+ uint64_t hash;
+} Pos;
+
+typedef struct {
+ uint64_t hash;
+ Move m;
+ uint8_t pc, cap, castle, ep, fifty;
+} Undo;
+
+extern Pos P;
+extern Undo H[];
+extern int hp;
+
+enum { ONGOING, CHECKMATE, STALEMATE, FIFTY, REPETITION, MATERIAL };
+
+void ch_init(void);
+void ch_reset(void);
+void make(Move m);
+void unmake(void);
+int in_check(void);
+int legal(Move *out);
+int is_legal(Move m);
+int gives_check(Move m);
+int status(void);
+void san(Move m, char *out);
+
+int eval(void);
+int search(int depth, int alpha, int beta, int ply);
+Move think(int depth, int ms, int *score);
+int score_move(Move m, int depth, int alpha, int beta);
+Move bot_move(int depth, int noise, int blunder, int ms);
+int mate_in(int n, int checks_only);
+int mate_len(int max, int checks_only);
+int mated_within(int n);
+Move mate_move(int n);
+Move defend(int n);
+
+typedef struct {
+ Pos start; /* position before the opponent's last move */
+ Move pre; /* that move, played when the puzzle starts */
+ Move sol[5]; /* solver moves and replies */
+ uint8_t nsol, mate;
+ int16_t rating;
+} Puzzle;
+extern Puzzle PZ;
+void puzzle_gen(int kind, int target);
+extern int think_depth;
+
+extern uint32_t nodes;
+
+#endif
diff --git a/games/chess/src/icon.png b/games/chess/src/icon.png
new file mode 100644
index 00000000..3c80b1a7
Binary files /dev/null and b/games/chess/src/icon.png differ
diff --git a/games/chess/src/libc.c b/games/chess/src/libc.c
new file mode 100644
index 00000000..e9ee8a9d
--- /dev/null
+++ b/games/chess/src/libc.c
@@ -0,0 +1,38 @@
+/* Minimal replacements for the few libc routines the app needs: much
+ * smaller than newlib's speed-optimized versions. */
+#include <stddef.h>
+
+#define EXPORT __attribute__((used, externally_visible))
+
+EXPORT void *memcpy(void *d, const void *s, size_t n) {
+ char *o = d;
+ const char *i = s;
+ while (n--) *o++ = *i++;
+ return d;
+}
+
+EXPORT void *memmove(void *d, const void *s, size_t n) {
+ char *o = d;
+ const char *i = s;
+ if (o < i) return memcpy(d, s, n);
+ while (n--) o[n] = i[n];
+ return d;
+}
+
+EXPORT void *memset(void *d, int c, size_t n) {
+ char *o = d;
+ while (n--) *o++ = c;
+ return d;
+}
+
+EXPORT size_t strlen(const char *s) {
+ const char *e = s;
+ while (*e) e++;
+ return e - s;
+}
+
+EXPORT char *strcpy(char *d, const char *s) {
+ char *o = d;
+ while ((*o++ = *s++)) {}
+ return d;
+}
diff --git a/games/chess/src/main.c b/games/chess/src/main.c
new file mode 100644
index 00000000..36940a88
--- /dev/null
+++ b/games/chess/src/main.c
@@ -0,0 +1,893 @@
+#include <eadk.h>
+#include <string.h>
+#include "chess.h"
+#include "sprites.h"
+
+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;
+
+typedef uint16_t C;
+#define RGB(r, g, b) ((C)((((r) & 0xF8) << 8) | (((g) & 0xFC) << 3) | ((b) >> 3)))
+
+#define BG RGB(0x26, 0x25, 0x22)
+#define CARD RGB(0x3A, 0x38, 0x35)
+#define GREEN RGB(0x81, 0xB6, 0x4C)
+#define RED RGB(0xE0, 0x43, 0x3B)
+#define WHITE 0xFFFF
+#define DIM RGB(0x98, 0x97, 0x95)
+#define INK RGB(0x26, 0x25, 0x22)
+#define SQ_L RGB(0xEB, 0xEC, 0xD0)
+#define SQ_D RGB(0x77, 0x95, 0x56)
+#define HL_L RGB(0xF5, 0xF6, 0x82)
+#define HL_D RGB(0xB9, 0xCA, 0x43)
+#define HINT RGB(0x5B, 0x9B, 0xE6)
+
+enum { K_LEFT, K_UP, K_DOWN, K_RIGHT, K_OK, K_BACK, K_UNDO = 17, K_EXE = 52 };
+enum { M_BOT, M_2P, M_PUZ };
+
+static C buf[900];
+
+/* ------------------------------------------------------------ Drawing */
+
+static C mix(C a, C b, int t) {
+ uint32_t A = (a | a << 16) & 0x07E0F81F, B = (b | b << 16) & 0x07E0F81F;
+ uint32_t M = ((A * (32 - t) + B * t) >> 5) & 0x07E0F81F;
+ return M | M >> 16;
+}
+
+static void fill(int x, int y, int w, int h, C c) {
+ eadk_display_push_rect_uniform((eadk_rect_t){x, y, w, h}, c);
+}
+
+static void text(const char *s, int x, int y, int big, C fg, C bg) {
+ eadk_display_draw_string(s, (eadk_point_t){x, y}, big, fg, bg);
+}
+
+static void ctext(const char *s, int cx, int y, int big, C fg, C bg) {
+ int n = 0;
+ for (const char *c = s; *c; c++) n += (*c & 0xC0) != 0x80;
+ text(s, cx - n * (big ? 10 : 7) / 2, y, big, fg, bg);
+}
+
+static char *itoa(int v, char *o) {
+ char t[8];
+ int n = 0;
+ if (v < 0) *o++ = '-', v = -v;
+ do t[n++] = '0' + v % 10; while (v /= 10);
+ while (n) *o++ = t[--n];
+ *o = 0;
+ return o;
+}
+
+static float clampf(float v) { return v < 0 ? 0 : v > 1 ? 1 : v; }
+
+/* Anti-aliased rounded rectangle blended over what is on screen. */
+static void rrect(int x, int y, int w, int h, int r, C c) {
+ for (int j = 0; j < h; j++) {
+ int e = j < r || j >= h - r;
+ if (!e) {
+ fill(x, y + j, w, h - 2 * r, c);
+ j = h - r - 1;
+ continue;
+ }
+ eadk_rect_t R = {x, y + j, w, 1};
+ eadk_display_pull_rect(R, buf);
+ for (int i = 0; i < w; i++) {
+ float dx = i < r ? r - i - 0.5f : i >= w - r ? i + 0.5f - (w - r) : 0;
+ float dy = j < r ? r - j - 0.5f : j + 0.5f - (h - r);
+ float d = __builtin_sqrtf(dx * dx + dy * dy) - r;
+ buf[i] = mix(buf[i], c, (int)(32 * clampf(0.5f - d)));
+ }
+ eadk_display_push_rect(R, buf);
+ }
+}
+
+static void disc(int cx, int cy, int r, C c) { rrect(cx - r, cy - r, 2 * r, 2 * r, r, c); }
+
+/* Thick anti-aliased line blended over the screen. */
+static void stroke(float x0, float y0, float x1, float y1, float w, C c) {
+ int bx = (x0 < x1 ? x0 : x1) - w - 1, by = (y0 < y1 ? y0 : y1) - w - 1;
+ int bw = (x0 < x1 ? x1 - x0 : x0 - x1) + 2 * w + 3, bh = (y0 < y1 ? y1 - y0 : y0 - y1) + 2 * w + 3;
+ float ex = x1 - x0, ey = y1 - y0, l2 = ex * ex + ey * ey;
+ for (int j = 0; j < bh; j++) {
+ eadk_rect_t R = {bx, by + j, bw, 1};
+ eadk_display_pull_rect(R, buf);
+ for (int i = 0; i < bw; i++) {
+ float px = bx + i + 0.5f - x0, py = by + j + 0.5f - y0, t = clampf((px * ex + py * ey) / l2);
+ px -= ex * t, py -= ey * t;
+ buf[i] = mix(buf[i], c, (int)(32 * clampf(w / 2 + 0.5f - __builtin_sqrtf(px * px + py * py))));
+ }
+ eadk_display_push_rect(R, buf);
+ }
+}
+
+static void dim(int x, int y, int w, int h) {
+ for (int j = 0; j < h; j++) {
+ eadk_rect_t R = {x, y + j, w, 1};
+ eadk_display_pull_rect(R, buf);
+ for (int i = 0; i < w; i++) buf[i] = mix(buf[i], 0, 15);
+ eadk_display_push_rect(R, buf);
+ }
+}
+
+/* ------------------------------------------------------------ Sprites */
+
+static const C PCOL[2][3] = {
+ {RGB(0xF9, 0xF9, 0xF7), RGB(0x3A, 0x3A, 0x3A), RGB(0x3A, 0x3A, 0x3A)},
+ {RGB(0x52, 0x4F, 0x4D), RGB(0x16, 0x15, 0x14), RGB(0xA8, 0xA5, 0xA2)},
+};
+/* class -> (color a, color b, weight of b) with colors: 0 bg, 1 body, 2 ink, 3 detail */
+static const uint8_t SHADE[8][3] = {{0, 0, 0}, {1, 1, 0}, {2, 2, 0}, {0, 2, 19},
+ {0, 2, 10}, {3, 3, 0}, {1, 2, 16}, {1, 3, 16}};
+
+static int spx(int t, int x, int y) {
+ const uint8_t *m = &SPR[t - 1].x;
+ int w = m[2] & 0x7F;
+ y -= m[1];
+ if ((unsigned)y >= m[3]) return 0;
+ if (m[2] & 0x80 && x > 14) x = 29 - x;
+ x -= m[0];
+ if ((unsigned)x >= (unsigned)w) return 0;
+ unsigned i = (SPR[t - 1].off + y * w + x) * 3;
+ return ((SPRD[i >> 3] | SPRD[(i >> 3) + 1] << 8) >> (i & 7)) & 7;
+}
+
+static C shade(int pc, int x, int y, C bg) {
+ int k = spx(TYPE(pc), x, y);
+ if (!k) return bg;
+ const C *p = PCOL[COLOR(pc) > 1 ? x > 14 : COLOR(pc)];
+ C c[4] = {bg, p[0], p[1], p[2]};
+ return mix(c[SHADE[k][0]], c[SHADE[k][1]], SHADE[k][2]);
+}
+
+/* Draw a piece (30px, or 15px when small) over the screen content.
+ * COLOR 2 draws a half white / half black piece. */
+static void sprite(int pc, int X, int Y, int small) {
+ int s = small ? 15 : 30;
+ eadk_rect_t R = {X, Y, s, s};
+ eadk_display_pull_rect(R, buf);
+ for (int y = 0; y < s; y++)
+ for (int x = 0; x < s; x++) {
+ C *o = &buf[y * s + x];
+ if (small) {
+ C a = mix(shade(pc, 2 * x, 2 * y, *o), shade(pc, 2 * x + 1, 2 * y, *o), 16);
+ C b = mix(shade(pc, 2 * x, 2 * y + 1, *o), shade(pc, 2 * x + 1, 2 * y + 1, *o), 16);
+ *o = mix(a, b, 16);
+ } else {
+ *o = shade(pc, x, y, *o);
+ }
+ }
+ eadk_display_push_rect(R, buf);
+}
+
+/* -------------------------------------------------------------- Board */
+
+static int mode, flip, cur = 0x14, sel = -1, hintsq = -1, badsq = -1, ntg, incheck;
+static int anim_pc, anim_x, anim_y, anim_hide = -1;
+static Move tg[256];
+static char lastsan[10];
+
+static int sqx(int s) { return 30 * (flip ? 7 - (s & 7) : s & 7); }
+static int sqy(int s) { return 30 * (flip ? s >> 4 : 7 - (s >> 4)); }
+static int at(int vx, int vy) { return flip ? vy * 16 + 7 - vx : (7 - vy) * 16 + vx; }
+
+static void draw_sq(int s) {
+ int X = sqx(s), Y = sqy(s), light = ((s >> 4) + s) & 1, mark = 0;
+ Move lm = hp ? H[hp - 1].m : 0;
+ C base = light ? SQ_L : SQ_D;
+ if (s == sel || (hp && (s == MFROM(lm) || s == MTO(lm)))) base = light ? HL_L : HL_D;
+ if (s == hintsq) base = mix(base, HINT, 18);
+ if (s == badsq) base = mix(base, RED, 20);
+ int pc = s == anim_hide ? 0 : P.b[s];
+ if (sel >= 0)
+ for (int i = 0; i < ntg; i++)
+ if (MFROM(tg[i]) == sel && MTO(tg[i]) == s) mark = pc ? 2 : 1;
+ int chk = incheck && s == P.king[P.side];
+ for (int y = 0; y < 30; y++)
+ for (int x = 0; x < 30; x++) {
+ C c = base;
+ int dx = 2 * x - 29, dy = 2 * y - 29, d2 = dx * dx + dy * dy;
+ if (chk && d2 < 1300) c = mix(c, RED, d2 < 500 ? 30 : (1300 - d2) * 30 / 800);
+ if (mark == 2 && d2 > 600 && d2 < 900) c = mix(c, 0, 8);
+ if (pc) c = shade(pc, x, y, c);
+ if (mark == 1 && d2 < 150) c = mix(c, 0, d2 < 118 ? 8 : 4);
+ if (anim_pc) {
+ int u = X + x - anim_x, v = Y + y - anim_y;
+ if ((unsigned)u < 30 && (unsigned)v < 30) c = shade(anim_pc, u, v, c);
+ }
+ if (s == cur && sel != -2 && (x < 3 || x > 26 || y < 3 || y > 26)) c = light ? mix(c, INK, 13) : mix(c, WHITE, 22);
+ buf[y * 30 + x] = c;
+ }
+ eadk_display_push_rect((eadk_rect_t){X, Y, 30, 30}, buf);
+}
+
+static void draw_board(void) {
+ for (int s = 0; s < 120; s++)
+ if (!(s & 0x88)) draw_sq(s);
+}
+
+static void draw_rect_squares(int x, int y) {
+ for (int j = 0; j < 2; j++)
+ for (int i = 0; i < 2; i++) {
+ int vx = (x + i * 29) / 30, vy = (y + j * 29) / 30;
+ if (vx >= 0 && vx < 8 && vy >= 0 && vy < 8) draw_sq(at(vx, vy));
+ }
+}
+
+static void animate(Move m) {
+ int f = MFROM(m), t = MTO(m), x0 = sqx(f), y0 = sqy(f), x1 = sqx(t), y1 = sqy(t);
+ anim_pc = P.b[f], anim_hide = f, anim_x = x0, anim_y = y0;
+ int n = 7;
+ for (int i = 1; i <= n; i++) {
+ int ox = anim_x, oy = anim_y, k = n - i;
+ int e = 1024 - k * k * k * 1024 / (n * n * n); /* ease-out cubic */
+ anim_x = x0 + (x1 - x0) * e / 1024, anim_y = y0 + (y1 - y0) * e / 1024;
+ draw_rect_squares(ox, oy);
+ draw_rect_squares(anim_x, anim_y);
+ eadk_timing_msleep(14);
+ }
+ anim_pc = 0, anim_hide = -1;
+}
+
+/* ---------------------------------------------------------------- Bots */
+
+static const struct {
+ char name[6];
+ uint8_t pc, depth, noise, blunder;
+ uint16_t elo, ms;
+ C col;
+} BOTS[] = {
+ {"Pip", PAWN, 1, 250, 45, 150, 0, RGB(0x8B, 0xC3, 0x4A)},
+ {"Milo", PAWN, 1, 200, 28, 300, 0, RGB(0x4C, 0xAF, 0x50)},
+ {"Luna", KNIGHT, 1, 130, 14, 450, 0, RGB(0x26, 0xA6, 0x9A)},
+ {"Otto", KNIGHT, 2, 110, 10, 600, 0, RGB(0x29, 0xB6, 0xF6)},
+ {"Ivy", BISHOP, 2, 85, 7, 750, 0, RGB(0x42, 0x8D, 0xF5)},
+ {"Finn", BISHOP, 2, 65, 5, 900, 0, RGB(0x5C, 0x6B, 0xC0)},
+ {"Nova", ROOK, 3, 55, 3, 1050, 0, RGB(0x7E, 0x57, 0xC2)},
+ {"Hugo", ROOK, 4, 40, 2, 1200, 0, RGB(0xAB, 0x47, 0xBC)},
+ {"Vera", QUEEN, 4, 20, 1, 1400, 0, RGB(0xEC, 0x40, 0x7A)},
+ {"Rex", QUEEN, 5, 10, 0, 1600, 800, RGB(0xEF, 0x53, 0x50)},
+ {"Zara", KING, 7, 0, 0, 1850, 900, RGB(0xFF, 0x70, 0x43)},
+ {"Atlas", KING, 40, 0, 0, 2100, 2500, RGB(0xFF, 0xB3, 0x00)},
+};
+#define NBOTS 12
+
+static const struct { uint8_t min, inc; } TC[] = {{1, 0}, {3, 0}, {3, 2}, {5, 0}, {10, 0}, {15, 10}, {30, 0}, {0, 0}};
+
+static int bot = 4, pside = 0, pcol, tc = 3, autoflip = 1;
+static int32_t tm[2];
+static int prating = 800, pstreak, pdelta, spin_mode, spin_y, spin;
+
+/* -------------------------------------------------------------- Input */
+
+static int key(int ms) {
+ int32_t t = ms;
+ int e = eadk_event_get(&t);
+ return e == K_EXE ? K_OK : e;
+}
+
+static int arrow(int e, int *i, int n, int horiz) {
+ if (e == (horiz ? K_LEFT : K_UP) && *i > 0) return --*i, 1;
+ if (e == (horiz ? K_RIGHT : K_DOWN) && *i < n - 1) return ++*i, 1;
+ return 0;
+}
+
+/* ---------------------------------------------------------------- Menus */
+
+static void button(int x, int y, int w, int h, const char *s, int on, int icon) {
+ C c = on ? GREEN : CARD;
+ rrect(x, y, w, h, 8, c);
+ if (icon) {
+ int ty = y + (h - 40) / 2;
+ rrect(x + 8, ty, 40, 40, 9, SQ_L);
+ if (icon == KING) {
+ sprite(KING, x + 6, ty + 5, 0);
+ sprite(KING | BLACK, x + 20, ty + 5, 0);
+ } else {
+ sprite(icon, x + 13, ty + 5, 0);
+ }
+ text(s, x + 60, y + (h - 18) / 2, 1, WHITE, c);
+ } else {
+ ctext(s, x + w / 2, y + (h - 18) / 2, 1, on ? WHITE : RGB(0xDD, 0xDC, 0xDA), c);
+ }
+}
+
+/* Vertical list of buttons. Returns chosen index or -1. */
+static int list(const char *const *items, const uint8_t *icons, int n, int x, int w, int h, int gap, int *i) {
+ int y0 = (240 - n * h - (n - 1) * gap) / 2, redraw = 1;
+ for (;;) {
+ if (redraw)
+ for (int k = 0; k < n; k++) button(x, y0 + k * (h + gap), w, h, items[k], k == *i, icons ? icons[k] : 0);
+ int e = key(100000);
+ redraw = arrow(e, i, n, 0);
+ if (e == K_OK) return *i;
+ if (e == K_BACK) return -1;
+ }
+}
+
+static int main_menu(int *i) {
+ static const char *const items[] = {"Play", "Puzzles", "2 Players"};
+ static const uint8_t icons[] = {KNIGHT | BLACK, QUEEN | BLACK, KING};
+ fill(0, 0, 320, 240, BG);
+ return list(items, icons, 3, 60, 200, 56, 14, i);
+}
+
+static void avatar(int b, int cx, int cy, int r) {
+ disc(cx, cy, r, BOTS[b].col);
+ sprite(BOTS[b].pc, cx - 15, cy - 16, 0);
+}
+
+static int bot_select(void) {
+ fill(0, 0, 320, 240, BG);
+ int redraw = 1;
+ for (;;) {
+ if (redraw) {
+ for (int k = 0; k < NBOTS; k++) {
+ C c = k == bot ? CARD : BG;
+ rrect(6, k * 20, 148, 20, 6, c);
+ disc(20, k * 20 + 10, 5, BOTS[k].col);
+ text(BOTS[k].name, 32, k * 20 + 3, 0, k == bot ? WHITE : RGB(0xC8, 0xC7, 0xC5), c);
+ char e[6];
+ itoa(BOTS[k].elo, e);
+ text(e, 146 - 7 * strlen(e), k * 20 + 3, 0, DIM, c);
+ }
+ fill(160, 0, 160, 240, BG);
+ avatar(bot, 240, 62, 40);
+ ctext(BOTS[bot].name, 240, 114, 1, WHITE, BG);
+ char e[6];
+ itoa(BOTS[bot].elo, e);
+ ctext(e, 240, 136, 0, DIM, BG);
+ for (int k = 0; k < 3; k++) {
+ int x = 184 + k * 40;
+ rrect(x, 172, 32, 32, 8, k == pside ? GREEN : CARD);
+ sprite(KING | (k == 1 ? 16 : k == 2 ? BLACK : 0), x + 1, 173, 0);
+ }
+ }
+ int e = key(100000), o = bot, os = pside;
+ arrow(e, &bot, NBOTS, 0);
+ arrow(e, &pside, 3, 1);
+ redraw = o != bot || os != pside;
+ if (e == K_OK) return 1;
+ if (e == K_BACK) return 0;
+ }
+}
+
+static int time_select(void) {
+ fill(0, 0, 320, 240, BG);
+ int redraw = 1;
+ for (;;) {
+ if (redraw)
+ for (int k = 0; k < 8; k++) {
+ int x = 12 + (k & 3) * 76, y = 64 + (k >> 2) * 64;
+ char s[8], *o = s;
+ if (TC[k].min) {
+ o = itoa(TC[k].min, o);
+ *o++ = '+';
+ itoa(TC[k].inc, o);
+ } else {
+ strcpy(s, "\xE2\x88\x9E");
+ }
+ rrect(x, y, 68, 52, 8, k == tc ? GREEN : CARD);
+ ctext(s, x + 34, y + 17, 1, WHITE, k == tc ? GREEN : CARD);
+ }
+ int e = key(100000), o = tc;
+ if (e == K_LEFT && tc & 3) tc--;
+ if (e == K_RIGHT && (tc & 3) < 3) tc++;
+ if (e == K_UP && tc > 3) tc -= 4;
+ if (e == K_DOWN && tc < 4) tc += 4;
+ redraw = o != tc;
+ if (e == K_OK) return 1;
+ if (e == K_BACK) return 0;
+ }
+}
+
+/* Modal list drawn over the dimmed board. */
+static int overlay(const char *const *items, int n) {
+ dim(0, 0, 240, 240);
+ int h = n * 36 + 12, y = (240 - h) / 2, i = 0;
+ rrect(40, y, 160, h, 12, BG);
+ for (;;) {
+ for (int k = 0; k < n; k++) {
+ C c = k == i ? GREEN : BG;
+ rrect(46, y + 6 + k * 36, 148, 36, 8, c);
+ ctext(items[k], 120, y + 15 + k * 36, 1, WHITE, c);
+ }
+ int e = key(100000);
+ arrow(e, &i, n, 0);
+ if (e == K_OK || e == K_BACK) return e == K_OK ? i : -1;
+ }
+}
+
+/* --------------------------------------------------------------- Panel */
+
+static const uint8_t START[7] = {0, 8, 2, 2, 2, 1, 0};
+static const uint8_t WORTH[7] = {0, 1, 3, 3, 5, 9, 0};
+
+static int material(int c) {
+ int m = 0;
+ for (int t = PAWN; t < KING; t++) m += WORTH[t] * P.cnt[c << 3 | t];
+ return m;
+}
+
+/* Pieces captured by side c, drawn as small icons from (x, y). */
+static void captures(int c, int y) {
+ int x = 244;
+ for (int t = QUEEN; t >= PAWN; t--) {
+ int n = START[t] - P.cnt[(!c) << 3 | t];
+ for (int k = 0; k < n; k++, x += 7) {
+ if (x > 302) x = 244, y += 15;
+ sprite(t | (!c) << 3, x, y, 1);
+ }
+ if (n > 0) x += 6;
+ }
+ int d = material(c) - material(!c);
+ if (d > 0) {
+ char s[6] = "+";
+ itoa(d, s + 1);
+ text(s, x > 290 ? 244 : x + 4, x > 290 ? y + 15 : y, 0, DIM, BG);
+ }
+}
+
+static void fmt_clock(int32_t ms, char *o) {
+ if (ms < 0) ms = 0;
+ if (ms < 10000) {
+ o = itoa(ms / 1000, o);
+ *o++ = '.', *o++ = '0' + ms / 100 % 10, *o = 0;
+ } else {
+ int s = (ms + 999) / 1000;
+ o = itoa(s / 60, o);
+ *o++ = ':', *o++ = '0' + s % 60 / 10, *o++ = '0' + s % 10, *o = 0;
+ }
+}
+
+static void clock_pill(int c, int y) {
+ int on = P.side == c;
+ C bg = on ? (tm[c] < 10000 && TC[tc].min ? RED : WHITE) : CARD, fg = on ? (bg == RED ? WHITE : INK) : DIM;
+ rrect(244, y, 72, 34, 8, bg);
+ if (TC[tc].min) {
+ char s[8];
+ fmt_clock(tm[c], s);
+ ctext(s, 280, y + 8, 1, fg, bg);
+ } else {
+ sprite(KING | c << 3, 265, y + 2, 0);
+ }
+}
+
+static void feedback(int ok) {
+ fill(244, 84, 72, 76, BG);
+ if (ok < 0) return;
+ disc(280, 120, 26, ok ? GREEN : RED);
+ if (ok) {
+ stroke(268, 121, 276, 129, 5, WHITE);
+ stroke(276, 129, 292, 112, 5, WHITE);
+ } else {
+ stroke(270, 110, 290, 130, 5, WHITE);
+ stroke(290, 110, 270, 130, 5, WHITE);
+ }
+}
+
+static void puzzle_rating(void) {
+ char s[8];
+ fill(240, 176, 80, 64, BG);
+ itoa(prating, s);
+ ctext(s, 280, 186, 1, WHITE, BG);
+ if (pdelta) {
+ char *o = s;
+ if (pdelta > 0) *o++ = '+';
+ itoa(pdelta, o);
+ ctext(s, 280, 208, 0, pdelta > 0 ? GREEN : RED, BG);
+ }
+}
+
+static void panel(void) {
+ int top = !flip;
+ fill(240, 0, 80, 240, BG);
+ if (mode == M_PUZ) {
+ int s = !PZ.start.side;
+ C bg = s ? RGB(0x10, 0x10, 0x10) : WHITE;
+ rrect(244, 8, 72, 34, 8, bg);
+ char t[10] = "Mate in ";
+ t[8] = '0' + PZ.mate;
+ ctext(PZ.mate ? t : "Best move", 280, 18, 0, s ? WHITE : INK, bg);
+ if (pstreak > 1) {
+ char k[12];
+ strcpy(itoa(pstreak, k), " in a row");
+ ctext(k, 280, 52, 0, DIM, BG);
+ }
+ puzzle_rating();
+ return;
+ }
+ if (mode == M_BOT) {
+ avatar(bot, 280, 24, 18);
+ ctext(BOTS[bot].name, 280, 46, 1, WHITE, BG);
+ char e[6];
+ itoa(BOTS[bot].elo, e);
+ ctext(e, 280, 66, 0, DIM, BG);
+ captures(top, 88);
+ } else {
+ clock_pill(top, 6);
+ clock_pill(!top, 200);
+ captures(top, 46);
+ }
+ captures(!top, mode == M_BOT ? 200 : 164);
+ if (hp) {
+ char n[8];
+ strcpy(itoa((hp + 1) / 2, n), P.side ? "." : "...");
+ ctext(n, 280, 112 - (mode == M_2P) * 8, 0, DIM, BG);
+ ctext(lastsan, 280, 128 - (mode == M_2P) * 8, 1, WHITE, BG);
+ }
+}
+
+/* ------------------------------------------------------------ Moving */
+
+static void refresh(void) {
+ sel = -1;
+ ntg = legal(tg);
+ incheck = in_check();
+}
+
+static void set_lastsan(void) {
+ lastsan[0] = 0;
+ if (!hp) return;
+ Move m = H[hp - 1].m;
+ unmake();
+ san(m, lastsan);
+ make(m);
+}
+
+static void do_move(Move m) {
+ san(m, lastsan);
+ animate(m);
+ make(m);
+ refresh();
+ draw_board();
+ panel();
+}
+
+static int promo_pick(int to) {
+ static const uint8_t order[4] = {3, 0, 2, 1};
+ int X = sqx(to), Y = sqy(to), dir = Y ? -30 : 30, i = 0, c = P.side << 3;
+ for (;;) {
+ for (int k = 0; k < 4; k++) {
+ fill(X, Y + k * dir, 30, 30, k == i ? GREEN : WHITE);
+ sprite(c | (order[k] + KNIGHT), X, Y + k * dir, 0);
+ }
+ int e = key(100000);
+ if (e == K_UP || e == K_DOWN) i = (i + ((e == K_DOWN) == (dir > 0) ? 1 : 3)) & 3;
+ if (e == K_OK || e == K_BACK) {
+ draw_board();
+ return e == K_OK ? order[i] : -1;
+ }
+ }
+}
+
+/* Cursor handling. Returns a move, 0, or -1 when back is pressed with nothing selected. */
+static int human(int e) {
+ if (e <= K_RIGHT) {
+ int f = cur & 7, r = cur >> 4, d = flip ? -1 : 1, o = cur;
+ if (e == K_LEFT) f = (f - d) & 7;
+ if (e == K_RIGHT) f = (f + d) & 7;
+ if (e == K_UP) r = (r + d) & 7;
+ if (e == K_DOWN) r = (r - d) & 7;
+ cur = r * 16 + f;
+ draw_sq(o);
+ draw_sq(cur);
+ } else if (e == K_OK) {
+ if (sel >= 0)
+ for (int i = 0; i < ntg; i++)
+ if (MFROM(tg[i]) == sel && MTO(tg[i]) == cur) {
+ Move m = tg[i];
+ if (TYPE(P.b[sel]) == PAWN && (cur >> 4 == 0 || cur >> 4 == 7)) {
+ int p = promo_pick(cur);
+ if (p < 0) return 0;
+ m = MOVE(sel, cur, p);
+ }
+ return m;
+ }
+ int p = P.b[cur];
+ sel = p && COLOR(p) == P.side && sel != cur ? cur : -1;
+ draw_board();
+ } else if (e == K_BACK) {
+ if (sel < 0) return -1;
+ sel = -1;
+ draw_board();
+ } else if (e == K_UNDO) {
+ return -2;
+ }
+ return 0;
+}
+
+/* ---------------------------------------------------------------- Game */
+
+static int game_over(const char *title, const char *why) {
+ eadk_timing_msleep(400);
+ dim(0, 0, 240, 240);
+ rrect(20, 58, 200, 124, 12, BG);
+ ctext(title, 120, 74, 1, WHITE, BG);
+ ctext(why, 120, 98, 0, DIM, BG);
+ int i = 0;
+ for (;;) {
+ static const char *const b[2] = {"Rematch", "Menu"};
+ for (int k = 0; k < 2; k++) {
+ C c = k == i ? GREEN : CARD;
+ rrect(30 + k * 94, 130, 86, 38, 8, c);
+ ctext(b[k], 73 + k * 94, 140, 1, WHITE, c);
+ }
+ int e = key(100000);
+ arrow(e, &i, 2, 1);
+ if (e == K_OK) return !i;
+ if (e == K_BACK) return 0;
+ }
+}
+
+static void undo(int n) {
+ while (n-- && hp) unmake();
+ if (mode == M_2P && autoflip) flip = P.side;
+ set_lastsan();
+ refresh();
+ draw_board();
+ panel();
+}
+
+static void game(int md) {
+ static const char *const why[] = {"", "Checkmate", "Stalemate", "50-move rule", "Repetition", "Insufficient material"};
+again:
+ mode = md;
+ ch_reset();
+ refresh();
+ lastsan[0] = 0;
+ pcol = pside == 1 ? eadk_random() & 1 : pside >> 1;
+ flip = md == M_BOT && pcol;
+ int curs[2] = {0x14, 0x64};
+ cur = curs[flip];
+ tm[0] = tm[1] = TC[tc].min * 60000;
+ uint64_t last = eadk_timing_millis();
+ draw_board();
+ panel();
+ for (;;) {
+ const char *title = 0, *reason = 0;
+ int st = status(), winner = -1;
+ if (st) {
+ reason = why[st];
+ if (st == CHECKMATE) winner = !P.side;
+ }
+ if (md == M_2P && TC[tc].min && hp) {
+ uint64_t now = eadk_timing_millis();
+ int32_t before = tm[P.side];
+ tm[P.side] -= now - last;
+ last = now;
+ if (tm[P.side] <= 0) winner = !P.side, reason = "Timeout";
+ if (before / 100 != tm[P.side] / 100 && (tm[P.side] < 10000 || before / 1000 != tm[P.side] / 1000))
+ clock_pill(P.side, (P.side == !flip) ? 6 : 200);
+ } else {
+ last = eadk_timing_millis();
+ }
+ if (reason) {
+ if (md == M_BOT) title = winner < 0 ? "Draw" : winner == pcol ? "You won" : BOTS[bot].name;
+ else title = winner < 0 ? "Draw" : winner ? "Black won" : "White won";
+ static char t[12];
+ if (md == M_BOT && winner >= 0 && winner != pcol) strcpy(strcpy(t, title) + strlen(title), " won"), title = t;
+ if (game_over(title, reason)) goto again;
+ return;
+ }
+ if (md == M_BOT && P.side != pcol) {
+ uint64_t t0 = eadk_timing_millis();
+ spin_mode = 2, spin_y = 80;
+ Move m = bot_move(BOTS[bot].depth, BOTS[bot].noise, BOTS[bot].blunder, BOTS[bot].ms);
+ spin_mode = 0;
+ int32_t wait = 450 - (int32_t)(eadk_timing_millis() - t0);
+ if (wait > 0) eadk_timing_msleep(wait);
+ do_move(m);
+ continue;
+ }
+ int e = key(md == M_2P && TC[tc].min && hp ? 50 : 100000);
+ int m = human(e);
+ if (m == -2) {
+ undo(md == M_BOT ? (hp >= 2) * 2 : 1);
+ continue;
+ }
+ if (m == -1) {
+ static const char *const pb[] = {"Undo", "Flip", "Resign", "Menu"};
+ static const char *const p2[] = {"Undo", "Flip", "Draw", "Resign", "Menu"};
+ int k = md == M_BOT ? overlay(pb, 4) : overlay(p2, 5);
+ if (md == M_BOT && k >= 2) k++;
+ if (k == 0) {
+ undo(md == M_BOT ? (hp >= 2) * 2 : 1);
+ continue;
+ }
+ if (k == 1) {
+ flip ^= 1;
+ autoflip = flip == P.side;
+ }
+ if (k == 2 || k == 3) {
+ title = k == 2 ? "Draw" : P.side ? "White won" : "Black won";
+ if (md == M_BOT && k == 3) {
+ static char t[12];
+ strcpy(strcpy(t, BOTS[bot].name) + strlen(BOTS[bot].name), " won");
+ title = t;
+ }
+ if (game_over(title, k == 2 ? "Agreement" : "Resignation")) goto again;
+ return;
+ }
+ if (k == 4) return;
+ draw_board();
+ panel();
+ last = eadk_timing_millis();
+ continue;
+ }
+ if (m > 0) {
+ int mover = P.side;
+ curs[mover] = cur;
+ do_move(m);
+ if (md == M_2P) {
+ tm[mover] += TC[tc].inc * 1000;
+ if (autoflip && flip != P.side) {
+ eadk_timing_msleep(250);
+ flip = P.side;
+ cur = curs[P.side];
+ draw_board();
+ }
+ panel();
+ }
+ }
+ }
+}
+
+/* ------------------------------------------------------------- Puzzles */
+
+/* Progress animation while the engine works: 0 off, 1 ring (puzzles), 2 dots (bot). */
+void ui_tick(void) {
+ static uint64_t t;
+ uint64_t now = eadk_timing_millis();
+ if (!spin_mode || now - t < 70) return;
+ t = now;
+ spin++;
+ for (int k = 0; k < 8; k++) {
+ static const int8_t dx[8] = {0, 11, 16, 11, 0, -11, -16, -11}, dy[8] = {-16, -11, 0, 11, 16, 11, 0, -11};
+ if (spin_mode == 1) fill(278 + dx[(spin - k) & 7], 118 + dy[(spin - k) & 7], 5, 5, mix(BG, WHITE, 32 - k * 4));
+ else if (k < 3) fill(271 + k * 8, spin_y, 3, 3, (spin % 3) == k ? WHITE : CARD);
+ }
+}
+
+static void rate(int won) {
+ int e = 16 + (prating - PZ.rating) / 25;
+ e = e < 2 ? 2 : e > 30 ? 30 : e;
+ pdelta = won ? 32 - e : -e;
+ prating += pdelta;
+ if (prating < 100) prating = 100;
+ pstreak = won ? pstreak + 1 : 0;
+}
+
+/* Generate the next puzzle while the solved one stays on screen. */
+static Puzzle next;
+static int have_next;
+static void pregenerate(int kind) {
+ static Undo h[16];
+ Puzzle cur = PZ;
+ Pos p = P;
+ int n = hp;
+ memcpy(h, H, sizeof h);
+ spin_mode = 2, spin_y = 164;
+ puzzle_gen(kind, prating);
+ spin_mode = 0;
+ next = PZ, have_next = 1;
+ PZ = cur, P = p, hp = n;
+ memcpy(H, h, sizeof h);
+ fill(270, 164, 24, 3, BG);
+}
+
+static void puzzles(int kind) {
+ mode = M_PUZ;
+ have_next = 0;
+ for (;;) {
+ if (have_next) {
+ PZ = next, have_next = 0;
+ } else {
+ fill(240, 0, 80, 240, BG);
+ sel = -2;
+ draw_board();
+ dim(0, 0, 240, 240);
+ spin_mode = 1;
+ puzzle_gen(kind, prating);
+ spin_mode = 0;
+ }
+ P = PZ.start;
+ hp = 0;
+ flip = !P.side;
+ cur = flip ? 0x74 : 0x04;
+ refresh();
+ sel = -2;
+ lastsan[0] = 0;
+ pdelta = 0;
+ draw_board();
+ panel();
+ eadk_timing_msleep(500);
+ do_move(PZ.pre);
+ int step = 0, failed = 0, done = 0, rem = PZ.mate;
+ for (;;) {
+ int e = key(100000), m = 0;
+ if (done) {
+ if (e == K_OK) break;
+ if (e != K_BACK) continue;
+ m = -1;
+ } else {
+ m = human(e);
+ }
+ if (m == -1) {
+ static const char *const it[] = {"Hint", "Solution", "Next", "Menu"};
+ int k = overlay(it, 4);
+ draw_board();
+ if (k == 3) return;
+ if (k == 2) {
+ if (!done && !failed) rate(0);
+ break;
+ }
+ if (k < 0 || done) continue;
+ Move sm = PZ.mate ? (step ? mate_move(rem) : PZ.sol[0]) : PZ.sol[step];
+ if (k == 0) {
+ hintsq = MFROM(sm);
+ draw_sq(hintsq);
+ continue;
+ }
+ if (!failed) failed = 1, rate(0);
+ m = sm;
+ }
+ if (m <= 0) continue;
+ hintsq = -1;
+ make(m);
+ int ok = (!step && m == PZ.sol[0]) || status() == CHECKMATE ||
+ (PZ.mate ? mated_within(rem - 1) : m == PZ.sol[step]);
+ unmake();
+ if (!ok) {
+ do_move(m);
+ badsq = MTO(m);
+ draw_sq(badsq);
+ if (!failed) failed = 1, rate(0);
+ feedback(0);
+ puzzle_rating();
+ eadk_timing_msleep(700);
+ badsq = -1;
+ unmake();
+ set_lastsan();
+ refresh();
+ draw_board();
+ continue;
+ }
+ do_move(m);
+ step++;
+ if (status() == CHECKMATE || (!PZ.mate && step >= PZ.nsol)) {
+ if (!failed) rate(1);
+ done = 1;
+ sel = -2;
+ draw_board();
+ panel();
+ feedback(1);
+ pregenerate(kind);
+ continue;
+ }
+ feedback(1);
+ eadk_timing_msleep(350);
+ feedback(-1);
+ do_move(PZ.mate ? defend(--rem) : PZ.sol[step]);
+ step++;
+ }
+ hintsq = -1;
+ }
+}
+
+static int puzzle_menu(int *i) {
+ static const char *const items[] = {"Mix", "Mate in 1", "Mate in 2", "Mate in 3", "Best move"};
+ fill(0, 0, 320, 240, BG);
+ return list(items, 0, 5, 70, 180, 38, 8, i);
+}
+
+int main(void) {
+ ch_init();
+ int m = 0, pk = 0;
+ for (;;) {
+ if (main_menu(&m) < 0) return 0;
+ if (m == 0 && bot_select()) game(M_BOT);
+ if (m == 1 && puzzle_menu(&pk) >= 0) puzzles(pk);
+ if (m == 2 && time_select()) game(M_2P);
+ }
+}
diff --git a/games/chess/src/sprites.h b/games/chess/src/sprites.h
new file mode 100644
index 00000000..17bfbc70
--- /dev/null
+++ b/games/chess/src/sprites.h
@@ -0,0 +1,44 @@
+/* Generated by tools/pieces.py: 3 bits per pixel, 8 pixels per 3 bytes. */
+static const struct { uint16_t off; uint8_t x, y, w, h; } SPR[6] = {
+ {0, 7, 4, 136, 23},
+ {184, 6, 3, 18, 24},
+ {616, 7, 2, 16, 25},
+ {1016, 6, 3, 137, 24},
+ {1232, 3, 3, 140, 24},
+ {1520, 6, 2, 137, 25},
+};
+static const uint8_t SPRD[658] = {
+ 0,0,108,0,64,201,0,32,39,0,168,36,0,230,36,0,230,36,0,168,
+ 36,0,32,37,0,0,73,0,0,73,0,64,217,0,32,39,0,48,37,0,
+ 64,37,0,32,39,0,168,36,0,230,36,0,101,219,156,36,73,178,109,219,
+ 74,146,36,178,109,219,220,182,109,0,0,0,36,0,0,0,0,128,163,6,
+ 0,0,0,0,160,36,17,0,0,0,0,230,196,18,1,0,0,48,37,73,
+ 44,0,0,0,234,77,146,104,0,0,80,105,147,36,209,0,0,114,146,36,
+ 73,34,0,152,146,36,73,146,136,0,148,36,73,146,36,30,48,53,137,228,
+ 36,73,4,168,143,180,41,73,18,17,178,52,96,74,146,68,4,53,0,152,
+ 147,36,17,1,0,192,148,36,73,52,0,0,168,36,73,18,15,0,64,37,
+ 73,146,68,3,0,204,73,146,36,17,1,0,114,146,36,73,68,0,156,36,
+ 73,146,36,13,144,36,73,146,36,73,2,148,36,73,146,36,137,8,217,182,
+ 109,219,182,45,130,219,182,109,219,182,13,0,0,96,3,0,0,0,0,72,
+ 18,0,0,0,0,40,17,0,0,0,0,200,22,0,0,0,0,80,34,0,
+ 0,0,0,76,26,0,0,0,64,201,150,8,0,0,40,39,137,69,0,0,
+ 228,36,105,44,0,0,149,36,109,34,2,192,156,228,77,226,1,128,156,164,
+ 79,98,1,128,146,188,73,18,1,192,156,36,73,226,1,192,148,36,73,162,
+ 1,0,148,36,73,34,0,0,166,36,73,52,0,0,32,217,182,4,0,0,
+ 38,73,146,52,0,0,38,219,182,53,0,192,36,73,146,164,1,156,156,36,
+ 73,98,141,146,147,36,73,18,75,178,109,219,182,109,91,219,182,109,219,182,
+ 109,0,73,128,4,38,17,19,48,139,152,129,89,155,12,204,177,29,96,178,
+ 109,3,156,36,9,0,230,36,0,48,39,1,128,57,9,0,204,73,0,96,
+ 78,2,0,115,18,0,152,147,0,192,148,4,0,166,36,0,56,73,2,40,
+ 73,18,64,37,73,192,73,146,4,73,146,36,42,73,146,80,182,109,27,219,
+ 182,109,0,0,0,0,8,0,0,9,76,0,0,74,131,2,0,152,35,76,
+ 152,134,73,2,70,69,3,7,128,84,52,96,0,136,105,0,54,96,0,9,
+ 96,2,6,64,3,166,97,0,164,97,18,5,96,210,38,75,0,168,88,78,
+ 2,0,74,146,36,0,32,39,73,2,0,115,146,36,0,64,253,255,15,0,
+ 80,219,182,0,0,37,73,2,0,144,36,73,0,48,73,146,4,0,114,146,
+ 36,0,32,219,182,13,0,220,182,109,0,0,0,3,0,0,16,0,0,155,
+ 0,0,148,4,0,0,41,0,0,0,1,0,0,8,0,0,64,192,36,73,
+ 194,228,88,254,148,36,201,229,36,73,174,36,73,114,57,73,146,79,73,146,
+ 28,114,146,228,160,146,36,1,166,36,9,64,181,109,129,201,73,2,76,146,
+ 36,76,146,36,65,78,146,4,178,109,219,224,182,109,3,0,0,0,
+};
diff --git a/games/chess/test/perft.c b/games/chess/test/perft.c
new file mode 100644
index 00000000..ba5b5347
--- /dev/null
+++ b/games/chess/test/perft.c
@@ -0,0 +1,106 @@
+/* Host-side engine tests: perft node counts on standard positions,
+ * incremental hash/eval consistency, and a quick search benchmark. */
+#include "../src/chess.c"
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+
+uint64_t eadk_timing_millis() {
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec * 1000ull + ts.tv_nsec / 1000000;
+}
+uint32_t eadk_random() { return (uint32_t)rand(); }
+void ui_tick(void) {}
+
+static void set_fen(const char *f) {
+ memset(&P, 0, sizeof P);
+ hp = 0;
+ for (int r = 7, c = 0; *f && *f != ' '; f++) {
+ if (*f == '/') r--, c = 0;
+ else if (*f >= '1' && *f <= '8') c += *f - '0';
+ else {
+ const char *pcs = " PNBRQK pnbrqk", *q = strchr(pcs, *f);
+ put(r * 16 + c++, q - pcs);
+ }
+ }
+ f++;
+ P.side = *f == 'b';
+ f += 2;
+ for (; *f && *f != ' '; f++) P.castle |= *f == 'K' ? 1 : *f == 'Q' ? 2 : *f == 'k' ? 4 : *f == 'q' ? 8 : 0;
+ f++;
+ P.ep = *f == '-' ? NOSQ : (f[1] - '1') * 16 + f[0] - 'a';
+ P.hash ^= Zc[P.castle];
+ if (P.ep != NOSQ) P.hash ^= Zep[P.ep & 7];
+ if (P.side) P.hash ^= Zside;
+}
+
+static int consistent(void) {
+ Pos s = P;
+ uint8_t b[128];
+ memcpy(b, P.b, 128);
+ memset(&P, 0, sizeof P);
+ for (int i = 0; i < 128; i++)
+ if (!OFF(i) && b[i]) put(i, b[i]);
+ P.side = s.side, P.castle = s.castle, P.ep = s.ep, P.fifty = s.fifty;
+ P.hash ^= Zc[P.castle];
+ if (P.ep != NOSQ) P.hash ^= Zep[P.ep & 7];
+ if (P.side) P.hash ^= Zside;
+ int ok = P.hash == s.hash && P.mg == s.mg && P.eg == s.eg && P.phase == s.phase &&
+ !memcmp(P.cnt, s.cnt, 16) && P.king[0] == s.king[0] && P.king[1] == s.king[1];
+ P = s;
+ return ok;
+}
+
+static uint64_t perft(int d) {
+ Move ml[256];
+ int n = legal(ml);
+ if (d == 1) return n;
+ uint64_t c = 0;
+ for (int i = 0; i < n; i++) {
+ make(ml[i]);
+ if (d == 2 && !consistent()) {
+ printf("inconsistent incremental state\n");
+ exit(1);
+ }
+ c += perft(d - 1);
+ unmake();
+ }
+ return c;
+}
+
+int main(void) {
+ static const struct { const char *fen; int d; uint64_t n; } T[] = {
+ {"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -", 5, 4865609},
+ {"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq -", 4, 4085603},
+ {"8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - -", 5, 674624},
+ {"r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq -", 4, 422333},
+ {"rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ -", 4, 2103487},
+ {"r4rk1/1pp1qppp/p1np1n2/2b1p1B1/2B1P1b1/P1NP1N2/1PP1QPPP/R4RK1 w - -", 4, 3894594},
+ };
+ ch_init();
+ int fail = 0;
+ for (unsigned i = 0; i < sizeof T / sizeof *T; i++) {
+ set_fen(T[i].fen);
+ uint64_t n = perft(T[i].d);
+ printf("perft %u: %llu %s\n", i, (unsigned long long)n, n == T[i].n ? "ok" : "FAIL");
+ fail |= n != T[i].n;
+ }
+ static const char *bench[] = {
+ "r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq -",
+ "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq -",
+ "6k1/5ppp/8/8/8/8/5PPP/3R2K1 w - -",
+ };
+ for (unsigned i = 0; i < 3; i++) {
+ set_fen(bench[i]);
+ uint64_t t = eadk_timing_millis();
+ int s;
+ Move m = think(7, 100000, &s);
+ t = eadk_timing_millis() - t;
+ char buf[16];
+ san(m, buf);
+ printf("bench %u: %s score %d depth %d nodes %u in %llums\n", i, buf, s, think_depth, nodes,
+ (unsigned long long)t);
+ }
+ return fail;
+}
diff --git a/games/chess/tools/icon.py b/games/chess/tools/icon.py
new file mode 100644
index 00000000..6b9a53c2
--- /dev/null
+++ b/games/chess/tools/icon.py
@@ -0,0 +1,39 @@
+#!/usr/bin/env python3
+"""Render the home screen icon (src/icon.png, 55x56): a knight on a green tile."""
+import struct, sys, zlib, os
+sys.path.insert(0, os.path.dirname(__file__))
+import pieces
+
+W, H, SS = 55, 56, 6
+GREEN, BODY, INK = (0x81, 0xB6, 0x4C), (0xF9, 0xF9, 0xF7), (0x3A, 0x3A, 0x3A)
+tile = pieces.box(0, 0, W, H, 10)
+body, details, eye = pieces.knight()
+scale, ox, oy = 1.6, 3.5, 3.5 # icon px -> piece space
+
+
+def px(x, y):
+ acc = [0, 0, 0]
+ for sy in range(SS):
+ for sx in range(SS):
+ X, Y = x + (sx + 0.5) / SS, y + (sy + 0.5) / SS
+ c = (255, 255, 255)
+ if tile(X, Y) < 0:
+ c = GREEN
+ u, v = (X - ox) / scale + 0.8, (Y - oy) / scale
+ d = body(u, v)
+ if d < 0:
+ ink = d > -1.0 or eye(u, v) < 0 or any(g(u, v) < 0.5 for g in details)
+ c = INK if ink else BODY
+ acc = [a + b for a, b in zip(acc, c)]
+ return tuple(round(a / SS / SS) for a in acc)
+
+
+raw = b''.join(b'\0' + bytes(v for x in range(W) for v in px(x, y)) for y in range(H))
+
+
+def chunk(t, d):
+ return struct.pack('>I', len(d)) + t + d + struct.pack('>I', zlib.crc32(t + d))
+
+
+open('src/icon.png', 'wb').write(b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', W, H, 8, 2, 0, 0, 0)) +
+ chunk(b'IDAT', zlib.compress(raw, 9)) + chunk(b'IEND', b''))
diff --git a/games/chess/tools/pieces.py b/games/chess/tools/pieces.py
new file mode 100644
index 00000000..e077d400
--- /dev/null
+++ b/games/chess/tools/pieces.py
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+"""Rasterize the chess piece set into compact sprites (src/sprites.h).
+
+Pieces are described as signed distance fields and rendered with 8x8
+supersampling into a 30x30 cell. Each pixel is quantized to one of eight
+classes (3 bits):
+ 0 transparent 1 body 2 outline 3 outline 60% over background
+ 4 outline 30% 5 inner detail 6 outline/body 7 detail/body
+Symmetric pieces only store their left half.
+
+ python3 tools/pieces.py # writes src/sprites.h
+ python3 tools/pieces.py prev.png # also writes a zoomed preview (docs/pieces.png)
+"""
+import math, struct, sys, zlib
+
+N = 30 # cell size
+SS = 8 # supersampling per axis
+OUTLINE = 1.2 # outline width in pixels
+DETAIL = 0.55 # half width of inner detail strokes
+
+
+def length(x, y):
+ return math.sqrt(x * x + y * y)
+
+
+def circle(cx, cy, r):
+ return lambda x, y: length(x - cx, y - cy) - r
+
+
+def ellipse(cx, cy, rx, ry):
+ m = min(rx, ry)
+ return lambda x, y: (length((x - cx) / rx, (y - cy) / ry) - 1) * m
+
+
+def box(x0, y0, x1, y1, r=0.0):
+ cx, cy, hx, hy = (x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0) / 2, (y1 - y0) / 2
+
+ def f(x, y):
+ qx, qy = abs(x - cx) - hx + r, abs(y - cy) - hy + r
+ return length(max(qx, 0), max(qy, 0)) + min(max(qx, qy), 0) - r
+ return f
+
+
+def poly(pts):
+ def f(x, y):
+ d = 1e9
+ s = 1
+ n = len(pts)
+ for i in range(n):
+ ax, ay = pts[i]
+ bx, by = pts[i - 1]
+ ex, ey = bx - ax, by - ay
+ wx, wy = x - ax, y - ay
+ t = max(0, min(1, (wx * ex + wy * ey) / (ex * ex + ey * ey)))
+ d = min(d, length(wx - ex * t, wy - ey * t))
+ c1, c2, c3 = y >= ay, y < by, ex * wy > ey * wx
+ if (c1 and c2 and c3) or (not c1 and not c2 and not c3):
+ s = -s
+ return s * d
+ return f
+
+
+def seg(ax, ay, bx, by):
+ def f(x, y):
+ ex, ey, wx, wy = bx - ax, by - ay, x - ax, y - ay
+ t = max(0, min(1, (wx * ex + wy * ey) / (ex * ex + ey * ey)))
+ return length(wx - ex * t, wy - ey * t)
+ return f
+
+
+def union(*fs):
+ return lambda x, y: min(f(x, y) for f in fs)
+
+
+def smooth_union(k, *fs):
+ def f(x, y):
+ d = fs[0](x, y)
+ for g in fs[1:]:
+ e = g(x, y)
+ h = max(0, min(1, 0.5 + 0.5 * (e - d) / k))
+ d = e * (1 - h) + d * h - k * h * (1 - h)
+ return d
+ return f
+
+
+def sub(a, b):
+ return lambda x, y: max(a(x, y), -b(x, y))
+
+
+def mirror(pts):
+ """Close a left-half outline (top to bottom) into a symmetric polygon."""
+ return pts + [(N - x, y) for x, y in reversed(pts)]
+
+
+# ---------------------------------------------------------------- pieces
+def pawn():
+ body = smooth_union(1.2,
+ circle(15, 8.9, 4.7),
+ poly(mirror([(12.4, 13.2), (10.6, 16.2), (11.9, 16.6), (9.4, 22.8)])),
+ box(7.0, 22.2, 23.0, 26.8, 1.6))
+ return body, []
+
+
+def rook():
+ top = sub(box(8.2, 3.6, 21.8, 9.6, 0.6),
+ union(box(11.4, 2, 13.4, 6.4), box(16.6, 2, 18.6, 6.4)))
+ body = union(top,
+ poly(mirror([(10.2, 9), (10.6, 20.5)])),
+ box(8.6, 19.8, 21.4, 23.2, 0.6),
+ box(6.8, 22.6, 23.2, 26.8, 1.2))
+ details = [seg(9.5, 9.6, 20.5, 9.6), seg(9.8, 20.2, 20.2, 20.2), seg(8, 23.2, 22, 23.2)]
+ return body, details
+
+
+def bishop():
+ mitre = smooth_union(0.8,
+ ellipse(15, 14.2, 5.9, 6.9),
+ poly([(15, 6.0), (19.9, 12), (10.1, 12)]))
+ body = union(
+ circle(15, 4.6, 2.2),
+ mitre,
+ box(10.4, 19.6, 19.6, 22.6, 0.8),
+ poly(mirror([(9.5, 22), (7.4, 26.8)])),
+ box(7, 23.5, 23, 26.8, 1.2))
+ details = [seg(16.6, 10.6, 14.2, 14.4), seg(11.4, 19.7, 18.6, 19.7), seg(9.6, 22.8, 20.4, 22.8)]
+ return body, details
+
+
+def queen():
+ tips = [(5.6, 9.0), (10.2, 6.6), (15, 5.6), (19.8, 6.6), (24.4, 9.0)]
+ crown = poly([(8.4, 22.6), (5.4, 10.6), (10.6, 15.0), (10.0, 8.2), (13.9, 14.2), (15, 7.2),
+ (16.1, 14.2), (20.0, 8.2), (19.4, 15.0), (24.6, 10.6), (21.6, 22.6)])
+ body = union(crown, *[circle(x, y, 2.0) for x, y in tips],
+ box(8.0, 20.0, 22.0, 23.4, 0.8),
+ box(7, 23, 23, 26.8, 1.2))
+ details = [seg(9.0, 20.2, 21.0, 20.2), seg(8.6, 23.3, 21.4, 23.3)]
+ return body, details
+
+
+def king():
+ lobes = smooth_union(1.4,
+ circle(10.6, 14.6, 4.6),
+ circle(19.4, 14.6, 4.6),
+ ellipse(15, 13.6, 3.2, 4.2),
+ poly(mirror([(7.2, 15.5), (9.4, 22.6)])))
+ cross = union(box(14, 2.4, 16, 10.2, 0.4), box(11.8, 4.2, 18.2, 6.2, 0.4))
+ body = union(lobes, cross,
+ box(8.4, 20.4, 21.6, 23.4, 0.8),
+ box(7, 23, 23, 26.8, 1.2))
+ details = [seg(15, 10.4, 15, 17.5), seg(9.4, 20.4, 20.6, 20.4), seg(8.6, 23.3, 21.4, 23.3)]
+ return body, details
+
+
+def knight():
+ head = poly([
+ (22.2, 23.2), (22.6, 18.5), (22.2, 13.8), (20.8, 9.8), (18.4, 6.6), (15.8, 5.2),
+ (15.2, 2.8), (13.4, 4.8), (11.8, 3.6), (11.4, 6.4), (8.6, 9.6), (6.2, 13.6),
+ (5.8, 15.6), (7.2, 17.0), (9.4, 16.2), (11.2, 15.2), (13.6, 14.2),
+ (13.4, 16.4), (10.6, 19.6), (9.6, 23.2)])
+ body = smooth_union(0.8, head, box(7, 22.6, 23.2, 26.8, 1.2))
+ details = [seg(8.8, 23.2, 21.6, 23.2), seg(7.4, 14.4, 8.4, 13.8)]
+ eye = circle(12.2, 9.2, 1.0)
+ return body, details, eye
+
+
+def render(shape):
+ body, details = shape[0], shape[1]
+ eye = shape[2] if len(shape) > 2 else None
+ cls = []
+ for py in range(N):
+ row = []
+ for px in range(N):
+ inside = ink = det = 0
+ for sy in range(SS):
+ for sx in range(SS):
+ x = px + (sx + 0.5) / SS
+ y = py + (sy + 0.5) / SS
+ d = body(x, y)
+ if d < 0:
+ inside += 1
+ if d > -OUTLINE:
+ ink += 1
+ elif any(g(x, y) < DETAIL for g in details) or (eye and eye(x, y) < 0):
+ det += 1
+ a = inside / (SS * SS)
+ if a < 0.2:
+ c = 0
+ elif a < 0.5:
+ c = 4
+ elif a < 0.85:
+ c = 3
+ else:
+ fi, fd = ink / inside, det / inside
+ c = 2 if fi > 0.65 else 6 if fi > 0.3 else 5 if fd > 0.55 else 7 if fd > 0.2 else 1
+ row.append(c)
+ cls.append(row)
+ return cls
+
+
+PIECES = [('pawn', pawn), ('knight', knight), ('bishop', bishop),
+ ('rook', rook), ('queen', queen), ('king', king)]
+
+
+def bounds(img):
+ ys = [y for y in range(N) if any(img[y])]
+ xs = [x for x in range(N) if any(img[y][x] for y in range(N))]
+ return min(xs), min(ys), max(xs), max(ys)
+
+
+def symmetric(img):
+ return all(img[y][x] == img[y][N - 1 - x] for y in range(N) for x in range(N))
+
+
+def main():
+ imgs = [(name, render(f())) for name, f in PIECES]
+ out, bits, meta, off = [], [], [], 0
+ for name, img in imgs:
+ x0, y0, x1, y1 = bounds(img)
+ sym = symmetric(img)
+ if sym:
+ x0 = min(x0, N - 1 - x1)
+ w = N // 2 - x0
+ else:
+ w = x1 - x0 + 1
+ h = y1 - y0 + 1
+ px = [img[y][x] for y in range(y0, y1 + 1) for x in range(x0, x0 + w)]
+ bits.extend(px)
+ meta.append((off, x0, y0, w, h, sym))
+ off += len(px)
+ for i in range(0, len(bits), 8):
+ v = 0
+ for j, c in enumerate(bits[i:i + 8]):
+ v |= c << (3 * j)
+ out += [v & 255, (v >> 8) & 255, v >> 16]
+ out.append(0) # padding: the decoder reads two bytes at a time
+ with open('src/sprites.h', 'w') as f:
+ f.write('/* Generated by tools/pieces.py: 3 bits per pixel, 8 pixels per 3 bytes. */\n')
+ f.write('static const struct { uint16_t off; uint8_t x, y, w, h; } SPR[6] = {\n')
+ for off, x0, y0, w, h, sym in meta:
+ f.write(' {%d, %d, %d, %d, %d},\n' % (off, x0, y0, w | (0x80 if sym else 0), h))
+ f.write('};\nstatic const uint8_t SPRD[%d] = {\n' % len(out))
+ for i in range(0, len(out), 20):
+ f.write(' ' + ','.join(str(v) for v in out[i:i + 20]) + ',\n')
+ f.write('};\n')
+ print('sprite bytes:', len(out), file=sys.stderr)
+ if len(sys.argv) > 1:
+ preview(imgs, sys.argv[1])
+
+
+def shade(c, bg, color):
+ ink = (0x3A, 0x3A, 0x3A) if color == 0 else (0x14, 0x13, 0x12)
+ body = (0xF8, 0xF8, 0xF6) if color == 0 else (0x52, 0x4F, 0x4D)
+ det = ink if color == 0 else (0xA8, 0xA5, 0xA2)
+ mix = lambda a, b, t: tuple(round(x * (1 - t) + y * t) for x, y in zip(a, b))
+ return [bg, body, ink, mix(bg, ink, 0.6), mix(bg, ink, 0.3), det, mix(body, ink, 0.5), mix(body, det, 0.5)][c]
+
+
+def preview(imgs, path, Z=4):
+ """Both colors of the set on board squares, zoomed Z times."""
+ light, dark = (0xEB, 0xEC, 0xD0), (0x77, 0x95, 0x56)
+ W, Hh = 6 * N * Z, 2 * N * Z
+ pix = [[None] * W for _ in range(Hh)]
+ for color in range(2):
+ for i, (name, img) in enumerate(imgs):
+ bg = light if (i + color) % 2 == 0 else dark
+ for y in range(N * Z):
+ for x in range(N * Z):
+ pix[color * N * Z + y][i * N * Z + x] = shade(img[y // Z][x // Z], bg, color)
+ raw = b''.join(b'\0' + bytes(v for p in row for v in p) for row in pix)
+
+ def chunk(t, d):
+ return struct.pack('>I', len(d)) + t + d + struct.pack('>I', zlib.crc32(t + d))
+ png = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', W, Hh, 8, 2, 0, 0, 0))
+ png += chunk(b'IDAT', zlib.compress(raw, 9)) + chunk(b'IEND', b'')
+ open(path, 'wb').write(png)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/games/crossyroad/.gitignore b/games/crossyroad/.gitignore
new file mode 100644
index 00000000..81a4c6e9
--- /dev/null
+++ b/games/crossyroad/.gitignore
@@ -0,0 +1,3 @@
+output/
+*.o
+__pycache__/
diff --git a/games/crossyroad/Makefile b/games/crossyroad/Makefile
new file mode 100644
index 00000000..43208330
--- /dev/null
+++ b/games/crossyroad/Makefile
@@ -0,0 +1,70 @@
+# Crossy Road for NumWorks
+# make build output/crossyroad.nwa for the calculator
+# make sim build output/crossyroad.nwb for the native Epsilon simulator
+# make host build a desktop test harness (frame dumps)
+
+NWLINK ?= npx --yes -- [email protected]
+CC_DEVICE = arm-none-eabi-gcc
+BUILD = output
+APP = crossyroad
+
+EADK_INC := $(shell $(NWLINK) eadk-cflags-device 2>/dev/null | sed -e 's/.*"-I\([^"]*\)".*/\1/')
+
+DEVICE_CFLAGS = -std=c11 -mthumb -mfloat-abi=hard -mcpu=cortex-m7 -mfpu=fpv5-sp-d16 -DPLATFORM_DEVICE=1 \
+ -I$(EADK_INC) -Os -Wall -g0 -fno-common \
+ -fno-asynchronous-unwind-tables -fno-unwind-tables -fsingle-precision-constant -fno-math-errno -ffreestanding -fno-tree-loop-distribute-patterns \
+ -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal -fno-reorder-blocks -fno-schedule-insns2 -fno-ipa-sra \
+ -fno-caller-saves -fno-thread-jumps -fno-optimize-sibling-calls
+DEVICE_LDFLAGS = -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main \
+ -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level -Wl,--gc-sections \
+ -flinker-output=nolto-rel -Tsrc/nwa.ld
+
+.PHONY: all sim host clean
+all: $(BUILD)/$(APP).nwa
+
+$(BUILD):
+ mkdir -p $@
+
+# Icon: LZ4 block of RGB565 pixels in .rodata.eadk_app_icon (what nwlink png-icon-o
+# makes, with a much tighter encoder).
+$(BUILD)/icon.o: assets/icon.png tools/png2nwi.py | $(BUILD)
+ mkdir -p $(BUILD)/icon && python3 tools/png2nwi.py $< $(BUILD)/icon/input.dat
+ cd $(BUILD)/icon && arm-none-eabi-objcopy --input-target binary --output-target elf32-littlearm \
+ --rename-section .data=.rodata.eadk_app_icon --redefine-sym _binary_input_dat_start=eadk_app_icon \
+ --strip-symbol _binary_input_dat_end --strip-symbol _binary_input_dat_size input.dat ../icon.o
+
+# Constant tables: compiled once to read their bytes, then embedded compressed.
+$(BUILD)/rom.inc: src/crossy.c tools/pack_rom.py | $(BUILD)
+ $(CC_DEVICE) $(filter-out -flto -fno-fat-lto-objects -fwhole-program,$(DEVICE_CFLAGS)) -c $< -o $(BUILD)/rom.o
+ python3 tools/pack_rom.py $(BUILD)/rom.o $@
+
+$(BUILD)/$(APP).nwa: src/crossy.c src/nwa.ld $(BUILD)/icon.o $(BUILD)/rom.inc | $(BUILD)
+ $(CC_DEVICE) $(DEVICE_CFLAGS) -DROM_PACKED='"rom.inc"' -I$(BUILD) $(DEVICE_LDFLAGS) src/crossy.c $(BUILD)/icon.o -lgcc -o [email protected]
+ python3 tools/nwa_min.py [email protected] $@
+
+sim: $(BUILD)/$(APP).nwb
+$(BUILD)/$(APP).nwb: src/crossy.c | $(BUILD)
+ gcc -std=c11 -O2 -fno-math-errno -fPIC -shared -DPLATFORM_SIM=1 -I$(EADK_INC) src/crossy.c -o $@ -Wl,--unresolved-symbols=ignore-all
+
+host: $(BUILD)/host
+$(BUILD)/host: src/crossy.c host/host.c | $(BUILD)
+ gcc -std=c11 -O2 -g -Wall -fno-math-errno -DPLATFORM_DEVICE=1 -DHOST=1 -Dmain=game_main -I$(EADK_INC) -c src/crossy.c -o $(BUILD)/crossy_host.o
+ gcc -std=c11 -O2 -g -DPLATFORM_DEVICE=1 -I$(EADK_INC) host/host.c $(BUILD)/crossy_host.o -o $@ -lm
+
+clean:
+ rm -rf $(BUILD)
+
+# NumPlay launcher: the game as a module (see ../../tools/npmodule.py) for the
+# calculator, and as a relocatable object for the simulator build.
+.PHONY: module sim-module
+module: $(BUILD)/module.o
+$(BUILD)/module.o: src/crossy.c $(BUILD)/rom.inc | $(BUILD)
+ $(CC_DEVICE) $(DEVICE_CFLAGS) -DROM_PACKED='"rom.inc"' -I$(BUILD) -Wl,--relocatable -nostartfiles -nostdlib \
+ -Wl,-e,main -flinker-output=nolto-rel src/crossy.c -o $@
+
+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 \
+ -c src/crossy.c -o $(BUILD)/sim.o
+ ld -r $(BUILD)/sim.o -exported_symbol _np_crossyroad_main -o $@
diff --git a/games/crossyroad/README.md b/games/crossyroad/README.md
new file mode 100644
index 00000000..a912140a
--- /dev/null
+++ b/games/crossyroad/README.md
@@ -0,0 +1,36 @@
+# CrossyWorks
+
+Crossy Road for the NumWorks calculator.
+
+<p align="center">
+ <img src="screenshots/title.png" width="49%" alt="Title screen">
+ <img src="screenshots/river.png" width="49%" alt="Riding a log">
+ <img src="screenshots/train.png" width="49%" alt="Train crossing">
+ <img src="screenshots/gameover.png" width="49%" alt="Game over">
+</p>
+
+Hop as far as you can. Dodge cars, trucks and trains, ride logs and lily pads across rivers, grab coins, and keep moving or the eagle will get you.
+
+## Install
+
+1. Download `crossyroad.nwa` from the [latest release](https://github.com/Mason363/CrossyWorks/releases/latest).
+2. Plug in your calculator and open [my.numworks.com/apps](https://my.numworks.com/apps).
+3. Add the file and send it to the calculator.
+
+Made for the NumWorks N0120.
+
+## Controls
+
+| Key | Action |
+| --- | --- |
+| Up, OK or EXE | Hop forward |
+| Left, Right, Down | Hop left, right or back |
+| Back | Pause. On the title or game over screen, quit |
+
+Your top score and coins are saved on the calculator.
+
+## Build
+
+You need `arm-none-eabi-gcc`, Python 3 and Node.js. Run `make` to get `output/crossyroad.nwa`.
+
+Crossy Road is a trademark of Hipster Whale. This is an unofficial fan remake.
diff --git a/games/crossyroad/VERSION b/games/crossyroad/VERSION
new file mode 100644
index 00000000..d3827e75
--- /dev/null
+++ b/games/crossyroad/VERSION
@@ -0,0 +1 @@
+1.0
diff --git a/games/crossyroad/assets/icon.png b/games/crossyroad/assets/icon.png
new file mode 100644
index 00000000..d83b45cc
Binary files /dev/null and b/games/crossyroad/assets/icon.png differ
diff --git a/games/crossyroad/host/host.c b/games/crossyroad/host/host.c
new file mode 100644
index 00000000..51247378
--- /dev/null
+++ b/games/crossyroad/host/host.c
@@ -0,0 +1,105 @@
+// Desktop harness: emulates the EADK API, scripted input, frame dumps (PPM).
+#include <eadk.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+int game_main(int argc, char *argv[]);
+
+static uint16_t screen[EADK_SCREEN_WIDTH * EADK_SCREEN_HEIGHT];
+static long frame = 0, max_frames = 1;
+static double now_ms = 0;
+static const char *outdir = ".";
+static char shots[4096] = "";
+static char keys[8192] = "";
+static uint32_t rng = 2463534242u;
+
+void eadk_display_push_rect(eadk_rect_t r, const eadk_color_t *p) {
+ for (int y = 0; y < r.height; y++)
+ for (int x = 0; x < r.width; x++) {
+ int sx = r.x + x, sy = r.y + y;
+ if (sx < EADK_SCREEN_WIDTH && sy < EADK_SCREEN_HEIGHT) screen[sy * EADK_SCREEN_WIDTH + sx] = p[y * r.width + x];
+ }
+}
+void eadk_display_push_rect_uniform(eadk_rect_t r, eadk_color_t c) {
+ for (int y = 0; y < r.height; y++)
+ for (int x = 0; x < r.width; x++) screen[(r.y + y) * EADK_SCREEN_WIDTH + r.x + x] = c;
+}
+void eadk_display_pull_rect(eadk_rect_t r, eadk_color_t *p) { (void)r; (void)p; }
+void eadk_display_draw_string(const char *t, eadk_point_t p, bool l, eadk_color_t a, eadk_color_t b) {
+ (void)t; (void)p; (void)l; (void)a; (void)b;
+}
+
+static int in_list(const char *list, long f) {
+ char buf[32];
+ snprintf(buf, sizeof buf, ",%ld,", f);
+ char tmp[4200];
+ snprintf(tmp, sizeof tmp, ",%s,", list);
+ return strstr(tmp, buf) != NULL;
+}
+
+static void dump(long f) {
+ char path[512];
+ snprintf(path, sizeof path, "%s/f%05ld.ppm", outdir, f);
+ FILE *fp = fopen(path, "wb");
+ fprintf(fp, "P6\n%d %d\n255\n", EADK_SCREEN_WIDTH, EADK_SCREEN_HEIGHT);
+ for (int i = 0; i < EADK_SCREEN_WIDTH * EADK_SCREEN_HEIGHT; i++) {
+ uint16_t c = screen[i];
+ unsigned char rgb[3] = {(unsigned char)(((c >> 11) & 31) * 255 / 31), (unsigned char)(((c >> 5) & 63) * 255 / 63),
+ (unsigned char)((c & 31) * 255 / 31)};
+ fwrite(rgb, 1, 3, fp);
+ }
+ fclose(fp);
+}
+
+bool eadk_display_wait_for_vblank(void) {
+ // the previous frame is complete at this point
+ if (frame > 0 && (in_list(shots, frame) || strcmp(shots, "all") == 0)) dump(frame);
+ frame++;
+ now_ms += 1000.0 / 60.0;
+ if (frame > max_frames) exit(0);
+ return true;
+}
+
+// keys: "f0-f1:key,..." where key is one of U D L R O B E
+eadk_keyboard_state_t eadk_keyboard_scan(void) {
+ eadk_keyboard_state_t s = 0;
+ const char *p = keys;
+ while (*p) {
+ long a = strtol(p, (char **)&p, 10), b = a;
+ if (*p == '-') b = strtol(p + 1, (char **)&p, 10);
+ if (*p == ':') p++;
+ char k = *p ? *p++ : 0;
+ if (*p == ',') p++;
+ if (frame >= a && frame <= b) {
+ int key = k == 'U' ? eadk_key_up : k == 'D' ? eadk_key_down : k == 'L' ? eadk_key_left : k == 'R' ? eadk_key_right
+ : k == 'O' ? eadk_key_ok : k == 'B' ? eadk_key_back : k == 'E' ? eadk_key_exe : -1;
+ if (key >= 0) s |= (eadk_keyboard_state_t)1 << key;
+ }
+ }
+ return s;
+}
+
+uint64_t eadk_timing_millis(void) { return (uint64_t)now_ms; }
+void eadk_timing_msleep(uint32_t ms) { now_ms += ms; }
+void eadk_timing_usleep(uint32_t us) { now_ms += us / 1000.0; }
+uint32_t eadk_random(void) {
+ rng ^= rng << 13; rng ^= rng >> 17; rng ^= rng << 5;
+ return rng;
+}
+bool eadk_usb_is_plugged(void) { return false; }
+uint8_t eadk_battery_level(void) { return 100; }
+const char *eadk_external_data = NULL;
+size_t eadk_external_data_size = 0;
+
+int main(int argc, char *argv[]) {
+ for (int i = 1; i < argc; i++) {
+ if (!strcmp(argv[i], "--frames") && i + 1 < argc) max_frames = atol(argv[++i]);
+ else if (!strcmp(argv[i], "--shots") && i + 1 < argc) snprintf(shots, sizeof shots, "%s", argv[++i]);
+ else if (!strcmp(argv[i], "--keys") && i + 1 < argc) snprintf(keys, sizeof keys, "%s", argv[++i]);
+ else if (!strcmp(argv[i], "--out") && i + 1 < argc) outdir = argv[++i];
+ else if (!strcmp(argv[i], "--seed") && i + 1 < argc) rng = (uint32_t)atol(argv[++i]);
+ }
+ char *args[] = {"crossy", NULL};
+ return game_main(1, args);
+}
diff --git a/games/crossyroad/screenshots/gameover.png b/games/crossyroad/screenshots/gameover.png
new file mode 100644
index 00000000..563666cf
Binary files /dev/null and b/games/crossyroad/screenshots/gameover.png differ
diff --git a/games/crossyroad/screenshots/river.png b/games/crossyroad/screenshots/river.png
new file mode 100644
index 00000000..6f570d38
Binary files /dev/null and b/games/crossyroad/screenshots/river.png differ
diff --git a/games/crossyroad/screenshots/title.png b/games/crossyroad/screenshots/title.png
new file mode 100644
index 00000000..b789a979
Binary files /dev/null and b/games/crossyroad/screenshots/title.png differ
diff --git a/games/crossyroad/screenshots/train.png b/games/crossyroad/screenshots/train.png
new file mode 100644
index 00000000..d32dbcd9
Binary files /dev/null and b/games/crossyroad/screenshots/train.png differ
diff --git a/games/crossyroad/src/crossy.c b/games/crossyroad/src/crossy.c
new file mode 100644
index 00000000..3caa9212
--- /dev/null
+++ b/games/crossyroad/src/crossy.c
@@ -0,0 +1,2004 @@
+// Crossy Road for NumWorks
+// A faithful remake of Hipster Whale's Crossy Road for the NumWorks calculator.
+#include <eadk.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#if PLATFORM_DEVICE && !defined(HOST)
+// Freestanding build: the tiny libc subset the compiler may call.
+__attribute__((used, externally_visible)) void *memset(void *d, int c, size_t n) {
+ uint8_t *p = d;
+ if (n >= 8) {
+ uint32_t w = (uint8_t)c * 0x01010101u;
+ while ((uintptr_t)p & 3) { *p++ = (uint8_t)c; n--; }
+ for (; n >= 4; n -= 4, p += 4) *(uint32_t *)p = w;
+ }
+ while (n--) *p++ = (uint8_t)c;
+ return d;
+}
+__attribute__((used, externally_visible)) void *memcpy(void *d, const void *s, size_t n) {
+ uint8_t *p = d;
+ const uint8_t *q = s;
+ while (n--) *p++ = *q++;
+ return d;
+}
+#else
+#include <string.h>
+#endif
+
+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;
+
+#define SW 320
+#define SH 240
+
+// Helpers used from many places are kept out of line: smaller code.
+#define NOINLINE __attribute__((noinline))
+
+// ---------------------------------------------------------------------------
+// Palette indices (the colors are in the constant data below).
+
+#define RGB(r, g, b) ((((r) & 0xF8) << 8) | (((g) & 0xFC) << 3) | ((b) >> 3))
+
+enum {
+ C_GRASS, C_GRASS2, C_GRASS_O, C_GRASS2_O, C_GRASS_SH, C_GRASS_OSH,
+ C_ROAD, C_ROAD_O, C_ROAD_SH, C_ROAD_OSH, C_ROAD_SIDE, C_DASH, C_DASH_O,
+ C_WATER, C_WATER_O, C_WATER_SH, C_WATER_OSH, C_FOAM,
+ C_RAIL, C_RAIL_S, C_TIE, C_TIE_S, C_RAIL_SH, C_TIE_SH,
+ C_WHITE, C_GRAY, C_COMB, C_COMB_S, C_BEAK, C_BEAK_S, C_EYE,
+ C_LEAF, C_LEAF_A, C_LEAF_B, C_TRUNK, C_TRUNK_E,
+ C_ROCK, C_ROCK_S,
+ C_LOG, C_LOG_BARK, C_LOG_S, C_LOG_END, C_LOG_SH,
+ C_LILY, C_LILY_S,
+ C_BLACK, C_CABIN_S, C_UNDER, C_HUB,
+ C_BLUE_T, C_BLUE_S, C_BLUE_S2,
+ C_GREEN_T, C_GREEN_S, C_GREEN_S2,
+ C_YELLOW_T, C_YELLOW_S, C_YELLOW_S2,
+ C_ORANGE_T, C_ORANGE_S, C_ORANGE_S2,
+ C_PURPLE_T, C_PURPLE_S, C_PURPLE_S2,
+ C_RED_T, C_RED_S, C_TBLUE_T, C_TBLUE_S, C_TGREEN_T, C_TGREEN_S,
+ C_BOX_T, C_BOX_S, C_BOX_S2,
+ C_TRAIN_T, C_TRAIN_S, C_TRAIN_S2, C_TRAIN_W, C_TRAIN_WS, C_TRAIN_Y, C_TRAIN_YS,
+ C_POLE_R, C_POLE_RS, C_POLE_W, C_POLE_WS, C_LAMP_OFF, C_LAMP_ON, C_SIGNAL, C_SIGNAL_S,
+ C_COIN, C_COIN_S, C_COIN_C,
+ C_EAGLE, C_EAGLE_S, C_EAGLE_H, C_EAGLE_HS, C_EAGLE_B, C_EAGLE_BS,
+ C_BTN, C_BTN_S, C_GOLD, C_OUTLINE,
+ NCOLORS
+};
+
+// ---------------------------------------------------------------------------
+// Materials: colors of the top, south and east faces of a box.
+
+typedef struct { uint8_t t, s, e; } Mat; // top, south, east colors
+
+enum {
+ M_WHITE, M_COMB, M_BEAK, M_EYE, M_TRUNK, M_ROCK, M_LOG, M_LOG_BARK, M_LILY,
+ M_BLACK, M_CABIN, M_UNDER, M_HUB,
+ M_BLUE, M_BLUE2, M_GREEN, M_GREEN2, M_YELLOW, M_YELLOW2, M_ORANGE, M_ORANGE2, M_PURPLE, M_PURPLE2,
+ M_RED, M_TBLUE, M_TGREEN, M_BOX, M_BOX2,
+ M_TRAIN, M_TRAIN2, M_TRAIN_W, M_TRAIN_Y,
+ M_POLE_R, M_POLE_W, M_SIGNAL, M_LAMP_OFF, M_LAMP_ON,
+ M_EAGLE, M_EAGLE_H, M_EAGLE_B,
+ NMATS
+};
+
+// ---------------------------------------------------------------------------
+// Game state. Everything lives in one block so code reaches it from a single
+// base address (member order tuned for code size: hot fields get short offsets).
+
+typedef struct { int8_t x, y, z; uint8_t w, h, d, m; } Box; // 1/40 tile units
+
+typedef struct { uint16_t off; uint8_t n; uint8_t reach; } Mdl; // sorted box list
+enum {
+ MD_CHICKEN, // 4 facings
+ MD_CAR = MD_CHICKEN + 4, // 5 colors x 2 directions
+ MD_TRUCK = MD_CAR + 10, // 3 colors x 2 directions
+ MD_ENGINE = MD_TRUCK + 6, // 2 directions
+ MD_WAGON = MD_ENGINE + 2,
+ MD_LOG = MD_WAGON + 1, // 2..4 tiles
+ MD_LILY = MD_LOG + 3,
+ MD_ROCK,
+ MD_SIGNAL, // lamps off, left on, right on
+ MD_EAGLE = MD_SIGNAL + 3,
+ NMODELS
+};
+
+#define PLAY_MIN (-4)
+#define PLAY_MAX 4
+#define NCOLS 27 // columns -13..13 (the rest of each lane is shaded scenery)
+#define COL0 13
+#define NLANES 40
+#define MAXOBJ 8
+#define NO_COIN (-128)
+#define NPARTS 40
+#define STRIP 12
+
+typedef struct {
+ float x; // center
+ uint8_t kind; // vehicle type (road) or length in tiles (river)
+ int8_t coin; // slot holding a coin (logs), -1 if none
+} Obj;
+
+typedef struct {
+ int row;
+ uint8_t type, nobj, alt, train;
+ int8_t dir, coin, bob;
+ float speed, period, timer, trainx, bobt;
+ uint8_t cells[NCOLS];
+ Obj obj[MAXOBJ];
+} Lane;
+
+typedef struct { float x, y, z, vx, vy, vz, life; uint8_t c, sz; } Part;
+
+enum { L_GRASS, L_ROAD, L_RIVER, L_LILY, L_RAIL };
+
+// Constant tables (see "Constant data" below); a copy lives in the state block.
+struct Rom {
+ uint16_t pal[NCOLORS]; // RGB565 of each color
+ uint8_t shade_pairs[16][2]; // color, its shadowed version
+ Mat mats[NMATS];
+ Box shapes[101];
+ uint8_t shape_at[13];
+ uint8_t model_def[NMODELS][4];
+ uint8_t obstacle_pct[12];
+ uint8_t kinds[4];
+ int8_t dx[4], dz[4];
+ char font_chars[23];
+ uint8_t font_w[22];
+ uint16_t font[22][10];
+ uint16_t hand_ol[14], hand_in[14];
+ char save_name[15];
+ uint32_t slots[2];
+ char s_crossy[7], s_road[5], s_new_top[8];
+};
+
+struct State {
+ uint16_t reach_prev; // bits 0..8: playable columns reachable in the previous lane
+ float ox, oy; // screen position of the world origin (whole pixels)
+ float lxa, lxb; // visible x range of the lane being drawn
+ float cam_x, cam_z, shake;
+ float st_time, game_time, fade, restart_t;
+ float eagle_x, eagle_y, eagle_z;
+ int state, paused, show_logo, new_top, restarting, eagle_on;
+ int score, top_score, coins;
+ int gen_next, set_left, set_type, prev_dir, start_end;
+ uint32_t rng_s;
+ uint8_t *fs_buf;
+ uint32_t fs_size;
+ struct {
+ float x, y, z, base; // position; base = standing height of the surface
+ int face, row, best;
+ int hop;
+ float t, fx, fz, fbase, tx, tz;
+ int q[3], nq;
+ float sx, sy, sz; // squash / death scale
+ float logoff;
+ int dead, visible;
+ int log; // index of the log ridden in the current row, or -1
+ float dt, idle;
+ int crow, cobj; // vehicle carrying the splatted chicken
+ float cdx;
+ } P;
+ uint16_t fpal[NCOLORS];
+ uint8_t shade[NCOLORS];
+ Mdl models[NMODELS];
+ Part parts[NPARTS];
+ struct Rom rom;
+ Lane lanes[NLANES];
+ Box boxpool[420];
+ uint16_t strip[SW * STRIP] __attribute__((aligned(4)));
+ uint8_t fb[SW * SH] __attribute__((aligned(4)));
+};
+
+#if PLATFORM_DEVICE && !defined(HOST)
+// On the calculator a reserved register holds its address.
+static struct State state_mem;
+register struct State *g9 __asm__("r9");
+#define G (*g9)
+#else
+static struct State G;
+#endif
+
+#define ox G.ox
+#define oy G.oy
+#define lxa G.lxa
+#define lxb G.lxb
+#define cam_x G.cam_x
+#define cam_z G.cam_z
+#define shake G.shake
+#define st_time G.st_time
+#define game_time G.game_time
+#define fade G.fade
+#define restart_t G.restart_t
+#define eagle_x G.eagle_x
+#define eagle_y G.eagle_y
+#define eagle_z G.eagle_z
+#define state G.state
+#define paused G.paused
+#define show_logo G.show_logo
+#define new_top G.new_top
+#define restarting G.restarting
+#define eagle_on G.eagle_on
+#define score G.score
+#define top_score G.top_score
+#define coins G.coins
+#define gen_next G.gen_next
+#define set_left G.set_left
+#define set_type G.set_type
+#define prev_dir G.prev_dir
+#define start_end G.start_end
+#define reach_prev G.reach_prev
+#define rng_s G.rng_s
+#define fs_buf G.fs_buf
+#define fs_size G.fs_size
+#define P G.P
+#define shade G.shade
+#define fpal G.fpal
+#define models G.models
+#define parts G.parts
+#define boxpool G.boxpool
+#define lanes G.lanes
+#define strip G.strip
+#define fb G.fb
+
+// ---------------------------------------------------------------------------
+// Constant data
+
+enum { M_V0 = NMATS, M_V1, M_V2 };
+#define NONE 0xFF
+enum { S_CHICKEN, S_CAR, S_TRUCK, S_ENGINE, S_WAGON, S_LOG, S_LILY = S_LOG + 3, S_ROCK, S_SIGNAL, S_EAGLE };
+
+// Per model: shape | quarter turns clockwise << 4 (4: mirrored east-west), variants.
+#define CAR(t, s, sign) {S_CAR, t, s, sign}, {S_CAR | 4 << 4, t, s, sign}
+#define TRUCK(c) {S_TRUCK, c}, {S_TRUCK | 4 << 4, c}
+// Font glyph: 10 rows of 10 pixels, stored in the top bits of 12.
+#define GLYPH(a, b, c, d, e, f, g, h, i, j) {a << 2, b << 2, c << 2, d << 2, e << 2, f << 2, g << 2, h << 2, i << 2, j << 2}
+
+#ifdef ROM_PACKED
+// The calculator build stores the tables below compressed (tools/pack_rom.py).
+static const uint8_t rom_packed[] = {
+#include ROM_PACKED
+};
+#else
+static const struct Rom rom_init = {
+ // Palette. Colors sampled from the original game (lit top faces, ambient-only
+ // side faces, and shadowed ground).
+ .pal = {
+ [C_GRASS] = RGB(217, 252, 130), [C_GRASS2] = RGB(208, 244, 120),
+ [C_GRASS_O] = RGB(192, 235, 110), [C_GRASS2_O] = RGB(184, 227, 102),
+ [C_GRASS_SH] = RGB(96, 116, 54), [C_GRASS_OSH] = RGB(84, 102, 43),
+ [C_ROAD] = RGB(97, 104, 108), [C_ROAD_O] = RGB(89, 96, 100),
+ [C_ROAD_SH] = RGB(40, 42, 42), [C_ROAD_OSH] = RGB(36, 38, 38),
+ [C_ROAD_SIDE] = RGB(61, 64, 64), [C_DASH] = RGB(141, 151, 155), [C_DASH_O] = RGB(129, 141, 144),
+ [C_WATER] = RGB(170, 252, 254), [C_WATER_O] = RGB(144, 236, 252),
+ [C_WATER_SH] = RGB(75, 116, 131), [C_WATER_OSH] = RGB(64, 104, 122), [C_FOAM] = RGB(255, 255, 255),
+ [C_RAIL] = RGB(170, 167, 183), [C_RAIL_S] = RGB(74, 71, 76),
+ [C_TIE] = RGB(127, 85, 79), [C_TIE_S] = RGB(54, 33, 29),
+ [C_RAIL_SH] = RGB(74, 71, 76), [C_TIE_SH] = RGB(54, 33, 29),
+ [C_WHITE] = RGB(255, 255, 255), [C_GRAY] = RGB(144, 144, 144),
+ [C_COMB] = RGB(239, 130, 131), [C_COMB_S] = RGB(117, 55, 53),
+ [C_BEAK] = RGB(240, 146, 107), [C_BEAK_S] = RGB(120, 63, 43), [C_EYE] = RGB(31, 17, 13),
+ [C_LEAF] = RGB(208, 234, 90), [C_LEAF_A] = RGB(100, 112, 39), [C_LEAF_B] = RGB(91, 101, 33),
+ [C_TRUNK] = RGB(64, 41, 35), [C_TRUNK_E] = RGB(58, 32, 27),
+ [C_ROCK] = RGB(252, 239, 254), [C_ROCK_S] = RGB(111, 103, 108),
+ [C_LOG] = RGB(150, 102, 92), [C_LOG_BARK] = RGB(135, 85, 76), [C_LOG_S] = RGB(64, 41, 35),
+ [C_LOG_END] = RGB(96, 62, 55), [C_LOG_SH] = RGB(66, 45, 40),
+ [C_LILY] = RGB(115, 229, 135), [C_LILY_S] = RGB(46, 99, 55),
+ [C_BLACK] = RGB(0, 0, 0), [C_CABIN_S] = RGB(135, 142, 144), [C_UNDER] = RGB(71, 66, 80),
+ [C_HUB] = RGB(160, 166, 170),
+ [C_BLUE_T] = RGB(120, 248, 253), [C_BLUE_S] = RGB(48, 107, 116), [C_BLUE_S2] = RGB(31, 78, 95),
+ [C_GREEN_T] = RGB(196, 244, 124), [C_GREEN_S] = RGB(95, 114, 56), [C_GREEN_S2] = RGB(77, 102, 48),
+ [C_YELLOW_T] = RGB(255, 254, 129), [C_YELLOW_S] = RGB(138, 123, 56), [C_YELLOW_S2] = RGB(118, 104, 48),
+ [C_ORANGE_T] = RGB(255, 140, 84), [C_ORANGE_S] = RGB(140, 54, 34), [C_ORANGE_S2] = RGB(114, 42, 28),
+ [C_PURPLE_T] = RGB(182, 160, 255), [C_PURPLE_S] = RGB(82, 64, 142), [C_PURPLE_S2] = RGB(66, 50, 118),
+ [C_RED_T] = RGB(250, 92, 100), [C_RED_S] = RGB(120, 30, 38),
+ [C_TBLUE_T] = RGB(64, 184, 248), [C_TBLUE_S] = RGB(8, 82, 124),
+ [C_TGREEN_T] = RGB(110, 214, 198), [C_TGREEN_S] = RGB(36, 98, 90),
+ [C_BOX_T] = RGB(236, 236, 240), [C_BOX_S] = RGB(128, 130, 138), [C_BOX_S2] = RGB(112, 114, 122),
+ [C_TRAIN_T] = RGB(96, 200, 252), [C_TRAIN_S] = RGB(22, 116, 176), [C_TRAIN_S2] = RGB(14, 88, 142),
+ [C_TRAIN_W] = RGB(200, 236, 236), [C_TRAIN_WS] = RGB(88, 118, 124),
+ [C_TRAIN_Y] = RGB(252, 252, 131), [C_TRAIN_YS] = RGB(128, 124, 52),
+ [C_POLE_R] = RGB(196, 60, 72), [C_POLE_RS] = RGB(89, 33, 31),
+ [C_POLE_W] = RGB(238, 238, 238), [C_POLE_WS] = RGB(144, 144, 144),
+ [C_LAMP_OFF] = RGB(62, 19, 24), [C_LAMP_ON] = RGB(255, 36, 36),
+ [C_SIGNAL] = RGB(36, 36, 40), [C_SIGNAL_S] = RGB(14, 14, 16),
+ [C_COIN] = RGB(255, 238, 70), [C_COIN_S] = RGB(176, 132, 16), [C_COIN_C] = RGB(255, 36, 16),
+ [C_EAGLE] = RGB(136, 72, 64), [C_EAGLE_S] = RGB(74, 36, 34),
+ [C_EAGLE_H] = RGB(250, 250, 250), [C_EAGLE_HS] = RGB(150, 150, 150),
+ [C_EAGLE_B] = RGB(255, 170, 60), [C_EAGLE_BS] = RGB(140, 80, 24),
+ [C_BTN] = RGB(86, 196, 248), [C_BTN_S] = RGB(36, 150, 220), [C_GOLD] = RGB(248, 232, 77),
+ [C_OUTLINE] = RGB(0, 0, 0),
+ },
+ .shade_pairs = {
+ {C_GRASS, C_GRASS_SH}, {C_GRASS2, C_GRASS_SH}, {C_GRASS_O, C_GRASS_OSH}, {C_GRASS2_O, C_GRASS_OSH},
+ {C_ROAD, C_ROAD_SH}, {C_ROAD_O, C_ROAD_OSH}, {C_DASH, C_ROAD_SH}, {C_DASH_O, C_ROAD_OSH},
+ {C_WATER, C_WATER_SH}, {C_WATER_O, C_WATER_OSH}, {C_FOAM, C_WATER_SH},
+ {C_RAIL, C_RAIL_SH}, {C_TIE, C_TIE_SH}, {C_LOG, C_LOG_SH}, {C_LOG_BARK, C_LOG_SH}, {C_LILY, C_LILY_S},
+ },
+ .mats = {
+ [M_WHITE] = {C_WHITE, C_GRAY, C_GRAY}, [M_COMB] = {C_COMB, C_COMB_S, C_COMB_S},
+ [M_BEAK] = {C_BEAK, C_BEAK_S, C_BEAK_S}, [M_EYE] = {C_EYE, C_EYE, C_EYE},
+ [M_TRUNK] = {C_TRUNK, C_TRUNK, C_TRUNK_E}, [M_ROCK] = {C_ROCK, C_ROCK_S, C_ROCK_S},
+ [M_LOG] = {C_LOG, C_LOG_S, C_LOG_END}, [M_LOG_BARK] = {C_LOG_BARK, C_LOG_S, C_LOG_END},
+ [M_LILY] = {C_LILY, C_LILY_S, C_LILY_S},
+ [M_BLACK] = {C_BLACK, C_BLACK, C_BLACK}, [M_CABIN] = {C_WHITE, C_CABIN_S, C_CABIN_S},
+ [M_UNDER] = {C_UNDER, C_UNDER, C_UNDER}, [M_HUB] = {C_HUB, C_HUB, C_HUB},
+ [M_BLUE] = {C_BLUE_T, C_BLUE_S, C_BLUE_S}, [M_BLUE2] = {C_BLUE_T, C_BLUE_S2, C_BLUE_S2},
+ [M_GREEN] = {C_GREEN_T, C_GREEN_S, C_GREEN_S}, [M_GREEN2] = {C_GREEN_T, C_GREEN_S2, C_GREEN_S2},
+ [M_YELLOW] = {C_YELLOW_T, C_YELLOW_S, C_YELLOW_S}, [M_YELLOW2] = {C_YELLOW_T, C_YELLOW_S2, C_YELLOW_S2},
+ [M_ORANGE] = {C_ORANGE_T, C_ORANGE_S, C_ORANGE_S}, [M_ORANGE2] = {C_ORANGE_T, C_ORANGE_S2, C_ORANGE_S2},
+ [M_PURPLE] = {C_PURPLE_T, C_PURPLE_S, C_PURPLE_S}, [M_PURPLE2] = {C_PURPLE_T, C_PURPLE_S2, C_PURPLE_S2},
+ [M_RED] = {C_RED_T, C_RED_S, C_RED_S}, [M_TBLUE] = {C_TBLUE_T, C_TBLUE_S, C_TBLUE_S},
+ [M_TGREEN] = {C_TGREEN_T, C_TGREEN_S, C_TGREEN_S},
+ [M_BOX] = {C_BOX_T, C_BOX_S, C_BOX_S}, [M_BOX2] = {C_BOX_T, C_BOX_S2, C_BOX_S2},
+ [M_TRAIN] = {C_TRAIN_T, C_TRAIN_S, C_TRAIN_S}, [M_TRAIN2] = {C_TRAIN_T, C_TRAIN_S2, C_TRAIN_S2},
+ [M_TRAIN_W] = {C_TRAIN_W, C_TRAIN_WS, C_TRAIN_WS}, [M_TRAIN_Y] = {C_TRAIN_Y, C_TRAIN_YS, C_TRAIN_YS},
+ [M_POLE_R] = {C_POLE_R, C_POLE_RS, C_POLE_RS}, [M_POLE_W] = {C_POLE_W, C_POLE_WS, C_POLE_WS},
+ [M_SIGNAL] = {C_SIGNAL, C_SIGNAL_S, C_SIGNAL_S},
+ [M_LAMP_OFF] = {C_LAMP_OFF, C_LAMP_OFF, C_LAMP_OFF}, [M_LAMP_ON] = {C_LAMP_ON, C_LAMP_ON, C_LAMP_ON},
+ [M_EAGLE] = {C_EAGLE, C_EAGLE_S, C_EAGLE_S}, [M_EAGLE_H] = {C_EAGLE_H, C_EAGLE_HS, C_EAGLE_HS},
+ [M_EAGLE_B] = {C_EAGLE_B, C_EAGLE_BS, C_EAGLE_BS},
+ },
+ // Model shapes, facing north (creatures) or east (vehicles). Materials M_V0..M_V2
+ // are filled in per model (colors, lamps); a variant of NONE drops the box.
+ .shapes = {
+ // chicken
+ {-6, 0, -2, 3, 6, 3, M_BEAK}, {3, 0, -2, 3, 6, 3, M_BEAK}, // legs
+ {-6, 0, 1, 3, 1, 2, M_BEAK}, {3, 0, 1, 3, 1, 2, M_BEAK}, // toes
+ {-6, 6, -9, 12, 12, 16, M_WHITE}, // body
+ {-9, 9, -6, 3, 6, 9, M_WHITE}, {6, 9, -6, 3, 6, 9, M_WHITE}, // wings
+ {-4, 14, -12, 8, 6, 3, M_WHITE}, // tail
+ {-6, 18, -3, 12, 14, 10, M_WHITE}, // head
+ {-2, 32, -1, 5, 4, 7, M_COMB}, // comb
+ {-2, 24, 7, 4, 3, 3, M_BEAK}, // beak
+ {-2, 21, 7, 4, 3, 1, M_COMB}, // wattle
+ {-7, 26, 2, 1, 2, 2, M_EYE}, {6, 26, 2, 1, 2, 2, M_EYE}, // eyes
+ // car: wheels, chassis, two-tone body, cabin with windows, taxi sign
+ {-21, 0, -18, 12, 10, 4, M_BLACK}, {-21, 0, 14, 12, 10, 4, M_BLACK}, {-17, 3, -19, 4, 4, 1, M_HUB},
+ {9, 0, -18, 12, 10, 4, M_BLACK}, {9, 0, 14, 12, 10, 4, M_BLACK}, {13, 3, -19, 4, 4, 1, M_HUB},
+ {-25, 3, -15, 50, 5, 30, M_UNDER},
+ {-27, 8, -17, 54, 7, 34, M_V1}, {-27, 15, -17, 54, 7, 34, M_V0},
+ {-14, 22, -14, 26, 2, 28, M_CABIN}, {-14, 24, -14, 12, 7, 28, M_BLACK}, {-2, 24, -14, 3, 7, 28, M_CABIN},
+ {1, 24, -14, 11, 7, 28, M_BLACK}, {-14, 31, -14, 26, 5, 28, M_CABIN},
+ {-5, 36, -4, 8, 4, 8, M_V2},
+ // truck: wheels, chassis, box, cab
+ {-46, 0, -19, 13, 11, 4, M_BLACK}, {-46, 0, 15, 13, 11, 4, M_BLACK}, {-42, 4, -20, 5, 4, 1, M_HUB},
+ {-30, 0, -19, 13, 11, 4, M_BLACK}, {-30, 0, 15, 13, 11, 4, M_BLACK}, {-26, 4, -20, 5, 4, 1, M_HUB},
+ {30, 0, -19, 13, 11, 4, M_BLACK}, {30, 0, 15, 13, 11, 4, M_BLACK}, {34, 4, -20, 5, 4, 1, M_HUB},
+ {-54, 4, -16, 108, 6, 32, M_UNDER},
+ {-56, 10, -18, 80, 30, 36, M_BOX2}, {-56, 40, -18, 80, 12, 36, M_BOX},
+ {26, 10, -18, 30, 14, 36, M_V0}, {28, 24, -16, 24, 9, 32, M_BLACK}, {28, 33, -16, 24, 5, 32, M_V0},
+ // train engine (4 tiles)
+ {-66, 0, -15, 26, 8, 30, M_BLACK}, {40, 0, -15, 26, 8, 30, M_BLACK},
+ {-80, 8, -18, 154, 14, 36, M_TRAIN2}, {-80, 22, -18, 154, 12, 36, M_TRAIN_W}, {-80, 34, -18, 154, 16, 36, M_TRAIN},
+ {74, 8, -18, 6, 42, 36, M_TRAIN_Y}, {60, 24, -19, 12, 8, 1, M_BLACK},
+ // train wagon
+ {-66, 0, -15, 26, 8, 30, M_BLACK}, {40, 0, -15, 26, 8, 30, M_BLACK},
+ {-79, 8, -18, 158, 14, 36, M_TRAIN2}, {-79, 22, -18, 158, 12, 36, M_TRAIN_W}, {-79, 34, -18, 158, 16, 36, M_TRAIN},
+ // logs of 2, 3 and 4 tiles with bark patches
+ {-38, 0, -13, 76, 9, 26, M_LOG},
+ {-34, 9, -9, 10, 1, 5, M_LOG_BARK}, {-18, 9, 3, 12, 1, 6, M_LOG_BARK},
+ {6, 9, -9, 10, 1, 5, M_LOG_BARK}, {22, 9, 3, 12, 1, 6, M_LOG_BARK},
+ {-58, 0, -13, 116, 9, 26, M_LOG},
+ {-54, 9, -9, 10, 1, 5, M_LOG_BARK}, {-38, 9, 3, 12, 1, 6, M_LOG_BARK},
+ {-14, 9, -9, 10, 1, 5, M_LOG_BARK}, {2, 9, 3, 12, 1, 6, M_LOG_BARK},
+ {26, 9, -9, 10, 1, 5, M_LOG_BARK}, {42, 9, 3, 12, 1, 6, M_LOG_BARK},
+ {-78, 0, -13, 156, 9, 26, M_LOG},
+ {-74, 9, -9, 10, 1, 5, M_LOG_BARK}, {-58, 9, 3, 12, 1, 6, M_LOG_BARK},
+ {-34, 9, -9, 10, 1, 5, M_LOG_BARK}, {-18, 9, 3, 12, 1, 6, M_LOG_BARK},
+ {6, 9, -9, 10, 1, 5, M_LOG_BARK}, {22, 9, 3, 12, 1, 6, M_LOG_BARK},
+ {46, 9, -9, 10, 1, 5, M_LOG_BARK}, {62, 9, 3, 12, 1, 6, M_LOG_BARK},
+ // lily pad
+ {-11, 0, -11, 22, 2, 22, M_LILY}, {-14, 0, -6, 3, 2, 12, M_LILY}, {11, 0, -7, 3, 2, 10, M_LILY},
+ // rock
+ {-15, 0, -13, 30, 14, 26, M_ROCK}, {-15, 14, -5, 22, 8, 18, M_ROCK},
+ // railroad signal: striped pole, black head with two lamps
+ {-2, 0, -2, 5, 4, 5, M_POLE_W}, {-2, 4, -2, 5, 10, 5, M_POLE_R}, {-2, 14, -2, 5, 4, 5, M_POLE_W},
+ {-2, 18, -2, 5, 10, 5, M_POLE_R}, {-2, 28, -2, 5, 4, 5, M_POLE_W}, {-2, 32, -2, 5, 12, 5, M_POLE_R},
+ {-13, 44, -3, 26, 6, 6, M_SIGNAL}, {-13, 36, -3, 8, 8, 6, M_SIGNAL}, {5, 36, -3, 8, 8, 6, M_SIGNAL},
+ {-12, 37, -4, 6, 6, 1, M_V0}, {6, 37, -4, 6, 6, 1, M_V1},
+ // eagle, flying south toward the camera, wings spread
+ {-30, 10, -6, 22, 3, 14, M_EAGLE}, {8, 10, -6, 22, 3, 14, M_EAGLE}, {-8, 4, -12, 16, 12, 22, M_EAGLE},
+ {-6, 7, 10, 12, 4, 9, M_EAGLE_H}, {-6, 10, -21, 12, 10, 9, M_EAGLE_H}, {-2, 12, -25, 4, 4, 4, M_EAGLE_B},
+ {-6, 0, -8, 3, 4, 3, M_EAGLE_B}, {3, 0, -8, 3, 4, 3, M_EAGLE_B},
+ },
+ .shape_at = {0, 14, 29, 44, 51, 56, 61, 68, 77, 80, 82, 93, 101},
+ .model_def = {
+ {S_CHICKEN}, {S_CHICKEN | 1 << 4}, {S_CHICKEN | 2 << 4}, {S_CHICKEN | 3 << 4},
+ CAR(M_BLUE, M_BLUE2, NONE), CAR(M_GREEN, M_GREEN2, NONE), CAR(M_YELLOW, M_YELLOW2, M_YELLOW),
+ CAR(M_ORANGE, M_ORANGE2, NONE), CAR(M_PURPLE, M_PURPLE2, NONE),
+ TRUCK(M_RED), TRUCK(M_TBLUE), TRUCK(M_TGREEN),
+ {S_ENGINE}, {S_ENGINE | 4 << 4}, {S_WAGON},
+ {S_LOG}, {S_LOG + 1}, {S_LOG + 2}, {S_LILY}, {S_ROCK},
+ {S_SIGNAL, M_LAMP_OFF, M_LAMP_OFF}, {S_SIGNAL, M_LAMP_ON, M_LAMP_OFF}, {S_SIGNAL, M_LAMP_OFF, M_LAMP_ON},
+ {S_EAGLE},
+ },
+ .obstacle_pct = {10, 10, 20, 20, 25, 25, 30, 30, 35, 40, 45, 50}, // tree density by distance (25 rows each)
+ .kinds = {L_GRASS, L_ROAD, L_RIVER, L_RAIL},
+ .dx = {0, 1, 0, -1},
+ .dz = {1, 0, -1, 0},
+ // Font: the original's blocky digits (decoded from the game) and matching
+ // capitals. 10 rows; bit 11 is the leftmost column.
+ .font_chars = "0123456789ACDENOPRSTWY",
+ .font_w = {10, 5, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 12, 10},
+ .font = {
+ GLYPH(0x1FE, 0x3FF, 0x3CF, 0x3CF, 0x3CF, 0x3CF, 0x3CF, 0x3CF, 0x3FF, 0x1FE), // 0
+ GLYPH(0x3C0, 0x3E0, 0x1E0, 0x1E0, 0x1E0, 0x1E0, 0x1E0, 0x1E0, 0x1E0, 0x1E0), // 1
+ GLYPH(0x3FE, 0x3FF, 0x00F, 0x00F, 0x1FF, 0x3FE, 0x3C0, 0x3C0, 0x3FF, 0x3FF), // 2
+ GLYPH(0x3FE, 0x3FF, 0x00F, 0x00F, 0x07E, 0x07E, 0x00F, 0x00F, 0x3FF, 0x3FE), // 3
+ GLYPH(0x3CF, 0x3CF, 0x3CF, 0x3CF, 0x3FF, 0x1FF, 0x00F, 0x00F, 0x00F, 0x00F), // 4
+ GLYPH(0x3FF, 0x3FF, 0x3C0, 0x3C0, 0x3FE, 0x1FF, 0x00F, 0x00F, 0x3FF, 0x3FE), // 5
+ GLYPH(0x1FF, 0x3FF, 0x3C0, 0x3C0, 0x3FE, 0x3FF, 0x3CF, 0x3CF, 0x3FF, 0x1FE), // 6
+ GLYPH(0x3FE, 0x3FF, 0x00F, 0x00F, 0x00F, 0x00F, 0x00F, 0x00F, 0x00F, 0x00F), // 7
+ GLYPH(0x1FE, 0x3FF, 0x3CF, 0x3CF, 0x1FE, 0x1FE, 0x3CF, 0x3CF, 0x3FF, 0x1FE), // 8
+ GLYPH(0x1FE, 0x3FF, 0x3CF, 0x3CF, 0x3FF, 0x1FF, 0x00F, 0x00F, 0x3FF, 0x3FE), // 9
+ GLYPH(0x1FE, 0x3FF, 0x3CF, 0x3CF, 0x3FF, 0x3FF, 0x3CF, 0x3CF, 0x3CF, 0x3CF), // A
+ GLYPH(0x1FF, 0x3FF, 0x3C0, 0x3C0, 0x3C0, 0x3C0, 0x3C0, 0x3C0, 0x3FF, 0x1FF), // C
+ GLYPH(0x3FE, 0x3FF, 0x3CF, 0x3CF, 0x3CF, 0x3CF, 0x3CF, 0x3CF, 0x3FF, 0x3FE), // D
+ GLYPH(0x1FF, 0x3FF, 0x3C0, 0x3C0, 0x3F8, 0x3F8, 0x3C0, 0x3C0, 0x3FF, 0x1FF), // E
+ GLYPH(0x3CF, 0x3EF, 0x3FF, 0x3FF, 0x3DF, 0x3CF, 0x3CF, 0x3CF, 0x3CF, 0x3CF), // N
+ GLYPH(0x1FE, 0x3FF, 0x3CF, 0x3CF, 0x3CF, 0x3CF, 0x3CF, 0x3CF, 0x3FF, 0x1FE), // O
+ GLYPH(0x3FE, 0x3FF, 0x3CF, 0x3CF, 0x3FF, 0x3FE, 0x3C0, 0x3C0, 0x3C0, 0x3C0), // P
+ GLYPH(0x3FE, 0x3FF, 0x3CF, 0x3CF, 0x3FE, 0x3FF, 0x3CF, 0x3CF, 0x3CF, 0x3CF), // R
+ GLYPH(0x1FF, 0x3FF, 0x3C0, 0x3C0, 0x3FE, 0x1FF, 0x00F, 0x00F, 0x3FF, 0x3FE), // S
+ GLYPH(0x3FF, 0x3FF, 0x078, 0x078, 0x078, 0x078, 0x078, 0x078, 0x078, 0x078), // T
+ {0xF0F, 0xF0F, 0xF0F, 0xF6F, 0xF6F, 0xFFF, 0xFFF, 0xF9F, 0xF0F, 0xF0F}, // W
+ GLYPH(0x3CF, 0x3CF, 0x3CF, 0x3CF, 0x3FF, 0x1FE, 0x078, 0x078, 0x078, 0x078), // Y
+ },
+ // Pixel-art pointing hand (tap hint), 12x14: outline and fill masks.
+ .hand_ol = {0x0E0, 0x1B0, 0x1B0, 0x1BE, 0x1B5, 0x7B5, 0x9D5, 0x8C1,
+ 0x801, 0x401, 0x402, 0x202, 0x1FC, 0x1FC},
+ .hand_in = {0x000, 0x040, 0x040, 0x040, 0x04A, 0x04A, 0x62A, 0x73E,
+ 0x7FE, 0x3FE, 0x3FC, 0x1FC, 0x000, 0x000},
+ .save_name = "crossyroad.sav",
+ .slots = {0x90010000u, 0x90410000u}, // userland headers of the two firmware slots
+ .s_crossy = "CROSSY",
+ .s_road = "ROAD",
+ .s_new_top = "NEW TOP",
+};
+#endif
+
+#define pal G.rom.pal
+#define shade_pairs G.rom.shade_pairs
+#define mats G.rom.mats
+#define shapes G.rom.shapes
+#define shape_at G.rom.shape_at
+#define model_def G.rom.model_def
+#define obstacle_pct G.rom.obstacle_pct
+#define kinds G.rom.kinds
+#define DX G.rom.dx
+#define DZ G.rom.dz
+#define font_chars G.rom.font_chars
+#define font_w G.rom.font_w
+#define font G.rom.font
+#define hand_ol G.rom.hand_ol
+#define hand_in G.rom.hand_in
+#define save_name G.rom.save_name
+#define slots G.rom.slots
+#define str_crossy G.rom.s_crossy
+#define str_road G.rom.s_road
+#define str_new_top G.rom.s_new_top
+
+static void init_palette(void) {
+ for (int i = 0; i < NCOLORS; i++) shade[i] = i;
+ for (unsigned i = 0; i < sizeof(shade_pairs) / sizeof(shade_pairs[0]); i++) shade[shade_pairs[i][0]] = shade_pairs[i][1];
+}
+
+// ---------------------------------------------------------------------------
+// Rasterizer: convex polygons sampled at pixel centers. c < 0 darkens (shadow).
+
+// ceil(v - 0.5): index of the first pixel whose center is at or after v
+// (a single VCVTP instruction on the Cortex-M7).
+static inline int ceil_half(float v) { return (int)__builtin_lceilf(v - 0.5f); }
+
+#ifdef HOST_STATS
+long st_polys, st_lines, st_pixels;
+#endif
+static void raster(const float *px, const float *py, int n, int c) {
+#ifdef HOST_STATS
+ st_polys++;
+#endif
+ int it = 0, ib = 0;
+ float xmin = px[0], xmax = px[0];
+ for (int i = 1; i < n; i++) {
+ if (py[i] < py[it]) it = i;
+ if (py[i] > py[ib]) ib = i;
+ if (px[i] < xmin) xmin = px[i];
+ if (px[i] > xmax) xmax = px[i];
+ }
+ if (xmax <= 0.5f || xmin >= SW - 0.5f) return;
+ int y0 = ceil_half(py[it]), y1 = ceil_half(py[ib]);
+ if (y0 < 0) y0 = 0;
+ if (y1 > SH) y1 = SH;
+ if (y0 >= y1) return;
+#ifdef HOST_STATS
+ { extern long st_iters; st_iters += y1 - y0; }
+#endif
+ // Walk the two chains from the top vertex to the bottom one. Each edge is
+ // evaluated from its upper end, so edges shared by neighbours match exactly.
+ int a0 = it, a1 = it + 1 == n ? 0 : it + 1, b0 = it, b1 = it ? it - 1 : n - 1;
+ float sa = 0, sb = 0, yc = y0 + 0.5f;
+ int na = 1, nb = 1; // slopes need computing
+ uint8_t *row = fb + y0 * SW;
+ for (int y = y0; y < y1; y++, yc += 1.0f, row += SW) {
+ while (py[a1] <= yc && a1 != ib) {
+ a0 = a1;
+ a1 = a1 + 1 == n ? 0 : a1 + 1;
+ na = 1;
+ }
+ while (py[b1] <= yc && b1 != ib) {
+ b0 = b1;
+ b1 = b1 ? b1 - 1 : n - 1;
+ nb = 1;
+ }
+ if (na) {
+ float d = py[a1] - py[a0];
+ sa = d > 0 ? (px[a1] - px[a0]) / d : 0;
+ na = 0;
+ }
+ if (nb) {
+ float d = py[b1] - py[b0];
+ sb = d > 0 ? (px[b1] - px[b0]) / d : 0;
+ nb = 0;
+ }
+ float xa = px[a0] + (yc - py[a0]) * sa, xb = px[b0] + (yc - py[b0]) * sb;
+ if (xa > xb) {
+ float t = xa;
+ xa = xb;
+ xb = t;
+ }
+ int a = ceil_half(xa), b = ceil_half(xb);
+#ifdef HOST_STATS
+ { extern long st_off, st_zero, st_offc[256]; if (b <= 0 || a >= SW) { st_off++; st_offc[c & 255]++; } else if (a >= b) st_zero++; }
+#endif
+ if (a < 0) a = 0;
+ if (b > SW) b = SW;
+ if (a >= b) continue;
+ uint8_t *p = row + a, *q = row + b;
+#ifdef HOST_STATS
+ st_lines++;
+ st_pixels += b - a;
+#endif
+ if (c >= 0) memset(p, c, q - p);
+ else
+ for (; p < q; p++) *p = shade[*p];
+ }
+}
+
+static void fill_rect(int x, int y, int w, int h, int c) {
+ if (x < 0) { w += x; x = 0; }
+ if (y < 0) { h += y; y = 0; }
+ if (x + w > SW) w = SW - x;
+ if (y + h > SH) h = SH - y;
+ if (w <= 0 || h <= 0) return;
+ for (uint8_t *p = fb + y * SW + x; h--; p += SW) memset(p, c, w);
+}
+
+// ---------------------------------------------------------------------------
+// Projection. World units are tiles: x east, y up, z north. Orthographic
+// camera measured on screenshots of the original: yaw 19.04, pitch 42.33 deg.
+
+#ifndef K
+#define K 30.0f // pixels per tile
+#endif
+#define PXX (K * 0.94528f)
+#define PXY (K * 0.21969f)
+#define PZX (K * 0.32622f)
+#define PZY (K * -0.63658f)
+#define PYY (K * -0.73924f)
+
+static inline float sx_of(float x, float z) { return ox + PXX * x + PZX * z; }
+static inline float sy_of(float x, float y, float z) { return oy + PXY * x + PZY * z + PYY * y; }
+
+// Axis aligned box: top, south (-z) and east (+x) faces are the visible ones.
+static void draw_cuboid(float x0, float y0, float z0, float x1, float y1, float z1, int ct, int cs, int ce) {
+ float ax = sx_of(x0, z0), ay = sy_of(x0, y0, z0);
+ float dxx = PXX * (x1 - x0), dxy = PXY * (x1 - x0);
+ float dzx = PZX * (z1 - z0), dzy = PZY * (z1 - z0);
+ float dy = PYY * (y1 - y0);
+ float px[4], py[4];
+ if (ct >= 0) {
+ px[0] = ax; py[0] = ay + dy;
+ px[1] = ax + dxx; py[1] = ay + dxy + dy;
+ px[2] = ax + dxx + dzx; py[2] = ay + dxy + dzy + dy;
+ px[3] = ax + dzx; py[3] = ay + dzy + dy;
+ raster(px, py, 4, ct);
+ }
+ if (dy == 0) return;
+ if (cs >= 0) {
+ px[0] = ax; py[0] = ay;
+ px[1] = ax + dxx; py[1] = ay + dxy;
+ px[2] = ax + dxx; py[2] = ay + dxy + dy;
+ px[3] = ax; py[3] = ay + dy;
+ raster(px, py, 4, cs);
+ }
+ if (ce >= 0) {
+ float bx = ax + dxx, by = ay + dxy;
+ px[0] = bx; py[0] = by;
+ px[1] = bx + dzx; py[1] = by + dzy;
+ px[2] = bx + dzx; py[2] = by + dzy + dy;
+ px[3] = bx; py[3] = by + dy;
+ raster(px, py, 4, ce);
+ }
+}
+
+// Horizontal rectangle [x0,x1]x[z0,z1] at height y (c < 0: shadow).
+static void ground_quad(float x0, float x1, float z0, float z1, float y, int c) {
+ float px[4], py[4];
+ px[0] = sx_of(x0, z0); py[0] = sy_of(x0, y, z0);
+ px[1] = sx_of(x1, z0); py[1] = sy_of(x1, y, z0);
+ px[2] = sx_of(x1, z1); py[2] = sy_of(x1, y, z1);
+ px[3] = sx_of(x0, z1); py[3] = sy_of(x0, y, z1);
+ raster(px, py, 4, c);
+}
+
+// Vertical rectangle facing south at z, spanning [x0,x1] and [y0,y1].
+static void south_quad(float x0, float x1, float y0, float y1, float z, int c) {
+ float px[4], py[4];
+ px[0] = px[3] = sx_of(x0, z);
+ px[1] = px[2] = sx_of(x1, z);
+ py[0] = sy_of(x0, y0, z); py[1] = sy_of(x1, y0, z);
+ py[2] = sy_of(x1, y1, z); py[3] = sy_of(x0, y1, z);
+ raster(px, py, 4, c);
+}
+
+// Vertical rectangle facing east at x, spanning [z0,z1] and [y0,y1].
+static void east_quad(float x, float z0, float z1, float y0, float y1, int c) {
+ float px[4], py[4];
+ px[0] = px[3] = sx_of(x, z0);
+ px[1] = px[2] = sx_of(x, z1);
+ py[0] = sy_of(x, y0, z0); py[1] = sy_of(x, y0, z1);
+ py[2] = sy_of(x, y1, z1); py[3] = sy_of(x, y1, z0);
+ raster(px, py, 4, c);
+}
+
+// ---------------------------------------------------------------------------
+// Box models. Units: 1/40 tile. Origin: model center, on the ground.
+
+// Painter's order: a box goes first when it is behind (west of, north of, or
+// below) another one it overlaps on screen.
+static NOINLINE int behind(const Box *a, const Box *b) {
+ return a->x + a->w <= b->x || a->z >= b->z + b->d || a->y + a->h <= b->y;
+}
+
+static void sort_boxes(Box *bx, int n) {
+ Box out[32];
+ uint32_t used = 0;
+ for (int k = 0; k < n; k++)
+ for (int i = 0; i < n; i++) {
+ if (used >> i & 1) continue;
+ int ok = 1;
+ for (int j = 0; j < n && ok; j++)
+ if (j != i && !(used >> j & 1) && behind(&bx[j], &bx[i]) && !behind(&bx[i], &bx[j])) ok = 0;
+ if (ok) {
+ out[k] = bx[i];
+ used |= 1u << i;
+ break;
+ }
+ }
+ memcpy(bx, out, n * sizeof(Box));
+}
+
+static void build_models(void) {
+ Box *dst = boxpool;
+ for (int id = 0; id < NMODELS; id++) {
+ const uint8_t *def = model_def[id];
+ int s = def[0] & 15, r = def[0] >> 4, n = 0, reach = 0;
+ for (int i = shape_at[s]; i < shape_at[s + 1]; i++) {
+ Box b = shapes[i];
+ if (b.m >= M_V0 && (b.m = def[1 + b.m - M_V0]) == NONE) continue;
+ int x0 = b.x, x1 = b.x + b.w, z0 = b.z, z1 = b.z + b.d;
+ if (r == 1) { b.x = z0; b.w = z1 - z0; b.z = -x1; b.d = x1 - x0; }
+ else if (r == 2) { b.x = -x1; b.z = -z1; }
+ else if (r == 3) { b.x = -z1; b.w = z1 - z0; b.z = x0; b.d = x1 - x0; }
+ else if (r == 4) b.x = -x1; // mirror east-west
+ dst[n++] = b;
+ int e = b.x < 0 ? -b.x : b.x;
+ if (b.x + b.w > e) e = b.x + b.w;
+ if (b.y + b.h > e) e = b.y + b.h;
+ if (-b.z > e) e = -b.z;
+ if (b.z + b.d > e) e = b.z + b.d;
+ if (e > reach) reach = e;
+ }
+ sort_boxes(dst, n);
+ models[id] = (Mdl){(uint16_t)(dst - boxpool), (uint8_t)n, (uint8_t)reach};
+ dst += n;
+ }
+}
+
+// Draw a model at a world position with per-axis scale; shapes are snapped to
+// whole pixels so moving models keep a stable look.
+static void draw_model_s(int id, float wx, float wy, float wz, float sx, float sy, float sz) {
+ const Mdl *m = &models[id];
+ float bx = sx_of(wx, wz), by = sy_of(wx, wy, wz);
+ float r = m->reach * (K / 40.0f) * 1.3f;
+ if (bx + r < 0 || bx - r > SW || by + r * 0.8f < 0 || by - r * 1.6f > SH) return;
+ float fx = (float)(int)(bx + 16384.5f) - 16384.0f, fy = (float)(int)(by + 16384.5f) - 16384.0f;
+ float sox = ox, soy = oy;
+ ox += fx - bx;
+ oy += fy - by;
+ const float u = 1.0f / 40.0f;
+ const Box *b = boxpool + m->off;
+ for (int i = 0; i < m->n; i++, b++) {
+ const Mat *t = &mats[b->m];
+ draw_cuboid(wx + b->x * u * sx, wy + b->y * u * sy, wz + b->z * u * sz, wx + (b->x + b->w) * u * sx,
+ wy + (b->y + b->h) * u * sy, wz + (b->z + b->d) * u * sz, t->t, t->s, t->e);
+ }
+ ox = sox;
+ oy = soy;
+}
+static void draw_model(int id, float x, float y, float z) { draw_model_s(id, x, y, z, 1, 1, 1); }
+
+// Shadows: light comes from the west, so a box shades the ground to its east.
+#define LIGHT_SLOPE 0.9f
+static void shadow_box(float x0, float x1, float z0, float z1, float ylo, float yhi, float g) {
+ if (yhi <= g) return;
+ if (ylo < g) ylo = g;
+ ground_quad(x0 + LIGHT_SLOPE * (ylo - g), x1 + LIGHT_SLOPE * (yhi - g), z0, z1, g, -1);
+}
+static void shadow_model_s(int id, float wx, float wy, float wz, float g, float sx, float sy, float sz) {
+ const Mdl *m = &models[id];
+ float bx = sx_of(wx, wz);
+ float r = m->reach * (K / 40.0f) * 2.2f;
+ if (bx + r < 0 || bx - r > SW) return;
+ const float u = 1.0f / 40.0f;
+ const Box *b = boxpool + m->off;
+ for (int i = 0; i < m->n; i++, b++)
+ shadow_box(wx + b->x * u * sx, wx + (b->x + b->w) * u * sx, wz + b->z * u * sz, wz + (b->z + b->d) * u * sz,
+ wy + b->y * u * sy, wy + (b->y + b->h) * u * sy, g);
+}
+static void shadow_model(int id, float x, float y, float z, float g) { shadow_model_s(id, x, y, z, g, 1, 1, 1); }
+
+// Trees: trunk plus a leaf block with the original's striped layers
+// (a dark band, then a light band per layer). Only visible faces are drawn.
+static void draw_tree(float x, float g, float z, int layers) {
+ float sx = sx_of(x, z);
+ if (sx < -30 || sx > SW + 30) return;
+ const float u = 1.0f / 40.0f;
+ float t = 6 * u, l = 12.5f * u;
+ float top = g + (10 + 5 + 15 * layers) * u;
+ east_quad(x + t, z - t, z + t, g, g + 10 * u, C_TRUNK_E);
+ south_quad(x - t, x + t, g, g + 10 * u, z - t, C_TRUNK);
+ float y = g + 10 * u;
+ for (int i = 0; i <= layers; i++) {
+ float y1 = y + 5 * u;
+ south_quad(x - l, x + l, y, y1, z - l, C_LEAF_B);
+ east_quad(x + l, z - l, z + l, y, y1, C_LEAF_B);
+ if (i == layers) break;
+ float y2 = y1 + 10 * u;
+ south_quad(x - l, x + l, y1, y2, z - l, C_LEAF_A);
+ east_quad(x + l, z - l, z + l, y1, y2, C_LEAF_A);
+ y = y2;
+ }
+ ground_quad(x - l, x + l, z - l, z + l, top, C_LEAF);
+}
+
+// ---------------------------------------------------------------------------
+// Random numbers
+
+static uint32_t rnd(void) {
+ rng_s ^= rng_s << 13;
+ rng_s ^= rng_s >> 17;
+ rng_s ^= rng_s << 5;
+ return rng_s;
+}
+static int irand(int n) { return (int)((rnd() >> 8) % (uint32_t)n); }
+static float frand(float a, float b) { return a + (b - a) * (float)(rnd() >> 8) * (1.0f / 16777216.0f); }
+static float fabs_(float v) { return __builtin_fabsf(v); }
+static NOINLINE int iround(float v) { return (int)(v + 16384.5f) - 16384; }
+static NOINLINE float clampf(float v, float a, float b) { return v < a ? a : v > b ? b : v; }
+
+// ---------------------------------------------------------------------------
+// World
+
+enum { O_NONE, O_SHORT, O_MEDIUM, O_TALL, O_ROCK, O_PAD };
+
+#define H_GRASS (15 / 40.0f)
+#define H_ROAD (10 / 40.0f)
+#define H_WATER (5 / 40.0f)
+#define H_LOG (9 / 40.0f)
+#define H_PAD (2 / 40.0f)
+
+#define HOP_TIME 0.16f
+#define HOP_HEIGHT 0.36f
+#define CAR_HALF (27 / 40.0f)
+#define TRUCK_HALF (56 / 40.0f)
+#define WAGON 4.0f
+#define TRAIN_CARS 7
+#define TRAIN_SPEED 33.3f
+#define TRAIN_WARN 2.0f
+#define CHICK_HALF 0.14f
+#define IDLE_EAGLE 6.0f
+
+static NOINLINE Lane *lane_at(int row) { return &lanes[(unsigned)(row + NLANES * 1024) % NLANES]; }
+
+static float lane_h(int type) { return type == L_GRASS ? H_GRASS : type == L_ROAD || type == L_RAIL ? H_ROAD : H_WATER; }
+
+static int is_truck(int kind) { return kind >= 5; }
+static float obj_half(const Lane *L, const Obj *o) {
+ if (L->type == L_ROAD) return is_truck(o->kind) ? TRUCK_HALF : CAR_HALF;
+ return o->kind * 0.5f - 0.05f;
+}
+
+// ---------------------------------------------------------------------------
+// Generation: sets of lanes like the original (grass, roads, rivers, rails).
+
+#define ALLPLAY 0x1FF
+
+
+static int pick_tree(int edge) {
+ int r = irand(100);
+ if (edge) return r < 60 ? O_TALL : r < 80 ? O_MEDIUM : r < 90 ? O_SHORT : O_ROCK;
+ return r < 10 ? O_TALL : r < 40 ? O_MEDIUM : r < 80 ? O_SHORT : O_ROCK;
+}
+
+static uint16_t spread(uint16_t seed, uint16_t fr) {
+ uint16_t m = seed & fr, old;
+ do {
+ old = m;
+ m |= ((m << 1) | (m >> 1)) & fr;
+ } while (m != old);
+ return m;
+}
+
+static int random_bit(uint16_t mask) {
+ int n = 0;
+ for (int i = 0; i < 9; i++) n += mask >> i & 1;
+ int k = irand(n ? n : 1);
+ for (int i = 0; i < 9; i++)
+ if ((mask >> i & 1) && k-- == 0) return i;
+ return 4;
+}
+
+static void new_set(int row) {
+ int t, gp = row < 50 ? 90 : row < 100 ? 75 : row < 150 ? 50 : row < 200 ? 25 : 0;
+ if (set_type == L_GRASS) t = kinds[1 + irand(3)];
+ else if (irand(100) < gp) t = L_GRASS;
+ else do t = kinds[irand(4)]; while (t == set_type);
+ int n;
+ switch (t) {
+ case L_GRASS: {
+ int r = irand(100);
+ n = r < 60 ? 1 : r < 80 ? 2 : r < 90 ? 3 : r < 95 ? 4 : 5;
+ break;
+ }
+ case L_ROAD: n = 1 + irand(row <= 25 ? 2 : row <= 50 ? 3 : row <= 100 ? 4 : row <= 150 ? 5 : 6); break;
+ case L_RIVER: n = 1 + irand(row <= 25 ? 1 : row <= 50 ? 2 : row <= 100 ? 3 : row <= 150 ? 4 : 5); break;
+ default: n = 1 + irand(row <= 100 ? 1 : row <= 150 ? 2 : 3); break;
+ }
+ set_type = t;
+ set_left = n;
+}
+
+// Evenly spaced moving objects on a looping lane.
+static void place_movers(Lane *L, float spacing) {
+ int n = (int)(30.0f / spacing) + 1;
+ if (n > MAXOBJ) n = MAXOBJ;
+ L->period = n * spacing;
+ L->nobj = n;
+ float x0 = frand(0, spacing) - L->period * 0.5f;
+ for (int i = 0; i < n; i++) L->obj[i].x = x0 + i * spacing;
+}
+
+static void gen_lane(void) {
+ int row = gen_next++;
+ Lane *L = lane_at(row);
+ memset(L, 0, sizeof(*L));
+ L->row = row;
+ L->coin = NO_COIN;
+ L->bob = -1;
+ L->alt = row & 1;
+ int type = L_GRASS, dir = 0;
+ if (row > start_end) {
+ if (set_left <= 0) new_set(row);
+ set_left--;
+ type = set_type;
+ if (type == L_RIVER && irand(100) < 30) type = L_LILY;
+ }
+ L->type = type;
+ switch (type) {
+ case L_GRASS: {
+ int wall = row <= -4, open = row >= -3 && row <= 0;
+ int p = obstacle_pct[row / 25 > 11 ? 11 : row / 25];
+ int keep = row <= 1 ? 4 : random_bit(reach_prev);
+ for (int c = -NCOLS / 2; c <= NCOLS / 2; c++) {
+ int edge = c < PLAY_MIN || c > PLAY_MAX, o = 0;
+ if (edge) {
+ if (c == PLAY_MIN - 1 || c == PLAY_MAX + 1 || irand(10)) o = pick_tree(1);
+ } else if (wall) {
+ o = pick_tree(1);
+ } else if (!open && c - PLAY_MIN != keep && irand(100) < p) {
+ o = pick_tree(0);
+ }
+ L->cells[COL0 + c] = (uint8_t)o;
+ }
+ if (row > 0) {
+ uint16_t fr = 0;
+ for (int i = 0; i < 9; i++)
+ if (!L->cells[COL0 + PLAY_MIN + i]) fr |= 1 << i;
+ reach_prev = spread(reach_prev, fr);
+ if (row > 1 && irand(100) < 10) {
+ int c = random_bit(fr);
+ L->coin = (int8_t)(c + PLAY_MIN);
+ }
+ } else {
+ reach_prev = ALLPLAY;
+ }
+ break;
+ }
+ case L_ROAD: {
+ dir = prev_dir ? -prev_dir : (irand(2) ? 1 : -1);
+ int kind = irand(8);
+ float len = is_truck(kind) ? 2 * TRUCK_HALF : 2 * CAR_HALF, span = 30 + len;
+ float boost = 1.0f + (row > 300 ? 300 : row) / 600.0f;
+ L->speed = frand(2.0f, 3.33f) * boost;
+ float gap = (float)(2 + irand(12));
+ int n = (int)(span / (gap + len));
+ if (n < 1) n = 1;
+ if (n > MAXOBJ) n = MAXOBJ;
+ place_movers(L, span / n);
+ for (int i = 0; i < L->nobj; i++) L->obj[i].kind = (uint8_t)kind;
+ if (irand(100) < 5) L->coin = (int8_t)(PLAY_MIN + irand(9));
+ reach_prev = ALLPLAY;
+ break;
+ }
+ case L_RIVER: {
+ dir = prev_dir && irand(100) < 95 ? -prev_dir : (irand(2) ? 1 : -1);
+ L->speed = frand(1.33f, 3.0f);
+ place_movers(L, L->speed * frand(2.5f, 3.0f));
+ float maxlen = L->period / L->nobj - 1.2f;
+ for (int i = 0; i < L->nobj; i++) {
+ int r = irand(100), len = r < 35 ? 2 : r < 80 ? 3 : 4;
+ while (len > 2 && len > maxlen) len--;
+ L->obj[i].kind = (uint8_t)len;
+ L->obj[i].coin = irand(100) < 5 ? (int8_t)irand(len) : -1;
+ }
+ reach_prev = ALLPLAY;
+ break;
+ }
+ case L_LILY: {
+ uint16_t pads = 1 << random_bit(reach_prev);
+ int n = 1;
+ for (int i = 0; i < 9 && n < 3; i++) {
+ if (pads >> i & 1) continue;
+ if (irand(100) < ((reach_prev >> i & 1) ? 30 : 10)) {
+ pads |= 1 << i;
+ n++;
+ }
+ }
+ for (int i = 0; i < 9; i++)
+ if (pads >> i & 1) L->cells[COL0 + PLAY_MIN + i] = O_PAD;
+ for (int c = 0; c < NCOLS; c++)
+ if ((c - COL0 < PLAY_MIN || c - COL0 > PLAY_MAX) && irand(100) < 12) L->cells[c] = O_PAD;
+ if (irand(100) < 5) L->coin = (int8_t)(random_bit(pads) + PLAY_MIN);
+ reach_prev &= pads;
+ break;
+ }
+ case L_RAIL: {
+ dir = irand(2) ? 1 : -1;
+ float wait = frand(3.0f, 8.0f);
+ L->period = wait;
+ L->timer = frand(0, wait) + TRAIN_WARN;
+ if (irand(100) < 5) L->coin = (int8_t)(PLAY_MIN + irand(9));
+ reach_prev = ALLPLAY;
+ dir = 0; // trains do not set the next lane's direction
+ L->dir = irand(2) ? 1 : -1;
+ break;
+ }
+ }
+ if (type != L_RAIL) L->dir = (int8_t)dir;
+ prev_dir = dir;
+}
+
+// ---------------------------------------------------------------------------
+// Gameplay
+
+enum { ST_TITLE, ST_PLAY, ST_DEAD, ST_OVER };
+enum { D_NONE, D_PANCAKE, D_SPLAT, D_TRAIN, D_DROWN, D_LOG, D_EAGLE };
+
+
+static void spawn_parts(float x, float y, float z, int n, int c1, int c2, float spd, float up) {
+ for (int i = 0; i < NPARTS && n > 0; i++) {
+ Part *p = &parts[i];
+ if (p->life > 0) continue;
+ *p = (Part){x, y, z, frand(-spd, spd), frand(up * 0.5f, up), frand(-spd, spd), frand(0.6f, 1.0f),
+ (uint8_t)(irand(3) ? c1 : c2), (uint8_t)(2 + irand(3))};
+ n--;
+ }
+}
+
+static int rail_warning(const Lane *L) { return L->train || L->timer < TRAIN_WARN; }
+
+#ifdef HOST_GOD
+static int god = 1;
+#else
+static const int god = 0;
+#endif
+
+static void kill(int how) {
+ if (P.dead || (god && how != D_EAGLE)) return;
+ P.dead = how;
+ P.dt = 0;
+ P.hop = 0;
+ P.nq = 0;
+ state = ST_DEAD;
+ st_time = 0;
+ if (how == D_DROWN || how == D_LOG) {
+ spawn_parts(P.x, P.base - H_WATER, P.z, 20, C_FOAM, C_WATER, 1.2f, 4.5f);
+ if (how == D_LOG) shake = 0.5f;
+ } else if (how == D_EAGLE) {
+ eagle_on = 1;
+ eagle_x = P.x;
+ eagle_z = P.z + 13.0f;
+ eagle_y = 2.4f;
+ }
+}
+
+// Surface height where the chicken would stand at (x, row).
+static float stand_h(int row, int on_log) {
+ const Lane *L = lane_at(row);
+ if (L->type == L_RIVER) return H_WATER + (on_log ? H_LOG : 0);
+ if (L->type == L_LILY) return H_WATER + H_PAD;
+ return lane_h(L->type);
+}
+
+// Log covering x in lane L after time t; returns its index and the nearest slot center.
+static int find_log(const Lane *L, float x, float t, float *slot) {
+ for (int i = 0; i < L->nobj; i++) {
+ const Obj *o = &L->obj[i];
+ float cx = o->x + L->dir * L->speed * t, half = o->kind * 0.5f;
+ float rel = x - cx;
+ if (rel < -half - 0.45f || rel > half + 0.45f) continue;
+ int idx = (int)(rel + half + 16384.0f) - 16384;
+ if (idx < 0) idx = 0;
+ if (idx >= o->kind) idx = o->kind - 1;
+ *slot = cx - half + 0.5f + idx;
+ return i;
+ }
+ return -1;
+}
+
+static void start_hop(int dir) {
+ P.face = dir;
+ int trow = P.row + DZ[dir];
+ int tcol = iround(P.x + DX[dir]);
+ Lane *T = lane_at(trow);
+ if (tcol < PLAY_MIN || tcol > PLAY_MAX || T->row != trow ||
+ (T->type == L_GRASS && T->cells[COL0 + tcol] && T->cells[COL0 + tcol] != O_PAD)) {
+ P.nq = 0; // blocked: just turn
+ return;
+ }
+ float tx = (float)tcol;
+ if (T->type == L_RIVER) {
+ float slot;
+ if (find_log(T, P.x + DX[dir], HOP_TIME, &slot) >= 0) tx = slot;
+ else tx = P.x + DX[dir];
+ }
+ P.hop = 1;
+ P.t = 0;
+ P.fx = P.x;
+ P.fz = P.z;
+ P.fbase = P.base;
+ P.tx = tx;
+ P.tz = (float)trow;
+ P.log = -1;
+}
+
+static void collect_coin(void) {
+ Lane *L = lane_at(iround(P.z));
+ int col = iround(P.x);
+ if (L->coin != NO_COIN && L->coin == col && fabs_(P.x - col) < 0.4f && fabs_(P.z - L->row) < 0.4f) {
+ L->coin = NO_COIN;
+ coins++;
+ spawn_parts(col, P.base + 0.3f, L->row, 8, C_GOLD, C_COIN, 1.0f, 3.0f);
+ }
+ if (L->type == L_RIVER && P.log >= 0) {
+ Obj *o = &L->obj[P.log];
+ if (o->coin >= 0 && fabs_(o->x - o->kind * 0.5f + 0.5f + o->coin - P.x) < 0.4f) {
+ o->coin = -1;
+ coins++;
+ spawn_parts(P.x, P.base + 0.3f, L->row, 8, C_GOLD, C_COIN, 1.0f, 3.0f);
+ }
+ }
+}
+
+static void land(void) {
+ P.hop = 0;
+ P.y = 0;
+ P.x = P.tx;
+ P.z = P.tz;
+ P.row = iround(P.tz);
+ Lane *L = lane_at(P.row);
+ P.base = stand_h(P.row, 0);
+ if (L->type == L_RIVER) {
+ float slot;
+ int i = find_log(L, P.x, 0, &slot);
+ if (i < 0) {
+ kill(D_DROWN);
+ return;
+ }
+ P.log = i;
+ P.x = slot;
+ P.logoff = slot - L->obj[i].x;
+ P.base = stand_h(P.row, 1);
+ L->bob = (int8_t)i;
+ L->bobt = 0;
+ } else if (L->type == L_LILY) {
+ int col = iround(P.x);
+ if (L->cells[COL0 + col] != O_PAD) {
+ kill(D_DROWN);
+ return;
+ }
+ L->bob = (int8_t)col;
+ L->bobt = 0;
+ }
+ collect_coin();
+ P.sy = 0.8f;
+ P.sx = P.sz = 1.1f;
+ if (P.nq) {
+ int d = P.q[0];
+ P.nq--;
+ for (int i = 0; i < P.nq; i++) P.q[i] = P.q[i + 1];
+ start_hop(d);
+ }
+}
+
+static float train_len(void) { return WAGON * TRAIN_CARS; }
+
+static NOINLINE void update_lanes(float dt) {
+ int r0 = (int)cam_z - 8, r1 = (int)cam_z + 14;
+ for (int r = r0; r <= r1; r++) {
+ Lane *L = lane_at(r);
+ if (L->row != r) continue;
+ if (L->bob >= 0) {
+ L->bobt += dt;
+ if (L->bobt > 0.3f) L->bob = -1;
+ }
+ if (L->type == L_ROAD || L->type == L_RIVER) {
+ float v = L->dir * L->speed * dt, h = L->period * 0.5f;
+ for (int i = 0; i < L->nobj; i++) {
+ Obj *o = &L->obj[i];
+ o->x += v;
+ if (o->x > h) o->x -= L->period;
+ if (o->x < -h) o->x += L->period;
+ }
+ } else if (L->type == L_RAIL) {
+ if (L->train) {
+ L->trainx += L->dir * TRAIN_SPEED * dt;
+ if (fabs_(L->trainx) > 18 + train_len()) {
+ L->train = 0;
+ L->timer = L->period + TRAIN_WARN;
+ }
+ } else {
+ L->timer -= dt;
+ if (L->timer <= 0) {
+ L->train = 1;
+ L->trainx = -L->dir * 18.0f;
+ }
+ }
+ }
+ }
+}
+
+static void check_hazards(void) {
+ int row = iround(P.z);
+ Lane *L = lane_at(row);
+ if (L->type == L_ROAD) {
+ for (int i = 0; i < L->nobj; i++) {
+ Obj *o = &L->obj[i];
+ float half = obj_half(L, o), d = P.x - o->x;
+ if (fabs_(d) >= half + CHICK_HALF) continue;
+ if (P.hop && P.fz != P.tz && fabs_(d) < half - 0.1f) {
+ // hopped into the side of the vehicle: flattened against it and carried away
+ kill(D_SPLAT);
+ P.sz = 0.12f;
+ P.sx = P.sy = 1.15f;
+ P.z = row + (P.fz < P.tz ? -0.47f : 0.47f);
+ P.base = H_ROAD;
+ P.y = 0;
+ } else if (d * L->dir > 0) {
+ kill(D_PANCAKE); // run over
+ P.base = H_ROAD;
+ P.y = 0;
+ P.z = row;
+ return;
+ } else {
+ kill(D_SPLAT); // hopped into its back
+ P.sx = 0.12f;
+ P.sy = P.sz = 1.15f;
+ P.x = o->x - L->dir * (half + 0.03f);
+ P.base = H_ROAD;
+ P.y = 0;
+ P.z = row;
+ }
+ P.crow = row;
+ P.cobj = i;
+ P.cdx = P.x - o->x;
+ return;
+ }
+ } else if (L->type == L_RAIL && L->train) {
+ float a = L->trainx, b = L->trainx - L->dir * train_len();
+ if (a > b) { float t = a; a = b; b = t; }
+ if (P.x > a - CHICK_HALF && P.x < b + CHICK_HALF) {
+ kill(D_TRAIN);
+ P.sx = 0.12f;
+ P.sy = P.sz = 1.15f;
+ P.z = row;
+ P.base = H_ROAD;
+ P.y = 0;
+ P.crow = row;
+ P.cdx = L->dir * 0.03f;
+ }
+ }
+}
+
+static void update_player(float dt) {
+ if (P.hop) {
+ P.t += dt / HOP_TIME;
+ if (P.t >= 1) {
+ land();
+ } else {
+ float t = P.t;
+ P.x = P.fx + (P.tx - P.fx) * t;
+ P.z = P.fz + (P.tz - P.fz) * t;
+ P.base = P.fbase + (stand_h(iround(P.tz), lane_at(iround(P.tz))->type == L_RIVER) - P.fbase) * t;
+ P.y = HOP_HEIGHT * 4 * t * (1 - t);
+ P.sy = 0.8f + 0.35f * 4 * t * (1 - t);
+ P.sx = P.sz = 1.1f - 0.15f * 4 * t * (1 - t);
+ int r = iround(P.z);
+ if (r - 0 > P.best) {
+ P.best = r;
+ P.idle = 0;
+ }
+ collect_coin();
+ }
+ } else {
+ float k = dt * 12 > 1 ? 1 : dt * 12;
+ P.sy += (1 - P.sy) * k;
+ P.sx += (1 - P.sx) * k;
+ P.sz = P.sx;
+ if (P.log >= 0) {
+ Lane *L = lane_at(P.row);
+ P.x = L->obj[P.log].x + P.logoff;
+ if ((P.x < PLAY_MIN - 0.5f && L->dir < 0) || (P.x > PLAY_MAX + 0.5f && L->dir > 0)) kill(D_LOG);
+ }
+ }
+ if (P.row > P.best) {
+ P.best = P.row;
+ P.idle = 0;
+ }
+ if (!P.dead) check_hazards();
+}
+
+static void update_dead(float dt) {
+ P.dt += dt;
+ float k = dt * 16 > 1 ? 1 : dt * 16;
+ if (P.dead == D_PANCAKE) {
+ P.sy += (0.1f - P.sy) * k;
+ P.sx += (1.25f - P.sx) * k;
+ P.sz = P.sx;
+ } else if (P.dead == D_SPLAT || P.dead == D_TRAIN) {
+ Lane *L = lane_at(P.crow);
+ P.x = (P.dead == D_TRAIN ? L->trainx : L->obj[P.cobj].x) + P.cdx;
+ } else if (P.dead == D_DROWN || P.dead == D_LOG) {
+ if (P.dead == D_LOG && P.log >= 0) P.x = lane_at(P.row)->obj[P.log].x + P.logoff;
+ P.y -= dt * 3.0f;
+ } else if (P.dead == D_EAGLE) {
+ eagle_z -= 24.0f * dt;
+ float d = eagle_z - P.z;
+ if (d > 0) {
+ eagle_y = 0.75f + d * 0.13f;
+ } else { // grabbed and carried away
+ eagle_y += 1.2f * dt;
+ P.z = eagle_z;
+ P.y = eagle_y - 0.62f - P.base;
+ P.x = eagle_x;
+ }
+ if (d < -14) eagle_on = 0;
+ }
+}
+
+static void update_parts(float dt) {
+ for (int i = 0; i < NPARTS; i++) {
+ Part *p = &parts[i];
+ if (p->life <= 0) continue;
+ p->life -= dt;
+ p->x += p->vx * dt;
+ p->y += p->vy * dt;
+ p->z += p->vz * dt;
+ p->vy -= 16.0f * dt;
+ if (p->y < 0) p->life = 0;
+ }
+}
+
+static void update_camera(float dt) {
+ float ex = clampf(P.x, -2.5f, 2.5f) - cam_x;
+ float vx = fabs_(ex) * 3.33f;
+ if (vx > 3.33f) vx = 3.33f;
+ cam_x += (ex > 0 ? 1 : -1) * (vx * dt > fabs_(ex) ? fabs_(ex) : vx * dt);
+ if (state == ST_PLAY) {
+ float d = P.z - cam_z;
+ cam_z += (0.5f + 4.17f * clampf(d, 0, 1)) * dt;
+ if (d <= 0.05f) P.idle += dt;
+ }
+ if (shake > 0) shake -= dt;
+ while (gen_next < (int)cam_z + 16) gen_lane();
+}
+
+static void new_game(void) {
+ rng_s = eadk_random() | 1;
+ memset(lanes, 0, sizeof(lanes));
+ memset(parts, 0, sizeof(parts));
+ gen_next = -10;
+ set_left = 0;
+ set_type = L_GRASS;
+ prev_dir = 0;
+ start_end = 1 + irand(2);
+ reach_prev = ALLPLAY;
+ memset(&P, 0, sizeof(P));
+ P.sx = P.sy = P.sz = 1;
+ P.face = 0;
+ P.visible = 1;
+ P.log = -1;
+ P.base = H_GRASS;
+ cam_x = cam_z = 0;
+ eagle_on = 0;
+ shake = 0;
+ score = 0;
+ new_top = 0;
+ state = ST_TITLE;
+ st_time = 0;
+ while (gen_next < 16) gen_lane();
+}
+
+// ---------------------------------------------------------------------------
+// Drawing the world
+
+// Lanes are drawn only over the part that is on screen ([lxa, lxb]).
+
+static void lane_split(float z0, float z1, float y, int cin, int cout) {
+ float m0 = PLAY_MIN - 0.5f, m1 = PLAY_MAX + 0.5f;
+ if (lxa < m0) ground_quad(lxa, m0, z0, z1, y, cout);
+ ground_quad(lxa > m0 ? lxa : m0, lxb < m1 ? lxb : m1, z0, z1, y, cin);
+ if (lxb > m1) ground_quad(m1, lxb, z0, z1, y, cout);
+}
+
+static void lane_side(float z, float ylo, float yhi, int cin, int cout) {
+ float m0 = PLAY_MIN - 0.5f, m1 = PLAY_MAX + 0.5f;
+ if (lxa < m0) south_quad(lxa, m0, ylo, yhi, z, cout);
+ south_quad(lxa > m0 ? lxa : m0, lxb < m1 ? lxb : m1, ylo, yhi, z, cin);
+ if (lxb > m1) south_quad(m1, lxb, ylo, yhi, z, cout);
+}
+
+static void draw_ground(int row) {
+ Lane *L = lane_at(row), *S = lane_at(row - 1);
+ float z0 = row - 0.5f, z1 = row + 0.5f, h = lane_h(L->type), hs = lane_h(S->type);
+ lxa = (-ox - PZX * z1) / PXX - 0.6f;
+ lxb = (SW - ox - PZX * z0) / PXX + 0.6f;
+ int t = L->type, c0 = (int)(lxa + 1000) - 1000, c1 = (int)(lxb + 1000) - 999;
+ if (t == L_GRASS) lane_split(z0, z1, h, L->alt ? C_GRASS2 : C_GRASS, L->alt ? C_GRASS2_O : C_GRASS_O);
+ else if (t == L_ROAD || t == L_RAIL) lane_split(z0, z1, h, C_ROAD, C_ROAD_O);
+ else lane_split(z0, z1, h, C_WATER, C_WATER_O);
+ if (h > hs) {
+ if (t == L_GRASS) lane_side(z0, hs, h, C_GRASS_SH, C_GRASS_OSH);
+ else lane_side(z0, hs, h, C_ROAD_SIDE, C_ROAD_SIDE);
+ }
+ if (t == L_ROAD && lane_at(row + 1)->type == L_ROAD) {
+ // dashed divider: one tile long dashes centered on even columns
+ for (int c = c0 & ~1; c <= c1; c += 2) {
+ int in = c >= PLAY_MIN && c <= PLAY_MAX;
+ ground_quad(c - 0.5f, c + 0.5f, z1 - 0.05f, z1 + 0.05f, h, in ? C_DASH : C_DASH_O);
+ }
+ } else if (t == L_RAIL) {
+ for (int c = c0; c <= c1; c++)
+ draw_cuboid(c + 0.34f, h, row - 0.44f, c + 0.48f, h + 0.07f, row + 0.44f, C_TIE, C_TIE_S, C_TIE_S);
+ draw_cuboid(lxa, h, row - 0.36f, lxb, h + 0.13f, row - 0.23f, C_RAIL, C_RAIL_S, C_RAIL_S);
+ draw_cuboid(lxa, h, row + 0.3f, lxb, h + 0.13f, row + 0.43f, C_RAIL, C_RAIL_S, C_RAIL_S);
+ } else if (t == L_RIVER || t == L_LILY) {
+ // froth where the river meets the edges of the playable area
+ for (int s = -1; s <= 1; s += 2) {
+ float ex = s * (PLAY_MAX + 0.5f);
+ if (ex < lxa - 1 || ex > lxb + 1) continue;
+ for (int i = 0; i < 5; i++) {
+ float zz = row - 0.37f + i * 0.185f, a = game_time * (2.1f + 0.7f * i) + i * 1.7f + row;
+ float w = 0.13f + 0.03f * (i & 1);
+ ground_quad(ex - w, ex + w, zz - w, zz + w, h + 0.001f, C_FOAM);
+ float f = a - (int)a;
+ float jx = ex + 0.26f * s * (f > 0.5f ? 1.5f - f : f + 0.5f) - 0.13f * s;
+ float w2 = 0.17f + 0.02f * ((i + row) % 3);
+ ground_quad(jx - w2, jx + w2, zz - w2, zz + w2, h + 0.001f, C_FOAM);
+ }
+ }
+ }
+}
+
+static float bob_of(const Lane *L, int idx) {
+ if (L->bob != idx) return 0;
+ float t = L->bobt;
+ return t < 0.15f ? -t * (0.2f / 0.15f) : t < 0.3f ? -(0.3f - t) * (0.2f / 0.15f) : 0;
+}
+
+static void draw_coin(float x, float g, float z) {
+ float sx = sx_of(x, z);
+ if (sx < -10 || sx > SW + 10) return;
+ float a = game_time * 3.2f;
+ float ph = a - (int)a; // 0..1 turn
+ float c = ph < 0.5f ? 1 - ph * 4 : -3 + ph * 4;
+ float ac = fabs_(c), w = 0.2f * ac + 0.02f, d = 0.2f * (1 - ac) + 0.02f;
+ float y = g + 0.1f + 0.04f * (ph < 0.5f ? ph : 1 - ph);
+ draw_cuboid(x - w, y + 0.06f, z - d, x + w, y + 0.38f, z + d, C_COIN, C_COIN_S, C_COIN_S);
+ draw_cuboid(x - w * 0.7f, y, z - d, x + w * 0.7f, y + 0.44f, z + d, C_COIN, C_COIN_S, C_COIN_S);
+ if (ac > 0.5f) south_quad(x - w * 0.35f, x + w * 0.35f, y + 0.14f, y + 0.3f, z - d - 0.001f, C_COIN_C);
+}
+
+// Things standing on a lane, drawn west to east. md: the model, if any.
+typedef struct { float key; uint8_t kind, a, md; } Item;
+enum { I_MODEL, I_TREE, I_PAD, I_LOG, I_SIGNAL, I_COIN, I_PLAYER };
+
+static void draw_player(void) { draw_model_s(MD_CHICKEN + P.face, P.x, P.base + P.y, P.z, P.sx, P.sy, P.sz); }
+
+static void draw_lane_objects(int row) {
+ Lane *L = lane_at(row);
+ float g = lane_h(L->type);
+ Item it[NCOLS + MAXOBJ + 12];
+ int n = 0;
+ if (L->type == L_GRASS || L->type == L_LILY)
+ for (int c = 0; c < NCOLS; c++) {
+ int o = L->cells[c];
+ if (o) it[n++] = (Item){(float)(c - COL0), (uint8_t)(o == O_ROCK ? I_MODEL : o == O_PAD ? I_PAD : I_TREE), (uint8_t)c,
+ (uint8_t)(o == O_ROCK ? MD_ROCK : MD_LILY)};
+ }
+ for (int i = 0; i < L->nobj; i++) {
+ int k = L->obj[i].kind;
+ if (L->type == L_ROAD)
+ it[n++] = (Item){L->obj[i].x, I_MODEL, 0, (uint8_t)((is_truck(k) ? MD_TRUCK + (k - 5) * 2 : MD_CAR + k * 2) + (L->dir < 0))};
+ else
+ it[n++] = (Item){L->obj[i].x, I_LOG, (uint8_t)i, (uint8_t)(MD_LOG + k - 2)};
+ }
+ if (L->type == L_RAIL) {
+ it[n++] = (Item){-0.4f, I_SIGNAL, 0, MD_SIGNAL};
+ if (L->train)
+ for (int i = 0; i < TRAIN_CARS; i++)
+ it[n++] = (Item){L->trainx - L->dir * (WAGON * 0.5f + WAGON * i), I_MODEL, 0,
+ (uint8_t)(i == 0 ? MD_ENGINE + (L->dir < 0) : i == TRAIN_CARS - 1 ? MD_ENGINE + (L->dir > 0) : MD_WAGON)};
+ }
+ if (L->coin != NO_COIN) it[n++] = (Item){(float)L->coin, I_COIN};
+ int prow = iround(P.z), flat = P.dead == D_PANCAKE;
+ if (P.visible && prow == row && !flat) {
+ float k = P.x + 0.001f;
+ if (P.log >= 0 && P.row == row && L->obj[P.log].x + 0.002f > k) k = L->obj[P.log].x + 0.002f;
+ if (P.dead == D_SPLAT) k = L->obj[P.cobj].x + (P.z < row ? 0.002f : -0.002f) + (P.sx < 0.5f ? P.cdx : 0);
+ if (P.dead == D_TRAIN) k = P.x;
+ it[n++] = (Item){k, I_PLAYER};
+ }
+ for (int i = 1; i < n; i++) {
+ Item t = it[i];
+ int j = i - 1;
+ while (j >= 0 && it[j].key > t.key) { it[j + 1] = it[j]; j--; }
+ it[j + 1] = t;
+ }
+ if (P.visible && prow == row && flat) draw_player(); // the pancake lies under the traffic
+ // shadows on this lane's ground
+ for (int i = 0; i < n; i++) {
+ Item *d = &it[i];
+ float x = d->key;
+ if (d->kind == I_TREE) {
+ float top = g + (15 + 15 * L->cells[d->a]) / 40.0f;
+ shadow_box(x - 0.32f, x + 0.32f, row - 0.31f, row + 0.31f, g + 0.25f, top, g);
+ shadow_box(x - 0.15f, x + 0.15f, row - 0.15f, row + 0.15f, g, g + 0.25f, g);
+ } else if (d->kind == I_COIN) {
+ shadow_box(x - 0.14f, x + 0.14f, row - 0.05f, row + 0.05f, g + 0.1f, g + 0.54f, g);
+ } else if (d->kind == I_PLAYER) {
+ shadow_model_s(MD_CHICKEN + P.face, P.x, P.base + P.y, P.z, g, P.sx, P.sy, P.sz);
+ } else {
+ shadow_model(d->md, x, g, row - (d->kind == I_SIGNAL ? 0.43f : 0), g);
+ }
+ }
+ for (int i = 0; i < n; i++) {
+ Item *d = &it[i];
+ float x = d->key, b = 0, z = row;
+ int md = d->md;
+ switch (d->kind) {
+ case I_TREE: draw_tree(x, g, row, L->cells[d->a]); continue;
+ case I_COIN: draw_coin(x, g + (L->type == L_LILY ? H_PAD : 0), row); continue;
+ case I_PLAYER:
+ b = P.log >= 0 && P.row == row ? bob_of(L, P.log) : L->type == L_LILY && !P.hop ? bob_of(L, iround(P.x)) * 0.5f : 0;
+ P.base += b;
+ draw_player();
+ P.base -= b;
+ continue;
+ case I_PAD: b = bob_of(L, d->a - COL0) * 0.5f; break;
+ case I_LOG: b = bob_of(L, d->a); break;
+ case I_SIGNAL:
+ z -= 0.43f;
+ if (rail_warning(L)) md += 1 + ((int)(game_time / 0.3f) & 1);
+ break;
+ }
+ draw_model(md, x, g + b, z);
+ if (d->kind == I_LOG) {
+ Obj *o = &L->obj[d->a];
+ if (o->coin >= 0) draw_coin(x - o->kind * 0.5f + 0.5f + o->coin, g + H_LOG + b, row);
+ }
+ }
+}
+
+static void draw_parts(void) {
+ for (int i = 0; i < NPARTS; i++) {
+ Part *p = &parts[i];
+ if (p->life <= 0) continue;
+ float s = p->sz / 80.0f;
+ int side = p->c == C_WHITE || p->c == C_FOAM ? C_GRAY : shade[p->c];
+ if (p->c == C_GOLD) side = C_COIN_S;
+ draw_cuboid(p->x - s, p->y, p->z - s, p->x + s, p->y + 2 * s, p->z + s, p->c, side, side);
+ }
+}
+
+static void set_camera(void) {
+ float cx = cam_x, cz = cam_z;
+ if (shake > 0) {
+ cx += frand(-0.08f, 0.08f);
+ cz += frand(-0.08f, 0.08f);
+ }
+ float fx = 160.0f - (PXX * cx + PZX * cz), fy = 172.0f - (PXY * cx + PZY * cz + PYY * H_GRASS);
+ ox = (float)iround(fx);
+ oy = (float)iround(fy);
+}
+
+static void draw_world(void) {
+ set_camera();
+ int top = (int)cam_z + 12, bot = (int)cam_z - 7;
+ for (int row = top; row >= bot; row--) {
+ draw_ground(row);
+ draw_lane_objects(row);
+ }
+ draw_parts();
+ if (eagle_on) draw_model_s(MD_EAGLE, eagle_x, eagle_y, eagle_z, 2.2f, 2.2f, 2.2f);
+}
+
+// ---------------------------------------------------------------------------
+// Text, in the original's blocky font (glyphs are in the constant data).
+
+static NOINLINE int glyph_index(char ch) {
+ for (int i = 0; font_chars[i]; i++)
+ if (font_chars[i] == ch) return i;
+ return -1;
+}
+
+static int text_width(const char *s, int sc) {
+ int w = 0;
+ for (; *s; s++) {
+ int g = glyph_index(*s);
+ w += (g < 0 ? 4 : font_w[g] + 2) * sc;
+ }
+ return w - 2 * sc;
+}
+
+// Draws text as vertical runs of font pixels. Each run's rectangle is grown by
+// (gl, gt, gr, gb) pixels; ext > 0 instead sweeps it up-right into a 3D slab
+// (the logo's extrusion). shear: vertical offset per font column, 1/256 px.
+static void draw_text_x(int x, int y, const char *s, int sc, int c, int shear, int gl, int gt, int gr, int gb, int ext) {
+ int cx = 0;
+ for (; *s; s++) {
+ int g = glyph_index(*s);
+ if (g < 0) {
+ cx += 4;
+ continue;
+ }
+ for (int col = 0; col < font_w[g]; col++) {
+ int dy = ((cx + col) * sc * shear) >> 8, bit = 0x800 >> col;
+ for (int row = 0; row < 10; row++) {
+ if (!(font[g][row] & bit)) continue;
+ int r1 = row;
+ while (r1 + 1 < 10 && (font[g][r1 + 1] & bit)) r1++;
+ int x0 = x + (cx + col) * sc - gl, x1 = x + (cx + col + 1) * sc + gr;
+ int y0 = y + row * sc + dy - gt, y1 = y + (r1 + 1) * sc + dy + gb;
+ if (ext) {
+ float px[6] = {x0, x1, x1 + ext, x1 + ext, x0 + ext, x0};
+ float py[6] = {y1, y1, y1 - 2 * ext, y0 - 2 * ext, y0 - 2 * ext, y0};
+ raster(px, py, 6, c);
+ } else {
+ fill_rect(x0, y0, x1 - x0, y1 - y0, c);
+ }
+ row = r1;
+ }
+ }
+ cx += font_w[g] + 2;
+ }
+}
+
+static void draw_text(int x, int y, const char *s, int sc, int c, int shear) {
+ draw_text_x(x, y, s, sc, c, shear, 0, 0, 0, 0, 0);
+}
+
+// Text with a black outline and a drop shadow, like the game's HUD.
+static void text_ol(int x, int y, const char *s, int sc, int c) {
+ draw_text_x(x, y, s, sc, C_OUTLINE, 0, 1, 1, 1, 2, 0);
+ draw_text(x, y, s, sc, c, 0);
+}
+
+static void itoa_(int v, char *buf) {
+ char t[12];
+ int n = 0;
+ do {
+ t[n++] = (char)('0' + v % 10);
+ v /= 10;
+ } while (v);
+ while (n) *buf++ = t[--n];
+ *buf = 0;
+}
+
+// ---------------------------------------------------------------------------
+// User interface
+
+static void draw_coin_icon(int x, int y) {
+ fill_rect(x + 3, y - 1, 10, 18, C_OUTLINE);
+ fill_rect(x - 1, y + 3, 18, 10, C_OUTLINE);
+ fill_rect(x + 1, y + 1, 14, 14, C_OUTLINE);
+ fill_rect(x + 3, y + 1, 10, 14, C_COIN);
+ fill_rect(x + 1, y + 3, 14, 10, C_COIN);
+ fill_rect(x + 5, y + 4, 6, 8, C_COIN_C);
+ fill_rect(x + 7, y + 6, 4, 4, C_COIN);
+}
+
+static void draw_coins_hud(void) {
+ char buf[12];
+ itoa_(coins, buf);
+ int w = text_width(buf, 2);
+ text_ol(SW - 28 - w, 6, buf, 2, C_GOLD);
+ draw_coin_icon(SW - 22, 8);
+}
+
+// Title logo: sheared blocky letters on a black 3D slab. t: 0 at rest, <0 entering, >0 leaving.
+static void draw_logo(float t) {
+ int dx = (int)(t * 220), dy = (int)(t * 60);
+ const int sc = 3, sh = 59;
+ const char *l1 = str_crossy, *l2 = str_road;
+ int w1 = text_width(l1, sc), w2 = text_width(l2, sc);
+ int x1 = 160 - w1 / 2 - 8 + dx, y1 = 8 + dy;
+ int x2 = x1 + (w1 - w2) / 2 + 3, y2 = y1 + 33 + (((x2 - x1) * sh) >> 8);
+ draw_text_x(x1, y1, l1, sc, C_OUTLINE, sh, 2, 2, 2, 2, 9);
+ draw_text_x(x2, y2, l2, sc, C_OUTLINE, sh, 2, 2, 2, 2, 9);
+ draw_text(x1, y1, l1, sc, C_WHITE, sh);
+ draw_text(x2, y2, l2, sc, C_WHITE, sh);
+}
+
+// Pointing hand (tap hint), from its 12x14 outline and fill masks.
+static void draw_hand(int x, int y) {
+ for (int r = 0; r < 14; r++)
+ for (int c = 0; c < 12; c++) {
+ int m = 0x800 >> c;
+ if (hand_ol[r] & m) fill_rect(x + c * 2, y + r * 2, 2, 2, C_OUTLINE);
+ else if (hand_in[r] & m) fill_rect(x + c * 2, y + r * 2, 2, 2, C_WHITE);
+ }
+}
+
+static void draw_tap_hint(void) {
+ float ph = st_time / 0.6f;
+ ph -= (int)ph;
+ int up = ph > 0.5f ? 4 : 0;
+ int x = (int)(sx_of(P.x, P.z)) + 2, y = (int)(sy_of(P.x, P.base, P.z)) + 14 - up;
+ draw_hand(x, y);
+ if (up) { // tap marks around the fingertip
+ fill_rect(x + 10, y - 9, 2, 5, C_WHITE);
+ fill_rect(x + 3, y - 7, 2, 2, C_WHITE);
+ fill_rect(x + 5, y - 5, 2, 2, C_WHITE);
+ fill_rect(x + 17, y - 7, 2, 2, C_WHITE);
+ fill_rect(x + 15, y - 5, 2, 2, C_WHITE);
+ }
+}
+
+static void draw_play_button(int cx, int y) {
+ fill_rect(cx - 33, y + 2, 66, 42, C_OUTLINE);
+ fill_rect(cx - 31, y, 62, 46, C_OUTLINE);
+ fill_rect(cx - 31, y + 2, 62, 42, C_WHITE);
+ fill_rect(cx - 29, y + 2, 58, 40, C_BTN);
+ fill_rect(cx - 29, y + 36, 58, 6, C_BTN_S);
+ for (int i = 0; i < 10; i++) fill_rect(cx - 9 + i * 2, y + 9 + i, 2, 22 - 2 * i, C_WHITE);
+}
+
+static void draw_pause(void) {
+ fill_rect(140, 94, 16, 48, C_OUTLINE);
+ fill_rect(164, 94, 16, 48, C_OUTLINE);
+ fill_rect(142, 96, 12, 44, C_WHITE);
+ fill_rect(166, 96, 12, 44, C_WHITE);
+}
+
+static void render(void) {
+ draw_world();
+ char buf[16];
+ if (state == ST_TITLE) {
+ if (show_logo) draw_logo(st_time < 0.25f ? (st_time - 0.25f) * 4 : 0);
+ draw_tap_hint();
+ } else {
+ if (state == ST_PLAY && show_logo && st_time < 0.25f) draw_logo(st_time * 4);
+ itoa_(score, buf);
+ int big = state == ST_OVER ? 3 : 2;
+ text_ol(6, 6, buf, big, C_WHITE);
+ if (state == ST_OVER) {
+ float t = clampf(st_time * 4, 0, 1);
+ int x = -90 + (int)(t * 96);
+ if (new_top) text_ol(x, 42, str_new_top, 1, C_WHITE);
+ else {
+ char tb[20] = "TOP ";
+ itoa_(top_score, tb + 4);
+ text_ol(x, 42, tb, 1, C_WHITE);
+ }
+ float u = clampf((st_time - 0.3f) * 5, 0, 1);
+ draw_play_button(160, SH + 4 - (int)(u * 66));
+ }
+ }
+ draw_coins_hud();
+ if (paused) draw_pause();
+}
+
+// ---------------------------------------------------------------------------
+// Persistence
+
+// The calculator keeps its files in RAM; the userland header of the running
+// firmware slot tells where. Top score and coins go in a tiny record named
+// "crossyroad.sav", written only after the whole file system checks out.
+#if (PLATFORM_DEVICE && !defined(HOST)) || defined(SAVE_TEST)
+#define FS_MAGIC 0xEE0BDDBAu
+#define SAVE_LEN 12
+
+static uint16_t rd16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); }
+static void wr16(uint8_t *p, uint32_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); }
+
+// Walks all records; returns the end marker position or 0 if anything looks wrong.
+static uint8_t *fs_walk(uint8_t **found) {
+ uint8_t *p = fs_buf, *end = fs_buf + fs_size;
+ *found = 0;
+ for (;;) {
+ if (p + 2 > end) return 0;
+ uint32_t n = rd16(p);
+ if (!n) return p;
+ if (n < 4 || p + n > end) return 0;
+ const char *a = (const char *)p + 2, *b = save_name;
+ while (*a && *a == *b) a++, b++;
+ if (!*a && !*b && n == 2 + sizeof(save_name) + SAVE_LEN) *found = p;
+ p += n;
+ }
+}
+
+#ifdef SAVE_TEST
+static void fs_locate(void) {
+ extern void *dlsym(void *, const char *);
+ uint8_t *fs = dlsym((void *)0, "_ZN3Ion7Storage10FileSystem16sharedFileSystemE");
+ if (!fs || *(uint32_t *)fs != FS_MAGIC) return;
+ fs_buf = fs + 4;
+ fs_size = 42 * 1024;
+}
+#else
+static void fs_locate(void) {
+ uint32_t me; // any address inside this app: this code's own
+ __asm__("mov %0, pc" : "=r"(me));
+ for (int i = 0; i < 2; i++) {
+ const volatile uint32_t *h = (const volatile uint32_t *)slots[i];
+ if (h[0] != 0xDEC0EDFEu || me < h[5] || me >= h[6]) continue;
+ uint32_t a = h[3], n = h[4];
+ if ((a & 3) || a < 0x20000000u || a > 0x24080000u || n < 4096 || n > 0x20000 || (n & 3)) continue;
+ const volatile uint32_t *st = (const volatile uint32_t *)a;
+ if (st[0] != FS_MAGIC || st[1 + n / 4] != FS_MAGIC) continue;
+ fs_buf = (uint8_t *)(a + 4);
+ fs_size = n;
+ uint8_t *f;
+ if (!fs_walk(&f)) fs_buf = 0;
+ return;
+ }
+}
+#endif
+
+static uint32_t save_sum(uint32_t a, uint32_t b) { return (a * 2654435761u) ^ (b + 0x5A17u); }
+
+static void load_save(void) {
+ fs_locate();
+ uint8_t *f;
+ if (!fs_buf || !fs_walk(&f) || !f) return;
+ const uint8_t *d = f + 2 + sizeof(save_name);
+ uint32_t v[3];
+ for (int i = 0; i < 3; i++) v[i] = d[4 * i] | d[4 * i + 1] << 8 | d[4 * i + 2] << 16 | (uint32_t)d[4 * i + 3] << 24;
+ if (save_sum(v[0], v[1]) != v[2] || v[0] > 1000000 || v[1] > 1000000) return;
+ top_score = (int)v[0];
+ coins = (int)v[1];
+}
+
+static NOINLINE void write_save(void) {
+ uint8_t *f, *end;
+ if (!fs_buf || !(end = fs_walk(&f))) return;
+ uint32_t n = 2 + sizeof(save_name) + SAVE_LEN;
+ if (!f) { // append a new record if it fits
+ if (end + n + 2 > fs_buf + fs_size) return;
+ f = end;
+ wr16(f + n, 0);
+ memcpy(f + 2, save_name, sizeof(save_name));
+ wr16(f, n);
+ }
+ uint32_t v[3] = {(uint32_t)top_score, (uint32_t)coins, save_sum((uint32_t)top_score, (uint32_t)coins)};
+ uint8_t *d = f + 2 + sizeof(save_name);
+ for (int i = 0; i < 3; i++)
+ for (int j = 0; j < 4; j++) d[4 * i + j] = (uint8_t)(v[i] >> (8 * j));
+}
+#else
+static void load_save(void) {}
+static void write_save(void) {}
+#endif
+
+// ---------------------------------------------------------------------------
+// Display
+
+static void present(void) {
+ const uint16_t *p = pal;
+ if (fade > 0) { // fade to white
+ int f = (int)(fade * 32);
+ if (f > 32) f = 32;
+ for (int i = 0; i < NCOLORS; i++) {
+ int c = pal[i], r = c >> 11, g = (c >> 5) & 63, b = c & 31;
+ r += ((31 - r) * f) >> 5;
+ g += ((63 - g) * f) >> 5;
+ b += ((31 - b) * f) >> 5;
+ fpal[i] = (uint16_t)(r << 11 | g << 5 | b);
+ }
+ p = fpal;
+ }
+ eadk_display_wait_for_vblank();
+ for (int y = 0; y < SH; y += STRIP) {
+ const uint8_t *s = fb + y * SW;
+ const uint32_t *s4 = (const uint32_t *)s;
+ uint32_t *d4 = (uint32_t *)strip;
+ for (int i = 0; i < SW * STRIP / 4; i++) {
+ uint32_t v = s4[i];
+ d4[2 * i] = p[v & 255] | (uint32_t)p[(v >> 8) & 255] << 16;
+ d4[2 * i + 1] = p[(v >> 16) & 255] | (uint32_t)p[v >> 24] << 16;
+ }
+ eadk_display_push_rect((eadk_rect_t){0, (uint16_t)y, SW, STRIP}, strip);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Main loop
+
+static void update(float dt) {
+ game_time += dt;
+ st_time += dt;
+ update_lanes(dt);
+ update_parts(dt);
+ if (state == ST_TITLE || state == ST_PLAY) {
+ update_player(dt);
+ if (state == ST_PLAY && !P.dead &&
+ (P.idle >= IDLE_EAGLE || P.row <= P.best - 3 || P.z < cam_z - 3.6f))
+ kill(D_EAGLE);
+ } else if (state == ST_DEAD || state == ST_OVER) {
+ update_dead(dt);
+ float wait = P.dead == D_EAGLE ? 1.1f : P.dead == D_PANCAKE ? 0.7f : 0.5f;
+ if (state == ST_DEAD && st_time > wait) {
+ state = ST_OVER;
+ st_time = 0;
+ if (score > top_score) {
+ top_score = score;
+ new_top = 1;
+ }
+ write_save();
+ }
+ }
+ if (state == ST_PLAY) score = P.best;
+ update_camera(dt);
+#ifdef HOST_DEBUG
+ {
+ extern int printf(const char *, ...);
+ static int fr;
+ fr++;
+ printf("f%d st%d dead%d x%.2f z%.2f y%.2f base%.2f row%d best%d hop%d t%.2f log%d vis%d cam%.2f,%.2f idle%.1f\n", fr, state, P.dead, P.x, P.z, P.y,
+ P.base, P.row, P.best, P.hop, P.t, P.log, P.visible, cam_x, cam_z, P.idle);
+ }
+#endif
+}
+
+#ifdef ROM_PACKED
+// Decoder for the packed tables (tools/pack_rom.py): per item a flag bit, then
+// a literal byte or an 8-bit distance and a 4-bit length.
+static void unpack(uint8_t *d, const uint8_t *s) {
+ uint32_t buf = 0;
+ int nb = 0;
+ for (uint8_t *end = d + sizeof(struct Rom); d < end;) {
+ while (nb < 16) {
+ buf = buf << 8 | *s++;
+ nb += 8;
+ }
+ if (buf >> --nb & 1) {
+ unsigned v = buf >> (nb -= 12);
+ const uint8_t *m = d - (v >> 4 & 255) - 1;
+ for (int k = (v & 15) + 2; k--;) *d++ = *m++;
+ } else {
+ *d++ = (uint8_t)(buf >> (nb -= 8));
+ }
+ }
+}
+#endif
+
+int main(int argc, char *argv[]) {
+ (void)argc;
+ (void)argv;
+#if PLATFORM_DEVICE && !defined(HOST)
+ struct State *caller_r9 = g9; // r9 belongs to the caller: given back on exit
+ g9 = &state_mem;
+ __asm__("" : "+r"(g9)); // keep using r9, not the address it was given
+#endif
+#ifdef ROM_PACKED
+ unpack((uint8_t *)&G.rom, rom_packed);
+#else
+ memcpy(&G.rom, &rom_init, sizeof(rom_init));
+#endif
+ init_palette();
+ build_models();
+ load_save();
+ new_game();
+ P.face = 2;
+ show_logo = 1;
+ uint64_t last = eadk_timing_millis(), prevk = ~(uint64_t)0;
+ for (;;) {
+ uint64_t k = eadk_keyboard_scan(), pr = k & ~prevk;
+ prevk = k;
+#define PRESSED(key) ((pr >> (key)) & 1)
+ int dir = -1;
+ if (PRESSED(eadk_key_up) || PRESSED(eadk_key_ok) || PRESSED(eadk_key_exe)) dir = 0;
+ else if (PRESSED(eadk_key_right)) dir = 1;
+ else if (PRESSED(eadk_key_down)) dir = 2;
+ else if (PRESSED(eadk_key_left)) dir = 3;
+ if (PRESSED(eadk_key_back)) {
+ if (state == ST_PLAY && !paused) paused = 1;
+ else if (paused) paused = 0;
+ else break;
+ }
+ if (paused) {
+ if (dir >= 0) paused = 0;
+ dir = -1;
+ }
+ if (dir >= 0 && !restarting) {
+ if (state == ST_TITLE) {
+ state = ST_PLAY;
+ st_time = 0;
+ }
+ if (state == ST_PLAY && !P.dead) {
+ if (P.hop) {
+ if (P.nq < 3) P.q[P.nq++] = dir;
+ } else {
+ start_hop(dir);
+ }
+ } else if (state == ST_OVER && st_time > 0.4f && dir == 0) {
+ restarting = 1;
+ restart_t = 0;
+ }
+ }
+ uint64_t now = eadk_timing_millis();
+ float dt = (float)(uint32_t)(now - last) * 0.001f;
+ last = now;
+ if (dt > 0.05f) dt = 0.05f;
+ if (restarting) {
+ restart_t += dt;
+ fade = restart_t < 0.2f ? restart_t * 5 : 2 - restart_t * 5;
+ if (restart_t >= 0.2f && restarting == 1) {
+ new_game();
+ P.face = 0;
+ show_logo = 0;
+ restarting = 2;
+ }
+ if (restart_t >= 0.4f) {
+ restarting = 0;
+ fade = 0;
+ }
+ }
+ if (!paused) {
+ int steps = dt > 0.017f ? 2 : 1;
+ for (int i = 0; i < steps; i++) update(dt / steps);
+ }
+ render();
+#ifdef HOST_STATS
+ { extern void stats_frame(void); stats_frame(); }
+#endif
+ present();
+ }
+#if PLATFORM_DEVICE && !defined(HOST)
+ g9 = caller_r9;
+#endif
+ return 0;
+}
diff --git a/games/crossyroad/src/nwa.ld b/games/crossyroad/src/nwa.ld
new file mode 100644
index 00000000..e0a4e07f
--- /dev/null
+++ b/games/crossyroad/src/nwa.ld
@@ -0,0 +1,11 @@
+/* Merge input sections for the relocatable .nwa output (fewer section headers).
+ The eadk sections keep their names: the installer's linker script needs them. */
+SECTIONS {
+ .rodata.eadk_app_name : { KEEP(*(.rodata.eadk_app_name)) }
+ .rodata.eadk_api_level : { KEEP(*(.rodata.eadk_api_level)) }
+ .rodata.eadk_app_icon : { KEEP(*(.rodata.eadk_app_icon)) }
+ .text : { *(.text .text.*) *(.rodata .rodata.*) }
+ .data : { *(.data .data.*) }
+ .bss : { *(.bss .bss.* COMMON) }
+ /DISCARD/ : { *(.comment) *(.ARM.attributes) *(.note*) }
+}
diff --git a/games/crossyroad/tests/arm_emu.py b/games/crossyroad/tests/arm_emu.py
new file mode 100644
index 00000000..91c92dc0
--- /dev/null
+++ b/games/crossyroad/tests/arm_emu.py
@@ -0,0 +1,130 @@
+#!/usr/bin/env python3
+"""Runs the real calculator build (ARM Cortex-M7 code, linked by nwlink) in the
+Unicorn CPU emulator. EADK calls are serviced here, with the same scripted input,
+clock and random numbers as host/host.c, so frames can be compared pixel by pixel.
+Also reports executed instructions per frame (a CPU cost estimate).
+
+Usage: arm_emu.py app.elf --frames N --shots 10,20 --keys "30:U,50:L" --out DIR
+"""
+import argparse
+import struct
+
+from elftools.elf.elffile import ELFFile
+from unicorn import UC_ARCH_ARM, UC_HOOK_BLOCK, UC_HOOK_CODE, UC_MODE_MCLASS, UC_MODE_THUMB, Uc
+from unicorn.arm_const import UC_ARM_REG_LR, UC_ARM_REG_PC, UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_SP
+
+KEYS = {"L": 0, "U": 1, "D": 2, "R": 3, "O": 4, "B": 5, "E": 52}
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("elf")
+ ap.add_argument("--frames", type=int, default=60)
+ ap.add_argument("--shots", default="")
+ ap.add_argument("--keys", default="")
+ ap.add_argument("--seed", type=int, default=2463534242)
+ ap.add_argument("--out", default=".")
+ a = ap.parse_args()
+ shots = {int(s) for s in a.shots.split(",") if s}
+ script = []
+ for item in filter(None, a.keys.split(",")):
+ rng, k = item.split(":")
+ lo, hi = (rng.split("-") + [rng])[:2]
+ script.append((int(lo), int(hi), KEYS[k]))
+
+ uc = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS)
+ elf = ELFFile(open(a.elf, "rb"))
+ uc.mem_map(0x90000000, 0x800000) # external flash (both firmware slots)
+ uc.mem_map(0x20000000, 0x40000)
+ uc.mem_map(0x30000000, 0x10000) # process stack
+ for seg in elf.iter_segments():
+ if seg["p_type"] == "PT_LOAD" and seg["p_filesz"]:
+ uc.mem_write(seg["p_paddr"], seg.data())
+ syms = {s.name: s["st_value"] for s in elf.get_section_by_name(".symtab").iter_symbols()}
+
+ st = {"frame": 0, "now": 0.0, "rng": a.seed & 0xFFFFFFFF, "insns": 0, "last": 0}
+ screen = bytearray(320 * 240 * 2)
+
+ def ret(uc, r0=None, r1=None):
+ if r0 is not None:
+ uc.reg_write(UC_ARM_REG_R0, r0 & 0xFFFFFFFF)
+ if r1 is not None:
+ uc.reg_write(UC_ARM_REG_R1, r1 & 0xFFFFFFFF)
+ uc.reg_write(UC_ARM_REG_PC, uc.reg_read(UC_ARM_REG_LR))
+
+ def push_rect(uc):
+ r0, r1, p = (uc.reg_read(r) for r in (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2))
+ x, y, w, h = r0 & 0xFFFF, r0 >> 16, r1 & 0xFFFF, r1 >> 16
+ data = uc.mem_read(p, w * h * 2)
+ for j in range(h):
+ o = ((y + j) * 320 + x) * 2
+ screen[o:o + w * 2] = data[j * w * 2:(j + 1) * w * 2]
+ ret(uc)
+
+ def dump(f):
+ with open("%s/a%05d.ppm" % (a.out, f), "wb") as fp:
+ fp.write(b"P6\n320 240\n255\n")
+ out = bytearray()
+ for i in range(0, len(screen), 2):
+ c = screen[i] | screen[i + 1] << 8
+ out += bytes((((c >> 11) & 31) * 255 // 31, ((c >> 5) & 63) * 255 // 63, (c & 31) * 255 // 31))
+ fp.write(out)
+
+ def vblank(uc):
+ f = st["frame"]
+ if f > 0 and f in shots:
+ dump(f)
+ if f > 0:
+ print("frame %4d: %8d instructions" % (f, st["insns"] - st["last"]))
+ st["last"] = st["insns"]
+ st["frame"] = f + 1
+ st["now"] += 1000.0 / 60.0
+ if st["frame"] > a.frames:
+ uc.emu_stop()
+ ret(uc, 1)
+
+ def keyboard(uc):
+ s = 0
+ for lo, hi, k in script:
+ if lo <= st["frame"] <= hi:
+ s |= 1 << k
+ ret(uc, s, s >> 32)
+
+ def millis(uc):
+ t = int(st["now"])
+ ret(uc, t, t >> 32)
+
+ def random(uc):
+ r = st["rng"]
+ r ^= (r << 13) & 0xFFFFFFFF
+ r ^= r >> 17
+ r ^= (r << 5) & 0xFFFFFFFF
+ st["rng"] = r
+ ret(uc, r)
+
+ handlers = {"eadk_display_push_rect": push_rect, "eadk_display_wait_for_vblank": vblank,
+ "eadk_keyboard_scan": keyboard, "eadk_timing_millis": millis, "eadk_random": random}
+ for name, fn in handlers.items():
+ addr = syms[name] & ~1
+ uc.hook_add(UC_HOOK_CODE, lambda uc, ad, sz, ud, fn=fn: fn(uc), begin=addr, end=addr)
+
+ ninsn = {}
+
+ def block(uc, addr, size, ud):
+ n = ninsn.get((addr, size))
+ if n is None: # count Thumb-2 instructions: 32-bit ones start with 0b11101/0b1111x
+ code, i, n = uc.mem_read(addr, size), 0, 0
+ while i < size:
+ i += 4 if (code[i + 1] >> 3) in (0x1D, 0x1E, 0x1F) else 2
+ n += 1
+ ninsn[(addr, size)] = n
+ st["insns"] += n
+ uc.hook_add(UC_HOOK_BLOCK, block)
+
+ uc.reg_write(UC_ARM_REG_SP, 0x30010000)
+ uc.reg_write(UC_ARM_REG_LR, 0xFFFFFFFF)
+ uc.emu_start(syms["_start"] | 1, 0xFFFFFFFE)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/games/crossyroad/tests/save_test.c b/games/crossyroad/tests/save_test.c
new file mode 100644
index 00000000..be9eaa29
--- /dev/null
+++ b/games/crossyroad/tests/save_test.c
@@ -0,0 +1,38 @@
+// Runs the game's save code against the real Epsilon file system inside the
+// native simulator: build as a .nwb and launch with --nwb.
+#define main crossy_main
+#include "../src/crossy.c"
+#undef main
+#include <stdio.h>
+#include <dlfcn.h>
+
+typedef int (*count_fn)(void *);
+typedef size_t (*size_fn)(void *);
+typedef uint32_t (*sum_fn)(void *);
+
+int main(void) {
+ memcpy(&G.rom, &rom_init, sizeof(rom_init)); // as crossy_main does first
+ void *fs = dlsym(RTLD_DEFAULT, "_ZN3Ion7Storage10FileSystem16sharedFileSystemE");
+ count_fn nrec = (count_fn)dlsym(RTLD_DEFAULT, "_ZNK3Ion7Storage10FileSystem15numberOfRecordsEv");
+ size_fn avail = (size_fn)dlsym(RTLD_DEFAULT, "_ZNK3Ion7Storage10FileSystem13availableSizeEv");
+ sum_fn sum = (sum_fn)dlsym(RTLD_DEFAULT, "_ZNK3Ion7Storage10FileSystem8checksumEv");
+ printf("fs=%p records=%d avail=%zu sum=%08x\n", fs, nrec(fs), avail(fs), sum(fs));
+ load_save();
+ printf("loaded top=%d coins=%d (fs_buf=%p)\n", top_score, coins, (void *)fs_buf);
+ top_score = 123; coins = 45;
+ write_save();
+ printf("after write: records=%d avail=%zu sum=%08x\n", nrec(fs), avail(fs), sum(fs));
+ top_score = 0; coins = 0;
+ load_save();
+ printf("reloaded top=%d coins=%d\n", top_score, coins);
+ top_score = 4567; coins = 89;
+ write_save();
+ printf("after rewrite: records=%d avail=%zu sum=%08x\n", nrec(fs), avail(fs), sum(fs));
+ top_score = 0; coins = 0;
+ load_save();
+ printf("reloaded top=%d coins=%d\n", top_score, coins);
+ // dump the record list as Epsilon stores it
+ uint8_t *p = fs_buf;
+ while (rd16(p)) { printf(" record %-24s size %u\n", (char *)p + 2, rd16(p)); p += rd16(p); }
+ return 0;
+}
diff --git a/games/crossyroad/tests/save_test2.c b/games/crossyroad/tests/save_test2.c
new file mode 100644
index 00000000..122c3d2c
--- /dev/null
+++ b/games/crossyroad/tests/save_test2.c
@@ -0,0 +1,53 @@
+// Save code vs. a file system that already holds records (created and
+// destroyed through Epsilon's own API), inside the native simulator.
+#define main crossy_main
+#include "../src/crossy.c"
+#undef main
+#include <stdio.h>
+#include <dlfcn.h>
+
+typedef int (*count_fn)(void *);
+typedef size_t (*size_fn)(void *);
+typedef int (*create_fn)(void *, const char *, const char *, const void *, size_t, bool);
+typedef int (*destroy_all_fn)(void *);
+
+static void dump(void) {
+ uint8_t *p = fs_buf;
+ while (rd16(p)) { printf(" %-20s %u\n", (char *)p + 2, rd16(p)); p += rd16(p); }
+}
+
+int main(void) {
+ memcpy(&G.rom, &rom_init, sizeof(rom_init)); // as crossy_main does first
+ void *fs = dlsym(RTLD_DEFAULT, "_ZN3Ion7Storage10FileSystem16sharedFileSystemE");
+ count_fn nrec = (count_fn)dlsym(RTLD_DEFAULT, "_ZNK3Ion7Storage10FileSystem15numberOfRecordsEv");
+ size_fn avail = (size_fn)dlsym(RTLD_DEFAULT, "_ZNK3Ion7Storage10FileSystem13availableSizeEv");
+ create_fn create = (create_fn)dlsym(RTLD_DEFAULT, "_ZN3Ion7Storage10FileSystem25createRecordWithExtensionEPKcS3_PKvmb");
+ static char big[20000];
+ memset(big, 'x', sizeof big);
+ printf("create a.py -> %d\n", create(fs, "a", "py", "print(1)\n", 10, false));
+ printf("create b.py -> %d\n", create(fs, "b", "py", big, 3000, false));
+ fs_locate();
+ load_save();
+ printf("load on foreign storage: top=%d coins=%d records=%d\n", top_score, coins, nrec(fs));
+ top_score = 77; coins = 5;
+ write_save();
+ printf("after write records=%d avail=%zu\n", nrec(fs), avail(fs));
+ printf("create c.py -> %d\n", create(fs, "c", "py", big, 5000, false));
+ dump();
+ top_score = coins = 0;
+ load_save();
+ printf("reload top=%d coins=%d\n", top_score, coins);
+ // fill the storage almost completely, then a new save must not overflow
+ printf("create d.py -> %d (avail %zu)\n", create(fs, "d", "py", big, avail(fs) - 20, false), avail(fs));
+ top_score = 99; coins = 6;
+ write_save(); // record exists: rewrite in place
+ top_score = coins = 0;
+ load_save();
+ printf("in-place update with full storage: top=%d coins=%d records=%d avail=%zu\n", top_score, coins, nrec(fs), avail(fs));
+ // simulate a missing record with a full storage: corrupt our name and try to save
+ uint8_t *f; fs_walk(&f); f[2] = 'X';
+ top_score = 5; write_save();
+ printf("append refused when full: records=%d avail=%zu\n", nrec(fs), avail(fs));
+ dump();
+ return 0;
+}
diff --git a/games/crossyroad/tools/icon_render.c b/games/crossyroad/tools/icon_render.c
new file mode 100644
index 00000000..0d1ac681
--- /dev/null
+++ b/games/crossyroad/tools/icon_render.c
@@ -0,0 +1,29 @@
+// Renders the app icon with the game's own renderer (host build, K overridden).
+#define main crossy_main
+#include "../src/crossy.c"
+#undef main
+#include <stdio.h>
+
+int main(void) {
+ init_palette();
+ memcpy(pal, base_pal, sizeof(base_pal));
+ build_models();
+ memset(fb, C_WATER_O, sizeof(fb));
+ ox = 24; oy = 67;
+ draw_model(MD_CHICKEN + 2, 0, 0, 0);
+ FILE *f = fopen("output/icon_big.ppm", "wb");
+ fprintf(f, "P6\n%d %d\n255\n", SW, SH);
+ for (int i = 0; i < SW * SH; i++) {
+ uint16_t c = pal[fb[i]];
+ unsigned char rgb[3] = {(unsigned char)((c >> 11) * 255 / 31), (unsigned char)(((c >> 5) & 63) * 255 / 63),
+ (unsigned char)((c & 31) * 255 / 31)};
+ fwrite(rgb, 1, 3, f);
+ }
+ fclose(f);
+ return 0;
+}
+uint32_t eadk_random(void) { return 1; }
+uint64_t eadk_timing_millis(void) { return 0; }
+bool eadk_display_wait_for_vblank(void) { return true; }
+void eadk_display_push_rect(eadk_rect_t r, const eadk_color_t *p) { (void)r; (void)p; }
+uint64_t eadk_keyboard_scan(void) { return 0; }
diff --git a/games/crossyroad/tools/make_icon.py b/games/crossyroad/tools/make_icon.py
new file mode 100644
index 00000000..cbccf1cf
--- /dev/null
+++ b/games/crossyroad/tools/make_icon.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python3
+"""Draws the 55x56 app icon: the voxel chicken's face on sky blue.
+Axis-aligned blocks keep rows identical so the LZ4-compressed icon stays tiny."""
+from PIL import Image, ImageDraw
+
+SKY = (144, 236, 252)
+WHITE, LIGHT, SIDE = (255, 255, 255), (222, 222, 222), (144, 144, 144)
+COMB, COMB_S = (239, 130, 131), (160, 72, 70)
+BEAK, BEAK_S = (240, 146, 107), (176, 96, 60)
+WATTLE, EYE = (214, 70, 72), (31, 17, 13)
+
+im = Image.new("RGB", (55, 56), SKY)
+d = ImageDraw.Draw(im)
+def box(x0, y0, x1, y1, c):
+ d.rectangle((x0, y0, x1 - 1, y1 - 1), fill=c)
+
+box(8, 50, 46, 56, WHITE) # shoulders
+box(46, 50, 50, 56, SIDE)
+box(12, 12, 42, 17, WHITE) # head top
+box(42, 14, 46, 50, SIDE) # head side
+box(12, 17, 42, 50, LIGHT) # head front
+box(21, 5, 33, 9, COMB) # comb
+box(21, 9, 33, 13, COMB_S)
+box(16, 23, 19, 28, EYE) # eyes
+box(35, 23, 38, 28, EYE)
+box(22, 29, 32, 32, BEAK) # beak
+box(22, 32, 32, 36, BEAK_S)
+box(24, 36, 30, 42, WATTLE) # wattle
+im.save("assets/icon.png")
diff --git a/games/crossyroad/tools/nwa_min.py b/games/crossyroad/tools/nwa_min.py
new file mode 100644
index 00000000..3a32ed20
--- /dev/null
+++ b/games/crossyroad/tools/nwa_min.py
@@ -0,0 +1,174 @@
+#!/usr/bin/env python3
+"""Shrink a NumWorks .nwa (relocatable ARM ELF) without changing what gets installed.
+
+- Resolves Thumb branches between functions of the same .text section
+ (they are position independent), keeping only relocations the installer needs.
+- Keeps only the symbols those relocations and the loader reference.
+- Merges the symbol and section name tables and drops everything else.
+
+Usage: nwa_min.py in.nwa out.nwa
+"""
+import struct
+import sys
+
+R_ARM_THM_CALL, R_ARM_THM_JUMP24 = 10, 30
+SHT_SYMTAB, SHT_STRTAB, SHT_REL, SHT_NOBITS = 2, 3, 9, 8
+KEEP_GLOBALS = {b"main", b"eadk_app_name", b"eadk_app_icon", b"eadk_api_level"}
+
+
+def main(src, dst):
+ d = bytearray(open(src, "rb").read())
+ assert d[:4] == b"\x7fELF" and d[4] == 1 and d[5] == 1, "ELF32 LE expected"
+ e_shoff, = struct.unpack_from("<I", d, 0x20)
+ e_shentsize, e_shnum, e_shstrndx = struct.unpack_from("<HHH", d, 0x2E)
+ secs = []
+ for i in range(e_shnum):
+ f = struct.unpack_from("<IIIIIIIIII", d, e_shoff + i * e_shentsize)
+ secs.append(dict(zip("name type flags addr off size link info align entsize".split(), f)))
+ shstr = secs[e_shstrndx]
+
+ def secname(s):
+ o = shstr["off"] + s["name"]
+ return bytes(d[o:d.index(b"\0", o)])
+
+ for s in secs:
+ s["sname"] = secname(s)
+ symtab_i = next(i for i, s in enumerate(secs) if s["type"] == SHT_SYMTAB)
+ symtab = secs[symtab_i]
+ strtab = secs[symtab["link"]]
+ syms = []
+ for i in range(symtab["size"] // 16):
+ name, value, size, info, other, shndx = struct.unpack_from("<IIIBBH", d, symtab["off"] + 16 * i)
+ o = strtab["off"] + name
+ syms.append(dict(name=bytes(d[o:d.index(b"\0", o)]), value=value, size=size, info=info, other=other, shndx=shndx))
+ text_i = next(i for i, s in enumerate(secs) if s["sname"] == b".text")
+ text = secs[text_i]
+
+ # 1. resolve intra-.text Thumb branches, keep the rest
+ kept_rel = {}
+ for i, s in enumerate(secs):
+ if s["type"] != SHT_REL:
+ continue
+ target = s["info"]
+ out = []
+ for k in range(s["size"] // 8):
+ off, info = struct.unpack_from("<II", d, s["off"] + 8 * k)
+ typ, si = info & 255, info >> 8
+ sym = syms[si]
+ if target == text_i and typ in (R_ARM_THM_CALL, R_ARM_THM_JUMP24) and sym["shndx"] == text_i:
+ p = text["off"] + off
+ h, l = struct.unpack_from("<HH", d, p)
+ # decode the addend held in the instruction (BL/B.W encoding T4)
+ sbit = (h >> 10) & 1
+ j1, j2 = (l >> 13) & 1, (l >> 11) & 1
+ i1, i2 = 1 - (j1 ^ sbit), 1 - (j2 ^ sbit)
+ imm = (sbit << 24) | (i1 << 23) | (i2 << 22) | ((h & 0x3FF) << 12) | ((l & 0x7FF) << 1)
+ if sbit:
+ imm -= 1 << 25
+ dest = (sym["value"] & ~1) + imm - off
+ assert -(1 << 24) <= dest < (1 << 24) and dest % 2 == 0
+ v = dest & ((1 << 25) - 1)
+ sbit = (v >> 24) & 1
+ i1, i2 = (v >> 23) & 1, (v >> 22) & 1
+ j1, j2 = (1 - i1) ^ sbit, (1 - i2) ^ sbit
+ h = (h & 0xF800) | (sbit << 10) | ((v >> 12) & 0x3FF)
+ l = (l & 0xD000) | (j1 << 13) | (j2 << 11) | ((v >> 1) & 0x7FF)
+ if typ == R_ARM_THM_CALL and not (sym["value"] & 1):
+ raise SystemExit("BL to ARM code not supported")
+ struct.pack_into("<HH", d, p, h, l)
+ else:
+ out.append((off, typ, si))
+ kept_rel[i] = out
+
+ # 2. symbols still needed
+ need = set()
+ for rels in kept_rel.values():
+ need.update(si for _, _, si in rels)
+ for i, s in enumerate(syms):
+ if s["name"] in KEEP_GLOBALS and s["shndx"] != 0:
+ need.add(i)
+ need.discard(0)
+
+ # 3. new section list: drop symtab/strtab/shstrtab (rebuilt) and empty rel sections
+ keep = [i for i, s in enumerate(secs) if i and s["type"] not in (SHT_SYMTAB, SHT_STRTAB)
+ and not (s["type"] == SHT_REL and not kept_rel[i])]
+ newidx = {old: n + 1 for n, old in enumerate(keep)}
+ n_symtab = len(keep) + 1
+ n_strtab = n_symtab + 1
+
+ # one string table for symbol and section names; longer names first so
+ # shorter ones can reuse their tails (".rel.text" holds ".text")
+ names_needed = {syms[i]["name"] for i in need if (syms[i]["info"] & 15) != 3}
+ names_needed |= {secs[i]["sname"] for i in keep} | {b".symtab", b".strtab"}
+ strtab_b = bytearray(b"\0")
+ for b in sorted(names_needed - {b""}, key=lambda b: (-len(b), b)):
+ if strtab_b.find(b + b"\0") < 0:
+ strtab_b.extend(b + b"\0")
+
+ def addstr(b):
+ return strtab_b.find(b + b"\0") if b else 0
+
+ # symbols: null, locals first, then globals
+ order = sorted(need, key=lambda i: (syms[i]["info"] >> 4) != 0)
+ symmap = {0: 0}
+ symbytes = bytearray(16)
+ nlocal = 1
+ for i in order:
+ s = syms[i]
+ sh = s["shndx"]
+ if 0 < sh < 0xFF00:
+ sh = newidx[sh]
+ nm = 0 if (s["info"] & 15) == 3 else addstr(s["name"]) # section symbols are unnamed
+ symbytes += struct.pack("<IIIBBH", nm, s["value"], s["size"], s["info"], s["other"], sh)
+ symmap[i] = len(symmap)
+ if (s["info"] >> 4) == 0:
+ nlocal += 1
+
+ names = {i: addstr(secs[i]["sname"]) for i in keep}
+ rel_names = {}
+ nm_symtab, nm_strtab = addstr(b".symtab"), addstr(b".strtab")
+
+ body = bytearray(52)
+ headers = [struct.pack("<IIIIIIIIII", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)]
+
+ def align(a):
+ while len(body) % a:
+ body.append(0)
+
+ for i in keep:
+ s = secs[i]
+ a = max(s["align"], 1)
+ if s["type"] == SHT_REL:
+ data = b"".join(struct.pack("<II", off, (symmap[si] << 8) | typ) for off, typ, si in kept_rel[i])
+ link, info = n_symtab, newidx[s["info"]]
+ a = 4
+ else:
+ data = b"" if s["type"] == SHT_NOBITS else bytes(d[s["off"]:s["off"] + s["size"]])
+ link, info = s["link"], s["info"]
+ align(a)
+ off = len(body)
+ body += data
+ size = s["size"] if s["type"] == SHT_NOBITS else len(data)
+ headers.append(struct.pack("<IIIIIIIIII", names[i], s["type"], s["flags"], s["addr"], off, size, link, info,
+ a, s["entsize"] if s["type"] != SHT_REL else 8))
+ align(4)
+ off = len(body)
+ body += symbytes
+ headers.append(struct.pack("<IIIIIIIIII", nm_symtab, SHT_SYMTAB, 0, 0, off, len(symbytes), n_strtab, nlocal, 4, 16))
+ off = len(body)
+ body += strtab_b
+ headers.append(struct.pack("<IIIIIIIIII", nm_strtab, SHT_STRTAB, 0, 0, off, len(strtab_b), 0, 0, 1, 0))
+ align(4)
+ shoff = len(body)
+ body += b"".join(headers)
+ hdr = bytearray(d[:52])
+ struct.pack_into("<I", hdr, 0x20, shoff)
+ struct.pack_into("<HHH", hdr, 0x2E, 40, len(headers), n_strtab)
+ body[:52] = hdr
+ open(dst, "wb").write(body)
+ print("%s: %d -> %d bytes (%d relocations kept, %d symbols)" % (dst, len(d), len(body),
+ sum(len(v) for v in kept_rel.values()), len(symmap)))
+
+
+if __name__ == "__main__":
+ main(sys.argv[1], sys.argv[2])
diff --git a/games/crossyroad/tools/pack_rom.py b/games/crossyroad/tools/pack_rom.py
new file mode 100644
index 00000000..1b6518c5
--- /dev/null
+++ b/games/crossyroad/tools/pack_rom.py
@@ -0,0 +1,95 @@
+#!/usr/bin/env python3
+"""Pull the constant tables (symbol rom_init) out of a compiled ARM object and
+write them compressed as a C byte list, for the calculator build.
+
+Format (bits, most significant first): per item a flag bit, then either a
+literal byte (flag 0) or a match (flag 1): 8 bits distance - 1 and 4 bits
+length - 2. The parse is optimal. Standard library only.
+
+Usage: pack_rom.py crossy.o rom.inc
+"""
+import struct
+import sys
+
+MIN_LEN, MAX_LEN, MAX_DIST = 2, 17, 256
+
+
+def symbol_bytes(path, name):
+ d = open(path, "rb").read()
+ shoff, = struct.unpack_from("<I", d, 0x20)
+ shentsize, shnum = struct.unpack_from("<HH", d, 0x2E)
+ secs = [struct.unpack_from("<IIIIIIIIII", d, shoff + i * shentsize) for i in range(shnum)]
+ for s in secs:
+ if s[1] != 2: # SHT_SYMTAB
+ continue
+ strtab = secs[s[6]]
+ for k in range(s[5] // 16):
+ st_name, value, size, info, other, shndx = struct.unpack_from("<IIIBBH", d, s[4] + 16 * k)
+ o = strtab[4] + st_name
+ if d[o:d.index(b"\0", o)] == name:
+ return d[secs[shndx][4] + value:secs[shndx][4] + value + size]
+ raise SystemExit("symbol %s not found" % name.decode())
+
+
+def pack(raw):
+ n = len(raw)
+ cost, step = [0] * (n + 1), [None] * n
+ for i in range(n - 1, -1, -1):
+ cost[i], step[i] = cost[i + 1] + 9, None
+ for j in range(max(0, i - MAX_DIST), i):
+ k = 0
+ while i + k < n and k < MAX_LEN and raw[j + k] == raw[i + k]:
+ k += 1
+ for m in range(MIN_LEN, k + 1):
+ if cost[i + m] + 13 < cost[i]:
+ cost[i], step[i] = cost[i + m] + 13, (i - j, m)
+ bits, i = [], 0
+
+ def put(v, k):
+ bits.extend((v >> b) & 1 for b in range(k - 1, -1, -1))
+ while i < n:
+ if step[i] is None:
+ put(raw[i], 9)
+ i += 1
+ else:
+ dist, m = step[i]
+ put(1, 1)
+ put(dist - 1, 8)
+ put(m - MIN_LEN, 4)
+ i += m
+ bits += [0] * (-len(bits) % 8 + 16) # the decoder reads up to two bytes ahead
+ return bytes(sum(b << (7 - k) for k, b in enumerate(bits[p:p + 8])) for p in range(0, len(bits), 8))
+
+
+def unpack(data, n): # reference decoder
+ out, pos = bytearray(), 0
+
+ def get(k):
+ nonlocal pos
+ v = 0
+ for _ in range(k):
+ v = v << 1 | (data[pos >> 3] >> (7 - (pos & 7)) & 1)
+ pos += 1
+ return v
+ while len(out) < n:
+ if get(1):
+ dist, m = get(8) + 1, get(4) + MIN_LEN
+ for _ in range(m):
+ out.append(out[-dist])
+ else:
+ out.append(get(8))
+ return bytes(out)
+
+
+def main(src, dst):
+ raw = symbol_bytes(src, b"rom_init")
+ packed = pack(raw)
+ assert unpack(packed, len(raw)) == raw
+ with open(dst, "w") as f:
+ for i in range(0, len(packed), 16):
+ f.write(", ".join(str(b) for b in packed[i:i + 16]) + ",\n")
+ print("%s: %d bytes of tables -> %d" % (dst, len(raw), len(packed)))
+
+
+if __name__ == "__main__":
+ main(sys.argv[1], sys.argv[2])
diff --git a/games/crossyroad/tools/png2nwi.py b/games/crossyroad/tools/png2nwi.py
new file mode 100644
index 00000000..a0fe8654
--- /dev/null
+++ b/games/crossyroad/tools/png2nwi.py
@@ -0,0 +1,112 @@
+#!/usr/bin/env python3
+"""PNG -> NWI (raw LZ4 block of RGB565 little-endian pixels), the icon format of
+NumWorks apps. Uses an exhaustive match search, so icons come out much smaller
+than with nwlink's encoder. Standard library only.
+
+Usage: png2nwi.py icon.png icon.nwi
+"""
+import struct
+import sys
+import zlib
+
+
+def read_png(path):
+ data = open(path, "rb").read()
+ assert data[:8] == b"\x89PNG\r\n\x1a\n", "not a PNG"
+ pos, idat, w = 8, b"", 0
+ while pos < len(data):
+ n, typ = struct.unpack(">I4s", data[pos:pos + 8])
+ body = data[pos + 8:pos + 8 + n]
+ if typ == b"IHDR":
+ w, h, depth, ctype, _, _, interlace = struct.unpack(">IIBBBBB", body)
+ assert depth == 8 and ctype in (2, 6) and not interlace, "8-bit RGB/RGBA PNG expected"
+ bpp = 3 if ctype == 2 else 4
+ elif typ == b"IDAT":
+ idat += body
+ pos += 12 + n
+ raw = zlib.decompress(idat)
+ stride = w * bpp
+ rows, prev = [], bytearray(stride)
+ for y in range(h):
+ f = raw[y * (stride + 1)]
+ line = bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)])
+ for i in range(stride):
+ a = line[i - bpp] if i >= bpp else 0
+ b, c = prev[i], prev[i - bpp] if i >= bpp else 0
+ if f == 1: line[i] = (line[i] + a) & 255
+ elif f == 2: line[i] = (line[i] + b) & 255
+ elif f == 3: line[i] = (line[i] + (a + b) // 2) & 255
+ elif f == 4:
+ p = a + b - c
+ pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
+ line[i] = (line[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 255
+ rows.append(line)
+ prev = line
+ return w, h, bpp, rows
+
+
+def lz4_block(src):
+ n, out, anchor, i = len(src), bytearray(), 0, 0
+ limit = n - 12 # a match may not start in the last 12 bytes
+
+ def emit(lit, mlen, off):
+ tok_l, tok_m = min(len(lit), 15), 0 if mlen is None else min(mlen - 4, 15)
+ out.append(tok_l << 4 | tok_m)
+ if len(lit) >= 15:
+ r = len(lit) - 15
+ while r >= 255: out.append(255); r -= 255
+ out.append(r)
+ out.extend(lit)
+ if mlen is not None:
+ out.extend(struct.pack("<H", off))
+ if mlen - 4 >= 15:
+ r = mlen - 4 - 15
+ while r >= 255: out.append(255); r -= 255
+ out.append(r)
+
+ seen = {} # 4-byte prefix -> positions
+
+ def add(p):
+ if p + 4 <= n:
+ seen.setdefault(src[p:p + 4], []).append(p)
+
+ while i < limit:
+ best_len, best_off = 0, 0
+ for j in reversed(seen.get(src[i:i + 4], ())):
+ if i - j > 65535:
+ break
+ k = 4
+ while i + k < n - 5 and src[j + k] == src[i + k]:
+ k += 1
+ if k > best_len:
+ best_len, best_off = k, i - j
+ if best_len >= 4 and i + best_len > n - 5:
+ best_len = n - 5 - i
+ if best_len >= 4:
+ emit(src[anchor:i], best_len, best_off)
+ for p in range(i, i + best_len):
+ add(p)
+ i += best_len
+ anchor = i
+ else:
+ add(i)
+ i += 1
+ emit(src[anchor:], None, 0)
+ return bytes(out)
+
+
+def main(src, dst):
+ w, h, bpp, rows = read_png(src)
+ assert (w, h) == (55, 56), "NumWorks icons are 55x56"
+ px = bytearray()
+ for line in rows:
+ for x in range(w):
+ r, g, b = line[x * bpp:x * bpp + 3]
+ px += struct.pack("<H", (r >> 3) << 11 | (g >> 2) << 5 | b >> 3)
+ blob = lz4_block(bytes(px))
+ open(dst, "wb").write(blob)
+ print("%s: %d bytes of pixels -> %d bytes" % (dst, len(px), len(blob)))
+
+
+if __name__ == "__main__":
+ main(sys.argv[1], sys.argv[2])
diff --git a/games/games.json b/games/games.json
new file mode 100644
index 00000000..96f96add
--- /dev/null
+++ b/games/games.json
@@ -0,0 +1,62 @@
+[
+ {
+ "id": "numdash",
+ "title": "NumDash",
+ "tagline": "Geometry Dash, with the real levels",
+ "credit": null,
+ "top": "0x3D6BFF",
+ "bottom": "0x14124F",
+ "accent": "0x35C759",
+ "records": ["numdash.nds", "numdash.ndd", "numdash1.ndl", "numdash2.ndl", "numdash3.ndl"],
+ "shots": ["docs/screenshots/menu.png", "docs/screenshots/gameplay.png", "docs/screenshots/level-complete.png"],
+ "repo": "https://github.com/Mason363/NumDash"
+ },
+ {
+ "id": "crossyroad",
+ "title": "Crossy Road",
+ "tagline": "Hop across roads, rivers and rails",
+ "credit": null,
+ "top": "0x45B649",
+ "bottom": "0x10421C",
+ "accent": "0xFF8A1F",
+ "records": ["crossyroad.sav"],
+ "shots": ["screenshots/title.png", "screenshots/river.png", "screenshots/train.png"],
+ "repo": "https://github.com/Mason363/CrossyWorks"
+ },
+ {
+ "id": "numdrive",
+ "title": "NumDrive",
+ "tagline": "157 levels of Drive Mad style physics",
+ "credit": null,
+ "top": "0x35A8F0",
+ "bottom": "0x123A63",
+ "accent": "0xFFB020",
+ "records": ["drivemad.sav"],
+ "shots": ["docs/shot1.png", "docs/shot2.png", "docs/shot3.png"],
+ "repo": "https://github.com/Mason363/NumDrive"
+ },
+ {
+ "id": "tetris",
+ "title": "Tetris",
+ "tagline": "The classic, full screen. By Tatone26",
+ "credit": "Tatone26",
+ "top": "0x8A4DFF",
+ "bottom": "0x1E0B45",
+ "accent": "0xFF4FA3",
+ "records": ["tetris.sav", "tetris.set"],
+ "shots": ["docs/shot1.png", "docs/shot2.png", "docs/shot3.png"],
+ "repo": "https://github.com/Tatone26/Numworks-games/tree/main/apps/tetris"
+ },
+ {
+ "id": "chess",
+ "title": "Chess",
+ "tagline": "12 bots, endless puzzles, 2 players",
+ "credit": null,
+ "top": "0x7FA650",
+ "bottom": "0x22211E",
+ "accent": "0x81B64C",
+ "records": [],
+ "shots": ["docs/italian.png", "docs/bots.png", "docs/puzzle-mate1.png"],
+ "repo": "https://github.com/Mason363/NumChess"
+ }
+]
diff --git a/games/numdash/.gitignore b/games/numdash/.gitignore
new file mode 100644
index 00000000..762303b8
--- /dev/null
+++ b/games/numdash/.gitignore
@@ -0,0 +1,9 @@
+build/
+node_modules/
+*.ndsave
+*.tmp
+__pycache__/
+.DS_Store
+tools/fonts/*.ttf
+numdash.store
+numdash.store.tmp
diff --git a/games/numdash/LICENSES/OFL-1.1-Nunito.txt b/games/numdash/LICENSES/OFL-1.1-Nunito.txt
new file mode 100644
index 00000000..c8210f08
--- /dev/null
+++ b/games/numdash/LICENSES/OFL-1.1-Nunito.txt
@@ -0,0 +1,93 @@
+Copyright 2014 The Nunito Project Authors (https://github.com/googlefonts/nunito)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/games/numdash/LICENSES/OFL-1.1-RammettoOne.txt b/games/numdash/LICENSES/OFL-1.1-RammettoOne.txt
new file mode 100644
index 00000000..035fdde7
--- /dev/null
+++ b/games/numdash/LICENSES/OFL-1.1-RammettoOne.txt
@@ -0,0 +1,93 @@
+Copyright 2011 The Rammetto Project Authors (https://github.com/googlefonts/RammettoFont), with Reserved Font Name Rammetto.
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://openfontlicense.org
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/games/numdash/Makefile b/games/numdash/Makefile
new file mode 100644
index 00000000..45c6a939
--- /dev/null
+++ b/games/numdash/Makefile
@@ -0,0 +1,67 @@
+ARM_CC ?= arm-none-eabi-gcc
+CC = cc
+PYTHON ?= python3
+NWLINK = node node_modules/nwlink/bin/nwlink
+WARN = -Wall -Wextra -Werror -Wno-misleading-indentation
+CORE = src/game.c src/level.c src/inflate.c src/leveldata.c src/objdefs.c src/assets.c src/gfx.c src/scene.c src/fx.c src/save.c
+COMMON = $(CORE) src/ui.c src/app.c src/menu.c src/play.c src/editor.c
+DEVICE_SOURCES = $(COMMON) src/platform_eadk.c src/main.c
+DEVICE_OBJECTS = $(patsubst src/%.c,build/arm/%.o,$(DEVICE_SOURCES))
+HEADERS = $(wildcard src/*.h)
+ARM_FLAGS = -std=c11 -O2 -fno-math-errno $(WARN) -ffunction-sections -fdata-sections -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal $(shell $(NWLINK) eadk-cflags-device 2>/dev/null)
+ARM_LINK = -Wl,--relocatable -nostartfiles --specs=nano.specs -Wl,--gc-sections -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level -flinker-output=nolto-rel
+.PHONY: all build simulator test check clean levels assets run epsilon-app
+all: build
+build: build/numdash.nwa
+node_modules/nwlink/bin/nwlink: package.json package-lock.json
+ npm ci
+ touch $@
+# Regenerates the level data and artwork (needs Python 3 with numpy and Pillow).
+levels:
+ $(PYTHON) tools/levels.py
+assets:
+ $(PYTHON) tools/assets.py
+build/.stamp:
+ mkdir -p build
+ touch $@
+build/icon.o: assets/icon.png node_modules/nwlink/bin/nwlink | build/.stamp
+ $(NWLINK) png-icon-o $< $@
+build/arm/%.o: src/%.c $(HEADERS) node_modules/nwlink/bin/nwlink | build/.stamp
+ mkdir -p build/arm
+ $(ARM_CC) $(ARM_FLAGS) -c $< -o $@
+build/numdash.nwa: $(DEVICE_OBJECTS) build/icon.o | build/.stamp
+ $(ARM_CC) $(ARM_FLAGS) $(ARM_LINK) $(DEVICE_OBJECTS) build/icon.o -lm -o $@
+check: build/numdash.nwa
+ $(NWLINK) nwa-bin $< build/numdash.bin
+simulator: build/numdash-sim
+build/numdash-sim: $(COMMON) src/platform_sdl.c src/main.c $(HEADERS) | build/.stamp
+ $(CC) -std=c11 -O2 $(WARN) -Isrc $$(sdl2-config --cflags) $(COMMON) src/platform_sdl.c src/main.c $$(sdl2-config --libs) -lm -o $@
+build/tests: $(COMMON) tests/test.c $(HEADERS) | build/.stamp
+ $(CC) -std=c11 -O1 -g $(WARN) -fsanitize=address,undefined -fno-omit-frame-pointer -Isrc $(COMMON) tests/test.c -lm -o $@
+test: build/tests
+ ./build/tests
+ @for i in 1 2 3 4 5 6 7; do ./build/tests --replay $$((i-1)) tests/replays/level$$i.txt || exit 1; done
+ ./build/tests --monkey 1 60000
+ ./build/tests --monkey 2 60000
+run: simulator
+ ./build/numdash-sim
+# Native module for the official Epsilon simulator (nwlink >= 0.0.19).
+epsilon-app: | build/.stamp
+ $(CC) -std=c11 -O2 -Isrc $(shell $(NWLINK) eadk-cflags-simulator) $(COMMON) src/platform_eadk.c src/main.c $(shell $(NWLINK) eadk-ldflags-simulator) -Wl,-undefined,dynamic_lookup -o build/numdash.nwb
+clean:
+ rm -rf build
+
+# NumPlay launcher: the game as a module (see ../../tools/npmodule.py) for the
+# calculator, and as a relocatable object for the simulator build.
+.PHONY: module sim-module
+module: build/module.o
+build/module.o: $(DEVICE_OBJECTS) | build/.stamp
+ $(ARM_CC) $(ARM_FLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel \
+ $(DEVICE_OBJECTS) -o $@
+
+sim-module: build/sim-module.o
+build/sim-module.o: $(COMMON) src/platform_eadk.c src/main.c $(HEADERS) node_modules/nwlink/bin/nwlink | build/.stamp
+ mkdir -p build/sim
+ for f in $(COMMON) src/platform_eadk.c src/main.c; do cc -std=c11 -O2 -fPIC -fvisibility=hidden -Isrc \
+ $(shell $(NWLINK) eadk-cflags-simulator) -Dmain=np_numdash_main -c $$f -o build/sim/$$(basename $$f .c).o || exit 1; done
+ ld -r build/sim/*.o -exported_symbol _np_numdash_main -o $@
diff --git a/games/numdash/README.md b/games/numdash/README.md
new file mode 100644
index 00000000..00c96833
--- /dev/null
+++ b/games/numdash/README.md
@@ -0,0 +1,91 @@
+# NumDash
+
+**Geometry Dash on your NumWorks calculator.**
+
+NumDash is a fan-made version of Geometry Dash that runs right on a NumWorks graphing calculator. Jump over spikes, fly the ship, collect secret coins and try to beat the first seven levels of the real game, all with the calculator's keys.
+
+### [⬇ Download NumDash.nwa](https://github.com/Mason363/NumDash/releases/latest/download/NumDash.nwa)
+
+<img src="docs/screenshots/menu.png" width="640" alt="The NumDash main menu">
+
+## How to install it
+
+You only need the calculator, its USB cable and a computer with Chrome or Edge.
+
+1. **Download** [NumDash.nwa](https://github.com/Mason363/NumDash/releases/latest/download/NumDash.nwa) (the button above).
+2. **Plug** your calculator into the computer with the USB cable.
+3. **Open** [my.numworks.com/apps](https://my.numworks.com/apps) and follow the steps to send the file to your calculator.
+4. **Play:** on the calculator, press the Home key and open **NumDash**.
+
+That's it. Your progress is saved on the calculator, so you can close the game and come back later.
+
+> NumDash is made for the **NumWorks N0120** (the newest model). The website above tells you which model you have.
+
+## What's inside
+
+### The real levels
+
+Stereo Madness, Back on Track, Polargeist, Dry Out, Base After Base, Can't Let Go and Jumper, with the same obstacles, colour changes and 3 hidden coins in each one.
+
+<img src="docs/screenshots/level-select.png" width="320" alt="Picking a level"> <img src="docs/screenshots/gameplay.png" width="320" alt="Jumping through Stereo Madness">
+
+### It plays like the original
+
+The jump, the gravity, the ship and every pad and orb behave like they do in Geometry Dash, so the timing you already know works here too.
+
+<img src="docs/screenshots/ship.png" width="320" alt="Flying the ship"> <img src="docs/screenshots/pause.png" width="320" alt="The pause menu">
+
+### Practice mode
+
+Pause the game and pick the green diamond to practice. Press **0** to drop a checkpoint and you'll restart from there instead of from the beginning.
+
+### The level complete moment
+
+Beat a level and you get the light rays, the fireworks, the big "Level Complete!" and your stats, just like the game.
+
+<img src="docs/screenshots/level-complete.png" width="320" alt="Level complete"> <img src="docs/screenshots/results.png" width="320" alt="Your results after beating a level">
+
+### Make it yours
+
+Pick your icon colours in the icon kit, change settings like the progress bar or low detail mode, and build your own levels in the level editor (3 save slots).
+
+<img src="docs/screenshots/icon-kit.png" width="320" alt="The icon kit"> <img src="docs/screenshots/editor.png" width="320" alt="The level editor">
+
+## Controls
+
+| Key | What it does |
+| --- | --- |
+| **OK**, **EXE** or **Up** | Jump. Hold it to keep jumping, or to fly up in the ship |
+| **Back** | Pause the game, or go back in menus |
+| **Arrows** | Move around the menus |
+| **0** | Place a checkpoint (in practice mode) |
+| **Backspace** | Remove your last checkpoint |
+| **Home** | Save and quit |
+
+The **?** button on the main menu shows these again, plus the level editor keys.
+
+## Good to know
+
+- **There is no music.** NumWorks calculators have no speaker. Objects still pulse to the beat of each song.
+- **Your old progress is kept.** If you played an older version of NumDash, your progress on the first four levels and your custom levels carry over.
+- **It won't mess with your other files.** NumDash saves into a few small files of its own and never touches your Python scripts or anything else.
+- NumDash is a free fan project. It is not made by or connected to RobTop Games, who make Geometry Dash. All the graphics were redrawn from scratch to look like the game.
+
+## Thanks
+
+- **RobTop Games** for Geometry Dash.
+- **[gd3ds](https://github.com/AleFunky/gd3ds)** by AleFunky and friends, a Geometry Dash remake for the Nintendo 3DS, whose research into how the game works made this possible.
+- The **Rammetto One** and **Nunito** fonts, both free under the SIL Open Font License (see the [LICENSES](LICENSES) folder).
+
+## For developers
+
+You need `make`, `arm-none-eabi-gcc`, Node.js and, for the desktop version, SDL2.
+
+```sh
+npm ci
+make build check # builds build/numdash.nwa
+make test # tests, level replays and random-input tests
+make run # desktop version (arrow keys, Space to jump, Esc to go back)
+```
+
+`make assets` and `make levels` rebuild the graphics and level data (Python 3 with numpy and Pillow). Changing the `VERSION` file on `main` publishes a new release automatically.
diff --git a/games/numdash/VERSION b/games/numdash/VERSION
new file mode 100644
index 00000000..38f77a65
--- /dev/null
+++ b/games/numdash/VERSION
@@ -0,0 +1 @@
+2.0.1
diff --git a/games/numdash/assets/icon.png b/games/numdash/assets/icon.png
new file mode 100644
index 00000000..e2ba194a
Binary files /dev/null and b/games/numdash/assets/icon.png differ
diff --git a/games/numdash/docs/RELEASE_NOTES.md b/games/numdash/docs/RELEASE_NOTES.md
new file mode 100644
index 00000000..4c513615
--- /dev/null
+++ b/games/numdash/docs/RELEASE_NOTES.md
@@ -0,0 +1,11 @@
+**How to install:** download `NumDash.nwa` below, plug your NumWorks calculator into your computer, open [my.numworks.com/apps](https://my.numworks.com/apps) and send the file to the calculator. Then open **NumDash** from the Home screen.
+
+**What's new:** NumDash is now a much closer copy of Geometry Dash.
+
+- The first seven real levels, from Stereo Madness to Jumper, with their hidden coins.
+- Jumping, gravity and the ship feel like the original game.
+- New graphics, effects and menus that look like Geometry Dash: the main menu, level select, pause menu, "New Best!", practice mode and the full "Level Complete!" celebration.
+- Pick your icon colours, change settings and build your own levels.
+- Your old progress is kept.
+
+**Controls:** OK, EXE or Up to jump, Back to pause, 0 to place a checkpoint in practice mode, Home to save and quit.
diff --git a/games/numdash/docs/screenshots/editor.png b/games/numdash/docs/screenshots/editor.png
new file mode 100644
index 00000000..479dafa0
Binary files /dev/null and b/games/numdash/docs/screenshots/editor.png differ
diff --git a/games/numdash/docs/screenshots/gameplay.png b/games/numdash/docs/screenshots/gameplay.png
new file mode 100644
index 00000000..cdd5894e
Binary files /dev/null and b/games/numdash/docs/screenshots/gameplay.png differ
diff --git a/games/numdash/docs/screenshots/icon-kit.png b/games/numdash/docs/screenshots/icon-kit.png
new file mode 100644
index 00000000..4e217e8b
Binary files /dev/null and b/games/numdash/docs/screenshots/icon-kit.png differ
diff --git a/games/numdash/docs/screenshots/level-complete.png b/games/numdash/docs/screenshots/level-complete.png
new file mode 100644
index 00000000..a5f3d747
Binary files /dev/null and b/games/numdash/docs/screenshots/level-complete.png differ
diff --git a/games/numdash/docs/screenshots/level-select.png b/games/numdash/docs/screenshots/level-select.png
new file mode 100644
index 00000000..b8b6d66d
Binary files /dev/null and b/games/numdash/docs/screenshots/level-select.png differ
diff --git a/games/numdash/docs/screenshots/loading.png b/games/numdash/docs/screenshots/loading.png
new file mode 100644
index 00000000..82088ae1
Binary files /dev/null and b/games/numdash/docs/screenshots/loading.png differ
diff --git a/games/numdash/docs/screenshots/menu.png b/games/numdash/docs/screenshots/menu.png
new file mode 100644
index 00000000..ad2527cc
Binary files /dev/null and b/games/numdash/docs/screenshots/menu.png differ
diff --git a/games/numdash/docs/screenshots/pause.png b/games/numdash/docs/screenshots/pause.png
new file mode 100644
index 00000000..eb068073
Binary files /dev/null and b/games/numdash/docs/screenshots/pause.png differ
diff --git a/games/numdash/docs/screenshots/results.png b/games/numdash/docs/screenshots/results.png
new file mode 100644
index 00000000..d4f0d8d3
Binary files /dev/null and b/games/numdash/docs/screenshots/results.png differ
diff --git a/games/numdash/docs/screenshots/settings.png b/games/numdash/docs/screenshots/settings.png
new file mode 100644
index 00000000..65f397e8
Binary files /dev/null and b/games/numdash/docs/screenshots/settings.png differ
diff --git a/games/numdash/docs/screenshots/ship.png b/games/numdash/docs/screenshots/ship.png
new file mode 100644
index 00000000..4d2334dc
Binary files /dev/null and b/games/numdash/docs/screenshots/ship.png differ
diff --git a/games/numdash/levels/manifest.json b/games/numdash/levels/manifest.json
new file mode 100644
index 00000000..56c8fb89
--- /dev/null
+++ b/games/numdash/levels/manifest.json
@@ -0,0 +1,68 @@
+{
+ "source": "https://github.com/AleFunky/gd3ds/tree/cdea1c2fad3d67fa17d2cfa781013b0ee58bb280/romfs/main_levels",
+ "levels": [
+ {
+ "name": "STEREO MADNESS",
+ "file": "levels/reference/StereoMadness.gmd",
+ "sha256": "e42799a8d482d3a99d6f91f715de89258c2f95d4ea863151fe617bdb7c661ed3",
+ "objects": 2272,
+ "events": 19,
+ "compressed_bytes": 2247,
+ "skipped_ids": {}
+ },
+ {
+ "name": "BACK ON TRACK",
+ "file": "levels/reference/BackOnTrack.gmd",
+ "sha256": "6e77d5d126da52f8010cc775030e2376c685bd2dd930f7bc7f7eddc13da85f75",
+ "objects": 1530,
+ "events": 15,
+ "compressed_bytes": 1486,
+ "skipped_ids": {}
+ },
+ {
+ "name": "POLARGEIST",
+ "file": "levels/reference/Polargeist.gmd",
+ "sha256": "bb75d5f0ab577c7586c1143202f54dd39ba9237ed49a20cab3132092161b8e02",
+ "objects": 1509,
+ "events": 22,
+ "compressed_bytes": 1934,
+ "skipped_ids": {}
+ },
+ {
+ "name": "DRY OUT",
+ "file": "levels/reference/DryOut.gmd",
+ "sha256": "29349b1d9a72cf832a7236674e0360834203c35a16d90ebe2152bbbe72b3b0e3",
+ "objects": 1402,
+ "events": 42,
+ "compressed_bytes": 1823,
+ "skipped_ids": {}
+ },
+ {
+ "name": "BASE AFTER BASE",
+ "file": "levels/reference/BaseAfterBase.gmd",
+ "sha256": "f43634e6b4f5e0d02ff903f7890e478a1b61ba714b960d684aed0e85fa3ae94f",
+ "objects": 2126,
+ "events": 20,
+ "compressed_bytes": 2332,
+ "skipped_ids": {}
+ },
+ {
+ "name": "CAN'T LET GO",
+ "file": "levels/reference/CantLetGo.gmd",
+ "sha256": "0e081466ff06567cf8eddbcb2a0b6580867838be30bcff74954d7f1bc9b0aa4d",
+ "objects": 1691,
+ "events": 13,
+ "compressed_bytes": 2049,
+ "skipped_ids": {}
+ },
+ {
+ "name": "JUMPER",
+ "file": "levels/reference/Jumper.gmd",
+ "sha256": "20918d084e122190dff545fc20a2a91037bd82e0dce5db002486fdf6563c862a",
+ "objects": 2767,
+ "events": 46,
+ "compressed_bytes": 2498,
+ "skipped_ids": {}
+ }
+ ]
+}
diff --git a/games/numdash/levels/reference/BackOnTrack.gmd b/games/numdash/levels/reference/BackOnTrack.gmd
new file mode 100644
index 00000000..dbc34d1a
--- /dev/null
+++ b/games/numdash/levels/reference/BackOnTrack.gmd
@@ -0,0 +1 @@
+<?xml version="1.0"?><plist version="1.0" gjver="2.0"><dict><k>kCEK</k><i>4</i><k>k1</k><i>77236588</i><k>k18</k><i>5</i><k>k36</k><i>166</i><k>k85</k><i>106</i><k>k86</k><i>81</i><k>k87</k><i>1965037</i><k>k88</k><s>24,24,52</s><k>k89</k><t /><k>k23</k><i>3</i><k>k19</k><i>100</i><k>k71</k><i>100</i><k>k90</k><i>100</i><k>k2</k><s>Back on Track</s><k>k4</k><s>H4sIAAAAAAAAC41dbbItqwmd0HkpP1Cg8itjyADOADKFDD69WxRY7pukKnXuY21AREW01fzrn11-6m8b47f90m__rVJ_528tpfzyb_2t47c82PNHfuu_H8Y2H8byYeyyGOtXxvKw1dIexo_uuoqobf2zQPr9y8rSraKmsl6jPn8X_8vafj9cX037xk7_P2v_ylr7h_Xzt79__0dNRjTvS21ez7X_qWb-Qc3Pv_5R-0_5_DPWP3P9Qz_P3_XfvBD7Rz7__LPrS7X371Lw_vAPev-uX2tZ_9Sf8vf608dP-6EyfvpPe0j5UP1D1bHJmUlN5GiJ5JJJV1UfshbXpS-tu-Cnhud3IhOvJZvy8XySr23LL3IcdS8pr7YPNzv9Srfi4rWf8hcH03ZMpRE9U0myPaMCTUDzoektcb4VGH0zzOyvOqHCcwKt2aEa6OmAe1BBgfbkwVaSB1sZmZRNtuo_s5Xeaj0OVqePdKVM8ibZmb017HdvDeN4W-NV0Eps3tbeqvCu2hOzUlVbc9-w8xPQ7rsNlO281nPnboNqpjnTU1LrNCmnRHHaLdaR-HtZHiA2hg08o3z81APSBufPX1XKkSaXpojo2P25F63Bhb0WF1lAR2AioGCj6cg2mh4A5zdQM0ix2GB5a7HxjQx2tYGAgKEmkos3MQDlm02G6mmuXqHITghgg5pILq7TNxCafnmhz91-LxOB72sAQz8wRHfHe7Tkjsc-NMTp01G75I7dNce5rh7n3qFkDCcMdc2BkkoB2sdi4xdYM8OndeapGq0Af-w0mk8voXYiUFOn3z72qPmM-9F-PnOiPoHmUfrMhX8bH9lH4DP0yzsnlqCqHdE62URFv0julqPGuW7NnfVOAtRX3fYkQD3Pavv3HXWN3p2KOkzIvYN-ake_BvqQkskT8k16HGkDJKsbKcrToEyeKF-deTVs9d95s8-SpNd856QmZdO76TJtsQ-3dQm8QA0aqh6NPU5CNPN0SJxdxSOTkl21uFdpzu7dk717stNnGJFgzxDOrpbsasmuFs7maIGWW5N9BCYC0BXVPaxB5SF7JnNrKfTb9fPut6P4bPoOVgP6lh85Fxk5FxkldduRc43hucZbsbGSCennd--W7PRUC5ytuM563DMshahHTUv-GK1ncmZSc5mL1l1mlVDE7qCjZyf07ISee-CTkKxYfwyk7BaiTIIXTLxtk5bS4aPqlRq5liPXcmgmPUkL3G_9THvPY9YkAjA9Ar0qZnbJzC6Z4JLp0W8BzLk6nF3E2UWcB9UQzR1Jcg-Q7BvJvhHvAeJ0cMbKAN02zVXVXFXNVZ2leveUAPQ9fg1oh-RMnqrXID1cP2VXbvlt7qzJGbP2TGomj2_EZWkHQ6Or056-v-ItuWa2kUlfqRT_-Qzc2bMjOmUyLU2M2U3pvs6pgf8M2knZD5T9QDOTaVIz5jNJGE1Ae9g0QI--kR0zsmMGOGaAY2Z2zMyOmWk2t1_dtukT2Jv3GfAu2Vp1BXu6n5wdxdlRnB3F2VFhM2HpZk26JftBsh9EkjIZuSbiU_PLrtkPmgeO1qRs_epNuGgCOrjJgHeluZpFa2oWLslRXHomZyaTo4x8xpOVbwADTUB7F9tAO93GDHD78s4L15HJNFdzq5mkTHofE-d-B9dbnaY1Ng337JqeXdOza3p2TW9ZV06NmXI1KI8do-vO9_jJzJMfF-3ac6bMOVNmz5Tf7sxD-MfTpSdX1NRoiyagT5DatDogDkjgeBzk68zNdUAKytrJKzjn6exp9Mv-xKQ0c_AzWONEwTmv3z8f8QqWGgBGLXQZ9QJPr9zFvmJPX8j0BFp7ap8lv2ek51eO7FI4iUstNXpcwgbTO6wNOKtegR0paXm1ITnXk5zrSc-bb_bz7h9CPimx08EayttnklNDyamheGr49nWjT1-XkacpownoUPwIu2lvCSN1IclZpeSsUnJWKTkFlJwCyszj1Lhf29nZ-TTcoleApOIaKop49eaA6hnQ6ejgkI0ZQhfCjqgLnZrkZFQ4h0axDq67Q61k1PM9ydmp5OxUcnYqkmLjVnamDQnblYEmoH3US8iVDZgArAz2zXffmcaAeWzKCbDkBFg8AV7-sA1Udf3tFPgR0Jz_aqFM5lxf9-5nd2Q6og4cDTnF1ZwAq6fHr7lb2zFXLUtlL9A2GfkU2NJUqjntVU-Kl_jegXyHLQfkLPFesZwNa86GteeJybj5FLJ3Hd1q8nZepS4WX-qyc3GNi02lvL7SnEprTqU1p9LqqXQLdpzRpSM7L6fGOsB5K3n1hajOvHLUnCtrzpV1gtvmcVsgz-jRCastZVgHK08ENNuT82X1bLoGOnQ37iCfe68n54tdGpQvvloVp3lHH5Xs7pyBq4C7RbI1OcfWnIFrSLnFfw6VWwxnM84Y3N9hz_qj8PM9Ohbw-RwLdAc6u2cLeK_fyIxj7UkaJOupDfTUMPmYIoNKjXtFD-nxTgPgunNq_dAV6OPj2Ragb85jxUwOIB-pDp7ylNtqYDvYFGpgUK_JFx187Ll8S5q619kQrzOBPwl8QOhfGpd_DXL_RtG19IiynwBJj5fmz19aTkEDnD3SqvCh18LlTKgb8e8Vh6c14CEUCh13nI9AtbdkyngXxwua-xOaf_ro9v2i06d6z_--ffjYkvHLRxeT1FtwryQeuXpWJAbA5_Ay8wfTB1DOALcOAGWltWjWUWsDoOXPtp_P_Flp7f0jkhZCDzgTWAPnWVRtrhegyGJZQ2TytKHWnN4-dMq9Hjqn0xsIX_YNOfl8rZ4U10CH_mYII0AIhBMVM4-u6qn26rGPRD89dg2wakls6QGiG-IA1SgY_MSci88J8ZE44cEAnwdqtRw4Fr3y4JBnPdC8IQ1Qjbpi21pOXd1myeGxCrR1zsKP0hN2tnmhDiuPTdZpyBVX1TV8kN5MclXBUuhgr0IT5yR7Fx58rB4WX46W95EfmoA-rbTsaiWse2rUESrdasgrF09Orx96At2BhunEFHim-nTb5lPVhgTLzUn3J6AA7R7iqMLnE46F9ZTy1rbybfHyOvizgz89XzfFi-Gk0mtoGqqh_j1vK9ZG4FECjxJ41NPxN6ndAJ_OYRpD5xjgvAHOg7R7M7zuMLOHgNmeea_6h43oGoAQ-wxZi_4eeebn2_97-C0y-uxghX360p7vI87fYXJ4TaPbxnKmUaZ99IDoDwcImkbRHmbg8si-3nic9f3YQmtRdo54cuJJFJYHZTgScgZD2Cb-v386VkDGhUhACDXvlM15LM9rFzIuJOrpLmXIRJstNw32mNS4kMgzQ1kcjeYe5_8eTvwtYPgybgQgcoSOtwD2vjkCCyFQA-CfFCJACNRQA0MaH55ZQCicN6wBCOWEExE1ABSACRx2SiI0nB2UCE1gSGgCqRdCf-AZF8-NhE6yzkU8c4XzXJ1Wro4tV-c3PXrZ0_4rQpdUQJaFGvbtDJkX0i9EHRkRCTU1PRHpF1L-gCgisV56DVgt6FW9BprOC7kGrNVCr1roVYsLSRZeA1_nhegfeFoYSLoTEQsFSXQx2sIrgx-E7JhLD4hcyICWNCR4ZSPjQhoiwSsbmQFp35FUVrvKaldZ7SpLLs3ynSfpwdiwkRCMt6KagjHZ-ZxQYK1YYMUBuZFxIcEBlS4pDDQbiVIYRDZy81yak803EqRW3VsYfobgYNs8EnjgvDh1XwCOAEQO8dnKEN_mG4HlAgiBGoCBHAPKpXB2ZUSkIMII0CUT1JL3GUNwethIv5CCCCMQi4Y5fAP9QgoijABdpoTBYVqET5UGzh40FEtaPIwAIVAvICpRVKKoBHvcwNlmI_1CCiKMAF0yoSCc6DZSEGEE6JK5gB4awKDQAGGjxQDv7wbgiJg4EsNWzAg6KuqI45uv2MaY5xNfsY2v2MaYwxNj8mNI0nPFP2bUI1fzC6YNGxkX0hAJSRQJJkgkmCAZTyoLk4SNNERi3eXqW4KJ1kYUkaQZE5KNRAsxqduIIpI0Y2KzkdgWMUxwrBhMtNrQkXplEXrlA3rlDHrlFdrQKL0yFr2yGr0yH72yI8VVCOmVjeiVjeiVjeidjVhVs5NGwUxjI-NC3KhRcOxtJPLgKDLEQ8GoEA4HHJ98AAh1BhACUSTEe0NwRG2kIMII0CUTgIkiE0XCIpOTkrO6Ha2hKa2B3gZBdst4DRum66Nhcr6RgggjQJdMAORSIqhEUImgtXEpwYnnTEajY95kCCNACISSOqEIoQihCCMH9lrCTjrcBQbAvDkGNtjACGIyITU2tXFoDnTtgPnYtFTkCJF5FyQXz1t01wgVSsFiVqjoJAT4K0dYA5iShOCcbEio6MR2m9j24SRCFKmo9AKiJyaujra1NzIuqXFpjh41sePRDdN3mL_5nwt4N1xxM2AioAgUdD_jBqVpSQhO1YaEBmCMfgyZuIlEAIM544QQrmJHkUtpbCDGZGTX8EbGJTUuzQOtSXrK1dAGYYtaiRc8v8P6rf0FEvQRzq4YgKFIGjaljAu5Ao1goBGcGQTnJIHEfwiGIsFgJVdskis2CW7zbGRcUuPSHJvFxMCjihFNr-ikVwRT3NcwHkaWMPEoRjTFiKYY0RQjmmJEU4xoekU0vSKaXhFNr4imV0TTENHeKs6CgWQWDCSzYCCZBbcaTQ-jGkYtjErcuyZCAShfgYoiEZhfgahDvwIVgeDb7QHBgr8g45Ial-aBNUp6rmBkqnUGZF6IHmS5t2LMmBVjxqxyIRCcZh0IQKpoIsGhdSAgX4GKIhWVVhSJjqoYZnaVb2RcUuPSHB2-xKJ7l1hCBBzeMOjMhkHHeBhZIsBfgRDXTUnwTSME-CtAKEKolFAkOrNhFJoNo9BGxiU1Ls3R4UssuneJJYTB4f2KXR226mbHgNExpHSMINcX2tmvMdrvMbqgaN0VR_sVR_sVRzuGzY5hs2PY7Bg2O4a8jiGvY5TsGAP7FfGur9vz-ro9-xXxeoh4y37CgEJXWKIrLBEGHcL4QBhBCGMMYVgiDEt0xRi6IgpdUYeuiEIhoqylsUHKiLSSdnJ2gbHq7WvV6TIyFddAeYT17FvMgaFkYOQYVxgYuJG0kWD0uCLfwHTLpBiFGGUYiw5Vx9MLE88mTDzOsE27KzQunnG5Ifp48FcfL1jPHsicmBpNHOPzCmQTN4LnxEg2MXBNHNR45GJOjBTzGuXzin7zin4T98i3VPTOgmKHNybo8PMKivMKihNj4MQYODHkTQx5EyPcvOLZvKLXvKIXY_Ri-QoQAhV1xAryFfDisZWErGHXombSYzBjjGMMi4yBk6_wxVeI4xAG12kDK_vdVttnusc-U8btvz1nc2TpyFbWLbsOdX87j9aje-0om3vnipuMcZMxbvIdN6XwUvMzf94DdBkf33H-DtOB14NpAk-0cXiGxIABQIVtSw73OHUB-fQ2N7gJ9yD-9Mo6vm087-XQjfhrdxqA5nQHumQ63x996AF0fi9iA8NvVxjipzc53xJ9aAI6H1XlATYNsBkOvnM4-D6DgnVP1MxckF8b3FL-rs8R08CTny2pPME9E9zjR91rFAjOYHCGn0Y34-30eTR-QeE062baN5MeIL8QVVk6AhMB-KzO4fLlOv1ryPuczpJR6OkSvsMsAL-GSPhqoQuQXGPjIH8iUdYu_7nC-QDZawKnmcVPOy-XGRC6pYmcNwCqhFcxIhDqQuFj_yonXyXcHIGeQCvYtQTkNJyEjwZW-YV0V5Jf43joATR0Ohl-gWFVZIazJzUghEBopgkun-DyiS6f-X2kKgzOYnAWg7MYncXurI34_bgWefxctwh4S8BbAhFMwhXEFpFwxF_CvcWlRcE7Ct7xm4fWyeP7HKZU3WHrJLwhJ-XUsAu2Ooch3jnUrxCuxzgLjGrFB0-1NgQGAvAmqeKRZQ0JfAQujtDlNvJ-aKQEybmAotdrpGG2j8DFEUvidpVkkA88Dc-WRoAQiIrjAVpKUKiC4syt-Ebag_gjaRoBp8_YeCVaKfAG1YOMC8nP6h3AaXiL1Z9Ha7GUGnTawcaI0IUwlFs5lwPPthZ_ac0egV0M7CpbwUJC-rMRd6sEIX88tjTN5eZs6Oh0Oj8HW_A5jo2cBOtZBYGLO7jYEyqrqr-5YdWgy8N0eZjQwwQeJvCw51ymYRRwVjj9tlkUChngvgHuG-A-T9ysO-1DhHu4bJUzVA0fV3uQq2NP7NgTvD7B656nWblLYLoGBgcyOBBuBW4Bzw5bEb9dv2QE_CXgLwF_hVt7HACqP-FuVyvwAsUDQO0Vau-37RoHgTeJmr7HsRnPna8a1Yea1v0-8DGh-nW8uuiwLUQJei8ONg16wmLzvYL0_PfnEpJdYOpfF5tHlpKs9s9aU-cXUa_mNr9kv9Z4g1AiovvC7nuj_cgHgDdQs2Cove1XeS-ueBnxQXKHqPkyYqt-WdHes66emZgppvRUoYYDebvc7uVuaN6QXtB-3jhC44bCXUczygQDMBAQ8GAb2On2w8burpDl18jiudsDrevfwRhjCsBpzjepOkANWvrRYn1on4A6Y6Vbn17CwwN6DU-XbKRfSH6jpNW8stgigYauEd4pqUEgmuFLXquDXbSEYTAgvNS83mg1rzda9fWGBH7LkySIrMUWByYse_q8thGf-1ZpeR1yGJzO65AjEHQyJhOVMZmoPC8kP2S7gfA2PUObMbQZQ5v5Amcp1Lxob0_USA-wtRa-M0oAKL1ittHqtrb9XTDs0W6QRxAkFKQGNoVH4exN_JlUG6hfyoP93s0VDbDN7tYDpGjTXgMk5WFfkCKSBMc3wXEJDhQUbJmQ1K93_GFHr_WwYRcBujh89XCgs3o4SEk2d8LSiEF5vHBCCQrKw30SiSyntHdztvW597Hj5mzrHG6fRIQQONsIDwDDcwPe4Fsm2MkV7GT65pWwx7UKgwSsQwLWIQHrnoCZceKRokaVK5LNoGTtur6A-mb9koH8rEN-1j0_4_C7ty4V_2CmAWhOE9DpMvvm9_9jCgqnvdcURyVsIc7IU07NKJyhXuXk1xM2Q6A70CXbFc9gv0A4sKwBcA35nYSHzr6jcMA5AqumNYiwV3Sfmz6rOOrg3w7-9f1H856lDP1UhGCz4EHKhYTD8EsvgT9h1ifICsizgDXREsl5vo9SIaMHqDi09AzwMkzx5CnA0hDOGi-GCQ6DWZkmdEh4qmwDsZnyu76NGHwDsynBbEsMfS2cZ41ARcDnp81RTuAxI0LI20hoRAHnCeyqGOCJLEnOoEghvFM4XLhyVEO6N0k4kGjd2s4snv-vmXGO2f0HMdhYvK1rAAA=</s><k>k3</k><s>TGV2ZWwgMiBvZiBHZW9tZXRyeSBEYXNoLiBSZWxlYXNlZCB3aXRoIFVwZGF0ZSAxLjAgb24gQXVnIDEzLCAyMDEzLg==</s><k>k5</k><s>RobsVault</s><k>k6</k><i>169179680</i><k>k60</k><i>19293579</i><k>k8</k><i>1</i><k>k9</k><i>10</i><k>k10</k><i>40</i><k>k11</k><i>462936</i><k>k22</k><i>15433</i><k>k21</k><i>3</i><k>k16</k><i>1</i><k>k17</k><i>21</i><k>k80</k><i>2</i><k>k83</k><i>3392</i><k>k64</k><i>3</i><k>k41</k><i>1</i><k>k50</k><i>45</i><k>k48</k><i>1545</i><k>k66</k><i>2</i></dict></plist>
\ No newline at end of file
diff --git a/games/numdash/levels/reference/BaseAfterBase.gmd b/games/numdash/levels/reference/BaseAfterBase.gmd
new file mode 100644
index 00000000..51a80c4e
--- /dev/null
+++ b/games/numdash/levels/reference/BaseAfterBase.gmd
@@ -0,0 +1 @@
+<?xml version="1.0"?><plist version="1.0" gjver="2.0"><dict><k>kCEK</k><i>4</i><k>k1</k><i>77237540</i><k>k18</k><i>2</i><k>k36</k><i>124</i><k>k85</k><i>98</i><k>k86</k><i>83</i><k>k87</k><i>1914073</i><k>k88</k><s>17,83</s><k>k89</k><t /><k>k23</k><i>3</i><k>k19</k><i>100</i><k>k71</k><i>100</i><k>k90</k><i>100</i><k>k2</k><s>Base After Base</s><k>k4</k><s>H4sIAAAAAAAAC41dUbYtq6nt0M4bpYLguF9pQxqwG5AupPFvrRIFpp6b_Jx9mCWIgJRiVa1__6vpT_ml57f-lsq_7bcy__bf8jzPr_yW38K_z2_Rzz_6W_5Tft-GT40Ny__QsJT5p84_E6Tff5QpYiwRJYr4tpkMobf6-2116_HanP73pu3atLRv0--_7f33v4yEo3qX0TxfMfW_iul_EPPz73-W9vN8__D80-cf-vn8O_8vE7E_-v3zrzZeqr7_TgHvhX_S---8Wp75p_w8f5Uf_ak_rPzTfgobqTWTnMjBI5EqkSzP2K3Lly6Zu5QK173vzyA3QLQYKn1p4Z_-84_xZLQ8Dr_SqszGmf40-wAUEW5LUpM9nval6fnS9KWr08U7mmiDVn3T_NJjS2W_Hui26ertaZvJem38aV5AleG6BI1Lv6r4haeI2O8AxbFV91Ya2LY6GloBOG6Kj1snwzsJ46gVjBKBjkADgDn7hTX7hWv2w7weaM5-me3dL8afx2xMeczWsmeQL4awlgOVcPObltCB3mQp-HcCh4UiUB14_dDLHPMPeWedsl26zxpynrJ4OPC4Lgb0ZDzjzGMzMI_NQLeTKTFQK-hALi4zVaBXAdPMVhEoAMiT7SI-j9lpzy7ieWK2b9mO0kFemPI-4yXM-KI7KQokjdD2o3J0p3pYv42UT5cr78T39szO6Ol8NnoT7njp93ZQl4zx3g28n9E5DX_SIbmyc5UtdDxsQifZFlmfly7lHTYIxTRpMKZJ6yyHmoEeWRMIk2RK80ioT01Dqw8DrZtmb1-cZqD9xhjk53yymADUc0SLfWB_AzucYx6OfG-YnzD7kW-0_nzXE5-L_L3V_zz_97nG31vt9yb7vKZ-gqzHWYmMtWi7sL7KS2BtkzWPKZqbr_YPwGfpkeK3OUgbLOJoF4uwWigGXC2yA67My98gF-ho3HqKczTAPh3fDmoK8FpbJnvuvn7cMLufl8e6TI_T7wLnXVGZuPKQN3kRbUtE49Rh0yyx1S1xOL2bU8lkNh5t4xX1y2Vs6ZO9vPPXENnqzRFYk_YdQfEWM1YpIJXWum412bOgBFVr4JuION_2JruDODuIs4O4Z3I75M1PdjmMb0pz83dN_D2bt3P2xrwc7TX5J6IBaHtVvZheC75SJTtNstPEnRbo4DSRPATNBtJsIM0GUjdQcVq2cHX7GADxOrKFRg7fsc3Z-rz8blHKmjHt2WNvLylurRqAJ98pDJYrSlc03NgaR7ha0m1vivSsv-gHAAGanG7I0IChQQ8NBHQU0EFABwEdBAwUMEDAAAG-KKhhzG5_UzkAHYHhgL4AlznbN6AIVAdeNWoFvScg2ABoH3hlFMAggK8MexQ1TFN2QICOPShIVJBYwVDWpRuqFjfD26IVUMKABwGgCWhxiQRKNMEuCLugPPBJEzI4LTdagCZs_2wzmEAPjyac7UINlCacaQQzjWBmUcvOoQclwtwmmNsEyYFCcngzF615sVYeNaDPRslRiTs0w0KHHTSGmUwwk8lnsobrzxbANYcGwwzhvOi19kgTtPcOuYJfmVEDmFIMMyjUvl66Q2R1iLzuk6E5LdnWfa0yfTtlgjzrdcm0-FZo74SaQPKWJztIHhDiIdhcqC9339uf7NvvuzawRkKLSTU7TfV2h1OFO9xwtG6SM7nv2-_KyOi9c2vDM8mryaBs3Oog3UCw3oBENdx3rzpDknaDMrlXCRqY03pygb4OXVzvOvRrXXpk75DFaQJ6K0XPiFrQ0zPZMrmXXe9KymhZrl3Cn7Xso5L8Q4Uzuf1TwuV32ffu62iWXd-7ztzX6drW0fjTrm4ERt6MZahx6o3zdWxzzvce03dVg2q-5xgNMWpoyYUAqpeoMpBuYEnTh2qKmjWyTe6omR6oFTzQ0kqZWnZo2-5-V75G75UvtQHXx77-xp8Bpb6bJ_UeXie-Iigtnj_bsUzmvZ-1nnsxb-43zgXsohOFZrU4nyKfXvk08AWFXH1OGxfibH72rfrjtO-VjJ3dYBMY28I9T7iep2PP3ustW6s3cMcEpjteDsnWl2x90ay-VFB_trfNXwnI3p2TZgNpNpDmWobRa2tEI4fjyMYYeWdrdNlde6FuajtgI2fig31GsI81yRHPTzIYP5zJbbASaN-oWvtCzRENSAmI91mSCTmXg9jLQVOgVXpos9dkNa4jk08mt8XVr85F4hRvyGvld0NrLJ8djrdp3kZdhSSme5OigWlsnrDifVXLdR7OVSKGKpFdjpZuh6VbsHQJUvb05lxM4lxMYgLTUzC9enuv3pQgxKs-C5G2m4g3UQdcEMVmsl2dC0OcC0PshaESWvtgOWdzY_fpYUCYHswwpayPF_je3bjDCtgAuDVyh62lAbSd71UodikCzfdSbXV77yVWoqOkt_rKvbWfXG6JuNxhHI_ArpUlbymNJqd9cTgFCAoQEOALdg09NpcQdrUagAZ9CoPSsXq_mDImCXsNrmszGFcshkpasXAuv7GX396i1JJUK4h-LTxL16GdWzDQU-4O_hK6faO9tBqguT_h0ObbR68BWDJzpY9zpY9HWs32p2SSkj52ec--_uRksujmACFQHCgO9JUOeknpoJeWyby4W62d2zdm6vS8mRVn8O5qsk6vuVJsl9mbZ3O1bK62zfXe3PsqDO3rXhMOl99oj4DvhVYHOzuvJj3W1jtlm1G2GfVsE8qr2U45hZo0z4_GsBewxuAL0QXkheiS68PnbGvmbC0rPHi_E3Djc75dmjzeenEFvbje9DI1XK-evdgpk_n0xeg5J7158GIn9KJJdC92unhRshcln9F28TOQ4bQ3By9KAy_KyNbU7I1cZ-hehVC_Ostk_gzRgsOBcHHm6YgINDeJhl1KC6J40-u-54d8PVcbulcb3oV4nw9SybbYqNliI_lZciFAcplAchFBvEzQndwlCKNnVelxabtvyWUCKTWT29riVwtn-u2tOy1Oj1QgMXrfZ42eIRoa-CNjq8d3j_0a86Pw-PFdjeQ9utS8STTah2tlg79svS11PpTxrKQjeQ8veQ8vvocXv-rjay1bv7UUO4v28Tas585e_C7u5LfRDDlxMHQ9oOv8oIXk0oB4aaAEeude8VrBayYOC6LhwBbnW3UJzX2cXLK2XLK27OW76TfuJfnNN_8lKtRXZdMa-NrYADjSM5SuKBQ8JRcEpOdQyMUE8WLCO6CeS4NGE9BlzxSj9wJT9qNNa4D9yVFQHcz1LgPpBuZ6l-SKheSKhUDFQoS2T-bkkfdhiRAVuT4hmqNCIQgUgkBzDVe8ntHC5YbtPcp0Lcrj0xom5ouG6aOCvALKCSgnWbn84JLk4ork4oqMPKFHSAPNm4NvR7sF8Gi3ADaJiPZLdKzntC5gjg59cklfn_AwVn2BGS9W-bVQ1kezn_TRbGt9NNlaw_NTkYG3Iiku9UlrXc0VHc0VHS35hmCXy6rhq5VgOm-gg_qxbBOBBwABmpDB6Y4COgjoIKBng-Q6k-aHijTXqLTmM6GlzaA14lZBnVazOq1mdVrN6uRikuZikra0hjByn2MZHToD5-eqkeaqkXrVSPyqC6d1HuBT3wSGeRU4_cl4CqvnN9spv9lurEWf5vqQ5vqQ5geHlPP-z1rP45dXeii6vAz5SSHt2ab-WNEU13OpTfMjQJofAVJ_BOhdUhm9llSaH_jR_MCP5oqDKgwsVAbe5b3q-1wtNwcIAXGgOMsIgGzg7TSXDjSXDtRLByXQwdZjvOvxd0H-bTFs8-9nX48dYD1_9yiksa3zq__C9ub1Fthop82og8XfePLTuJ_bDdD-dPtrxdG9xPE26DmgRzjdngySq_Ejb_OGtEz2TGa322V3-9BQMn458rZu5G3d0LzWGAqnI8P2VM-WlzdNI5_wjpE3x2Od5v613mV54uOCT4SeFqD3USPv9ev-2M_3pSOgO9DZUIvBLVWe0t8iqXgneRf2oRloBaHhNHcJbSi05prYB9AGg6sl95M3V-VpMHjfHZXYYOehDwDmaGiONoDDNyqm5gTmSKwbODj8AGAgyuG0OYJrbcezzwk-qT6EREKUt2Df91Bs0torRmKbp4UiygcFW7JkuoNtfbthluoP-tiQ4GPflEzt-sAhGRKG5DuXEgGvTS4kDdK4YJACgSvgF8HAFcVBGRIG5bsKU1AF3K9gW8VQNw4K_rfNAnk_8C7CM2Bqjw7Kjw56jAH92imqD6bkM88PzUDnm9dqECxU0innExv5YEpeFX9Iysob4MqXkgOy5EXmh4bJXipmMmOJw81r0Q89Mu1LR1PL1pZBqDXxNFUa2KxppgkCplBBodaku9C8sPzQAprBCd8HyPFRfEFonUygVe-EwRxwSriBEXxrPMPzX-kVVPHVYpm02hIDEHrYecBq4WH0xMI-65fcmmZ9EYg1wVgTjDWBCbqAHsZtUoKLFAyuEKG-NC0RiH63Ji0IHTDs2aSNfWNYiL8quJDCyQ4D5vYAC_s61ewyjrltTcIaZEl99mutC9F4Er7QVtiHYpCbsOZztA9N2RELiCz5hYEFBK1Xk8CUj8c-9AM05FIDPERqgamxRIYQWVITNHzOaeRTV87P1maLGmbLCIirC8dvm6XuIKkf0-4JRgnyF5IN-R63mefm4emSRxx6qN7Dgjh0WhLfdycvz9a3QQasrYB5W053tcGMXMDw2W9Qe2RzEbjZD_zMrQRJs_qhn_VjQIgdQs9Twyb5xO5Dg78Y_WUN4mgmNEdToljfJSw5vn4yJLzAu5m8oECpaUnTdKH9ENBz-flz6ywwiH5Msw6ZtnbItLWjX3uY4CVCNFL5r1QB5wrMYYF0W3ET-EHC7WxExN1ggJaYSqvCLqDaBjGMXcHnCtnVgKiONekhCgzi1X1k_c6R6DpDJUzxCZHf4utAr9lWtIUmBIYb6LWBXjOWsAJfUC3xEHnB4fa1EL99LSTfvhpsZdsDk7k9kKMbbHbbAzN3NQi3s9XL4yNpa0ucfLAa5rucofEutyAPjQb755Yfjf7Q-fRrNQgjg51wg51ww820Mcyl74LIIRvpeup4rMd9OEgrum9JS_4e_BIpQWRAmr-23fxB7mi3_ay1282gYLcGEdAwAnB_32B_38L-PjBE9UwmqNeCW0uQnDh75tSoM8obB_cAi6ZuwhKitfkBgehK-5JIdOX6uMhIc4gg8ggijyBJtXDwWoKEqDndlnvGmNrxtZ0e7fRqCWvYmxXLLTbtEyQaYt2gaCDCXXtjmEFQ_2jhRDe0j3ru6ksaD9PR7hrwfEwMvs8pDjPXfLuOo2Gazo6SKZhw3B3mkNd1SmwQ5lCHOdQxi_bw7tWC-gmFU0VzqUG-DTRtolX6c40GaxiSA9R2mkBoCybVo7ZjIpLWwofWBs3nN03UeEuVVjL_kZ-xPlcg8ocSfWmBs_QX2KX7LdFr9218JL5j0T9V7yVy2rcT9vAV4h1qUk1zeaVBtalBtakNiAp4QH8JmMexT2iyH5ooBMUmgmITebGpTaAo_aRz5ITTH3CBlStB8YnymeyHlmu_3y3PtYPvxud-QfMxXiE4e13AftJiAf5dE8rHpx-6Az2u9JCY-RcXoi2jM-svEXnRS15xi6rPWm1CGEfztVyU1MDxUDEjqJgtGpQ3LkTrdUgNalJEEARQYCOSKw29GReiJaNzApiIdwJMe_FAC_KAcLAmvJ_Anj2wYOAZnqctQRGQoMJHPK40jIevwcPtij5X-xu8QyoOV3D8hOO3g-449vjUfrogf8AJbdUhCqHiSJ2v12G8_RqF_R6FJgImFhQoSSAURa40dCnXUJR7KK5XCHY7KFYSFDNJIXB0XGnoXa-Bo9fA0eeqqfpdoyShYMQB3oLq5qKh03H1HlRKF71bWVyN8QZiPwLOLow_XIg3kjfK-fHTbwlAOAdjKI0uOmvOD0ErudJ3ro0mHfjQqiIy601pKOkZ7cJQYGUowHLpQI8rDXqXW3gt2YhieJUAy56iHF59mBG4ODXLy29AfGgGWq80aFVv8bdke_ZIInLgc4PAgNIpN7nS0GW7ZY8lGxVpXhCaYRA-QBEBv49x-GTFlEEQEV6rbQaU66LOcFzULX4YAD1XFKKNINroGlcEMRhHGu7hC2EcvK-C0kjO1eO6UHGMUFdmhj0NM6xyFgeMhK9RxxChNiFMBEQdlLS5QxR2iEJ4HWQBQdV-TWj9GpcdYtgm8xKRzv8YCsMMheN1HboQiCdLBgLJoE00f1hoAXH9H_GCjhUISIEAnBt_FoEXEGPv_sZoUqHeVYhRl6THu9Zk0AqDU0Ygf9pkscxJwaFJQvhA8jdYVpOCUsJHUrXehr5K64BqRpOqfCh2IvUYTj2GfLZh1zZ8FsQAQkDAkkPQSoMOpNyRgkwF5RbUDW22Sv-Ays2So6AF1hnAMZwT4YOLjwG6JXt4kciAhkBHYGTTWotgtv60A3nuSEGmgnIjMLKtl4xtvxYFjfD2a4uK1vNCnMr-vuxWux5D42NoL0KxTfUPR1Lsnw88JLmoVnjPyoBQRTMkPIVfA-KFvho4Q_kvcj-uevFXuynoELxdILn0wgjotQVhiwOQMIp6G0UtONpKByIHUq6y6IpC8Zhjv65vJQQEgQJDrISAIOAvzkQWQRZBFn_lfWv2HKrtd442Mt-PlDju3pI12oO2bO1A-oGMA3lutsYjnSjvQMfNLw1zSMMc0jCHhBfmogxCGYQyCGUQyhCUIShDUIagjOi4-BphGs1zDOdxW1NF6-_v-zhyZA08fIqcB6o3XxDmBcK8QJgXCHMLYaIgTBRUwWzECCgCFY1GfCAhEWoc5K4X2jxZY5BtDT5yEh5oGXrNN3zkLz7yFx5oceyXASAEBIE4bsa0xZjYGNMWY9piTEqMaYuPnMRHTurhpf457H4kn34kn34kHzznipwHek01HVJNi_q1_E39fWQXPx64YH8jj6OywQwds0LHVNMxf3XMcB1zYMeE1jGhdcxOHfNXP5JRP5JRxyzYPbXabDFTwl1FrrlGrrlGdq7ZK7MoJKwYhBHARCCYbgTTjWC6EUxqgklNYCfVtfxBY6U_XZA_XSgwJCUEcO4pJgHF-as4fxUTiWIOUNjj9PEcGs_AHy1c8K2vMQTFB4bgwKgdGLUDA33gVBhrfe3IcKRGpObZPcKKPendc2sNaJwLA1cVAyfHOPYNEYm9CSorOMJjyHSMWA-raJiXYz2vFe8o8sD8EPiBgw_AVyCy6BUoCAQFF8IoNiEVjCX71wJivpD9owIZ1SsKKcSYIwApZInXQzF1pgKzVgohALNWCsxaYwlWK4IAIYsgUK4yolULlkCM6YKcXHxIPoyAFi90ReWGVrgnSYX5LxVShlQsMkg8SDexDZxRBwIdO27YccOOOwLjCiTVsEayEEa5CcGEJvhkQBzmgfYrCilR46hzbcraFlTxAGK6MVFjr5ml4cxrOPMazryGuahhLmqYaRrms4bZqmG2akdyaseMb1iTXQgfXHxIDo5r1wTWrgms6c1FLexazNTWEDI7YSogTDiE6YQwnRCmJMKURFhiXQijlNTmyDh0ZBwiNB5d8wtd8wtd8wthmiZM0-RpetqbcbMtDHdsYbhjW4tgR8bUwDiDwrMrbQJ7iu_llkbWJ_BiTmTMmnwkyYjUgMRhNRwWpkD2JBllzGLnPB2xl2DWV4RkeNha4x22C67instLM-mYMsKnFaZ1etj4a-BJiKJLO1QYDAhD7ZhGOuamjrmpY24K3-qcisg67t9ex69TbuSBVaoIFhFEQhGBI28AcD4Lzmf8nubmORBBgFDKAQiqNl-KCkBwrWIpQBRLAaJYChAdaATFyaB4a1ecjIo3PB1oAz1moeJmWRQ31KI4UxWnlGLqUEwditlGce2iOHHVp_b8tc6l_vuNrZK0lTdbzkk7H_t5D_Tt8-_8_QzG9-Po43tq_jcf0NjMYzPz96Pzqj9_8w2NHjjfo3P7dnyNuH-TyGAsfsoIxc8WWOEnNzb8XGG5onQXkcs-Syd3wcDsMDChDChqLpYQPgOrmoYQAvszfUs_r2lKROeCLQ1khIXFGoVsSJ9HIMNHPBh4PgOu85kp_yTkB6EDKRsZAahOE9DwPISG11ZnC3gkSvGNUwOKP8Sn8JSV-lNW9QkyAwc8xaTwFJP6U0ymZmVQEx4_Unj8SPHNTWOYHwOYz20Yz35vU-HZIIX3OBWe31F_fqdEeh5tRqg9_hyhhg-6Fms0f7qJy5bEYYlsCB-IItLLgdCBCCLyHEg7kH4g51inoOavZKvCmr1ElNnb8bXdMWQ9hjyOIY9jyPGof_Y35jdecn_jQUOMBw0xHjTEeA5DGJs5_UUK-nMUBqVWG1CqhCHPSF6sZT2ls2DN8OSvaKBR6VDY3nkLCle02WLLe6rVbqOmi_UKurTDwO0wcDsM3Aaq0p6bKq1d0VtJcslEte0IUbPadDiPMDIHKSpJ9dYx8RXVqzrrSDCrw4dHGUN-8OE-LreO-epUvjvVTqHqVqdH-OlJy374uh--7oev--HrfvV1v_q6X33dwdezJzmcKodT5XCqXJ0qV6fK3anrjARmrx2MQOjp4Ws9fK2Hr_Xqa736Wu--tlMOUGccTh2HU8fh1HE4dVydOq5OvZ4pDDyXMLXt0KOCcdd5A8Id5lePQlJA1-eBgPkgfCAQMJsrab85EYWAmTJLwV4KHYhgv1hQ1siJ6C0ElgiY7hsG69QHdartQPqBDNQby7MaZSF6iYwtE0dT54vJKaDr0w6ntsOp7XAqliI1ciJ6ywIfuGV1Ftzv8HOHx21MdAQMHQFDR8BghVAjJ6L3gKGa1dGI9hzVfMQLH_HCR7zwES98jRe-xgtf44Xv8TJraYfJmeUyRn4_Ze9jXI1VLv7pR8z1I-a6IiKHV-XwqhxeFfDUbKeH8fUwvh7G13Eg4XHPiPh3YDbSjjb-bvOCONtpHHYah50G2qk8aKfyoJ3KI39AKiJhJCX-anJqE0ZiEKfwWBpkL5SCXigFvVAKeqEU9EKpaKdS0U6lYg5bXKBTO6zXDuu1w3p0jISOkdAxEsLJvOTkCVrwLZYkrwZuXOf10PCzDEzsuMGuBTfYtfBhNL4l_sKX3WstuBmvBTfjteBmvBbcjNeCm_FacDNeixymFDBGi9LT0c7uAdvubEk_JZtU0KQ9SEdL62Fp3NfXEvf1EpHgXqwlaJS10R6484-i1YK1glqwVlAL1go2F_Q7bjfGMm7ptmJdoVasK9SKdYVaY11BgpyZkiISrFSf252vPrc73-oh22710vM0WnBLzq1Y16i1oHNrQeca1zy8SchAJA6t3NZXSzoMoqzC9tL2CSLmGwItIM0_W_HW7xf-pp5Zgq_0_bZG-dbga61_V7_fzM9m_uT6L3P_1v6fP5Xwp7WwXvNBMEgrFmc2F9jmVrLZ3BCksTajEQHu8JjyZAyPKUdgfl2FA_L-euO0bv4KzocmoPPHFRfgH02pddYFduV7AS4jf3HmQ3egc137A7xVWP8C-wfhjdgsWA96kjeyjXsJfPE3S2dn-Ssxq0Wgc717MfjXhrfQqJ9t0kM_CoZVMGz4BHCJIqLUET5Xu6C5fybvaIC1B1h7gLXhOy27l9hJ907M3NZorN8S_sRkNmTL32750Jq92gp-gewDwdeJViOXkr_M8qEhHg0I8dhq-KbbbJO_FPyhG9AdaDBRW7-5se2xWKqHX7MHfeL44q-QjtDIu2pgtfDLpiWK0CA1_vLoguiEBPsmsC2BbeGLwltEsK09lBH7secn9m-07UadQ6N-8mEkNwY3MbiJwU3wceLa7HGG2EvnE1JUuLexFR5BknfVwU3-pZBaAoN4L3I6yR5L8CTRBDwi4BFBj0jwSIn9xPiYW8iEvJZi71jB1AqmVjA1fIR4ASP0MbeEHBE9kAp6DLDzADsPtPMAO9PcZYZOaO7xEiIb0dBkf4tgSalOE9DbETV2G5ImzU2kj43yWeyHbkDnz5MuIDjXRIwgc2QZ-fT2Q-fvyn4AKlmrcJ7bQwvxREbt_QhwdXPt39uM65SF-m8TbkidlcKrFS_Aftgfgf3Btw1Ab_snKb03g_bva1aSBsKlgXBpN-HSDuEGhaHIA7LCK9UGyL1FSQu31axkHaxtUN7aUdBqvY3dAiQOvfK5aPoplg8wf8CDsUXWYKF0MGK7iQa9FhSUCG-eJgBkGRplGRRkNfAih5cjU4ts6NUMumzw0cHdLiphjYKhV6ug11zINtmC7LUoaPDJ-EmBHm-GCRrlr_8HHy-QJjCbAAA=</s><k>k3</k><s>TGV2ZWwgNSBvZiBHZW9tZXRyeSBEYXNoLiBSZWxlYXNlZCB3aXRoIFVwZGF0ZSAxLjAgb24gQXVnIDEzLCAyMDEzLg==</s><k>k5</k><s>RobsVault</s><k>k6</k><i>169179680</i><k>k60</k><i>19293579</i><k>k8</k><i>4</i><k>k9</k><i>10</i><k>k10</k><i>30</i><k>k11</k><i>187631</i><k>k22</k><i>3044</i><k>k21</k><i>3</i><k>k16</k><i>1</i><k>k17</k><i>21</i><k>k80</k><i>1</i><k>k83</k><i>3389</i><k>k64</k><i>3</i><k>k41</k><i>1</i><k>k50</k><i>45</i><k>k48</k><i>2146</i><k>k66</k><i>5</i></dict></plist>
\ No newline at end of file
diff --git a/games/numdash/levels/reference/CantLetGo.gmd b/games/numdash/levels/reference/CantLetGo.gmd
new file mode 100644
index 00000000..7878d075
--- /dev/null
+++ b/games/numdash/levels/reference/CantLetGo.gmd
@@ -0,0 +1 @@
+<?xml version="1.0"?><plist version="1.0" gjver="2.0"><dict><k>kCEK</k><i>4</i><k>k1</k><i>77237542</i><k>k18</k><i>1</i><k>k36</k><i>109</i><k>k85</k><i>111</i><k>k86</k><i>80</i><k>k87</k><i>1998976</i><k>k88</k><s>100</s><k>k89</k><t /><k>k23</k><i>3</i><k>k19</k><i>100</i><k>k71</k><i>100</i><k>k90</k><i>100</i><k>k2</k><s>Cant Let Go</s><k>k4</k><s>H4sIAAAAAAAAC41dUbItKaqd0KkXqaBo1FePoQdwBtBT6MG_zBQFVnK7O6LinnJtREA0QXK7__VPGj_ltxb6rb_X7_0vjd_-W67r-pXf8lvajZZx_zN-y7-ftihh6bQIS0p43WTlqg_H1n5LWX_q-rNA_v2rLBZzsyiexUOzOiz6l7T-PlTZiCk5_--klCtMD-nzL73__hdNmhcv0ea1XP2vbPof2Pz86x-Ffq7nT1t_-vrDP_e_6_9lIfpnPH_-SfNt1fffxeD94B_8_rs-Ldf6U36uv8vP-Kk_dc4f-intbs67SdLuZt2tNrXVn1Z9WvyQymm-PYt9LKx9-fKcmEKrh9bcrTJOxzLvNl-HuJFSt-r7thZa43CypnHSrnTa7bQf8l48r86hdexSr9Msh9MiHk_7ZrLbpRTtLsEYEowhwRgygwqraSos4lK2zCNYYwRrjGONcSjL3b_9PGIVw-Yzh2xA5aPYAl7FxmF5LxLPZCjjw2SN-8pIp_36TTX6dvvUX_NSWWew_Qy2n8f2r3-s5msSOj35YfdyqwcrB3u4PCvXMS0XxWaPzTMNrxm087J7EUPu1dNvsS4jXBMmjnAhzSjfEUqYuVJabI6gs35sfrAJyMZRpMA4NVi2VI5NiXrqxxcZIoYMRzK8DyhI5TjBRvrpR8v-dW81GzjNOCEUJ4TOhLwLUKltBW5uTvLVpfBeK4WjyTmanEccYVG7ERTgo1Er0RILXPZqwTwKjnaAgvZS5LUXu05ER_4Wp7LFqWy2RbnucsTX3s5Ai2L56it7J50ir1DXLSgotMA1mcV1babQQugyhbSTHIV69IAePaBHD-iwJBf1mg5ygl57o1FAbKdxKKeo25WKE-ldd29bogtJdCE5LkRGfAv0w6_lqoES9isFOQNtF3ufshul5zlLLzJYN-Utxoh-MqKfjLid7u5HxRknZcZJmXFS5gwaT7X4VmGmtp5o67Xgpi3pNzK5kofNBu1po0g9j8R6hTmqV4vNMEdKLH6KFIuzoaDNxuuEyu0NTooXem4lCm8fcEoUN2PskXGUKGcOu_u8bbZ1xjY1iu1RdvvtT_U8g8XaK3hrBoy96itfMzBkkt2mt0M7bkKvwO2dvW7tDu0Z271Cu0F7nParQWfZGiwCKbGDMLQlMpCXwdoeXpUGxZXoQM5AtxJf8DITWpuhLWe4OUvcjRz6-EcGk9uPbpiuWjZP1146ecA8ayMnhKNyBdehQs27CpUJn3fT0xHwDvSphvVGtcVmjGS0bZGMAit27o7iOgNQ2M-IODbjc0_bssVf6UOMezdoga8i9QQLFPMXigkMxQyGOEbtSu2UZBc_KtKP2lUMeKXv5-lLrX43wQ3aJqhIPZsnrdxHTl4X0yaKeRO1sCkq8YnYlXqtPSNnv2lumcxhm_UsxsmC_7W1Omneeb1Vf3aom9mTvc7bZPLzZK3_15595-7weMb1dKXLdS2n6xMpr663Jb89d0ZGMdujmO4R5Hv6sZu-RXD2a4oZHsUUjyzHW4tAqmz_eF1e7Lkp1mZouyzd_M31X0vm9YeVQfFZxKt9NiO-KDDkKzzHeWVDZ3xtF2vbc_3sWZuoFnXV1zM3OqeKdnhtF-dSg6tyzIw4ZkYMmRG7zKhbb47Pae1leTPHtIhjWsQ1Tr-2bfqVfjgg-gMTHH_E84-Y3DDF0FY_LpaGs89lhuNQitsXNshmfUXGjkeY3dYxDTiixKSIISlilxS9u60SnCyDfZL0Pnd55R1uxJjGcExjuMXwVNsnPOWYM3CHg6VoWMgZNvWbk7xhDO8g-3SJET7HCJ8F7CEDHEM--mu8ffJejuE5x_CcLTxf3actRQWKnEf8MAoqMYRQ-HmYZnCLkQVrIN8aAAMAl7JupB-nj6kDx9SBY-rAljosU67OZ4W2GMa3GMa3K24D-rE769N4_SS3reyU262YDZ6orRUxLYcBluSz7zfJEInGaCVMcyscm_HgZVOTHU4WOHhpdafYXgEFx5kVRezYoNUwK7vHafbYjIex2tmfoZLZVZFuyMuD4sxRnDmCQ1rCmVN6Okuo8T5T2Tw42pajbTkcYrcW9W9R_xb1bzGSU2onnRKcc63WTwTipqXviOZMiyLzWKlHK_VopR43Gm3bRrPpnZVEE_ljJYlWkmgliXGztp-dvDryNyrVoOxEVu2NrPgTkT07ahvyFg3KGWhE-49o_xHtP8D-o4P9lf117DijHWe04zx2fKehX6-W_B76O4BOaLQB9odg_SpK5SZZQb6acdfD6FNSuGJN4YpFhSs-65TalN3dpxUatMtxv17cxv0yLcHcvVBs9tiMy12pnQTa3falzcEj0xDHJS6JDdqS2MhZEj1mkj1mkr3GjaNjJrnpjV9MHHtMHDvFLVjbZPWgmAL2mAL2mAJ2SAE7g-MqAZlvxJSsx5SsW0o27FMO50gbtGx_IxaYbj7zhDyKlCdX6MOAN3eg6gZn2cJAaQxqYx0M2T9eqx3m8ZCeraf-WU8d11NMs3pMs3ospXUB5xacktV9TckyhbQnuHqjwWWsBfTDMxbceqy49QG7zaJu9rBUhE-irl04nE9s0M4nFGnsOL0IjbOT6WD17GQ61jm5f0WMlbYeS20dam1KfY4zlZzDccQG7ThCkeYKpAvxpp7vieIwUy9g1v0EkpWkdjlPoEufP9dK7Gt6JLC78f_UzSq0x7OGNW29rerrQtcW8Wq66c4sbGCtSScPWd1ZVgq8kOEAbkeaWCKO1Um5omNr--TASv5s1DvGF0fWT278EmsCjeg5fD-H9PTiVR83-5RqOvQ0W2yeVSFGjAPWc1C-B1xwMTkcKkZ8KrwSc3qJOb1YTl_cx8e1heyM5R2D9Pz2yPPqvxLqUy8Qw85pibaLtQk4TeN_xLMTglcaHofHajdouwN8R39Ot6XFioFoHm3tEtv9gjZBu0N7RgG0Pxmw64YRcCVCReikOCI1DiJgBWlx0J1-H4IBWg6wwgCt54Q2aDnBCtOs1K2_xGR6U3UgW6p7oIasUlGzx7ii_uNq0K5BHP3cShpiRFB4GFBRGqUE0w5fo1oEkhK4l0c0xT2HVKNGnxqVoN2hHX1K6U9oPii6xyAwB43YXz8_i2JwnP7BYAQGHbVtRmigUQONWo8M2jRPGA447Q4qdVCpg0pSzOrDAdYGlQRU0mysAeDOdTbS6ZBMGHSAGQaYYcDEDphYzcoaAF4IRU6iMyZYaoKlZrTUXJmSmX5e0VLzYmhHS83iVvECCDjubMmAaJdZCNod2tEuc2Uw5m-zRqU3gbVBaXKL0gFu01XENplJYBcCuxDYRYtbJiSD1gxaM2jNoHWrKONCloz9BfSQKIQBSrZQ29o2fMZrYLQGRuvuhPYl6GCRDhbpYBHZR62bQMAiAhYRsIjE2GNqWlFjMDQ1vaih7jIHqDtA3REfInOCdhO0m1G7571Zc6q-EBdJmuGfKDywOl0d0BGIqpfrEx4uutKgYxkIVJC7wiPsRgr0qYyAgDgrTMO49MbJcCcmoQUILUBoAZogN1vtdlFwhS6MxnDh4hKvaQEQpF5RIIPQDc3S0CwNfWK_W3UoOireUfGOindU3IdzAbEgY0MWZdwImkfQPILmWXHiKbhugJGihFfhroGGGmioiWaYaIaJZphghrLfP9oUBcLAG2gIgO-XEgu-NyDQBQLAGyjAQ8Ozy0jgtaND4gBC4AKu1KKlyy4AfJAeouMNu5kvhIYhNAyhYVhMqYDY8cWG7HWKQ2SMGc3HaL7WYRobWq-h9Rpar6H1ekPxe_uIr7UBJ35HQ3U0VEdDCYP4giYQNIGLRderiWVMYDLQBgNtMNAGEGyWMlGZicq4WFEFmZAf334Ja7lCPHgDAlxqcUnu8IgDCIGOwES21RXlh0cc0BCIQcy98PBpVwk1JNQQQrtSmdBMjAoyKsioIMR393O5oWgN9WuoX0P9OqNoHfXrqF9H_cSF8B5ZwR8HyN6LroJGEDSCoBEgpCt1nLeBwyO5jma4PZPrQAsNtNBAC01BM0-00EQLTfRxuiBlvRHQnjCqI4zq6IJlTqUi0BAYKEmFXPcgDmAEPvrQBL8hDMkIQzIiFB_DOsKQjDAkI_7o09Y3ppwkGHgRBl4Ex3aFMM4ijLMI4yzq4IraRcATtaOdHr1eReIWb0BcUKaQezQTBmWEQRkJ-C8NiFkIwy3CcIsGLHCaGLMQRmSEERlhREYYkfEF54w3AuoxhmSMQRuXggAjANpwHfbSc3NIr6cPnLHdACHQETD13ldPN5P3kbJO9Qu9uL4FfjN4vpP4twbLzJZcTIfKn1H_vpHnkeAuhnAAI2DvwXSPvjn44tSuTJ5GKdpTdP4Z_UrePm9W-RET_MrxXrNRe0vR8Wc04dz-04hfXMofcPNTBdxknlrJpntg_ilhtsR9IcrTnsIKOQGkAfDqu77j5scXMINYTjdcb7c5aMeAuPzg_SJB4RWAdgcQAh2BicCa7MlqhtDxC88cphSeFQabDYGBQM05tRweEX7N21wAvejaFb-CcQOCQMkG0I5fWCLcHQ_L3dtlO8QCivt2WkBOAWYj9rU2HbLAXLdCCHQEJgLpXCunL9wz4xb3-qUSVpjmVhsCA4F0mltNp1m7oyQkFK27AD_vVGBcQkegfN4pn3dK532NK25cxrlhnBvGuWGcX84ni_PJ4nS96jAfuOGMNZyxhjPW8hlr-Yw1mLHh0Qqns21_H96VtBebjvPXcf46LuSeT2jPJ7SnE6o8agPEfdd0vY90GDQ3-YIzKegNgt4g6A2ST77kky_5LEvuEwPneuRzONJVp-8ZDbPNOA9pb8MRv9i3Ab86B_rYzOdu5nM3JYfRZyb6zASf6Vdq7X6l1u5XatZ-pZOgvDty7civI6e-TakEEuyroAsQlDF-Y2_jgourl3RF95J6g1J3pPPASIEPpwoT1CsjgBNUU8fQjl8YHOP1v-5SZ6UjnBrCqSGcGso9hXJPIfQUJ8h6s78rXf8JNREvse4tHnEbaODgPwgshnkJQXix6NiCeN-daw5nwb0Sf3Z3xV1A40b0yvGpLT5BuT9z0o8-QrtswsnRSibdp-6ksPwHHl8Y0wnPBEfslBL3nsMzhy-AycEWanZ3cvIhW2-Mw6z0XT40xB2xkhM1pj4KMs5yd_uR1witIlm62CX1KKmpTfBSAs_4kxMq6w-TkXrJyA4Q-oD5JYeCv4aPnHMPdKgAf9atfvcqFtQ3ua2D4Yg_qGRrZubeN3Pvm9lJRZ_ZSYWiX_vP_DShz-xko8_MaeRKHUGulsM44-SYuBTdw7aUBN9VI8fUub2H43f1N0-3uJRpQFzhZw1cMueTkm0uUtINSom_cLpvKRNkXdMpqJkrSM1cQSpMLTnaz7TUc7dL8A8d8COzfi2sIhf_ZPTTW91DdLgBYbko3w-aPS2Fsg1IKPdGSvcf5fGFs-1ReSDKuQ9wPtmcuwbLcWDv12xH3h5gZ18vBLy4odTe3X15u_ILrfNKd7HA4tjyiW_pFiUtfcpKS_c5SY9TJT16FTxkJScd7g7uSNc9FBX2a7znTtJzb-i576QHsZIexEp6ECuyv1y24epg-86HohzRpbLsb8oYU_ed1YAUhzAMPPwQFFefimNf6igLpnUFzEmGdBx7a9mjzofdIa36cPXd0cziTu6LUq5LS5p56zr6dAopfOVwN9hvdmMiXh2OE7K4fFBK0Suiw6Ngb-WAaE_RGdGlh74ci2qvU90v3FIvnCNTZBF_0JqppyiIPFuKjoiuq6su9FNZcMncd1NzkG1c2WpS2g9aEj02SoBmi2WPRpFvyZxilCtFM2cbpWeSlcyB9miIZg60Rzuo3hm2QhWqJkCtmVg1c4dRRyZszdxhc0AU3KEs9L2jiawCOqoYMhyNva27adxldEoDd9YpnaEc4LtLhDnCS3MqmT0odTaSzEqUOhulzkaSTh5JOU-ANRSnnsapV3K2rQ2embCc-h-n_sep__HMJlovO7reWzybg-qsQayWemVLvbKlXtlSr2ypV7Z0k9LDdystb8Si3Y3UKFFPvaWn3tJTb-mpt_TUW3ruLedQ_SjUx1NJqfxBCjB80TKioJL6mqS-JqmvSeprkvqapL4mqa9J6mvC82wPa_yROtVInQq_nzs8Bxh_pE410q1uvK9W2FdgbuS9itldEjpGN2RJM1OHmqlDzdShZupQ-L3e4TmA5LOaVMMjLdDNi2CRzAtmmDza7cRguP7NLprVYtC8tlNtVTeLVdmqcsEHrf7pg_anD8b3g3VqXTCsVXGyD-bnA3ZjhA-GY-VUftGyT3YRsS_-b2jsp9XaVBVtc3jPUDSRWIsNyQfjDxKvD1Di-t5vpgdzS5JVRGDZkohDm1XqN-K8pp6MOgzh3iBZMmrB4yu81jn8B93LFA8jlNxUGo67oUFaW7OT9Go3h7QPMgwZHolr9eb17r_nspKN2LVDG4kh8aRsM56UbcaTss14owRotu3u0RDFxd4cC2ojzCbthO3sCuR2BX93LPml_sFb_QPe_oC767HY4d3dprUk1AtQ7TVIRcStwYXUEDFOzh42k7OHzeTsYbNRsC9nD5s9Wtyy5ynhPMi6PnljFCeiuZq8IvxB3PflquuF2rTssaS9UccmmTYteyzt0UDHfqGc5zrr03Nf5ww98Y3n6a-S9jR-svdt1kG5nsVGOuwHTZdjT5djT5djT5djT5djvzKjifvmgSLtgww0j1Q0j1Q0jxaVonkkXQuSrgVJ14Kka0HStSDpWhgF1Rnnjgk__kh9eqQ-PVKfHqlPj9SnB_j0it3nvhTPltpMfWmmvjRTX5qpL83Ul2bqSxN8qXq0e3PX66pRg41EWW80cYIbTZzgoARo4gRnNESxzORhf0r_Xh19FaLzwF6ClcQ7bjTxjhtNvOOgIFhJvOOMRtG0u64EgK3CjfxFoZ9WZrp1PPWXI3NNNrLd84Mmzrd5otY1cb7DAdHE-Y5kYAva-bchw5AlEaWOR6njUep4lDoepY5HqeMxvuHmUC8rp57EyfHloU1Hiov0RlNf5CTRu-18oU1Puefwa-nct3TuWzr3rWdyNko5UEqbnL0fFHTq7r06RdoHGYZU1wu17C0bt6fe0GsmeU-9rKdeZtUTr08onixEcNYEv-B6oCJBHEk3NaxLDY-mQqKaWO8aHgVaLMUMj8JoWDIpDvUmGRMnNCvt3Gi66WHBZ3gUJUqejPXC6omi6caDVZnhURgtq7Sc0cAq0zm-p0OHmrhtFqyZKJptUAVrMcOjBGjmQQVrMcVxcI8sRdyzTpETcfqh7UdhasmKMrVkBZxasCijaOaiBQstw3NANHOegsWeFXwoC0tjNqH7KQtlGJD-QSCp2XzEAYRAR8DyoGWMrGxUS1Y2qiUrGx0UjJGVjc5o4B21oXdUy0d8R698behA-rUISeTwDpSVgGrJSkC1ZCWgg4JuWQnojAYak0vK10hZBehGU7fOKkC1ZBWgg4JUWa3njIZo9iBW1M6_N0-3b-vYum-TI3rdcr3M8t75WEs736LetxVf53cg5h9-B2KpnVWYNr8PmjpwVmE6HBBNigGbg9ucS8PNOai5AvXpITLNaajmo_7htzOWNll1qpasOlVLVp06HEDHrDp1OITa2uGwz3838NZ7p-tXrc27XZdN9CoLOrJmBapasEA1PC3IikWn7mjtNaONCAKMgFPHLqXVdoc2QftcE1mG63Au-6xluAxbPHIhIgjwp48JanfZartB-9z5qdundpB9Wn0Q9-Qa5ytI6tae97qZtzju6wYwj1g56SBWc13M9I4DtyD4Cgvi_g_WA7mOEn4LrOxfUvHvzpwxwutptUzLv6sDOJ49b9gdMavg4Onxbt7dzXn-XFWD84tp9XKP-O4Qm_i6f7oFgOK60KF4z-w30qv1oegs9YpeXeOFtbuDa1-xXQa0G7SPs61VoB3sLudaV4HGfkGt1mjOGu-D3R2qcVh1DLs7-0ZetZrxJNCTQE8CPQlWb93fCzm-ryRek30y75B2kOlJrA32sl91Ga4Nv6VX_Y_BsIeq86lGZc-1Ar3EybcfdFkEcNPDDdhVCKrQOu5sNoq76mGTMJIwsIXLXjeFRX0V7n64bU3xZ-0IrsWq5O5TIP3pvH7Ww3CA7zMRIADc7-91B3iKhsBAQdwXYF_Dk_3QxeoC15veAINVtYt5NMVfx3h-SBDaHdpnBSyPJvyFjI00ckiPc6mAOMGWHE6w-PsYz0qD9lkCazfUDsUNq0iAxlnjxQ9zmWzaS_ahKQfC953UJUH8fY27zdAWkFBvG3DiiG1a7GkCIgcZDnCpHblbtWQBlsh5gBFwvuIu4lri2-92kO9Bjkffu4q7lfNIQ-Htzd3_flT4PWijZM_-DQ1x-s2zUQXxnQ0mrqiJK2p-VtScq8B-Ij-GW8FugBGAHYPhCrB7Cx0AcCsAVKQQiUBDHr0civfLiDeyIhPeYQW7267IUThArsVEI5yhYNzfFLizOT9RG5Xz7sGG7gfp3_8PjN7LX2WAAAA=</s><k>k3</k><s>TGV2ZWwgNiBvZiBHZW9tZXRyeSBEYXNoLiBSZWxlYXNlZCB3aXRoIFVwZGF0ZSAxLjAgb24gQXVnIDEzLCAyMDEzLg==</s><k>k5</k><s>RobsVault</s><k>k6</k><i>169179680</i><k>k60</k><i>19293579</i><k>k8</k><i>5</i><k>k9</k><i>10</i><k>k10</k><i>40</i><k>k11</k><i>192343</i><k>k22</k><i>2864</i><k>k21</k><i>3</i><k>k16</k><i>1</i><k>k17</k><i>21</i><k>k80</k><i>2</i><k>k83</k><i>3388</i><k>k64</k><i>3</i><k>k41</k><i>1</i><k>k50</k><i>45</i><k>k48</k><i>1704</i><k>k66</k><i>6</i></dict></plist>
\ No newline at end of file
diff --git a/games/numdash/levels/reference/DryOut.gmd b/games/numdash/levels/reference/DryOut.gmd
new file mode 100644
index 00000000..adddc6ed
--- /dev/null
+++ b/games/numdash/levels/reference/DryOut.gmd
@@ -0,0 +1 @@
+<?xml version="1.0"?><plist version="1.0" gjver="2.0"><dict><k>kCEK</k><i>4</i><k>k1</k><i>77236593</i><k>k18</k><i>3</i><k>k36</k><i>110</i><k>k85</k><i>108</i><k>k86</k><i>80</i><k>k87</k><i>1973614</i><k>k88</k><s>2,98</s><k>k89</k><t /><k>k23</k><i>3</i><k>k19</k><i>100</i><k>k71</k><i>100</i><k>k90</k><i>100</i><k>k2</k><s>Dry Out</s><k>k4</k><s>H4sIAAAAAAAAC41da5Ikq63eUPsGAoEg_Mtr8AJ6Ad6CF3-zkNArqRlHnOg5-hIE6IUgIes__27zB35r77_1F8tv-6X1O36hlPJLv_AL_bf8wnz-zF_47yn4KdeBy8G1XHlKQalPuU8N4IpQ-R8G8fcfwmIdFvBu6vOXy--i9fdT6nvPUnH834u2a1Fon6Kfv23__ctIuu_eZTQfwUH9K5vxhc3Pf_4F7ad8_un8z-B_8Of5y_9PjMg_8_PPv9vaVN1_mcF-8C_cf_kpFP4Hfso_4aeun_rztNJ-YDx_xw_80A88DX0qrp-HLp__Wn8e1KfQYzBPrflU6m3X6occgRz0IVt7yGGkUItC2YWRBCU_haGsD40fmozez3fnH3U8dFWyRXJEch0SHHPCjyiKVYd2Kjxq9PWhR3Iqu7lpap_a6zyvcJ7v1mocKWCPdEce6lP6H6tElAyFjRKjkd5iQgdAbYfPWLG11YKODi2PaxnLPz60DK2WtdzQKkDQyjPw5gRVYUayHnJLvQKp1IGMXaPDvrZgBEJbc7UEvcrzrdc9mLbVCCWK9sAtyvapLKUT0FS6B5kqLjSj3k5VkSWy1K3Kp-Cnvx__uvpVK67iCBWxfirieleEI6PkkbWXKKMeXKF2dQXWQZ-qg81uVDUwMhoTbexH8JQ6eiTVU-qW3yD4cFeFCbeCp3kyg9oVCEUqCWg6XlK5BR0L7HSMrn4F1SBF76wUw1SdJdJrBroV6zF-JNq2Cp9AKTIQuiqpCtjVoanJk9F0Stcg3sdwIxkDkTzegYj7wgW2ue7hC8DhYbNoGqu4RkOtsYzWFhsF85HHW5pSH1KLUmK3uEeILFDRuJAL4uOR6AZHYFK9GoNJ3mKFhkTjsVhhoCPCFsmoLTR3AStNJ2IJ83UiVuuojZHR6i6tR332qM8-AzkgklEVQ1XBXRkVjiWBK7CtYVgB6wupIPZjwhW6zrQrDif0bz0Q6WNw9XfwbR96JkeZPdGgotnlTwbwg9s4KoPH_3dUlKpY4pyGxdKQT1cRghzRpu9ttPJYYx5CjGlYKVSvGMkwu2MdQarYgnlha5EckbTExJVmB4YNbCmvJuFPaDVmxGBPiDrSHRAQp_JbRtfDDfdsTjq_CWDhAbsOtm2SoqS6imbbgDzHMwFjZ19sMTgf2MXs-oGHqZHpleg41clztOcWqvdoBpDOFR4YNmBGeDrYPKjGNqknekZ6QqIx0SYxbvFUOBOQAE-xvg3cFyrKZpXIdrVEJ9Gt5CGrBVH1Eof5JA2Jjs4rz0MnT52iY1MuTeyln_zw0fNW89pg8KcOFsccvW12G5Uw2Ua1C1R1mt2GSwqZHiGOcJXglFLFyOCUvdVI9kjO2N1mc-4w2mXzOzr31lqEyZhlFM2GdhMY5gF5bKTKb7rK5ahqGocMUgTBlVSfOfwcQAagR2zSP1xm0yHBdaCU0GotaozrPSqvR-XF_LZbfjusLqoB7rAoddjEdkd6pVBss7LUdtvVSC4yzEX2c4rzF9sume3uljmb7CvEQ0HnCuuRPhuXjfTUyUEA2FP-5rPMq_dyvPQV6RlpsCix1-s1JvtCqyGOGubVYdkouOo7A9jJ4OBkEHRdPVqYWUdMLofloltN8tjS2SG5HzVDWN1NW7CEjckRyRbJuH48lbtuDEgFG0DM0EbM34Zld-BoNwBZbZF6ymFoGfTgNI_LbC4jCi2mgWPEBF5o38TA3AS1JDWKUqMoNYpSs7yR1cS0G-VkMSxlP6PUZpTarFELTDcwLcyqWuAWeC-pDm1hRRmtKKOVDGtR7DEVJxBBWCLltEAliIjiDhPF_Sey3am9bJDKJJ4spRt2BRYP-XjmaW36gH2qwQHRM1vNEOY2bDTg7G4ZoP2NG1xk21_gnk7tnQA9doTR5oTIiGs2ZtYUM2uqUU1COzVJbl2sBU6gXQstqinm2xSzcWrR_w9dURXHCFl7I7WHUZAYBWnpOY8IU0Agya_NzHqUUEqwT_mKxoFSjyxlH7vNJ1_64fU296FbVIVWlxVBUKajJKYjinWUSEaxDhU6eBq0S2M06RI3x0m31ytlg6UoWIox49AVtcCMUqB1pLAfzyjmGQ1xxpgqpQGtf5Lmb4TFOs1YN48VJbaiIa4osVWixJatA5__28CWmIlQAGEwSzDDWXokoxnKYzNDKQAWYYWhbnQK_UkYLFk8rVZNBQ-iepsx2Z-gkt3-JbT6lxTvVj0kt_L4s550vQC3R4gO4Rlv28fkBQCefUahNd4eOuTCB7RM9yBbLNt1piwlPgK1bdvPS5S9YQvXvd5Tqf4PlawzQ3qoXd4AhRh8SnXroOS6Tduqn8ZIWyv_1--d7KfBU7E_9Rp8qbe3bD5J4xzdN_hPTiUnb6uyqTjgMSjtKSNoDUL5vJH6yHZt6A-d5bo7veS6-BkljPqH7gJYzX7Wb6dfamK-s-Mk-2c4XYczx7EDv8KZc93hdofLFea0_g33Ozxv8OJ96jeMd5iuMFz7veA6-AXXwS94jXLrf_Fywul_vzrB8XkFQn9Uv1R16t_a34Yjr10u-t-dqVfZCkOGHXoXbbuLtr1kuF90trSgPoDtowjSSUxwuFLL26WA5lUHyF3Bq2EtvKsT7-rEuzr7XYJ9JgnuwfeeBt_zJpIgcfBSKg5eFl82-H51iDXwpstBVxQSyqbJ66MQmkhD0x_DqFR1pjnGts31h8i0u0Ll1kFqV3Rc0XVTAUGTycfJctYbg3kX6Hy5wXRw9WuWwyK2tu5Wul4Os1zpdixiubIKMoOsveFQ7QJ4Bk8aYgw-irv17HNq4wv-8gk5YSAnCh5lW6eVvfZ6euZBcMpa0cA3eMJBk_oUVg-BAldnffCrph_8qmrlo53jEyWFV2w5hPf2icP9j35y6uYYjvTUnesPjnJqvjtfr2b24NfJDUq7hsMHfyl_erxGXbSXCU3PPemzrSuP7LkM4xft4Rft4Rft4aKLwWG9mSHu91u5g_2LyPsXkfcvIh9f_G18UcX44ofj5YfT8ecsEzxiqwWFgMIQ6Yuw6Yuw6Yuwqd40PL8IcH4R4HwJUFyOK7xcbqc-9YvHTc9SOyZ-yAydH66PH7a_zVdQ1hddri86W190Jny0X8tzCbOA8mhRdSuHw-FhC1rF86iBB5S7-qHc1Q_lpf7l-TSfzxwuFsaX5x3HeDi31D-X_fBAzjG3NBC4WxrA3dIArrOw8kmdg8vkrDwU5UlRCj8OF2SRF_W-e-ynAVkZcfMb1LsNQr3HE6h324T6ss3l-afhCveM3iz2cDbRTM8ipiPQvhhh-2KE7WWEHCWEkU9gW7c48SVM-Kp5GO1qqi2Z6vBojIDQAFR5wyHmFByQpAMuIFHdEWn-LSIBfjF9_GL6-MX08Wr6eDV9TKYvvimFk2_2L-bav5hr_2Ku_Yu59qth9qth9lsoPT2s3cqVm477mWjjsKWpNOzxxazHF7MeX2LruJrmuJrmSKYpIUlOILYYkgQd_dJtH4BGNekwQl9Mjl4mt3z51Fm6mhZxKpY0RC-j5THQiombaEQaTBq5b0g9-BeDe-9rSaBhRj7QWJgZt50YnfefqnwgrMV84ODVcJC-SfmMVH0VdiCKinzvs0momS2FGl6D7PVLuYVJ43nfpHvwl01PXz5m26d0CpUr76UMD8fC9b7R9-D3oFffW33L84k2eLhk9Br0TuFoa_W9_yf43QbrfXfxwe9B7_BPXYRbKDy8YzATDik7O-3lsuuSvRzUspeDrIy44HF6XvVQpVbTlGm_NrF-t9DqfTPzwe9xtb73M5fnk2RVb3H18Ej5TK237ZV63yl98JdtcjipLb8T4NVN-dMbgeWbSr1t-01nCqH1vVPLwm_7_ExeIUnx127z2jHuT0Gi3vdhH_yL6d93Yh_8vnQ6eIoI9x1aqP2lfh523m2dnktclh0eaVo9LHT7ixyatzVq3sh9MucvdjLus-gpn5Q9rrFqXHYOFX3JYqRFskS2cZtFK31RI73UuHz51EG6JViV0gtYKcsXbrL4pXASP32xvtc-MTkmfoV5OpyGfd08fuC7tuftxcADp11aQfGyU1UnRb8E7t3cd5X4LXZzXcBuwDlwKYfMXSlwwceVtcOrEpJW3nD5DIVf3yJ9CUmsldf29PRw3Bis7n6chJ2VN2ae1E8a_tzzvL-Sbb4qdn-MHlqhcB7wWYCVBFQ73sxAS9fJGtoZwcFAV2AxYCdmfQl9Gf_MnXLX7dhIO1fiEuCY2imX5Qo4mlKjwqHo2Z5ThtS8haleDHhWBXL8zzoiSMkIZQBfdazzdnwGQjsDVazuLLwAWfDupLoAPQFrRW1iSbrCkqognxClNK8InC_SPevipZcfgAHQGwUecO_3FNIT8IDVbqYw4E5AC0Cp5-6am1yqbBkYGTAJgmeyDXEfswG0C2ttqwp5uTQcgBkgBZjrNP1LEV5vuDpcxAMjAysBvF4YZzS9YJRILxTNTgA3XkHIxtvtchpzhWRlvdYM9AzMBDSLGdz3jml0HVcGWhSilHBC7L2mOpw2eGAmYGAGVFfcyoAks_HqO5VYhZK7C4AZcAKZyQ-7XH0q8Ri44i0eBH9wFDwjRQ-DKzT3KdMmV7yXO87P14FLi3Yz-O2j9X-421TgAc9EzwZ1O3yksN4efJBwVwOGu2olwJl77bbGKVWN7om2w32brsn0BXCmLwih8qhxAhnxLOqpoEfyTgW75T3iTa-HbokeiYO73SWAXf9i2m4PTgeQzhwDkyTsgCkPE8uKksASbvE9QJIdmvtygTSzjngi9aFVUDyNCkBaYCS5jCQXOx4q9Io9GiVp093r4olaWNh9_UHJYijJidKoya45g0c4PyCHuH64GZdHTqsdLtMBPNtxwzNJcyYzs4Oo3I3ZdQIlB2AGWBrkeLrsjlmvpAc7cwq-gF5deoAVY5sAmAFnLXauFZqU2HM5ftTjPjZxWPm0OZ6guZ-VPBXTavv7YcndC6oW1DygR-cFXBZ8Lg90mcAgnjzdkPP-6VLOvcZwZT-oNcaioZ53HYftmfZ2l82uKEcti_VILiWV2CMuR7FDXJTeg5c932lcp95GwHe5HtnaznDmu2bSyblK70vNAm_Rz3PJ_iW7WfKiaP7NqnY1v_fmkaS1WetFw4JGXfKTZisZAciknEphbKqRDTw8wJX0MW37x5eTDZqopWmbPy_ZcQLlF5Tu6ED9g_TInaEQRBYwsW06B6hDP-ksqlyPdjydK60DBcAMWAgWwO0dTT1clpGpUWvG60JKLwoCWpzPeAGNtkUEX81LKsbQu9LnaVb6Ps2Kl4u0_gobQ4dLRscVXRHlbVkpzJc_pmc6we-wLNA4EjJUwSltZK2UsK2UsK143UjLpz5LrYzONBJfmEcSmM7gPau6q9SC6A1ZfJWTcPiM7gktqYY-c_KoOb8-3D3i7r4yV1_ygpPJuFLGRSf8YLkGTLoplV3x1pWWT3KWWhmlqx0JC5U152U6eK2ecuSVcuTVkiO05Ajt6gjt6gjt6gjt7ghtZPNpyREYxWTZKQFfmCwbr5aNV8vGbNnTF9aOgOexe8zlumYf0Ue7Zhr6dpNxdwXDI77k9CV7T4h8sYGNlXuVVgsr7cOttHo45ZMk-tX2era9FcaXEWeNDPO6IWWOMr-V8X1-k4os2ZVhFpd3WD3EmJAgLnnQnM68c4_mVOGdO62mVlpNrbSaWiN50Lh60Lh60Lh60Lh70GhZDVIwBwVpa0aulBwnreBWWsGd56lvdHUsSo4lHSG7RsxDmDoTRPuf-dtrrP95AnBC8nbpKejmgOm-dODdJy0PV1oerpncZ17dZ17dZ95D90yhGzxnvnK4gVWccNgi_QPKXrBKHvQqedCCtxdn_4BePpBWsmslH1jJB1bygXX1gXX1gXX1gZV9wBf2PiBNZR-Q-sEHainB5h-6J3om-uIDWiujt8lF4di_wwP02mAt51t8GjzBHRikr7nvqWidjjdAH5oSfTFprZXRm0mfwlsNMh6prvKernqe7xQfMa2tJX425qFbokeiV6IvdqdcMnqxO-UY7e6wMLtTpiH5PR3gQycByZ_LK3rXNea-1lQKA_pgxDigeEtuf0YYOIUH4_3AnYfxzOWETKtBSL2r2FpyrJYcqyXHalfHalfHanfHailrE0NsNudwdUzugck9MLkHXt0Dr-6Bd_dAyNYiBUOu-wg7mXtP5m6f2pmu_OvzmoKn6fOws-nzIPSq7966egRfxml3lJNx9qGcvQnqZeiE5Dnqwdd1jjoP8hx18JqFmTTUr77fr77f775_Tto6ZN20mb7MWdKnOctIPjCuPjCuPjBua_LDguOwR_ws0tZfNui4IiU3oeQmlNyErm5CVzehu5uQcxOPZMHO5CYzaZotcNp7wuqA9LGrA0N2lukWCmxmvng4Kcf4yM2tDKTbar6Yod2jO6J2X9sj9m7AF3kBkKu8AN6ZC-3MLLfPtuZNQg3yCAOSvquj4i4OcR9W4K_SPhodMS4F3K-4JcqLCWi6wa2vmlSwegZmBvK9Slfvhc6b6vQcsiH9hcw7AhnAzMUD9QpArvJi6tUtfZuZizeAVbNauVZAZkKgQBQtFMwAZQAuYoaCV5Quwgc9e20IvhB6IZCEcGrNV60XgrnSC4DcEGQerxKYZRIEiy-EkpedlsMJUm1tRUlCSWqAloGRgZWBctMR5Pt-jtsLvcVB0KPqhrQXkiPj4eWRkrUH7YWMF5KjoyCYAchcXgDmll8A5N6-AMzy9jYAORpLwwFx0XjHcJAvBoZ9toNymOWcrHrczk8GeF65NDu_Cb44oH5g9IE6aoMu3gtu3eOk5nC2pKbilHfSn0Hvk5jt_pX3UxctIZrnffbnXNy7rplonUkL1UIyOub67rT78Zo2a89A_JJlhRbfwVYHxm-5VoifcKxgX3hsjtbjRhUwnjE4AGbARRM8lylOvubRvbZFD1XU1RbEz0E-9Eh0S7R9uK-4Cnqk-JSIn_k8qB5prdB7GlXvaVT6KZQwqnNw3o1KjsfbGhLiVyi1hNHhVFAFd6pteqDEtod7mYUBsh88gHS6rQKNpOEFaejutz2ErRx5hqZtS5lhfPXomk--Ib65rWBfeqzgAPsJiVJi92pJBljTT40cwIZ4gGiAB3UGKJAzwBrf7NYa3_zWGt8Mn-7u8zTkgKanlA8L-8mGCsnWKvQkcEGcwE8ZE_hBosCrvdrlUi3LE2dq3Z0oA1-E1Dtq-o74A8TlXo2vkU4F88va-ft3JoSRtegOTDOP-CbloZPo3WcLPcvdbZAiyDeUVRrpEPbn2lMGZpKX-xQ3OcB1dCWbse1tGfwiPg8qMWjzbXK4W0-mH4QygBmw3h4gfObvoO47fwrph_4eJAalljazm212V2GxvwKpntqgtNhdBjADJssGK5dYLQ5IqkTXPahzXYHYdffh6MNs2BDSVnZLW90NRvyBm3Y-baDdqTX1r_YMzAQ0yAAmADtFsbifvJgOSHPNQYeJz_12Bvoy1TF3P2kxPRAnk4OGH8-RE8pmM50_v6-sxliR97Cj05x8takvYfW9xPndqk-69iRQ_Z56nZr2Czvr3NuBDq-Kumx56iV5z5aAtaJdoltXTQbcuSVfRL8M_gCwIhNIEQ3T4XwFoloP6lIIgVwKcRCjR6JbouMXSk8BPcxcMX4c_KF7os3_iwMstUKXmDbHUnMtFkuzZTs5ADKgH5A_gHUlJa3oPjzu23C_S4Todo7JIyUjlAF81TENYlqMgke70yBDrZgGU2qLKbXFlNpiTm0xfdu8YkorMaWVmNJKob0EeppxBMAMOCvva6Uqa6UqFgPA12H1cNdG0mj86ZyHpth1DjSuVQYwA05VAvBvcoBrlbQV-zI6zyBIO3o2XQ4hWaiuroRN_kg1hETkOyG26kP3uzlSIt4aeADKVTC1yiWcp61C3tOmAx8-_w_xn0jPSXIAAA==</s><k>k3</k><s>TGV2ZWwgNCBvZiBHZW9tZXRyeSBEYXNoLiBSZWxlYXNlZCB3aXRoIFVwZGF0ZSAxLjAgb24gQXVnIDEzLCAyMDEzLg==</s><k>k5</k><s>RobsVault</s><k>k6</k><i>169179680</i><k>k60</k><i>19293579</i><k>k8</k><i>3</i><k>k9</k><i>10</i><k>k10</k><i>30</i><k>k11</k><i>188099</i><k>k22</k><i>3058</i><k>k21</k><i>3</i><k>k16</k><i>1</i><k>k17</k><i>21</i><k>k80</k><i>2</i><k>k83</k><i>3390</i><k>k64</k><i>3</i><k>k41</k><i>1</i><k>k50</k><i>45</i><k>k48</k><i>1444</i><k>k66</k><i>4</i></dict></plist>
\ No newline at end of file
diff --git a/games/numdash/levels/reference/Jumper.gmd b/games/numdash/levels/reference/Jumper.gmd
new file mode 100644
index 00000000..7e16fe01
--- /dev/null
+++ b/games/numdash/levels/reference/Jumper.gmd
@@ -0,0 +1 @@
+<?xml version="1.0"?><plist version="1.0" gjver="2.0"><dict><k>kCEK</k><i>4</i><k>k1</k><i>77237545</i><k>k18</k><i>15</i><k>k36</k><i>535</i><k>k85</k><i>174</i><k>k86</k><i>86</i><k>k87</k><i>2581594</i><k>k88</k><s>76,24</s><k>k89</k><t /><k>k23</k><i>3</i><k>k19</k><i>100</i><k>k71</k><i>100</i><k>k90</k><i>100</i><k>k2</k><s>Jumper</s><k>k4</k><s>H4sIAAAAAAAAC41dW7Ztq6mt0MppQwWUlq-UIQXYBUgVbuHvnMMH0GWd5GevTZ-KCggOn__5dxs_5U8h_VP_VPnT_lTmP_KnPM_zp__5_MJ_nj9lfP4Zf8r_fejySfehPgk_Kd6EJU34fJKVpy6Opcw_df6ZIP35R5ksdLMonsU3zczgqlX_fFNlJabJ6X9P2vIGt2_S77_t_fe_tIR99ZLWfCVX6n9lI7-w-fnPv0r7eb5_eP6R-Yd-Pv_O__eJrD_j--ffTV-qvv9OBu8P_6L33_lreeaf8vP8s_x8GNQfavzTfvqH1A_F_KXqpsamypeqX4o4kEW-dH2-gOgXaB-62-8cSY10rUAz0CPS7eX3rZsUX1OhQHVf75mycCTbqfdMfeq9fheOtEbaKr5oBnpE2ireH1_VLoFSX_HegsAnOStWLHXRnbntzN1ScyQ10taKRTPQI9LWilF9vUcwlPEaUedAzqL10LuekyIOZIlkA9qqtWgG-m3Wp-Mcfg-twjWYjQZDUTpV0UN-f6zl5Oxb-GrC7yfxMbJF9hZ-bjXSVYEWoBvQT1t1-_oh147ySCSDHZVnKv_h83tLfp9SqxPpuhrbLUHnSBPQBWhTywYGAGZPpQTPU0qwqE9MMttXA-D3yf_jEA-Do5_NoTEADwAdaMIMQM8mvLa2U-g2tlKDtZVKkQzWt349JrR-duwnQId7izbQjlJfATQtgV0T64av3yutlu34XAoTwKQJ6AK0-ZANMAIDgCmzVcul2B_-KacialUdruST6tPSD0ojNJiK7upVtd_bVwfy81aA6ecbFD-_lq8N_vBfL69Phq8lPN-g2B7HeljWRz9Z5ZO1aP9mpb_UZz11J3Ze2ljNxkygQutWlrZbN1wqieBIQBdoJ81AjxYMgV0AmwAh0A0YluVT5VAuZWCP4MtPHihAGshEBKQmasAwHlCatEQei1cU5-IXwQ6S6ibJtxJ9pLRVagEttLZXaEtnzJYpvNeE13CDlQmQea3hUjyB10zVI6upGVPqBKJAtUWJqEQJzKhHRqPeVBFo0PgFxMZrpjMFnXUHGv9pF2y5JvDxbavxYtk6rWz1ASXVh6Ok6zOipHeWUMed7YngCOJ_sdJDvTd95LKBoP9aprrJ2EyglJBq2sA7uhgGaFuJvt6w1hMeJimRDCOGWp-g50U7cdURosumT3jdgCCgAFj42AAjMACw4eCulwLgmT4MTB8Gpk-MSZtpsLsNniHSR579q-QfMhG3MCj-CDySNqR5i2mke4Ty_k5hsFCJIhkGCyuxyZ-co-gOUACcZAg-XDYwAHDiJvdtVFy1rBEcxiSVo1lx_KJZtDMShs-UBbhaMwwtNzAAsKHlTnHIY_m-SFMsn7Hv6zpWgr6HXVWiliVqWcLAdSU2PQkMQzcgCCgATgQCn8obGACsoamrlumpR2Pr0bp6_BJaNPzs6twJqrgARmAA4GyrE7S7EyhmVtIUMxOYYka0vRE93NBIhk-gRZqeRgM9jQb1HWh3Ay1zoO0OtO6Bn_SrlqYnjcam0dg0GpvGb-lFu_KUoUYK388bGAC4ditHSakf8IohRy_tCbbWHopkML316wy7DrA6b4ARGABYnRfQgSagzdRWlY-p7QTt26b2IsU-id9mlGB862cjJZLmFoelfrVeu0uwvj9OoXXKuuzpulaDeazfjTTzmLSEiNPaUUyd9PzAbLy_ep5vQKTxST3e76Un_Vra-Z6Tr3_ylf79Wup05XuHLcXyFT5CbNE0Wo_1bxZsxP3-aaX8_EOfFb83zDt-kyustT2F0ihqjKLGKGqMjsa6y-tK7o7HBUsOK8LFpeY9HtmFsR9P7swHnHa68lZxw8NdKz5disEvLGD2sbe5HO0qTgs3jiOZtud2D7uatpc5h8ffpTYxnBliL4aVmf2ouQlF570BQUABcBKI88stTjA3m2F-p1JOiYddSdsklMOXHfvUJoEz1ewlID0zhFWhJxhCV2j1mm8239ofEFR_MMtjsh0OePxoeYEX42pdPU6Dtx57X5wWbx38ZZdocD3vjj3vjj3vjv3qjh42LZypcq-FLpkWlsAlaGFNlpupxbn0NmJns7n17hJjLUfet0bet8aANo2sb53JdfcZ2eIEetPYLxQ8tpaoKM37heb9QnP_rlk3UMpA6BtfrvQ4UywGmI3vFNVSaFQZxel3elokJZLRehd9hLJ_ZywfxEFPas67tAu-zHk4JkFOm0W03i2XY71vY0owVorT9lSCsVJJjXVnuuDLWIdjEmtcOANHou5aQN0Vvox3CtNunLanOG1PNdr4-tnUWVMb31wuOLXxnTq2r2aufrcnOBlqzk13BwgCCoD57A0cL7GAs7C36HcYTQ74h593orhKQS12lRa7SgvDrJ0XZdbyjtDyjtDyjtCyjtAkA3Go9QWpgtFQ7BgUO4atVUwfsFcFdiUJvuk3gI2hvOtQ3nUo6yWUDJmIYdWbGHuJXzYYLsX5UltAN3NYWbo3B459i2Pf4h70zzBFtQFsPud9i_O-xVnfYuxbX1CwSwgMYzZwyGjdEq1bjnW_o0baKxXAHZshublLbu6Sm7tk5i6ZuUtm7h1mpRbgRNMriKbHDtFjh-jQITp0iJ7bf8_tv-f23zP772j_4hoYg92IxjqisY5orMPZptVsUIp2QIdLG6s7MsMcMJm7gVf6n8_sk-_9op5TCOW1Ob8e87ZCowVrtGCNFqzRP-uTNU5bikqKaiYITb54NwMAwVira8T7xb9XfvmTvn8b8YzfZzJ2RjoZC7e1ZFzqndGqAb1rjgzURgbFKnumzvixyWE1-uy-euJmrCeMrXbiKLmN1tgRdkmaw2JwcwVHVW3Udmg9MJu4AFvZ3rVh4y8unQRprfZNaYnlpr1mxyXOSnMJvZNL6I4rtQm3xO08XN79EWeKb_1-Vgi5wqYZrqGjcFxAY7eA5ujjzxa7MwW5aALaqmvLdbN66_d26tc4ZoiLTxwXn9gWn4Yl9or3MJpJu4zK1-AsCm5AAZgWQh7pexaObV1rklGntgj2ToB-Inf_cbOuHJebOK70MEcVcfwOW5lfFdFj6Us5lYtLPRyXeliiTIVTmQqj8HxqBZmKmxxwgJOpuE0I5PO8Mp0NmcxHO9a4Szsp5loK7xXjRcfV5w26otY6kUkoriNxp0ge5a5S6ZQ6gblk44GGgCCgseYDVmuHsUFQkjYOWNnmsCbjsjkprJUlk0JceeIRzTAuRPEAMxxmhsUleIE3gdrGtCmCCTiZ6JzYtwrFZSOOy0Zsy0Zz466ubSzH2Sx-r7N5S5BH301EtEuQuKgjcVFH3KKOzOxzN8BeE5K4XCJxuURsuaS_pO06cbTb0atHQK9IF_cjQaln35TvgxtuCMcNVdII6LiVQxps0tmAWcxCpsW8POiJPChuvBFaTXKmurAZkcgjpzMI7P0Sth1Mr2Bhn7TEqYxFn6AluHV60q8iqkvwLjuJDaYX_MbSN1mPwU1s8re0l6a5e6R_6e0LBfY_C-5ZFty0LH7XcpslvZYkRmtGV6W9s9DlMrSqcXeDw-_yWP-ujlV-fh9Uytk77fN9h5Qz01-MQ8pZiTkna1Wd07GOHhmNTVmTuIjWDJ0Tq8Zxjl8d3TP64kK_8wa0zylGMboBLUBrRl9cJUXb7zVAtETZ98JAj4y-uGSyX7wRrVH2vRLQPaMvLpnsF29EG8i-gewbyL5pRl9cU9m3VPYNZP_t5f3McB3ALVZMoGKKuMlmsSjA4XUkbHQBejEUh4R11O63xU4AppY77qRdQIccdqRjsuynJlxizbgDTbElTFl6AnrW0GXwgNv05VMM5DGlM2u9doUe1_hBSnSN36_mb1j4_pp5xpePn02bQENAQNVndivyIGBBwKEAA5OYPEC37HcnDmloLAs5xvKNvL3HQUSHvcbd7S126b8jEs-EM3Ak4CiR3SCgO9AlY0IZ2BNQn8gO9g13t2940gr0kzFtGSgZqDc4nijx8TDQA-hE4uNJJL5yAliixEchoDvQicRXJgQTiY8aJT5qAzqR6EpkYHnBOHoeVTLautjK4IA2glcbzfadTbpmtHXrlcED7rOXLUsxmoEeGU2Q3rrtLmFACXcKPh17JTlTQoNKbLffUjsBgnZRR4CiaCg67EExAKz0ju5Alyy_axURAh0BH8WeF3na8e9TEjPTK4nX4a8kMBZWfcfC_KvHH_yAKfnduy5FgQRm5yxAa_Y79APO_IWAvxDwF5L5B8n8g2T-QayTdKMJaCuugz_p4E96z9JDoT3zJz3zJwP8yQA5D5DryPzLSDz2yolgPDu2aHeQc8DZsQ1UBhbhwMpQUKKCEhWkrJlSNdOfgqa_1qiPdddJw7HPp2S0mbf6vaqOow3IFlCAduONjYTBqbr9qJMWoOM4adHmmRYDc2aLwwImslrbThJFJjZTw1aKNaY0oAVozdITpCf43UmvCAIwfttZBmYZUIkJvN5uNRy83Rre6q_eTivEPa3wbaN1IBBD58pRIIMJqNaM9taykDA61RadjcIUl7YOdOJstCV-ZXECkKKzUZjtUhKgFejE-Sglnl4JnE-34sy3KDkbcBX6isrxgoOVygPoxJcoJwFCOXEwCnN1KpmMJROnZIIXtx2jG9CBNlNxk3nlE80PX3UAHaDNniA21HtL7aDZDprtoNkOmu2ZZntLlOj3YXpgQFnISxPNDtDsAFUM0PTIND0yTY9M0wq9SzNNa6ZphXiiPaPNf3xvWgl-_3vTSPAo32tQEIhOevMgBHwKQSCen9lMQ83g435zCYjbaOmLNod-kIG1CQh-pG9oDmGby-Z3SLywuwdgAQzicDcDeMC1vrjdMZ6Jb2vxwaBOaA68qQNn3_xSUbDFxYjH14f2OZEPYtttxAE2ot-Z3KaJIR8jFPqbMX3zxbnw-G6aeKPjF8jOf7g6nAX98sB9CQ9cmPDY1st5g8FT27nCYLzAuTrAjY026tahD9TtRg24TuGJOxU_NNyxYXsVl0jXjsqHrNwHTKntI83Lie0khEBxgFv28UhHgK487whmlTxnIv-5FvQ-tZw-rpgA4g7GD81AHxvaLNhYrGImZHbHoFEGjdqGv3ltx7NvFTgpBNQioBYBtdgmu1VLsQXj4jg48bk5Qw9M8S0mvW9DW9peaR6ykrqty6oDrG4dJOo2wfkErvUD5DdAfrYHbVVr3xhgRjhgYLCRjgAhMF3KcAW5minoRUEvCnpR7C57J5oT4JomtCtJnnNbwKmaNmyOoj4V9emmJ2dJZU0WmvWXuPnqQzPQoKvNYi8yl1L2dJD3PRtl8z0LanabT4lbmT4kAR2vilnpbbvuQdqFPIh0BOjK4wS15h2doOI-qA_dgBagoUOuDJPlhtzOm-GR5sS2tlDt3eXrnp99BYApxm29mkAD1TZQrW2Oqh5wAc1ujinjjbLll1i4s7pLZ2r9ZC3fskrXO69ZyprjdAqbSEeAECg2ztlIO9cEFQLjIjAuAh-8Epx9iwewWz02DxdRN9SdWukNz-wRuRA9yHBA95xlRvn9OdBCLZ2xrtlRC-qFwVgZjDVeUPCh4Q6kBdgYpcTrAzbtNbAQFxlWNXzFBGxSwCZtc9mMrAvoJySVfZXAqbu_WyAg6mS5yiWnAbm0JJeWBLUkl5YkainUYFpOq6Ftw6Rh28hmNjfZuRJQTADTl6XAxN8HGAjAPUnVnQIvE4hfWzuFz9ILZOklSwHX-GxUroxONQuaqpnMKla5QitrW20IpTVbdSaP2A0xpbrbsiYwr70wkVcZfYl8JpBHo3SkYY5325iF-JXi3cFbV55zh8PM0ssuZNEEdO9e77VXDf1zAYSA648befvj7Dt1b3c85YwnlhvPZH5oBjpsxv7QU5zmuxfSESAEnAr2TsCozeEOoVCAerNEk1dzzFrKrN3MGvrtT-te46zltDce-_zQcJWdHfxcLLQYiw1Ne6nl1HEhzhlVlY6JJvImKsPVxrazlvbAIL_hlYUN7yxsbspCJwD36cVTnR9agIYR7eboDK09vW1DWzUtsHnzg3D0ra30s8t5J3kR-7Jo8RjmlwfQ8XjNB5hSPIOiZt_aUxyVQD7uPkJ1gJUB9xeu37v1vM3isSsLrzsLQcbwkd1ajM8rvRvmbuRBpCNAV57TWTYQO8uunOssG-pna_WuopOsfUfXSa9B29ll6uFywbZuyA4gBObXqQPWFvNPaPznPGexa9Lzkt8ifDq_R90ntC-a5huo4hC-kHGQwMudBWnNi0d4T8NVz9PdRjIP8XwH4ZRvtwwFubNgXmxuKq35fV9z-L4LtatM4l7N9B6TT67lyd-JkO5k5FrlG9su5XnEnaNcACHQwUbcvjJ2WTzQU6BgloJMC9Yj2JmvcfZDv35Y9jGzeIuZ3APSD-Jr5FWI-9lOkYztcNPDzW9pC3yGuQS889K3tF1CCUhH5JwjRfmI_PZD--0H_e2HB2zC7YzzgK_WcpTfFuY1--U3zX4b7jcT21LlLNsrdxYeELkQBQPwOwbZC8ojciG4htBwV9_hMy4-4-Jz5SLMRJjnAgpmKcj0Mp92aS4gciGKSK-_2E7n336ov1tB57_5bfxuIecocehY_cSwYDf9CjX9CjV9gJX4o8jsG-iRKxqcHZiYa1y5BuYizESY5wIKZinI9NJc0OUVSPoVSPY8b6ahQVHeC-0pWlLdjMuFj8uFD3PhvlwXywbGsnE5-XE5-XG59EEXcgWCcbn9gXFzYNwcGDcHxs2BcXNg3BxX0BhX0BguaMx-ojAmnUO1c-OuWxs_qLsxW8EPV8fTNMku97r_3eVGO9AntQO9fLtevl0v364KlqEPWIab16-OScdqOtvRKz7oFR_0ig96xQe94oNe8UGv-KBXfFCMwYoBQzFgKIYDt3jhmRYslxBw1qVXBNErgugVQdRFkNeq6AHfPXW5YKddetBL0wMfBCuTaXPl8cBA4AQwZ5b0cIpCQGHPwVRND4aGndMjGBrowdBAD4aGlYswE2GeCyiYpSDTgjJpBeUYEAwN5JaChgPAXxAuaS00ix1UIHYsvZcCei8QAVbGF9h5ZgEPAase4bnbgfYl2XqEVDCEbI4ewfBABYMKFQwqVDCEUIEQQoUQ6ClQMEtBppe-ggYxhCy2HqlPpqgKjpZqQ0AQUFTRYo0qWouBFyw5rBH21blqLSkKgYp95ZxuK4aBzc8jGAaoYhigimGAKoYBqhgGqEIYoNoQEAQ0BQpmKci0YLHOfdd9VyPYQrAZDAyroIDgpwU1dOYNnbk7NLK0v5Zl0SjW6uwFj8xWWhoRWhoRWhoR2hUR2hUR8KzISeORK2rgkZPNh5ANYZ4LKJilIFOn5TZPUz8O6QX03q6o0a6o0a6oQTAzRYS-nC5fvlafUZ1EmTopjTdEmeLocvJ0OXk8DnPSDExDCBTM41OgRyf06O7cjhfMFR0JQppnFxri4o4XVdDOFRHoigiMvp_R97sVcHZZXGMZnRej82J0TYyuidE1sZvGXxVRrFkazTiNFpxGC9ZUCZzHMs5jGeexjDXTJKMbZ3TjfEULvuIQX7GKr3jGV8zjKzLxFb38gSwv5WAzV0TgKyLwFREEI4JgRBAc3kvqzCV15pLOF20WqBzJY4qMTGeCXlrQSwt6aUEvLeil3Wkzn8XrS664I1dskisSyRWJxMWd2blEO3Quufy_XP5fLv_f0f939P-9I5B69J5-QXTwkew4OGF3dMcd3XFHd9xxgN3Rx_fL5fYrmvQr4vQrvvQrvnTnupfddZw5W9kCYjNnc5WJerNjmV64QUNXDOhXDBgYA0bqWEfqWEc2M7TSepb4BTFgqmYV6pQ2MKwMDCsDnelAZzow8AwMPONB4PK24_K24_K24_K24_pWGJe3HZdHHs77e8ldjm3gJNtiHxCcZFvsX2R6gnWyBT7zx-Xzx-Xzx-Xzx-XzFX2-os9XWN1eWZxOFZ2torNVdLaKzlbR2erlbPVytnq5Vr1cqw5Ul6bRSdNPDXXu3AvsUrZe82lq82kygb0D-MeOC5Vz42SYHd5p3YuD6xwRmIFeQUGvoKAYFPiBoMAPIQBT_CsLOYAQ6ClQMEtBpgWzOBXzgy6dH3TX_KBL5wfnfHYaRiGAGfCThbnNrwbV8bM26EBa9PD8oIdf_DxSwMNzaQgIAuCfuYB_ZjiLu3l4QFOgYJaCTAsWW5CH1xme8T3IQL4BQf_MBX04FxyLbz6MskWdlixYcsm-QnYpdk7gCaJoUFRQLLrlVURA0C1zBbfMlREAt8wV3PLK4oGRAgWzFGRaMIvXQEW3zBXHwBsZV65xcR4oBNRFzdz3zg09tLr9-Z5nEDU6zMWruVY39H4NPVfDgeZGXHta6nH2we19c69H596rGx4IZ9MtG_V1unxng1mPVQJhARgx3Ibl5vJ9_qGrBq_cxDe2hWi3UTsbsxHFes0ND-fix1N_jRdCHlx-wZu7xHWVOD-42uEfcfkFVxOUl8M-k_nF1ct17S77NvPpa6PaOqtJ-fmUndN21X1vXVxHW3hcOQsozVt2c5EoVLdsvc3dqzxP17str0xyIfFa1w2cq34_QNw6yvHBrs3T0bZ11GewYy3MrkN7xK6Y3EhHgBAoCNhJ9YMMRNqVq12MmxNBfJbr8DUaDo0soJ_2-YewPOKrhq9nHeRBpF9JECAE2pWk3Wlci-MzXKe6RsOJYJ6nFtyGa15XEpCHxKDJp4NxdTCuDsbV0bj221pHsOtOAXvjeiFeAiuNXEi7kAeRjgBdeRBoVxIvajjywHDkge3IwxL1-vp2cl2fH06ucG6A4dwAuwejxLOQc35VHnf_skecze407UIeRDoCdOVBoN3IlckJUuAcgcA5AoFzBALvQ20G7niDFHfSemaCAwACBwAEDwCsDHa9_mFqR4WldhOjR5wv22keRDoCdOVBwGuwdhT1Qi42XtRwYYDAEQXBCwNWBmez0t5zT3a0QuCIgsARBYEjCtJQfe5AwJL0LKOboEnj4aAFFATspNlOoZjE62YhA5F2MfZiXchVG3vc6IOAucHdAGJ3A0wazv0LnPsXd-7fJzD_KYInqhbSESAECgMTF883whcyEPFCW8hVlLdFuKhA4KICgYsKBF4D2gm8bfb3yJ2dkxS4UEDgQgHBCwXEXShQxbFwBxOWjfZ5YMturxB3TcB7TfdGCp17uruDnXD89QEO8HrwuzwDMhDxeljIVdTUwxwc7-oo-zMco9nY-Jez2zuj8P92-KOt4l7LFQd0BKbxx9uPdzq4ZXyndtX_HhvfY_s2Zwuw_jOnPlDw3OTnAUFAEcjuw96cbji77XlzRbjPrWriAEZgIFBzTpzDI4Xn5inHtRACHYGSc0o1ubLHi6xLd5t8xgTWlJqdgFKHu9JrQ0AQUARSvS1ON5zqbXE1eHiUr3o31GdDfTbUZ8v12XJ9tpHJ1e_YWQkJNUyoYUINU65hyjVMPZMM7Ss2wiMum8mMXYsBo44ZdcyoY0Ydc65jznXMuY451bHtoogtOfsojIGg1gW1Lqh1ybUuudYFtF49k_cTGM8DlnnN1OUXh8tI2DS3qr8K7mhFHa2ooxX13Ip6bkU9taKz0AwV9EvSi8FAKxpoRQOtaKAVjdyKRm5FI7eikVrR2Jt4oCXDfYwtBopWpGhFilakuRVpbkWa-g6_EDh89su7jQesYTyEQEcgtYaV8YYzaxh7KSyKcLgFsZW9gC0s4CqmpIodJVXsKGnoXkwEswtmlFPhgkdSFg8_u7qyVrCFURmBgUBqCyvjDWe2MNwKxnC5r_g8GlpCQ0toaAktt4SWW0JLLaHlfmG0yy8MQlsg1BehvkgRyM2HcvOh3HwIzKd63m5MO333eytSPqQtjp3byrrKDS6mVV-27yKMhsVoWIyGxblhcW5YPDLFsT-P7w1J0JAEDUnQkCQ3JMkNSbKB6OZRTYqy11eggh3tqOdG0XOjwHeTNpz7lI422tFG7bWm4RldPaLbevfKmT5w9IFzNaZPJ20mgtkFM5rTG25oOlyK26ek7yF94Fyv6UtLm4lgdsGMVkG1T_XhEtxOWdOHkT5wqnlNn1z6wKnmFZ592lwF-QlyOqag-57baAm6p07NFDR9b2nDrgR44-kDjDTFzSmLLuquka0-u1-0q98bVr8Pka4phnwAq_auPegIHo36AIRARyC1O00fjtrZsWnVzd2shA012lCjDTUK70ltHlcd0rejNr8bzgam2vDLuzjW1hv0XBSLkia0FkJrIbQWyu2OciOi1Ij8K_MrIaPOGXXOqHPOdc65zjkbjCjnn7qLiR_aq6AtCNqCoC0I2oLktiC5LUhuC5LawrlDAlrib5JYDDpqvaPWe67kniu5p3FmwebbevrBqh0_WHWgLeBcpOJc5MpyVSGfolScoiwetfGE2m0C0G9wSlJxSlJxBlJxjlLzKUnNpyQ1n5JUnJKsnonzyfK-XEbjv7jkfTYdVOROqL_l1gfmPD8AIzAQyGxqZ7zhZAh6eICRHyb2Tvxm4PaYLMYwa_oBCIHMlna6aDQfNK4SboAQOKsGG7BVg4Pwhdgt6h9o7qTkswOlPhV2oHwQuZC4A2UDZ4XnA4QVns3V0QJ0XBncCc4iV33cocjuAEKgWCXiZbYfmoG2JSDPQJGlF6s_uxgQu0D_MDqXudUnXiz7oSkWTahhd0xOHYA5bEPEQRQRX326rCIcl5vqpXkLZDtlufNl3QGEgKsugwEwGACDAcTbZQ9DxSJ8Y_zpr4BMXfiCbYn5sH7Ohf71ERxvuldrCv_61f3JODXdrAoLeRDpCNCVx6QnYLkClitguXJZpT_ZVItj0k0Q-310Onx6x8p39EUdLbWjpXaw9fjS-c5QoVCv2H5Zab-tdG1WaieNOwTjgbdm4oBzlcNJ8VjlB9itPVC-crj7QorL8d423B3gH8vgF18TqifyFLgz9wCPv1vxoHa_94FGs6zxdt0DIK99566l2wfeYrq9K9OVOSFfpsliJnG72ocD5rr4K4RS51W5VpLbPj0cYF-DtVwbMb-9s3ykrXuZOh161NJQwA1stcSdkLVQdEMFHh-vxb3HNO2wUI_esrA1oDuAECgWMTby-qRZVdm31IeNtAd_fsEFhjHF70gMSLsQcdpes2bFtA3vF9XiHjCaedwLRlOatvVv0nHfXC1x31wttm-uTbEMOde7Lmmv94jayRO3zdUSt83VotHbfIe3H1r6UcYEkG7mJxcyzxcOV-h50KDWR1OtbBy1uHG58NqPeb31r-sFHb8L-Zu4_Y3xF5fRqXkjz4U4xS_IKb6WeD34AaLL2GjzvAa4qVoL8Kol47X3njleCxqnn9U2osv7jDERqAeYqlx56ES8Su91waJb_QtoCHzpxg4Ysk2s0rsfqBqtLdICdIwpHzW-p1VrOWVORBEQBBoCxZiOycJv29-opGhL0QPOunNtoe5dNMq8KwJZINqo1_CCXg0v418bfPBi2-_jqR9_9Lvnr-PJCl2oL3RBzqzgAeYPIAi06OdafADlQw-gj9-b_mMlsK-b5q5GUgcYi_jMyYc2t8YuwyhnYNKKbMc2aXfHjTrAeMJHWoOPtIYfac09HzIddmvvJfWuHfAN1uAbrLkHRcgB_ht7cqYGnOGTqhFIyH0wLWBt610nLsqUCruLfhayF19332pnywciZ_Xi8LH68bN7Sl2AXMb8nUHp9dcJlO7y-VuaF66ID5-e_ZGsk_qg4mrteQSpeBk8lwzcocAglYubVMzrr2sIiJ2wWjDn8AB4-NTQ9PN15J1B64RN9NcYBMRV3N4SDvWx14QjjMfGhmcC1TxfPbua4uspEmo_LpP0J-8X8qSVGi2HJYc1bcI51R-aMFLTG5rJXxnlfw6II-LapLmZaG4mmpvJOV0eqqloJuLrGeVPD1oGPWg99KRGQQ8axYLRsoaHY13pQVt5Ub-RpDvEV9MfCV5IaiZUUjOhkpoJldRMNm-o_TkqHFE0E_GNAvlXtJWNuIbV1FZ2wgtObWUzgbrWzKVQwxk4ajiTQc3NdszAQOuUqxvif-Lrd_7p-fvIQC11RtRyu7vOsA7PBBpoO2qCMvaJ0agMgjNFG_HtpssS6bJWcueXFpIbIeVGSGiEC0YDHx6GhlNqm5Tb5t5iE8XBOAW4EC-Os_EFEC-OhciFOEFzbuOc2zjnNs6pjTOnbV4HJWOTpWPF5LJ8wXm-nUsvxDVZchuX3MYlt3FJbVzQxl-0K2qvK1aq4-w0dZydJnyF-eRqVxpsRc89cs87Q8fOMDwTaHNPzbtLqupZPVD1uGxwXHY6Llsel72Pq08MtM4F57Y80PKHh6GBA235RfWyNr1sVC871stqNY_omtuo5oFeUxvVzEb5QUviB210I4qIaxz7J6NnMOL1-FOcbP2Mgr6f3KP-Hoz4SX0yP6nR8pP65A1HIfCTGS0_YLShScb4rXHluaVonHkdLqnn5JJaG5fUc3LJrI0LpyiMGeai8mKx39E5Ki5qc1cTkAPMKtXUM3JNrY5r6hm5Zla3eSAKg071aY3uQNc9O1YWYAftZsvgYecNuLYvQK4kioi37oYfqNxSf8stN92Wm25D053ecuH9LPpyPB57-BktQMP8ykrgJEWwtLAAQsCJbs96YBIvKMKvcabUFTPlnYOwKy2JkFvVUJ_SaAbapoNmt6U1T3ja495v6g5wLeaCxuIfQwpIvdg4OXHq1Znz_sXYG9XDRkNvgdO9G3A6hze4N1AQIIYsvi2C0wUsOF3AkncOyTuH5J1Dfukc_g1w9SmNht4h0DvcIeDVyvfBwDO_yR37Qse-0CtaRr8sv1-9o7setIJkvxZlvj7y_V4rNA9Y_VXyMNnzntXzntWxZ_nyTTYdulHHbrQe0rFu5B6X6Q4gBJz0Bk6Y8cApDx44LcIj70Uj70UDe9Eyn1W2M58BHWtAx7Ln3pe5rGs1T3Pg6fMNuAbvZ9evJIqIb7BeHUvzjqV5x9K8Yyl2LPWw0dCLFHqRe1v-S4t7SaQ7gBAwsWxAMYlrspyHRgxJ7V6e1O7lySPKLtvsQOJj9Ieh0acrlAXMFZ_jYKXgphfBDXiCG_AEN-DJtQFPrg14UtKuICXtClLyrrCLbiYCWCsSWCuSAjFGynyf-KyEvKB7yaI7gBBwja44gyMV532k4ryP1LQ7SE27g9S0O0hNu4PAkpbAkpbAkpbYktZ0lFJL3M0h-5F4qz8-Pr-RjgBdeRjYekG1vIO0vIO0XzrIKkjMOmDFTRrEBml6mlxX5Z69cqi-sFN5f2i7O6QjQAg4CRCGCvGPEohHsPGUjrUEVgQFVgSFICR8gDCCkH1qHIDzBbRpulIURAYC_AKz_jx3eXxMzd9tt_GRw7zg_wc_yFOtp9AAAA==</s><k>k3</k><s>TGV2ZWwgNyBvZiBHZW9tZXRyeSBEYXNoLiBSZWxlYXNlZCB3aXRoIFVwZGF0ZSAxLjAgb24gQXVnIDEzLCAyMDEzLg==</s><k>k5</k><s>RobsVault</s><k>k6</k><i>169179680</i><k>k60</k><i>19293579</i><k>k8</k><i>6</i><k>k9</k><i>10</i><k>k10</k><i>40</i><k>k11</k><i>234204</i><k>k22</k><i>3420</i><k>k21</k><i>3</i><k>k16</k><i>1</i><k>k17</k><i>21</i><k>k80</k><i>2</i><k>k83</k><i>3387</i><k>k64</k><i>3</i><k>k41</k><i>1</i><k>k50</k><i>45</i><k>k48</k><i>2813</i><k>k66</k><i>7</i></dict></plist>
\ No newline at end of file
diff --git a/games/numdash/levels/reference/Polargeist.gmd b/games/numdash/levels/reference/Polargeist.gmd
new file mode 100644
index 00000000..bfffd5ff
--- /dev/null
+++ b/games/numdash/levels/reference/Polargeist.gmd
@@ -0,0 +1 @@
+<?xml version="1.0"?><plist version="1.0" gjver="2.0"><dict><k>kCEK</k><i>4</i><k>k1</k><i>77236592</i><k>k18</k><i>11</i><k>k36</k><i>445</i><k>k85</k><i>160</i><k>k86</k><i>89</i><k>k87</k><i>2488273</i><k>k88</k><s>30,37,10,23</s><k>k89</k><t /><k>k23</k><i>3</i><k>k19</k><i>100</i><k>k71</k><i>100</i><k>k90</k><i>100</i><k>k2</k><s>Polargeist</s><k>k4</k><s>H4sIAAAAAAAAC41d2bXlum5MqO3FGeR6X47BAXQATsHBWyLm2rq2f_ZplAASBCcApNT_9Z99_6l_19_2t835t_8tz79rKeUv_a1_63zoup-f_bf-d32w9reu7mz1k628bKU9bG-ZtfIfrqEyOP7-W-UijhZRYxEvj6r0_l7W9vfl-qrxk338_1n7J2vtL-v72-_v_9GSGdX7aE15i2n_ZzHrH4r581__Ufuf8v6Z_Gfxn_Hn-eV_EyPyZ79__rOfS7X7ywXcB_8x7i8_rYX_1D_lX_XPI9L-DJp_-p-l5CyZ7JlcRq6XfFToz6_Sh47RL_tpJ0qfmcmdyFpqpvtJldUxaiq9jp2Uq2MC3ZSuLzlvS-t86eXAGCYway5gjlTAugqNtwBy-hZ4nG5GrkyWTHYlWRkWpqHPaSZ22plsidw1kyOTZFUF7nrMsgycqgInq3p6JnO7jrV6FKdnd2Ah0B2oDpwuRbaSWtfKzOROzRHu25xbvgBevgBefk3matXM1Yo_rl36vdUwcKYDdyS2W0LjkfD-rj_v6Hg66M_-88z4P-_Eu9PuaePD_nA9y-5r-eKCrbngw7vf0fEp-Na4r1wxlZjumZ7wfH4_f36fwoHJwBo4-zSgOzAiy3aDC89FbtGrn9_61voCmXMCk1Uvz10fYQj6CEvQR3gu0m8XEqUhsEsmeyZXJm3ELyefMbT-_NspVifDd9BVugD1zMejjQuvNjhPHvwnD_5jg5-cOZRJLvOD7g-0l_qJjk-UAD1eQjNyZNIMvZ2Zps5eAe7svXXU8lVzdRsHcH2BPYPHCzWdas_kyqR17-0g4b4d9PZ3by3XcLtbUFtjhLZC28ykr2FX6zYolVm3Cz12GjYfe_fF6JbUs_W7Wf9yD9-yttOkk6evkbY0ob305VvH8ud3l7rlrWr8dyvptKyCWwBly1O2PGXLk1me209EOjbu851turNN905NPzU37biq3BYGbltegVFWso3Qz9ABoKs1R-ksYWM1oO-Q-4I7rBNa6l2b7m4y6oTdpNheUh8X6tkU1uduIoJhN7l7ybMpPkJPm1FQ19xRd-r10ShacjQfFHf_E2CafKtZvidHaPSVyZ5JGyE1PPbtfPTrNvp2LoBNtTGSbzTGzKQNGi5u9NeNbF4cA8v8k8Fu37TyZ9or5LGTNesvbuax8pnf1V25_e4XXu7lo5CcHkCHzhCgViswm3tl_2xQy63LruTIfudwv1OkmdaNfWwfG0z78sQC4ppade6qXv6THZVZy8m0uwOVQ47z9lbVFWi2GxW4QCOjX3vOfrd-WwGFJqODp8QVSP_psjDXzrNeAXNbRmQzl2cGR-YyUM2O1KSBAEFNIpIcJBUDkL50EnSrJzs3OHNzdwQWAgeU2h-uo5YD4PoCz5emOziMdxGc4vdMW8vef74R7bOW0f_iUqvgNsE6lwpe3l-XujcXvPvpsv12socV2i8ANEBQ9zDnsVXjHVaL3SKb16vknVdoW0NX9pv08d2MOjO0cQVsO4nw-IYpu24r-0Ur-0Ur-0XL_aK71a_a6p_oygm_bdcru0Aru0DLXSAurrXQwot0N9mVyK7O6iOTZrDrtsnj67b1lx6-sLZLH6DdmxT33NFg5emyt_MC7Z03sl2Hx_ozFHqX7KvbnOJIsKN3a54t6zfdqXf1GKwGTpd07Zh27ebO6kgh1fI4i90-t_zKll_Z8u4ksjQd78nLkJ3AlZ3AlZ3ABU6gcPuoyk7gyk7gciewVX9MauhTs1EPRj8BDZ3OdhKY7cQIb-3NipcRm_rojNxxV09fHQJPTTxUkp2orEyeTJqN776rj7vOByp3ulbze4Rj6c5MNRmW6sxkdgSUuzswEciuAqmXmf1ihfcn3OL6ti5-vbVq8TK1NDapjUxSVrtV0FL4dYsk9WUnABuAVi3hoMgKpZJXUx1wY_c0JSj7xJQ9Zup55RV6Vevb7iHqFRi5K7NHTCMn0IS2GUYzWzT7uzTBosy9ve3MMK3fp7o1Ia2k4HIjSrneiJwwJXebuRqhvV7xewPgU-AEBiN9oVlOD_UspYKcDlPQs02KbKsmO9SUHWqivEDJY9LHOZNLOZNLO6-0wh0GgrjfbgNOrbpyObVLObVLObVLkNolTO3ukmOJnRO3u-xMzlTcljyr9fiuKdDadWSygjhZ0-5OoeXpON4trZC7rUz2TOb1Ux5PWz-lNDetlHc57v7w-LBXId3Bd9-2D3d_PqY9983bfQuRst16d7PpLWT4jmVbjIC-fbCCwxehE2gjzbx3IMvj5e3hUm97uECOlXyG7dkROAisrMPMfTJzn8zcJ7NkDWfesfbK42vNTJrhauD2xMLm8MpHb84Jb8rDj2D4PRM_N_WZTLaTTJcI9tsnV7izMXKaeeec9PacNI_HPXpc8_fJxsh5431yFmSfAdofysAplJQ9JVnn5DTv8STwXdaEm9QWQm9NUpyamn5qnn3njdSSNnUawAIry-fN4XCs4cq3ZJyTQ5HjgUoL0mba0_OWd3oB7XrP2uXQ5OTA5Yzc9pGbMnomzTJ8xMqPlxly5pbN3LLZsjQ_vid9d80Uhjspbtx9xJn3uLtI8Mwx97_Pz6hbxfb_S-w60N3FQszNOnhKjbmGOAsvXWQrFrT1d5BRABYCB4A-Mz1ziQceL33-NthWcAaqJhsMaeGw8AIjJBAYEc-lOSK7_kaEHDgrl1v12NMRO0x0BPStI7hdjMiC7FXX1aAmS0MZslGolZqFmkzQ60ffkVUbT8I7N0J6utKbmenjHSfjc3CZZE2Scz-CnA8fOLpYB5nHrniTiekmagPs2kZsWxfVZRbOwFbA_G2hmZoEukFqt9whTeJAV6gXUEiAYOxecvpBgYrAr0zQpdeWh1iv8xOIyknU17wmOawIQPsEBor8AKxblPlA9o9UaCPHjIRAUnejdhuV2T8VbTRdg9nZ2_gEoukkSAy6hHOVGVh-gIEiP0DUttV_QOaPVGwRYQPoR13CugnVpZ-KCPuIA19CYCBQEYi27DgdFeGKWixnHFtHBLrbeViB2rhJ5fWZG-YFQLUsJtlfyfNe03hXma90tGjhc7Uz4Ac6LQAQBqig3y7qOUegcoH2c-tLjwY1D80gepZRwZxBVNlQec4oqFigzQ25N4r69PFEARgIhCpy2uGhB9BwjUkEru9SZyzTzsJqh1tXfYER4ZJWXzn7qAwWVNYOV686XNTqlPPaD1CqehGtBBbzL2uH-1sdLnB1iPsf4Cbz2I-LLEFPuMTVPdTn0XBwHB4chyfAPqwObj4HB-rJiRUt4p6037pH0SsUYSQKmHOgijanJ9A7d5gAPCpWKIKrZ6SGswYuJl8Je-gBdA4B6nj8hD8xefEg2eAjJxgeegENQ00EPECto9_TUM-tPciyw3AupYN9Otin52SfMtxadqjk9dc8z2XosUSXQm10Z1oiGpguxGm8HZks_yctGfdyaPOWjHQy_NCbT2qTWgxyz40EhfuEUrYfxhpSoLTmd8eYb_pgZoCaHePqrVO_lyrAAuA0BPBm6vGrqyuI3FnFd1PL7Gm9FMCn2fSAvEYRCvdZi11oZaPPZ7yq0RXxRIBegr08PVyDZZ4ey6EfKXKpFRByhfNp40N3oBfQvqHVIECuRiuoBiNR1dZ_eLrxCJDnzMzZgofO-QEVsCthz9grdhZKARgIhO7LSYGHHkBj90oJxZZRYfElfOrlMD8zuTAcdSqAS_0c0EEDOmhABw1Y6LXcq2ILRfqi3gPq6z9377iX4Ai0hMO5x-v3uIVL-zg9VRD8mglHoQp4kyYMhXBWumK5t4mxzNALeFLLgkuvaNiQWOABzQVDYsGQWOABicBdy2Ml73jlZS6h0xdNgXrpoA2hemFJonAVhCJSECEExo-Mt5pg1BGMOoJR5wfEMhspX9A0jpmtQCEmFisw9HjWVviG8bBhPGxwN4QhdIGcEi9vcbh5eALghR7r51jEuwpF_RntNegv0OpujOMnQCcADbXpP_oVRAgBHwtLbjNarsyQZc1cJXfsyufZD40vSKR71cr_rpPBDIoON4NCp6MyHdUbP_r-AAUR8lZL9sD7VpH-gxRECIHxI-Omy2fxDz2BhmG4npgnDcPVBirWBioWshYRGD8yrlg-bVeGQKdrS_a8Jb9rxfzDiBAvSNyCXlxfQRboG5IJERgIhF4O4XcEQhM7DFuIuxfE3auDmyIAmQ26pgrDPTirN7vdinpaccXsx4hM7IiPxEVuvgEe5RobTIFB_oIgf3mQv6NAzw0ZcB-yRtTT3iodggVl2qEhooPHD2tBQnSFO6bMAZdQHwDueqvMPdxnv3CFw2xuLQTMC157WvDe0_Iw91ZKxdOnXIUgfEJcI9Sb2OowmO1OEOOSx7hScPU7FycALgHhK3n42kpgcCtTC5u71CJQjfozdlqK5UgiV991CIJhgmCYIBgmDIa1cg-GSQLX4ZVA7EsQ-1JHu8nxB3kRAwznh-Itidx51SJilpthK5R6BKJoOX0FC0wn5y_FVZpgugmm8zNzUUhi1n-pWygcvBkwCx-N1wBsBXqkq3mxgmzwvgWekK0U2LPFEdAqm6m5Y51HJzZRSJHviMxQjJxGBWDkpghDTfGAoDvdm1B05ijBav0CuiCLg7GgBiPWTbRJR7ScIgnLIuPZ0NUbunrDLNmw1QgDBcD2Ho7CSa4JNPMM6EzwDBQpiBAC40fGNg86MBkPTEa_nyCqMkC2RmuRy96B3fnVsoeGF1s9BdIDv9whDhLv5hQGw9a30PLY3j_vwkW4_sAflz0VHZ9ozSHhrhAs7QrBkgBu5Q05lA05lA05lF1hXY2XpGrUgiNaFsoXtx96Ar2z2ZsPjh4Ycn5XuH7M2HY2DVcB2ZEN2ZEdbnvXwEBm2wGu4R7gGu5RwLaQ_tiQ_tiQ_tiY_tASPUOzxwLLWE4jWubnknkLvGgZyFhsyFhsz1jwDiaA780b0gwb0gx7gbMgDHyVnlu6muX2GCBwqwUI1oUwf0OYvyHM3xjm7xDm11ipvzO_IXrfEL3vDQN3uwfcg4BtHVzNgaMrAULbIKDfByx60KIahHtbmMXbcjx67kz3rOvRiwKi653ep4FvfEIAtBjoWfkD8czpYHgBgrJSxvWmGRiwPZwB28OB2OLAAeKBA8SDB4gHDxAPHiAeOEA8cIB4JqwZIuA7kBZZvGErZLh461eoWUpFkKArfini4KciDpxLHjiXPHAuecK5ZBTw874D55IHziUPQcpAAHe_joRRx7WEc8kD55InfFni0vI2n18vOie8T3YCj5eBX5f4-bwE7GAiYG9F71jqTKGplpWzD8q7UcuYjxCI8xEjynG28K7RpYRzREE813MCS3MaPmZR8nKtgEVmVklKHxhbSh9YbQ0VCud4VqWnD0yOvGnVU0GsKHw0o-QQ86FT5kef52v_hq6gjhTk39so-HULBfKXKRQNX35QyD88UUb9Eh31R1SgrS-MKWKJ_QcgBAYC6CrOIGg3ZVQwtHB6qpFLmgWK1vgxnqQoOlIAo8LVOy_fs35oX-MZWPi6ZX01u58hee_HPDHs_P6CiUqGT5iMe63vrUou1cyfy5-LRYedmokWMFkWTJaV1zBl4E_ZXIC8RwTQb1a4w6Vc4HApb3a4HhQGPsHApxSEtLIPdOXPB0IiDIdwD5w_RVLgWyQFPkZSdt4ZVCDY5MiBWTJB-HJI0Ol83MFQ1KuEb5KUg2vYkSN_Hd616KFIesnL8PBRhMp4yF6fwNmcHkD7BY1YRFhWtNBlg6MWmGS1LAQ6Avn6i3LUALjn20ItuCjUkn2CVnNs99Ad6HQT56Eb6FZzHPYAOQ7bASRXGG5sajmhBfUjRnvQHP-8cnc-D-NoyalTmgvmTy3JW7_dhm_l03n_6AkFyXvXe1GQJK8rp7is6JBpbbXDKOowisKhe2RgJ6kElr47dCdzjjIR6QEhRygolBCWWumzNia68vqv8uxxqYaMnWV2F6TEk7RWISJWIIzIASNywIjMEXGrA9YiYWDzxTqWZahUqLcOevyYgGv_hdc3fACesZDQKcIYkfWDFEdY63gLYQbkNNMgXAyIQLBveD1DgHxRqNVpF4Uki6hQ3x0rQgvIPYQfeH8aRrhDo4UxIs0RUXBV0FhemgiAfWFwBjoWK0iYOitMHQr1_DRmfc-WhbNlxkKi_nT0q4MsSaGne0S8LJ1n8iDMM7JbwjzPZITvsC6fgAQj7Y1AowwcNPQBQ7eyEDgA1IaA67ECR1C1VdCsNVNEPj0H35Zrwz_B0jojdkQor_kwvHJK4wFySoPrC6EvBbFOVuHKOY7WKB-wK-Azr-Vo-aEn0PnejwJ3b-OtS4qwayetbYJKcvj80APo9ImQ1s4BteFq7QPkBbnl4PmhF6h9_LOSN-mhIqReUdd400MhhTyKUiRvIL3mlIwCPhQUyNGXorHKSlhlhcBN0PFZYAjnauRzB7LnE8mH7kCv1BlC-xmyImO4yMlF-HkkC_R8iqLAQCAYrOvhTGqfoCFqFshflzfE6ex89QHDs-ezz4ceQOcbiAoMnwNd42irZMIQ7hOGcJ_QDxP6AULVPsHLFCAMaSnCXMEOYWSHMLIviFeEITSD_AIU77qCwMtrrb_voI3NvuFnfKyC_u4aveExvbr8ylWzG1UwJFUwJMSlHeLSTth9-h5fsBzZa7rMYt9xsmq3JyYiMBAIikEE2yGC7RDB9nCq2aLAtO2iJu16GIDbc9N3C-nxdJNLO_sH0fPOHJF3PfX8hDF-11J-4G2F_KDjE_W4akT0qle3xVsdwvAOYXj3MHzH5y2voGdntEbe6SvoCW-9jcjkl0bbKDlLr8BAwGPJUSp0x4jBfotCvzzcZWyUVFx8MGMZ9o6HsjanB9A5g6n82X4qhSh9WFVLcKuqdETC5VxuUi3Yev0EaUDWDwK3cw1BYCBAP8X-mrn2f3pQ_sH-eqzs9of8xoD8xshn11qC90ctX5av_RNdn-j56qVasE9q_0HWDxJeqG3RnOFtdl6krPvMaJr1cMM3XLZGw2VLkd8-aPOfHrSfByc8cFPnE36tyk3f2pc52_wyZ2toqhYWlxEhXkpq1IE_RXCBHlaKzoidKcRlVOFi8I7wmo4QyCf4R57ySh7R8V0EKvZ1z8Qa9g3jPjP0M3hfbR7flsgbitYX9rsTcO91yIYNz4ax-Yfv9FzdWAiAtzcggzQggzQggzQ8g8QFhpQJ64DvdeyADu_pCQHfmDDi_doED0gqUAL5BRIOfAdBOD12Q2AikN_zUo4QXw-M60eI65kOX5RYARn6lk2bpeR-mKUjsBDIL7oph2eTZwXTzwqmZ20Etu9mtdl8hoRc_2w-nUKqf8IL4Qr4_X5Fqn1Krs0BcdMMl5tZ2YUNXtjg1REoUAbpaUhIR0zIFMyQKRDgdF3H2EA736pXwAfnhETBhETB3ODKC0OIgYTFPPl5Qm5lBqTboj7DJ0UEgNk7Pd3A3-IvLUusAv2wwn9EsBjIF4MUiCLwmdga0fhZ_xa-lH0YSW-MvIkhmCqCeMy-8p1hZQh0vqb4_mcC9lZaYaDahxS5jpFfo1BgIGBX2A3wrUkRf0s2MoYwf3nU3gWw_GoNdCqbvssmL5uXpzU9uJPS4T-EUZYILAR8neRSFy56a8HKKSwRsJWTc4jLPpdsOURmJFg_hfHaYwag-X8xcXyxuAoSfIxXgTCQBLEv3z8AxOPk4QNLVIylBSEEBgKhUPCZCXxmAp-Z4J1ZBSxXqjXkeyOKhlsiWtOwYI8aHF8QeJEEXiQ1yLOQfJzbpg41TzfXiFw7c63qQwEQ1AA3hsCNIbgrqgy2VpL5R1CHewPKAmYTNJpNlAlmC6dqAhxo0YC4jNCNInCjCNwoAjeKRl4YKRz11YjQcJYQr-2IQJsFjW2W2kKb0f0icL9owlCZsOwKg_fR3NiC6Rl5LmPBOFj2YgAFuiNg-Wyhly0UApz6r_8B_8U9WEFtAAA=</s><k>k3</k><s>TGV2ZWwgMyBvZiBHZW9tZXRyeSBEYXNoLiBSZWxlYXNlZCB3aXRoIFVwZGF0ZSAxLjAgb24gQXVnIDEzLCAyMDEzLg==</s><k>k5</k><s>RobsVault</s><k>k6</k><i>169179680</i><k>k60</k><i>19293579</i><k>k8</k><i>2</i><k>k9</k><i>10</i><k>k10</k><i>30</i><k>k11</k><i>252961</i><k>k22</k><i>4090</i><k>k21</k><i>3</i><k>k16</k><i>1</i><k>k17</k><i>21</i><k>k80</k><i>2</i><k>k83</k><i>3391</i><k>k64</k><i>3</i><k>k41</k><i>1</i><k>k50</k><i>45</i><k>k48</k><i>1531</i><k>k66</k><i>3</i></dict></plist>
\ No newline at end of file
diff --git a/games/numdash/levels/reference/StereoMadness.gmd b/games/numdash/levels/reference/StereoMadness.gmd
new file mode 100644
index 00000000..47487182
--- /dev/null
+++ b/games/numdash/levels/reference/StereoMadness.gmd
@@ -0,0 +1 @@
+<?xml version="1.0"?><plist version="1.0" gjver="2.0"><dict><k>kCEK</k><i>4</i><k>k1</k><i>77236587</i><k>k18</k><i>8</i><k>k36</k><i>109</i><k>k85</k><i>105</i><k>k86</k><i>85</i><k>k87</k><i>1989927</i><k>k88</k><s>3,2,95</s><k>k89</k><t /><k>k23</k><i>3</i><k>k19</k><i>100</i><k>k71</k><i>100</i><k>k90</k><i>100</i><k>k2</k><s>Stereo Madness</s><k>k4</k><s>H4sIAAAAAAAAC41da5IuK27cUI-Dh0AQ_uU1eAG9AG_Bi3dV8VAqoe84ZuL0VX6SAKESICjqf_47t5_4K-E3_db0m39TKb_1N4YQfvU3_sbyG35je_5pv_F_4-_LF_vL9zB8fPFvvrAUxjj-pPFngPL7rzhU9KUiooqXZwhArdLvy3Ur8cou_3_WfGWN-WV9_83fv_-mJQWrd2lNeNWkf6um_qHm53_-K-af8P4p408df-Tn-Xf8tw5k_mnvn__O_aPS9-9Q8P3wX_L9O36NYfyJP-E_40_qP-nnafFPHv_Wn_ijP7G0n_ZAz4-l_DwSz_-fXx_2h-3xmUcwBxOsW7DXn7fE_hPbRS4-cu0RK-kTK6-at_yuL13nr699188fLY3osun40iVu-mtNkZdOm9RFpmB0zK94NXmRpa9-rZKtrwanb_xsZF2k2q9WmdrXzxHo2HfpQ0BlCWjaAh_5NVbL0j9oIXoYowIQZJorZW--JGau_NKlbzq9_6uJ6EJ087RGooVo9eW12b0_8hNno1NzNk2terK7Hpw_fz34aexU40417r7GOUSihWh1Fpu07N9j8PwxE12J7s4COaXDAjkVbHJObTc5Gq3r5xzXz5_CLL6CeTbop_78q4eNWjOK0VZNCV6LZKIr0d3rEzNLMXmgK9He8fIIC6avJPq9-fJLIf7m9Zfiu7HYo_TJV7JapW6u0euv0euvQjTYU0FghsfVd-qcO2t3XanT6NM3kmFfd369-ZWm5IRqvffpbckV05ont7tJMLp9QVEN0Lewtx6xGfgFr09Lj05pF0-qL2PQMVohEwmrlFdMggu3ErInqyctNETj1lXm_D3KLnMh2ZUZnbGeCOlJZztJ0ZPiyd3qOOjQl81GlYZ4VKvSRKqrUvZmyN4M2Zshd2fqxR2sjIHE7jp0FrI7VMTbQbwdxIJSsJ-__qxAV4s7amIIvw4rc9jOdzhcYb2iclfBqM5qzCdIxjzhqcAG9A6wBNFCtLJ8YAWBOFhix6AlUAu1zYAxO0EgM1AZ6GSJqcMaXjMDlYF-B1iCVXKZRCv_HggQUihUoFCFmEaFlYF8BZQklFTqGmGWgl72gzinfzlvlmosDaqFMtVkvv4aU0LoQC0MNOrRKWLdM0UAaHeAJVgl0UL8QvqYVi4vcIGBS2RAScLsPwX6tkuLZJcWqdUtUhkt-jKanwUsgV1mUy6TH9nGgadRGGl6pTMLHEAgQEkF08JFsAIxL-zBvHAimXy5B_LlnhmoZJzO0apztOocrTpHq06Ro1Nk6RR5er_SgQUOIHMRmevAgJCEkEqhSjCNCrvvwU6xp1Ns6uFGY6Mgur2GLYHCSgnFW3pxGF2IbjdaiFbmD6wwc4kHEAgQUsG0chGs4GPIUKm6ptwCYF7gJxn9c1qiEB1vtBCtzG9Vi0oCcqOVK8AKDmCveVaR2QBhgIJPSf7xKakSnYkORHtPn_JC8kLyTEObUmagMtCvgJKEkkqlMs1sKZCVUmagMgAP9Bc_p5IxKZ9IPpB6IN2QBmpS2UBmoDLQDfjal_mhyPTUZHqqMj35OV3pQIASvSe2S8DslQsDNEFZQCBAmYFo2U-6wGxAALAyhcbuIjR2Lw6rlfDzIvxUCz-lwk-pUGAQes5Fb3TkErgKxC_EL8RvdOFHrvjBpRR6Xgo9T6Xf6Ej8kfRFrgDRQvxC-oTKs54vO1FtaZUF5p1XEUCDZ6Vpy2qQDaaFY1CBkNFAcTeAQ0YtpLTyU1XpqarlRgvRkeSZtqey8iNW6RGrNMJDMvhNERR1yZCilnv_SFvE73X5BOUGxiv41U6ttJEr2PmGWSigX1Way6cUn3EuPuNcLOMcgf7yJGrKoIhqOrng7nIqpRdP-kTv_HknsKb0SJpNpBxIM-RVWoPLUNUgnvR5uUm3bEA0fQ2AvLq5RmfMGrMnqyfNmM3osQUC2ixFNgGo0SgAgcpA38CnMzmrV59er5ZeH9KDG9Qly4c2o4frfRqyN3H2Js5k4sFdTP_gR0A38DnCFFkZ_yre4uItLt7i4tOBUxhKG-KjNOAwDyrefMWbrzTfozPzbh1YKJ08gZ1O_rTU6GtZIT88GLxRq2VWFfhd9riqt5N6O_nce1Wyk3K2eCE7WzyspdVby-faa_PW8qn36pPm1SfNqyXNh2lnitxM2zl9vBCXPlafRVefRVefRdfg7bC4w8rsTgZMysYCuMRVmSlqeeZPv0-vq0-vq6XX1X6loD6ZAB01nap2TmIBpWzBxFX_nq-Jr-dLfVJffVJfLamvxsxVTLfRaIoC-rnQUrFyfJrDHhotZz1RuaKRUVrfa64M0LJoAUZXovONFuIX0se0Er-Svr0Unw17g3HZc6_JxGC9gf0GhukQNxu-48CCoUbDfaDKCHQG8tREIo1FWqEODATko0sHLFzJPrl9iZk76gS46zL31QC-UyGrd986jNMd4XnE5Hkg5D3Xka4nQpZedUJJvqMkh9juJElkECkM0MxUxS_2VArR6UYL8QvpY1qJX0mf-e4svzvnm5UkMHk3FRN_QdfVk7dQNRBodyBRTcEfp47GIgxktm5mc54AGzizRfNebWiJ1Mm4PTYAWikr7cgp7chpiTdaiF9IH9NK_Er6lJvgO3hWikD1IKiDzptnlwpVCIFI3TtFEoskFmks0liEgcyGyWz5zKY-ATY-OEDlOFh5DKs8hvEunlYaY2jbT2lbUGmfUmmfUmmfUmmfUmkbUmkbUmnPUGnPUGmfc9LQwTVQ99VAnVMrc3QG8h0oDBxKCystzNGYo3F_esffm6IOrDewexAKAbeqMFBBvTJ3AQLhLsK9nrmb8z5fo8pDlPIQxRuaSjuqSjuqSjuqSjuqSjuqSjuqSjuqqjREwXYpNsEbXW_jlrZLT-gat3x5CPDQozx8KQ9fysOX8milPFopj1bKo5XyaKU8Wmkjj1AerRTGs88mjUerxqMVb6oqbewqbfxqizdaiV9JH9NC_EL6jibsbs1Qqf4lPNEJ2hpHcJ7SBEA_V2k8MjUe3RqPbo1Ht8ZDVeOhqsFQlTK0cs5TPV9m42e2NgI86DVhIJJTdB7BeJdVcXP5q-7efoYEs67dXsx36tojvoD-MKDS5rDSbrPSlrjSlrnSlrrSZrLSZrPS7rbC7je08fUS8ql-W7f12wqv01pwLC_6XF7oWl60PE-c5_4uL8J_lOsCo6_B7GLLsQgEY_KI3Hnw7DxWdh6iOw-vHQbPiH7w4O9hf1-lHG8VzUIV5UGrBwZ4nOs8VnYeKzuMlWMd2Hkd-JqxvdZ-TB7lYvYvQfRmP1p4_rjsB8J6Rcca6ISt777cUxubVulLPb1JqjY3WGQL1p3ieckeIPpEREKePobg11MVgO2Jb56pw2HmQfcb_brWIWTgp16yB0fVJlrzyRoLcWVdBcCR6UEXotuNplqWcgPTBYQT0YMWovVGsxL5UzOBcOR50Jlo6hPtN5qV1huY_yyewEYWb-VGX4XID1q7-cFEvR-0Rn4wgLxcPYaknmMhVaeOBciqaQzZm_cBMgOVAbPwKAXXCIOl9rOtm6-4xm44Z7BWDHrxvQe9WPZB2624ntkcM-7pnMbEFraKzq3s3o9iDImBwkDzhokxEkcUBqzLKoiIVXoi1Vd6_ASnbBAA_SkwkBmoVAM4NhNRa7-YLZbL0_Wgl8frQS_PV4z1Eo0e9NbPsZJPjOopTEEdUg7EXDTqJQI9qF48aUrbFDqi0qjOcWO7RIwHvTa-XQ3Vrkbttwci9quh-s2oKVzi64PeDJECGSJ_aLQpYQKAUtgPXJmvXwU5Q79xStEvjTb7WiovSCss1ZgnMkss1EY_Md2aGKXNh-EYKT6TO1wv2bxm_1b-_k3dT6M7IjkVNiYfrbEMxmoO7zIsXO52FjYYBKRZS3G1HDpTol5OhQGfvVgA9mJq3GcpHTzlD-SUaqw5slBkGbBeSrduT-WKNo9iofkoNR_FnoiwkHBjxKqaI9k6CwNKxs-RzZgjGy3LgegfSDmkCvNEZolcduQWsZmzXFG9GT9HNmyWA9EDiWTrLAwoGV8C2Vo4UgqHROnUGxLYrpIP5AhocgQ9OQKjHMFT8oGEA-FQSe9yLi2RlUS2C3eWXEOsXEOs9FvHSuBOk3wg9UCOeAmvv6IaYS3CSqDvi98UfIAZ9SDXs0BKRmzYZyOWTuzVcgRBfKMedR0JmC1s4xQWHqVTdXK8VgeHFXgvV0BS8Oz8LgDqDG9ldyzR9o5jazO7M-8huOQZxkUEq0xLUsT8yuorG26yMEYXtbzDv5JyW6F_4ZXgCQgDSj5Cbw0vEQT8e9gxwau8E8gMVAY6FauBSlF-QJUfYVguD6WNm9945IHVbwEO1NFYBLo9o0wvK387JDtH2m6GG4JdnZ8lAGOh-VS35e_k48jeraO-qX4OFpUVAGFgn359AHeuajEAnYnep7TG3RSTYZ8si9kfnXroQnQjDVHUa_Anmx5aiN5nmyrw2ynbhSgDwsBYXy-t-7XnAfj3mR-aTJHJdPZKcwX-eVo6AMvX1AI8No5mOrD0zxyunAMIK2CO6gn1i1C_2LvSFX63FwkWhz0qi4Vm5xkOpkQsqr-2bYjUjuu2VYWNRkQ_aUGFWd6H4-m52YD-dmCPVl96Z2QhNtplOlPzb2ScYbI3byGnpTtdsl3qUoC2QJTpYMjSCOYuFMtzEQYoQ7ZqRRadKFp0HX3QXWG6RCbTLTK5kvvbvTEZfvexLq-zC24ekSuNFpmOLCwOMA4cchi3yEzVdi1NVnJ43Q4fEYgdbjV5QHoMYMtaARAGsCprX93q0sg7GnlHs9cOIjBYb_Tgq4XbeAqIMiAMQPDv1KWdurTbOXhXahYLaevN01UzwRciFZHAiDIgh8yu6wSS0YXo5nt3AnBv0dJZZdc1wttTikg-kMCIMiCHjNU--v6fDECrt_TS0K2uCd5MVkTqgeQDCYwoA3LIWO2TDwWSMtGV6E59kQL3xXrjz9qX4SiGAoItzo1bjO_cOSQwogzIIWMtzuRtmbwt0yRG1tuB1sLJUnYQECEnEHICoXu_ZL269yIJkG-NXy3HKwXWv4pIYgStie-IOSQfSGBEGZBDxqxZtv9EV99mtil-3imFXKpsl5OAAuPOCQXoy3cM4yzWtTO5tdXmtVfq3pqotAnY3QJbRzCt9u7YpKl_dfd_bADYqxKbJUA58-UwtXIa2abR42gvjk0V8-UvBa3zzS_UahcTBSjG5uXSyWqdrNbZavPFL4Fy55tfsl8bWmJ7qCvBm7H4l8Eeepsxwe98_87C9Q7LHYa57KjwwpMCpAYVRGzWOBFlQBiAHb4SUqaGuB-gJcMQ_p22h85EV6K7N1zkdwIR1isqV9Tmc9NCE_4sNHz9qcxeXs1WPT_74h1u5Y_KJ-98xb8f99Db-QrwQwckWtcXyKjPag-k7yV3WXsC5Csrwc2-MvBD_nSqUfluDgR7DQgIA-gu7ykQVzmHo4MPC-1k-D4VI3EdRWr_mKsq2Q07b65KwhINf6SqZqF-zFuVMFq9T66NAO9mK7t-Q4Wdb8AdHths74uOUoWeHKEnR-jJodcTN5ABsRcUIxYyPP4D6LTHA2QGaOQsygWPZFSxpvg3-R6angt7l2-6R8v508A-OQSxAXB53mhAV6pep961VwNnYT3oKgyeZXhlEMTiThjUQHaolIaqlLaqlLaqlqYaFalBd6tHvnS0egraW6xLtXlPHQktM3mlDFelDFeNZPI6MlxmhQX3_LnlrtMIlVMepgV1ZMDMgSulyCqlyCrc6TfKSlVXWdDpU8947fUD-MBMhQMzkyMzQMc0KrzINIDKInjjm2PZSRVBxrRf7H6QmknXAFDXQA5dH4y62pdGB10TAF0TYV0DRl09UL0mALomkt1hhdpTJ8EBoOBAuBIDhkoonNmJCJgu3ffpOF0TRl18lkozdVFEdFxRghDqKpR2VpuADxG49mFeCjwvhpCto1JGQNU_A0rTbVXKqUyGb3QOoCFu758itpRRuAp41msgcPuxv6bhoTPRlejum94oaT8BYQArMZEvwTQbN4rds2j1lzg8dCGaVrDapS9jfBzN38nw0EK0j-KTH5aKE1EGhAGYg81SIqykF9OXdZpcfN_Cg1QfpRvNjhvNjhvNjhtc-qCg4JtHLOQTqTarbXwRRGxzHmr1sInp1DIPTKwjsLEJBdAmFC9btYzTBGx50YDjmwvBEbe2Nvc2LKgwpu36TQMVoZmK0HAtYt__S0XMyU3aUaDhIdAPgA2s74T0Qoot3vscTLc9u42uk2OOhRkQORAlLTSAdhpAuw2gU0O2icLgoO2hTttDnbaHeib_eoB3OMgrNZ9mOTa-DTnat-m0b9PhjtsIDDsSdNqZ6LQz0Qs3tcCkQAHZuwiTb47ZFjI67Rl02zOYrVv3thoHWYlvn-94_bxOpa-FOlVGj1xDV8g1DGW0JdCVbKk0c3sYvt5IVNh8LUn249PxTSqHdBsYJ5SgQrQv0GlfoDcfYzu81jIBOOEGHDgeT2iMx4Ji0WaUnfYCOu0F9N6Jthl2A8BWCx0viHxlUvA5_IcuRLtZwUOPnMGOUhv5NvA6IuNjCGMrcIGWm0vBJ-AfWoj2l2AvBovsD9I6RoAUfFr8oTPRneht0jbpvDpzFjEQKCKTxTJZzPLQsQEDVjtnqraQKYRMIT4eLAYbbBdL27fxLCRaKYWMU8g4PsH70D79uIAIpZbA9Sh-0E-hkr0q2as2alu14Xoh5UBsCBpGhg9ITMAWsDIctbe8HzCHZJOaSMD1wEZRV1HWVZR1Fb3pKm5tkd5v2mxBcdC-OWojXteDqtcFRx77ALwjRbpTagPZCh9IzcBjY_fQ4nM1KfpcTYo-V5Oi-KculkS1KF_zsBYDqVamvz0qxeLH2AXoZqCboR6Am1HJOHY31KzEYEBTVCUddlVUBBq6BI5dIQB9ZNdLzULUHqGF-JnOYrGqQ1IqAtBNwielHprs2fziYwlY-IiWWZoWn9vbxkD27Oxs3WYxC1HfsGRZosGRQvcWTz7vlJLPO22B3ZDJAFFrqUCkUik-oZSSTyilRFPelFKklth09lszLWAvUx_A2yvRBHcBZYeBCYxDv8hivZT8HPihyVyZzJX97G4xwHCVYJ69EPbQWUzJ1tx5SkqMRxKZyObRU2beh4MyvXsTDECLKaGeERp_k1jubnAUigypsBcW6hmbjw-6spdWf3PgA5DZK5kdJtUVADug8vRsooasqxeMg5qu7JRKVxIuERtZEt5AMbT4CfBDkzEaGaOxOZs9CtOn4OrLxSPsQY07waazaQL77Sb3DvF3tDfEf9ouWbKwXSJL9LrRspJpjyDcguKQciCNEWFgjAsZEek_89VtZNRintGrjBrsXLXDyx3XO2xbM19xGe5gnkDxNZ8ANDfD4Q0EwEZTrZ03XzwRgMKA3w3cagvLnGqn6RXKzsqIvf86ROkC5AcQBuIVEBZBQK8ANkLkQOIfSDuk2qHZvC7DFdARhBBQBiJ3nciBKCMlkxq4O3kCfo9iiTgl8BYJCmEb6Y7npQaBcAWERQ4AzY2HdRzSDqmjctgBJbBd4MzPdMbZyO2MDs57NpX9gZh3yCU6ET3P5Cqcgd1SjCaPFtCQwZa1HEj6A5FDCpF2RySzlEPSH0g4pMKh-UCyHjXUoxU2r8j-6NBDC9GRaL1ZekoxGj06BvjJ_A2TBXSitVUOJP6ByCGFiN4RtPaQckj8AwmHVDg0Hwjaf9ZQj1bAw9R8Yu0BODrAtgwCbnholR40-m5ktt0j1JEPrWi8iSgjsu_w2UjG99F2dfxBig3LHdYrLHZuRxDOthFQoIWuReFoUf4DUUawYyeSWfMFCUfpR1ePgDxWOqtbmo9ZDV7Tqw76Zn81YQEBTEAvPnpkVKLDXWWIgAU6z2o6z2rgu6IICIsIKxUWweGplwM5Jku9cRP7MX3q6Wi0HXuKoEaZw5kF5n-oF32lH6G7H6G7H6G7H0NSP4aSfoT3foT3fgxJ_Rja-jG0dbq-bdeQnuFermjy6IdLoBnYBMB4EmhiKkEYiFdAWERYqbAIOIwEnpiuup1IO_Q0aFHkJgoDPOuUIIcVeGRZTTgQ6OiFHMZzPPEP5LCOvaG6S_edvOzMaPSoq9vRSyfi2ggT_7F0XGJzzFjrx-J_26aNNiGegN_LXhwwE5fIk12JNM9eQjC0Lima2k7YRlzx-_wP3a-0nzQtKT9pXa0LXLF8VBXNHGHEyVhJ6HC--2LV6-Th7o-3kX6WcKCB0O5s9oBvn5wJj398lfkv-XVC9J8OiCbxn714k3JEtytN3ZVuK4-lm2a-k3nsVDZU2qKzFt5skUDSIe1A0s3y6Ra1p7ShDcvdr_HtcuGxyhzZ4VYHBCz1L_4o7kML0bc1xeJilNcUWKRNQyUfkQ3vsEgg5ZB4M1am6Jex3XBoXhDPcDz6w-FuCwSEAXii4X4MBIQBsDVtSgltSi2arCr1iuYrGm49IPC6jmsN9AleP5GAxyFHOJIjHMk1xMg1SEm_9Z0E6Lt5eAh_yPBDDBlLjetR3Xj1-LBSoehCG3tS2vV3snW5xpxyjy7rUowdSyLo0G0RvpViCToEgktDKSmkh-1druGmULhZtpsl527lwMQ3Fiz6O5u1oGbQsEmlGEO7nlL1SpNl6zXmVIo5CVC0Wj0iTD0iTL1GmHqdX1W9W22WDFarclhtQmAi_72fh85EU-jQfqXJOHoNHXoNHUqhY3roYl4TqrEUntz7uy8LQGvqET_0iB96xA_lyQjoOtBrVFGOKthqiWLRI6OVrr_045dhlcaL1oWUA4EVRuNNioWUA4Fpb6PryTdSDqTZWEOb7UKb7QJvgAD_OJgWQcIh8OptAinsv3bEq3ZMhto1OrVrdGp_RKdZ8vecbaxcsGZYERQdQ7cgl-VepVPMopMF0vVK00PVrzGr8zwJVcS-296PKNaPKNaPKNavUaxfo1j_I4r1eFpylu0xPazbhUxZ_De8HjoTXYnuV9obcUkxeottqwYW2wIyNzd2TBQsOotyCMetWQTZd-o60FvcmjoNraA372upNjIWz6MfVp3zPhC72epe8xY6UFLoQEmJ7UqTLeNtMrR0-2F4omimyOFhlnLysHliu5knrpzeRAVRnOZPQ03dPFFc2g1XbEDLrrH-mPhDC9F6pclk6RYblm6aP07YYsME0GyJY8PkYUOmWySYdaS5-ETR-5Ke3pfk8L7JBt5Hp4IW7ZcqhV4se4DKgC3EGnAIAJ0BWswV_NYZFuMQ2LdBvXbZMxZ_oNmjCdrMps_XIJGvQSLf8jolQ5BAnQ6pB8J7SCVz3qrwF9i2HkQgGOaOTXomTjgHW23a8HSWqWC8QvMhcKnUBAoDidwAPozWQASBRm4gPIsr-EkxrAm6wf6Wmevw_UEzj7abG8ht_rPqy-gt3V-EV3yFP1O2eaCj-OtnS_vsOkTUnnj83tnoxkLxj86qFTqrtmiKdOUa_wqv5wKqaAzDXSggzuYq15BXbun0yZu1EB8k6wt_I2xLIcLbAKVwqr24z5MJNiAgBJsO2MpLjcC5KwdO-ILYBDoDRxDEr2mhEKw9Cn2JbLPAIwMfN2ug9wD8xym2po0OF6k0ktBBx0WTY9Xr-nbCOwMzaXaKeg3R9Rqi6zVE18BuVfOB1APhTf1SjxDNXwXbmpHnCNr8PbKNyCF1akaHrbgDL2gByzcW-CTYBAoDHJyVF9QFP7qFQuiM9K2yJYRAYoBX3IU_1bUrAy4NN8A1EEIgXQH28f31MY_SzdsJzUiupdeBQ68Dh8LaF6XRxfgrY5vnROSQ2h9PWjXgkyJlf7PMnRQp--tn67pdwcaBL8HXwBCIDKCj4Pe4GiDKAMcaOnlc6OTxoinWNBraEpSAE_R2TNkbL-dXc6kf23VEazSiYctg56jgB8FGjTvF1E4xtdMavfcrTXbo1zV6v8bnzuuBhsw7cR5RB6yHOucfC35WKkF1HHKs4_s1_neK_xn10U1ACz92nxYOy1Jsoy1iM9ZNYbsDK81HrRbstkfeH2qg4zM1FAYSA5ypnDIO4fxmDRTlK9zX6GQsYM-SBIByBSKLHADE64UU1nJB4PRADevypHdPGq9lWT_J3z_dvo2xfyv-N7TF_uzoQsAbZx0dwumSZXXvscuMjN62lpeG7X-jfpE2kyvccDmByAAf054yDoGDNwWkoMfh5swCMgcQWSSy0sgi6ACRDxut-p9IO6TaoRk6MnKkXy3wAWTqgjMgs7z3oRfotrjitQ80i5uG0sUeiyFrWJlqG1ZTChXEXhM5S_yh-FWlAVQGMgOBgc7usa4AZS0OCexC8NmoAmoQyAyEKxBZJLLSyMUeADpQqgfCJ_1XC8uhpx162iHVDs3giInHwKnHITwGLluRF6TbamdZ3nyjYsGyv2K4S85qsjxmr04hT8s8POXEDpDpSGvNNM1fMuVAGujl9M9C0oHY5xcfSNeXHUeQn_d2AXtkeWVADn1C6oZhc7u-ijVxmmvPJqKFM40WGeuQ7Zj2ujVhqTgq_Cr9P9YaZICQpQAA</s><k>k3</k><s>TGV2ZWwgMSBvZiBHZW9tZXRyeSBEYXNoLiBSZWxlYXNlZCB3aXRoIFVwZGF0ZSAxLjAgb24gQXVnIDEzLCAyMDEzLg==</s><k>k5</k><s>RobsVault</s><k>k6</k><i>169179680</i><k>k60</k><i>19293579</i><k>k9</k><i>10</i><k>k10</k><i>30</i><k>k11</k><i>943796</i><k>k22</k><i>22536</i><k>k21</k><i>3</i><k>k16</k><i>1</i><k>k17</k><i>21</i><k>k80</k><i>7</i><k>k83</k><i>3393</i><k>k64</k><i>3</i><k>k41</k><i>1</i><k>k50</k><i>45</i><k>k48</k><i>2291</i><k>k66</k><i>1</i></dict></plist>
\ No newline at end of file
diff --git a/games/numdash/package-lock.json b/games/numdash/package-lock.json
new file mode 100644
index 00000000..55577115
--- /dev/null
+++ b/games/numdash/package-lock.json
@@ -0,0 +1,147 @@
+{
+ "name": "NumDash",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "devDependencies": {
+ "nwlink": "0.0.19"
+ }
+ },
+ "node_modules/@types/w3c-web-usb": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/@types/w3c-web-usb/-/w3c-web-usb-1.0.6.tgz",
+ "integrity": "sha512-cSjhgrr8g4KbPnnijAr/KJDNKa/bBa+ixYkywFRvrhvi9n1WEl7yYbtRyzE6jqNQiSxxJxoAW3STaOQwJHndaw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/cli-progress": {
+ "version": "3.11.2",
+ "resolved": "https://registry.npmjs.org/cli-progress/-/cli-progress-3.11.2.tgz",
+ "integrity": "sha512-lCPoS6ncgX4+rJu5bS3F/iCz17kZ9MPZ6dpuTtI0KXKABkhyXIdYB3Inby1OpaGti3YlI3EeEkM9AuWpelJrVA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "string-width": "^4.2.3"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/commander": {
+ "version": "9.3.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-9.3.0.tgz",
+ "integrity": "sha512-hv95iU5uXPbK83mjrJKuZyFM/LBAoCV/XhVGkS5Je6tl7sxr6A0ITMw5WoRV46/UaJ46Nllm3Xt7IaJhXTIkzw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^12.20.0 || >=14"
+ }
+ },
+ "node_modules/emoji-regex": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/is-fullwidth-code-point": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/node-addon-api": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-4.3.0.tgz",
+ "integrity": "sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/node-gyp-build": {
+ "version": "4.8.4",
+ "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz",
+ "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "node-gyp-build": "bin.js",
+ "node-gyp-build-optional": "optional.js",
+ "node-gyp-build-test": "build-test.js"
+ }
+ },
+ "node_modules/nwlink": {
+ "version": "0.0.19",
+ "resolved": "https://registry.npmjs.org/nwlink/-/nwlink-0.0.19.tgz",
+ "integrity": "sha512-8o7Ym4wd7zKErwRry9D/U9pD7/wbrMFm0QR5m3KLQUXiMe3/8Km3Z8wU0vGQkeUYIMeoc5uUAx9q3HOZboeLIw==",
+ "dev": true,
+ "license": "All rights reserved",
+ "dependencies": {
+ "cli-progress": "3.11.2",
+ "commander": "9.3.0",
+ "usb": "2.4.3"
+ },
+ "bin": {
+ "nwlink": "bin/nwlink"
+ }
+ },
+ "node_modules/string-width": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/usb": {
+ "version": "2.4.3",
+ "resolved": "https://registry.npmjs.org/usb/-/usb-2.4.3.tgz",
+ "integrity": "sha512-BmCjjxsriODcrb+TdXdzSDDys+MOUeRvo22ywmyIxYcuVW9YKrr2Wp2gQZUfHrQbvovKu87Po9mk5OPftJdDeQ==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/w3c-web-usb": "1.0.6",
+ "node-addon-api": "^4.2.0",
+ "node-gyp-build": "^4.3.0"
+ },
+ "engines": {
+ "node": ">=10.20.0 <11.x || >=12.17.0 <13.0 || >=14.0.0"
+ }
+ }
+ }
+}
diff --git a/games/numdash/package.json b/games/numdash/package.json
new file mode 100644
index 00000000..7b9121ed
--- /dev/null
+++ b/games/numdash/package.json
@@ -0,0 +1,5 @@
+{
+ "devDependencies": {
+ "nwlink": "0.0.19"
+ }
+}
diff --git a/games/numdash/src/app.c b/games/numdash/src/app.c
new file mode 100644
index 00000000..1e728525
--- /dev/null
+++ b/games/numdash/src/app.c
@@ -0,0 +1,221 @@
+/* Screen management, input, transitions and dialogs. */
+#include "app.h"
+#include "ui.h"
+#include <math.h>
+#include <string.h>
+
+App app;
+Progress progress;
+CustomMeta custom_meta[CUSTOM_SLOTS];
+
+/* Geometry Dash's icon colours (the classic 2.1 set). */
+static const uint8_t icon_colors[42][3] = {
+ {125, 255, 0}, {0, 255, 0}, {0, 255, 125}, {0, 255, 255}, {0, 125, 255}, {0, 0, 255}, {125, 0, 255},
+ {255, 0, 255}, {255, 0, 125}, {255, 0, 0}, {255, 125, 0}, {255, 255, 0}, {255, 255, 255}, {185, 0, 255},
+ {255, 185, 0}, {0, 0, 0}, {0, 200, 255}, {175, 175, 175}, {90, 90, 90}, {255, 125, 125}, {0, 175, 75},
+ {0, 125, 125}, {0, 75, 175}, {75, 0, 175}, {125, 0, 125}, {175, 0, 75}, {175, 75, 0}, {125, 125, 0},
+ {75, 175, 0}, {255, 75, 0}, {150, 50, 0}, {150, 100, 0}, {100, 150, 0}, {0, 150, 100}, {0, 100, 150},
+ {100, 0, 150}, {150, 0, 100}, {150, 0, 0}, {0, 150, 0}, {0, 0, 150}, {125, 255, 175}, {125, 125, 255}};
+color_t icon_color(int i) {
+ if (i < 0 || i >= 42) i = 0;
+ return rgb(icon_colors[i][0], icon_colors[i][1], icon_colors[i][2]);
+}
+color_t app_p1(void) { return icon_color(progress.color1); }
+color_t app_p2(void) { return icon_color(progress.color2); }
+
+static uint32_t rng = 0x9e3779b9u;
+float frand(void) {
+ rng ^= rng << 13; rng ^= rng >> 17; rng ^= rng << 5;
+ return (rng >> 8) * (1.0f / 16777216.0f);
+}
+
+uint32_t app_hit(uint32_t mask) { return app.hit & mask; }
+bool app_accept(void) { return (app.hit & (K_OK | K_EXE)) != 0; }
+void app_begin_press(int id) { app.press_id = id; app.press_t = 0; }
+
+void app_notice(const char *s) {
+ strncpy(app.notice, s, sizeof(app.notice) - 1);
+ app.notice[sizeof(app.notice) - 1] = 0;
+ app.notice_t = 2.5f;
+}
+
+bool app_save_progress(void) { return save_write_progress(&progress); }
+
+static void enter(Screen s) {
+ app.screen = s;
+ app.t = 0;
+ app.sel = 0;
+ app.row = 0;
+ app.press_id = -1;
+ if (s == SCR_PLAY && !play_start(app.level, app.practice, app.testing)) {
+ app_notice("LEVEL DATA INVALID");
+ s = app.screen = app.testing ? SCR_EDITOR : app.level < LEVEL_COUNT ? SCR_SELECT : SCR_CREATOR;
+ }
+ if (s == SCR_EDITOR) editor_open(app.slot);
+ else if (s != SCR_PLAY) menu_enter(s);
+}
+
+void app_go(Screen s) {
+ if (app.fading_out) return;
+ app.next = s;
+ app.fading_out = true;
+}
+
+void app_init(void) {
+ memset(&app, 0, sizeof(app));
+ app.running = true;
+ app.press_id = -1;
+ rng ^= platform_random() | 1;
+ if (!save_load_all(&progress, custom_meta)) {
+ size_t size;
+ if (platform_storage(&size)) app_notice("SAVE DATA UNREADABLE");
+ }
+ app.level = progress.last_level < LEVEL_COUNT ? progress.last_level : 0;
+ app.select_page = app.level;
+ app.select_scroll = (float)app.level;
+ enter(SCR_LOADING);
+ app.fade = 1;
+}
+
+static void quit(void) {
+ if (app.screen == SCR_PLAY) play_flush();
+ if (app.screen == SCR_EDITOR) editor_flush();
+ app_save_progress();
+ app.running = false;
+}
+
+/* ------------------------------------------------------------ dialogs */
+
+static float dialog_t;
+static int dialog_sel, saved_sel;
+static void dialog_open(int kind, const char *title, const char *text) {
+ app.dialog = kind;
+ app.dialog_title = title;
+ app.dialog_text = text;
+ dialog_t = 0;
+ dialog_sel = 0;
+ saved_sel = app.sel;
+}
+static void dialog_close(void) {
+ app.dialog = DLG_NONE;
+ app.sel = saved_sel;
+}
+static void dialog_tick(void) {
+ if (app.dialog == DLG_QUIT) {
+ if (app_hit(K_LEFT | K_RIGHT)) dialog_sel ^= 1;
+ if (app_hit(K_BACK)) { dialog_close(); return; }
+ if (app_accept()) {
+ if (dialog_sel == 1) quit();
+ dialog_close();
+ }
+ } else if (app_accept() || app_hit(K_BACK)) {
+ dialog_close();
+ }
+}
+static void dialog_draw(void) {
+ float s = ui_ease_elastic_out(dialog_t / 0.5f, 0.6f);
+ ui_dim((unsigned)(fminf(dialog_t / 0.14f, 1) * 110));
+ int w = (int)(250 * s), h = (int)(128 * s);
+ if (w < 8 || h < 8) return;
+ ui_window_brown(160 - w / 2, 120 - h / 2, w, h);
+ if (s < 0.85f) return;
+ ui_gold(FONT_BIG, 160, 84, app.dialog_title);
+ /* message, split on '\n' */
+ const char *p = app.dialog_text;
+ int y = 110;
+ char line[48];
+ while (p && *p) {
+ int n = 0;
+ while (*p && *p != '\n' && n < 47) line[n++] = *p++;
+ line[n] = 0;
+ if (*p == '\n') p++;
+ ui_title(FONT_SMALL, 160, y, line);
+ y += 13;
+ }
+ if (app.dialog == DLG_QUIT) {
+ ui_text_button(118, 154, 76, 26, "CANCEL", BTN_GREEN, dialog_sel == 0 ? 1.1f : 1.0f);
+ ui_text_button(202, 154, 60, 26, "YES", BTN_GREEN, dialog_sel == 1 ? 1.1f : 1.0f);
+ } else {
+ ui_text_button(160, 154, 60, 26, "OK", BTN_GREEN, 1.1f);
+ }
+}
+void app_dialog_quit(void) { dialog_open(DLG_QUIT, "QUIT GAME", "ARE YOU SURE YOU\nWANT TO QUIT?"); }
+void app_dialog_info(const char *title, const char *text) { dialog_open(DLG_INFO, title, text); }
+
+/* ------------------------------------------------------------ main hooks */
+
+void app_tick(uint32_t keys) {
+ app.ticks++;
+ uint32_t hit = keys & ~app.prev_keys;
+ const uint32_t arrows = K_LEFT | K_RIGHT | K_UP | K_DOWN;
+ static uint32_t held_since;
+ if (keys & arrows) {
+ if ((keys & arrows) != (app.prev_keys & arrows)) {
+ app.repeat_at = app.ticks + 96;
+ held_since = app.ticks;
+ } else if (app.ticks >= app.repeat_at) {
+ hit |= keys & arrows;
+ /* 10 repeats per second, then 24 after holding for a while */
+ app.repeat_at = app.ticks + (app.ticks - held_since > 360 ? 10 : 24);
+ }
+ }
+ app.prev_keys = keys;
+ app.keys = keys;
+ app.hit = hit;
+ if (hit & K_HOME) { quit(); return; }
+ if (app.fading_out) { app.hit = 0; if (app.screen != SCR_PLAY) return; }
+ if (app.dialog) { dialog_tick(); return; }
+ switch (app.screen) {
+ case SCR_PLAY: play_tick(); break;
+ case SCR_EDITOR: editor_tick(); break;
+ case SCR_CREATOR: creator_tick(); break;
+ default: menu_tick(); break;
+ }
+}
+
+void app_frame(float dt) {
+ app.t += dt;
+ if (app.press_id >= 0) app.press_t += dt;
+ if (app.notice_t > 0) app.notice_t -= dt;
+ if (app.dialog) dialog_t += dt;
+ if (app.fading_out) {
+ app.fade += dt / 0.25f;
+ if (app.fade >= 1) {
+ app.fade = 1;
+ app.fading_out = false;
+ enter(app.next);
+ dt = 0; /* the new screen still prepares its first frame below */
+ }
+ } else if (app.fade > 0) {
+ app.fade -= dt / 0.25f;
+ if (app.fade < 0) app.fade = 0;
+ }
+ switch (app.screen) {
+ case SCR_PLAY: play_frame(dt); break;
+ case SCR_EDITOR: editor_frame(dt); break;
+ default: menu_frame(dt); break;
+ }
+}
+
+void app_draw(void) {
+ switch (app.screen) {
+ case SCR_PLAY: play_draw(); break;
+ case SCR_EDITOR: editor_draw(); break;
+ case SCR_CREATOR: creator_draw(); break;
+ default: menu_draw(); break;
+ }
+ if (app.dialog) dialog_draw();
+ if (app.notice_t > 0) {
+ unsigned a = app.notice_t < 0.3f ? (unsigned)(app.notice_t / 0.3f * 256) : 256;
+ int w = gfx_text_width(FONT_SMALL, app.notice) + 16;
+ gfx_round_rect(160 - w / 2, 196, w, 16, 5, 0, a * 3 / 5);
+ gfx_text_center(FONT_SMALL, 160, 208, app.notice, 0xffff, 0xffff, a);
+ }
+ if (progress.options & OPT_FPS) {
+ char buf[12];
+ int n = gfx_format_uint(buf, app.fps);
+ memcpy(buf + n, " FPS", 5);
+ gfx_text(FONT_SMALL, 4, 236, buf, 0xffff, 0xffff, 220);
+ }
+ if (app.fade > 0) gfx_scale_rect(0, 0, GFX_W, GFX_H, (unsigned)((1 - app.fade) * 256));
+}
diff --git a/games/numdash/src/app.h b/games/numdash/src/app.h
new file mode 100644
index 00000000..0ca62a3a
--- /dev/null
+++ b/games/numdash/src/app.h
@@ -0,0 +1,109 @@
+#ifndef NUMDASH_APP_H
+#define NUMDASH_APP_H
+#include "fx.h"
+#include "game.h"
+#include "gfx.h"
+#include "platform.h"
+#include "save.h"
+#include "scene.h"
+
+typedef enum { SCR_MENU, SCR_SELECT, SCR_PLAY, SCR_GARAGE, SCR_CREATOR, SCR_EDITOR, SCR_LOADING } Screen;
+enum { DLG_NONE, DLG_QUIT, DLG_INFO };
+#define MAX_CHECKPOINTS 40
+
+typedef struct {
+ Screen screen, next, back_to;
+ float fade; /* 0..1 screen transition to black */
+ bool fading_out;
+ float t; /* seconds on this screen */
+ uint32_t keys, prev_keys, hit, repeat_at, ticks;
+ int sel, row; /* focused widget */
+ float press_t; /* button press animation */
+ int press_id;
+ int dialog;
+ const char *dialog_title, *dialog_text;
+ char notice[48];
+ float notice_t;
+ unsigned fps;
+ bool running, vsync;
+
+ /* level being played */
+ int level; /* 0..LEVEL_COUNT-1 built-in, then custom slots */
+ Level L;
+ Game g;
+ bool practice, testing, paused, has_level;
+ unsigned attempt, session_jumps;
+ uint32_t session_ticks; /* time played in this session (complete screen) */
+ float death_t, complete_t, end_menu_t, newbest_t, pause_t;
+ int newbest_percent;
+ bool newbest, end_menu, first_attempt;
+ uint8_t coins_before, coins_got;
+ Checkpoint checkpoints[MAX_CHECKPOINTS];
+ unsigned checkpoint_count;
+ float auto_check_t;
+ float attempt_x, attempt_y;
+ const char *complete_msg;
+
+ /* menus */
+ int select_page;
+ float select_scroll; /* animated page position */
+ float menu_bg_x, menu_ground_x;
+ int menu_color;
+ float menu_color_t;
+ uint8_t menu_from[3], menu_to[3];
+ int garage_tab;
+
+ /* editor */
+ int slot;
+ int cur_x, cur_y, brush, rotate, edit_mode, edit_page;
+ float edit_cam_x, edit_cam_y;
+ bool dirty;
+} App;
+extern App app;
+
+extern Progress progress;
+extern CustomMeta custom_meta[CUSTOM_SLOTS];
+
+void app_init(void);
+void app_tick(uint32_t keys);
+void app_frame(float dt);
+void app_draw(void);
+
+/* app.c helpers shared with the screens */
+void app_go(Screen s);
+void app_notice(const char *s);
+bool app_save_progress(void);
+color_t icon_color(int index);
+color_t app_p1(void);
+color_t app_p2(void);
+float frand(void);
+uint32_t app_hit(uint32_t mask);
+bool app_accept(void);
+void app_begin_press(int id);
+void app_dialog_quit(void);
+void app_dialog_info(const char *title, const char *text);
+
+/* play.c */
+bool play_start(int level, bool practice, bool testing);
+void play_tick(void);
+void play_frame(float dt);
+void play_draw(void);
+void play_flush(void);
+
+/* menu.c */
+void menu_enter(Screen s);
+void menu_tick(void);
+void menu_frame(float dt);
+void menu_draw(void);
+
+/* editor.c */
+void editor_open(int slot);
+void editor_tick(void);
+void editor_frame(float dt);
+void editor_draw(void);
+void creator_tick(void);
+void creator_draw(void);
+bool editor_load_slot(int slot, Level *L);
+void editor_flush(void);
+unsigned editor_object_count(void);
+#endif
diff --git a/games/numdash/src/assets.c b/games/numdash/src/assets.c
new file mode 100644
index 00000000..666eca51
--- /dev/null
+++ b/games/numdash/src/assets.c
@@ -0,0 +1,2066 @@
+/* Generated by tools/assets.py. Do not edit. */
+#include "assets.h"
+const Sprite sprites[SPR_COUNT] = {
+ {20,20,10,10,1,0,0},
+ {20,20,10,10,1,0,400},
+ {20,20,10,10,1,0,800},
+ {20,20,10,10,1,0,1200},
+ {20,20,10,10,1,0,1600},
+ {20,20,10,10,1,0,2000},
+ {20,20,10,10,1,0,2400},
+ {26,26,13,13,0,0,2800},
+ {20,6,10,13,0,0,3138},
+ {23,23,13,13,0,0,3198},
+ {6,6,13,13,0,0,3474},
+ {26,23,13,13,0,0,3492},
+ {26,20,13,10,0,0,3791},
+ {20,20,10,10,1,0,4051},
+ {20,10,10,5,1,0,4451},
+ {14,14,7,7,1,0,4651},
+ {26,26,13,13,0,0,4847},
+ {26,16,13,8,0,0,5185},
+ {20,20,10,10,0,0,5393},
+ {20,17,10,8,0,0,5593},
+ {20,18,10,9,0,0,5763},
+ {20,18,10,9,0,0,5943},
+ {20,10,10,5,1,0,6123},
+ {26,14,13,7,0,0,6323},
+ {20,10,10,6,1,0,6505},
+ {20,11,10,6,1,0,6705},
+ {20,10,10,6,1,0,6925},
+ {20,12,10,6,1,0,7125},
+ {6,27,3,13,0,0,7365},
+ {6,17,3,8,0,0,7446},
+ {6,8,3,3,0,0,7497},
+ {20,20,10,10,0,0,7521},
+ {83,27,40,13,0,0,7721},
+ {70,25,35,12,0,0,8855},
+ {46,18,22,8,0,0,9730},
+ {28,8,14,3,0,0,10144},
+ {10,48,5,24,0,0,10256},
+ {10,24,5,12,0,0,10496},
+ {18,18,9,9,0,0,10616},
+ {20,20,10,10,1,0,10778},
+ {18,4,9,2,2,0,11178},
+ {18,6,9,3,0,0,11214},
+ {18,4,9,2,2,1,11268},
+ {18,6,9,3,0,0,11304},
+ {18,4,9,2,2,2,11358},
+ {18,6,9,3,0,0,11394},
+ {20,20,10,10,2,3,11448},
+ {26,26,13,13,0,0,11648},
+ {20,20,10,10,2,4,11986},
+ {26,26,13,13,0,0,12186},
+ {20,20,10,10,2,5,12524},
+ {26,26,13,13,0,0,12724},
+ {8,50,8,25,2,6,13062},
+ {15,50,9,25,2,7,13262},
+ {8,50,8,25,2,8,13662},
+ {15,50,9,25,2,9,13862},
+ {16,52,10,26,2,10,14262},
+ {21,62,11,31,2,11,14678},
+ {16,52,10,26,2,12,15360},
+ {21,62,11,31,2,13,15776},
+ {26,26,13,13,2,14,16458},
+ {20,26,10,13,2,15,16796},
+ {6,26,3,13,2,16,17056},
+ {20,26,10,13,2,17,17134},
+ {20,20,10,10,1,0,17394},
+ {6,6,3,3,1,0,17794},
+ {26,15,13,8,1,0,17830},
+ {17,7,8,7,1,0,18220},
+ {78,78,39,39,2,18,18339},
+ {54,54,27,27,2,19,21381},
+ {54,54,27,27,2,20,22839},
+ {36,37,18,18,2,21,24297},
+ {36,37,18,18,2,22,24963},
+ {36,37,18,18,2,23,25629},
+ {32,33,16,16,2,24,26295},
+ {68,69,34,34,2,25,26823},
+ {52,53,26,26,2,26,29169},
+ {52,53,26,26,2,27,30547},
+ {52,53,26,26,2,28,31925},
+ {52,53,26,26,2,29,33303},
+ {30,31,15,15,2,30,34681},
+ {24,25,12,12,2,31,35146},
+ {24,30,12,15,2,32,35446},
+ {22,50,11,25,2,33,35806},
+ {27,27,14,14,2,34,36356},
+ {27,27,14,14,2,35,36734},
+ {27,27,14,14,2,36,37112},
+ {27,27,14,14,2,37,37490},
+ {27,27,14,14,2,38,37868},
+ {14,13,7,7,2,39,38246},
+ {22,22,11,12,2,40,38337},
+ {16,16,8,8,2,41,38579},
+ {16,16,8,8,2,42,38707},
+ {28,28,14,14,2,43,38835},
+ {28,28,14,14,2,44,39227},
+ {41,41,0,43,2,45,39619},
+ {19,19,10,10,2,46,40480},
+ {19,19,10,10,2,47,40670},
+ {1,1,0,0,0,0,40860},
+ {3,7,0,7,0,0,40861},
+ {10,9,0,8,0,0,40875},
+ {3,4,0,7,0,0,40920},
+ {3,9,-1,7,0,0,40928},
+ {4,9,0,7,0,0,40946},
+ {6,6,0,6,0,0,40964},
+ {3,5,0,3,0,0,40982},
+ {4,3,0,4,0,0,40992},
+ {3,3,0,3,0,0,40998},
+ {4,9,0,8,0,0,41004},
+ {6,7,0,7,0,0,41022},
+ {6,7,0,7,0,0,41043},
+ {6,7,0,7,0,0,41064},
+ {6,7,0,7,0,0,41085},
+ {6,7,0,7,0,0,41106},
+ {6,7,0,7,0,0,41127},
+ {6,7,0,7,0,0,41148},
+ {6,7,0,7,0,0,41169},
+ {6,7,0,7,0,0,41190},
+ {6,7,0,7,0,0,41211},
+ {3,5,0,5,0,0,41232},
+ {5,7,0,7,0,0,41242},
+ {8,7,0,7,0,0,41263},
+ {7,7,0,7,0,0,41291},
+ {7,7,0,7,0,0,41319},
+ {8,7,0,7,0,0,41347},
+ {6,7,0,7,0,0,41375},
+ {6,7,0,7,0,0,41396},
+ {7,7,0,7,0,0,41417},
+ {8,7,0,7,0,0,41445},
+ {3,7,0,7,0,0,41473},
+ {5,7,1,7,0,0,41487},
+ {7,7,0,7,0,0,41508},
+ {6,7,0,7,0,0,41536},
+ {9,7,0,7,0,0,41557},
+ {7,7,0,7,0,0,41592},
+ {8,7,0,7,0,0,41620},
+ {7,7,0,7,0,0,41648},
+ {8,9,0,7,0,0,41676},
+ {7,7,0,7,0,0,41712},
+ {7,7,0,7,0,0,41740},
+ {7,7,0,7,0,0,41768},
+ {7,7,0,7,0,0,41796},
+ {8,7,0,7,0,0,41824},
+ {11,7,0,7,0,0,41852},
+ {7,7,0,7,0,0,41894},
+ {7,7,0,7,0,0,41922},
+ {7,7,0,7,0,0,41950},
+ {1,1,0,0,0,0,41978},
+ {6,14,0,13,0,0,41979},
+ {26,14,0,13,0,0,42021},
+ {5,7,0,13,0,0,42203},
+ {8,15,0,14,0,0,42224},
+ {8,15,0,14,0,0,42284},
+ {9,9,0,11,0,0,42344},
+ {6,8,0,4,0,0,42389},
+ {7,5,0,8,0,0,42413},
+ {6,6,0,5,0,0,42433},
+ {8,13,0,13,0,0,42451},
+ {14,14,0,13,0,0,42503},
+ {9,13,0,13,0,0,42601},
+ {13,13,0,13,0,0,42666},
+ {14,14,0,13,0,0,42757},
+ {14,13,0,13,0,0,42855},
+ {14,14,0,13,0,0,42946},
+ {14,14,0,13,0,0,43044},
+ {14,14,0,13,0,0,43142},
+ {14,14,0,13,0,0,43240},
+ {14,14,0,13,0,0,43338},
+ {5,11,0,11,0,0,43436},
+ {9,14,0,13,0,0,43469},
+ {17,13,0,13,0,0,43539},
+ {15,13,0,13,0,0,43656},
+ {12,14,0,13,0,0,43760},
+ {14,13,0,13,0,0,43844},
+ {11,13,0,13,0,0,43935},
+ {10,13,0,13,0,0,44013},
+ {13,14,0,13,0,0,44078},
+ {14,13,0,13,0,0,44176},
+ {6,13,0,13,0,0,44267},
+ {12,14,0,13,0,0,44306},
+ {15,13,0,13,0,0,44390},
+ {10,13,0,13,0,0,44494},
+ {17,13,0,13,0,0,44559},
+ {14,13,0,13,0,0,44676},
+ {15,14,0,13,0,0,44767},
+ {14,13,0,13,0,0,44879},
+ {16,14,0,13,0,0,44970},
+ {15,13,0,13,0,0,45082},
+ {11,15,0,14,0,0,45186},
+ {13,13,0,13,0,0,45276},
+ {13,14,0,13,0,0,45367},
+ {15,14,0,13,0,0,45465},
+ {21,14,0,13,0,0,45577},
+ {15,13,0,13,0,0,45731},
+ {13,13,0,13,0,0,45835},
+ {14,13,0,13,0,0,45926},
+ {1,1,0,0,0,0,46017},
+ {7,20,-1,19,0,0,46018},
+ {39,21,0,20,0,0,46098},
+ {7,9,0,19,0,0,46518},
+ {11,21,0,20,0,0,46554},
+ {11,21,-1,20,0,0,46680},
+ {13,13,0,16,0,0,46806},
+ {8,11,-1,5,0,0,46897},
+ {10,6,-1,11,0,0,46941},
+ {8,8,0,7,0,0,46971},
+ {12,19,0,19,0,0,47003},
+ {21,21,0,20,0,0,47117},
+ {13,19,0,19,0,0,47348},
+ {20,20,0,20,0,0,47481},
+ {20,20,-1,19,0,0,47681},
+ {21,19,0,19,0,0,47881},
+ {19,20,-1,19,0,0,48090},
+ {20,21,0,20,0,0,48290},
+ {20,19,-1,19,0,0,48500},
+ {19,21,-1,20,0,0,48690},
+ {20,21,0,20,0,0,48900},
+ {7,16,-1,16,0,0,49110},
+ {14,21,0,20,0,0,49174},
+ {25,21,0,20,0,0,49321},
+ {21,21,-1,20,0,0,49594},
+ {17,21,0,20,0,0,49825},
+ {20,21,-1,20,0,0,50014},
+ {15,19,-1,19,0,0,50224},
+ {14,20,-1,19,0,0,50376},
+ {19,21,0,20,0,0,50516},
+ {19,19,-1,19,0,0,50726},
+ {8,19,-1,19,0,0,50916},
+ {18,20,0,19,0,0,50992},
+ {21,19,-1,19,0,0,51172},
+ {14,19,-1,19,0,0,51381},
+ {25,19,-1,19,0,0,51514},
+ {20,19,-1,19,0,0,51761},
+ {22,21,0,20,0,0,51951},
+ {19,20,-1,20,0,0,52182},
+ {24,21,0,20,0,0,52382},
+ {21,20,-1,20,0,0,52634},
+ {15,21,-1,20,0,0,52854},
+ {19,19,0,19,0,0,53022},
+ {19,20,-1,19,0,0,53212},
+ {22,20,0,19,0,0,53412},
+ {31,20,0,19,0,0,53632},
+ {21,19,-1,19,0,0,53952},
+ {20,19,0,19,0,0,54161},
+ {20,19,-1,19,0,0,54351},
+};
+const uint16_t sprite_pal_rgb[][16] = {
+ {0x0000,0xfe00,0xff4b,0xff6b,0xfda0,0xff2b,0xff4b,0xff4b,0xfec5,0xff4b,0xff0b,0xff2b,0xfeeb,0xfeea,0xfec7,0xfea3},
+ {0x0000,0x0d9f,0x879f,0x87bf,0x877f,0x87bf,0x87bf,0x4eff,0x877f,0x771f,0x771f,0x263f,0x879f,0x7f5f,0x36df,0x5f1f},
+ {0x0000,0xea9f,0xfd3f,0xfd3f,0xe23f,0xfd1f,0xfd3f,0xf4ff,0xfd3f,0xf4ff,0xf3bf,0xfd1f,0xf4df,0xf4bf,0xf45f,0xf3ff},
+ {0x0000,0xfe83,0xffff,0xffff,0xffb0,0xffff,0xff90,0xff48,0xffb0,0xffff,0xffb0,0xffff,0xffff,0xff6d,0xfee5,0xffff},
+ {0x0000,0x369f,0xffff,0xffff,0xb7bf,0x979f,0xffff,0xb7bf,0xffff,0xb7bf,0xffff,0x6f5f,0xafbf,0xffff,0xffff,0x4eff},
+ {0x0000,0xf2bf,0xffff,0xffff,0xffff,0xfddf,0xfddf,0xfddf,0xffff,0xffff,0xfc5f,0xfddf,0xffff,0xfd5f,0xffff,0xf37f},
+ {0x0000,0xcf5f,0x663d,0x457d,0xd75f,0x5ddd,0xd75f,0x871d,0x4d7d,0xdf9f,0xd77f,0x34fd,0x7ebe,0x76bd,0x453d,0x5e1d},
+ {0x0000,0x459f,0x0000,0xdf9f,0x0000,0x3c13,0xdf9f,0x0000,0x3d3e,0x7eff,0xdf9f,0x1a8f,0xd77f,0x2a4b,0x875f,0x55bd},
+ {0x0000,0xff79,0xee8b,0xede8,0xff7a,0xff7a,0xee4b,0xede8,0xff9b,0xef0f,0xff7a,0xed86,0xeece,0xf6ee,0xedc7,0xee6b},
+ {0x0000,0xfe08,0x0000,0xff9b,0x0000,0x9c27,0xff9a,0x0000,0xf66b,0xff2e,0xffbb,0x7ac3,0x5a64,0xdda9,0xff0d,0x0000},
+ {0x0000,0xcf99,0x0000,0xd79a,0x1122,0x4e69,0xdfbb,0x0000,0x96f2,0x43e7,0xdfbb,0x8750,0x2543,0x0000,0x0000,0xd79a},
+ {0x0000,0x4ec8,0xe7dc,0x0000,0xcfb9,0x3fe7,0x0020,0x87b0,0xe7dc,0x3de6,0x0020,0x0020,0x47e8,0x2384,0x3fe7,0x1a83},
+ {0x0000,0xf69e,0x0000,0xf6be,0x1843,0xd25a,0xf6de,0x0000,0x7a2f,0xec3d,0xe4bc,0x0000,0xf6fe,0x0000,0xf6de,0x50ca},
+ {0x0000,0xe2dc,0x0000,0xf71e,0x0801,0xff3f,0xfaff,0x716e,0x0801,0xc9d9,0xf53e,0xfaff,0x510a,0xff3f,0x0000,0xfaff},
+ {0x0000,0x3900,0x38e0,0xfed1,0xcbc2,0x38e0,0xf606,0x7283,0x38e0,0xdd06,0x38e0,0xf669,0xf561,0xa342,0x59a1,0xe4a3},
+ {0x0000,0x4100,0x38e0,0xfed1,0xc3a2,0x38e0,0xeda5,0x38e0,0x7242,0x38e0,0xdcc3,0xf669,0xf561,0x38e0,0x38e0,0x38e0},
+ {0x0000,0x8b24,0x38e0,0xc548,0xff76,0x38e0,0xdd67,0x93a5,0xc528,0xb4ec,0x38e0,0xff0e,0xc4a6,0x8b44,0x38e0,0xf68a},
+ {0x0000,0x4100,0x38e0,0xfed1,0xcb81,0x38e0,0xf629,0x38e0,0x6a21,0x38e0,0xdcc5,0xf561,0x9323,0x38e0,0x38e0,0x38e0},
+ {0x0000,0x0840,0x7f1d,0x0000,0xed24,0x0000,0x5542,0xbf6e,0x2d5a,0x8ec5,0x8b23,0x0000,0x3201,0xee07,0x0000,0xb464},
+ {0x0000,0x0840,0xef4b,0x0000,0x3433,0x6e04,0x0000,0xe421,0x32e2,0x6596,0xaf49,0x1aee,0x0000,0x8323,0xeda5,0x44a1},
+ {0x0000,0x0020,0xbf6e,0x0000,0x2d5a,0x6de3,0x0000,0xee48,0x23f3,0x7f1d,0x9f26,0x44a1,0x0000,0x5d76,0xcc43,0x2141},
+ {0x0000,0x0020,0x0000,0xf668,0x4d02,0x0000,0xdcc4,0x7282,0x9ee9,0x0000,0x0000,0x7605,0x42e4,0xb76d,0x5bc6,0x2982},
+ {0x0000,0x0840,0x0000,0xb76d,0x8b22,0x0000,0xe545,0x7e65,0x4d22,0x0000,0x3a23,0x0000,0x6c88,0x9ee9,0xe482,0xf627},
+ {0x0000,0x0020,0x0000,0xf709,0x5d82,0x0000,0xdc62,0x6a83,0x96a7,0x0000,0x0000,0x7ce7,0x2161,0xe5c6,0x4b24,0xb76c},
+ {0x0000,0x0000,0x0000,0xb76d,0x5522,0x0000,0xed24,0x4263,0x0000,0x9706,0x0000,0xede6,0x75e5,0x2121,0x5c05,0x96ab},
+ {0x0000,0x0861,0xef7d,0x0000,0xef7d,0x7bef,0xeda5,0xef7d,0x0821,0xa72a,0x2965,0x8c51,0x65a3,0xc638,0xad75,0x4aa5},
+ {0x0000,0x0881,0xef7d,0x76fd,0x0000,0x6b6d,0x6583,0xef7d,0x2d39,0x0000,0xbdd7,0xa72a,0x42e7,0xef7d,0x8cb2,0xe73c},
+ {0x0000,0x0861,0xef7d,0x6ebd,0x0000,0x6b6d,0x5d63,0xef7d,0x24b7,0x0000,0xbdd7,0xa72a,0x3246,0x8c71,0xef5d,0xe73c},
+ {0x0000,0x0861,0xef7d,0x0000,0xb777,0x6b6d,0x5d84,0xef7d,0x0000,0xbdd7,0x3aa5,0x8450,0xa72a,0xe73c,0x47aa,0xef7d},
+ {0x0000,0x0841,0xef7d,0x0000,0xe77c,0x6b6d,0xf125,0x4da4,0xef7d,0x0000,0x6c2a,0xa72a,0x6882,0xb5d6,0x3264,0xe73c},
+ {0x0000,0x0020,0x0000,0xf688,0x5542,0x0000,0xe483,0x4243,0x8ea8,0x0000,0x0000,0xa3e4,0xed85,0x1901,0xb76c,0x5bc6},
+ {0x0000,0x0020,0x0000,0x6edd,0x65a3,0x0000,0x2391,0xb78d,0x3ae4,0x3ddb,0x0000,0x0000,0x1a09,0x96c9,0x4432,0x6c88},
+ {0x0000,0x0000,0x0000,0xc76e,0x0000,0x5ba6,0x8ea7,0x0000,0x1922,0x0000,0x7625,0x8d8a,0xa6ec,0x0000,0x0000,0x0000},
+ {0x0000,0xdedb,0x0000,0xffdf,0x4a49,0x73ae,0x0000,0xbdf7,0x4228,0xce59,0xef5d,0x7bef,0x94b2,0xce79,0xb596,0xffff},
+ {0x0000,0x0000,0xe7df,0x0000,0x25ff,0xf2ce,0x0000,0x1aad,0x6f1f,0x9cf3,0x89a8,0x0000,0x0000,0x7b10,0x1bb3,0x1125},
+ {0x0000,0x0040,0xf7fe,0x0000,0x5f06,0x0000,0x9cf3,0x23a2,0xafb2,0x0000,0x0000,0x7f8a,0x3662,0x2985,0x3ba5,0x1201},
+ {0x0000,0x0000,0xffde,0x0000,0xfce2,0x0000,0x9cf3,0x7283,0xfe2a,0x0000,0x0000,0x3962,0xdd49,0xfed2,0x9b22,0xfd85},
+ {0x0000,0x0000,0xffdf,0x0000,0xf36a,0x0000,0x528a,0xf512,0x7924,0x94b2,0x0000,0x0000,0xe638,0x40e3,0x9a67,0xe9e6},
+ {0x0000,0x0000,0xffdf,0x0000,0xd9fb,0x0000,0x518a,0xf41e,0xa434,0x712e,0x0000,0x3106,0x0000,0xf59e,0xe2fc,0x8a71},
+ {0x0000,0x0000,0x0000,0xee07,0x0000,0x7344,0x0000,0xcc43,0x5202,0x0000,0x0000,0xcd46,0x7241,0x1060,0x9ba3,0xed44},
+ {0x0000,0x0820,0x0000,0xf688,0x0000,0x8b64,0xe4e3,0x0000,0x3941,0x0000,0xd566,0xbbc2,0x6a62,0x0000,0xa425,0xedc6},
+ {0x0000,0x4940,0x38e0,0xf669,0x38e0,0xcb81,0x38e0,0x82e3,0xc4e7,0x38e0,0xa3e5,0x38e0,0xeda7,0xdca3,0x92c1,0x3900},
+ {0x0000,0x2925,0x2104,0x8c71,0x2104,0x2104,0x5aeb,0x2104,0x4a49,0x2104,0x7bcf,0x2104,0x2104,0x2104,0x2104,0x4208},
+ {0x0000,0x4940,0x38e0,0xf689,0x38e0,0xcba1,0x38e0,0x38e0,0xbcc7,0x8b03,0x6a01,0x38e0,0xedc7,0xabe4,0xdca3,0x92a0},
+ {0x0000,0x3166,0x2104,0x9492,0x2104,0x632c,0x2104,0x2104,0x738e,0x4208,0x2104,0x2104,0x2104,0x2104,0x5acb,0x8410},
+ {0x0000,0x0020,0x16de,0xafa7,0x0000,0x1537,0x8e06,0x0000,0x15fa,0x00c3,0x9ee6,0x10c1,0x1598,0x167c,0x9686,0xa747},
+ {0x0000,0x0861,0xb596,0x0000,0x4e23,0x0000,0x4a49,0x8430,0x7f47,0x22c1,0x2164,0x4463,0x0000,0x5aeb,0x66a5,0x5d65},
+ {0x0000,0x2945,0x0000,0xb5d6,0x0000,0x736e,0x94b2,0x4a69,0x0000,0x0000,0x62ec,0x8410,0xad55,0x4208,0x0000,0x3186},
+};
+const uint8_t sprite_pal_a[][16] = {
+ {0,15,2,9,9,15,5,13,15,8,11,6,3,9,15,15},
+ {0,15,1,9,15,5,12,15,7,4,15,15,14,10,15,15},
+ {0,15,2,9,9,13,5,15,8,11,15,6,3,9,15,15},
+ {0,15,2,12,5,7,13,15,8,15,3,4,9,15,15,14},
+ {0,15,2,12,5,15,7,8,15,3,4,15,13,9,14,15},
+ {0,15,2,9,15,5,13,8,12,4,15,3,7,15,14,15},
+ {0,15,1,9,8,14,1,9,6,11,4,14,14,11,2,4},
+ {0,15,2,3,14,6,10,7,10,15,7,8,15,5,10,7},
+ {0,15,1,9,8,1,14,6,11,9,4,14,11,14,2,4},
+ {0,15,2,3,14,6,14,6,9,15,8,8,5,6,12,9},
+ {0,15,1,1,14,14,8,8,11,15,11,14,12,4,13,5},
+ {0,15,3,1,14,5,11,15,9,11,14,5,9,15,1,11},
+ {0,15,1,1,14,14,8,8,15,14,11,13,11,4,5,14},
+ {0,15,2,2,14,10,5,15,5,11,15,9,11,6,10,1},
+ {0,15,3,15,15,9,15,15,6,15,13,15,15,15,15,15},
+ {0,15,2,15,15,9,15,5,15,11,15,15,15,13,3,7},
+ {0,15,1,6,15,7,15,10,2,15,3,15,15,13,6,15},
+ {0,15,2,15,15,9,15,5,15,11,15,15,15,13,3,7},
+ {0,15,15,2,15,7,15,15,15,15,15,6,15,15,12,15},
+ {0,15,15,3,15,15,11,15,15,15,15,15,7,15,15,15},
+ {0,15,15,3,15,15,11,15,15,15,15,15,7,15,15,15},
+ {0,15,2,15,15,7,15,15,15,5,11,15,15,15,15,15},
+ {0,15,2,15,15,7,15,15,15,5,15,11,15,15,15,15},
+ {0,15,2,15,15,7,15,15,15,5,11,15,15,15,15,15},
+ {0,15,1,15,15,7,15,15,11,15,3,15,15,15,15,15},
+ {0,15,3,2,15,9,15,9,6,15,2,15,15,13,4,15},
+ {0,15,2,15,2,8,15,9,15,6,12,15,15,15,15,5},
+ {0,15,2,15,2,8,15,9,15,6,12,15,15,15,15,5},
+ {0,15,2,2,15,8,15,9,6,12,15,15,15,5,15,15},
+ {0,15,2,2,15,8,15,15,9,6,15,15,15,14,15,5},
+ {0,15,2,15,15,7,15,15,15,11,5,15,15,15,15,15},
+ {0,15,2,15,15,8,15,15,15,15,5,11,15,15,15,15},
+ {0,15,1,15,8,15,15,11,15,3,15,15,15,5,13,9},
+ {0,15,2,5,9,4,7,9,2,6,15,11,6,12,13,7},
+ {0,15,15,2,15,15,8,15,15,15,15,5,12,15,15,15},
+ {0,15,15,2,15,8,15,15,15,5,12,15,15,15,15,15},
+ {0,15,15,2,15,8,15,15,15,5,12,15,15,15,15,15},
+ {0,15,15,2,15,8,15,15,15,15,5,12,15,15,15,15},
+ {0,15,15,2,15,8,15,15,15,15,5,15,12,15,15,15},
+ {0,15,1,15,7,15,11,15,15,4,13,15,15,15,15,15},
+ {0,15,2,15,8,15,15,11,15,4,15,15,15,13,15,15},
+ {0,15,2,15,10,15,5,15,15,11,15,4,15,15,15,14},
+ {0,15,1,15,9,5,15,12,15,4,15,14,2,10,11,15},
+ {0,15,1,15,6,15,12,4,15,15,15,10,15,15,15,15},
+ {0,15,1,15,7,15,12,4,15,15,10,14,5,2,15,15},
+ {0,15,15,15,11,15,15,13,15,15,15,15,15,15,15,15},
+ {0,15,15,5,15,9,15,15,15,15,15,15,8,15,15,15},
+ {0,15,4,15,9,15,15,15,6,8,15,15,15,15,5,15},
+};
+static const uint8_t adv_small[] = {3,3,10,3,4,4,6,3,5,3,4,6,6,6,6,6,6,6,6,6,6,3,5,8,7,7,8,6,6,8,8,3,4,7,6,9,8,8,7,8,7,7,7,8,8,11,7,7,6};
+static const uint8_t adv_big[] = {4,6,26,5,8,8,8,6,8,6,8,14,9,13,14,15,14,14,14,14,14,6,9,17,15,12,14,11,10,13,14,7,12,15,10,18,14,15,14,16,15,11,13,14,14,21,15,13,14};
+static const uint8_t adv_huge[] = {6,9,39,8,12,12,13,9,12,9,12,21,14,20,22,22,21,21,21,21,21,8,14,25,22,18,21,17,16,20,21,10,19,23,15,26,22,23,21,24,22,17,19,20,22,31,23,20,22};
+const Font fonts[3] = {
+ {7,1,1,1,8,98,adv_small},
+ {13,1,1,2,9,147,adv_big},
+ {19,2,2,2,9,196,adv_huge},
+};
+const uint8_t font_charmap[96] = {0,1,255,255,255,2,255,3,4,5,255,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,255,255,255,255,22,255,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,255,255,255,255,255,255,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,255,255,255,255,255};
+const uint16_t bg_rects[BG_RECTS][4] = {{4,4,16,16},{28,4,64,16},{4,28,88,72},{4,108,88,64},{4,180,88,88},{4,276,88,104},{4,388,88,120},{100,4,120,88},{100,100,120,88},{100,196,72,16},{100,220,72,64},{180,196,40,16},{180,220,40,64},{100,292,40,40},{148,292,72,40},{100,340,120,168},{228,4,152,88},{228,100,152,56},{228,164,56,104},{292,164,88,104},{228,276,96,104},{332,276,48,56},{332,340,48,40},{228,388,152,120},{388,4,120,200},{388,212,120,48},{388,268,120,80},{388,356,120,88},{388,452,32,56},{428,452,80,56}};
+const uint8_t sprite_blob[] = {
+ 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,159,111,111,111,111,111,111,111,111,111,111,
+ 111,111,111,111,111,111,159,255,255,111,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,111,255,255,110,14,14,
+ 14,14,14,14,14,14,14,14,14,14,14,14,14,14,110,255,255,110,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+ 13,13,110,255,255,109,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,109,255,255,125,11,11,11,11,11,11,
+ 11,11,11,11,11,11,11,11,11,11,125,255,255,124,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,124,255,
+ 255,124,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,124,255,255,139,9,9,9,9,9,9,9,9,9,9,
+ 9,9,9,9,9,9,139,255,255,139,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,139,255,255,138,7,7,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,138,255,255,154,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
+ 6,6,154,255,255,153,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,153,255,255,169,5,5,5,5,5,5,
+ 5,5,5,5,5,5,5,5,5,5,169,255,255,168,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,168,255,
+ 255,184,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,184,255,255,199,2,2,2,2,2,2,2,2,2,2,
+ 2,2,2,2,2,2,199,255,255,234,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,234,255,255,255,255,255,
+ 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
+ 255,255,255,255,138,109,109,109,109,109,184,124,109,109,109,109,124,184,109,109,109,109,109,138,8,12,12,12,12,12,3,11,
+ 12,12,12,12,11,3,12,12,12,12,12,8,8,12,12,12,12,12,3,11,12,12,12,12,11,3,12,12,12,12,12,8,
+ 8,12,12,12,12,12,3,11,12,12,12,12,11,3,12,12,12,12,12,8,8,12,12,12,12,12,3,11,12,12,12,12,
+ 11,3,12,12,12,12,12,8,2,3,3,3,3,3,1,3,3,3,3,3,3,1,3,3,3,3,3,2,5,8,8,8,
+ 8,8,2,7,8,8,8,8,7,2,8,8,8,8,8,5,6,9,9,9,9,9,2,8,9,9,9,9,8,2,9,9,
+ 9,9,9,6,6,9,9,9,9,9,2,8,9,9,9,9,8,2,9,9,9,9,9,6,6,9,9,9,9,9,2,8,
+ 9,9,9,9,8,2,9,9,9,9,9,6,6,9,9,9,9,9,2,8,9,9,9,9,8,2,9,9,9,9,9,6,
+ 5,8,8,8,8,8,2,7,8,8,8,8,7,2,8,8,8,8,8,5,1,2,2,2,2,2,0,1,2,2,2,2,
+ 1,0,2,2,2,2,2,1,4,6,6,6,6,6,2,5,6,6,6,6,5,2,6,6,6,6,6,4,4,6,6,6,
+ 6,6,2,5,6,6,6,6,5,2,6,6,6,6,6,4,4,6,6,6,6,6,2,5,6,6,6,6,5,2,6,6,
+ 6,6,6,4,4,6,6,6,6,6,2,5,6,6,6,6,5,2,6,6,6,6,6,4,4,6,6,6,6,6,2,5,
+ 6,6,6,6,5,2,6,6,6,6,6,4,2,4,4,4,4,4,1,3,4,4,4,4,3,1,4,4,4,4,4,2,
+ 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,174,109,109,109,109,184,124,109,109,109,109,
+ 124,184,109,109,109,109,109,138,255,109,12,12,12,12,3,11,12,12,12,12,11,3,12,12,12,12,12,8,255,109,12,12,
+ 12,12,3,11,12,12,12,12,11,3,12,12,12,12,12,8,255,109,12,12,12,12,3,11,12,12,12,12,11,3,12,12,
+ 12,12,12,8,255,109,12,12,12,12,3,11,12,12,12,12,11,3,12,12,12,12,12,8,255,184,3,3,3,3,1,3,
+ 3,3,3,3,3,1,3,3,3,3,3,2,255,139,8,8,8,8,2,7,8,8,8,8,7,2,8,8,8,8,8,5,
+ 255,139,9,9,9,9,2,8,9,9,9,9,8,2,9,9,9,9,9,6,255,139,9,9,9,9,2,8,9,9,9,9,
+ 8,2,9,9,9,9,9,6,255,139,9,9,9,9,2,8,9,9,9,9,8,2,9,9,9,9,9,6,255,139,9,9,
+ 9,9,2,8,9,9,9,9,8,2,9,9,9,9,9,6,255,139,8,8,8,8,2,7,8,8,8,8,7,2,8,8,
+ 8,8,8,5,255,215,2,2,2,2,0,1,2,2,2,2,1,0,2,2,2,2,2,1,255,153,6,6,6,6,2,5,
+ 6,6,6,6,5,2,6,6,6,6,6,4,255,153,6,6,6,6,2,5,6,6,6,6,5,2,6,6,6,6,6,4,
+ 255,153,6,6,6,6,2,5,6,6,6,6,5,2,6,6,6,6,6,4,255,153,6,6,6,6,2,5,6,6,6,6,
+ 5,2,6,6,6,6,6,4,255,153,6,6,6,6,2,5,6,6,6,6,5,2,6,6,6,6,6,4,255,184,4,4,
+ 4,4,1,3,4,4,4,4,3,1,4,4,4,4,4,2,255,138,8,8,8,8,2,7,8,8,8,8,7,2,8,8,
+ 8,8,8,5,138,60,12,12,12,12,3,11,12,12,12,12,11,3,12,12,12,12,12,8,8,12,12,12,12,12,3,11,
+ 12,12,12,12,11,3,12,12,12,12,12,8,8,12,12,12,12,12,3,11,12,12,12,12,11,3,12,12,12,12,12,8,
+ 8,12,12,12,12,12,3,11,12,12,12,12,11,3,12,12,12,12,12,8,8,12,12,12,12,12,3,11,12,12,12,12,
+ 11,3,12,12,12,12,12,8,2,3,3,3,3,3,1,3,3,3,3,3,3,1,3,3,3,3,3,2,5,8,8,8,
+ 8,8,2,7,8,8,8,8,7,2,8,8,8,8,8,5,6,9,9,9,9,9,2,8,9,9,9,9,8,2,9,9,
+ 9,9,9,6,6,9,9,9,9,9,2,8,9,9,9,9,8,2,9,9,9,9,9,6,6,9,9,9,9,9,2,8,
+ 9,9,9,9,8,2,9,9,9,9,9,6,6,9,9,9,9,9,2,8,9,9,9,9,8,2,9,9,9,9,9,6,
+ 5,8,8,8,8,8,2,7,8,8,8,8,7,2,8,8,8,8,8,5,1,2,2,2,2,2,0,1,2,2,2,2,
+ 1,0,2,2,2,2,2,1,4,6,6,6,6,6,2,5,6,6,6,6,5,2,6,6,6,6,6,4,4,6,6,6,
+ 6,6,2,5,6,6,6,6,5,2,6,6,6,6,6,4,4,6,6,6,6,6,2,5,6,6,6,6,5,2,6,6,
+ 6,6,6,4,4,6,6,6,6,6,2,5,6,6,6,6,5,2,6,6,6,6,6,4,4,6,6,6,6,6,2,5,
+ 6,6,6,6,5,2,6,6,6,6,6,4,2,4,4,4,4,4,1,3,4,4,4,4,3,1,4,4,4,4,4,2,
+ 5,8,8,8,8,8,2,7,8,8,8,8,7,2,8,8,8,8,8,5,8,12,12,12,12,12,3,11,12,12,12,12,
+ 11,3,12,12,12,12,12,8,8,12,12,12,12,12,3,11,12,12,12,12,11,3,12,12,12,12,12,8,8,12,12,12,
+ 12,12,3,11,12,12,12,12,11,3,12,12,12,12,12,8,8,12,12,12,12,12,3,11,12,12,12,12,11,3,12,12,
+ 12,12,12,8,8,12,12,12,12,12,3,11,12,12,12,12,11,3,12,12,12,12,12,8,2,3,3,3,3,3,1,3,
+ 3,3,3,3,3,1,3,3,3,3,3,2,5,8,8,8,8,8,2,7,8,8,8,8,7,2,8,8,8,8,8,5,
+ 6,9,9,9,9,9,2,8,9,9,9,9,8,2,9,9,9,9,9,6,6,9,9,9,9,9,2,8,9,9,9,9,
+ 8,2,9,9,9,9,9,6,6,9,9,9,9,9,2,8,9,9,9,9,8,2,9,9,9,9,9,6,6,9,9,9,
+ 9,9,2,8,9,9,9,9,8,2,9,9,9,9,9,6,5,8,8,8,8,8,2,7,8,8,8,8,7,2,8,8,
+ 8,8,8,5,1,2,2,2,2,2,0,1,2,2,2,2,1,0,2,2,2,2,2,1,4,6,6,6,6,6,2,5,
+ 6,6,6,6,5,2,6,6,6,6,6,4,4,6,6,6,6,6,2,5,6,6,6,6,5,2,6,6,6,6,6,4,
+ 4,6,6,6,6,6,2,5,6,6,6,6,5,2,6,6,6,6,6,4,4,6,6,6,6,6,2,5,6,6,6,6,
+ 5,2,6,6,6,6,6,4,4,6,6,6,6,6,2,5,6,6,6,6,5,2,6,6,6,6,6,4,2,4,4,4,
+ 4,4,1,3,4,4,4,4,3,1,4,4,4,4,4,2,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
+ 255,255,255,255,255,174,109,109,109,109,184,124,109,109,109,109,124,184,109,109,109,109,174,255,255,109,12,12,12,12,3,11,
+ 12,12,12,12,11,3,12,12,12,12,109,255,255,109,12,12,12,12,3,11,12,12,12,12,11,3,12,12,12,12,109,255,
+ 255,109,12,12,12,12,3,11,12,12,12,12,11,3,12,12,12,12,109,255,255,109,12,12,12,12,3,11,12,12,12,12,
+ 11,3,12,12,12,12,109,255,255,184,3,3,3,3,1,3,3,3,3,3,3,1,3,3,3,3,184,255,255,139,8,8,
+ 8,8,2,7,8,8,8,8,7,2,8,8,8,8,139,255,255,139,9,9,9,9,2,8,9,9,9,9,8,2,9,9,
+ 9,9,139,255,255,139,9,9,9,9,2,8,9,9,9,9,8,2,9,9,9,9,139,255,255,139,9,9,9,9,2,8,
+ 9,9,9,9,8,2,9,9,9,9,139,255,255,139,9,9,9,9,2,8,9,9,9,9,8,2,9,9,9,9,139,255,
+ 255,139,8,8,8,8,2,7,8,8,8,8,7,2,8,8,8,8,139,255,255,215,2,2,2,2,0,1,2,2,2,2,
+ 1,0,2,2,2,2,215,255,255,153,6,6,6,6,2,5,6,6,6,6,5,2,6,6,6,6,153,255,255,153,6,6,
+ 6,6,2,5,6,6,6,6,5,2,6,6,6,6,153,255,255,153,6,6,6,6,2,5,6,6,6,6,5,2,6,6,
+ 6,6,153,255,255,153,6,6,6,6,2,5,6,6,6,6,5,2,6,6,6,6,153,255,255,153,6,6,6,6,2,5,
+ 6,6,6,6,5,2,6,6,6,6,153,255,255,184,4,4,4,4,1,3,4,4,4,4,3,1,4,4,4,4,184,255,
+ 255,138,8,8,8,8,2,7,8,8,8,8,7,2,8,8,8,8,138,255,255,109,12,12,12,12,3,11,12,12,12,12,
+ 11,3,12,12,12,12,109,255,255,109,12,12,12,12,3,11,12,12,12,12,11,3,12,12,12,12,109,255,255,109,12,12,
+ 12,12,3,11,12,12,12,12,11,3,12,12,12,12,109,255,255,109,12,12,12,12,3,11,12,12,12,12,11,3,12,12,
+ 12,12,109,255,255,109,12,12,12,12,3,11,12,12,12,12,11,3,12,12,12,12,109,255,255,184,3,3,3,3,1,3,
+ 3,3,3,3,3,1,3,3,3,3,184,255,255,139,8,8,8,8,2,7,8,8,8,8,7,2,8,8,8,8,139,255,
+ 255,139,9,9,9,9,2,8,9,9,9,9,8,2,9,9,9,9,139,255,255,139,9,9,9,9,2,8,9,9,9,9,
+ 8,2,9,9,9,9,139,255,255,139,9,9,9,9,2,8,9,9,9,9,8,2,9,9,9,9,139,255,255,139,9,9,
+ 9,9,2,8,9,9,9,9,8,2,9,9,9,9,139,255,255,139,8,8,8,8,2,7,8,8,8,8,7,2,8,8,
+ 8,8,139,255,255,215,2,2,2,2,0,1,2,2,2,2,1,0,2,2,2,2,215,255,255,153,6,6,6,6,2,5,
+ 6,6,6,6,5,2,6,6,6,6,153,255,255,153,6,6,6,6,2,5,6,6,6,6,5,2,6,6,6,6,153,255,
+ 255,153,6,6,6,6,2,5,6,6,6,6,5,2,6,6,6,6,153,255,255,153,6,6,6,6,2,5,6,6,6,6,
+ 5,2,6,6,6,6,153,255,255,153,6,6,6,6,2,5,6,6,6,6,5,2,6,6,6,6,153,255,255,184,4,4,
+ 4,4,1,3,4,4,4,4,3,1,4,4,4,4,184,255,16,34,34,34,34,34,34,34,34,34,34,34,1,33,68,68,
+ 68,68,68,68,68,68,68,68,68,18,66,118,119,119,119,119,119,119,119,119,119,103,36,66,119,119,119,119,119,119,119,119,
+ 119,119,119,36,66,119,68,68,68,68,68,68,68,68,68,119,36,66,119,36,34,34,34,34,34,34,34,66,119,36,66,119,
+ 36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,
+ 0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,
+ 119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,
+ 0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,
+ 66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,
+ 0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,34,34,34,34,34,34,34,66,119,
+ 36,66,119,68,68,68,68,68,68,68,68,68,119,36,66,119,119,119,119,119,119,119,119,119,119,119,36,66,118,119,119,119,
+ 119,119,119,119,119,119,103,36,33,68,68,68,68,68,68,68,68,68,68,68,18,16,34,34,34,34,34,34,34,34,34,34,
+ 34,1,34,34,34,34,34,34,34,34,34,34,68,68,68,68,68,68,68,68,68,68,119,119,119,119,119,119,119,119,119,119,
+ 119,119,119,119,119,119,119,119,119,119,68,68,68,68,68,68,68,68,68,68,34,34,34,34,34,34,34,34,34,34,16,34,
+ 34,34,34,34,34,34,34,34,34,2,33,68,68,68,68,68,68,68,68,68,68,4,66,118,119,119,119,119,119,119,119,119,
+ 119,7,66,119,119,119,119,119,119,119,119,119,119,7,66,119,68,68,68,68,68,68,68,68,68,4,66,119,36,34,34,34,
+ 34,34,34,34,34,2,66,119,36,0,0,0,0,0,0,0,0,0,66,119,36,0,0,0,0,0,0,0,0,0,66,119,
+ 36,0,0,0,0,0,0,0,0,0,66,119,36,0,0,0,0,0,0,0,0,0,66,119,36,0,0,0,0,0,0,0,
+ 0,0,66,119,36,0,0,0,0,0,0,0,0,0,66,119,36,0,0,0,0,0,0,0,0,0,66,119,36,0,0,0,
+ 0,0,0,0,0,0,66,119,36,0,0,0,0,0,0,0,0,0,66,119,36,0,0,0,0,0,0,0,0,0,66,119,
+ 36,0,0,0,0,0,0,0,0,0,66,119,36,0,0,0,0,0,0,0,0,0,66,119,36,0,0,0,0,0,0,0,
+ 0,0,66,119,36,0,0,0,0,0,0,0,0,0,66,119,36,0,0,0,0,0,0,0,0,0,66,119,36,0,0,0,
+ 0,0,0,0,0,0,66,119,36,0,0,0,0,0,0,0,0,0,0,17,0,32,51,2,49,85,19,49,85,19,32,51,
+ 2,0,17,0,16,34,34,34,34,34,34,34,34,34,34,34,1,33,68,68,68,68,68,68,68,68,68,68,68,18,66,118,
+ 119,119,119,119,119,119,119,119,119,103,36,66,119,119,119,119,119,119,119,119,119,119,119,36,66,119,68,68,68,68,68,68,
+ 68,68,68,119,36,66,119,36,34,34,34,34,34,34,34,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,
+ 119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,
+ 0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,
+ 66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,
+ 0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,
+ 36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,
+ 0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,
+ 119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,
+ 0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,
+ 66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,
+ 0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,
+ 0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,
+ 36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,
+ 0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,
+ 119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,66,119,36,0,0,0,0,
+ 0,0,0,66,119,36,66,119,36,0,0,0,0,0,0,0,66,119,36,0,0,0,0,0,0,0,0,0,243,245,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,250,252,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,243,239,223,245,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,250,127,111,252,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,243,239,15,15,223,245,0,0,0,0,0,0,0,0,0,0,0,0,0,0,250,127,
+ 15,15,111,252,0,0,0,0,0,0,0,0,0,0,0,0,0,243,239,15,15,15,15,223,245,0,0,0,0,0,0,0,
+ 0,0,0,0,0,250,127,15,15,15,15,111,252,0,0,0,0,0,0,0,0,0,0,0,243,239,15,15,15,15,15,15,
+ 223,245,0,0,0,0,0,0,0,0,0,0,250,127,15,15,15,15,15,15,111,252,0,0,0,0,0,0,0,0,0,243,
+ 239,30,14,14,14,14,14,14,14,223,245,0,0,0,0,0,0,0,0,250,109,13,13,13,13,13,13,13,13,109,252,0,
+ 0,0,0,0,0,0,243,222,12,12,12,12,12,12,12,12,12,12,222,245,0,0,0,0,0,0,250,124,11,11,11,11,
+ 11,11,11,11,11,11,124,252,0,0,0,0,0,243,238,10,10,10,10,10,10,10,10,10,10,10,10,238,245,0,0,0,
+ 0,250,139,9,9,9,9,9,9,9,9,9,9,9,9,139,252,0,0,0,243,238,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,238,245,0,0,250,154,7,7,7,7,7,7,7,7,7,7,7,7,7,7,154,252,0,243,238,22,6,6,
+ 6,6,6,6,6,6,6,6,6,6,6,6,22,238,245,250,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
+ 255,255,252,0,0,0,0,0,0,0,0,0,244,245,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,245,
+ 254,239,246,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,245,239,79,79,239,247,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,247,239,79,15,15,47,239,248,0,0,0,0,0,0,0,0,0,0,0,247,239,47,15,15,15,15,47,
+ 223,248,0,0,0,0,0,0,0,0,0,248,223,45,13,13,13,13,13,13,45,223,250,240,0,0,0,0,0,240,248,222,
+ 43,11,11,11,11,11,11,11,11,27,206,250,240,0,0,0,240,250,221,25,9,9,9,9,9,9,9,9,9,9,25,205,
+ 251,241,0,241,250,238,154,138,138,138,138,138,138,138,138,138,138,138,138,154,238,251,241,248,251,251,251,251,251,251,251,251,
+ 251,251,251,251,251,251,251,251,251,251,249,0,0,0,0,0,0,240,241,0,0,0,0,0,0,0,0,0,0,0,0,247,
+ 248,0,0,0,0,0,0,0,0,0,0,0,241,254,255,241,0,0,0,0,0,0,0,0,0,0,248,175,143,249,0,0,
+ 0,0,0,0,0,0,0,241,254,63,31,255,242,0,0,0,0,0,0,0,0,248,159,15,15,143,250,0,0,0,0,0,
+ 0,0,242,255,47,15,15,31,239,243,0,0,0,0,0,0,249,158,13,13,13,13,142,250,0,0,0,0,0,243,239,44,
+ 12,12,12,12,28,239,244,0,0,0,0,251,157,10,10,10,10,10,10,140,251,0,0,0,244,238,41,9,9,9,9,9,
+ 9,25,238,244,0,0,252,155,7,7,7,7,7,7,7,7,155,252,0,245,255,204,204,204,204,204,204,204,204,204,204,255,
+ 245,244,246,246,246,246,246,246,246,246,246,246,246,246,244,0,0,0,0,0,16,17,1,0,0,0,0,0,0,0,0,0,
+ 0,33,51,18,0,0,0,0,0,0,0,0,0,0,50,85,35,0,0,0,0,0,0,0,0,0,16,66,119,36,1,0,
+ 0,0,0,0,0,0,0,32,99,119,54,2,0,0,0,0,0,0,0,0,33,116,102,71,18,0,0,0,0,0,0,0,
+ 0,50,118,68,103,35,0,0,0,0,0,0,0,16,66,103,51,118,36,1,0,0,0,0,0,0,32,99,71,34,116,54,
+ 2,0,0,0,0,0,0,33,116,54,34,99,71,18,0,0,0,0,0,0,50,118,36,17,66,103,35,0,0,0,0,0,
+ 16,66,103,35,0,50,118,36,1,0,0,0,0,32,99,71,18,0,33,116,54,2,0,0,0,0,33,116,54,2,0,32,
+ 99,71,18,0,0,0,0,50,118,36,1,0,16,66,103,35,0,0,0,16,66,103,35,0,0,0,50,118,36,1,0,0,
+ 32,99,71,18,0,0,0,33,116,54,2,0,0,33,116,54,2,0,0,0,32,99,71,18,0,0,50,118,36,1,0,0,
+ 0,16,66,103,35,0,16,66,103,35,0,0,0,0,0,50,118,36,1,32,99,71,18,0,0,0,0,0,33,116,54,2,
+ 33,116,54,18,17,17,17,17,17,33,99,71,18,49,118,52,34,34,34,34,34,34,34,67,103,19,49,85,35,34,34,34,
+ 34,34,34,34,50,85,19,33,51,18,17,17,17,17,17,17,17,33,51,18,16,17,1,0,0,0,0,0,0,0,16,17,
+ 1,0,0,0,0,0,16,17,1,0,0,0,0,0,0,0,0,0,0,33,51,18,0,0,0,0,0,0,0,0,0,16,
+ 50,85,35,1,0,0,0,0,0,0,0,0,33,83,119,53,18,0,0,0,0,0,0,0,16,50,117,102,87,35,1,0,
+ 0,0,0,0,0,33,84,103,68,118,69,18,0,0,0,0,0,16,66,117,70,51,100,87,36,1,0,0,0,0,33,100,
+ 103,36,17,66,118,70,18,0,0,0,16,66,118,70,18,0,33,100,103,36,1,0,0,49,100,87,36,1,0,16,66,117,
+ 70,19,0,16,67,118,69,18,0,0,0,33,84,103,52,1,49,100,87,35,17,17,17,17,17,50,117,70,19,50,118,53,
+ 51,51,51,51,51,51,51,83,103,35,49,85,35,34,34,34,34,34,34,34,50,85,19,33,51,18,0,0,0,0,0,0,
+ 0,33,51,18,16,17,1,0,0,0,0,0,0,0,16,17,1,0,0,0,0,16,1,0,0,0,0,0,0,0,0,33,
+ 18,0,0,0,0,0,0,0,16,67,52,1,0,0,0,0,0,0,33,100,70,18,0,0,0,0,0,0,49,117,87,19,
+ 0,0,0,0,0,16,66,102,102,36,1,0,0,0,0,16,83,87,117,53,1,0,0,0,0,33,100,70,100,70,18,0,
+ 0,0,0,49,117,53,83,87,19,0,0,0,16,66,102,36,66,102,36,1,0,0,16,83,87,19,49,117,53,1,0,0,
+ 33,100,70,18,33,100,70,18,0,0,50,117,53,1,16,83,87,35,0,16,66,103,36,1,16,66,118,36,1,32,99,87,
+ 19,0,0,49,117,54,2,33,116,54,34,34,34,34,99,71,18,49,101,52,51,51,51,51,67,86,19,33,68,35,17,17,
+ 17,17,50,68,18,16,34,18,0,0,0,0,33,34,1,0,17,0,0,0,0,0,0,17,0,0,80,0,2,0,0,0,
+ 0,4,0,0,160,1,8,0,0,0,0,8,0,0,208,36,14,0,0,0,0,13,0,32,241,103,47,0,48,4,48,15,
+ 5,168,244,170,95,48,192,9,82,63,92,255,248,236,143,246,250,31,139,143,191,255,255,255,191,253,255,191,223,255,255,255,
+ 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
+ 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,238,238,238,238,238,238,238,238,238,238,187,187,187,187,187,
+ 187,187,187,187,187,136,136,136,136,136,136,136,136,136,136,85,85,85,85,85,85,85,85,85,85,34,34,34,34,34,34,34,
+ 34,34,34,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,128,0,0,112,0,0,0,0,0,0,192,0,
+ 0,179,0,0,0,3,0,16,224,2,0,231,32,0,16,12,19,130,241,20,3,250,163,51,102,47,87,214,243,118,42,254,
+ 247,137,188,127,156,251,247,200,127,255,254,222,255,207,223,255,254,253,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
+ 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
+ 255,255,255,255,255,238,238,238,238,238,238,238,238,238,238,187,187,187,187,187,187,187,187,187,187,136,136,136,136,136,136,136,
+ 136,136,136,85,85,85,85,85,85,85,85,85,85,34,34,34,34,34,34,34,34,34,34,0,0,5,0,0,0,16,3,0,
+ 16,0,16,9,0,0,0,64,6,0,48,0,64,12,0,0,0,96,8,0,80,0,112,14,0,0,0,128,11,0,112,0,
+ 160,31,3,33,0,160,14,1,144,147,192,79,12,150,128,192,63,7,178,255,250,143,79,251,248,229,191,92,217,255,255,239,
+ 175,255,255,254,255,191,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
+ 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,238,238,238,238,238,238,238,
+ 238,238,238,187,187,187,187,187,187,187,187,187,187,136,136,136,136,136,136,136,136,136,136,85,85,85,85,85,85,85,85,85,
+ 85,34,34,34,34,34,34,34,34,34,34,249,249,249,249,249,249,249,249,249,249,249,249,249,249,249,249,249,249,249,249,255,
+ 207,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,207,255,255,110,13,13,13,13,13,13,13,13,13,13,13,
+ 13,13,13,13,13,110,255,255,125,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,125,255,255,124,10,10,10,
+ 10,10,10,10,10,10,10,10,10,10,10,10,10,124,255,255,139,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,139,255,255,154,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,154,255,255,153,5,5,5,5,5,5,5,
+ 5,5,5,5,5,5,5,5,5,153,255,255,236,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,236,255,249,
+ 249,249,249,249,249,249,249,249,249,249,249,249,249,249,249,249,249,249,249,16,34,34,34,34,34,34,34,34,34,34,34,1,
+ 49,85,85,85,85,85,85,85,85,85,85,85,19,49,118,119,119,119,119,119,119,119,119,119,103,19,49,102,68,68,68,68,
+ 68,68,68,68,68,102,19,49,102,35,34,34,34,34,34,34,34,50,102,19,49,102,19,0,0,0,0,0,0,0,49,102,
+ 19,49,102,19,0,0,0,0,0,0,0,49,102,19,49,102,19,0,0,0,0,0,0,0,49,102,19,49,102,19,0,0,
+ 0,0,0,0,0,49,102,19,49,102,35,34,34,34,34,34,34,34,50,102,19,49,102,68,68,68,68,68,68,68,68,68,
+ 102,19,49,118,119,119,119,119,119,119,119,119,119,103,19,49,85,85,85,85,85,85,85,85,85,85,85,19,16,34,34,34,
+ 34,34,34,34,34,34,34,34,1,246,246,246,246,246,246,246,246,246,246,246,246,246,246,246,246,246,246,246,246,255,255,255,
+ 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
+ 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
+ 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
+ 15,10,13,15,15,15,15,15,15,13,10,10,13,15,15,15,15,15,15,13,10,8,8,10,14,15,15,14,10,8,8,8,
+ 8,10,14,15,15,14,10,8,8,0,3,7,8,10,10,8,7,3,0,0,3,7,8,10,10,8,7,3,0,0,0,0,
+ 5,8,8,5,0,0,0,0,0,0,5,8,8,5,0,0,0,246,246,246,246,246,246,246,246,246,246,246,246,246,246,246,
+ 246,246,246,246,246,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,15,15,15,15,15,15,15,
+ 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
+ 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
+ 15,15,15,15,15,15,15,15,15,15,15,15,15,13,11,11,11,12,14,15,15,15,15,15,15,15,14,12,11,15,15,12,
+ 9,8,8,8,8,8,8,11,14,15,15,15,13,10,8,8,8,13,9,8,6,3,1,0,0,2,5,8,8,12,14,10,
+ 8,7,4,1,0,8,6,2,0,0,0,0,0,0,0,1,5,8,8,7,3,0,0,0,0,3,0,0,0,0,0,0,
+ 0,0,0,0,0,1,4,0,0,0,0,0,0,246,246,246,246,246,246,246,246,246,246,246,246,246,246,246,246,246,246,246,
+ 246,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,15,15,15,15,15,15,15,15,15,15,15,
+ 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
+ 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,13,14,15,15,15,15,15,15,15,
+ 14,13,14,15,15,15,15,15,15,12,9,8,8,11,15,15,15,15,15,12,9,8,8,11,15,13,15,14,10,8,5,3,
+ 4,8,9,13,15,14,10,8,5,3,4,8,9,8,8,8,7,2,0,0,0,1,6,8,8,8,7,2,0,0,0,1,
+ 6,3,5,4,1,0,0,0,0,0,0,3,5,4,1,0,0,0,0,0,0,246,246,246,246,246,246,246,246,246,246,246,
+ 246,246,246,246,246,246,246,246,246,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,15,15,15,
+ 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
+ 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
+ 15,15,15,15,15,15,15,15,15,15,15,15,15,8,9,10,12,14,15,15,15,15,15,15,15,15,15,15,14,12,10,9,
+ 8,6,6,8,8,8,10,13,15,15,15,15,15,15,13,10,8,8,8,6,6,0,0,0,2,5,8,8,10,14,15,15,
+ 14,10,8,8,5,2,0,0,0,0,0,0,0,0,0,4,7,8,11,11,8,7,4,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,4,8,8,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,
+ 0,0,0,0,0,0,17,0,0,68,0,16,102,1,16,119,1,0,51,0,16,136,1,16,136,1,16,136,1,0,51,0,
+ 16,153,1,16,153,1,16,102,1,16,102,1,16,170,1,16,187,1,16,68,1,16,187,1,16,204,1,32,204,2,16,85,
+ 1,32,221,2,32,221,2,16,136,1,16,153,1,32,238,2,129,255,24,242,255,47,0,68,0,16,68,1,16,85,1,16,
+ 136,1,16,136,1,0,51,0,16,153,1,16,170,1,16,170,1,16,68,1,16,187,1,32,204,2,16,136,1,16,136,1,
+ 32,238,2,129,255,24,242,255,47,16,119,1,16,136,1,16,170,1,16,68,1,16,204,1,48,221,3,242,255,47,97,102,
+ 22,0,0,0,98,185,155,38,0,0,0,0,0,146,255,255,255,255,41,0,0,0,64,254,255,255,255,255,239,4,0,0,
+ 244,255,255,255,255,255,255,79,0,32,254,255,255,255,255,255,255,239,2,144,255,255,255,255,255,255,255,255,9,242,255,255,
+ 255,255,255,255,255,255,47,246,255,255,255,255,255,255,255,255,111,249,255,255,255,255,255,255,255,255,159,251,255,255,255,255,
+ 255,255,255,255,191,251,255,255,255,255,255,255,255,255,191,249,255,255,255,255,255,255,255,255,159,246,255,255,255,255,255,255,
+ 255,255,111,242,255,255,255,255,255,255,255,255,47,144,255,255,255,255,255,255,255,255,9,32,254,255,255,255,255,255,255,239,
+ 2,0,244,255,255,255,255,255,255,79,0,0,64,254,255,255,255,255,239,4,0,0,0,146,255,255,255,255,41,0,0,0,
+ 0,0,98,185,155,38,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,80,0,0,0,0,0,0,0,0,0,0,112,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,112,2,0,0,0,0,0,0,0,0,0,145,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,38,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,144,6,0,0,0,0,
+ 0,0,0,0,0,148,0,0,0,0,0,0,0,0,0,0,0,0,0,0,41,0,7,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,160,9,0,0,0,0,0,0,0,0,0,150,0,0,0,0,0,0,0,0,0,0,0,0,0,0,59,0,
+ 10,0,0,0,0,0,0,0,0,0,0,0,0,0,176,12,0,0,0,0,0,0,0,0,0,169,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,77,0,29,0,0,0,0,0,0,0,0,0,0,0,0,0,192,45,0,0,0,0,0,0,
+ 0,0,0,171,0,0,0,0,0,0,0,0,0,0,0,0,0,32,93,16,61,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,208,77,0,0,0,0,0,0,0,0,0,173,0,0,0,0,0,0,0,0,0,0,0,0,0,80,109,32,93,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,209,125,0,0,0,0,0,0,0,0,32,189,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,112,108,48,140,0,0,0,32,5,0,0,0,0,0,0,0,0,194,172,0,0,0,0,0,0,0,0,
+ 80,188,0,0,0,0,0,0,0,0,0,0,0,0,0,144,124,64,172,0,0,0,80,10,0,0,0,0,0,0,0,0,
+ 195,204,1,0,0,0,0,0,0,0,112,172,0,0,0,0,0,0,0,0,0,0,0,0,0,176,139,80,187,1,0,0,
+ 112,91,0,0,0,0,0,0,0,0,180,187,4,0,0,0,0,0,0,0,144,187,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,178,139,80,187,3,0,0,160,171,1,0,0,0,0,0,0,0,180,187,6,0,0,0,0,0,0,0,160,187,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,179,155,96,187,5,0,0,178,187,6,0,0,0,0,0,80,1,181,187,
+ 9,0,0,0,0,0,0,0,177,187,16,0,0,0,0,0,0,0,0,0,0,0,0,165,154,112,170,7,0,0,165,170,
+ 26,0,0,0,0,0,163,3,166,170,10,0,0,0,0,0,0,0,163,170,81,0,0,0,0,0,0,0,0,0,0,0,
+ 0,167,170,112,170,9,0,0,167,170,122,0,0,0,0,16,169,5,166,170,58,0,0,0,0,0,0,0,165,170,113,0,
+ 0,0,0,0,0,0,0,0,0,0,0,153,153,128,153,25,0,0,153,153,153,2,0,0,0,112,153,7,151,153,89,0,
+ 0,0,0,1,0,0,150,153,129,2,0,1,0,0,0,0,0,0,0,0,16,153,153,129,153,57,0,48,153,153,153,7,
+ 0,0,0,149,153,8,152,153,121,0,0,0,32,7,0,0,152,153,146,3,0,72,0,0,0,0,0,0,0,0,48,136,
+ 136,129,136,72,0,80,136,136,136,56,0,0,48,136,136,24,136,136,136,0,0,0,112,72,0,0,136,136,131,5,48,136,
+ 22,0,0,0,0,0,0,0,64,136,136,130,136,104,0,112,136,136,136,120,0,0,129,136,136,40,136,136,136,2,0,0,
+ 132,136,1,32,136,136,131,6,80,136,136,3,0,0,0,0,0,0,80,136,136,131,136,120,0,129,136,136,136,136,3,0,
+ 134,136,136,88,136,136,136,4,0,16,135,136,5,48,136,136,132,7,112,136,136,88,0,0,0,0,0,0,96,119,119,116,
+ 119,119,1,115,119,119,119,119,7,80,119,119,119,103,119,119,119,5,0,96,119,119,39,64,119,119,117,23,114,119,119,119,
+ 22,0,0,0,0,0,112,119,119,117,119,119,2,116,119,119,119,119,71,115,119,119,119,119,119,119,119,6,0,115,119,119,
+ 103,80,119,119,117,55,115,119,119,119,103,3,0,0,0,0,97,102,102,101,102,102,3,102,102,102,102,102,102,102,102,102,
+ 102,102,102,102,102,22,16,102,102,102,102,99,102,102,102,70,101,102,102,102,102,70,1,0,0,0,98,102,102,102,102,102,
+ 20,102,102,102,102,102,102,102,102,102,102,102,102,102,102,38,64,102,102,102,102,102,102,102,102,86,102,102,102,102,102,102,
+ 37,0,0,0,83,85,85,85,85,85,37,85,85,85,85,85,85,85,85,85,85,85,85,85,85,53,81,85,85,85,85,85,
+ 85,85,85,85,85,85,85,85,85,85,85,3,0,0,67,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,
+ 68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,52,1,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,52,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,87,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,137,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,171,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,
+ 0,0,189,0,0,0,0,0,0,0,0,16,18,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,12,0,32,221,0,0,0,0,0,0,0,0,64,51,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,61,0,64,221,2,0,0,0,0,0,0,0,80,51,204,4,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,32,92,0,96,204,4,0,0,1,0,0,0,0,112,68,204,92,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,145,3,48,124,0,112,204,6,0,16,4,0,0,0,0,144,68,187,187,5,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,48,186,5,64,155,0,144,187,8,0,48,4,0,0,0,0,160,85,187,187,107,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,181,187,6,80,187,0,160,187,9,0,96,4,0,0,0,0,177,85,187,
+ 187,187,7,0,0,0,0,0,0,0,0,0,0,0,0,112,187,187,8,96,187,2,177,187,11,0,144,5,0,0,0,0,
+ 163,101,170,170,170,122,0,0,0,0,0,0,0,0,0,0,0,32,169,170,170,9,112,170,4,163,170,42,0,161,5,0,
+ 0,0,0,164,102,170,170,170,170,23,0,0,0,0,0,0,0,0,0,0,147,170,170,170,26,128,170,6,164,170,74,0,
+ 164,5,0,0,0,0,150,118,153,153,153,153,137,1,0,0,0,0,0,0,0,0,80,153,153,153,153,41,144,153,8,150,
+ 153,89,0,150,23,0,0,0,0,151,118,153,153,153,153,153,24,0,0,0,0,0,0,0,16,151,153,153,153,153,57,144,
+ 153,9,151,153,105,0,152,86,0,0,0,0,136,118,136,136,136,136,136,136,2,0,0,0,0,0,0,114,136,136,136,136,
+ 136,72,129,136,40,136,136,120,32,136,135,1,0,0,16,136,118,136,136,136,136,136,136,39,0,0,0,0,0,64,135,136,
+ 136,136,136,136,88,130,136,72,136,136,136,64,136,135,5,0,0,32,119,118,119,119,119,119,119,119,119,3,0,0,0,0,
+ 117,119,119,119,119,119,119,103,115,119,119,119,119,119,97,119,119,23,0,0,48,119,118,119,119,119,119,119,119,119,55,0,
+ 0,0,97,119,119,119,119,119,119,119,119,116,119,119,119,119,119,115,119,119,87,0,0,64,102,102,102,102,102,102,102,102,
+ 102,102,3,0,32,102,102,102,102,102,102,102,102,102,101,102,102,102,102,102,101,102,102,102,1,0,64,85,85,85,85,85,
+ 85,85,85,85,85,53,0,83,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,4,16,83,85,85,
+ 85,85,85,85,85,85,85,85,85,67,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,21,17,
+ 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
+ 17,17,0,2,0,0,0,0,0,0,0,0,0,0,0,112,3,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,
+ 0,0,0,0,0,0,112,94,0,0,0,0,0,0,0,0,0,43,0,0,0,0,0,0,0,0,0,0,0,128,238,4,
+ 0,0,0,0,0,0,0,0,92,0,0,0,0,0,0,0,0,0,0,0,128,221,109,0,0,0,0,0,0,0,16,141,
+ 0,0,0,0,0,0,0,0,0,0,0,128,221,221,6,0,0,0,0,0,0,32,172,0,0,0,0,0,16,6,0,0,
+ 64,1,128,204,204,108,0,0,0,0,0,0,64,204,1,0,0,0,0,80,10,0,0,144,2,112,204,204,204,7,0,0,
+ 0,0,0,80,187,3,0,0,0,0,128,59,0,0,177,4,112,187,187,187,107,0,0,0,0,0,96,170,6,0,0,6,
+ 0,160,122,0,0,166,5,128,170,170,170,170,7,0,0,0,0,128,170,8,0,64,26,0,164,170,1,0,169,6,114,170,
+ 170,170,170,122,0,0,0,0,128,153,9,0,128,89,0,150,153,4,48,153,7,117,153,153,153,153,153,7,0,0,0,144,
+ 153,41,0,147,137,1,152,153,7,96,153,7,103,153,153,153,153,153,121,0,0,0,129,136,72,0,134,136,36,136,136,40,
+ 129,136,24,104,136,136,136,136,136,136,23,0,0,114,119,87,16,119,119,87,119,119,71,116,119,55,119,119,119,119,119,119,
+ 119,103,1,0,115,119,103,64,119,119,119,119,119,103,118,119,87,119,119,119,119,119,119,119,119,22,0,99,102,102,98,102,
+ 102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,86,1,84,85,85,84,85,85,85,85,85,85,85,85,85,85,
+ 85,85,85,85,85,85,85,85,21,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51,
+ 0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,112,0,0,0,0,0,0,0,0,0,0,0,0,0,116,2,
+ 0,32,1,0,0,0,0,0,0,0,0,48,135,83,1,144,138,37,0,0,0,0,0,0,0,96,136,116,5,148,153,153,
+ 104,19,0,0,0,0,0,113,119,118,23,119,119,119,119,119,70,2,0,0,0,99,102,102,86,102,102,102,102,102,102,86,
+ 36,1,0,33,34,34,34,34,34,34,34,34,34,34,34,18,0,64,204,4,0,0,176,68,11,0,0,179,0,59,0,0,
+ 149,0,89,0,0,134,0,104,0,0,134,0,104,0,0,165,0,90,0,0,194,17,44,0,0,160,238,10,0,0,176,221,
+ 11,0,0,194,0,44,0,0,165,0,90,0,0,134,0,104,0,0,134,0,104,0,0,149,0,89,0,0,195,0,60,0,
+ 0,176,187,11,0,0,144,238,9,0,0,193,34,28,0,0,164,0,74,0,0,134,0,104,0,0,134,0,104,0,0,150,
+ 0,105,0,0,179,0,59,0,0,192,119,12,0,0,144,238,9,0,0,193,102,28,0,0,180,0,75,0,0,150,0,105,
+ 0,0,134,0,104,0,0,134,0,104,0,0,164,0,74,0,0,193,68,28,0,0,144,238,9,0,0,192,170,12,0,0,
+ 195,0,60,0,0,149,0,89,0,0,134,0,104,0,0,134,0,104,0,0,164,0,74,0,0,194,0,44,0,0,160,136,
+ 10,0,0,96,255,6,0,0,241,102,31,0,0,228,0,78,0,184,251,204,191,139,251,255,255,255,191,100,102,102,102,70,
+ 0,64,204,4,0,0,176,68,11,0,0,194,0,44,0,0,149,0,89,0,0,134,0,104,0,0,134,0,104,0,0,149,
+ 0,89,0,0,195,0,60,0,0,176,153,11,0,0,144,238,9,0,0,193,68,28,0,0,180,0,75,0,0,150,0,105,
+ 0,0,134,0,104,0,0,134,0,104,0,0,164,0,74,0,0,194,0,44,0,0,160,102,10,0,0,96,255,6,0,0,
+ 241,102,31,0,0,228,0,78,0,184,251,204,191,139,251,255,255,255,191,100,102,102,102,70,0,0,0,0,49,0,0,0,
+ 0,0,0,0,0,135,0,0,0,0,0,0,0,0,237,0,0,0,0,0,0,0,64,255,4,0,0,0,0,0,0,144,
+ 255,10,0,0,0,0,0,0,241,255,31,0,0,0,68,101,135,250,255,175,120,86,68,228,255,255,255,255,255,255,255,78,
+ 32,252,255,255,255,255,255,207,2,0,144,255,255,255,255,255,9,0,0,0,246,255,255,255,111,0,0,0,0,241,255,255,
+ 255,31,0,0,0,0,244,255,255,255,79,0,0,0,0,248,255,238,255,143,0,0,0,0,252,191,18,250,207,0,0,0,
+ 16,239,5,0,80,253,1,0,0,80,25,0,0,0,145,5,0,0,16,0,0,0,0,0,1,0,10,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,6,13,10,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 6,5,13,13,10,8,8,8,8,8,8,8,8,8,8,8,8,8,8,6,5,5,13,13,13,10,8,8,8,8,8,8,
+ 8,8,8,8,8,8,6,5,5,5,13,13,13,13,10,8,8,8,8,8,8,8,8,8,8,6,5,5,5,5,13,13,
+ 13,13,13,10,8,8,8,8,8,8,8,8,6,5,5,5,5,5,13,13,13,13,13,13,10,8,8,8,8,8,8,6,
+ 5,5,5,5,5,5,13,13,13,13,13,13,13,10,8,8,8,8,6,5,5,5,5,5,5,5,13,13,13,13,13,13,
+ 13,13,10,8,8,6,5,5,5,5,5,5,5,5,13,13,13,13,13,13,13,13,13,10,6,5,5,5,5,5,5,5,
+ 5,5,13,13,13,13,13,13,13,13,13,7,4,5,5,5,5,5,5,5,5,5,13,13,13,13,13,13,13,13,7,3,
+ 3,4,5,5,5,5,5,5,5,5,13,13,13,13,13,13,13,7,3,3,3,3,4,5,5,5,5,5,5,5,13,13,
+ 13,13,13,13,7,3,3,3,3,3,3,4,5,5,5,5,5,5,13,13,13,13,13,7,3,3,3,3,3,3,3,3,
+ 4,5,5,5,5,5,13,13,13,13,7,3,3,3,3,3,3,3,3,3,3,4,5,5,5,5,13,13,13,7,3,3,
+ 3,3,3,3,3,3,3,3,3,3,4,5,5,5,13,13,7,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,
+ 5,5,13,7,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,5,7,3,3,3,3,3,3,3,3,3,
+ 3,3,3,3,3,3,3,3,3,4,0,0,98,57,51,147,38,0,0,0,123,229,248,255,143,94,183,0,160,229,17,17,
+ 17,17,17,94,10,220,77,68,68,68,68,68,212,205,0,0,0,17,17,17,0,0,0,0,16,33,34,51,34,18,1,0,
+ 16,33,51,68,85,68,51,18,1,16,50,84,118,119,103,69,35,1,33,67,101,135,170,120,86,52,18,16,17,34,51,68,
+ 51,34,17,1,0,32,53,198,68,108,83,2,0,0,200,244,231,238,126,79,140,0,208,244,187,187,187,187,187,79,13,169,
+ 26,17,17,17,17,17,161,154,0,0,0,17,17,17,0,0,0,0,16,33,34,51,34,18,1,0,16,33,51,68,85,68,
+ 51,18,1,16,50,84,118,119,103,69,35,1,33,67,101,135,170,120,86,52,18,16,17,34,51,68,51,34,17,1,0,0,
+ 98,56,51,131,38,0,0,0,91,231,175,170,250,126,181,0,144,247,17,17,17,17,17,127,9,220,77,68,68,68,68,68,
+ 212,205,0,0,0,17,17,17,0,0,0,0,16,33,34,51,34,18,1,0,16,33,51,68,85,68,51,18,1,16,50,84,
+ 118,119,103,69,35,1,33,67,101,135,170,120,86,52,18,16,17,34,51,68,51,34,17,1,0,0,0,176,197,92,11,0,
+ 0,0,0,0,80,159,63,243,249,5,0,0,0,32,147,188,0,0,203,57,2,0,0,242,35,0,74,164,0,50,47,0,
+ 0,51,2,100,221,221,70,32,51,0,80,41,128,125,119,119,215,8,146,5,240,12,212,119,119,119,119,77,192,15,155,11,
+ 118,238,238,238,238,103,176,185,245,160,237,238,238,238,238,222,10,95,60,64,237,238,238,238,238,222,4,195,60,64,237,238,
+ 238,238,238,222,4,195,245,160,29,17,17,17,17,209,10,95,155,11,230,17,17,17,17,110,176,185,240,12,212,17,17,17,
+ 17,77,192,15,80,41,128,29,17,17,209,8,146,5,0,51,2,100,125,215,70,32,51,0,0,242,35,0,74,164,0,50,
+ 47,0,0,32,147,188,0,0,203,57,2,0,0,0,80,159,63,243,249,5,0,0,0,0,0,176,197,92,11,0,0,0,
+ 0,0,0,0,0,16,17,1,0,0,0,0,0,0,0,0,0,33,34,34,34,18,0,0,0,0,0,0,0,33,51,84,
+ 85,69,51,18,0,0,0,0,0,16,66,101,119,119,119,86,36,1,0,0,0,0,50,100,135,136,136,136,120,70,35,0,
+ 0,0,16,83,134,120,86,85,101,135,104,53,1,0,0,33,100,136,70,52,51,67,100,136,70,18,0,0,66,134,104,52,
+ 18,17,33,67,134,104,36,0,16,83,135,70,18,0,0,0,33,100,120,53,1,32,99,120,52,1,0,0,0,16,67,135,
+ 54,2,32,116,104,36,0,0,0,0,0,66,134,71,2,33,117,88,19,0,0,0,0,0,49,133,87,18,33,117,88,19,
+ 0,0,0,0,0,49,133,87,18,33,117,88,19,0,0,0,0,0,49,133,87,18,33,117,88,19,0,0,0,0,0,49,
+ 133,87,18,32,116,104,36,0,0,0,0,0,66,134,71,2,32,99,120,52,1,0,0,0,16,67,135,54,2,16,83,135,
+ 70,18,0,0,0,33,100,120,53,1,0,66,134,104,52,18,17,33,67,134,104,36,0,0,33,100,136,70,52,51,67,100,
+ 136,70,18,0,0,16,83,134,120,86,85,101,135,104,53,1,0,0,0,50,100,135,136,136,136,120,70,35,0,0,0,0,
+ 16,66,101,119,119,119,86,36,1,0,0,0,0,0,33,51,84,85,69,51,18,0,0,0,0,0,0,0,33,34,34,34,
+ 18,0,0,0,0,0,0,0,0,0,16,17,1,0,0,0,0,0,0,0,0,160,214,109,10,0,0,0,0,0,96,142,
+ 62,227,232,6,0,0,0,32,131,173,0,0,218,56,2,0,0,226,35,0,73,148,0,50,46,0,0,51,2,196,85,85,
+ 76,32,51,0,96,40,112,85,85,85,85,7,130,6,224,13,84,187,187,187,187,69,208,14,138,10,188,187,187,187,187,203,
+ 160,168,230,144,181,187,187,187,187,91,9,110,61,64,245,255,255,255,255,95,4,211,61,64,245,255,255,255,255,95,4,211,
+ 230,144,245,255,255,255,255,95,9,110,138,10,252,17,17,17,17,207,160,168,224,13,84,17,17,17,17,69,208,14,96,40,
+ 112,21,17,17,81,7,130,6,0,51,2,196,181,91,76,32,51,0,0,226,35,0,73,148,0,50,46,0,0,32,131,173,
+ 0,0,218,56,2,0,0,0,96,142,62,227,232,6,0,0,0,0,0,160,214,109,10,0,0,0,0,0,0,0,0,16,
+ 17,1,0,0,0,0,0,0,0,0,0,33,34,34,34,18,0,0,0,0,0,0,0,33,51,84,85,69,51,18,0,0,
+ 0,0,0,16,66,101,119,119,119,86,36,1,0,0,0,0,50,100,135,136,136,136,120,70,35,0,0,0,16,83,134,120,
+ 86,85,101,135,104,53,1,0,0,33,100,136,70,52,51,67,100,136,70,18,0,0,66,134,104,52,18,17,33,67,134,104,
+ 36,0,16,83,135,70,18,0,0,0,33,100,120,53,1,32,99,120,52,1,0,0,0,16,67,135,54,2,32,116,104,36,
+ 0,0,0,0,0,66,134,71,2,33,117,88,19,0,0,0,0,0,49,133,87,18,33,117,88,19,0,0,0,0,0,49,
+ 133,87,18,33,117,88,19,0,0,0,0,0,49,133,87,18,33,117,88,19,0,0,0,0,0,49,133,87,18,32,116,104,
+ 36,0,0,0,0,0,66,134,71,2,32,99,120,52,1,0,0,0,16,67,135,54,2,16,83,135,70,18,0,0,0,33,
+ 100,120,53,1,0,66,134,104,52,18,17,33,67,134,104,36,0,0,33,100,136,70,52,51,67,100,136,70,18,0,0,16,
+ 83,134,120,86,85,101,135,104,53,1,0,0,0,50,100,135,136,136,136,120,70,35,0,0,0,0,16,66,101,119,119,119,
+ 86,36,1,0,0,0,0,0,33,51,84,85,69,51,18,0,0,0,0,0,0,0,33,34,34,34,18,0,0,0,0,0,
+ 0,0,0,0,16,17,1,0,0,0,0,0,0,0,0,144,60,195,9,0,0,0,0,0,192,78,142,232,228,12,0,0,
+ 0,32,72,147,0,0,57,132,2,0,0,226,40,0,91,181,0,130,46,0,0,136,2,101,221,221,86,32,136,0,192,36,
+ 112,173,170,170,218,7,66,12,224,3,213,170,170,170,170,93,48,14,73,9,166,170,170,170,170,106,144,148,236,176,253,255,
+ 255,255,255,223,11,206,131,80,250,255,255,255,255,175,5,56,131,80,250,255,255,255,255,175,5,56,236,176,253,255,255,255,
+ 255,223,11,206,73,9,246,17,17,17,17,111,144,148,224,3,213,17,17,17,17,93,48,14,192,36,112,29,17,17,209,7,
+ 66,12,0,136,2,101,170,170,86,32,136,0,0,226,40,0,91,181,0,130,46,0,0,32,72,147,0,0,57,132,2,0,
+ 0,0,192,78,142,232,228,12,0,0,0,0,0,144,60,195,9,0,0,0,0,0,0,0,0,16,17,1,0,0,0,0,
+ 0,0,0,0,0,33,34,34,34,18,0,0,0,0,0,0,0,33,51,84,85,69,51,18,0,0,0,0,0,16,66,101,
+ 119,119,119,86,36,1,0,0,0,0,50,100,135,136,136,136,120,70,35,0,0,0,16,83,134,120,86,85,101,135,104,53,
+ 1,0,0,33,100,136,70,52,51,67,100,136,70,18,0,0,66,134,104,52,18,17,33,67,134,104,36,0,16,83,135,70,
+ 18,0,0,0,33,100,120,53,1,32,99,120,52,1,0,0,0,16,67,135,54,2,32,116,104,36,0,0,0,0,0,66,
+ 134,71,2,33,117,88,19,0,0,0,0,0,49,133,87,18,33,117,88,19,0,0,0,0,0,49,133,87,18,33,117,88,
+ 19,0,0,0,0,0,49,133,87,18,33,117,88,19,0,0,0,0,0,49,133,87,18,32,116,104,36,0,0,0,0,0,
+ 66,134,71,2,32,99,120,52,1,0,0,0,16,67,135,54,2,16,83,135,70,18,0,0,0,33,100,120,53,1,0,66,
+ 134,104,52,18,17,33,67,134,104,36,0,0,33,100,136,70,52,51,67,100,136,70,18,0,0,16,83,134,120,86,85,101,
+ 135,104,53,1,0,0,0,50,100,135,136,136,136,120,70,35,0,0,0,0,16,66,101,119,119,119,86,36,1,0,0,0,
+ 0,0,33,51,84,85,69,51,18,0,0,0,0,0,0,0,33,34,34,34,18,0,0,0,0,0,0,0,0,0,16,17,
+ 1,0,0,0,0,0,0,0,160,68,0,0,26,17,0,96,17,17,0,64,81,187,0,22,188,187,0,20,187,187,0,201,
+ 187,59,96,177,187,139,160,177,187,235,64,92,85,5,144,85,85,3,16,85,85,3,22,85,85,8,26,85,85,15,202,85,
+ 85,2,196,204,204,2,196,204,204,0,201,204,220,0,201,204,220,0,201,204,220,0,193,204,220,0,193,204,124,0,193,204,
+ 124,0,193,204,124,0,193,204,124,0,193,204,124,0,193,204,124,0,193,204,124,0,193,204,124,0,193,204,220,0,201,204,
+ 220,0,201,204,220,0,201,204,220,0,196,204,204,0,196,204,204,2,202,85,85,2,26,85,85,15,22,85,85,8,16,85,
+ 85,3,144,85,85,3,64,92,85,5,160,177,187,235,96,177,187,139,0,201,187,59,0,20,187,187,0,22,188,187,0,64,
+ 81,187,0,96,17,17,0,0,26,17,0,0,160,68,0,0,160,54,0,0,0,0,0,0,202,108,0,0,0,0,0,48,
+ 204,108,112,7,0,0,0,96,28,129,66,36,0,0,0,195,17,129,71,116,119,2,0,154,17,129,68,68,68,2,0,28,
+ 17,129,68,68,68,2,48,28,17,177,68,68,68,2,160,25,17,113,68,68,68,2,160,25,17,120,68,68,39,0,96,17,
+ 17,72,68,68,116,2,192,17,17,79,68,68,68,7,195,17,17,79,68,68,68,7,147,153,153,69,68,68,68,7,154,153,
+ 153,77,68,68,68,7,154,153,153,71,68,68,116,2,150,153,153,71,68,68,116,2,150,153,153,71,68,68,68,4,150,153,
+ 233,71,68,68,68,4,156,153,233,71,68,68,68,4,156,153,233,71,68,68,68,4,156,153,233,71,68,68,116,2,156,153,
+ 233,71,68,68,68,7,156,153,233,71,68,68,68,4,156,153,233,71,68,68,68,4,156,153,233,71,68,68,68,4,156,153,
+ 233,71,68,68,68,4,156,153,233,71,68,68,116,2,156,153,233,71,68,68,68,7,156,153,233,71,68,68,68,4,156,153,
+ 233,71,68,68,68,4,150,153,233,71,68,68,68,4,150,153,153,71,68,68,68,4,150,153,153,71,68,68,116,2,154,153,
+ 153,71,68,68,116,2,154,153,153,77,68,68,68,7,147,153,153,69,68,68,68,7,195,17,17,79,68,68,68,7,192,17,
+ 17,79,68,68,68,7,96,17,17,72,68,68,36,2,160,25,17,120,68,68,116,2,160,25,17,113,68,68,68,2,48,28,
+ 17,177,68,68,68,2,0,28,17,129,68,68,68,2,0,154,17,129,68,68,68,2,0,195,17,129,71,116,34,0,0,96,
+ 28,129,66,36,0,0,0,48,204,108,112,7,0,0,0,0,202,108,0,0,0,0,0,0,160,54,0,0,0,0,0,0,
+ 160,68,0,0,26,17,0,80,17,17,0,64,97,187,0,21,189,187,0,20,187,187,0,216,187,59,80,177,187,123,160,177,
+ 187,235,64,189,187,11,128,102,102,3,16,102,102,3,21,102,102,7,26,102,102,15,218,102,102,2,212,102,102,2,212,102,
+ 102,0,216,221,205,0,216,221,205,0,216,221,205,0,209,221,205,0,209,221,157,0,209,221,157,0,209,221,157,0,209,221,
+ 157,0,209,221,157,0,209,221,157,0,209,221,157,0,209,221,157,0,209,221,205,0,216,221,205,0,216,221,205,0,216,221,
+ 205,0,212,102,102,0,212,102,102,2,218,102,102,2,26,102,102,15,21,102,102,7,16,102,102,3,128,102,102,3,64,189,
+ 187,11,160,177,187,235,80,177,187,123,0,216,187,59,0,20,187,187,0,21,189,187,0,64,97,187,0,80,17,17,0,0,
+ 26,17,0,0,160,68,0,0,160,58,0,0,0,0,0,0,106,166,0,0,0,0,0,48,102,166,112,7,0,0,0,96,
+ 22,129,66,36,0,0,0,99,17,129,79,244,119,2,0,154,17,129,68,68,68,2,0,22,17,129,68,68,68,2,48,22,
+ 17,177,68,68,68,2,160,25,17,241,68,68,68,2,160,25,17,254,68,68,47,0,96,17,17,248,68,68,116,2,96,17,
+ 17,72,68,68,68,15,99,17,17,77,68,68,68,15,147,153,153,69,68,68,68,15,154,153,153,76,68,68,68,15,154,153,
+ 153,71,68,68,116,2,154,153,153,71,68,68,244,7,154,153,233,71,68,68,68,4,150,153,233,71,68,68,68,4,150,153,
+ 233,79,68,68,68,4,150,153,233,79,68,68,68,4,150,153,137,79,68,68,244,2,150,153,137,79,68,68,244,7,150,153,
+ 137,79,68,68,68,4,150,153,137,79,68,68,68,4,150,153,137,79,68,68,68,4,150,153,137,79,68,68,68,4,150,153,
+ 137,79,68,68,244,2,150,153,137,79,68,68,244,7,150,153,233,79,68,68,68,4,150,153,233,79,68,68,68,4,150,153,
+ 233,71,68,68,68,4,154,153,233,71,68,68,68,4,154,153,153,71,68,68,116,2,154,153,153,71,68,68,244,2,154,153,
+ 153,76,68,68,68,15,147,153,153,69,68,68,68,15,99,17,17,77,68,68,68,15,96,17,17,72,68,68,68,15,96,17,
+ 17,248,68,68,47,2,160,25,17,254,68,68,127,2,160,25,17,241,68,68,68,2,48,22,17,177,68,68,68,2,0,22,
+ 17,129,68,68,68,2,0,154,17,129,68,68,68,2,0,99,17,129,79,244,34,0,0,96,22,129,66,36,0,0,0,48,
+ 102,166,112,7,0,0,0,0,106,166,0,0,0,0,0,0,160,58,0,0,0,0,0,0,0,243,3,0,0,0,0,0,
+ 96,17,10,0,0,0,0,0,31,17,10,0,0,0,0,48,17,91,40,215,0,0,0,96,81,85,236,238,13,0,0,16,
+ 91,85,228,238,14,0,0,31,85,85,228,238,222,0,0,186,85,149,238,238,126,0,0,81,85,69,238,238,238,2,240,81,
+ 85,69,238,238,238,13,96,91,85,69,238,238,238,7,160,91,85,233,238,238,238,7,160,85,85,233,238,238,238,14,19,85,
+ 85,228,238,238,238,46,31,85,85,228,238,238,238,222,31,187,91,228,238,238,238,222,182,187,91,228,238,238,238,126,182,187,
+ 91,228,238,238,238,126,186,187,155,228,238,238,238,126,186,187,155,238,238,238,238,126,186,187,155,238,238,238,238,238,186,187,
+ 155,238,238,238,238,238,177,187,155,238,238,238,238,238,177,187,155,238,238,238,238,238,177,187,155,238,238,238,238,238,177,187,
+ 155,238,238,238,238,238,177,187,155,238,238,238,238,238,177,187,155,238,238,238,238,238,177,187,155,238,238,238,238,238,177,187,
+ 155,238,238,238,238,238,186,187,155,238,238,238,238,238,186,187,155,238,238,238,238,238,186,187,155,238,238,238,238,126,186,187,
+ 155,228,238,238,238,126,182,187,91,228,238,238,238,126,182,187,91,228,238,238,238,126,31,187,91,228,238,238,238,222,31,85,
+ 85,228,238,238,238,222,19,85,85,228,238,238,238,46,160,85,85,233,238,238,238,14,160,91,85,233,238,238,238,7,96,91,
+ 85,69,238,238,238,7,240,81,85,69,238,238,238,13,0,81,85,69,238,238,238,2,0,186,85,149,238,238,126,0,0,31,
+ 85,85,228,238,222,0,0,16,91,85,228,238,14,0,0,96,81,85,236,238,13,0,0,48,17,91,40,215,0,0,0,0,
+ 31,17,10,0,0,0,0,0,96,17,10,0,0,0,0,0,0,243,3,0,0,0,0,0,0,0,0,80,5,0,0,0,
+ 0,0,0,0,0,0,124,193,0,0,0,0,0,0,0,0,0,124,193,0,0,0,0,0,0,0,0,0,21,81,0,0,
+ 0,0,0,0,0,0,0,224,14,0,0,0,0,0,0,32,68,8,0,179,3,0,0,0,0,0,66,68,8,176,170,58,
+ 0,0,0,0,0,72,68,8,171,170,170,3,0,0,0,32,68,17,9,166,170,170,11,0,0,0,128,20,17,185,170,170,
+ 170,58,0,0,0,64,23,17,105,170,170,170,186,0,0,0,66,17,17,169,170,221,218,253,0,0,0,120,17,17,175,170,
+ 221,218,221,3,0,0,116,17,17,166,170,170,170,170,11,0,32,20,17,145,170,170,170,170,170,6,0,32,20,17,145,170,
+ 170,170,170,170,6,0,128,23,17,209,170,170,170,170,170,58,0,128,23,17,241,170,170,221,218,221,186,0,64,119,119,167,
+ 170,170,221,218,221,186,0,64,119,119,167,170,170,221,218,221,106,0,66,119,119,167,170,170,170,170,17,109,0,66,119,119,
+ 161,170,170,170,218,119,97,0,66,119,119,161,170,170,170,218,17,161,0,66,119,119,161,170,170,221,218,221,170,0,120,119,
+ 119,161,170,170,221,218,221,170,3,120,119,119,173,170,170,221,218,221,170,3,120,119,119,173,170,170,170,170,170,170,11,120,
+ 119,119,173,170,170,170,170,170,170,11,120,119,119,173,170,170,170,170,170,170,11,120,119,119,173,170,170,170,170,170,170,11,
+ 120,119,119,173,170,170,221,218,221,170,11,120,119,119,173,170,170,221,218,221,170,11,120,119,119,173,170,170,170,170,170,170,
+ 11,120,119,119,173,170,170,170,170,170,170,11,120,119,119,173,170,170,170,170,170,170,11,120,119,119,173,170,170,170,170,170,
+ 170,11,120,119,119,173,170,170,221,218,221,170,3,120,119,119,161,170,170,221,218,221,170,3,66,119,119,161,170,170,221,218,
+ 221,170,0,66,119,119,161,170,170,170,218,119,161,0,66,119,119,161,170,170,170,218,119,97,0,66,119,119,167,170,170,170,
+ 170,17,109,0,64,119,119,167,170,170,221,218,221,106,0,64,119,119,167,170,170,221,218,221,186,0,128,23,17,241,170,170,
+ 221,218,221,186,0,128,23,17,209,170,170,170,170,170,58,0,32,20,17,145,170,170,170,170,170,6,0,32,20,17,145,170,
+ 170,170,170,170,6,0,0,116,17,17,166,170,170,170,170,11,0,0,120,17,17,175,170,221,218,221,3,0,0,66,17,17,
+ 169,170,221,218,253,0,0,0,64,23,17,105,170,170,170,186,0,0,0,128,20,17,185,170,170,170,58,0,0,0,32,68,
+ 17,9,166,170,170,11,0,0,0,0,72,68,8,171,170,170,3,0,0,0,0,66,68,8,176,170,58,0,0,0,0,0,
+ 32,68,8,0,179,3,0,0,0,0,0,0,0,0,224,14,0,0,0,0,0,0,0,0,0,117,81,0,0,0,0,0,
+ 0,0,0,0,76,193,0,0,0,0,0,0,0,0,0,28,193,0,0,0,0,0,0,0,0,0,80,5,0,0,0,0,
+ 0,0,0,227,3,0,0,0,0,0,96,17,12,0,0,0,0,0,30,17,12,0,0,0,0,48,17,89,42,215,0,0,
+ 0,96,81,85,181,187,13,0,0,16,89,85,191,187,11,0,0,30,85,85,180,187,219,0,0,156,85,133,187,187,123,0,
+ 0,81,85,245,187,187,187,2,224,81,85,69,187,187,187,13,96,89,85,69,187,187,187,7,192,89,85,184,187,187,187,7,
+ 192,89,85,184,187,187,187,11,19,153,153,191,187,187,187,43,30,153,153,180,187,187,187,219,30,153,153,180,187,187,187,219,
+ 150,153,89,180,187,187,187,123,150,153,89,180,187,187,187,123,156,153,137,180,187,187,187,123,156,153,137,187,187,187,187,123,
+ 156,153,137,187,187,187,187,187,156,153,137,187,187,187,187,187,145,153,137,187,187,187,187,187,145,153,137,187,187,187,187,187,
+ 145,153,137,187,187,187,187,187,145,153,137,187,187,187,187,187,145,153,137,187,187,187,187,187,145,153,137,187,187,187,187,187,
+ 145,153,137,187,187,187,187,187,145,153,137,187,187,187,187,187,156,153,137,187,187,187,187,187,156,153,137,187,187,187,187,187,
+ 156,153,137,187,187,187,187,123,156,153,137,180,187,187,187,123,150,153,89,180,187,187,187,123,150,153,89,180,187,187,187,123,
+ 30,153,153,180,187,187,187,219,30,153,153,180,187,187,187,219,19,153,153,191,187,187,187,43,192,89,85,184,187,187,187,11,
+ 192,89,85,184,187,187,187,7,96,89,85,69,187,187,187,7,224,81,85,69,187,187,187,13,0,81,85,245,187,187,187,2,
+ 0,156,85,133,187,187,123,0,0,30,85,85,180,187,219,0,0,16,89,85,191,187,11,0,0,96,81,85,181,187,13,0,
+ 0,48,17,89,42,215,0,0,0,0,30,17,12,0,0,0,0,0,96,17,12,0,0,0,0,0,0,227,3,0,0,0,
+ 0,0,0,0,0,96,6,0,0,0,0,0,0,0,0,0,171,177,0,0,0,0,0,0,0,0,0,171,177,0,0,0,
+ 0,0,0,0,0,0,22,97,0,0,0,0,0,0,0,0,0,240,15,0,0,0,0,0,0,48,165,13,0,130,2,0,
+ 0,0,0,0,163,170,5,128,68,36,0,0,0,0,0,165,170,5,72,68,68,2,0,0,0,48,170,17,9,68,68,68,
+ 14,0,0,0,80,26,17,137,68,68,68,36,0,0,0,160,17,17,233,68,68,68,132,0,0,0,173,17,17,73,68,119,
+ 116,199,0,0,0,165,17,17,76,68,119,116,119,2,0,0,21,17,17,78,68,68,68,68,8,0,48,26,17,145,68,68,
+ 68,68,68,14,0,208,26,17,145,68,68,68,68,68,4,0,208,26,17,113,68,68,68,68,68,36,0,80,26,17,193,68,
+ 68,119,116,119,36,0,80,17,17,65,68,68,119,116,119,132,0,160,17,17,65,68,68,119,116,119,228,0,163,17,17,65,
+ 68,68,68,68,17,231,0,163,170,170,65,68,68,68,116,170,65,0,173,170,170,65,68,68,68,116,17,65,0,173,170,170,
+ 71,68,68,119,116,119,68,0,173,170,170,71,68,68,119,116,119,68,2,173,170,170,71,68,68,119,116,119,68,2,165,170,
+ 170,71,68,68,68,68,68,68,2,165,170,170,71,68,68,68,68,68,68,2,165,170,170,71,68,68,68,68,68,68,2,165,
+ 170,170,71,68,68,68,68,68,68,8,165,170,170,71,68,68,119,116,119,68,8,165,170,170,71,68,68,119,116,119,68,8,
+ 165,170,170,71,68,68,68,68,68,68,8,165,170,170,71,68,68,68,68,68,68,2,165,170,170,71,68,68,68,68,68,68,
+ 2,165,170,170,71,68,68,68,68,68,68,2,173,170,170,71,68,68,119,116,119,68,2,173,170,170,71,68,68,119,116,119,
+ 68,2,173,170,170,71,68,68,119,116,119,68,0,173,170,170,65,68,68,68,116,170,65,0,163,170,170,65,68,68,68,116,
+ 26,65,0,163,17,17,65,68,68,68,68,17,231,0,160,17,17,65,68,68,119,116,119,228,0,80,17,17,65,68,68,119,
+ 116,119,132,0,80,26,17,193,68,68,119,116,119,36,0,208,26,17,113,68,68,68,68,68,36,0,208,26,17,145,68,68,
+ 68,68,68,4,0,48,26,17,145,68,68,68,68,68,14,0,0,21,17,17,78,68,68,68,68,8,0,0,165,17,17,76,
+ 68,119,116,119,2,0,0,173,17,17,73,68,119,116,199,0,0,0,160,17,17,233,68,68,68,132,0,0,0,80,26,17,
+ 137,68,68,68,36,0,0,0,48,170,17,9,68,68,68,14,0,0,0,0,165,170,5,72,68,68,2,0,0,0,0,163,
+ 170,5,128,68,36,0,0,0,0,0,48,165,13,0,130,2,0,0,0,0,0,0,0,0,240,15,0,0,0,0,0,0,
+ 0,0,0,166,97,0,0,0,0,0,0,0,0,0,171,177,0,0,0,0,0,0,0,0,0,27,177,0,0,0,0,0,
+ 0,0,0,0,96,6,0,0,0,0,0,0,0,0,32,88,85,133,2,0,0,0,0,0,0,0,128,26,225,238,30,161,
+ 8,0,0,0,0,0,32,26,151,187,187,187,121,161,2,0,0,0,0,24,158,187,187,187,187,187,233,129,0,0,0,128,
+ 113,187,107,198,204,108,182,187,23,8,0,0,18,183,187,187,198,204,204,204,182,123,33,0,0,234,182,51,51,179,204,204,
+ 204,108,107,174,0,128,145,102,59,51,179,204,204,204,204,102,25,8,160,110,198,108,187,198,255,204,204,204,108,230,10,18,
+ 109,198,204,204,204,102,204,204,204,108,214,33,24,153,204,204,204,204,102,204,204,204,204,153,129,21,153,204,252,111,102,102,
+ 102,246,207,204,153,81,229,153,204,204,255,102,102,102,255,204,204,153,94,229,153,204,204,252,111,102,246,207,204,204,153,94,
+ 21,153,204,204,204,111,102,246,204,204,204,153,81,24,255,204,204,204,105,255,150,204,204,204,255,129,18,253,207,204,204,255,
+ 255,255,204,204,252,223,33,160,254,207,204,252,207,204,252,207,204,252,239,10,128,209,255,204,252,204,204,204,207,204,255,29,
+ 8,0,234,68,207,204,204,204,204,204,252,68,174,0,0,18,78,68,204,204,204,204,204,68,228,33,0,0,128,225,68,68,
+ 207,204,252,68,68,30,8,0,0,0,24,222,68,68,68,68,68,237,129,0,0,0,0,32,26,222,68,68,68,237,161,2,
+ 0,0,0,0,0,128,26,17,238,17,161,8,0,0,0,0,0,0,0,32,88,85,133,2,0,0,0,0,0,0,0,224,
+ 95,245,14,0,0,0,0,0,224,25,129,24,145,14,0,0,0,0,23,168,187,187,138,113,0,0,0,112,129,187,187,187,
+ 187,24,7,0,0,18,184,107,204,204,182,139,33,0,0,133,187,187,204,204,108,187,88,0,32,161,59,51,195,204,204,182,
+ 26,2,80,184,54,51,195,204,204,108,139,5,208,100,204,187,204,204,204,204,70,13,18,102,204,204,108,198,204,204,102,33,
+ 135,102,204,204,108,198,204,204,102,120,143,198,204,106,182,107,166,204,108,248,143,198,204,106,187,187,166,204,108,248,143,202,
+ 204,172,182,107,202,204,172,248,143,202,204,204,182,107,204,204,172,248,23,170,204,204,171,186,204,204,170,113,18,170,204,204,
+ 170,170,204,204,170,33,208,164,204,172,202,172,202,204,74,13,80,168,202,172,204,204,204,172,138,5,32,65,196,204,204,204,
+ 204,76,20,2,0,133,68,204,204,204,204,68,88,0,0,18,72,164,204,204,74,132,33,0,0,112,129,68,68,68,68,24,
+ 7,0,0,0,23,129,68,68,24,113,0,0,0,0,224,25,17,17,145,14,0,0,0,0,0,224,95,245,14,0,0,0,
+ 0,238,0,128,17,8,48,255,3,112,255,7,208,255,13,18,251,33,154,244,172,154,244,172,206,251,236,101,255,86,101,255,
+ 86,101,255,86,101,255,86,101,255,86,101,255,86,197,255,92,197,255,92,206,255,236,202,255,172,26,255,161,18,255,33,208,
+ 255,13,112,255,7,48,255,3,128,17,8,0,238,0,0,0,0,224,95,245,14,0,0,0,0,0,224,25,129,24,145,14,
+ 0,0,0,0,23,168,102,102,138,113,0,0,0,112,193,102,102,102,102,28,7,0,0,18,108,102,187,187,102,198,33,0,
+ 0,133,102,102,187,187,187,102,88,0,32,161,54,51,179,187,187,107,26,2,80,104,54,51,179,187,187,107,134,5,208,106,
+ 187,102,75,180,187,187,166,13,18,106,187,187,75,180,187,187,166,33,135,186,187,187,75,180,187,187,171,120,143,186,187,68,
+ 68,68,68,187,171,248,143,186,187,68,68,68,68,187,171,248,143,186,187,75,68,68,180,187,171,248,143,186,187,187,68,68,
+ 187,187,171,248,135,186,187,187,68,68,187,187,171,120,18,170,187,75,68,68,180,187,170,33,208,172,187,75,180,75,180,187,
+ 202,13,80,168,186,75,187,187,180,171,138,5,32,65,180,187,187,187,187,75,20,2,0,133,68,187,187,187,187,68,88,0,
+ 0,18,72,68,187,187,68,132,33,0,0,112,129,68,68,68,68,24,7,0,0,0,23,193,68,68,28,113,0,0,0,0,
+ 224,25,17,17,145,14,0,0,0,0,0,224,95,245,14,0,0,0,15,31,31,31,31,31,31,31,31,31,31,31,31,31,
+ 31,31,31,31,31,15,31,191,207,207,207,207,207,207,207,207,207,207,207,207,207,207,207,207,191,31,31,207,255,255,255,255,
+ 255,255,255,255,255,255,255,255,255,255,255,255,207,31,31,207,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
+ 207,31,31,207,255,255,223,159,159,159,159,159,159,159,159,159,159,223,255,255,207,31,31,207,255,255,159,15,15,15,15,15,
+ 15,15,15,15,15,159,255,255,207,31,31,207,255,255,159,15,9,6,6,6,6,6,6,9,15,159,255,255,207,31,31,207,
+ 255,255,159,15,6,8,11,11,11,11,8,6,15,159,255,255,207,31,31,207,255,255,159,15,6,11,4,2,2,4,11,6,
+ 15,159,255,255,207,31,31,207,255,255,159,15,6,11,2,0,0,2,11,6,15,159,255,255,207,31,31,207,255,255,159,15,
+ 6,11,2,0,0,2,11,6,15,159,255,255,207,31,31,207,255,255,159,15,6,11,4,2,2,4,11,6,15,159,255,255,
+ 207,31,31,207,255,255,159,15,6,8,11,11,11,11,8,6,15,159,255,255,207,31,31,207,255,255,159,15,9,6,6,6,
+ 6,6,6,9,15,159,255,255,207,31,31,207,255,255,159,15,15,15,15,15,15,15,15,15,15,159,255,255,207,31,31,207,
+ 255,255,223,159,159,159,159,159,159,159,159,159,159,223,255,255,207,31,31,207,255,255,255,255,255,255,255,255,255,255,255,255,
+ 255,255,255,255,207,31,31,207,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,207,31,31,191,207,207,207,207,
+ 207,207,207,207,207,207,207,207,207,207,207,207,191,31,15,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,
+ 31,15,246,249,249,249,249,246,249,255,255,255,255,249,249,255,255,255,255,249,249,255,255,255,255,249,249,255,255,255,255,249,
+ 246,249,249,249,249,246,0,0,0,0,2,9,9,9,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,4,13,6,14,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,11,
+ 0,13,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,15,15,15,11,9,9,9,
+ 10,8,5,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,15,6,6,6,6,6,6,6,5,7,10,13,15,12,
+ 9,3,0,0,0,0,0,0,0,0,0,0,15,0,0,0,0,0,0,0,0,0,0,0,1,4,8,14,12,5,0,0,
+ 0,0,1,4,4,4,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,13,10,0,0,0,4,15,31,15,
+ 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,8,0,0,4,47,159,15,111,159,159,159,47,111,
+ 159,159,159,159,159,159,143,15,143,159,159,111,63,15,6,0,4,47,159,15,159,255,255,255,79,159,255,255,255,255,255,255,
+ 223,15,223,255,255,255,255,207,47,4,4,47,159,15,159,255,255,255,79,159,255,255,255,255,255,255,223,15,223,255,255,255,
+ 255,255,79,4,4,47,127,15,143,223,223,223,63,143,223,223,223,223,223,223,207,15,207,223,223,223,223,159,31,3,3,11,
+ 11,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,5,0,0,0,0,10,31,31,12,2,
+ 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,0,0,0,0,0,4,9,9,5,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,242,249,241,0,0,0,0,0,0,0,0,0,0,0,0,0,0,244,255,242,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,249,
+ 249,249,249,249,249,249,250,248,245,242,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,254,251,248,241,0,
+ 0,239,239,239,239,239,239,239,239,239,239,239,239,239,239,239,249,242,81,81,81,81,81,81,81,81,81,81,81,81,81,81,
+ 81,81,0,0,0,0,0,0,0,0,0,0,0,224,238,238,238,238,238,238,238,238,238,238,238,238,238,238,238,238,14,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,17,17,17,17,17,17,17,17,17,17,17,
+ 17,17,17,17,17,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,113,119,119,119,
+ 119,119,119,119,119,119,119,119,119,119,119,23,177,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,224,113,119,119,119,119,119,119,119,119,119,119,119,119,119,119,23,81,3,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,224,113,151,153,153,153,153,153,153,153,153,153,153,153,153,153,25,81,3,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,113,151,153,153,153,153,153,153,153,153,153,153,153,153,153,
+ 25,81,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,113,151,153,153,153,153,153,153,
+ 153,153,153,153,153,153,153,25,81,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,113,
+ 151,153,153,153,153,153,153,153,153,153,153,153,153,153,25,81,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,224,113,151,153,153,153,153,153,153,153,153,153,153,153,153,153,25,81,3,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,224,113,151,153,153,153,153,153,153,153,153,153,153,153,153,153,25,81,3,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,113,151,153,153,153,153,153,153,153,153,153,153,
+ 153,153,153,25,81,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,113,151,153,153,153,
+ 153,153,153,153,153,153,153,153,153,153,25,81,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,224,113,151,153,153,153,153,153,153,153,153,153,153,153,153,153,25,81,3,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,224,113,151,153,153,153,153,153,153,153,153,153,153,153,153,153,25,81,3,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,229,238,238,30,113,151,153,153,153,153,153,153,153,153,153,153,153,153,153,25,
+ 225,238,238,94,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,30,17,17,17,113,151,153,153,153,153,153,153,153,
+ 153,153,153,153,153,153,25,17,17,17,225,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,30,34,34,34,114,151,
+ 153,153,153,153,153,153,153,153,153,153,153,153,153,41,34,34,34,225,59,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,30,34,34,34,114,151,153,153,153,153,153,153,153,153,153,153,153,153,153,41,34,34,34,225,53,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,30,34,34,34,114,151,153,153,153,153,153,153,153,153,153,153,153,153,153,41,34,34,34,225,
+ 53,0,0,0,0,0,0,0,0,0,0,0,0,0,0,30,34,34,34,114,151,153,153,153,153,153,153,153,153,153,153,153,
+ 153,153,41,34,34,34,225,53,0,0,0,0,0,0,0,0,0,0,0,0,0,0,30,34,34,34,114,151,153,153,153,153,
+ 153,153,153,153,153,153,153,153,153,41,34,34,34,225,53,0,0,0,0,0,0,0,238,238,238,238,238,238,238,17,34,34,
+ 34,114,151,153,153,153,153,153,153,153,153,153,153,153,153,153,41,34,34,34,17,225,238,238,238,238,238,238,0,30,17,17,
+ 17,17,17,17,17,34,34,34,114,151,204,204,150,153,153,153,153,153,153,153,153,153,153,41,34,34,34,17,17,17,17,17,
+ 17,17,225,0,30,119,119,119,119,119,119,119,119,119,119,119,151,17,17,17,150,153,153,153,153,153,153,153,153,153,153,121,
+ 119,119,119,119,119,119,119,119,119,17,59,30,119,119,119,119,119,119,119,119,119,119,119,151,17,28,17,193,150,153,153,153,
+ 153,153,153,153,153,153,121,119,119,119,119,119,119,119,119,119,17,53,30,119,153,153,153,153,153,153,153,153,153,153,153,17,
+ 253,28,17,193,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,17,53,30,119,153,153,153,153,153,
+ 153,153,153,153,153,153,17,221,173,17,17,193,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,17,53,
+ 30,119,153,153,153,153,153,153,153,153,153,153,105,17,221,221,173,17,17,97,153,153,153,153,153,153,153,153,153,153,153,153,
+ 153,153,153,153,153,17,53,30,119,153,153,153,153,153,153,153,153,153,153,105,17,221,221,221,205,17,17,97,153,153,153,153,
+ 153,153,153,153,153,153,153,153,153,153,153,153,17,53,30,119,153,153,153,153,153,153,153,153,153,153,105,17,221,221,221,221,
+ 207,17,17,108,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,17,53,30,119,153,153,153,153,153,153,153,153,153,
+ 153,105,17,221,221,221,221,221,31,17,17,108,153,153,153,153,153,153,153,153,153,153,153,153,153,153,17,53,30,119,153,153,
+ 153,153,153,153,153,153,153,153,105,17,221,221,221,221,221,221,26,17,17,156,153,153,153,153,153,153,153,153,153,153,153,153,
+ 153,17,53,30,119,153,153,153,153,153,153,153,153,153,153,105,17,221,221,221,221,221,221,221,26,17,17,156,153,153,153,153,
+ 153,153,153,153,153,153,153,153,17,53,30,119,153,153,153,153,153,153,153,153,153,153,105,17,221,221,221,221,221,221,221,77,
+ 28,17,17,150,153,153,153,153,153,153,153,153,153,153,153,17,53,30,119,153,153,153,153,153,153,153,153,153,153,105,17,221,
+ 221,221,221,221,221,221,221,253,28,17,193,150,153,153,153,153,153,153,153,153,153,153,17,53,30,119,153,153,153,153,153,153,
+ 153,153,153,153,105,17,221,221,221,221,221,221,221,221,221,253,28,17,193,150,153,153,153,153,153,153,153,153,153,17,53,30,
+ 119,153,153,153,153,153,153,153,153,153,153,105,17,221,221,221,221,221,221,221,221,221,221,173,17,17,156,153,153,153,153,153,
+ 153,153,153,153,17,53,30,119,153,153,153,153,153,153,153,153,153,153,105,17,221,221,221,221,221,221,221,221,221,221,221,164,
+ 17,156,153,153,153,153,153,153,153,153,153,17,53,30,119,153,153,153,153,153,153,153,153,153,153,105,17,221,221,221,221,221,
+ 221,221,221,221,221,221,164,17,156,153,153,153,153,153,153,153,153,153,17,53,30,119,102,102,102,102,102,102,102,102,102,102,
+ 102,17,68,68,68,68,68,68,68,68,68,68,244,28,17,108,102,102,102,102,102,102,102,102,102,17,53,30,119,102,102,102,
+ 102,102,102,102,102,102,102,102,17,68,68,68,68,68,68,68,68,68,244,28,17,17,102,102,102,102,102,102,102,102,102,102,
+ 17,53,30,119,102,102,102,102,102,102,102,102,102,102,102,17,68,68,68,68,68,68,68,68,68,28,17,17,102,102,102,102,
+ 102,102,102,102,102,102,102,17,53,30,119,102,102,102,102,102,102,102,102,102,102,102,17,68,68,68,68,68,68,68,68,26,
+ 17,17,108,102,102,102,102,102,102,102,102,102,102,102,17,53,30,119,102,102,102,102,102,102,102,102,102,102,102,17,68,68,
+ 68,68,68,68,68,26,17,17,108,102,102,102,102,102,102,102,102,102,102,102,102,17,53,30,119,102,102,102,102,102,102,102,
+ 102,102,102,102,17,68,68,68,68,68,68,202,17,17,108,102,102,102,102,102,102,102,102,102,102,102,102,102,17,53,30,119,
+ 102,102,102,102,102,102,102,102,102,102,102,17,68,68,68,68,68,207,17,17,97,102,102,102,102,102,102,102,102,102,102,102,
+ 102,102,102,17,53,30,119,102,102,102,102,102,102,102,102,102,102,102,17,68,68,68,68,207,17,17,193,102,102,102,102,102,
+ 102,102,102,102,102,102,102,102,102,102,17,53,30,119,102,102,102,102,102,102,102,102,102,102,102,17,68,68,68,164,17,17,
+ 193,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,17,53,30,119,102,102,102,102,102,102,102,102,102,102,102,
+ 17,68,68,164,17,17,193,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,17,53,30,119,102,102,102,102,
+ 102,102,102,102,102,102,102,17,68,164,17,17,193,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,17,
+ 53,30,119,102,102,102,102,102,102,102,102,102,102,102,17,244,28,17,17,102,102,102,102,102,102,102,102,102,102,102,102,102,
+ 102,102,102,102,102,102,17,53,30,119,102,102,102,102,102,102,102,102,102,102,102,17,28,17,17,108,102,102,102,102,102,102,
+ 102,102,102,102,102,102,102,102,102,102,102,102,102,17,53,30,119,102,102,102,102,102,102,102,102,102,102,102,17,17,17,108,
+ 102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,102,17,53,30,17,17,17,17,17,17,17,136,136,
+ 136,104,102,204,204,108,102,102,102,102,102,102,102,102,102,102,134,136,136,136,17,17,17,17,17,17,17,17,53,238,17,17,
+ 17,17,17,17,17,136,136,136,104,102,102,102,102,102,102,102,102,102,102,102,102,102,102,134,136,136,136,17,17,17,17,17,
+ 17,17,225,53,48,85,85,85,85,85,85,30,136,136,136,120,105,102,102,102,102,102,102,102,102,102,102,102,102,102,134,136,
+ 136,136,225,85,85,85,85,85,85,85,53,48,187,187,187,187,187,187,30,136,136,136,120,103,102,102,102,102,102,102,102,102,
+ 102,102,102,102,102,134,136,136,136,225,181,187,187,187,187,187,187,59,0,0,0,0,0,0,0,30,136,136,136,120,103,102,
+ 102,102,102,102,102,102,102,102,102,102,102,102,134,136,136,136,225,53,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 30,136,136,136,120,103,102,102,102,102,102,102,102,102,102,102,102,102,102,134,136,136,136,225,53,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,30,136,136,136,120,105,102,102,102,102,102,102,102,102,102,102,102,102,102,134,136,136,136,225,53,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,30,17,17,17,113,105,102,102,102,102,102,102,102,102,102,102,102,102,
+ 102,22,17,17,17,225,53,0,0,0,0,0,0,0,0,0,0,0,0,0,0,229,238,238,30,113,105,102,102,102,102,102,
+ 102,102,102,102,102,102,102,102,22,225,238,238,238,53,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,85,85,21,
+ 113,105,102,102,102,102,102,102,102,102,102,102,102,102,102,22,81,85,85,85,53,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,48,187,187,27,113,105,102,102,102,102,102,102,102,102,102,102,102,102,102,22,81,187,187,187,59,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,224,113,105,102,102,102,102,102,102,102,102,102,102,102,102,102,22,81,3,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,113,105,102,102,102,102,102,102,102,102,102,
+ 102,102,102,102,22,81,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,113,105,102,102,
+ 102,102,102,102,102,102,102,102,102,102,102,22,81,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,224,113,105,102,102,102,102,102,102,102,102,102,102,102,102,102,22,81,3,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,224,113,105,102,102,102,102,102,102,102,102,102,102,102,102,102,22,81,3,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,113,105,102,102,102,102,102,102,102,102,102,102,102,102,102,
+ 22,81,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,113,105,102,102,102,102,102,102,
+ 102,102,102,102,102,102,102,22,81,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,113,
+ 105,102,102,102,102,102,102,102,102,102,102,102,102,102,22,81,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,224,113,105,102,102,102,102,102,102,102,102,102,102,102,102,102,22,81,3,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,224,113,105,102,102,102,102,102,102,102,102,102,102,102,102,102,22,81,3,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,17,17,17,17,17,17,17,17,17,17,17,17,
+ 17,17,17,17,81,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,30,17,17,17,17,
+ 17,17,17,17,17,17,17,17,17,17,17,94,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,83,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,3,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,179,187,187,187,187,187,187,187,187,187,187,187,187,187,187,187,187,3,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,102,102,102,102,102,102,102,102,102,102,102,102,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,17,17,17,17,17,17,17,17,17,17,17,17,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,17,34,34,34,34,34,34,34,34,34,34,17,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,17,34,34,
+ 34,34,34,34,34,34,34,34,17,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,17,162,170,170,170,170,170,170,
+ 170,170,170,17,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,17,162,170,170,170,170,170,170,170,170,170,17,60,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,17,162,170,170,170,170,170,170,170,170,170,17,60,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,17,162,170,170,170,170,170,170,170,170,170,17,60,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,17,170,170,170,170,170,170,170,170,170,170,17,60,0,0,0,0,0,0,0,0,0,0,0,48,204,204,17,
+ 170,170,170,170,170,170,170,170,170,170,17,198,204,3,0,0,0,0,0,0,0,0,0,192,17,17,17,170,170,170,170,170,
+ 170,170,170,170,170,17,17,17,12,0,0,0,0,0,0,0,0,0,192,65,153,153,170,170,170,170,170,170,170,170,170,170,
+ 153,153,20,54,0,0,0,0,0,0,0,0,0,192,145,73,68,85,255,255,255,255,255,255,255,255,255,68,148,25,198,0,
+ 0,0,0,0,0,0,0,0,192,145,20,17,17,17,17,17,17,17,17,17,17,17,17,177,25,198,0,0,0,0,0,22,
+ 17,17,17,17,145,20,34,34,34,34,34,34,34,34,34,34,34,34,177,25,17,17,17,17,97,0,22,17,17,17,17,145,
+ 20,34,34,34,34,34,34,34,34,34,34,34,34,177,25,17,17,17,17,17,0,22,170,170,170,170,170,21,34,34,34,34,
+ 34,34,34,34,34,34,34,34,209,170,170,170,170,170,17,60,22,170,170,170,170,170,21,34,34,34,34,34,34,34,34,34,
+ 34,34,34,209,170,170,170,170,170,17,60,22,170,85,85,85,85,31,34,34,34,34,34,34,34,34,34,34,34,34,129,85,
+ 85,85,85,85,17,60,22,170,85,85,85,85,31,34,34,34,34,34,34,34,34,34,34,34,34,129,85,85,85,85,85,17,
+ 60,22,170,85,85,85,85,31,34,34,221,221,237,34,34,210,221,221,34,34,129,85,85,85,85,85,17,60,22,170,85,85,
+ 85,85,31,238,238,17,17,225,238,238,30,17,17,238,238,129,85,85,85,85,85,17,60,22,170,85,85,85,85,31,238,238,
+ 17,17,225,238,238,30,17,17,238,238,129,85,85,85,85,85,17,60,22,170,85,85,85,85,31,238,238,17,17,225,238,238,
+ 30,17,17,238,238,129,85,85,85,85,85,17,60,22,170,85,85,85,85,31,238,238,17,17,225,238,238,30,17,17,238,238,
+ 129,85,85,85,85,85,17,60,22,170,85,85,85,85,31,238,238,221,221,237,238,238,222,221,221,238,238,129,85,85,85,85,
+ 85,17,60,22,170,85,85,85,85,31,238,238,238,238,238,238,238,238,238,238,238,238,129,85,85,85,85,85,17,60,22,170,
+ 85,85,85,85,31,238,238,238,238,238,238,238,238,238,238,238,238,129,85,85,85,85,85,17,60,22,170,85,85,85,85,31,
+ 238,238,238,238,238,238,238,238,238,238,238,238,129,85,85,85,85,85,17,60,22,170,85,85,85,85,24,238,238,222,221,221,
+ 221,221,221,221,237,238,238,129,85,85,85,85,85,17,60,22,170,85,85,85,85,24,238,238,142,17,17,17,17,17,17,232,
+ 238,238,129,85,85,85,85,85,17,60,22,170,85,85,85,85,24,119,119,135,17,17,17,17,17,17,120,119,119,129,85,85,
+ 85,85,85,17,60,22,170,85,85,85,85,24,119,119,119,221,221,221,221,221,221,119,119,119,129,85,85,85,85,85,17,60,
+ 22,170,85,85,85,85,24,119,119,119,119,119,119,119,119,119,119,119,119,129,85,85,85,85,85,17,60,22,170,85,85,85,
+ 85,24,119,119,119,119,119,119,119,119,119,119,119,119,129,85,85,85,85,85,17,60,22,170,85,85,85,85,24,119,119,119,
+ 119,119,119,119,119,119,119,119,119,129,85,85,85,85,85,17,60,22,17,17,17,17,65,27,119,119,119,119,119,119,119,119,
+ 119,119,119,119,177,20,17,17,17,17,17,60,22,17,17,17,17,65,27,119,119,119,119,119,119,119,119,119,119,119,119,177,
+ 20,17,17,17,17,17,60,48,204,204,204,108,65,27,17,17,17,17,17,17,17,17,17,17,17,17,177,20,198,204,204,204,
+ 204,60,48,204,204,204,108,65,180,187,136,136,136,136,136,136,136,136,136,136,187,75,20,198,204,204,204,204,60,0,0,0,
+ 0,192,177,68,68,170,255,255,255,255,255,255,255,255,255,68,68,27,198,0,0,0,0,0,0,0,0,0,192,17,17,17,
+ 170,255,255,255,255,255,255,255,255,255,17,17,17,198,0,0,0,0,0,0,0,0,0,48,108,102,17,170,255,255,255,255,
+ 255,255,255,255,255,17,102,102,198,0,0,0,0,0,0,0,0,0,0,192,204,17,170,255,255,255,255,255,255,255,255,255,
+ 17,204,204,204,0,0,0,0,0,0,0,0,0,0,48,51,17,170,255,255,255,255,255,255,255,255,255,17,204,51,51,0,
+ 0,0,0,0,0,0,0,0,0,0,0,17,170,255,255,255,255,255,255,255,255,255,17,60,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,17,170,255,255,255,255,255,255,255,255,255,17,60,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,17,170,255,255,255,255,255,255,255,255,255,17,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,17,170,255,255,
+ 255,255,255,255,255,255,255,17,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,17,170,255,255,255,255,255,255,255,
+ 255,255,17,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,17,17,17,17,17,17,17,17,17,17,17,17,60,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,22,17,17,17,17,17,17,17,17,17,17,17,60,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,48,204,204,204,204,204,204,204,204,204,204,204,60,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,48,204,204,204,204,204,204,204,204,204,204,204,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,102,102,
+ 102,102,102,102,102,102,102,102,102,102,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,17,17,17,17,17,17,17,
+ 17,17,17,17,17,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,241,34,34,34,34,34,34,34,34,34,34,31,
+ 60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,241,34,34,34,34,34,34,34,34,34,34,31,60,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,241,34,170,170,170,170,170,170,170,170,170,31,60,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,241,34,170,170,170,170,170,170,170,170,170,31,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 241,34,170,170,170,170,170,170,170,170,170,31,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,241,34,170,170,170,
+ 170,170,170,170,170,170,31,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,241,34,170,170,170,170,170,170,170,170,
+ 170,31,60,0,0,0,0,0,0,0,0,0,0,0,48,204,204,241,34,170,170,170,170,170,170,170,170,170,31,198,204,3,
+ 0,0,0,0,0,0,0,0,0,192,17,17,241,34,170,170,170,170,170,170,170,170,170,31,17,17,12,0,0,0,0,0,
+ 0,0,0,0,192,129,221,221,34,170,170,170,170,170,170,170,170,170,221,221,24,54,0,0,0,0,0,0,0,0,0,192,
+ 209,153,153,34,170,170,170,170,170,170,90,85,85,153,153,29,198,0,0,0,0,0,0,0,0,0,192,209,153,153,34,170,
+ 90,255,175,170,90,31,17,17,223,153,29,198,0,0,0,0,0,22,17,17,17,17,209,153,153,34,90,31,241,241,170,27,
+ 81,119,87,17,157,29,17,17,17,17,97,0,22,255,255,255,255,223,153,153,34,27,241,119,31,165,17,119,119,119,23,157,
+ 253,255,255,255,255,17,0,22,34,34,34,34,34,34,34,245,241,126,119,23,191,225,119,119,119,31,42,34,34,34,34,34,
+ 31,60,22,34,34,34,34,34,34,250,17,126,119,119,183,241,113,119,119,30,177,34,34,34,34,34,34,31,60,22,34,170,
+ 170,170,170,90,17,127,119,119,119,119,31,127,119,119,31,95,170,170,170,170,170,170,31,60,22,34,170,170,170,170,90,225,
+ 119,119,119,119,119,31,113,119,119,247,17,171,170,170,170,170,170,31,60,22,34,85,85,85,85,85,241,119,119,119,119,247,
+ 17,113,119,119,119,254,95,85,85,85,85,85,31,60,22,34,85,85,85,85,85,27,127,119,119,119,254,17,126,119,119,119,
+ 247,95,85,85,85,85,85,31,60,22,34,85,85,85,85,85,181,241,119,119,119,231,225,119,119,119,231,31,91,85,85,85,
+ 85,85,31,60,22,34,85,85,85,85,85,85,31,127,27,126,119,126,119,247,241,17,177,85,85,85,85,85,85,31,60,22,
+ 34,85,85,85,85,85,85,245,17,17,127,119,119,119,31,191,187,85,85,85,85,85,85,85,31,60,22,34,85,85,85,85,
+ 85,85,85,187,187,241,119,119,247,241,85,85,85,85,85,85,85,85,85,31,60,22,34,85,85,85,85,85,85,85,85,245,
+ 241,119,119,247,241,85,85,85,85,85,85,85,85,85,31,60,22,34,85,85,85,85,85,85,85,85,31,239,119,119,119,31,
+ 95,85,85,85,85,85,85,85,85,17,60,22,34,85,85,85,85,85,85,85,181,241,126,119,126,119,254,177,85,85,85,85,
+ 85,85,85,85,17,60,22,34,85,85,85,85,85,85,85,27,225,238,238,225,238,238,31,91,85,85,85,85,85,85,85,17,
+ 60,22,34,85,85,85,85,85,85,181,17,238,238,30,17,238,238,30,177,85,85,85,85,85,85,85,17,60,22,34,85,85,
+ 85,85,85,85,27,225,238,238,17,27,225,238,238,17,91,85,85,85,85,85,85,17,60,22,34,85,85,85,85,85,181,17,
+ 238,238,30,177,181,17,238,238,30,177,85,85,85,85,85,85,17,60,22,34,85,85,85,85,85,181,225,238,238,31,91,85,
+ 27,239,238,190,241,85,85,85,85,85,85,17,60,22,34,85,85,85,85,85,181,225,238,254,241,85,85,245,241,238,238,31,
+ 91,85,85,85,85,85,17,60,22,34,85,85,85,85,85,181,225,238,31,95,85,85,85,31,239,238,30,91,85,85,85,85,
+ 85,17,60,22,255,17,17,17,129,68,68,17,31,241,187,187,187,187,251,225,238,30,72,24,17,17,17,17,17,60,22,17,
+ 17,17,17,129,68,68,251,255,187,187,187,187,187,187,17,255,17,68,24,17,17,17,17,17,60,48,204,204,204,108,129,68,
+ 68,170,187,187,187,187,187,187,187,251,255,143,68,24,198,204,204,204,204,60,48,204,204,204,108,129,68,68,162,187,187,187,
+ 187,187,187,187,187,187,68,68,24,198,204,204,204,204,60,0,0,0,0,192,129,136,136,162,187,187,187,187,187,187,187,187,
+ 187,136,136,24,198,0,0,0,0,0,0,0,0,0,192,17,17,241,162,187,187,187,187,187,187,187,187,187,17,17,17,198,
+ 0,0,0,0,0,0,0,0,0,48,108,102,241,162,187,187,187,187,187,187,187,187,187,17,102,102,198,0,0,0,0,0,
+ 0,0,0,0,0,192,204,241,162,187,187,187,187,187,187,187,187,187,17,204,204,204,0,0,0,0,0,0,0,0,0,0,
+ 48,51,241,162,187,187,187,187,187,187,187,187,187,17,204,51,51,0,0,0,0,0,0,0,0,0,0,0,0,241,162,187,
+ 187,187,187,187,187,187,187,187,17,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,241,162,187,187,187,187,187,187,
+ 187,187,187,17,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,241,162,187,187,187,187,187,187,187,187,187,17,60,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,241,162,187,187,187,187,187,187,187,187,187,17,60,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,241,170,187,187,187,187,187,187,187,187,187,17,60,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,17,255,17,17,17,17,17,17,17,17,17,17,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,22,
+ 17,17,17,17,17,17,17,17,17,17,17,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,204,204,204,204,204,
+ 204,204,204,204,204,204,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,204,204,204,204,204,204,204,204,204,204,
+ 204,60,0,0,0,0,0,0,0,0,0,0,0,0,32,89,170,170,170,90,41,0,0,0,0,0,0,0,0,0,0,144,
+ 26,17,207,238,206,31,17,154,0,0,0,0,0,0,0,0,32,26,193,219,221,221,221,221,200,17,42,0,0,0,0,0,
+ 0,0,25,193,221,221,221,221,221,221,221,205,17,5,0,0,0,0,0,80,17,219,221,141,136,136,136,136,221,221,248,161,
+ 0,0,0,0,0,21,143,221,141,136,136,136,136,136,136,221,221,31,10,0,0,0,144,241,221,141,136,136,136,136,136,136,
+ 136,136,221,253,81,0,0,0,18,129,221,136,221,221,221,184,204,132,136,136,216,221,31,9,0,0,26,219,141,221,221,221,
+ 221,30,17,177,136,136,136,221,24,10,0,144,193,221,216,221,253,17,17,241,102,241,136,136,136,216,237,81,0,160,129,141,
+ 216,221,29,103,206,55,51,23,188,136,136,136,221,17,2,18,220,141,139,221,24,54,51,51,51,243,17,241,187,139,221,28,
+ 9,25,219,184,187,216,28,51,51,51,51,51,99,23,187,187,216,24,10,21,221,184,187,251,241,51,51,51,51,51,51,22,
+ 187,187,216,29,42,250,221,187,75,17,55,51,51,247,55,51,51,23,187,187,219,205,145,202,141,187,203,97,51,51,22,17,
+ 17,54,51,23,187,187,139,237,145,234,141,187,203,97,51,51,23,188,28,55,51,23,188,187,139,237,145,234,141,187,75,17,
+ 54,51,31,187,27,63,51,22,65,187,139,237,81,234,141,187,187,28,103,102,23,188,28,103,102,118,193,187,139,237,81,202,
+ 141,187,187,27,103,102,22,17,17,102,102,102,193,187,139,237,81,250,141,187,187,27,103,102,102,247,103,102,102,23,65,187,
+ 139,205,81,21,136,75,68,20,103,102,102,102,102,102,246,241,68,68,139,248,154,25,139,72,68,20,119,102,102,102,102,102,
+ 22,79,68,68,136,24,154,18,140,72,68,244,17,241,102,102,102,102,23,68,68,68,136,28,149,160,129,184,68,68,68,31,
+ 103,102,247,119,23,68,68,180,136,17,37,144,193,136,68,68,68,20,113,23,17,17,241,68,68,132,232,161,5,0,26,139,
+ 72,68,68,68,17,17,76,68,68,68,68,136,24,81,9,0,18,129,136,68,68,68,252,79,68,68,68,68,132,136,31,90,
+ 2,0,80,241,136,72,68,68,68,68,68,68,68,68,136,200,161,149,0,0,0,26,143,136,75,68,68,68,68,68,68,139,
+ 136,28,81,37,0,0,0,162,17,139,136,75,68,68,68,68,139,136,251,17,85,2,0,0,0,32,26,193,136,136,184,187,
+ 187,136,136,200,17,90,37,0,0,0,0,0,82,17,193,139,136,136,136,136,203,17,161,85,2,0,0,0,0,0,32,169,
+ 17,17,207,238,206,28,17,161,85,41,0,0,0,0,0,0,0,32,85,170,17,17,17,161,90,85,37,0,0,0,0,0,
+ 0,0,0,0,32,89,85,85,85,85,85,41,0,0,0,0,0,0,0,0,0,0,0,0,34,34,34,34,2,0,0,0,
+ 0,0,0,0,0,0,0,0,32,89,187,187,187,91,41,0,0,0,0,0,0,0,0,0,0,144,27,17,170,204,172,26,
+ 17,155,0,0,0,0,0,0,0,0,32,27,161,60,51,51,51,51,173,17,43,0,0,0,0,0,0,0,25,161,61,51,
+ 51,51,51,51,51,163,17,5,0,0,0,0,0,80,17,60,51,211,221,221,221,221,51,51,29,177,0,0,0,0,0,21,
+ 218,51,211,221,221,221,221,221,221,51,51,26,11,0,0,0,144,161,51,211,221,221,221,221,221,221,221,221,51,163,81,0,
+ 0,0,18,209,51,221,51,51,51,221,221,221,221,221,61,51,17,9,0,0,27,60,211,51,51,51,51,211,221,221,221,221,
+ 221,51,29,11,0,144,161,51,61,51,51,51,51,51,125,119,119,119,119,61,163,81,0,176,209,211,55,51,51,195,17,17,
+ 17,113,119,119,119,215,51,17,2,18,58,115,215,51,51,195,97,102,70,113,119,119,119,119,51,26,9,25,60,125,119,61,
+ 51,195,241,255,79,113,119,119,119,119,61,29,11,21,51,119,119,119,221,205,241,255,79,17,17,17,122,119,55,19,43,171,
+ 51,119,119,119,119,135,241,255,79,65,68,164,113,119,55,163,145,171,211,119,119,170,170,26,241,255,79,241,255,79,113,119,
+ 215,195,145,203,211,119,135,65,68,164,241,255,79,241,255,79,113,119,215,195,145,203,211,119,135,97,102,70,97,102,70,97,
+ 102,70,113,119,215,195,81,203,211,119,135,225,102,70,97,102,70,97,102,70,113,119,215,195,81,171,211,119,135,225,102,70,
+ 97,102,70,97,102,70,113,119,215,195,81,171,221,136,136,225,102,70,97,102,70,97,102,70,129,136,216,173,81,21,221,135,
+ 136,225,238,78,225,238,78,225,238,78,129,136,215,29,155,25,220,135,136,225,238,78,225,238,78,225,238,78,129,136,215,29,
+ 155,18,218,141,136,225,238,78,225,238,78,225,238,78,129,136,221,26,149,176,209,125,136,65,68,164,65,68,164,65,68,164,
+ 129,120,221,17,37,144,161,221,136,17,17,17,17,17,17,17,17,17,129,216,205,177,5,0,27,220,141,136,136,136,136,136,
+ 136,136,136,136,136,221,29,81,9,0,18,209,221,136,136,136,136,136,136,136,136,136,216,221,26,91,2,0,80,161,221,141,
+ 136,136,136,136,136,136,136,136,221,173,177,149,0,0,0,27,218,221,135,136,136,136,136,136,136,215,221,26,81,37,0,0,
+ 0,178,17,220,221,135,136,136,136,136,215,221,28,17,85,2,0,0,0,32,27,161,221,221,125,119,119,221,221,173,17,91,
+ 37,0,0,0,0,0,82,17,161,220,221,221,221,221,172,17,177,85,2,0,0,0,0,0,32,185,17,17,170,204,172,26,
+ 17,177,85,41,0,0,0,0,0,0,0,32,85,187,17,17,17,177,91,85,37,0,0,0,0,0,0,0,0,0,32,89,
+ 85,85,85,85,85,41,0,0,0,0,0,0,0,0,0,0,0,0,34,34,34,34,2,0,0,0,0,0,0,0,0,0,
+ 0,0,32,89,170,170,170,90,41,0,0,0,0,0,0,0,0,0,0,144,26,17,236,190,235,28,17,154,0,0,0,0,
+ 0,0,0,0,32,26,225,251,255,255,255,255,232,17,42,0,0,0,0,0,0,0,25,225,255,255,255,255,255,255,255,239,
+ 17,5,0,0,0,0,0,80,17,251,255,255,136,136,136,248,255,255,200,161,0,0,0,0,0,21,252,255,143,136,136,136,
+ 136,136,136,255,255,28,10,0,0,0,144,193,255,143,136,136,136,184,68,132,136,136,255,207,81,0,0,0,18,241,255,248,
+ 255,235,206,17,193,17,136,136,248,255,28,9,0,0,26,251,143,255,191,17,124,187,51,27,140,136,136,255,24,10,0,144,
+ 225,255,248,255,239,60,51,51,51,115,193,136,136,248,239,81,0,160,129,143,248,255,31,55,51,51,51,51,23,65,136,136,
+ 255,17,2,18,254,143,248,255,27,59,51,189,215,51,179,65,136,136,255,30,9,25,251,136,136,248,28,51,115,17,193,51,
+ 51,236,136,136,248,24,10,21,255,136,136,136,124,51,29,140,28,59,211,225,136,136,248,31,42,202,255,136,136,136,177,221,
+ 29,68,28,221,125,65,136,136,248,239,145,234,255,136,136,136,193,221,23,30,113,221,205,140,136,136,248,239,145,234,143,68,
+ 68,68,30,17,17,193,219,221,22,78,68,68,132,191,145,234,143,68,68,68,228,238,28,215,221,221,23,68,68,68,132,191,
+ 81,234,143,68,68,68,68,68,206,221,221,198,17,68,68,68,132,191,81,234,143,68,68,68,68,68,30,221,125,17,76,68,
+ 68,68,132,239,81,202,255,68,68,68,68,68,206,102,198,76,68,68,68,68,244,239,81,21,255,68,68,68,68,68,30,102,
+ 22,78,68,68,68,68,244,207,154,25,251,72,68,68,68,68,28,108,28,76,68,68,68,68,248,24,154,18,254,72,68,68,
+ 68,68,204,102,198,76,68,68,68,68,248,30,149,160,129,143,68,68,68,68,124,102,118,76,68,68,68,132,143,17,37,144,
+ 225,136,68,68,68,68,204,102,198,76,68,68,68,132,232,161,5,0,26,139,72,68,68,68,28,124,28,76,68,68,68,136,
+ 27,81,9,0,18,129,136,68,68,68,196,204,204,68,68,68,132,136,28,90,2,0,80,193,136,72,68,68,68,68,68,68,
+ 68,68,136,200,161,149,0,0,0,26,140,136,75,68,68,68,68,68,68,139,136,28,81,37,0,0,0,162,193,139,136,75,
+ 68,68,68,68,139,136,203,17,85,2,0,0,0,32,26,225,136,136,136,187,139,136,136,232,17,90,37,0,0,0,0,0,
+ 82,17,225,139,136,136,136,136,235,17,161,85,2,0,0,0,0,0,32,169,17,17,236,238,238,204,17,161,85,41,0,0,
+ 0,0,0,0,0,32,85,170,17,17,17,161,90,85,37,0,0,0,0,0,0,0,0,0,32,89,85,85,85,85,85,41,
+ 0,0,0,0,0,0,0,0,0,0,0,0,34,34,34,34,2,0,0,0,0,0,0,0,0,0,0,0,90,136,136,136,
+ 88,10,0,0,0,0,0,0,0,0,32,21,17,125,238,126,29,17,37,0,0,0,0,0,0,0,21,209,62,51,51,51,
+ 51,222,17,5,0,0,0,0,0,128,17,62,51,51,51,51,51,51,220,129,2,0,0,0,0,24,253,51,147,153,153,153,
+ 153,51,51,23,40,0,0,0,128,113,51,147,153,153,153,153,153,153,51,115,129,0,0,0,21,61,51,57,51,147,153,153,
+ 153,153,57,51,23,5,0,32,17,63,51,51,51,51,147,153,153,153,153,63,211,161,0,80,225,51,63,51,51,115,17,158,
+ 153,153,153,57,243,129,0,16,61,147,63,51,51,23,215,158,153,153,153,153,51,23,10,26,62,159,57,51,211,113,219,158,
+ 153,153,153,153,63,28,5,21,63,153,153,255,29,183,219,71,68,68,196,153,57,19,40,216,51,204,204,220,113,187,219,17,
+ 17,17,225,204,252,115,161,120,243,204,204,29,183,187,187,187,187,187,237,204,252,227,161,232,243,204,220,113,187,187,187,187,
+ 187,187,237,204,156,227,81,232,147,204,220,189,187,187,187,187,187,187,237,204,156,227,81,232,243,204,220,225,102,102,102,102,
+ 102,102,237,204,156,227,81,120,255,204,76,17,103,102,102,102,102,102,237,204,252,239,81,216,255,204,204,212,113,102,214,17,
+ 17,17,225,204,252,127,81,21,255,76,68,68,29,103,214,231,238,238,78,68,252,31,88,26,254,76,68,68,212,113,214,71,
+ 68,68,68,68,252,28,168,16,253,79,68,68,68,29,29,71,68,68,68,68,255,23,165,80,225,255,68,68,68,212,17,71,
+ 68,68,68,196,207,129,37,32,209,255,76,68,68,68,68,68,68,68,68,252,223,81,5,0,21,247,207,68,68,68,68,68,
+ 68,68,196,255,23,88,10,0,128,113,255,76,68,68,68,68,68,68,252,127,17,85,0,0,32,24,247,255,76,68,68,68,
+ 68,252,255,23,81,37,0,0,0,138,209,254,255,204,76,196,252,255,220,17,85,10,0,0,0,160,24,209,254,255,255,255,
+ 255,126,17,88,165,0,0,0,0,0,82,24,17,125,238,126,23,17,88,85,10,0,0,0,0,0,32,90,136,17,17,17,
+ 129,88,85,42,0,0,0,0,0,0,0,32,90,85,85,85,85,85,42,0,0,0,0,0,0,0,0,0,0,34,170,170,
+ 42,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,114,119,68,68,68,68,68,116,119,34,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,114,68,68,68,68,68,68,68,68,68,68,68,116,
+ 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,71,68,68,68,189,251,255,255,255,255,187,77,
+ 68,68,68,39,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,71,68,68,180,31,17,241,255,255,255,255,
+ 17,17,191,77,68,68,39,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,71,68,68,251,17,241,156,153,153,153,
+ 153,153,153,249,17,241,75,68,68,7,0,0,0,0,0,0,0,0,0,0,0,0,0,114,68,68,27,17,159,153,153,153,
+ 153,153,153,153,153,153,153,31,17,75,68,68,2,0,0,0,0,0,0,0,0,0,0,0,32,68,68,253,17,159,153,153,
+ 153,153,153,153,153,153,153,153,153,153,28,17,75,68,116,0,0,0,0,0,0,0,0,0,0,0,71,68,180,17,159,153,
+ 153,153,153,153,153,153,153,153,153,153,153,153,153,31,241,68,68,7,0,0,0,0,0,0,0,0,0,112,68,212,31,145,
+ 153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,31,209,68,116,0,0,0,0,0,0,0,0,0,71,68,27,
+ 241,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,249,17,75,68,7,0,0,0,0,0,0,0,112,68,
+ 180,17,156,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,25,177,68,116,0,0,0,0,0,0,0,
+ 66,68,27,145,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,17,75,68,7,0,0,0,0,
+ 0,32,68,180,17,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,25,177,68,36,0,0,
+ 0,0,0,112,68,29,145,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,17,77,68,
+ 2,0,0,0,0,71,68,31,156,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,25,
+ 65,68,7,0,0,0,32,68,180,241,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,
+ 153,201,241,68,228,0,0,0,112,68,29,145,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,
+ 153,153,153,153,31,75,212,0,0,0,66,68,31,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,
+ 153,153,153,153,153,153,25,65,68,14,0,0,71,180,241,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,
+ 153,153,153,153,153,153,153,153,201,177,68,13,0,0,68,20,145,153,153,153,153,153,153,153,31,17,159,153,153,153,153,153,
+ 153,153,153,153,153,153,153,153,153,153,153,17,68,164,0,32,68,27,159,153,153,153,153,153,153,153,31,17,17,159,153,153,
+ 153,153,153,153,153,153,153,153,153,153,153,153,153,28,75,84,0,112,68,31,153,153,153,153,153,153,153,153,31,255,17,17,
+ 159,153,153,153,153,153,153,153,153,153,153,153,153,153,153,25,65,212,3,64,68,241,153,153,153,153,153,153,153,153,31,108,
+ 22,17,17,159,153,153,153,153,153,153,153,153,153,153,153,153,153,249,209,68,10,66,180,145,153,153,153,153,153,153,153,153,
+ 31,108,102,28,17,17,156,153,153,153,153,153,153,153,153,153,153,153,153,153,177,68,5,66,244,145,153,153,204,204,204,153,
+ 153,153,31,108,102,102,31,17,17,204,204,204,204,204,204,204,204,204,204,156,153,153,31,68,53,71,20,159,153,201,204,204,
+ 204,204,153,153,31,108,102,102,102,31,17,241,204,204,204,204,204,204,204,204,204,204,153,153,31,68,61,71,29,156,153,201,
+ 204,204,204,204,204,204,31,108,102,102,102,102,31,17,241,204,204,204,204,204,204,204,204,204,153,153,25,75,61,71,27,153,
+ 153,201,204,204,204,204,204,204,31,108,102,102,102,102,102,17,17,241,204,204,204,204,204,204,204,204,153,153,25,75,132,68,
+ 27,153,153,204,204,204,204,204,204,204,31,108,102,102,102,102,102,246,17,17,193,204,204,204,204,204,204,204,156,153,25,79,
+ 132,68,31,153,153,204,204,204,204,204,204,204,31,108,102,102,102,102,102,102,246,17,17,193,204,204,204,204,204,204,156,153,
+ 249,79,132,68,255,153,153,204,204,204,204,204,204,204,31,108,102,102,102,102,102,102,102,246,17,17,207,204,204,204,204,204,
+ 156,153,249,79,132,68,255,153,153,204,204,204,204,204,204,204,31,108,102,102,102,102,102,102,102,102,246,17,17,207,204,204,
+ 204,204,156,153,249,65,132,68,255,153,153,204,204,204,204,204,204,204,31,111,102,102,102,102,102,102,102,102,102,28,17,193,
+ 204,204,204,204,156,153,201,65,132,68,255,153,153,204,204,204,204,204,204,204,31,111,102,102,102,102,102,102,102,102,102,102,
+ 31,193,204,204,204,204,156,153,201,65,132,68,255,153,153,204,204,204,204,204,204,204,31,111,102,102,102,102,102,102,102,102,
+ 102,246,17,193,204,204,204,204,156,153,201,65,132,68,255,153,153,204,204,204,204,204,204,204,31,111,102,102,102,102,102,102,
+ 102,102,246,17,17,207,204,204,204,204,156,153,249,65,132,68,255,153,153,204,204,204,204,204,204,204,31,111,102,102,102,102,
+ 102,102,102,246,17,17,193,204,204,204,204,204,156,153,249,65,132,68,255,153,153,204,204,204,204,204,204,204,31,111,102,102,
+ 102,102,102,102,246,17,17,241,204,204,204,204,204,204,156,153,249,79,132,68,27,153,153,204,204,204,204,204,204,204,31,111,
+ 102,102,102,102,102,198,17,17,241,204,204,204,204,204,204,204,156,153,25,79,132,71,27,153,153,204,204,204,204,204,204,204,
+ 31,111,102,102,102,102,102,31,17,241,204,204,204,204,204,204,204,204,156,153,25,75,132,71,29,156,153,201,204,204,204,204,
+ 204,204,31,111,102,102,102,102,31,17,17,204,204,204,204,204,204,204,204,204,153,153,25,75,141,71,20,159,153,201,204,204,
+ 204,204,204,204,31,111,102,102,102,31,17,17,204,204,204,204,204,204,204,204,204,204,153,153,31,77,141,66,244,145,153,201,
+ 204,204,204,204,204,204,31,111,102,102,31,17,17,207,204,204,204,204,204,204,204,204,204,204,153,153,31,68,133,66,180,145,
+ 153,153,204,204,204,204,204,204,31,111,102,31,17,17,207,204,204,204,204,204,204,204,204,204,204,156,153,153,241,68,53,64,
+ 212,241,153,153,204,204,204,204,204,204,31,111,22,17,17,207,204,204,204,204,204,204,204,204,204,204,204,156,153,249,209,68,
+ 56,112,68,31,153,153,201,204,204,204,204,204,31,255,17,17,193,204,204,204,204,204,204,204,204,204,204,204,204,153,153,25,
+ 65,212,56,32,68,27,159,153,201,204,204,204,204,204,31,17,17,241,204,204,204,204,204,204,204,204,204,204,204,204,204,153,
+ 153,28,75,84,8,0,68,20,145,153,153,204,204,204,204,204,17,17,241,204,204,204,204,204,204,204,204,204,204,204,204,204,
+ 156,153,153,17,68,132,3,0,71,180,241,153,153,204,204,204,204,204,204,204,204,204,204,204,204,204,204,204,204,204,204,204,
+ 204,204,156,153,201,177,68,141,3,0,66,68,17,153,153,201,204,204,204,204,204,204,204,204,204,204,204,204,204,204,204,204,
+ 204,204,204,204,153,153,25,65,68,133,0,0,112,68,27,159,153,153,204,204,204,204,204,204,204,204,204,204,204,204,204,204,
+ 204,204,204,204,204,156,153,153,31,75,212,56,0,0,32,68,244,241,153,153,201,204,204,204,204,204,204,204,204,204,204,204,
+ 204,204,204,204,204,204,204,153,153,201,241,68,84,8,0,0,0,71,68,17,156,153,153,204,204,204,204,204,204,204,204,204,
+ 204,204,204,204,204,204,204,204,156,153,153,28,209,68,141,3,0,0,0,64,68,29,193,153,153,201,204,204,204,204,204,204,
+ 204,204,204,204,204,204,204,204,204,204,153,153,153,17,75,68,136,0,0,0,0,32,68,180,17,156,153,153,204,204,204,204,
+ 204,204,204,204,204,204,204,204,204,204,204,156,153,153,25,177,68,84,56,0,0,0,0,0,71,68,27,193,153,153,153,204,
+ 204,204,204,204,204,204,204,204,204,204,204,204,156,153,153,153,17,75,68,141,8,0,0,0,0,0,112,68,180,17,156,153,
+ 153,201,204,204,204,204,204,204,204,204,204,204,204,204,153,153,153,28,177,68,212,136,0,0,0,0,0,0,160,77,68,27,
+ 241,153,153,153,201,204,204,204,204,204,204,204,204,204,204,153,153,153,201,17,75,68,141,56,0,0,0,0,0,0,0,218,
+ 68,212,17,159,153,153,153,153,204,204,204,204,204,204,204,156,153,153,153,153,31,177,68,212,136,3,0,0,0,0,0,0,
+ 0,160,77,68,244,17,159,153,153,153,153,153,201,204,204,153,153,153,153,153,153,31,241,77,68,141,56,0,0,0,0,0,
+ 0,0,0,0,83,68,68,27,17,159,153,153,153,153,153,153,153,153,153,153,153,153,28,17,75,68,212,136,3,0,0,0,
+ 0,0,0,0,0,0,48,69,68,68,27,17,159,153,153,153,153,153,153,153,153,153,153,31,17,75,68,68,133,56,0,0,
+ 0,0,0,0,0,0,0,0,0,131,77,68,68,27,17,241,156,153,153,153,153,153,153,252,31,17,75,68,68,141,136,3,
+ 0,0,0,0,0,0,0,0,0,0,0,0,83,77,68,68,189,17,17,241,255,255,255,255,17,17,241,77,68,68,93,136,
+ 3,0,0,0,0,0,0,0,0,0,0,0,0,0,48,88,77,68,68,68,187,255,31,17,17,241,191,219,68,68,68,93,
+ 136,56,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,136,213,68,68,68,68,68,68,68,68,68,68,68,212,
+ 133,136,56,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,131,88,213,77,68,68,68,68,68,68,221,
+ 85,136,136,51,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,51,136,136,136,136,136,136,136,
+ 136,136,136,56,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,51,51,51,51,
+ 51,51,51,51,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,242,119,221,221,221,221,221,
+ 125,247,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,215,221,221,221,221,221,221,221,221,221,221,39,0,0,
+ 0,0,0,0,0,0,0,0,0,0,32,215,221,221,237,206,204,204,204,204,238,221,221,221,39,0,0,0,0,0,0,0,
+ 0,0,0,0,215,221,221,206,17,17,204,204,204,28,17,193,222,221,221,39,0,0,0,0,0,0,0,0,0,210,221,221,
+ 30,17,108,187,187,187,187,187,107,28,17,222,221,221,2,0,0,0,0,0,0,0,240,221,221,30,17,182,187,187,187,187,
+ 187,187,187,187,22,17,222,221,253,0,0,0,0,0,0,0,223,221,205,17,188,187,187,187,187,187,187,187,187,187,187,22,
+ 193,221,221,15,0,0,0,0,0,240,221,221,17,177,187,187,187,187,187,187,187,187,187,187,187,187,28,209,221,253,0,0,
+ 0,0,0,210,221,29,193,187,187,187,187,187,187,187,187,187,187,187,187,187,203,17,222,221,2,0,0,0,0,221,221,17,
+ 182,187,187,187,187,187,187,187,187,187,187,187,187,187,187,22,209,221,45,0,0,0,112,221,29,97,187,187,187,187,187,187,
+ 187,187,187,187,187,187,187,187,187,107,17,221,125,0,0,0,210,221,28,188,187,187,187,187,187,187,187,187,187,187,187,187,
+ 187,187,187,187,28,220,221,15,0,0,215,237,17,187,187,187,187,187,187,187,187,187,187,102,187,187,187,187,187,187,203,225,
+ 221,10,0,32,221,29,177,187,187,187,187,187,187,187,187,187,198,17,193,187,187,187,187,187,187,17,221,93,0,112,221,30,
+ 188,187,187,187,187,187,187,198,17,17,17,225,17,97,187,187,187,187,187,22,220,173,0,208,221,17,187,187,187,187,187,187,
+ 22,17,236,51,227,60,195,17,97,187,187,187,187,27,209,221,4,210,237,193,187,187,187,187,187,203,17,62,51,51,51,51,
+ 51,195,17,108,187,187,187,107,225,221,5,223,205,177,187,187,187,187,187,28,49,51,51,51,51,51,51,51,24,17,108,187,
+ 187,187,193,221,74,215,29,188,187,102,102,187,107,17,51,51,51,51,51,51,51,51,51,30,97,102,182,187,28,221,74,215,
+ 30,182,187,102,102,102,27,49,51,51,51,136,56,51,51,51,51,195,97,102,182,187,27,222,77,221,30,187,187,102,102,102,
+ 28,60,51,51,28,17,17,60,51,51,51,28,97,102,182,187,27,222,157,221,28,187,107,102,102,102,17,51,51,195,17,102,
+ 22,193,51,51,19,17,102,102,102,187,27,220,157,221,204,187,107,102,102,102,193,51,51,28,108,102,102,17,51,131,17,108,
+ 102,102,102,187,203,220,157,221,204,187,107,102,102,102,129,51,51,17,102,102,102,28,51,28,17,108,102,102,102,187,203,209,
+ 157,221,204,187,107,102,102,102,129,51,131,97,102,102,102,22,200,17,17,97,102,102,102,187,107,209,157,221,204,187,107,102,
+ 102,102,129,51,131,97,102,102,102,22,129,51,131,97,102,102,102,187,107,209,157,221,204,187,107,102,102,102,129,136,136,97,
+ 102,102,102,22,129,136,136,97,102,102,102,187,107,209,157,221,204,187,107,102,102,102,129,136,136,17,102,102,102,22,129,136,
+ 136,97,102,102,102,187,203,209,157,221,204,187,107,102,102,102,193,136,136,28,97,102,102,17,140,136,200,97,102,102,102,187,
+ 203,220,157,221,28,187,107,102,102,102,17,136,136,24,17,108,28,17,136,136,24,97,102,102,102,187,203,220,157,221,30,187,
+ 107,102,102,102,28,140,136,136,28,17,17,140,136,136,28,108,102,102,102,187,27,220,157,215,30,182,107,102,102,102,22,129,
+ 136,136,136,200,136,136,136,136,17,102,102,102,102,187,22,222,157,215,29,188,187,102,102,102,198,17,136,136,136,136,136,136,
+ 136,24,193,102,102,102,182,187,28,221,154,223,205,177,187,102,102,102,102,17,129,136,136,136,136,136,136,17,97,102,102,102,
+ 182,187,17,221,154,210,237,193,187,107,102,102,102,22,17,140,136,136,136,136,28,17,102,102,102,102,187,107,225,221,69,208,
+ 221,17,187,107,102,102,102,102,28,17,140,136,136,28,17,108,102,102,102,102,187,27,209,221,73,112,221,30,188,187,102,102,
+ 102,102,102,28,17,17,17,17,108,102,102,102,102,182,187,22,220,173,73,32,221,29,177,187,107,102,102,102,102,102,102,102,
+ 102,102,102,102,102,102,102,187,187,17,221,93,9,0,215,237,193,187,107,102,102,102,102,102,102,102,102,102,102,102,102,102,
+ 102,187,203,225,221,157,4,0,210,221,28,188,187,102,102,102,102,102,102,102,102,102,102,102,102,102,182,187,22,220,221,149,
+ 4,0,112,221,29,97,187,187,102,102,102,102,102,102,102,102,102,102,102,182,187,107,17,221,173,73,0,0,32,221,221,17,
+ 182,187,107,102,102,102,102,102,102,102,102,102,102,187,187,22,225,221,93,73,0,0,0,223,221,30,193,187,187,107,102,102,
+ 102,102,102,102,102,102,187,187,203,17,222,221,149,4,0,0,0,240,221,221,17,188,187,187,107,102,102,102,102,102,102,187,
+ 187,187,28,225,221,173,153,0,0,0,0,0,218,221,205,17,188,187,187,187,102,102,102,182,187,187,187,22,193,221,221,154,
+ 9,0,0,0,0,0,84,221,221,30,17,182,187,187,187,187,187,187,187,187,22,17,222,221,173,153,4,0,0,0,0,0,
+ 64,213,221,221,28,17,108,187,187,187,187,187,107,28,17,220,221,221,149,73,0,0,0,0,0,0,0,144,218,221,221,206,
+ 17,17,204,204,204,28,17,17,222,221,221,90,153,4,0,0,0,0,0,0,0,0,84,218,221,221,237,206,28,17,17,204,
+ 236,221,221,221,93,153,4,0,0,0,0,0,0,0,0,0,64,89,218,221,221,221,221,221,221,221,221,221,221,90,153,73,
+ 0,0,0,0,0,0,0,0,0,0,0,64,153,165,218,221,221,221,221,221,221,170,149,153,73,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,64,148,153,153,153,153,153,153,153,153,153,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,64,68,68,68,68,68,68,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,242,119,238,238,238,
+ 238,238,126,247,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,231,238,238,238,238,238,238,238,238,238,238,39,
+ 0,0,0,0,0,0,0,0,0,0,0,0,32,231,238,238,238,221,204,204,204,220,221,238,238,238,39,0,0,0,0,0,
+ 0,0,0,0,0,0,231,238,238,205,17,17,204,102,198,28,17,193,237,238,238,39,0,0,0,0,0,0,0,0,0,226,
+ 238,238,29,17,108,187,187,187,187,187,107,28,17,237,238,238,2,0,0,0,0,0,0,0,240,238,238,29,17,182,187,187,
+ 187,187,187,187,187,187,22,17,237,238,254,0,0,0,0,0,0,0,239,238,206,17,182,187,187,187,187,187,187,187,187,187,
+ 187,22,193,238,238,15,0,0,0,0,0,240,238,238,28,188,187,187,187,187,187,187,187,187,187,187,187,187,28,225,238,254,
+ 0,0,0,0,0,226,238,30,193,187,187,187,187,187,187,187,187,187,187,187,187,187,107,17,237,238,2,0,0,0,0,238,
+ 238,17,182,187,187,187,187,187,187,187,187,187,187,187,187,187,187,22,225,238,46,0,0,0,112,238,206,97,187,187,187,187,
+ 187,187,187,187,187,187,187,187,187,187,187,107,17,238,126,0,0,0,226,238,28,188,187,187,187,187,187,187,187,187,187,187,
+ 187,187,187,187,187,187,22,236,238,15,0,0,231,222,193,187,187,187,187,187,187,187,187,187,187,187,187,187,187,187,187,187,
+ 203,209,238,10,0,32,238,30,177,187,187,187,187,187,187,187,187,187,187,187,187,187,187,187,187,187,187,17,238,94,0,112,
+ 238,29,182,187,187,187,187,198,108,187,187,187,107,102,102,102,102,182,187,187,187,22,237,174,0,224,238,17,187,187,187,187,
+ 27,193,28,17,17,17,17,17,17,17,17,97,187,187,187,203,225,238,4,226,222,97,187,187,187,187,28,61,211,17,51,51,
+ 51,51,51,51,51,97,187,187,187,107,209,238,5,239,206,177,187,187,187,187,204,51,51,28,51,51,51,51,51,51,51,97,
+ 187,187,187,187,193,238,74,231,30,188,187,187,187,187,204,51,51,28,51,51,51,51,51,51,51,97,187,187,187,187,28,238,
+ 74,231,30,182,187,102,102,102,28,51,51,17,51,51,51,51,51,51,51,97,102,102,182,187,27,237,78,238,29,187,187,102,
+ 102,102,28,140,200,17,204,204,204,204,204,204,204,97,102,102,182,187,27,237,158,238,29,187,107,102,102,102,198,17,17,204,
+ 204,204,204,204,204,204,204,108,102,102,102,187,203,236,158,238,204,187,107,102,102,102,22,17,17,17,17,17,17,17,17,17,
+ 17,97,102,102,102,187,203,236,158,238,204,187,107,102,102,102,28,60,195,17,136,136,136,136,136,136,136,97,102,102,102,187,
+ 203,225,158,238,204,187,107,102,102,102,193,51,51,28,51,51,51,51,51,51,131,97,102,102,102,187,107,225,158,238,204,187,
+ 107,102,102,102,193,51,51,28,51,51,51,51,51,51,131,97,102,102,102,187,107,225,158,238,204,187,107,102,102,102,193,51,
+ 51,28,51,51,51,51,51,51,131,97,102,102,102,187,107,225,158,238,204,187,107,102,102,102,28,140,200,17,136,136,136,136,
+ 136,136,136,97,102,102,102,187,107,225,158,238,204,187,107,102,102,102,22,17,17,17,17,17,17,17,17,17,17,97,102,102,
+ 102,187,203,236,158,238,29,187,107,102,102,102,198,17,17,204,204,204,204,204,204,204,204,108,102,102,102,187,203,236,158,238,
+ 29,187,107,102,102,102,28,140,200,17,204,204,204,204,204,204,204,97,102,102,102,187,27,237,158,231,29,182,107,102,102,102,
+ 17,136,136,17,136,136,136,136,136,136,136,97,102,102,102,187,22,237,158,231,30,188,187,102,102,102,193,136,136,28,136,136,
+ 136,136,136,136,136,97,102,102,182,187,28,238,154,239,206,177,187,102,102,102,193,136,136,28,136,136,136,136,136,136,136,97,
+ 102,102,182,187,193,238,154,226,222,97,187,107,102,102,17,136,136,17,136,136,136,136,136,136,136,97,102,102,187,107,209,238,
+ 69,224,238,17,187,107,102,102,22,17,17,17,17,17,17,17,17,17,17,97,102,102,187,203,225,238,73,112,238,29,182,187,
+ 102,102,102,204,204,102,102,102,102,102,102,102,102,102,102,182,187,22,236,174,73,32,238,30,177,187,107,102,102,102,102,102,
+ 102,102,102,102,102,102,102,102,102,187,187,17,238,94,9,0,231,222,193,187,187,102,102,102,102,102,102,102,102,102,102,102,
+ 102,102,182,187,203,209,238,158,4,0,226,238,28,188,187,102,102,102,102,102,102,102,102,102,102,102,102,102,182,187,22,236,
+ 238,149,4,0,112,238,30,97,187,187,102,102,102,102,102,102,102,102,102,102,102,182,187,107,17,238,174,73,0,0,32,238,
+ 238,17,182,187,107,102,102,102,102,102,102,102,102,102,102,187,187,22,209,238,94,73,0,0,0,239,238,29,193,187,187,107,
+ 102,102,102,102,102,102,102,102,187,187,107,17,237,238,149,4,0,0,0,240,238,238,17,188,187,187,107,102,102,102,102,102,
+ 102,187,187,187,28,209,238,174,153,0,0,0,0,0,234,238,206,17,182,187,187,187,102,102,102,182,187,187,187,22,193,238,
+ 238,154,9,0,0,0,0,0,84,238,238,29,17,182,187,187,187,187,187,187,187,187,198,17,237,238,174,153,4,0,0,0,
+ 0,0,64,229,238,238,29,17,108,187,187,187,187,187,107,28,17,236,238,238,149,73,0,0,0,0,0,0,0,144,234,238,
+ 238,205,17,193,204,102,198,204,17,193,237,238,238,90,153,4,0,0,0,0,0,0,0,0,84,234,238,238,222,205,28,17,
+ 17,204,221,238,238,238,94,153,4,0,0,0,0,0,0,0,0,0,64,89,234,238,238,238,238,238,238,238,238,238,238,90,
+ 153,73,0,0,0,0,0,0,0,0,0,0,0,64,153,165,234,238,238,238,238,238,238,170,149,153,73,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,64,148,153,153,153,153,153,153,153,153,153,68,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,64,68,68,68,68,68,68,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,210,119,255,
+ 255,255,255,255,127,215,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,247,255,255,255,255,255,255,255,255,255,
+ 255,39,0,0,0,0,0,0,0,0,0,0,0,0,32,247,255,255,79,187,170,170,170,186,75,255,255,255,39,0,0,0,
+ 0,0,0,0,0,0,0,0,247,255,255,171,17,17,170,102,166,26,17,161,251,255,255,39,0,0,0,0,0,0,0,0,
+ 0,242,255,255,27,17,106,204,204,204,204,204,108,26,17,251,255,255,2,0,0,0,0,0,0,0,208,255,255,27,17,198,
+ 204,204,204,204,204,204,204,204,22,17,251,255,223,0,0,0,0,0,0,0,253,255,175,17,198,204,204,204,204,204,204,204,
+ 204,204,204,22,161,255,255,13,0,0,0,0,0,208,255,255,26,202,204,204,204,204,204,204,204,204,204,204,204,204,26,65,
+ 255,223,0,0,0,0,0,242,255,20,161,204,204,204,204,204,204,204,204,204,204,204,204,204,108,17,244,255,2,0,0,0,
+ 0,255,255,17,198,204,204,204,204,204,204,102,198,204,204,204,204,204,204,22,65,255,47,0,0,0,112,255,175,97,204,204,
+ 204,204,204,204,108,17,97,204,204,204,204,204,204,108,17,255,127,0,0,0,242,255,26,202,204,204,204,204,204,204,28,177,
+ 17,204,204,204,204,204,204,204,22,250,255,13,0,0,247,191,161,204,204,204,204,204,204,204,22,202,27,202,204,204,204,204,
+ 204,204,172,177,255,9,0,32,255,31,193,204,204,204,204,204,204,204,17,206,20,97,204,204,204,204,204,204,204,17,255,95,
+ 0,112,255,27,202,204,204,204,204,204,204,172,97,206,180,161,204,204,204,204,204,204,204,22,251,159,0,240,255,17,204,204,
+ 204,204,204,204,204,28,225,206,68,26,198,204,204,204,204,204,204,28,241,255,3,242,191,97,204,204,204,204,204,204,204,17,
+ 238,206,68,20,193,204,204,204,204,204,204,108,177,255,5,253,175,193,204,204,204,204,204,204,108,161,238,206,68,180,161,204,
+ 204,204,204,204,204,204,161,255,57,247,31,202,204,204,204,204,204,204,28,225,238,206,68,68,17,198,204,204,204,204,204,204,
+ 26,255,57,247,20,198,204,102,102,102,204,204,26,230,238,206,68,68,27,106,102,102,102,102,198,204,28,251,63,255,27,204,
+ 204,102,102,102,102,102,17,238,238,206,68,68,164,97,102,102,102,102,198,204,28,251,143,255,27,204,108,102,102,102,102,22,
+ 225,238,238,206,68,68,68,17,102,102,102,102,102,204,172,250,143,255,170,204,108,102,102,102,102,26,234,238,238,206,68,68,
+ 68,26,106,102,102,102,102,204,172,250,143,255,170,204,108,102,102,102,102,17,238,238,238,206,68,68,68,20,97,102,102,102,
+ 102,204,172,241,143,255,170,204,108,102,102,102,166,97,238,238,238,206,68,68,68,180,161,102,102,102,102,204,108,241,143,255,
+ 170,204,108,102,102,102,166,225,238,238,238,238,68,68,68,68,161,102,102,102,102,204,108,241,143,255,170,204,108,102,102,102,
+ 166,161,102,102,102,230,238,238,238,110,161,102,102,102,102,204,108,241,143,255,170,204,108,102,102,102,102,17,102,102,102,230,
+ 238,238,238,30,97,102,102,102,102,204,172,241,143,255,170,204,108,102,102,102,102,26,106,102,102,230,238,238,238,26,106,102,
+ 102,102,102,204,172,250,143,255,27,204,108,102,102,102,102,22,97,102,102,230,238,238,238,17,102,102,102,102,102,204,172,250,
+ 143,255,27,204,108,102,102,102,102,102,17,102,102,230,238,238,174,161,102,102,102,102,102,204,28,251,143,247,20,198,108,102,
+ 102,102,102,102,26,106,102,230,238,238,22,97,102,102,102,102,102,204,22,251,143,247,31,202,204,102,102,102,102,102,22,97,
+ 102,230,238,238,17,102,102,102,102,102,198,204,26,244,137,253,175,193,204,102,102,102,102,102,166,161,102,230,238,174,161,102,
+ 102,102,102,102,198,204,17,255,137,242,191,97,204,108,102,102,102,102,102,17,102,230,238,30,97,102,102,102,102,102,204,108,
+ 177,255,53,240,255,17,204,108,102,102,102,102,102,26,97,230,238,26,106,102,102,102,102,102,204,172,241,255,56,112,255,27,
+ 202,204,102,102,102,102,102,22,161,230,110,17,102,102,102,102,102,198,204,22,250,159,56,32,255,31,193,204,108,102,102,102,
+ 102,102,17,230,30,97,102,102,102,102,102,204,204,17,244,95,8,0,247,191,161,204,204,102,102,102,102,102,26,234,26,106,
+ 102,102,102,102,198,204,172,177,255,143,3,0,242,255,26,202,204,102,102,102,102,102,22,97,17,102,102,102,102,102,198,204,
+ 22,250,255,133,3,0,112,255,31,97,204,204,102,102,102,102,166,17,161,102,102,102,102,198,204,108,17,244,159,56,0,0,
+ 32,255,79,17,198,204,108,102,102,102,102,170,106,102,102,102,102,204,204,22,65,255,95,56,0,0,0,253,255,20,161,204,
+ 204,108,102,102,102,102,102,102,102,102,204,204,108,17,251,255,133,3,0,0,0,208,255,79,17,202,204,204,108,102,102,102,
+ 102,102,102,204,204,204,26,65,255,159,136,0,0,0,0,0,249,255,175,17,198,204,204,204,102,102,102,198,204,204,204,22,
+ 161,244,255,137,8,0,0,0,0,0,83,255,255,27,17,198,204,204,204,204,204,204,204,204,166,17,251,255,159,136,3,0,
+ 0,0,0,0,48,245,255,255,27,17,106,204,204,204,204,204,108,26,17,74,255,255,133,56,0,0,0,0,0,0,0,128,
+ 249,255,255,171,17,17,170,170,170,170,17,17,251,255,255,89,136,3,0,0,0,0,0,0,0,0,83,249,255,255,191,171,
+ 26,17,17,170,187,244,255,255,95,136,3,0,0,0,0,0,0,0,0,0,48,88,249,255,255,255,255,255,255,255,255,255,
+ 255,89,136,56,0,0,0,0,0,0,0,0,0,0,0,48,136,149,249,255,255,255,255,255,255,153,133,136,56,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,48,131,136,136,136,136,136,136,136,136,136,51,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,48,51,51,51,51,51,51,51,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,242,
+ 136,68,68,68,68,68,132,248,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,72,68,68,68,68,68,68,68,
+ 68,68,68,40,0,0,0,0,0,0,0,0,0,0,0,0,32,72,68,68,212,170,238,238,238,174,218,68,68,68,40,0,
+ 0,0,0,0,0,0,0,0,0,0,72,68,68,237,17,17,238,170,234,30,17,225,77,68,68,40,0,0,0,0,0,0,
+ 0,0,0,66,68,68,26,17,174,187,187,187,187,187,171,30,17,74,68,68,2,0,0,0,0,0,0,0,240,68,68,29,
+ 17,186,187,187,187,187,187,187,187,187,26,17,77,68,244,0,0,0,0,0,0,0,79,68,164,17,186,187,187,187,187,187,
+ 187,187,187,187,187,26,225,68,68,15,0,0,0,0,0,240,68,68,30,190,187,187,187,187,187,187,187,187,187,187,187,187,
+ 30,209,68,244,0,0,0,0,0,66,68,29,225,187,187,187,187,187,187,187,187,187,187,187,187,187,171,17,77,68,2,0,
+ 0,0,0,68,68,17,186,187,187,187,187,187,187,119,183,187,187,187,187,187,187,26,209,68,36,0,0,0,128,68,228,161,
+ 187,187,187,187,187,187,119,17,225,183,187,187,187,187,187,171,17,68,132,0,0,0,66,68,26,190,187,187,187,187,171,30,
+ 17,204,28,17,126,187,187,187,187,187,26,78,68,15,0,0,72,212,225,187,187,187,187,171,17,108,102,102,102,102,28,225,
+ 187,187,187,187,235,161,68,4,0,32,68,20,177,187,187,187,235,17,108,102,102,102,102,102,102,28,113,187,187,187,187,17,
+ 68,84,0,128,68,26,186,187,187,187,17,108,102,102,102,102,102,102,102,102,17,183,187,187,187,26,74,212,0,64,68,17,
+ 187,187,187,235,97,102,102,102,28,17,17,108,102,102,22,113,187,187,187,235,65,68,3,66,212,161,187,187,187,27,108,102,
+ 102,28,113,183,173,30,108,102,102,17,187,187,187,171,161,68,5,79,228,177,187,187,187,26,102,102,102,17,119,183,68,164,
+ 17,108,102,22,190,187,187,187,225,68,61,72,20,190,187,187,123,193,102,102,102,22,126,183,68,212,17,193,102,198,113,187,
+ 187,187,26,68,61,72,29,186,187,187,235,97,102,102,102,102,225,183,68,68,26,17,102,102,225,187,187,187,27,77,52,68,
+ 26,187,187,119,23,108,102,28,102,102,22,190,68,68,228,17,108,102,28,119,183,187,27,74,148,68,26,187,123,119,23,102,
+ 102,17,97,102,102,225,77,68,212,17,97,102,22,119,119,187,235,78,148,68,238,187,123,119,23,102,198,17,17,102,102,22,
+ 222,68,68,26,193,102,22,119,119,187,235,78,148,68,238,187,123,119,23,102,22,17,231,97,102,102,225,77,68,29,17,102,
+ 22,119,119,187,171,65,148,68,174,187,123,119,206,102,22,113,119,30,102,102,22,222,68,164,17,102,198,126,119,187,171,65,
+ 148,68,174,187,123,119,206,102,22,113,119,23,97,102,102,225,187,187,17,102,198,126,119,187,171,65,148,68,174,187,123,119,
+ 206,102,22,225,119,119,17,102,102,22,126,119,17,102,198,126,119,187,171,65,148,68,238,187,123,119,30,102,22,17,119,119,
+ 23,97,102,102,225,23,17,102,22,126,119,187,171,65,148,68,238,187,123,119,23,102,198,17,126,119,119,17,102,102,22,17,
+ 193,102,22,119,119,187,235,78,148,68,26,187,123,119,23,102,102,17,113,119,119,23,97,102,102,17,97,102,22,119,119,187,
+ 235,78,148,68,26,187,123,119,23,108,102,28,17,119,119,119,30,102,102,22,108,102,28,119,119,187,27,74,148,72,29,186,
+ 187,119,231,97,102,22,17,126,119,119,231,97,102,102,102,102,225,119,183,187,26,77,148,72,20,190,187,119,119,193,102,198,
+ 17,113,119,119,119,30,102,102,102,198,113,119,183,187,26,68,157,79,228,177,187,119,119,30,102,102,28,225,119,119,119,23,
+ 97,102,102,22,126,119,183,187,225,68,157,66,212,161,187,123,119,23,97,102,102,28,225,119,119,17,108,102,102,28,119,119,
+ 187,171,161,68,53,64,68,17,187,123,119,119,17,102,102,102,28,17,17,108,102,102,102,17,119,119,187,235,65,68,57,128,
+ 68,26,186,187,119,119,23,97,102,102,102,102,102,102,102,102,28,113,119,183,187,26,74,212,57,32,68,20,177,187,123,119,
+ 119,17,108,102,102,102,102,102,102,28,17,119,119,187,187,17,68,84,9,0,72,212,225,187,187,119,119,231,17,108,102,102,
+ 102,102,28,225,119,119,183,187,235,161,68,148,3,0,66,68,30,190,187,123,119,119,231,17,17,204,28,17,225,119,119,119,
+ 187,187,26,78,68,149,3,0,128,68,20,161,187,187,119,119,119,119,238,17,225,126,119,119,119,183,187,171,17,68,212,57,
+ 0,0,32,68,212,17,186,187,123,119,119,119,119,238,126,119,119,119,119,187,187,26,209,68,84,57,0,0,0,79,68,29,
+ 225,187,187,123,119,119,119,119,119,119,119,119,187,187,171,17,77,68,149,3,0,0,0,240,68,212,17,190,187,187,123,119,
+ 119,119,119,119,119,187,187,187,30,209,68,212,153,0,0,0,0,0,72,68,228,17,186,187,187,187,123,119,119,187,187,187,
+ 187,26,225,68,68,157,9,0,0,0,0,0,83,68,68,26,17,186,187,187,187,187,187,187,187,187,234,17,74,68,212,153,
+ 3,0,0,0,0,0,48,69,68,68,26,17,174,187,187,187,187,187,171,30,17,74,68,68,149,57,0,0,0,0,0,0,
+ 0,144,77,68,68,234,17,225,238,170,234,238,17,225,74,68,68,93,153,3,0,0,0,0,0,0,0,0,83,77,68,68,
+ 212,234,30,17,17,238,218,68,68,68,84,153,3,0,0,0,0,0,0,0,0,0,48,89,77,68,68,68,68,68,68,68,
+ 68,68,68,93,153,57,0,0,0,0,0,0,0,0,0,0,0,48,153,213,77,68,68,68,68,68,68,221,149,153,57,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,48,147,153,153,153,153,153,153,153,153,153,51,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,48,51,51,51,51,51,51,51,0,0,0,0,0,0,0,0,0,0,0,0,0,32,85,153,
+ 153,153,165,0,0,0,0,0,0,0,0,160,25,209,247,255,215,17,89,0,0,0,0,0,0,32,25,241,238,238,238,238,
+ 254,29,169,0,0,0,0,0,26,241,238,238,238,238,238,238,254,17,5,0,0,0,160,17,232,238,142,136,136,136,238,238,
+ 216,81,0,0,0,18,129,238,142,136,136,136,136,136,232,142,29,10,0,0,25,232,238,238,238,142,215,77,136,136,238,24,
+ 33,0,160,241,238,238,126,119,23,113,17,136,136,232,254,81,0,144,225,142,238,30,119,221,59,27,77,136,136,238,29,2,
+ 18,239,142,238,24,60,51,51,243,17,113,136,238,31,5,21,232,136,136,29,51,51,51,51,179,215,136,232,30,41,213,238,
+ 136,31,241,51,51,60,51,51,215,136,232,126,41,121,142,136,29,59,51,219,209,59,51,125,136,136,254,161,249,142,136,125,
+ 204,204,29,23,205,204,29,132,136,254,161,249,142,68,29,203,108,113,116,97,204,27,77,132,254,81,249,142,68,20,205,204,
+ 29,23,205,204,124,77,132,254,81,121,142,68,116,205,204,219,209,203,204,27,77,132,254,81,217,142,68,212,103,102,102,102,
+ 102,118,17,79,132,126,89,21,232,68,212,189,102,102,102,102,22,77,68,228,24,169,26,239,72,116,17,113,102,102,102,27,
+ 79,68,232,31,169,144,141,72,68,244,29,107,27,113,29,68,68,136,29,37,80,241,136,68,68,20,113,17,221,221,68,132,
+ 248,145,37,0,25,143,72,68,116,17,77,68,68,68,136,24,81,10,0,26,141,136,68,68,68,68,68,68,132,136,29,89,
+ 2,0,80,209,136,136,68,68,68,68,68,136,216,145,165,0,0,0,21,241,136,136,68,68,132,136,248,17,89,37,0,0,
+ 0,82,17,253,136,136,136,136,248,29,145,85,2,0,0,0,32,154,17,209,247,255,119,17,145,85,42,0,0,0,0,0,
+ 32,85,153,17,17,145,153,85,165,0,0,0,0,0,0,0,32,90,85,85,85,85,170,2,0,0,0,0,0,0,0,0,
+ 0,34,34,34,34,0,0,0,0,0,0,0,0,162,181,187,187,165,2,0,0,0,0,0,80,17,129,248,143,17,81,2,
+ 0,0,0,32,27,241,119,119,119,247,24,33,0,0,0,18,129,119,119,119,119,119,247,17,10,0,0,27,127,119,221,221,
+ 221,125,119,31,33,0,80,129,119,119,119,215,221,221,125,247,177,0,18,113,119,247,255,255,68,68,221,119,24,2,26,127,
+ 125,23,204,28,204,28,221,125,29,11,21,119,221,29,51,30,62,19,221,125,23,43,139,215,68,20,51,30,62,19,68,212,
+ 135,161,139,215,68,20,51,30,62,19,68,212,247,161,139,215,68,20,153,30,158,25,68,212,247,161,139,215,68,20,153,22,
+ 150,25,68,212,247,161,139,221,68,20,153,22,150,25,68,212,141,161,21,221,68,20,153,22,150,25,68,212,29,171,26,223,
+ 77,20,204,28,204,28,68,212,31,171,18,209,77,132,136,136,136,136,68,221,24,165,80,129,221,68,68,68,68,68,212,253,
+ 177,37,32,17,223,77,68,68,68,68,221,31,81,10,0,26,129,221,77,68,68,221,253,17,85,2,0,160,17,248,221,221,
+ 221,253,24,81,165,0,0,0,186,17,129,248,136,17,177,85,10,0,0,0,32,181,27,17,17,187,85,165,0,0,0,0,
+ 0,162,85,85,85,85,165,2,0,0,0,0,0,0,32,34,34,34,0,0,0,0,0,0,0,0,0,0,0,0,0,114,
+ 119,215,0,0,0,0,0,0,0,0,208,30,17,39,0,0,0,0,0,0,0,32,31,17,139,222,0,0,0,0,0,0,
+ 0,233,17,56,131,222,0,0,0,0,0,0,64,17,81,51,131,222,0,0,0,0,0,144,30,129,60,51,131,222,0,0,
+ 0,0,0,20,17,53,51,51,131,222,0,0,0,0,121,17,184,51,195,60,131,222,0,0,0,64,17,81,51,51,108,60,
+ 131,222,0,0,32,23,129,59,51,108,102,60,131,222,0,0,29,17,53,51,108,102,102,60,131,222,0,114,17,184,51,195,
+ 102,102,102,60,131,222,208,30,81,60,195,102,102,102,102,60,131,222,20,17,59,51,102,102,102,102,102,54,131,222,31,200,
+ 51,108,102,102,102,102,102,54,131,222,31,197,204,108,170,170,170,170,170,198,140,222,20,129,203,204,166,170,170,170,170,198,
+ 140,222,240,17,81,204,204,170,170,170,170,198,140,222,32,228,17,184,204,108,170,170,170,198,140,222,0,208,23,17,197,204,
+ 172,170,170,198,140,222,0,0,73,30,129,203,204,170,170,202,140,222,0,0,32,125,17,81,204,108,170,202,140,222,0,0,
+ 0,144,20,17,184,204,172,202,140,222,0,0,0,0,210,23,17,197,204,198,140,222,0,0,0,0,0,249,17,129,203,204,
+ 140,222,0,0,0,0,0,32,237,17,81,204,140,222,0,0,0,0,0,0,144,31,17,184,140,222,0,0,0,0,0,0,
+ 0,210,30,129,133,222,0,0,0,0,0,0,0,0,249,17,17,222,0,0,0,0,0,0,0,0,32,228,238,215,15,0,
+ 0,0,0,0,0,0,0,0,0,58,0,0,0,0,0,0,0,0,0,0,170,12,0,0,0,0,0,0,0,0,0,170,
+ 90,0,0,0,0,0,0,0,0,0,170,218,8,0,0,0,0,0,0,0,0,170,170,45,0,0,0,0,0,0,0,0,
+ 170,170,122,0,0,0,0,0,0,0,0,170,170,170,12,0,0,0,0,0,0,0,170,170,170,202,0,0,0,0,0,0,
+ 0,170,170,170,170,5,0,0,0,0,0,0,170,170,170,170,141,0,0,0,0,0,0,170,170,170,170,218,2,0,0,0,
+ 0,0,170,170,170,170,170,7,0,0,0,0,0,170,170,170,170,170,202,0,0,0,0,0,170,170,170,170,170,170,5,0,
+ 0,0,0,170,170,170,170,170,170,81,0,0,0,0,170,170,170,170,170,170,218,8,0,0,0,170,170,170,170,170,170,170,
+ 45,0,0,0,170,170,170,170,170,170,170,122,0,0,0,170,170,170,170,170,170,170,170,12,0,0,170,170,170,170,170,170,
+ 170,170,81,0,0,170,170,170,170,170,170,170,170,26,5,0,170,170,170,170,170,170,170,170,170,141,0,170,170,170,170,170,
+ 170,170,170,170,218,2,17,17,17,17,17,17,17,17,17,225,6,17,17,17,17,17,17,17,17,17,97,102,17,17,17,17,
+ 17,17,17,17,17,100,102,17,17,17,17,17,17,17,17,65,102,6,17,17,17,17,17,17,17,17,107,102,2,17,17,17,
+ 17,17,17,17,225,102,38,0,17,17,17,17,17,17,17,110,102,2,0,17,17,17,17,17,17,209,102,102,0,0,17,17,
+ 17,17,17,17,65,102,6,0,0,17,17,17,17,17,17,100,102,0,0,0,17,17,17,17,17,177,102,38,0,0,0,17,
+ 17,17,17,17,110,102,2,0,0,0,17,17,17,17,225,102,38,0,0,0,0,17,17,17,17,110,102,6,0,0,0,0,
+ 17,17,17,17,100,102,0,0,0,0,0,17,17,17,65,102,6,0,0,0,0,0,17,17,17,107,102,2,0,0,0,0,
+ 0,17,17,225,102,38,0,0,0,0,0,0,17,17,110,102,2,0,0,0,0,0,0,17,225,102,102,0,0,0,0,0,
+ 0,0,17,65,102,6,0,0,0,0,0,0,0,17,100,102,0,0,0,0,0,0,0,0,145,102,38,0,0,0,0,0,
+ 0,0,0,7,102,2,0,0,0,0,0,0,0,0,0,38,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,179,198,204,204,102,3,0,0,0,0,0,0,0,203,17,127,231,119,31,193,11,0,0,0,
+ 0,0,99,17,135,136,136,136,136,23,193,3,0,0,0,48,28,143,136,136,136,136,136,136,23,49,0,0,0,195,113,136,
+ 136,136,136,136,136,136,232,17,3,0,0,22,135,136,136,136,136,136,136,136,136,30,12,0,176,241,136,136,136,136,136,136,
+ 136,136,136,120,177,0,192,65,136,136,136,136,136,136,136,136,136,136,193,0,19,135,136,136,136,136,136,136,136,136,136,136,
+ 30,11,27,132,136,136,34,136,136,136,40,130,136,136,20,6,246,136,136,40,34,130,136,136,34,34,136,136,248,12,124,136,
+ 136,152,159,130,136,136,146,159,136,136,120,12,124,68,68,248,241,130,68,132,242,241,72,68,228,1,124,68,68,152,159,130,
+ 68,132,146,159,72,68,228,1,124,68,68,36,34,72,68,68,40,34,68,68,228,1,124,68,68,68,136,68,68,68,132,72,
+ 68,68,116,1,246,68,68,68,255,255,255,255,255,79,68,68,244,12,22,68,68,68,31,17,17,17,17,79,68,68,20,6,
+ 19,71,68,68,30,161,85,165,17,78,68,68,30,11,192,65,68,68,228,95,85,85,239,68,68,68,17,0,176,241,68,68,
+ 68,228,221,237,68,68,68,116,97,0,0,28,71,68,68,68,68,68,68,68,68,30,12,0,0,19,113,68,68,68,68,68,
+ 68,68,228,17,3,0,0,48,17,79,68,68,68,68,68,68,23,177,0,0,0,0,195,17,71,68,68,68,68,30,193,3,
+ 0,0,0,0,0,203,17,127,238,126,31,17,6,0,0,0,0,0,0,0,107,204,17,17,108,11,0,0,0,0,0,0,
+ 0,0,147,165,170,170,85,3,0,0,0,0,0,0,0,169,17,209,238,222,17,161,9,0,0,0,0,0,83,17,78,187,
+ 187,187,187,30,161,3,0,0,0,48,26,191,187,187,187,187,187,187,31,58,0,0,0,163,225,187,187,187,187,187,187,187,
+ 235,161,3,0,0,21,190,187,139,187,187,187,187,187,187,30,10,0,144,241,187,136,136,136,187,187,187,187,187,251,145,0,
+ 160,65,187,136,136,136,184,187,187,187,187,75,161,0,19,183,187,136,136,136,187,187,187,187,187,187,30,9,25,68,68,180,
+ 136,187,68,68,139,184,68,68,20,5,21,68,68,43,34,66,68,68,34,34,75,68,244,10,250,68,68,104,109,178,68,180,
+ 98,109,72,68,116,10,122,68,68,216,209,130,68,132,210,209,72,68,228,10,122,68,68,107,109,178,68,180,98,109,75,68,
+ 228,10,122,68,68,132,34,72,68,68,40,130,68,68,228,10,250,68,68,68,75,68,68,68,68,75,68,68,116,10,21,68,
+ 68,68,17,17,17,17,17,65,68,68,244,10,21,204,204,204,31,17,17,17,17,207,204,204,28,5,19,199,204,204,28,17,
+ 17,17,17,204,204,204,23,9,160,193,204,204,124,17,17,17,113,204,204,204,17,0,144,241,204,204,204,124,255,127,204,204,
+ 204,252,81,0,0,26,199,204,204,204,204,204,204,204,204,23,10,0,0,163,113,204,204,204,204,204,204,204,124,17,3,0,
+ 0,48,26,207,204,204,204,204,204,204,31,145,0,0,0,0,163,17,199,204,204,204,204,23,161,3,0,0,0,0,0,169,
+ 17,255,119,247,31,17,5,0,0,0,0,0,0,0,89,170,170,170,90,9,0,0,0,0,0,0,0,0,147,165,170,170,
+ 85,3,0,0,0,0,0,0,0,169,17,177,119,119,27,161,9,0,0,0,0,0,83,17,199,136,136,136,200,23,161,3,
+ 0,0,0,48,26,203,136,136,136,136,136,200,27,49,0,0,0,163,113,136,136,136,136,136,136,136,120,17,3,0,0,21,
+ 135,136,216,136,136,136,136,136,136,23,10,0,144,177,136,221,221,221,136,136,136,136,136,184,145,0,160,193,136,221,221,221,
+ 141,136,136,136,136,200,161,0,19,135,136,221,221,221,136,136,136,136,136,136,23,9,25,140,136,136,221,136,136,136,216,141,
+ 136,136,28,5,21,255,255,40,34,130,255,143,34,34,248,255,191,10,186,255,255,109,107,130,255,143,98,107,253,255,127,10,
+ 122,255,255,189,177,210,255,223,178,177,253,255,239,1,122,255,255,104,107,130,255,143,98,107,248,255,239,1,122,255,255,223,
+ 34,253,255,255,45,210,255,255,239,1,186,255,255,255,136,255,255,255,143,248,255,255,127,1,181,255,255,255,255,255,255,255,
+ 255,255,255,255,191,10,21,244,255,255,255,255,255,255,255,255,255,255,20,5,19,71,68,68,30,17,17,17,17,78,68,68,
+ 30,9,160,65,68,68,190,187,187,187,187,78,68,68,17,0,144,177,68,68,68,68,68,68,68,68,68,116,81,0,0,26,
+ 71,68,68,68,68,68,68,68,68,30,10,0,0,19,113,68,68,68,68,68,68,68,228,17,3,0,0,48,17,75,68,68,
+ 68,68,68,68,23,145,0,0,0,0,163,17,71,68,68,68,68,30,161,3,0,0,0,0,0,169,17,123,238,126,27,17,
+ 5,0,0,0,0,0,0,0,89,170,17,17,90,9,0,0,0,0,0,0,0,0,163,181,187,187,85,3,0,0,0,0,
+ 0,0,0,186,17,209,232,216,17,177,10,0,0,0,0,0,83,17,72,68,68,68,68,24,177,3,0,0,0,48,27,77,
+ 68,68,68,68,68,68,29,59,0,0,0,179,209,68,68,68,68,68,68,68,212,177,3,0,0,21,216,78,119,71,68,68,
+ 68,68,222,24,11,0,160,209,212,225,119,119,71,68,68,228,209,212,161,0,176,65,228,17,126,119,71,68,68,30,225,68,
+ 177,0,19,72,68,20,225,119,68,68,228,17,78,68,24,10,26,78,68,228,153,78,68,68,158,233,68,68,20,5,21,68,
+ 68,36,34,236,68,228,44,34,68,68,212,11,219,68,68,151,157,98,78,110,146,157,71,68,132,11,139,68,68,215,209,98,
+ 77,109,210,209,71,68,132,11,139,68,68,148,157,66,72,72,146,157,68,68,228,11,139,255,255,207,34,247,255,255,39,194,
+ 255,255,143,11,219,255,255,255,68,255,255,255,79,244,255,255,143,11,21,255,255,255,255,255,255,255,255,255,255,255,223,11,
+ 21,255,255,255,255,216,17,209,248,255,255,255,31,5,19,248,255,255,223,17,17,17,209,255,255,255,24,10,176,241,255,255,
+ 29,17,17,17,17,253,255,255,17,0,160,209,255,255,17,17,17,17,17,241,255,143,81,0,0,27,248,255,255,255,255,255,
+ 255,255,255,24,11,0,0,179,129,255,255,255,255,255,255,255,143,17,3,0,0,48,27,253,255,255,255,255,255,255,29,161,
+ 0,0,0,0,179,17,248,255,255,255,255,24,177,3,0,0,0,0,0,186,17,141,136,136,29,17,5,0,0,0,0,0,
+ 0,0,90,187,187,187,91,10,0,0,0,0,0,0,0,0,163,197,204,204,85,3,0,0,0,0,0,0,0,202,17,97,
+ 255,111,27,193,10,0,0,0,0,0,83,17,230,119,119,119,231,25,193,3,0,0,0,48,28,235,119,119,119,119,119,119,
+ 22,49,0,0,0,195,177,119,119,119,119,119,119,119,103,17,3,0,0,21,182,127,221,125,119,119,119,119,191,31,12,0,
+ 160,177,183,241,221,221,119,119,119,247,177,103,161,0,192,225,135,17,223,221,125,119,119,31,129,231,193,0,19,118,119,24,
+ 241,221,119,119,247,17,120,119,25,10,26,116,119,135,136,120,119,119,143,136,119,119,30,5,21,119,119,39,34,253,119,247,
+ 45,34,119,119,183,12,108,238,238,141,139,98,239,111,130,139,237,238,158,12,156,238,238,189,177,98,230,102,178,177,237,238,
+ 254,1,156,238,238,135,139,226,233,233,130,139,231,238,254,1,156,238,238,222,34,237,238,238,45,210,238,238,254,1,108,238,
+ 238,238,231,238,238,238,238,231,238,238,158,1,181,238,238,238,238,238,238,238,238,238,238,238,190,12,21,228,238,238,126,253,
+ 134,246,125,238,238,238,20,5,19,73,68,68,100,178,43,187,98,68,68,68,25,10,192,65,68,68,22,27,177,17,27,70,
+ 68,68,17,0,160,177,68,68,17,17,17,17,17,65,68,100,81,0,0,28,73,68,68,68,68,68,68,68,68,25,12,0,
+ 0,19,145,68,68,68,68,68,68,68,148,17,3,0,0,48,17,75,68,68,68,68,68,68,22,161,0,0,0,0,195,17,
+ 73,68,68,68,68,25,193,3,0,0,0,0,0,202,17,155,153,153,27,17,5,0,0,0,0,0,0,0,90,204,17,17,
+ 92,10,0,0,0,0,0,0,0,68,2,0,0,0,0,64,209,4,0,0,0,0,160,85,10,0,0,0,0,25,59,145,
+ 0,0,105,26,129,51,24,161,150,217,190,51,51,51,235,157,162,189,51,51,51,219,42,32,218,247,255,127,173,2,0,18,
+ 254,255,239,33,0,0,18,247,119,127,33,0,0,217,199,17,124,157,0,0,217,29,68,209,157,0,0,66,36,0,66,36,
+ 0,0,0,0,0,0,68,2,0,0,0,0,0,0,0,0,144,17,4,0,0,0,0,0,0,0,0,112,92,13,0,0,
+ 0,0,0,0,0,0,25,58,145,0,0,0,0,0,0,0,0,132,51,120,0,0,0,0,0,0,0,32,225,51,30,2,
+ 0,0,0,0,0,0,64,49,51,19,4,0,0,0,153,73,68,212,60,51,195,77,68,148,153,129,200,92,229,58,51,163,
+ 94,197,140,24,129,250,255,255,255,255,255,255,255,175,24,217,168,255,255,255,255,255,255,255,138,157,32,29,254,255,255,255,
+ 255,255,239,209,2,0,114,81,255,255,255,255,255,21,39,0,0,0,20,245,255,255,255,95,65,0,0,0,0,16,107,102,
+ 102,102,182,1,0,0,0,0,25,102,102,102,102,102,145,0,0,0,0,132,102,102,187,102,102,72,0,0,0,0,199,102,
+ 198,17,108,102,124,0,0,0,0,177,182,24,68,129,107,27,0,0,0,144,177,28,151,0,114,193,27,9,0,0,144,17,
+ 77,0,0,0,212,17,9,0,0,32,68,2,0,0,0,32,68,2,0,0,0,0,187,187,2,0,0,0,32,244,167,122,
+ 65,2,0,0,251,55,51,51,163,191,0,32,175,51,51,51,51,248,2,64,55,51,195,60,51,163,9,240,204,204,220,205,
+ 204,204,33,123,204,204,92,197,204,204,103,123,204,93,85,85,213,204,106,123,204,220,85,85,205,204,106,123,221,221,85,85,
+ 221,221,103,18,221,221,213,93,221,221,33,64,222,221,221,221,221,237,9,32,239,221,221,221,221,21,11,0,251,94,85,85,
+ 229,97,0,0,32,25,238,238,145,11,0,0,0,32,102,102,2,0,0,0,0,0,153,153,2,0,0,0,32,180,111,134,
+ 209,12,0,0,185,56,51,51,99,155,0,32,107,51,51,51,51,186,12,64,56,51,163,58,51,99,14,176,170,170,106,166,
+ 170,170,193,249,170,170,138,168,170,170,88,137,170,246,255,255,111,170,86,137,170,106,248,143,166,170,88,249,170,170,248,143,
+ 170,170,95,18,102,102,111,246,102,102,193,208,111,102,102,102,102,134,7,192,139,102,102,102,102,24,9,0,185,111,102,102,
+ 246,81,0,0,192,30,255,255,113,9,0,0,0,192,85,85,12,0,0,0,0,0,0,0,32,119,119,2,0,0,0,0,
+ 0,0,0,0,0,183,161,217,157,26,123,0,0,0,0,0,0,0,103,138,51,51,51,51,168,118,0,0,0,0,0,64,
+ 129,51,51,51,51,51,51,24,11,0,0,0,0,171,60,51,51,51,51,51,51,51,186,0,0,0,64,202,51,51,51,51,
+ 51,51,51,51,163,11,0,0,23,60,51,51,51,51,60,51,51,51,195,65,0,0,214,51,51,51,51,195,62,51,51,51,
+ 51,24,0,112,202,204,204,204,204,236,197,204,204,204,204,172,4,176,205,204,204,204,204,92,197,204,204,204,204,140,6,16,
+ 204,204,204,204,204,94,229,204,204,204,204,204,33,162,204,204,204,204,238,85,85,238,204,204,204,204,121,151,204,204,236,85,
+ 85,85,85,85,85,206,204,204,73,151,204,204,204,94,85,85,85,85,229,204,204,204,77,151,204,204,204,236,85,85,85,85,
+ 206,204,204,204,77,151,238,238,238,238,94,85,85,229,238,238,238,238,73,162,238,238,238,238,94,85,85,229,238,238,238,238,
+ 121,16,238,238,238,238,85,85,85,85,238,238,238,238,33,176,237,238,238,238,85,229,94,85,238,238,238,222,6,112,234,238,
+ 238,238,229,238,238,94,238,238,238,174,4,0,214,238,238,238,238,238,238,238,238,238,238,21,2,0,23,229,238,238,238,238,
+ 238,238,238,238,238,65,0,0,176,90,238,238,238,238,238,238,238,238,174,6,0,0,0,171,85,85,85,85,85,85,85,85,
+ 106,2,0,0,0,176,81,85,85,85,85,85,85,21,38,0,0,0,0,0,20,250,85,85,85,85,165,65,0,0,0,0,
+ 0,0,0,100,161,255,255,26,70,2,0,0,0,0,0,0,0,0,114,68,68,39,0,0,0,0,0,0,0,0,0,0,
+ 208,119,119,13,0,0,0,0,0,0,0,0,0,167,155,238,238,185,202,0,0,0,0,0,0,0,103,81,51,51,51,51,
+ 152,203,0,0,0,0,0,64,81,51,51,51,51,51,51,24,10,0,0,0,0,26,63,51,51,51,51,51,51,243,169,0,
+ 0,0,64,241,51,51,51,51,51,51,51,51,159,10,0,0,23,63,51,51,51,243,63,51,51,51,243,193,0,0,86,255,
+ 255,255,255,143,245,255,255,255,255,184,0,112,241,255,255,255,255,239,254,255,255,255,255,159,12,160,254,255,255,255,255,152,
+ 137,255,255,255,255,95,6,176,248,255,255,255,255,149,233,255,255,255,255,255,33,29,255,255,136,136,136,153,153,136,136,136,
+ 255,255,121,151,136,136,232,153,153,153,153,153,153,142,136,136,206,151,136,136,136,149,153,153,153,153,89,136,136,136,206,151,
+ 136,136,136,88,153,153,153,153,133,136,136,136,206,151,136,136,136,136,149,153,153,89,136,136,136,136,201,29,136,136,136,136,
+ 158,153,153,233,136,136,136,136,121,176,85,85,85,85,153,153,153,153,85,85,85,85,33,160,94,85,85,85,153,94,229,153,
+ 85,85,85,229,6,192,81,85,85,229,233,85,85,158,94,85,85,149,4,0,235,85,85,229,85,85,85,85,94,85,85,190,
+ 2,0,28,94,85,85,85,85,85,85,85,85,229,65,0,0,160,225,238,238,238,238,238,238,238,238,30,6,0,0,0,26,
+ 238,238,238,238,238,238,238,238,97,2,0,0,0,160,145,238,238,238,238,238,238,30,38,0,0,0,0,0,188,145,238,238,
+ 238,238,25,75,0,0,0,0,0,0,0,108,17,153,153,17,70,2,0,0,0,0,0,0,0,0,114,204,204,39,0,0,
+ 0,0,0,116,119,119,119,119,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,55,51,51,51,51,11,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,55,51,51,51,51,11,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,247,255,255,255,255,11,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,167,170,170,170,170,11,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,167,170,170,170,170,11,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,231,238,238,238,238,11,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,231,238,238,238,238,11,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,103,102,102,102,102,11,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 103,102,102,102,102,11,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,183,187,187,187,187,113,119,119,119,119,7,
+ 0,0,0,0,0,0,0,0,0,0,39,34,34,34,34,57,51,51,51,51,11,0,0,0,0,0,0,0,0,0,0,39,
+ 34,34,34,34,57,51,51,51,51,11,0,0,0,0,0,0,0,0,0,0,215,221,221,221,221,249,255,255,255,255,11,0,
+ 0,0,0,0,0,0,0,0,0,215,221,221,221,221,169,170,170,170,170,11,0,0,0,0,0,0,0,0,0,0,135,136,
+ 136,136,136,169,170,170,170,170,11,0,0,0,0,0,0,0,0,0,0,135,136,136,136,136,233,238,238,238,238,11,0,0,
+ 0,0,0,0,0,0,0,0,199,204,204,204,204,233,238,238,238,238,11,0,0,0,0,0,0,0,0,0,0,199,204,204,
+ 204,204,105,102,102,102,102,11,0,0,0,0,0,0,0,0,0,0,87,85,85,85,85,105,102,102,102,102,11,0,0,0,
+ 0,0,0,0,0,0,0,151,153,153,153,153,177,187,187,187,187,113,119,119,119,119,7,0,0,0,0,0,55,51,51,51,
+ 51,43,34,34,34,34,57,51,51,51,51,11,0,0,0,0,0,55,51,51,51,51,43,34,34,34,34,57,51,51,51,51,
+ 11,0,0,0,0,0,247,255,255,255,255,219,221,221,221,221,249,255,255,255,255,11,0,0,0,0,0,167,170,170,170,170,
+ 219,221,221,221,221,169,170,170,170,170,11,0,0,0,0,0,167,170,170,170,170,139,136,136,136,136,169,170,170,170,170,11,
+ 0,0,0,0,0,231,238,238,238,238,139,136,136,136,136,233,238,238,238,238,11,0,0,0,0,0,231,238,238,238,238,203,
+ 204,204,204,204,233,238,238,238,238,11,0,0,0,0,0,103,102,102,102,102,203,204,204,204,204,105,102,102,102,102,11,0,
+ 0,0,0,0,103,102,102,102,102,91,85,85,85,85,105,102,102,102,102,11,0,0,0,0,0,183,187,187,187,187,145,153,
+ 153,153,153,177,187,187,187,187,113,119,119,119,119,7,39,34,34,34,34,57,51,51,51,51,43,34,34,34,34,57,51,51,
+ 51,51,11,39,34,34,34,34,57,51,51,51,51,43,34,34,34,34,57,51,51,51,51,11,215,221,221,221,221,249,255,255,
+ 255,255,219,221,221,221,221,249,255,255,255,255,11,215,221,221,221,221,169,170,170,170,170,219,221,221,221,221,169,170,170,170,
+ 170,11,135,136,136,136,136,169,170,170,170,170,139,136,136,136,136,169,170,170,170,170,11,135,136,136,136,136,233,238,238,238,
+ 238,139,136,136,136,136,233,238,238,238,238,11,199,204,204,204,204,233,238,238,238,238,203,204,204,204,204,233,238,238,238,238,
+ 11,199,204,204,204,204,105,102,102,102,102,203,204,204,204,204,105,102,102,102,102,11,87,85,85,85,85,105,102,102,102,102,
+ 91,85,85,85,85,105,102,102,102,102,11,151,153,153,153,153,177,187,187,187,187,145,153,153,153,153,177,187,187,187,187,1,
+ 195,204,204,204,204,204,204,204,204,3,172,221,221,221,221,221,221,102,102,5,220,34,34,34,34,34,98,17,17,5,220,34,
+ 34,34,34,34,23,143,31,5,220,34,34,34,34,34,145,136,24,5,220,34,34,34,34,162,225,136,31,5,220,34,34,34,
+ 34,22,143,232,17,5,220,103,102,39,210,177,238,174,218,5,108,161,171,113,23,233,238,25,215,5,108,225,238,17,161,238,
+ 190,209,210,5,108,65,238,20,65,238,27,118,215,5,108,161,68,68,75,68,161,119,215,5,108,29,73,68,68,20,113,119,
+ 215,5,108,215,145,68,68,25,125,119,215,5,108,119,22,73,148,209,119,119,215,5,108,119,167,145,25,122,119,119,103,5,
+ 108,119,119,166,106,119,119,119,103,5,172,102,102,102,102,102,102,102,166,5,83,85,85,85,85,85,85,85,85,3,146,153,
+ 153,153,153,153,153,153,153,14,249,170,170,170,170,170,170,170,218,4,169,51,51,51,51,51,51,51,83,4,169,51,51,51,
+ 51,51,51,51,83,4,169,51,51,51,51,51,51,51,83,4,169,204,204,204,204,204,204,204,92,4,121,204,204,204,204,204,
+ 204,204,92,4,121,204,204,204,204,204,204,204,92,4,121,204,204,204,204,204,204,204,172,4,121,102,102,102,102,102,102,102,
+ 166,4,121,102,102,102,102,102,102,102,166,4,121,102,102,102,102,102,102,102,166,4,121,102,102,102,102,102,102,102,166,4,
+ 217,102,102,102,102,102,102,102,166,4,217,187,187,187,187,187,187,187,123,4,217,187,187,187,187,187,187,187,123,4,217,187,
+ 187,187,187,187,187,187,123,4,25,119,119,119,119,119,119,119,247,4,78,68,68,68,68,68,68,68,68,8,0,231,5,250,
+ 7,248,5,246,3,211,1,250,4,232,3,0,0,0,1,0,211,158,48,79,0,250,250,195,29,0,250,250,248,53,2,211,
+ 175,190,252,95,0,144,111,143,191,0,243,40,175,175,0,232,1,248,45,0,16,0,0,0,230,4,248,6,245,3,48,0,
+ 209,9,246,8,252,4,254,2,255,1,254,2,251,5,245,8,160,7,244,4,243,12,224,47,192,79,176,95,192,79,224,31,
+ 243,10,195,2,0,34,0,0,187,0,115,221,55,180,238,75,0,187,0,0,119,0,49,0,250,3,248,5,226,1,50,0,
+ 65,36,246,239,64,36,49,0,250,4,232,3,0,68,0,174,64,95,144,31,224,11,244,6,249,1,189,0,74,0,128,238,
+ 9,246,238,127,250,86,191,251,69,207,250,87,191,245,238,127,128,238,9,32,251,5,243,255,8,178,252,8,0,249,8,0,
+ 249,8,177,253,157,226,255,223,195,239,26,230,252,111,0,160,127,0,245,46,80,239,3,243,223,107,244,255,159,195,239,26,
+ 229,236,143,32,199,111,96,255,62,0,148,175,231,236,175,196,239,42,0,193,13,0,250,31,96,255,31,226,248,31,250,252,
+ 175,182,251,175,0,192,13,245,255,79,248,189,43,248,189,8,247,255,143,98,113,191,233,236,143,196,239,25,80,252,109,243,
+ 207,157,249,137,6,251,255,143,250,90,207,245,189,175,112,254,27,249,255,175,182,235,191,0,225,79,0,249,10,48,255,2,
+ 176,159,0,208,29,0,161,254,59,248,188,175,245,188,143,227,255,111,250,38,239,250,155,223,161,254,60,161,239,7,249,219,
+ 95,251,166,175,247,255,191,96,152,159,217,252,63,230,207,5,232,3,250,4,98,0,250,4,232,3,213,207,4,218,253,12,
+ 0,248,9,0,143,0,0,24,0,96,127,0,80,110,0,0,226,12,0,0,250,111,0,48,191,222,0,160,79,248,6,242,
+ 255,255,13,250,138,200,95,219,1,48,126,245,255,174,1,247,140,253,7,248,74,252,5,248,255,223,1,248,74,249,10,247,
+ 140,251,10,245,255,191,2,32,233,223,5,209,239,236,8,245,30,0,0,247,12,0,0,245,30,0,0,209,239,236,8,32,
+ 234,223,5,245,255,174,2,247,189,254,29,248,9,209,111,248,9,144,127,248,9,209,111,247,189,254,29,245,255,174,2,245,
+ 255,159,247,140,72,248,74,20,248,255,127,248,74,20,247,140,72,245,255,159,245,255,159,247,140,72,248,74,20,248,255,127,
+ 248,74,20,248,9,0,245,6,0,32,234,223,8,209,239,236,11,245,29,67,2,247,9,255,14,246,12,195,15,209,239,236,
+ 15,32,234,223,8,245,6,160,46,248,9,208,79,248,140,232,79,248,255,255,79,248,74,212,79,248,9,208,79,245,6,160,
+ 46,245,6,248,9,248,9,248,9,248,9,248,9,245,6,0,232,3,0,251,5,0,251,5,0,251,5,0,251,5,177,255,
+ 4,226,158,0,245,6,228,9,248,41,254,6,248,218,127,0,248,255,30,0,248,202,191,0,248,41,253,8,245,6,211,11,
+ 245,6,0,248,9,0,248,9,0,248,9,0,248,9,0,248,189,107,245,255,159,229,7,0,233,3,248,47,64,255,5,248,
+ 191,192,255,5,248,255,251,255,5,248,234,207,251,5,248,89,62,251,5,229,6,0,233,3,229,6,208,12,248,79,241,15,
+ 248,239,244,15,248,253,253,15,248,153,255,15,248,9,251,15,229,6,193,13,32,234,207,4,209,223,252,79,245,12,128,191,
+ 247,9,64,207,245,12,128,191,209,223,252,79,32,234,207,4,245,255,174,1,248,140,253,7,248,9,249,8,248,255,255,3,
+ 248,140,55,0,248,9,0,0,245,6,0,0,32,234,207,4,209,223,252,79,245,12,128,191,247,9,64,207,245,12,128,191,
+ 209,223,252,79,32,234,255,10,0,0,226,111,0,0,64,110,245,255,174,1,248,140,253,7,248,9,249,8,248,255,255,3,
+ 248,204,159,0,248,41,254,4,245,6,230,7,112,253,142,0,245,206,221,0,247,92,2,0,210,255,175,0,16,99,254,4,
+ 248,205,255,3,180,254,92,0,253,255,255,9,185,254,189,6,0,251,5,0,0,251,5,0,0,251,5,0,0,251,5,0,
+ 0,232,3,0,245,6,208,12,248,9,241,15,248,9,241,15,248,9,241,15,247,11,243,14,243,207,254,10,80,252,174,1,
+ 234,2,96,78,249,9,224,63,242,31,246,11,160,143,252,4,48,255,207,0,0,251,95,0,0,227,11,0,231,5,226,8,
+ 192,12,246,11,248,30,243,12,241,31,253,95,249,6,160,175,207,191,254,1,80,255,63,253,175,0,0,254,13,247,79,0,
+ 0,231,6,209,12,0,229,7,228,8,243,111,254,6,96,255,175,0,0,253,31,0,96,255,175,0,243,95,253,7,229,6,
+ 227,9,232,4,232,4,247,93,239,2,192,255,111,0,32,254,10,0,0,251,5,0,0,251,5,0,0,232,3,0,249,255,
+ 223,1,182,235,239,1,0,227,95,0,16,253,7,0,193,159,0,0,248,207,187,1,247,255,239,2,0,178,187,59,241,255,
+ 47,240,255,31,208,255,14,176,255,13,160,255,11,128,255,9,80,187,6,0,0,0,32,185,6,209,255,63,243,255,63,192,
+ 255,10,0,51,0,0,179,254,141,1,0,112,170,154,0,0,0,0,80,255,255,255,28,0,224,255,111,0,0,0,0,225,
+ 255,206,255,143,0,245,255,13,0,0,0,0,246,255,2,249,239,0,250,255,5,32,52,0,0,248,223,0,245,255,17,254,
+ 207,64,252,255,110,0,247,239,0,246,255,81,255,79,243,255,255,255,6,243,255,89,253,207,160,255,10,252,239,216,255,30,
+ 176,255,255,255,79,241,255,18,255,111,32,255,95,16,251,255,239,6,246,159,48,255,63,0,254,111,0,48,119,22,0,251,
+ 30,16,255,111,32,255,95,0,0,0,0,16,255,8,0,252,239,200,255,30,0,0,0,0,96,239,1,0,243,255,255,255,
+ 6,0,0,0,0,176,110,0,0,64,252,255,110,0,0,0,0,0,0,0,0,0,0,32,52,0,0,180,187,6,244,255,
+ 7,242,255,6,240,255,4,208,255,2,176,255,1,32,68,0,0,0,16,3,0,80,252,15,0,248,255,15,96,255,255,13,
+ 225,255,223,1,245,255,95,0,248,255,14,0,250,255,11,0,250,255,11,0,248,255,13,0,243,255,111,0,176,255,255,9,
+ 16,253,255,31,0,145,255,31,0,0,81,7,48,1,0,0,240,207,5,0,240,255,143,0,208,255,255,6,16,253,255,30,
+ 0,245,255,95,0,224,255,143,0,176,255,175,0,176,255,175,0,208,255,143,0,246,255,63,144,255,255,11,241,255,223,1,
+ 241,255,25,0,112,21,0,0,0,65,52,0,0,0,243,175,0,0,0,243,175,0,0,184,252,239,187,3,251,255,255,255,
+ 4,251,255,255,255,4,67,246,207,68,1,0,243,175,0,0,0,178,139,0,0,64,68,52,241,255,191,241,255,191,241,255,
+ 191,0,251,175,96,255,111,241,255,11,176,89,0,64,68,68,3,241,255,255,14,241,255,255,14,241,255,255,14,64,68,68,
+ 3,16,118,2,192,255,30,245,255,95,245,255,63,209,255,9,0,35,0,0,181,187,155,0,248,255,159,0,251,255,95,0,
+ 254,255,31,16,255,255,12,64,255,255,8,112,255,255,4,144,255,255,1,192,255,191,0,224,255,127,0,242,255,63,0,245,
+ 255,14,0,247,255,10,0,0,32,216,255,157,2,0,0,229,255,255,255,94,0,48,255,255,255,255,255,3,176,255,255,221,
+ 255,255,12,242,255,239,17,254,255,47,245,255,175,0,250,255,95,246,255,159,0,249,255,111,245,255,175,0,250,255,95,242,
+ 255,239,17,253,255,47,192,255,255,221,255,255,12,64,255,255,255,255,255,4,0,247,255,255,255,127,0,0,64,252,255,207,
+ 4,0,0,0,16,51,1,0,0,0,0,48,186,1,0,64,251,255,1,64,252,255,255,1,251,255,255,255,1,253,255,255,
+ 255,1,253,255,255,255,1,188,246,255,255,1,1,241,255,255,1,0,241,255,255,1,0,241,255,255,1,0,241,255,255,1,
+ 0,241,255,255,1,0,241,255,255,1,0,32,200,254,174,4,0,0,248,255,255,255,143,0,176,255,255,255,255,255,4,245,
+ 255,255,255,255,255,8,176,239,23,226,255,255,9,32,44,0,208,255,255,5,0,0,0,248,255,207,0,0,0,144,255,255,
+ 28,0,0,16,251,255,175,1,0,0,210,255,255,191,187,8,64,254,255,255,255,255,11,128,255,255,255,255,255,11,128,255,
+ 255,255,255,255,11,96,187,187,187,187,187,91,128,255,255,255,255,255,127,128,255,255,255,255,255,7,96,187,187,255,255,78,
+ 0,0,0,194,255,223,2,0,0,0,252,255,255,174,2,0,0,228,255,255,255,46,0,0,0,64,254,255,143,0,72,0,
+ 0,250,255,191,80,255,157,152,255,255,175,209,255,255,255,255,255,111,210,255,255,255,255,255,11,0,181,254,255,255,108,0,
+ 0,0,32,67,19,0,0,0,0,161,187,187,187,9,0,0,248,255,255,255,12,0,64,255,255,255,255,12,0,209,255,255,
+ 255,255,12,0,249,255,175,255,255,12,64,255,255,120,255,255,12,209,255,223,112,255,255,12,248,255,175,184,255,255,125,250,
+ 255,255,255,255,255,223,250,255,255,255,255,255,223,250,255,255,255,255,255,223,66,68,68,148,255,255,61,0,0,0,112,255,
+ 255,12,0,179,187,187,187,187,27,0,247,255,255,255,255,13,0,250,255,255,255,255,10,0,253,255,105,102,102,3,32,255,
+ 255,103,53,0,0,80,255,255,255,255,126,0,80,254,255,255,255,255,9,0,97,70,148,255,255,47,0,20,0,16,255,255,
+ 95,48,255,139,200,255,255,79,192,255,255,255,255,255,30,244,255,255,255,255,255,5,48,217,255,255,239,42,0,0,0,49,
+ 52,2,0,0,0,0,182,254,174,4,0,0,210,255,255,255,175,0,16,253,255,255,255,255,8,144,255,255,140,253,191,6,
+ 225,255,223,0,81,1,0,244,255,223,185,155,22,0,246,255,255,255,255,239,5,246,255,255,187,254,255,30,244,255,255,1,
+ 247,255,95,225,255,255,7,242,255,95,96,255,255,175,250,255,47,0,247,255,255,255,255,7,0,48,250,255,255,92,0,0,
+ 0,16,67,19,0,0,130,136,136,136,136,136,72,244,255,255,255,255,255,111,244,255,255,255,255,255,30,227,255,255,255,255,
+ 255,7,0,0,0,160,255,239,1,0,0,0,245,255,143,0,0,0,32,254,255,30,0,0,0,176,255,255,8,0,0,0,
+ 247,255,255,2,0,0,48,255,255,159,0,0,0,192,255,255,47,0,0,0,248,255,255,9,0,0,64,255,255,255,2,0,
+ 0,16,34,34,34,0,0,0,0,113,235,255,189,22,0,48,254,255,255,255,223,1,176,255,255,255,255,255,8,208,255,239,
+ 84,255,255,10,160,255,239,49,255,255,8,32,252,255,237,255,191,1,16,248,255,255,255,127,0,176,255,239,118,255,255,8,
+ 243,255,191,0,253,255,31,245,255,239,152,255,255,47,243,255,255,255,255,255,31,160,255,255,255,255,255,7,0,198,255,255,
+ 255,92,0,0,0,49,68,18,0,0,0,113,236,239,124,1,0,64,254,255,255,255,78,0,225,255,239,253,255,255,3,245,
+ 255,79,128,255,255,12,246,255,127,16,255,255,63,243,255,239,136,254,255,95,144,255,255,255,255,255,95,0,165,253,239,255,
+ 255,79,0,0,1,0,253,255,31,48,200,175,148,255,255,10,176,255,255,255,255,239,2,32,254,255,255,255,78,0,0,145,
+ 254,255,158,2,0,0,0,48,52,0,0,0,0,51,0,160,255,8,244,255,14,244,255,12,160,223,3,0,0,0,0,51,
+ 0,160,255,8,244,255,14,244,255,12,160,223,3,179,254,206,40,0,245,255,255,239,2,245,255,255,255,9,116,51,252,255,
+ 11,0,16,252,255,9,0,210,255,239,3,0,250,255,61,0,0,252,223,1,0,0,166,74,0,0,0,163,75,0,0,32,
+ 254,239,1,0,80,255,255,1,0,16,253,143,0,0,0,49,2,0,0,0,0,0,211,110,0,0,0,0,0,0,0,252,
+ 255,2,0,0,0,0,0,80,255,255,10,0,0,0,0,0,208,255,255,63,0,0,0,0,0,246,255,255,191,0,0,0,
+ 0,0,253,255,255,255,4,0,0,0,96,255,175,253,255,12,0,0,0,208,255,79,248,255,111,0,0,0,246,255,13,242,
+ 255,223,1,0,16,254,255,190,251,255,255,7,0,112,255,255,255,255,255,255,30,0,225,255,255,188,219,255,255,159,0,247,
+ 255,239,0,32,255,255,255,2,209,221,221,221,205,89,0,0,241,255,255,255,255,255,11,0,241,255,255,255,255,255,79,0,
+ 241,255,255,90,251,255,79,0,241,255,223,0,250,255,29,0,241,255,223,163,255,223,2,0,241,255,255,255,255,255,62,0,
+ 241,255,255,142,248,255,207,0,241,255,223,1,243,255,255,1,241,255,223,80,253,255,255,2,241,255,239,254,255,255,239,0,
+ 241,255,255,255,255,255,95,0,241,255,255,255,255,157,3,0,0,0,164,253,239,9,0,177,255,255,255,12,16,253,255,255,
+ 255,12,144,255,255,255,255,12,241,255,255,255,72,4,245,255,255,95,0,0,247,255,255,13,0,0,247,255,255,12,0,2,
+ 245,255,255,47,113,30,225,255,255,255,255,31,112,255,255,255,255,31,0,248,255,255,255,31,0,48,250,255,255,12,0,0,
+ 16,67,19,0,192,253,255,255,190,4,0,241,255,255,255,255,127,0,241,255,255,255,255,255,5,241,255,255,221,255,255,13,
+ 241,255,223,1,252,255,79,241,255,207,0,247,255,127,241,255,207,0,248,255,143,241,255,207,48,254,255,143,241,255,207,229,
+ 255,255,95,241,255,255,255,255,255,30,241,255,255,255,255,255,6,241,255,255,255,255,127,0,241,255,255,255,157,2,0,176,
+ 187,187,187,187,0,241,255,255,255,239,0,241,255,255,255,239,0,241,255,255,255,239,0,241,255,207,0,0,0,241,255,255,
+ 255,239,0,241,255,255,255,239,0,241,255,255,255,239,0,241,255,223,34,34,0,241,255,239,187,187,3,241,255,255,255,255,
+ 3,241,255,255,255,255,3,241,255,255,255,255,3,176,187,187,187,187,241,255,255,255,239,241,255,255,255,239,241,255,239,187,
+ 187,241,255,207,0,0,241,255,255,255,239,241,255,255,255,239,241,255,255,255,239,241,255,239,136,120,241,255,207,0,0,241,
+ 255,207,0,0,241,255,207,0,0,241,255,207,0,0,0,0,130,235,255,173,0,0,145,255,255,255,255,0,16,252,255,255,
+ 255,255,0,160,255,255,255,255,255,0,242,255,255,175,3,49,0,246,255,255,11,0,0,0,247,255,255,4,0,0,0,247,
+ 255,255,4,246,255,10,243,255,255,27,246,255,10,192,255,255,255,255,255,10,48,255,255,255,255,255,10,0,228,255,255,255,
+ 255,10,0,16,216,255,255,239,8,0,0,0,49,52,1,0,176,187,155,0,183,187,59,241,255,207,0,249,255,79,241,255,
+ 207,0,249,255,79,241,255,207,0,249,255,79,241,255,223,50,251,255,79,241,255,255,255,255,255,79,241,255,255,255,255,255,
+ 79,241,255,255,255,255,255,79,241,255,239,103,251,255,79,241,255,207,0,249,255,79,241,255,207,0,249,255,79,241,255,207,
+ 0,249,255,79,241,255,207,0,249,255,79,176,187,155,241,255,207,241,255,207,241,255,207,241,255,207,241,255,207,241,255,207,
+ 241,255,207,241,255,207,241,255,207,241,255,207,241,255,207,241,255,207,0,0,0,181,187,107,0,0,0,246,255,159,0,0,
+ 0,246,255,159,0,0,0,246,255,159,0,0,0,246,255,159,0,0,0,246,255,159,16,83,3,246,255,143,252,255,7,246,
+ 255,143,253,255,9,249,255,111,252,255,207,255,255,47,248,255,255,255,255,11,209,255,255,255,239,2,16,233,255,255,42,0,
+ 0,0,67,19,0,0,176,187,171,0,180,187,139,0,241,255,239,32,254,255,46,0,241,255,239,192,255,255,5,0,241,255,
+ 239,248,255,159,0,0,241,255,255,255,255,12,0,0,241,255,255,255,255,2,0,0,241,255,255,255,255,7,0,0,241,255,
+ 255,255,255,47,0,0,241,255,255,253,255,191,0,0,241,255,255,242,255,255,6,0,241,255,255,128,255,255,30,0,241,255,
+ 255,16,254,255,175,0,241,255,255,0,246,255,255,4,144,153,137,0,0,241,255,207,0,0,241,255,207,0,0,241,255,207,
+ 0,0,241,255,207,0,0,241,255,207,0,0,241,255,207,0,0,241,255,207,0,0,241,255,207,0,0,241,255,239,187,187,
+ 241,255,255,255,255,241,255,255,255,255,241,255,255,255,255,176,43,0,0,0,0,0,181,8,241,223,2,0,0,0,80,255,
+ 11,241,255,62,0,0,0,246,255,11,241,255,239,3,0,112,255,255,11,241,255,255,62,0,248,255,255,11,241,255,255,239,
+ 148,255,255,255,11,241,255,255,255,255,255,255,255,11,241,255,255,255,255,255,255,255,11,241,255,255,255,255,255,255,255,11,
+ 241,255,143,255,255,141,255,255,11,241,255,79,246,239,99,255,255,11,241,255,79,112,79,96,255,255,11,241,255,79,0,3,
+ 96,255,255,11,176,8,0,0,176,187,91,241,207,2,0,224,255,127,241,255,94,0,224,255,127,241,255,255,25,224,255,127,
+ 241,255,255,207,227,255,127,241,255,255,255,254,255,127,241,255,255,255,255,255,127,241,255,255,255,255,255,127,241,255,239,255,
+ 255,255,127,241,255,95,230,255,255,127,241,255,95,32,252,255,127,241,255,95,0,112,255,127,241,255,95,0,0,195,127,0,
+ 0,182,254,190,23,0,0,0,194,255,255,255,239,4,0,32,253,255,255,255,255,63,0,160,255,255,255,252,255,223,0,242,
+ 255,255,62,112,255,255,4,245,255,255,7,96,255,255,7,246,255,239,0,160,255,255,8,245,255,175,0,242,255,255,8,242,
+ 255,207,16,252,255,255,5,176,255,255,237,255,255,239,1,48,254,255,255,255,255,95,0,0,228,255,255,255,255,6,0,0,
+ 16,233,255,239,58,0,0,0,0,0,67,3,0,0,0,160,220,221,221,173,23,0,241,255,255,255,255,239,3,241,255,255,
+ 255,255,255,12,241,255,255,109,248,255,47,241,255,255,1,242,255,79,241,255,255,0,248,255,95,241,255,255,146,255,255,63,
+ 241,255,255,254,255,255,12,241,255,255,255,255,255,4,241,255,255,255,255,78,0,241,255,255,187,106,1,0,241,255,255,1,
+ 0,0,0,241,255,255,1,0,0,0,0,0,182,254,190,23,0,0,0,210,255,255,255,223,4,0,32,254,255,255,255,255,
+ 62,0,160,255,255,255,252,255,207,0,242,255,255,62,112,255,255,3,245,255,255,6,96,255,255,7,246,255,239,144,164,255,
+ 255,8,246,255,175,242,255,255,255,8,242,255,207,112,255,255,255,5,176,255,255,236,255,255,255,38,48,254,255,255,255,255,
+ 255,143,0,228,255,255,255,255,255,143,0,32,233,255,255,90,250,159,0,0,0,67,3,0,16,35,192,221,221,221,205,24,
+ 0,0,241,255,255,255,255,239,4,0,241,255,255,255,255,255,30,0,241,255,255,108,248,255,95,0,241,255,255,1,242,255,
+ 127,0,241,255,255,0,248,255,111,0,241,255,255,146,255,255,30,0,241,255,255,255,255,255,5,0,241,255,255,255,255,95,
+ 0,0,241,255,255,253,255,191,0,0,241,255,255,245,255,255,8,0,241,255,255,161,255,255,79,0,241,255,255,17,254,255,
+ 239,2,0,0,49,52,1,0,0,197,255,255,191,0,112,255,255,255,207,0,241,255,255,255,207,0,243,255,255,137,187,0,
+ 243,255,255,24,0,0,208,255,255,239,7,0,48,254,255,255,175,0,0,162,255,255,255,4,33,0,245,255,255,8,243,156,
+ 248,255,255,8,243,255,255,255,255,5,243,255,255,255,207,0,177,255,255,239,25,0,0,32,67,3,0,0,132,136,136,136,
+ 136,136,2,248,255,255,255,255,255,4,248,255,255,255,255,255,4,248,255,255,255,255,255,4,132,136,255,255,141,136,2,0,
+ 16,255,255,12,0,0,0,16,255,255,12,0,0,0,16,255,255,12,0,0,0,16,255,255,12,0,0,0,16,255,255,12,
+ 0,0,0,16,255,255,12,0,0,0,16,255,255,12,0,0,0,16,255,255,12,0,0,178,187,155,0,182,187,9,243,255,
+ 191,0,248,255,12,243,255,191,0,248,255,12,243,255,191,0,248,255,12,243,255,191,0,248,255,12,243,255,191,0,248,255,
+ 12,243,255,191,0,248,255,12,243,255,191,0,248,255,12,242,255,239,1,251,255,11,240,255,255,205,255,255,9,160,255,255,
+ 255,255,255,5,32,253,255,255,255,175,0,0,145,254,255,239,7,0,0,0,32,67,2,0,0,183,187,187,1,96,187,187,
+ 1,243,255,255,7,224,255,159,0,160,255,255,14,246,255,47,0,32,255,255,111,252,255,9,0,0,249,255,239,255,255,2,
+ 0,0,242,255,255,255,175,0,0,0,144,255,255,255,47,0,0,0,32,255,255,255,10,0,0,0,0,249,255,255,3,0,
+ 0,0,0,226,255,175,0,0,0,0,0,128,255,63,0,0,0,0,0,16,254,11,0,0,0,0,0,0,248,4,0,0,
+ 0,0,0,0,48,0,0,0,0,180,187,187,2,0,100,0,48,187,187,2,241,255,255,7,16,238,2,128,255,223,0,176,
+ 255,255,12,176,255,12,208,255,143,0,80,255,255,47,247,255,127,243,255,63,0,16,254,255,159,255,255,255,250,255,13,0,
+ 0,250,255,255,255,255,255,255,255,9,0,0,245,255,255,255,255,255,255,255,4,0,0,224,255,255,255,254,255,255,239,0,
+ 0,0,144,255,255,239,178,255,255,159,0,0,0,64,255,255,95,32,254,255,79,0,0,0,0,253,255,9,0,246,255,14,
+ 0,0,0,0,248,223,1,0,160,255,9,0,0,0,0,243,63,0,0,16,254,4,0,0,0,0,80,3,0,0,0,99,
+ 0,0,0,177,187,187,6,177,187,75,0,128,255,255,30,247,255,13,0,16,253,255,175,254,255,5,0,0,245,255,255,255,
+ 207,0,0,0,176,255,255,255,79,0,0,0,32,255,255,255,11,0,0,0,0,251,255,255,7,0,0,0,32,255,255,255,
+ 30,0,0,0,160,255,255,255,175,0,0,0,243,255,255,255,255,4,0,0,250,255,189,255,255,12,0,48,255,255,54,255,
+ 255,127,0,176,255,223,0,250,255,239,2,181,187,187,1,184,187,10,225,255,255,55,255,255,7,144,255,255,174,255,239,1,
+ 32,255,255,255,255,127,0,0,249,255,255,255,30,0,0,242,255,255,255,7,0,0,144,255,255,239,1,0,0,32,255,255,
+ 127,0,0,0,0,253,255,63,0,0,0,0,253,255,63,0,0,0,0,253,255,63,0,0,0,0,253,255,63,0,0,0,
+ 0,253,255,63,0,0,128,187,187,187,187,187,91,160,255,255,255,255,255,95,160,255,255,255,255,255,11,160,255,255,255,255,
+ 255,2,0,0,160,255,255,143,0,0,0,244,255,255,29,0,0,0,252,255,255,5,0,0,96,255,255,191,0,0,0,225,
+ 255,255,47,0,0,0,248,255,255,190,187,91,32,255,255,255,255,255,127,176,255,255,255,255,255,127,242,255,255,255,255,255,
+ 127,0,185,187,187,10,250,255,255,12,249,255,255,11,247,255,255,9,246,255,255,7,244,255,255,6,242,255,255,4,241,255,
+ 255,3,224,255,255,1,208,255,239,0,176,255,223,0,80,136,104,0,0,0,0,0,0,116,39,0,160,255,255,5,247,255,
+ 255,12,252,255,255,14,250,255,255,10,227,255,223,2,32,118,5,0,0,0,0,50,35,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,16,232,255,255,109,0,0,0,0,187,187,187,10,0,0,0,0,0,0,0,210,255,255,255,255,
+ 27,0,0,80,255,255,255,6,0,0,0,0,0,0,16,253,255,255,255,255,191,0,0,160,255,255,207,0,0,0,0,0,
+ 0,0,128,255,255,207,253,255,255,5,0,225,255,255,79,0,0,0,0,0,0,0,224,255,255,7,160,255,255,11,0,245,
+ 255,255,11,0,0,0,0,0,0,0,243,255,239,0,32,255,255,15,0,250,255,255,3,0,98,119,37,0,0,0,244,255,
+ 191,0,0,254,255,47,16,255,255,175,0,195,255,255,255,42,0,0,244,255,207,0,0,255,255,47,80,255,255,47,80,255,
+ 255,255,255,239,3,0,242,255,255,2,80,255,255,14,176,255,255,8,226,255,255,255,255,255,29,0,208,255,255,93,229,255,
+ 255,10,241,255,239,1,250,255,239,153,255,255,143,0,96,255,255,255,255,255,255,3,246,255,127,16,255,255,79,0,247,255,
+ 223,0,0,251,255,255,255,255,143,0,251,255,13,48,255,255,13,0,241,255,255,1,0,161,255,255,255,255,8,16,255,255,
+ 5,64,255,255,12,0,224,255,255,2,0,0,164,253,223,57,0,96,255,207,0,48,255,255,13,0,241,255,255,1,0,0,
+ 0,0,0,0,0,192,255,79,0,16,255,255,95,0,247,255,223,0,0,0,0,0,0,0,0,242,255,11,0,0,250,255,
+ 239,153,255,255,143,0,0,0,0,0,0,0,0,247,255,3,0,0,226,255,255,255,255,255,29,0,0,0,0,0,0,0,
+ 0,252,159,0,0,0,80,255,255,255,255,239,3,0,0,0,0,0,0,0,32,255,46,0,0,0,0,195,255,255,255,42,
+ 0,0,0,0,0,0,0,0,0,17,1,0,0,0,0,0,98,119,37,0,0,0,241,255,255,13,224,255,255,11,192,255,
+ 255,10,160,255,255,8,128,255,255,6,96,255,255,5,64,255,255,3,32,255,255,2,0,255,255,0,0,0,0,81,168,6,
+ 0,0,112,254,255,8,0,32,252,255,255,8,0,209,255,255,255,8,0,251,255,255,255,4,80,255,255,255,95,0,176,255,
+ 255,255,8,0,241,255,255,239,1,0,244,255,255,143,0,0,247,255,255,79,0,0,248,255,255,31,0,0,247,255,255,31,
+ 0,0,246,255,255,47,0,0,244,255,255,95,0,0,224,255,255,191,0,0,128,255,255,255,7,0,16,253,255,255,191,4,
+ 0,227,255,255,255,8,0,48,253,255,255,8,0,0,129,254,255,8,0,0,0,81,168,6,166,88,1,0,0,0,248,255,
+ 126,0,0,0,248,255,255,44,0,0,248,255,255,223,1,0,244,255,255,255,11,0,64,255,255,255,95,0,0,248,255,255,
+ 191,0,0,225,255,255,255,1,0,128,255,255,255,4,0,64,255,255,255,7,0,16,255,255,255,8,0,16,255,255,255,7,
+ 0,32,255,255,255,6,0,80,255,255,255,4,0,176,255,255,239,0,0,247,255,255,143,0,180,255,255,255,29,0,248,255,
+ 255,239,3,0,248,255,255,61,0,0,248,255,142,1,0,0,166,88,1,0,0,0,0,0,67,68,2,0,0,0,0,252,
+ 255,8,0,0,0,0,252,255,8,0,0,0,0,252,255,8,0,0,133,136,253,255,140,136,3,249,255,255,255,255,255,5,
+ 249,255,255,255,255,255,5,249,255,255,255,255,255,5,183,187,254,255,189,187,4,0,0,252,255,8,0,0,0,0,252,255,
+ 8,0,0,0,0,252,255,8,0,0,0,0,185,187,6,0,0,248,255,255,143,248,255,255,143,248,255,255,143,248,255,255,
+ 143,248,255,255,143,0,248,255,143,0,253,255,95,196,255,255,30,248,255,255,5,248,255,76,0,116,37,0,0,182,187,187,
+ 187,75,248,255,255,255,111,248,255,255,255,111,248,255,255,255,111,248,255,255,255,111,66,68,68,68,20,0,64,103,2,16,
+ 251,255,62,144,255,255,207,240,255,255,255,241,255,255,239,208,255,255,159,80,255,255,27,0,114,71,0,0,16,187,187,187,
+ 155,0,64,255,255,255,143,0,96,255,255,255,79,0,144,255,255,255,31,0,192,255,255,255,11,0,224,255,255,255,7,0,
+ 242,255,255,255,3,0,245,255,255,239,0,0,247,255,255,175,0,0,250,255,255,111,0,0,253,255,255,47,0,16,255,255,
+ 255,13,0,48,255,255,255,9,0,96,255,255,255,5,0,144,255,255,255,1,0,176,255,255,207,0,0,224,255,255,143,0,
+ 0,242,255,255,79,0,0,244,255,255,14,0,0,0,0,0,0,49,52,1,0,0,0,0,0,0,16,216,255,255,223,40,
+ 0,0,0,0,0,230,255,255,255,255,239,6,0,0,0,112,255,255,255,255,255,255,143,0,0,0,245,255,255,255,255,255,
+ 255,255,5,0,16,253,255,255,255,255,255,255,255,30,0,96,255,255,255,207,200,255,255,255,111,0,176,255,255,255,30,16,
+ 254,255,255,191,0,224,255,255,255,9,0,249,255,255,239,0,241,255,255,255,7,0,247,255,255,255,1,241,255,255,255,7,
+ 0,246,255,255,255,2,241,255,255,255,7,0,246,255,255,255,1,224,255,255,255,8,0,248,255,255,239,0,176,255,255,255,
+ 12,0,252,255,255,191,0,96,255,255,255,159,148,255,255,255,111,0,16,254,255,255,255,255,255,255,255,30,0,0,245,255,
+ 255,255,255,255,255,255,6,0,0,128,255,255,255,255,255,255,159,0,0,0,0,247,255,255,255,255,255,8,0,0,0,0,
+ 48,250,255,255,255,59,0,0,0,0,0,0,16,117,119,21,0,0,0,0,0,0,0,0,129,187,1,0,0,0,146,254,
+ 255,2,0,0,163,255,255,255,2,0,163,255,255,255,255,2,180,255,255,255,255,255,2,251,255,255,255,255,255,2,251,255,
+ 255,255,255,255,2,251,255,255,255,255,255,2,251,255,255,255,255,255,2,251,90,250,255,255,255,2,20,0,249,255,255,255,
+ 2,0,0,249,255,255,255,2,0,0,249,255,255,255,2,0,0,249,255,255,255,2,0,0,249,255,255,255,2,0,0,249,
+ 255,255,255,2,0,0,249,255,255,255,2,0,0,249,255,255,255,2,0,0,249,255,255,255,2,0,0,0,0,32,51,2,
+ 0,0,0,0,0,32,200,255,255,239,91,0,0,0,32,250,255,255,255,255,255,27,0,0,228,255,255,255,255,255,255,207,
+ 0,64,255,255,255,255,255,255,255,255,7,225,255,255,255,255,255,255,255,255,12,160,255,255,223,137,254,255,255,255,14,16,
+ 254,223,5,0,245,255,255,255,13,0,244,27,0,0,244,255,255,255,10,0,96,0,0,0,250,255,255,255,3,0,0,0,
+ 0,128,255,255,255,143,0,0,0,0,16,250,255,255,255,8,0,0,0,0,194,255,255,255,111,0,0,0,0,48,254,255,
+ 255,223,3,0,0,0,0,245,255,255,255,207,187,187,27,0,128,255,255,255,255,255,255,255,31,0,249,255,255,255,255,255,
+ 255,255,31,0,252,255,255,255,255,255,255,255,31,0,252,255,255,255,255,255,255,255,31,0,252,255,255,255,255,255,255,255,
+ 31,144,187,187,187,187,187,187,187,187,59,208,255,255,255,255,255,255,255,255,63,208,255,255,255,255,255,255,255,255,46,208,
+ 255,255,255,255,255,255,255,191,1,208,255,255,255,255,255,255,255,8,0,96,136,136,152,255,255,255,94,0,0,0,0,0,
+ 228,255,255,207,2,0,0,0,0,128,255,255,255,223,107,1,0,0,0,128,255,255,255,255,255,126,0,0,0,16,254,255,
+ 255,255,255,255,8,0,0,0,50,116,252,255,255,255,47,0,0,0,0,0,160,255,255,255,127,0,136,1,0,0,96,255,
+ 255,255,159,48,255,174,37,1,211,255,255,255,159,192,255,255,255,255,255,255,255,255,127,246,255,255,255,255,255,255,255,255,
+ 47,253,255,255,255,255,255,255,255,255,8,145,255,255,255,255,255,255,255,143,0,0,114,252,255,255,255,255,158,3,0,0,
+ 0,16,83,119,103,37,0,0,0,0,0,0,80,221,221,221,221,221,45,0,0,0,0,225,255,255,255,255,255,63,0,0,
+ 0,0,250,255,255,255,255,255,63,0,0,0,80,255,255,255,255,255,255,63,0,0,0,226,255,255,255,255,255,255,63,0,
+ 0,0,251,255,255,239,255,255,255,63,0,0,96,255,255,255,186,255,255,255,63,0,0,226,255,255,239,178,255,255,255,63,
+ 0,0,251,255,255,111,176,255,255,255,63,0,96,255,255,255,12,176,255,255,255,63,0,226,255,255,255,3,176,255,255,255,
+ 111,3,247,255,255,255,255,255,255,255,255,255,13,247,255,255,255,255,255,255,255,255,255,13,247,255,255,255,255,255,255,255,
+ 255,255,13,247,255,255,255,255,255,255,255,255,255,13,247,255,255,255,255,255,255,255,255,255,13,131,136,136,136,136,216,255,
+ 255,255,159,6,0,0,0,0,0,176,255,255,255,63,0,0,0,0,0,0,176,255,255,255,63,0,0,160,187,187,187,187,
+ 187,187,187,7,0,241,255,255,255,255,255,255,255,7,0,244,255,255,255,255,255,255,255,3,0,248,255,255,255,255,255,255,
+ 255,1,0,251,255,255,239,238,238,238,190,0,0,254,255,255,6,0,0,0,0,0,32,255,255,255,70,68,2,0,0,0,
+ 80,255,255,255,255,255,239,90,0,0,128,255,255,255,255,255,255,255,44,0,144,255,255,255,255,255,255,255,223,1,0,147,
+ 239,172,202,255,255,255,255,8,0,0,1,0,0,245,255,255,255,13,0,20,0,0,0,241,255,255,255,15,16,254,106,19,
+ 16,249,255,255,255,15,160,255,255,255,255,255,255,255,255,12,244,255,255,255,255,255,255,255,255,7,252,255,255,255,255,255,
+ 255,255,207,0,232,255,255,255,255,255,255,255,27,0,16,183,255,255,255,255,255,91,0,0,0,0,48,101,119,103,19,0,
+ 0,0,0,0,0,0,32,67,3,0,0,0,0,0,0,164,254,255,255,107,0,0,0,0,178,255,255,255,255,255,61,0,
+ 0,48,254,255,255,255,255,255,255,4,0,209,255,255,255,255,255,255,255,13,0,250,255,255,255,205,255,255,255,44,32,255,
+ 255,255,95,0,227,174,22,0,128,255,255,255,11,0,32,0,0,0,192,255,255,255,74,118,103,20,0,0,240,255,255,255,
+ 255,255,255,255,75,0,241,255,255,255,255,255,255,255,255,9,242,255,255,255,255,255,255,255,255,111,241,255,255,255,143,136,
+ 253,255,255,207,224,255,255,255,31,0,243,255,255,255,144,255,255,255,111,0,192,255,255,255,48,255,255,255,239,2,160,255,
+ 255,223,0,248,255,255,255,158,249,255,255,159,0,160,255,255,255,255,255,255,255,46,0,0,247,255,255,255,255,255,223,3,
+ 0,0,32,233,255,255,255,223,23,0,0,0,0,0,99,119,87,2,0,0,186,187,187,187,187,187,187,187,187,59,253,255,
+ 255,255,255,255,255,255,255,63,253,255,255,255,255,255,255,255,255,12,253,255,255,255,255,255,255,255,255,5,253,255,255,255,
+ 255,255,255,255,223,0,99,135,136,136,136,253,255,255,95,0,0,0,0,0,32,254,255,255,13,0,0,0,0,0,176,255,
+ 255,255,6,0,0,0,0,0,247,255,255,223,0,0,0,0,0,48,255,255,255,111,0,0,0,0,0,209,255,255,255,13,
+ 0,0,0,0,0,250,255,255,255,6,0,0,0,0,80,255,255,255,239,1,0,0,0,0,226,255,255,255,127,0,0,0,
+ 0,0,252,255,255,255,30,0,0,0,0,128,255,255,255,255,7,0,0,0,0,244,255,255,255,239,1,0,0,0,16,253,
+ 255,255,255,127,0,0,0,0,160,255,255,255,255,30,0,0,0,0,0,0,0,33,67,35,0,0,0,0,0,48,217,255,
+ 255,255,207,39,0,0,16,250,255,255,255,255,255,255,7,0,160,255,255,255,255,255,255,255,111,0,242,255,255,255,255,255,
+ 255,255,223,0,244,255,255,255,121,251,255,255,255,0,244,255,255,223,0,241,255,255,255,0,241,255,255,239,1,244,255,255,
+ 191,0,96,255,255,255,141,254,255,255,62,0,0,212,255,255,255,255,255,191,2,0,16,249,255,255,255,255,255,239,6,0,
+ 193,255,255,255,139,253,255,255,143,0,248,255,255,191,0,225,255,255,255,3,253,255,255,143,0,192,255,255,255,9,255,255,
+ 255,207,2,228,255,255,255,10,254,255,255,255,255,255,255,255,255,10,251,255,255,255,255,255,255,255,255,7,244,255,255,255,
+ 255,255,255,255,239,1,96,255,255,255,255,255,255,255,62,0,0,146,254,255,255,255,255,141,1,0,0,0,32,101,119,103,
+ 36,0,0,0,0,0,0,16,50,36,0,0,0,0,0,0,147,253,255,255,191,6,0,0,0,161,255,255,255,255,255,223,
+ 4,0,16,252,255,255,255,255,255,255,127,0,128,255,255,255,255,255,255,255,255,5,224,255,255,239,18,246,255,255,255,30,
+ 241,255,255,239,0,96,255,255,255,127,242,255,255,255,4,0,254,255,255,207,224,255,255,255,76,68,253,255,255,239,144,255,
+ 255,255,255,255,255,255,255,255,16,253,255,255,255,255,255,255,255,255,0,145,255,255,255,255,255,255,255,239,0,0,81,168,
+ 187,154,253,255,255,207,0,0,0,0,0,0,251,255,255,143,0,0,98,186,1,48,255,255,255,63,32,216,255,255,141,233,
+ 255,255,255,10,32,255,255,255,255,255,255,255,239,2,0,249,255,255,255,255,255,255,78,0,0,128,255,255,255,255,255,223,
+ 3,0,0,0,163,255,255,255,223,23,0,0,0,0,0,65,118,87,2,0,0,0,0,66,2,0,160,255,127,0,248,255,
+ 255,3,254,255,255,6,255,255,255,5,251,255,223,0,178,239,42,0,0,0,0,0,0,0,0,0,0,66,2,0,160,255,
+ 143,0,248,255,255,3,254,255,255,6,255,255,255,5,251,255,223,0,178,239,42,0,0,32,67,35,0,0,0,176,254,255,
+ 255,174,4,0,241,255,255,255,255,175,0,241,255,255,255,255,255,8,241,255,255,255,255,255,14,241,157,152,255,255,255,47,
+ 48,0,0,248,255,255,31,0,0,0,251,255,255,14,0,0,211,255,255,255,8,0,32,254,255,255,191,0,0,128,255,255,
+ 255,7,0,0,160,255,255,78,0,0,0,144,255,255,6,0,0,0,64,153,153,0,0,0,0,0,114,71,0,0,0,0,
+ 112,255,255,8,0,0,0,243,255,255,31,0,0,0,247,255,255,63,0,0,0,246,255,255,14,0,0,0,209,255,239,4,
+ 0,0,0,16,118,22,0,0,0,0,0,0,0,0,16,1,0,0,0,0,0,0,0,0,0,0,0,249,207,2,0,0,
+ 0,0,0,0,0,0,0,112,255,255,12,0,0,0,0,0,0,0,0,0,225,255,255,95,0,0,0,0,0,0,0,0,
+ 0,247,255,255,223,0,0,0,0,0,0,0,0,16,254,255,255,255,7,0,0,0,0,0,0,0,128,255,255,255,255,30,
+ 0,0,0,0,0,0,0,225,255,255,255,255,159,0,0,0,0,0,0,0,248,255,255,255,255,255,2,0,0,0,0,0,
+ 32,255,255,239,255,255,255,10,0,0,0,0,0,144,255,255,127,252,255,255,79,0,0,0,0,0,242,255,255,31,246,255,
+ 255,207,0,0,0,0,0,250,255,255,10,241,255,255,255,5,0,0,0,48,255,255,255,4,176,255,255,255,13,0,0,0,
+ 160,255,255,255,136,184,255,255,255,127,0,0,0,243,255,255,255,255,255,255,255,255,239,1,0,0,251,255,255,255,255,255,
+ 255,255,255,255,9,0,64,255,255,255,255,255,255,255,255,255,255,47,0,192,255,255,255,111,68,68,249,255,255,255,175,0,
+ 244,255,255,255,13,0,0,242,255,255,255,255,4,33,34,34,34,1,0,0,32,34,34,34,34,1,50,51,51,51,51,35,
+ 1,0,0,0,0,248,255,255,255,255,255,255,156,3,0,0,248,255,255,255,255,255,255,255,175,0,0,248,255,255,255,255,
+ 255,255,255,255,8,0,248,255,255,255,255,255,255,255,255,14,0,248,255,255,255,207,216,255,255,255,15,0,248,255,255,239,
+ 4,64,255,255,255,12,0,248,255,255,191,0,128,255,255,255,4,0,248,255,255,191,16,248,255,255,60,0,0,248,255,255,
+ 207,232,255,255,255,142,0,0,248,255,255,255,255,255,255,255,255,28,0,248,255,255,255,255,188,255,255,255,143,0,248,255,
+ 255,255,59,0,250,255,255,239,0,248,255,255,207,0,0,252,255,255,255,2,248,255,255,191,0,145,255,255,255,255,3,248,
+ 255,255,191,147,254,255,255,255,255,2,248,255,255,255,255,255,255,255,255,223,0,248,255,255,255,255,255,255,255,255,95,0,
+ 248,255,255,255,255,255,255,255,239,5,0,248,255,255,255,255,255,255,190,23,0,0,33,34,34,34,34,34,18,0,0,0,
+ 0,0,0,0,0,0,50,68,2,0,0,0,0,113,252,255,255,239,2,0,0,128,254,255,255,255,255,3,0,16,252,255,
+ 255,255,255,255,3,0,193,255,255,255,255,255,255,3,0,249,255,255,255,255,255,255,3,48,255,255,255,255,255,255,255,3,
+ 160,255,255,255,255,255,40,32,1,224,255,255,255,255,95,0,0,0,242,255,255,255,255,9,0,0,0,244,255,255,255,255,
+ 4,0,0,0,244,255,255,255,255,2,0,0,0,243,255,255,255,255,4,0,112,8,241,255,255,255,255,28,81,252,8,176,
+ 255,255,255,255,255,255,255,8,64,255,255,255,255,255,255,255,8,0,249,255,255,255,255,255,255,8,0,160,255,255,255,255,
+ 255,255,8,0,0,248,255,255,255,255,255,8,0,0,32,233,255,255,255,223,5,0,0,0,0,99,119,87,2,0,0,33,
+ 67,68,68,52,1,0,0,0,231,255,255,255,255,255,191,4,0,0,248,255,255,255,255,255,255,175,1,0,248,255,255,255,
+ 255,255,255,255,11,0,248,255,255,255,255,255,255,255,143,0,248,255,255,255,255,255,255,255,255,2,248,255,255,255,73,248,
+ 255,255,255,8,248,255,255,191,0,144,255,255,255,13,248,255,255,191,0,48,255,255,255,47,248,255,255,191,0,32,255,255,
+ 255,79,248,255,255,191,0,96,255,255,255,95,248,255,255,191,0,209,255,255,255,79,248,255,255,191,16,252,255,255,255,63,
+ 248,255,255,191,211,255,255,255,255,14,248,255,255,239,255,255,255,255,255,10,248,255,255,255,255,255,255,255,255,3,248,255,
+ 255,255,255,255,255,255,143,0,248,255,255,255,255,255,255,255,9,0,248,255,255,255,255,255,255,110,0,0,248,255,255,255,
+ 255,239,107,1,0,0,33,34,34,34,34,1,0,0,0,0,248,255,255,255,255,255,239,0,248,255,255,255,255,255,239,0,
+ 248,255,255,255,255,255,239,0,248,255,255,255,255,255,239,0,248,255,255,255,255,255,239,0,248,255,255,223,136,136,120,0,
+ 248,255,255,191,0,0,0,0,248,255,255,255,238,238,222,0,248,255,255,255,255,255,239,0,248,255,255,255,255,255,239,0,
+ 248,255,255,255,255,255,239,0,248,255,255,239,187,187,171,0,248,255,255,191,0,0,0,0,248,255,255,223,136,136,136,3,
+ 248,255,255,255,255,255,255,5,248,255,255,255,255,255,255,5,248,255,255,255,255,255,255,5,248,255,255,255,255,255,255,5,
+ 248,255,255,255,255,255,255,5,182,187,187,187,187,187,171,248,255,255,255,255,255,239,248,255,255,255,255,255,239,248,255,255,
+ 255,255,255,239,248,255,255,255,255,255,239,248,255,255,223,136,136,120,248,255,255,191,0,0,0,248,255,255,239,187,187,171,
+ 248,255,255,255,255,255,239,248,255,255,255,255,255,239,248,255,255,255,255,255,239,248,255,255,255,255,255,239,248,255,255,223,
+ 136,136,120,248,255,255,191,0,0,0,248,255,255,191,0,0,0,248,255,255,191,0,0,0,248,255,255,191,0,0,0,248,
+ 255,255,191,0,0,0,248,255,255,191,0,0,0,33,34,34,18,0,0,0,0,0,0,0,0,33,67,35,0,0,0,0,
+ 0,64,217,255,255,255,190,0,0,0,80,253,255,255,255,255,255,1,0,16,251,255,255,255,255,255,255,1,0,193,255,255,
+ 255,255,255,255,255,1,0,251,255,255,255,255,255,255,255,1,80,255,255,255,255,255,157,136,234,1,176,255,255,255,255,110,
+ 0,0,0,0,241,255,255,255,255,4,0,0,0,0,243,255,255,255,175,0,0,0,0,0,244,255,255,255,95,0,0,0,
+ 0,0,243,255,255,255,95,0,241,255,255,14,241,255,255,255,159,0,241,255,255,14,192,255,255,255,255,22,242,255,255,14,
+ 112,255,255,255,255,255,255,255,255,14,16,253,255,255,255,255,255,255,255,14,0,243,255,255,255,255,255,255,255,14,0,64,
+ 254,255,255,255,255,255,255,14,0,0,194,255,255,255,255,255,255,14,0,0,0,164,254,255,255,255,255,13,0,0,0,0,
+ 49,118,119,70,19,0,182,187,187,139,0,64,187,187,187,10,248,255,255,191,0,96,255,255,255,14,248,255,255,191,0,96,
+ 255,255,255,14,248,255,255,191,0,96,255,255,255,14,248,255,255,191,0,96,255,255,255,14,248,255,255,191,0,96,255,255,
+ 255,14,248,255,255,191,0,113,255,255,255,14,248,255,255,239,254,255,255,255,255,14,248,255,255,255,255,255,255,255,255,14,
+ 248,255,255,255,255,255,255,255,255,14,248,255,255,255,255,255,255,255,255,14,248,255,255,255,255,255,255,255,255,14,248,255,
+ 255,223,86,116,255,255,255,14,248,255,255,191,0,96,255,255,255,14,248,255,255,191,0,96,255,255,255,14,248,255,255,191,
+ 0,96,255,255,255,14,248,255,255,191,0,96,255,255,255,14,248,255,255,191,0,96,255,255,255,14,248,255,255,191,0,96,
+ 255,255,255,14,182,187,187,139,248,255,255,191,248,255,255,191,248,255,255,191,248,255,255,191,248,255,255,191,248,255,255,191,
+ 248,255,255,191,248,255,255,191,248,255,255,191,248,255,255,191,248,255,255,191,248,255,255,191,248,255,255,191,248,255,255,191,
+ 248,255,255,191,248,255,255,191,248,255,255,191,248,255,255,191,0,0,0,0,16,187,187,187,75,0,0,0,0,32,255,255,
+ 255,95,0,0,0,0,32,255,255,255,95,0,0,0,0,32,255,255,255,95,0,0,0,0,32,255,255,255,95,0,0,0,
+ 0,32,255,255,255,95,0,0,0,0,32,255,255,255,95,0,0,0,0,32,255,255,255,95,0,0,0,0,32,255,255,255,
+ 95,0,0,16,2,32,255,255,255,95,133,202,254,10,32,255,255,255,95,253,255,255,10,32,255,255,255,79,252,255,255,12,
+ 80,255,255,255,31,252,255,255,143,213,255,255,255,13,249,255,255,255,255,255,255,255,8,244,255,255,255,255,255,255,255,2,
+ 176,255,255,255,255,255,255,127,0,16,252,255,255,255,255,255,8,0,0,112,253,255,255,255,76,0,0,0,0,32,117,119,
+ 37,0,0,0,182,187,187,171,0,0,186,187,187,139,0,248,255,255,223,0,144,255,255,255,46,0,248,255,255,223,0,245,
+ 255,255,255,4,0,248,255,255,223,32,254,255,255,143,0,0,248,255,255,223,209,255,255,255,11,0,0,248,255,255,223,250,
+ 255,255,239,2,0,0,248,255,255,255,255,255,255,79,0,0,0,248,255,255,255,255,255,255,8,0,0,0,248,255,255,255,
+ 255,255,255,2,0,0,0,248,255,255,255,255,255,255,11,0,0,0,248,255,255,255,255,255,255,111,0,0,0,248,255,255,
+ 255,255,255,255,239,1,0,0,248,255,255,255,252,255,255,255,10,0,0,248,255,255,255,209,255,255,255,95,0,0,248,255,
+ 255,255,80,255,255,255,239,1,0,248,255,255,255,0,251,255,255,255,10,0,248,255,255,255,0,242,255,255,255,79,0,248,
+ 255,255,255,0,128,255,255,255,223,1,248,255,255,255,0,16,253,255,255,255,9,215,221,221,173,0,0,0,248,255,255,191,
+ 0,0,0,248,255,255,191,0,0,0,248,255,255,191,0,0,0,248,255,255,191,0,0,0,248,255,255,191,0,0,0,248,
+ 255,255,191,0,0,0,248,255,255,191,0,0,0,248,255,255,191,0,0,0,248,255,255,191,0,0,0,248,255,255,191,0,
+ 0,0,248,255,255,191,0,0,0,248,255,255,191,0,0,0,248,255,255,239,187,187,187,248,255,255,255,255,255,255,248,255,
+ 255,255,255,255,255,248,255,255,255,255,255,255,248,255,255,255,255,255,255,248,255,255,255,255,255,255,182,107,0,0,0,0,
+ 0,0,0,0,161,187,1,248,255,7,0,0,0,0,0,0,16,252,255,1,248,255,127,0,0,0,0,0,0,210,255,255,
+ 1,248,255,255,8,0,0,0,0,32,253,255,255,1,248,255,255,159,0,0,0,0,227,255,255,255,1,248,255,255,255,9,
+ 0,0,64,254,255,255,255,1,248,255,255,255,175,0,0,245,255,255,255,255,1,248,255,255,255,255,11,96,255,255,255,255,
+ 255,1,248,255,255,255,255,191,247,255,255,255,255,255,1,248,255,255,255,255,255,255,255,255,255,255,255,1,248,255,255,255,
+ 255,255,255,255,255,255,255,255,1,248,255,255,255,255,255,255,255,255,255,255,255,1,248,255,255,255,255,255,255,255,255,255,
+ 255,255,1,248,255,255,190,255,255,255,207,251,255,255,255,1,248,255,255,30,252,255,255,29,250,255,255,255,1,248,255,255,
+ 14,193,255,239,2,250,255,255,255,1,248,255,255,14,32,253,62,0,250,255,255,255,1,248,255,255,14,0,210,4,0,250,
+ 255,255,255,1,248,255,255,14,0,0,0,0,250,255,255,255,1,182,25,0,0,0,0,181,187,187,43,248,223,3,0,0,
+ 0,247,255,255,47,248,255,127,0,0,0,247,255,255,47,248,255,255,27,0,0,247,255,255,47,248,255,255,239,4,0,247,
+ 255,255,47,248,255,255,255,143,0,247,255,255,47,248,255,255,255,255,44,247,255,255,47,248,255,255,255,255,239,251,255,255,
+ 47,248,255,255,255,255,255,255,255,255,47,248,255,255,255,255,255,255,255,255,47,248,255,255,255,255,255,255,255,255,47,248,
+ 255,255,255,255,255,255,255,255,47,248,255,255,223,255,255,255,255,255,47,248,255,255,31,249,255,255,255,255,47,248,255,255,
+ 15,64,253,255,255,255,47,248,255,255,15,0,145,255,255,255,47,248,255,255,15,0,0,212,255,255,47,248,255,255,15,0,
+ 0,16,249,255,47,248,255,255,15,0,0,0,64,253,47,0,0,0,0,32,67,19,0,0,0,0,0,0,0,147,254,255,
+ 255,141,2,0,0,0,0,161,255,255,255,255,255,143,1,0,0,48,254,255,255,255,255,255,255,28,0,0,226,255,255,255,
+ 255,255,255,255,207,0,0,251,255,255,255,255,255,255,255,255,8,64,255,255,255,255,223,168,255,255,255,30,160,255,255,255,
+ 255,27,0,250,255,255,111,224,255,255,255,223,1,0,248,255,255,175,241,255,255,255,95,0,0,250,255,255,207,242,255,255,
+ 255,13,0,16,254,255,255,223,241,255,255,255,9,0,128,255,255,255,207,224,255,255,255,7,0,243,255,255,255,191,176,255,
+ 255,255,12,48,253,255,255,255,127,80,255,255,255,239,252,255,255,255,255,47,0,252,255,255,255,255,255,255,255,255,9,0,
+ 227,255,255,255,255,255,255,255,223,1,0,64,254,255,255,255,255,255,255,45,0,0,0,195,255,255,255,255,255,191,1,0,
+ 0,0,0,198,255,255,255,191,4,0,0,0,0,0,0,82,119,70,1,0,0,0,0,32,50,51,51,35,0,0,0,0,
+ 231,255,255,255,255,255,223,57,0,0,248,255,255,255,255,255,255,255,26,0,248,255,255,255,255,255,255,255,175,0,248,255,
+ 255,255,255,255,255,255,255,4,248,255,255,255,239,169,255,255,255,10,248,255,255,255,25,0,252,255,255,13,248,255,255,255,
+ 1,0,251,255,255,14,248,255,255,255,1,16,254,255,255,15,248,255,255,255,1,193,255,255,255,14,248,255,255,255,81,253,
+ 255,255,255,11,248,255,255,255,253,255,255,255,255,6,248,255,255,255,255,255,255,255,223,0,248,255,255,255,255,255,255,255,
+ 62,0,248,255,255,255,255,255,255,239,4,0,248,255,255,255,255,255,255,25,0,0,248,255,255,255,154,137,21,0,0,0,
+ 248,255,255,255,1,0,0,0,0,0,248,255,255,255,1,0,0,0,0,0,248,255,255,255,1,0,0,0,0,0,0,0,
+ 0,0,32,67,19,0,0,0,0,0,0,0,0,164,254,255,255,141,2,0,0,0,0,0,178,255,255,255,255,255,143,1,
+ 0,0,0,48,254,255,255,255,255,255,255,28,0,0,0,226,255,255,255,255,255,255,255,207,0,0,0,251,255,255,255,255,
+ 255,255,255,255,8,0,64,255,255,255,255,223,168,255,255,255,30,0,160,255,255,255,255,27,0,251,255,255,111,0,224,255,
+ 255,255,223,1,0,248,255,255,175,0,241,255,255,255,95,0,0,251,255,255,207,0,242,255,255,255,13,210,22,255,255,255,
+ 207,0,242,255,255,255,8,251,239,255,255,255,207,0,224,255,255,255,7,244,255,255,255,255,175,0,176,255,255,255,12,112,
+ 255,255,255,255,111,0,80,255,255,255,223,252,255,255,255,255,63,0,0,252,255,255,255,255,255,255,255,255,255,77,0,227,
+ 255,255,255,255,255,255,255,255,255,95,0,64,254,255,255,255,255,255,255,255,255,95,0,0,211,255,255,255,255,255,255,255,
+ 255,95,0,0,0,198,255,255,255,191,20,232,255,95,0,0,0,0,82,119,71,1,0,16,116,39,16,50,51,51,51,35,
+ 1,0,0,0,0,247,255,255,255,255,255,239,74,0,0,0,248,255,255,255,255,255,255,255,27,0,0,248,255,255,255,255,
+ 255,255,255,207,1,0,248,255,255,255,255,255,255,255,255,8,0,248,255,255,255,239,153,255,255,255,14,0,248,255,255,255,
+ 23,0,252,255,255,63,0,248,255,255,255,1,0,251,255,255,79,0,248,255,255,255,1,32,254,255,255,63,0,248,255,255,
+ 255,1,193,255,255,255,14,0,248,255,255,255,97,254,255,255,255,8,0,248,255,255,255,254,255,255,255,207,0,0,248,255,
+ 255,255,255,255,255,255,27,0,0,248,255,255,255,255,255,255,207,0,0,0,248,255,255,255,254,255,255,255,6,0,0,248,
+ 255,255,255,247,255,255,255,63,0,0,248,255,255,255,177,255,255,255,223,1,0,248,255,255,255,33,255,255,255,255,11,0,
+ 248,255,255,255,1,248,255,255,255,127,0,248,255,255,255,1,209,255,255,255,255,4,0,0,48,118,119,70,1,0,0,145,
+ 254,255,255,255,175,0,48,254,255,255,255,255,191,0,225,255,255,255,255,255,191,0,248,255,255,255,255,255,191,0,252,255,
+ 255,255,255,255,191,0,253,255,255,255,3,66,119,0,252,255,255,255,59,0,0,0,248,255,255,255,255,58,0,0,226,255,
+ 255,255,255,255,8,0,80,255,255,255,255,255,159,0,0,211,255,255,255,255,255,4,0,0,231,255,255,255,255,10,2,0,
+ 16,252,255,255,255,13,220,72,1,248,255,255,255,13,252,255,255,255,255,255,255,12,252,255,255,255,255,255,255,8,252,255,
+ 255,255,255,255,239,1,252,255,255,255,255,255,78,0,197,255,255,255,255,175,2,0,0,65,118,119,70,1,0,0,180,187,
+ 187,187,187,187,187,187,187,4,245,255,255,255,255,255,255,255,255,6,245,255,255,255,255,255,255,255,255,6,245,255,255,255,
+ 255,255,255,255,255,6,245,255,255,255,255,255,255,255,255,6,245,255,255,255,255,255,255,255,255,6,65,68,84,255,255,255,
+ 111,68,68,1,0,0,32,255,255,255,63,0,0,0,0,0,32,255,255,255,63,0,0,0,0,0,32,255,255,255,63,0,
+ 0,0,0,0,32,255,255,255,63,0,0,0,0,0,32,255,255,255,63,0,0,0,0,0,32,255,255,255,63,0,0,0,
+ 0,0,32,255,255,255,63,0,0,0,0,0,32,255,255,255,63,0,0,0,0,0,32,255,255,255,63,0,0,0,0,0,
+ 32,255,255,255,63,0,0,0,0,0,32,255,255,255,63,0,0,0,0,0,32,255,255,255,63,0,0,0,185,187,187,123,
+ 0,48,187,187,187,2,251,255,255,175,0,64,255,255,255,3,251,255,255,175,0,64,255,255,255,3,251,255,255,175,0,64,
+ 255,255,255,3,251,255,255,175,0,64,255,255,255,3,251,255,255,175,0,64,255,255,255,3,251,255,255,175,0,64,255,255,
+ 255,3,251,255,255,175,0,64,255,255,255,3,251,255,255,175,0,64,255,255,255,3,251,255,255,175,0,64,255,255,255,3,
+ 251,255,255,175,0,64,255,255,255,3,251,255,255,175,0,80,255,255,255,3,251,255,255,223,0,128,255,255,255,2,249,255,
+ 255,255,73,230,255,255,255,1,245,255,255,255,255,255,255,255,207,0,225,255,255,255,255,255,255,255,127,0,80,255,255,255,
+ 255,255,255,255,29,0,0,246,255,255,255,255,255,223,2,0,0,48,234,255,255,255,239,24,0,0,0,0,0,99,119,103,
+ 3,0,0,0,214,221,221,221,28,0,0,218,221,221,29,225,255,255,255,127,0,48,255,255,255,9,112,255,255,255,223,0,
+ 144,255,255,255,2,16,254,255,255,255,6,242,255,255,175,0,0,247,255,255,255,13,248,255,255,47,0,0,225,255,255,255,
+ 111,254,255,255,10,0,0,96,255,255,255,255,255,255,255,3,0,0,0,253,255,255,255,255,255,175,0,0,0,0,246,255,
+ 255,255,255,255,63,0,0,0,0,208,255,255,255,255,255,11,0,0,0,0,80,255,255,255,255,255,3,0,0,0,0,0,
+ 253,255,255,255,191,0,0,0,0,0,0,245,255,255,255,79,0,0,0,0,0,0,192,255,255,255,11,0,0,0,0,0,
+ 0,64,255,255,255,4,0,0,0,0,0,0,0,252,255,207,0,0,0,0,0,0,0,0,244,255,79,0,0,0,0,0,
+ 0,0,0,176,255,12,0,0,0,0,0,0,0,0,64,255,4,0,0,0,0,0,0,0,0,0,101,0,0,0,0,0,
+ 241,255,255,255,79,0,0,32,77,0,0,96,255,255,255,4,176,255,255,255,159,0,0,176,223,1,0,176,255,255,239,0,
+ 96,255,255,255,239,0,0,247,255,9,0,241,255,255,159,0,16,254,255,255,255,3,48,255,255,95,0,245,255,255,79,0,
+ 0,250,255,255,255,8,209,255,255,239,1,250,255,255,14,0,0,245,255,255,255,13,250,255,255,255,10,254,255,255,9,0,
+ 0,224,255,255,255,143,255,255,255,255,175,255,255,255,4,0,0,144,255,255,255,255,255,255,255,255,255,255,255,239,0,0,
+ 0,64,255,255,255,255,255,255,255,255,255,255,255,159,0,0,0,0,253,255,255,255,255,255,255,255,255,255,255,95,0,0,
+ 0,0,248,255,255,255,255,255,255,255,255,255,255,14,0,0,0,0,243,255,255,255,255,191,250,255,255,255,255,10,0,0,
+ 0,0,192,255,255,255,255,29,225,255,255,255,255,5,0,0,0,0,112,255,255,255,255,4,64,255,255,255,239,0,0,0,
+ 0,0,32,255,255,255,143,0,0,249,255,255,175,0,0,0,0,0,0,251,255,255,11,0,0,209,255,255,95,0,0,0,
+ 0,0,0,246,255,239,2,0,0,48,255,255,30,0,0,0,0,0,0,241,255,95,0,0,0,0,248,255,10,0,0,0,
+ 0,0,0,160,255,8,0,0,0,0,192,255,5,0,0,0,0,0,0,32,138,0,0,0,0,0,32,138,0,0,0,0,
+ 183,187,187,187,8,0,181,187,187,43,0,242,255,255,255,63,0,253,255,255,10,0,128,255,255,255,191,112,255,255,255,2,
+ 0,16,253,255,255,255,229,255,255,159,0,0,0,244,255,255,255,255,255,255,30,0,0,0,160,255,255,255,255,255,255,7,
+ 0,0,0,32,254,255,255,255,255,223,1,0,0,0,0,247,255,255,255,255,111,0,0,0,0,0,208,255,255,255,255,12,
+ 0,0,0,0,0,128,255,255,255,255,10,0,0,0,0,0,225,255,255,255,255,79,0,0,0,0,0,247,255,255,255,255,
+ 223,0,0,0,0,16,254,255,255,255,255,255,8,0,0,0,128,255,255,255,255,255,255,47,0,0,0,242,255,255,239,255,
+ 255,255,191,0,0,0,249,255,255,95,254,255,255,255,5,0,32,255,255,255,11,246,255,255,255,30,0,160,255,255,255,4,
+ 208,255,255,255,159,0,243,255,255,207,0,96,255,255,255,255,3,180,187,187,187,27,0,182,187,187,91,208,255,255,255,127,
+ 16,254,255,255,30,96,255,255,255,223,112,255,255,255,7,0,253,255,255,255,214,255,255,239,1,0,246,255,255,255,255,255,
+ 255,127,0,0,208,255,255,255,255,255,255,30,0,0,96,255,255,255,255,255,255,7,0,0,0,253,255,255,255,255,239,1,
+ 0,0,0,246,255,255,255,255,127,0,0,0,0,208,255,255,255,255,30,0,0,0,0,96,255,255,255,255,7,0,0,0,
+ 0,0,254,255,255,239,1,0,0,0,0,0,252,255,255,207,0,0,0,0,0,0,252,255,255,207,0,0,0,0,0,0,
+ 252,255,255,207,0,0,0,0,0,0,252,255,255,207,0,0,0,0,0,0,252,255,255,207,0,0,0,0,0,0,252,255,
+ 255,207,0,0,0,0,0,0,252,255,255,207,0,0,0,176,187,187,187,187,187,187,187,187,59,240,255,255,255,255,255,255,
+ 255,255,63,240,255,255,255,255,255,255,255,255,11,240,255,255,255,255,255,255,255,255,3,240,255,255,255,255,255,255,255,143,
+ 0,240,255,255,255,255,255,255,255,29,0,0,0,0,192,255,255,255,255,5,0,0,0,0,247,255,255,255,175,0,0,0,
+ 0,32,254,255,255,255,46,0,0,0,0,160,255,255,255,255,7,0,0,0,0,244,255,255,255,207,0,0,0,0,0,253,
+ 255,255,255,79,0,0,0,0,112,255,255,255,255,9,0,0,0,0,226,255,255,255,255,137,136,136,40,0,250,255,255,255,
+ 255,255,255,255,63,64,255,255,255,255,255,255,255,255,63,208,255,255,255,255,255,255,255,255,63,247,255,255,255,255,255,255,
+ 255,255,63,251,255,255,255,255,255,255,255,255,63,
+};
diff --git a/games/numdash/src/assets.h b/games/numdash/src/assets.h
new file mode 100644
index 00000000..a770c41e
--- /dev/null
+++ b/games/numdash/src/assets.h
@@ -0,0 +1,117 @@
+/* Generated by tools/assets.py. Do not edit. */
+#ifndef NUMDASH_ASSETS_H
+#define NUMDASH_ASSETS_H
+#include <stdint.h>
+typedef struct { uint16_t w, h; int16_t ax, ay; uint8_t fmt, pal; uint32_t off; } Sprite;
+typedef struct { uint8_t cap, outline; int8_t sdx, sdy; uint8_t shadow; uint16_t base; const uint8_t *advance; } Font;
+enum {
+ SPR_BLOCK = 0,
+ SPR_GRID_T = 1,
+ SPR_GRID_TL = 2,
+ SPR_GRID_C = 3,
+ SPR_GRID_NONE = 4,
+ SPR_GRID_LTR = 5,
+ SPR_GRID_LR = 6,
+ SPR_GLOW_ALL = 7,
+ SPR_GLOW_T = 8,
+ SPR_GLOW_TL = 9,
+ SPR_GLOW_C = 10,
+ SPR_GLOW_LTR = 11,
+ SPR_GLOW_LR = 12,
+ SPR_SPIKE = 13,
+ SPR_SPIKE_SMALL = 14,
+ SPR_SPIKE_MED = 15,
+ SPR_GLOW_SPIKE = 16,
+ SPR_GLOW_SPIKE_SMALL = 17,
+ SPR_GLOW_SPIKE_MED = 18,
+ SPR_PIT0 = 19,
+ SPR_PIT1 = 20,
+ SPR_PIT2 = 21,
+ SPR_PLANK = 22,
+ SPR_GLOW_PLANK = 23,
+ SPR_SLAB0 = 24,
+ SPR_SLAB1 = 25,
+ SPR_SLAB2 = 26,
+ SPR_SLAB3 = 27,
+ SPR_ROD1 = 28,
+ SPR_ROD2 = 29,
+ SPR_ROD3 = 30,
+ SPR_ROD_BALL = 31,
+ SPR_DSPIKES1 = 32,
+ SPR_DSPIKES2 = 33,
+ SPR_DSPIKES3 = 34,
+ SPR_DSPIKES4 = 35,
+ SPR_CHAIN = 36,
+ SPR_CHAIN_SHORT = 37,
+ SPR_STAR = 38,
+ SPR_DIAG_BLOCK = 39,
+ SPR_PAD_YELLOW = 40,
+ SPR_GLOW_PAD_YELLOW = 41,
+ SPR_PAD_BLUE = 42,
+ SPR_GLOW_PAD_BLUE = 43,
+ SPR_PAD_PINK = 44,
+ SPR_GLOW_PAD_PINK = 45,
+ SPR_ORB_YELLOW = 46,
+ SPR_GLOW_ORB_YELLOW = 47,
+ SPR_ORB_BLUE = 48,
+ SPR_GLOW_ORB_BLUE = 49,
+ SPR_ORB_PINK = 50,
+ SPR_GLOW_ORB_PINK = 51,
+ SPR_PORTAL_GRAV_BLUE_BACK = 52,
+ SPR_PORTAL_GRAV_BLUE_FRONT = 53,
+ SPR_PORTAL_GRAV_YELLOW_BACK = 54,
+ SPR_PORTAL_GRAV_YELLOW_FRONT = 55,
+ SPR_PORTAL_CUBE_BACK = 56,
+ SPR_PORTAL_CUBE_FRONT = 57,
+ SPR_PORTAL_SHIP_BACK = 58,
+ SPR_PORTAL_SHIP_FRONT = 59,
+ SPR_COIN0 = 60,
+ SPR_COIN1 = 61,
+ SPR_COIN2 = 62,
+ SPR_COIN3 = 63,
+ SPR_CUBE1_P = 64,
+ SPR_CUBE1_S = 65,
+ SPR_SHIP1_P = 66,
+ SPR_SHIP1_S = 67,
+ SPR_BTN_PLAY = 68,
+ SPR_BTN_GARAGE = 69,
+ SPR_BTN_CREATOR = 70,
+ SPR_BTN_SETTINGS = 71,
+ SPR_BTN_STATS = 72,
+ SPR_BTN_HELP = 73,
+ SPR_BTN_BACK = 74,
+ SPR_BTN_RESUME = 75,
+ SPR_BTN_REPLAY = 76,
+ SPR_BTN_MENU = 77,
+ SPR_BTN_PRACTICE = 78,
+ SPR_BTN_NORMAL = 79,
+ SPR_BTN_SETTINGS_SMALL = 80,
+ SPR_BTN_PAUSE = 81,
+ SPR_ARROW_BACK = 82,
+ SPR_NAV_ARROW = 83,
+ SPR_FACE1 = 84,
+ SPR_FACE2 = 85,
+ SPR_FACE3 = 86,
+ SPR_FACE4 = 87,
+ SPR_FACE5 = 88,
+ SPR_STAR_UI = 89,
+ SPR_STAR_BIG = 90,
+ SPR_COIN_UI = 91,
+ SPR_COIN_UI_EMPTY = 92,
+ SPR_COIN_BIG = 93,
+ SPR_COIN_BIG_EMPTY = 94,
+ SPR_SIDE_ART = 95,
+ SPR_CHECK_ON = 96,
+ SPR_CHECK_OFF = 97,
+ SPR_COUNT = 245
+};
+extern const Sprite sprites[SPR_COUNT];
+extern const uint8_t sprite_blob[];
+extern const uint16_t sprite_pal_rgb[][16];
+extern const uint8_t sprite_pal_a[][16];
+enum { FONT_SMALL, FONT_BIG, FONT_HUGE };
+extern const Font fonts[3];
+extern const uint8_t font_charmap[96];
+#define BG_RECTS 30
+extern const uint16_t bg_rects[BG_RECTS][4];
+#endif
diff --git a/games/numdash/src/editor.c b/games/numdash/src/editor.c
new file mode 100644
index 00000000..484730cb
--- /dev/null
+++ b/games/numdash/src/editor.c
@@ -0,0 +1,464 @@
+/* "My levels" list and the level editor, laid out like Geometry Dash's
+ * editor: grid view on top, build/edit/delete modes and an object palette
+ * in the bottom panel. */
+#include "app.h"
+#include "ui.h"
+#include <math.h>
+#include <string.h>
+
+enum { MODE_BUILD, MODE_EDIT, MODE_DELETE };
+enum { UNDO_ADD, UNDO_REMOVE, UNDO_XF };
+typedef struct { uint8_t op; uint16_t index; LObj obj; } Undo;
+#define UNDO_N 32
+#define PAGE_ITEMS 12
+#define PAGES ((EDITOR_TYPES + PAGE_ITEMS - 1) / PAGE_ITEMS)
+
+static Level edit_level;
+static CustomMeta meta;
+static unsigned count;
+static Undo undo[UNDO_N];
+static int undo_len;
+static SceneOpts opts;
+static bool settings_open;
+static int settings_sel, clear_armed;
+static const char *const slot_names[CUSTOM_SLOTS] = {"MY LEVEL 1", "MY LEVEL 2", "MY LEVEL 3"};
+static const char *const theme_names[LEVEL_COUNT] = {"BLUE", "PINK", "GREEN", "RED", "OCEAN", "PURPLE", "VIOLET"};
+
+static int clampi(int v, int lo, int hi) { return v < lo ? lo : v > hi ? hi : v; }
+
+static void fill_level(Level *L, int slot, const CustomMeta *m, unsigned n) {
+ memset(L, 0, sizeof(*L));
+ const LevelDef *d = &level_defs[m->theme % LEVEL_COUNT];
+ L->name = slot_names[slot];
+ L->objs = level_objs;
+ L->count = (uint16_t)n;
+ unsigned end = n ? level_objs[n - 1].x + 300u : 0;
+ if (end < 900) end = 900;
+ if (end > 64000) end = 64000;
+ L->end_x = (uint16_t)end;
+ L->wall_x = (uint16_t)end;
+ memcpy(L->colors[CH_BG], d->bg, 3);
+ memcpy(L->colors[CH_G1], d->g1, 3);
+ memset(L->colors[CH_LINE], 255, 3);
+ memset(L->colors[CH_OBJ], 255, 3);
+ L->bpm = 120;
+ L->start_mode = m->flags & 1 ? MODE_SHIP : MODE_CUBE;
+ level_index_coins(L);
+}
+
+bool editor_load_slot(int slot, Level *L) {
+ if (slot < 0 || slot >= CUSTOM_SLOTS) return false;
+ if (!app.testing) {
+ CustomMeta m = {0};
+ count = 0;
+ if (save_read_custom(slot, level_objs, CUSTOM_MAX, &m)) count = m.count;
+ else m = custom_meta[slot];
+ meta = m;
+ }
+ fill_level(L, slot, &meta, count);
+ return level_valid(L) || count == 0;
+}
+
+static bool save_level(void) {
+ meta.count = (uint16_t)count;
+ fill_level(&edit_level, app.slot, &meta, count);
+ meta.end_x = edit_level.end_x;
+ meta.exists = true;
+ bool ok = save_write_custom(app.slot, level_objs, count, &meta);
+ if (ok) {
+ custom_meta[app.slot] = meta;
+ app.dirty = false;
+ /* edits reset the progress of the level */
+ }
+ return ok;
+}
+
+unsigned editor_object_count(void) { return count; }
+
+void editor_flush(void) {
+ if (app.dirty) save_level();
+}
+
+void editor_open(int slot) {
+ if (!app.testing) {
+ editor_load_slot(slot, &edit_level);
+ app.cur_x = 7;
+ app.cur_y = 0;
+ app.edit_cam_x = 0;
+ app.edit_cam_y = 0;
+ app.brush = 0;
+ app.rotate = 0;
+ app.edit_mode = MODE_BUILD;
+ app.edit_page = 0;
+ undo_len = 0;
+ app.dirty = false;
+ }
+ app.testing = false;
+ settings_open = false;
+ fx_reset();
+ fill_level(&edit_level, slot, &meta, count);
+}
+
+/* ------------------------------------------------------------ editing */
+
+static int brush_type(void) { return editor_types[clampi(app.brush, 0, EDITOR_TYPES - 1)]; }
+
+static void cell_offset(int type, int rot, int *ox, int *oy) {
+ int dy = objdefs[type].editor_dy;
+ switch (rot & 3) {
+ case 1: *ox = dy; *oy = 0; break;
+ case 2: *ox = 0; *oy = -dy; break;
+ case 3: *ox = -dy; *oy = 0; break;
+ default: *ox = 0; *oy = dy; break;
+ }
+}
+
+static int find_in_cell(int col, int row, int from_end) {
+ int x0 = col * 30, y0 = row * 30;
+ unsigned i = level_lower_bound(&edit_level, x0);
+ int found = -1;
+ for (; i < count && level_objs[i].x < x0 + 30; i++)
+ if (level_objs[i].y >= y0 && level_objs[i].y < y0 + 30) {
+ found = (int)i;
+ if (!from_end) break;
+ }
+ return found;
+}
+
+static void push_undo(int op, unsigned index, LObj o) {
+ if (undo_len == UNDO_N) { memmove(undo, undo + 1, sizeof(Undo) * (UNDO_N - 1)); undo_len--; }
+ undo[undo_len++] = (Undo){(uint8_t)op, (uint16_t)index, o};
+}
+
+static void remove_at(unsigned i) {
+ memmove(level_objs + i, level_objs + i + 1, (count - i - 1) * sizeof(LObj));
+ count--;
+}
+static unsigned insert_obj(LObj o) {
+ unsigned i = count;
+ while (i && level_objs[i - 1].x > o.x) { level_objs[i] = level_objs[i - 1]; i--; }
+ level_objs[i] = o;
+ count++;
+ return i;
+}
+
+static void edited(void) {
+ app.dirty = true;
+ fill_level(&edit_level, app.slot, &meta, count);
+ LevelStat *s = &progress.lv[LEVEL_COUNT + app.slot];
+ s->normal = s->practice = 0;
+}
+
+static void place(void) {
+ int type = brush_type(), ox, oy;
+ cell_offset(type, app.rotate, &ox, &oy);
+ LObj o = {(uint16_t)(app.cur_x * 30 + 15 + ox), (int16_t)(app.cur_y * 30 + 15 + oy), (uint8_t)type, (uint8_t)(app.rotate & 3)};
+ /* the same object in the same cell is replaced */
+ int x0 = app.cur_x * 30, y0 = app.cur_y * 30;
+ for (unsigned i = level_lower_bound(&edit_level, x0); i < count && level_objs[i].x < x0 + 30; i++)
+ if (level_objs[i].type == type && level_objs[i].y >= y0 && level_objs[i].y < y0 + 30) {
+ push_undo(UNDO_REMOVE, i, level_objs[i]);
+ remove_at(i);
+ break;
+ }
+ if (count >= CUSTOM_MAX) { app_notice("OBJECT LIMIT REACHED"); return; }
+ unsigned i = insert_obj(o);
+ push_undo(UNDO_ADD, i, o);
+ edited();
+}
+
+static void erase(void) {
+ int i = find_in_cell(app.cur_x, app.cur_y, 1);
+ if (i < 0) return;
+ push_undo(UNDO_REMOVE, (unsigned)i, level_objs[i]);
+ remove_at((unsigned)i);
+ edited();
+}
+
+static void rotate_obj(void) {
+ int i = find_in_cell(app.cur_x, app.cur_y, 1);
+ if (i < 0) return;
+ LObj *o = &level_objs[i];
+ push_undo(UNDO_XF, (unsigned)i, *o);
+ int ox, oy, nx, ny, r = o->xf & 3;
+ cell_offset(o->type, r, &ox, &oy);
+ cell_offset(o->type, r + 1, &nx, &ny);
+ o->x = (uint16_t)(o->x - ox + nx);
+ o->y = (int16_t)(o->y - oy + ny);
+ o->xf = (uint8_t)((o->xf & ~3) | ((r + 1) & 3));
+ /* keep the list sorted after the horizontal shift */
+ LObj moved = *o;
+ remove_at((unsigned)i);
+ insert_obj(moved);
+ undo_len = 0; /* index-based history is no longer valid */
+ edited();
+}
+
+static void undo_last(void) {
+ if (!undo_len) { app_notice("NOTHING TO UNDO"); return; }
+ Undo u = undo[--undo_len];
+ if (u.op == UNDO_ADD) {
+ if (u.index < count) remove_at(u.index);
+ } else if (u.op == UNDO_REMOVE) {
+ if (count < CUSTOM_MAX) insert_obj(u.obj);
+ } else if (u.index < count) {
+ level_objs[u.index] = u.obj;
+ }
+ edited();
+}
+
+static void pick(void) {
+ int i = find_in_cell(app.cur_x, app.cur_y, 1);
+ if (i < 0) return;
+ for (int k = 0; k < EDITOR_TYPES; k++)
+ if (editor_types[k] == level_objs[i].type) { app.brush = k; app.edit_page = k / PAGE_ITEMS; }
+ app.rotate = level_objs[i].xf & 3;
+ app.edit_mode = MODE_BUILD;
+}
+
+static void settings_tick(void) {
+ if (app_hit(K_BACK | K_PROPS)) { settings_open = false; return; }
+ if (app_hit(K_UP)) settings_sel = (settings_sel + 2) % 3;
+ if (app_hit(K_DOWN)) settings_sel = (settings_sel + 1) % 3;
+ if (settings_sel != 2) clear_armed = 0;
+ int d = app_hit(K_RIGHT) ? 1 : app_hit(K_LEFT) ? -1 : 0;
+ if (settings_sel == 0 && d) { meta.theme = (uint8_t)((meta.theme + LEVEL_COUNT + d) % LEVEL_COUNT); edited(); }
+ if (settings_sel == 1 && (d || app_accept())) { meta.flags ^= 1; edited(); }
+ if (settings_sel == 2 && app_accept()) {
+ if (clear_armed) {
+ count = 0;
+ undo_len = 0;
+ clear_armed = 0;
+ edited();
+ app_notice("LEVEL CLEARED");
+ } else {
+ clear_armed = 1;
+ }
+ }
+}
+
+void editor_tick(void) {
+ if (app.fading_out) return;
+ if (settings_open) { settings_tick(); return; }
+ uint32_t h = app.hit;
+ if (h & K_BACK) {
+ if (app.dirty && !save_level()) app_notice("SAVE FAILED - STORAGE FULL");
+ app_go(SCR_CREATOR);
+ return;
+ }
+ if (h & K_EXE) {
+ if (app.dirty && !save_level()) app_notice("NOT SAVED - STORAGE FULL");
+ app.testing = true;
+ app.level = LEVEL_COUNT + app.slot;
+ app.practice = false;
+ app_go(SCR_PLAY);
+ return;
+ }
+ if (h & K_LEFT) app.cur_x--;
+ if (h & K_RIGHT) app.cur_x++;
+ if (h & K_UP) app.cur_y++;
+ if (h & K_DOWN) app.cur_y--;
+ app.cur_x = clampi(app.cur_x, 0, 2100);
+ app.cur_y = clampi(app.cur_y, 0, 39);
+ if (h & (K_PLUS | K_TOOL)) { app.brush = (app.brush + 1) % EDITOR_TYPES; app.edit_mode = MODE_BUILD; }
+ if (h & K_MINUS) { app.brush = (app.brush + EDITOR_TYPES - 1) % EDITOR_TYPES; app.edit_mode = MODE_BUILD; }
+ app.edit_page = app.brush / PAGE_ITEMS;
+ if (h & K_SHIFT) app.rotate = (app.rotate + 1) & 3;
+ if (h & K_CHECK) app.edit_mode = (app.edit_mode + 1) % 3;
+ if (h & (K_OK)) {
+ if (app.edit_mode == MODE_BUILD) place();
+ else if (app.edit_mode == MODE_EDIT) rotate_obj();
+ else erase();
+ }
+ if (h & K_ERASE) erase();
+ if (h & K_UNDO) undo_last();
+ if (h & K_COPY) pick();
+ if (h & K_SAVE) app_notice(save_level() ? "LEVEL SAVED" : "SAVE FAILED - STORAGE FULL");
+ if (h & K_PROPS) { settings_open = true; settings_sel = 0; clear_armed = 0; }
+}
+
+void editor_frame(float dt) {
+ /* camera keeps the cursor inside the view */
+ float cx = app.cur_x * 30 + 15, cy = app.cur_y * 30 + 15;
+ float want_x = app.edit_cam_x, want_y = app.edit_cam_y;
+ if (cx - want_x < 90) want_x = cx - 90;
+ if (cx - want_x > VIEW_W - 90) want_x = cx - (VIEW_W - 90);
+ if (want_x < -60) want_x = -60;
+ /* the bottom panel hides the lowest 90 units of the view */
+ if (cy - want_y > 250) want_y = cy - 250;
+ if (cy - want_y < 15) want_y = cy - 15;
+ if (want_y < 0) want_y = 0;
+ float k = fminf(1, dt * 14);
+ app.edit_cam_x += (want_x - app.edit_cam_x) * k;
+ app.edit_cam_y += (want_y - app.edit_cam_y) * k;
+ Game *g = &app.g;
+ memset(g, 0, sizeof(*g));
+ g->L = &edit_level;
+ g->cam_x = app.edit_cam_x;
+ g->cam_y = app.edit_cam_y;
+ g->ground_x = g->bg_x = app.edit_cam_x;
+ g->dead = true;
+ for (int c = 0; c < CH_COUNT; c++) memcpy(g->ch[c].cur, edit_level.colors[c], 3);
+ memset(&opts, 0, sizeof(opts));
+ opts.p1 = app_p1();
+ opts.p2 = app_p2();
+ opts.editor = true;
+ opts.hide_player = true;
+ opts.time = app.t;
+ scene_prepare(g, &opts);
+}
+
+/* ------------------------------------------------------------ drawing */
+
+static void draw_type_icon(int type, int cx, int cy, int box, int rot, unsigned alpha) {
+ const ObjDef *d = &objdefs[type];
+ int w = 0, h = 0;
+ for (int k = 0; k < d->nparts; k++) {
+ const Sprite *s = &sprites[d->parts[k].sprite];
+ if (d->parts[k].ctype >= CT_GLOW) continue;
+ if (s->w > w) w = s->w;
+ if (s->h > h) h = s->h;
+ }
+ float sc = box / (float)(w > h ? w : h);
+ if (sc > 1) sc = 1;
+ for (int k = d->nparts - 1; k >= 0; k--) {
+ const ObjPart *pt = &d->parts[k];
+ if (pt->ctype >= CT_GLOW) continue;
+ color_t tint = pt->ctype == CT_BLACK ? 0 : pt->ctype == CT_P1ADD ? app_p1() : pt->ctype == CT_P2ADD ? app_p2() : 0xffff;
+ int mode = pt->ctype == CT_P1ADD || pt->ctype == CT_P2ADD ? BLEND_ADD : BLEND_NORMAL;
+ float ox = pt->dx4 / 4.f * (2.f / 3) * sc, oy = -pt->dy4 / 4.f * (2.f / 3) * sc;
+ gfx_sprite_ex(pt->sprite, (int)((cx + ox) * 16), (int)((cy + oy) * 16), rot * 90 * 16, (int)(sc * 256), 0, tint, alpha, mode);
+ }
+}
+
+static void draw_cursor(void) {
+ const Game *g = &app.g;
+ float sx = wx_to_sx(g, app.cur_x * 30.0f), sy = wy_to_sy(g, app.cur_y * 30.0f + 30);
+ int x = (int)floorf(sx + .5f), y = (int)floorf(sy + .5f);
+ if (app.edit_mode == MODE_BUILD) {
+ int ox, oy, t = brush_type();
+ cell_offset(t, app.rotate, &ox, &oy);
+ draw_type_icon(t, x + 10 + ox * 2 / 3, y + 10 - oy * 2 / 3, 40, app.rotate, 150);
+ }
+ color_t c = app.edit_mode == MODE_BUILD ? 0xffff : app.edit_mode == MODE_EDIT ? rgb(0, 255, 0) : rgb(255, 60, 60);
+ unsigned a = (unsigned)(170 + 80 * sinf(app.t * 6));
+ gfx_blend(x, y, 21, 2, c, a);
+ gfx_blend(x, y + 19, 21, 2, c, a);
+ gfx_blend(x, y + 2, 2, 17, c, a);
+ gfx_blend(x + 19, y + 2, 2, 17, c, a);
+}
+
+static void panel(void) {
+ const int top = 178;
+ gfx_blend(0, top, GFX_W, GFX_H - top, 0, 190);
+ gfx_fill(0, top, GFX_W, 1, rgb(90, 90, 90));
+ static const char *const modes[3] = {"BUILD", "EDIT", "DELETE"};
+ for (int i = 0; i < 3; i++) ui_text_button(30, top + 12 + i * 20, 50, 17, modes[i], app.edit_mode == i ? BTN_GREEN : BTN_GRAY, 1);
+ int page = app.edit_page;
+ for (int k = 0; k < PAGE_ITEMS; k++) {
+ int idx = page * PAGE_ITEMS + k;
+ if (idx >= EDITOR_TYPES) break;
+ int bx = 70 + (k % 6) * 32, by = top + 5 + (k / 6) * 29;
+ bool on = idx == app.brush;
+ gfx_round_rect(bx, by, 28, 26, 4, 0, 256);
+ gfx_round_rect(bx + 1, by + 1, 26, 24, 3, on ? rgb(90, 210, 60) : rgb(150, 150, 150), 256);
+ gfx_round_rect(bx + 2, by + 2, 24, 22, 3, on ? rgb(60, 160, 40) : rgb(105, 105, 105), 256);
+ draw_type_icon(editor_types[idx], bx + 14, by + 13, 20, 0, 256);
+ }
+ ui_nav_dots(286, top + 12, PAGES, page);
+ char buf[16];
+ int n = gfx_format_uint(buf, count);
+ buf[n++] = '/';
+ gfx_format_uint(buf + n, CUSTOM_MAX);
+ gfx_text_center(FONT_SMALL, 286, top + 34, buf, 0xffff, 0xffff, 220);
+ static const char *const rots[4] = {"ROT 0", "ROT 90", "ROT 180", "ROT 270"};
+ gfx_text_center(FONT_SMALL, 286, top + 50, rots[app.rotate], 0xffff, 0xffff, 220);
+}
+
+static void settings_draw(void) {
+ ui_dim(110);
+ ui_window_brown(40, 44, 240, 150);
+ ui_title(FONT_BIG, 160, 70, "LEVEL SETTINGS");
+ const LevelDef *d = &level_defs[meta.theme % LEVEL_COUNT];
+ const char *labels[3] = {"COLORS", "START MODE", "CLEAR LEVEL"};
+ for (int i = 0; i < 3; i++) {
+ int y = 98 + i * 28;
+ color_t t = settings_sel == i ? GOLD_TOP : 0xffff, b = settings_sel == i ? GOLD_BOTTOM : 0xffff;
+ gfx_text(FONT_SMALL, 60, y + 4, labels[i], t, b, 256);
+ }
+ gfx_round_rect(176, 90, 18, 16, 3, 0, 256);
+ gfx_fill(177, 91, 16, 14, rgb(d->bg[0], d->bg[1], d->bg[2]));
+ gfx_text(FONT_SMALL, 200, 102, theme_names[meta.theme % LEVEL_COUNT], 0xffff, 0xffff, 256);
+ gfx_text(FONT_SMALL, 200, 130, meta.flags & 1 ? "SHIP" : "CUBE", 0xffff, 0xffff, 256);
+ ui_text_button(214, 154, 90, 20, clear_armed ? "SURE?" : "CLEAR", clear_armed ? BTN_PINK : BTN_GRAY, settings_sel == 2 ? 1.08f : 1);
+ gfx_text_center(FONT_SMALL, 160, 186, "LEFT RIGHT: CHANGE BACK: CLOSE", rgb(255, 230, 190), rgb(255, 230, 190), 220);
+}
+
+void editor_draw(void) {
+ scene_draw();
+ draw_cursor();
+ panel();
+ gfx_text(FONT_SMALL, 6, 12, slot_names[app.slot], 0xffff, 0xffff, 230);
+ if (app.dirty) gfx_text(FONT_SMALL, 6, 24, "UNSAVED", rgb(255, 220, 120), rgb(255, 180, 60), 230);
+ gfx_text_right(FONT_SMALL, 314, 12, "EXE: PLAYTEST", 0xffff, 0xffff, 200);
+ gfx_text_right(FONT_SMALL, 314, 24, "LN: SETTINGS", 0xffff, 0xffff, 200);
+ if (settings_open) settings_draw();
+}
+
+/* ------------------------------------------------------------ my levels */
+
+void creator_tick(void) {
+ if (app_hit(K_BACK)) { app_go(SCR_MENU); return; }
+ if (app_hit(K_UP)) app.row = (app.row + CUSTOM_SLOTS - 1) % CUSTOM_SLOTS;
+ if (app_hit(K_DOWN)) app.row = (app.row + 1) % CUSTOM_SLOTS;
+ if (app_hit(K_LEFT | K_RIGHT)) app.sel ^= 1;
+ if (app_accept()) {
+ app.slot = app.row;
+ if (app.sel == 0) {
+ app.testing = false;
+ app_go(SCR_EDITOR);
+ } else if (!custom_meta[app.row].exists || !custom_meta[app.row].count) {
+ app_notice("THIS LEVEL IS EMPTY");
+ } else {
+ app.level = LEVEL_COUNT + app.row;
+ app.practice = false;
+ app.testing = false;
+ app_go(SCR_PLAY);
+ }
+ }
+}
+
+void creator_draw(void) {
+ ui_gradient_bg(rgb(0, 102, 255));
+ gfx_sprite(SPR_ARROW_BACK, 22, 26, 0, 0xffff, 256, BLEND_NORMAL);
+ /* list frame: lime sides and the header bar */
+ gfx_round_rect(26, 46, 268, 172, 4, 0, 256);
+ gfx_vgrad(28, 48, 6, 168, rgb(190, 242, 72), rgb(80, 150, 30));
+ gfx_vgrad(286, 48, 6, 168, rgb(190, 242, 72), rgb(80, 150, 30));
+ ui_top_bar(40, false);
+ ui_title(FONT_BIG, 160, 38, "MY LEVELS");
+ for (int i = 0; i < CUSTOM_SLOTS; i++) {
+ int y = 52 + i * 54;
+ color_t c = i & 1 ? rgb(161, 88, 44) : rgb(194, 114, 62);
+ gfx_fill(34, y, 252, 54, c);
+ gfx_fill(34, y + 53, 252, 1, rgb(120, 60, 30));
+ const CustomMeta *m = &custom_meta[i];
+ gfx_text(FONT_BIG, 44, y + 24, slot_names[i], 0xffff, 0xffff, 256);
+ char buf[24];
+ int n = gfx_format_uint(buf, m->exists ? m->count : 0);
+ memcpy(buf + n, " OBJECTS", 9);
+ gfx_text(FONT_SMALL, 46, y + 42, buf, rgb(255, 230, 190), rgb(255, 230, 190), 256);
+ const LevelStat *s = &progress.lv[LEVEL_COUNT + i];
+ if (m->exists && m->count) {
+ n = gfx_format_uint(buf, s->normal);
+ memcpy(buf + n, "%", 2);
+ gfx_text(FONT_SMALL, 140, y + 42, buf, 0xffff, 0xffff, 220);
+ }
+ bool row = app.row == i;
+ ui_text_button(216, y + 27, 52, 22, "EDIT", BTN_GREEN, row && app.sel == 0 ? 1.12f : 1);
+ ui_text_button(266, y + 27, 42, 22, "PLAY", BTN_CYAN, row && app.sel == 1 ? 1.12f : 1);
+ }
+ gfx_round_rect(26, 212, 268, 8, 3, 0, 256);
+ gfx_vgrad(28, 213, 264, 5, rgb(190, 242, 72), rgb(80, 150, 30));
+ gfx_text_center(FONT_SMALL, 160, 234, "UP DOWN: LEVEL LEFT RIGHT: EDIT / PLAY", 0xffff, 0xffff, 200);
+}
diff --git a/games/numdash/src/fx.c b/games/numdash/src/fx.c
new file mode 100644
index 00000000..5236f5b8
--- /dev/null
+++ b/games/numdash/src/fx.c
@@ -0,0 +1,417 @@
+/* Particles, circle "use effects", motion trail and ghost trail.
+ * Particle and circle parameters follow Geometry Dash's effect definitions
+ * (sizes and speeds in GD units, additive blending). */
+#include "fx.h"
+#include "scene.h"
+#include <math.h>
+#include <string.h>
+
+#define PX (2.0f / 3.0f)
+#define MAX_PARTICLES 240
+#define MAX_CIRCLES 20
+
+typedef struct {
+ uint8_t max; uint8_t radial;
+ float life, life_var, angle, angle_var, speed, speed_var, gx, gy, s0, s0_var, s1, pvx, pvy;
+ uint8_t c0[3], c1[3], a0, a1;
+ float r_max, r_min, rot;
+} PDef;
+static const PDef pdefs[] = {
+ /* drag */ {30, 0, .3f, .15f, 90, 45, 75, 20, 0, -300, 4, 3, 0, 2, 2, {255, 255, 255}, {0, 0, 0}, 255, 255, 0, 0, 0},
+ /* ship fire */ {30, 0, .3f, .15f, 90, 45, 75, 20, 0, -300, 8, 2, 0, 1, 5, {255, 255, 255}, {0, 0, 0}, 255, 255, 0, 0, 0},
+ /* ship smoke */ {30, 0, .4f, .15f, -90, 45, 0, 0, 0, -320, 3, 3, 0, 1, 2, {255, 255, 255}, {0, 0, 0}, 255, 255, 0, 0, 0},
+ /* land */ {100, 0, 0, .6f, 90, 60, 150, 25, 0, -500, 5, 3, 0, 10, 0, {255, 255, 255}, {0, 0, 0}, 255, 255, 0, 0, 0},
+ /* explode */ {100, 0, 0, .8f, 0, 360, 250, 150, 0, 0, 10, 5, 0, 10, 10, {255, 255, 255}, {0, 0, 0}, 255, 255, 0, 0, 0},
+ /* bump (pads) */ {30, 0, .4f, .2f, 90, 0, 100, 20, 0, 0, 3, 1, 0, 14, 0, {255, 255, 0}, {0, 0, 0}, 255, 0, 0, 0, 0},
+ /* ring (orbs) */ {30, 1, .3f, .1f, 0, 360, 75, 20, 0, -300, 4, 2, 0, 3, 5, {255, 255, 255}, {255, 255, 255}, 255, 255, 20, 0, 360},
+ /* portal */ {30, 0, .6f, .4f, 180, 95, 75, 20, 0, 0, 6, 2, 1, 3, 30, {0, 255, 255}, {0, 255, 255}, 128, 255, 0, 0, 0},
+ /* coin sparkle */ {15, 0, .25f, .15f, 270, 0, 70, 10, 0, 0, 5, 2, 1, 6, 5, {255, 255, 0}, {255, 255, 0}, 128, 255, 0, 0, 0},
+ /* coin pickup */ {50, 0, 0, .6f, 0, 360, 100, 30, 0, -400, 5, 2, 2, 10, 10, {255, 255, 0}, {255, 255, 0}, 255, 0, 0, 0, 0},
+ /* level complete */ {200, 0, 0, 1.0f, 270, 180, 125, 50, 0, 0, 6, 2, 2, 200, 20, {255, 255, 255}, {255, 255, 255}, 255, 255, 0, 0, 0},
+ /* firework */ {200, 0, 0, .5f, 0, 180, 180, 50, 0, 0, 6, 2, 2, 5, 5, {255, 255, 255}, {255, 255, 255}, 255, 0, 0, 0, 0},
+};
+
+typedef struct {
+ float x, y, vx, vy, life, age;
+ uint16_t c0, c1;
+ uint8_t a0, a1, s0, s1, def, flags;
+} Particle;
+enum { PF_SCREEN = 1, PF_RADIAL = 2 };
+static Particle parts[MAX_PARTICLES];
+static int nparts;
+
+enum { EI, EO, EL, EQ, EC }; /* ease in, ease out, linear, quad out, cubic out */
+typedef struct { float dur, a0, a1, r0, r1, thick; uint8_t hollow, tri, ea0, ea1, er0, er1; } CDef;
+static const CDef cdefs[] = {
+ /* pad */ {.3f, 1, 0, 4, 40, 0, 0, 0, EI, EL, EQ, EQ},
+ /* orb */ {.4f, .03f, .9f, 37, 3, 0, 0, 1, EC, EL, EL, EL},
+ /* portal */ {.4f, .01f, .91f, 48, 0, 0, 0, 1, EC, EL, EL, EL},
+ /* orb touch */ {.35f, .7f, 0, 0, 65, 1, 1, 0, EI, EO, EQ, EQ},
+ /* death */ {.5f, .9f, 0, 8, 80, 0, 0, 0, EI, EL, EQ, EQ},
+ /* coin */ {.4f, .03f, .9f, 30, 4, 0, 0, 1, EC, EL, EL, EL},
+ /* coin ring */ {.35f, .7f, 0, 0, 65, 2.5f, 1, 0, EI, EO, EQ, EQ},
+ /* wall 1 */ {.5f, 1, 0, 2.5f, 250, 0, 0, 0, EI, EO, EQ, EQ},
+ /* wall 2 */ {.8f, 1, 0, 2.5f, 480, 0, 0, 0, EI, EL, EQ, EQ},
+ /* title */ {1, .9f, 0, 25, 250, 0, 0, 0, EI, EL, EQ, EQ},
+ /* firework */ {.5f, 0, 1, 10, 42.5f, 0, 0, 1, EC, EL, EL, EL},
+ /* big ring */ {.5f, 0, 1, 2.5f, 480, 1.8f, 1, 1, EL, EL, EL, EL},
+ /* respawn */ {.3f, .1f, .95f, 67, 3, 1, 1, 1, EC, EL, EL, EL},
+};
+typedef struct { float x, y, t; uint16_t color; uint8_t def, screen; int16_t obj; } Circle;
+static Circle circles[MAX_CIRCLES];
+
+static const Game *G;
+static float cam_x, cam_y;
+static uint32_t seed = 12345;
+static float rnd(void) { seed = seed * 1664525u + 1013904223u; return (seed >> 8) * (1.0f / 16777216.0f); }
+static float rnd1(void) { return rnd() * 2 - 1; }
+
+/* trail */
+#define TRAIL_N 12
+static float trail_x[TRAIL_N], trail_y[TRAIL_N];
+static int trail_len;
+static bool trail_on;
+static float trail_acc;
+#define GHOST_N 10
+typedef struct { float x, y, rot, life; uint8_t mode, upside; } Ghost;
+static Ghost ghosts[GHOST_N];
+static int ghost_next;
+static float ghost_acc;
+static color_t col_p1, col_p2;
+
+void fx_reset(void) {
+ nparts = 0;
+ memset(circles, 0, sizeof(circles));
+ trail_len = 0;
+ trail_on = false;
+ memset(ghosts, 0, sizeof(ghosts));
+}
+
+static void spawn(int def, float x, float y, color_t c0, bool use_c0, color_t c1, bool use_c1, int flags, float angle_override) {
+ if (nparts >= MAX_PARTICLES) return;
+ const PDef *d = &pdefs[def];
+ Particle *p = &parts[nparts++];
+ float life = d->life + d->life_var * rnd1();
+ if (life < 0.05f) life = 0.05f + rnd() * 0.1f;
+ float ang = ((angle_override < 1e8f ? angle_override : d->angle) + d->angle_var * rnd1()) * 3.14159265f / 180.f;
+ float sp = d->speed + d->speed_var * rnd1();
+ p->x = x + d->pvx * rnd1();
+ p->y = y + d->pvy * rnd1();
+ if (d->radial) {
+ p->x = x; p->y = y;
+ p->vx = ang; /* angle */
+ p->vy = d->r_max; /* start radius */
+ flags |= PF_RADIAL;
+ } else {
+ p->vx = cosf(ang) * sp;
+ p->vy = sinf(ang) * sp;
+ }
+ p->life = life;
+ p->age = 0;
+ color_t sc = use_c0 ? c0 : rgb(d->c0[0], d->c0[1], d->c0[2]);
+ color_t ec = use_c1 ? c1 : rgb(d->c1[0], d->c1[1], d->c1[2]);
+ p->c0 = sc; p->c1 = ec;
+ p->a0 = d->a0; p->a1 = d->a1;
+ float s0 = d->s0 + d->s0_var * rnd1();
+ if (s0 < 1) s0 = 1;
+ p->s0 = (uint8_t)(s0 * 4);
+ p->s1 = (uint8_t)(d->s1 * 4);
+ p->def = (uint8_t)def;
+ p->flags = (uint8_t)flags;
+}
+
+static void circle(float x, float y, int def, color_t c, int obj, bool screen) {
+ for (int i = 0; i < MAX_CIRCLES; i++)
+ if (circles[i].def == 0 || circles[i].t >= cdefs[circles[i].def - 1].dur) {
+ circles[i] = (Circle){x, y, 0, c, (uint8_t)(def + 1), screen, (int16_t)obj};
+ return;
+ }
+}
+void fx_circle_screen(float x, float y, int def, color_t c) { circle(x, y, def, c, -1, true); }
+void fx_circle_world(float x, float y, int def, color_t c) { circle(x, y, def, c, -1, false); }
+void fx_burst_world(float x, float y, int def, color_t c, int count) {
+ for (int i = 0; i < count; i++) spawn(def, x, y, c, true, c, true, 0, 1e9f);
+}
+void fx_burst_screen(float x, float y, int def, color_t c, int count) {
+ for (int i = 0; i < count; i++) spawn(def, x, y, c, true, c, true, PF_SCREEN, 1e9f);
+}
+
+static float ease(int e, float t) {
+ if (t < 0) t = 0;
+ if (t > 1) t = 1;
+ switch (e) {
+ case EI: return t * t;
+ case EO: return sqrtf(t);
+ case EQ: return t * (2 - t);
+ case EC: { float u = 1 - t; return 1 - u * u * u; }
+ default: return t;
+ }
+}
+
+static void emit_rate(float *acc, float rate, float dt) { *acc += rate * dt; }
+
+static float drag_acc, fire_acc, smoke_acc, obj_acc;
+
+void fx_update(Game *g, float dt, color_t p1, color_t p2, bool practice) {
+ G = g;
+ cam_x = g->cam_x;
+ cam_y = g->cam_y;
+ col_p1 = p1;
+ col_p2 = p2;
+ const Player *p = &g->p;
+ /* events from physics */
+ for (int k = 0; k < g->fx_count; k++) {
+ const FxEvent *e = &g->fx[k];
+ switch (e->kind) {
+ case FX_LAND:
+ if (p->mode == MODE_CUBE)
+ for (int i = 0; i < 10; i++) spawn(PE_LAND, e->x, e->y + (p->upside ? 11 : -11), p1, true, 0, false, 0, p->upside ? 270 : 90);
+ break;
+ case FX_PAD: {
+ color_t c = e->arg == 0 ? rgb(255, 200, 0) : e->arg == 1 ? rgb(0, 255, 255) : rgb(255, 50, 255);
+ circle(e->x, e->y, CE_PAD, c, e->obj, false);
+ trail_on = true;
+ break;
+ }
+ case FX_ORB: {
+ color_t c = e->arg == 0 ? rgb(255, 200, 0) : e->arg == 1 ? rgb(255, 50, 255) : rgb(0, 255, 255);
+ circle(e->x, e->y, CE_ORB, c, e->obj, false);
+ trail_on = true;
+ break;
+ }
+ case FX_ORB_TOUCH: circle(e->x, e->y, CE_ORB_TOUCH, 0xffff, e->obj, false); break;
+ case FX_PORTAL: circle(e->x, e->y, CE_PORTAL, e->arg ? rgb(255, 0, 255) : rgb(0, 255, 50), e->obj, false); break;
+ case FX_GRAVITY:
+ circle(e->x, e->y, CE_PORTAL, e->arg ? rgb(255, 200, 0) : rgb(0, 200, 255), e->obj, false);
+ trail_on = true;
+ break;
+ case FX_COIN:
+ if (practice) break;
+ circle(e->x, e->y, CE_COIN, rgb(255, 190, 0), e->obj, false);
+ circle(e->x, e->y, CE_COIN_RING, rgb(255, 190, 0), e->obj, false);
+ for (int i = 0; i < 30; i++) spawn(PE_COIN_PICKUP, e->x, e->y, 0, false, 0, false, 0, 1e9f);
+ break;
+ case FX_DEATH:
+ circle(e->x, e->y, CE_DEATH, p1, -1, false);
+ for (int i = 0; i < 60; i++) spawn(PE_EXPLODE, e->x, e->y, 0, false, 0, false, 0, 1e9f);
+ trail_len = 0;
+ break;
+ case FX_WALL:
+ circle(e->x, e->y, CE_WALL1, p1, -1, false);
+ break;
+ default: break;
+ }
+ }
+ g->fx_count = 0;
+ /* continuous emitters */
+ if (!g->dead && !g->complete) {
+ if (p->mode == MODE_CUBE) {
+ if (p->time_since_ground < 0.1f && !g->ending) {
+ emit_rate(&drag_acc, 100, dt);
+ while (drag_acc >= 1) {
+ drag_acc -= 1;
+ float by = p->upside ? p->y + 13 : p->y - 13;
+ spawn(PE_DRAG, p->x - 15, by, p1, true, 0, false, 0, p->upside ? 270 : 90);
+ }
+ } else {
+ drag_acc = 0;
+ }
+ if (p->on_ground) trail_on = false;
+ } else {
+ trail_on = true;
+ float r = p->rot * 3.14159265f / 180.f, s = p->upside ? -1.f : 1.f;
+ float lx = -14, ly = -8 * s;
+ float ex = p->x + lx * cosf(r) + ly * sinf(r), ey = p->y - lx * sinf(r) + ly * cosf(r);
+ if (g->hold_prev) {
+ emit_rate(&fire_acc, 90, dt);
+ while (fire_acc >= 1) { fire_acc -= 1; spawn(PE_SHIP_FIRE, ex, ey, rgb(255, 150, 0), true, 0, false, 0, 180 + (p->upside ? 20 : -20)); }
+ }
+ emit_rate(&smoke_acc, 60, dt);
+ while (smoke_acc >= 1) { smoke_acc -= 1; spawn(PE_SHIP_SMOKE, ex, ey, p1, true, 0, false, 0, 1e9f); }
+ }
+ /* ambient particles of visible pads, orbs, portals and coins */
+ emit_rate(&obj_acc, 1, dt * 40);
+ int n = (int)obj_acc;
+ obj_acc -= n;
+ if (n > 0) {
+ const Level *L = g->L;
+ unsigned i = level_lower_bound(L, (int)(cam_x - 30));
+ for (; i < L->count && L->objs[i].x < cam_x + VIEW_W + 30; i++) {
+ const LObj *o = &L->objs[i];
+ int sp = objdefs[o->type].special;
+ for (int k = 0; k < n; k++) {
+ if (sp == SP_PAD_Y || sp == SP_PAD_P || sp == SP_PAD_B) {
+ color_t c = sp == SP_PAD_Y ? rgb(255, 255, 0) : sp == SP_PAD_B ? rgb(0, 255, 255) : rgb(255, 0, 255);
+ bool down = (o->xf & 3) == 2 || (o->xf & 8);
+ if (rnd() < 0.8f) spawn(PE_BUMP, o->x, o->y, c, true, 0, false, 0, down ? 270 : 90);
+ } else if (sp >= SP_ORB_Y && sp <= SP_ORB_B && !game_used(g, i)) {
+ color_t c = sp == SP_ORB_Y ? rgb(255, 255, 0) : sp == SP_ORB_P ? rgb(255, 0, 255) : rgb(0, 255, 255);
+ if (rnd() < 0.9f) spawn(PE_RING, o->x, o->y, c, true, c, true, 0, 1e9f);
+ } else if (sp >= SP_GRAV_N && sp <= SP_PORTAL_SHIP) {
+ color_t c = sp == SP_GRAV_N ? rgb(0, 255, 255) : sp == SP_GRAV_F ? rgb(255, 255, 0) : sp == SP_PORTAL_CUBE ? rgb(0, 255, 0) : rgb(255, 0, 255);
+ if (rnd() < 0.6f) spawn(PE_PORTAL, o->x + 14, o->y, c, true, c, true, 0, 180);
+ } else if (sp == SP_COIN && !game_used(g, i)) {
+ if (rnd() < 0.5f) spawn(PE_COIN, o->x, o->y - 10, 0, false, 0, false, 0, 1e9f);
+ }
+ }
+ }
+ }
+ }
+ /* motion trail samples */
+ trail_acc += dt;
+ bool sample = trail_acc >= 1.0f / 40;
+ if (sample) trail_acc -= 1.0f / 40;
+ if (trail_acc > 0.1f) trail_acc = 0;
+ if (!g->dead && (trail_on || g->ending) && !(p->mode == MODE_CUBE && p->on_ground)) {
+ if (sample) {
+ if (trail_len < TRAIL_N) trail_len++;
+ for (int i = trail_len - 1; i > 0; i--) { trail_x[i] = trail_x[i - 1]; trail_y[i] = trail_y[i - 1]; }
+ }
+ trail_x[0] = p->x;
+ trail_y[0] = p->y;
+ } else if (trail_len > 0 && sample) {
+ trail_len--;
+ }
+ /* ghost trail (Polargeist style afterimages) */
+ for (int i = 0; i < GHOST_N; i++) if (ghosts[i].life > 0) ghosts[i].life -= dt;
+ if ((g->trail || g->ending) && !g->dead) {
+ ghost_acc += dt;
+ if (ghost_acc >= 0.05f) {
+ ghost_acc = 0;
+ ghosts[ghost_next] = (Ghost){p->x, p->y, p->rot, 0.45f, p->mode, p->upside};
+ ghost_next = (ghost_next + 1) % GHOST_N;
+ }
+ }
+ /* advance particles */
+ for (int i = 0; i < nparts;) {
+ Particle *q = &parts[i];
+ q->age += dt;
+ if (q->age >= q->life) { parts[i] = parts[--nparts]; continue; }
+ const PDef *d = &pdefs[q->def];
+ if (!(q->flags & PF_RADIAL)) {
+ q->vx += d->gx * dt;
+ q->vy += d->gy * dt;
+ q->x += q->vx * dt;
+ q->y += q->vy * dt;
+ }
+ i++;
+ }
+ for (int i = 0; i < MAX_CIRCLES; i++) if (circles[i].def) circles[i].t += dt;
+}
+
+void fx_update_screen(float dt) {
+ for (int i = 0; i < nparts;) {
+ Particle *q = &parts[i];
+ q->age += dt;
+ if (q->age >= q->life) { parts[i] = parts[--nparts]; continue; }
+ const PDef *d = &pdefs[q->def];
+ q->vx += d->gx * dt;
+ q->vy += d->gy * dt;
+ q->x += q->vx * dt;
+ q->y += q->vy * dt;
+ i++;
+ }
+ for (int i = 0; i < MAX_CIRCLES; i++) if (circles[i].def) circles[i].t += dt;
+}
+
+static void to_screen(float wx, float wy, bool screen, float *sx, float *sy) {
+ if (screen) { *sx = wx; *sy = wy; return; }
+ *sx = (wx - cam_x) * PX;
+ *sy = 240 - (GROUND_OFFSET + wy - cam_y) * PX;
+}
+
+static void draw_particles(bool screen_pass) {
+ for (int i = 0; i < nparts; i++) {
+ const Particle *q = &parts[i];
+ bool scr = (q->flags & PF_SCREEN) != 0;
+ if (scr != screen_pass) continue;
+ float t = q->age / q->life;
+ float wx = q->x, wy = q->y;
+ if (q->flags & PF_RADIAL) {
+ const PDef *d = &pdefs[q->def];
+ float r = q->vy + (d->r_min - q->vy) * t, a = q->vx + d->rot * 3.14159265f / 180.f * q->age;
+ wx += cosf(a) * r;
+ wy += sinf(a) * r;
+ }
+ float sx, sy;
+ to_screen(wx, wy, scr, &sx, &sy);
+ float size = (q->s0 + (q->s1 - q->s0) * t) / 4.f * (scr ? 1 : PX);
+ if (size < 0.6f) continue;
+ int s = (int)(size + .5f), x = (int)(sx - size / 2), y = (int)(sy - size / 2);
+ if (y + s < gfx_y0 || y > gfx_y1) continue;
+ color_t c = c_mix(q->c0, q->c1, (unsigned)(t * 256));
+ unsigned a = (unsigned)(q->a0 + (q->a1 - q->a0) * t);
+ gfx_add(x, y, s < 1 ? 1 : s, s < 1 ? 1 : s, c, a);
+ }
+}
+
+static void draw_circles(bool screen_pass) {
+ for (int i = 0; i < MAX_CIRCLES; i++) {
+ const Circle *c = &circles[i];
+ if (!c->def || (c->screen != 0) != screen_pass) continue;
+ const CDef *d = &cdefs[c->def - 1];
+ if (c->t >= d->dur) continue;
+ float t = c->t / d->dur, a, r;
+ if (d->tri) {
+ a = t < .5f ? d->a0 + (d->a1 - d->a0) * ease(d->ea0, t * 2) : d->a1 + (d->a0 - d->a1) * ease(d->ea1, (t - .5f) * 2);
+ } else if (d->ea0 == d->ea1) {
+ a = d->a0 + (d->a1 - d->a0) * ease(d->ea0, t);
+ } else {
+ float mid = (d->a0 + d->a1) / 2;
+ a = t < .5f ? d->a0 + (mid - d->a0) * ease(d->ea0, t * 2) : mid + (d->a1 - mid) * ease(d->ea1, (t - .5f) * 2);
+ }
+ if (d->er0 == d->er1) r = d->r0 + (d->r1 - d->r0) * ease(d->er0, t);
+ else {
+ float mid = (d->r0 + d->r1) / 2;
+ r = t < .5f ? d->r0 + (mid - d->r0) * ease(d->er0, t * 2) : mid + (d->r1 - mid) * ease(d->er1, (t - .5f) * 2);
+ }
+ float sx, sy;
+ to_screen(c->x, c->y, c->screen, &sx, &sy);
+ float scale = c->screen ? 1 : PX;
+ if (sy + r * scale < gfx_y0 - 2 || sy - r * scale > gfx_y1 + 2) continue;
+ unsigned al = (unsigned)(a * 256);
+ if (al > 256) al = 256;
+ if (d->hollow)
+ gfx_ring((int)(sx * 16), (int)(sy * 16), (int)(r * scale * 16), (int)(d->thick * 16 * (scale < 1 ? 1.2f : 1)), c->color, al, BLEND_ADD);
+ else
+ gfx_disc((int)(sx * 16), (int)(sy * 16), (int)(r * scale * 16), c->color, al, BLEND_ADD);
+ }
+}
+
+void fx_draw_player_trail(void) {
+ if (!G) return;
+ /* afterimages */
+ for (int i = 0; i < GHOST_N; i++) {
+ const Ghost *gh = &ghosts[i];
+ if (gh->life <= 0) continue;
+ float sx, sy;
+ to_screen(gh->x, gh->y, false, &sx, &sy);
+ float k = gh->life / 0.45f;
+ scene_draw_player_icon(gh->mode == MODE_SHIP ? MODE_CUBE : MODE_CUBE, sx, sy, gh->rot, gh->mode == MODE_SHIP ? 0.5f + 0.4f * k : 0.8f + 0.2f * k,
+ col_p1, col_p2, gh->upside, (unsigned)(k * 0.7f * 256));
+ }
+ /* streak: a tapered ribbon through the recent positions */
+ for (int i = trail_len - 1; i > 0; i--) {
+ float x0, y0, x1, y1;
+ to_screen(trail_x[i], trail_y[i], false, &x0, &y0);
+ to_screen(trail_x[i - 1], trail_y[i - 1], false, &x1, &y1);
+ if ((y0 < gfx_y0 - 8 && y1 < gfx_y0 - 8) || (y0 > gfx_y1 + 8 && y1 > gfx_y1 + 8)) continue;
+ float k0 = 1 - (float)i / TRAIL_N, k1 = 1 - (float)(i - 1) / TRAIL_N;
+ float dx = x1 - x0, dy = y1 - y0, len = sqrtf(dx * dx + dy * dy);
+ int steps = (int)(len / 1.5f) + 1;
+ for (int s = 0; s < steps; s++) {
+ float t = (float)s / steps, k = k0 + (k1 - k0) * t;
+ gfx_disc((int)((x0 + dx * t) * 16), (int)((y0 + dy * t) * 16), (int)(k * 4.0f * 16), col_p1, (unsigned)(k * 38), BLEND_ADD);
+ }
+ }
+}
+
+void fx_draw(void) {
+ draw_circles(false);
+ draw_particles(false);
+}
+
+void fx_draw_screen(void) {
+ draw_circles(true);
+ draw_particles(true);
+}
diff --git a/games/numdash/src/fx.h b/games/numdash/src/fx.h
new file mode 100644
index 00000000..ea09fe8e
--- /dev/null
+++ b/games/numdash/src/fx.h
@@ -0,0 +1,20 @@
+#ifndef NUMDASH_FX_H
+#define NUMDASH_FX_H
+#include "game.h"
+#include "gfx.h"
+
+void fx_reset(void);
+/* Consume the physics event queue and advance effects by dt seconds. */
+void fx_update(Game *g, float dt, color_t p1, color_t p2, bool practice);
+void fx_draw(void);
+void fx_draw_player_trail(void);
+/* Screen-space effects used by menus and the level-complete sequence. */
+void fx_circle_screen(float x, float y, int def, color_t c);
+void fx_burst_screen(float x, float y, int def, color_t c, int count);
+void fx_circle_world(float x, float y, int def, color_t c);
+void fx_burst_world(float x, float y, int def, color_t c, int count);
+void fx_update_screen(float dt);
+void fx_draw_screen(void);
+enum { CE_PAD, CE_ORB, CE_PORTAL, CE_ORB_TOUCH, CE_DEATH, CE_COIN, CE_COIN_RING, CE_WALL1, CE_WALL2, CE_TITLE, CE_FIREWORK, CE_RING_BIG, CE_RESPAWN };
+enum { PE_DRAG, PE_SHIP_FIRE, PE_SHIP_SMOKE, PE_LAND, PE_EXPLODE, PE_BUMP, PE_RING, PE_PORTAL, PE_COIN, PE_COIN_PICKUP, PE_COMPLETE, PE_FIREWORK };
+#endif
diff --git a/games/numdash/src/game.c b/games/numdash/src/game.c
new file mode 100644
index 00000000..d68f9b5a
--- /dev/null
+++ b/games/numdash/src/game.c
@@ -0,0 +1,575 @@
+/* Geometry Dash 2.x cube/ship physics at 240 Hz.
+ *
+ * Constants and collision rules follow the reverse-engineered values used by
+ * the gd3ds project (itself based on the Pathfinder mod's physics): velocities
+ * are in GD units per second, "vy" is relative to the current gravity. */
+#include "game.h"
+#include <math.h>
+#include <string.h>
+
+enum { SPEED_SLOW, SPEED_NORMAL, SPEED_FAST, SPEED_FASTER };
+static const float SPEEDS[4] = {251.16007972f, 311.58009371f, 387.42014040f, 468.00013884f};
+static const float SPEED_MULT[4] = {0.7f, 0.9f, 1.1f, 1.3f};
+static const float CUBE_JUMP[4] = {573.481728f, 603.7217172f, 616.681728f, 606.421728f};
+static const float CUBE_GRAV[4] = {-2747.52f, -2794.1082f, -2786.4f, -2799.36f};
+static const float VEL_THRESH[4] = {101.541492f, 103.485494592f, 103.377492f, 103.809492f};
+enum { J_YPAD, J_YORB, J_BPAD, J_BORB, J_PPAD, J_PORB };
+/* [speed][jump type][cube, ship] for normal-size players */
+static const float JUMPS[4][6][2] = {
+ {{864, 432}, {573.48f, 573.48f}, {-345.6f, -229.392f}, {-229.392f, -229.392f}, {561.6f, 302.4f}, {412.884f, 212.166f}},
+ {{864, 432}, {603.72f, 603.72f}, {-345.6f, -345.6f}, {-241.488f, -241.488f}, {561.6f, 302.4f}, {434.7f, 223.398f}},
+ {{864, 432}, {616.68f, 616.68f}, {-345.6f, -345.6f}, {-246.672f, -246.672f}, {561.6f, 302.4f}, {443.988f, 228.15f}},
+ {{864, 432}, {606.42f, 606.42f}, {-345.6f, -345.6f}, {-242.568f, -242.568f}, {561.6f, 302.4f}, {436.644f, 224.37f}},
+};
+#define ROT_SPEED 415.3848f
+#define CEILING_INVUL 0.1f
+#define DRAG_TIME 0.1f
+#define SHIP_MIN (-345.6f)
+#define SHIP_MAX 432.0f
+#define END_START (10 * 30.0f)
+
+static float clampf(float v, float lo, float hi) { return v < lo ? lo : v > hi ? hi : v; }
+static float grav(const Player *p, float v) { return p->upside ? -v : v; }
+static float grav_bottom(const Player *p) { return p->upside ? -(p->y + 15) : p->y - 15; }
+static float grav_top(const Player *p) { return p->upside ? -(p->y - 15) : p->y + 15; }
+static float grav_floor(const Player *p) { return p->upside ? -p->ceiling_y : p->ground_y; }
+
+bool game_used(const Game *g, unsigned i) { return i < MAX_OBJECTS && (g->used[i >> 3] >> (i & 7) & 1); }
+static void set_used(Game *g, unsigned i) { g->used[i >> 3] |= (uint8_t)(1u << (i & 7)); }
+static void fx(Game *g, uint8_t kind, uint8_t arg, int obj, float x, float y) {
+ if (g->fx_count < sizeof(g->fx) / sizeof(g->fx[0])) g->fx[g->fx_count++] = (FxEvent){kind, arg, (int16_t)obj, x, y};
+}
+static void kill(Game *g, int obj) {
+ if (g->dead) return;
+ g->dead = true;
+ g->death_obj = obj < 0 ? 0xffff : (uint16_t)obj;
+ fx(g, FX_DEATH, 0, obj, g->p.x, g->p.y);
+}
+
+unsigned game_coin_index(const Level *L, unsigned obj) {
+ unsigned k = 0;
+ while (k < L->coin_count && L->coin_obj[k] < obj) k++;
+ return k;
+}
+
+static void set_velocity(Player *p, float v, bool override) { p->vel_override = override; p->vy = v; }
+static void landing(Player *p) { if (p->mode == MODE_CUBE) p->jumped = false; }
+static void update_rot_dir(Player *p) { p->rot_dir_neg = p->upside; }
+static float closest_rotation(float rot) {
+ float r = fmodf(rot, 360.0f);
+ if (r < 0) r += 360;
+ float s = roundf(r / 90) * 90;
+ s = fmodf(s, 360);
+ return s < 0 ? s + 360 : s;
+}
+static float slerp_angle(float from, float to, float t) {
+ float fx = cosf(from * .5f), fy = sinf(from * .5f), tx = cosf(to * .5f), ty = sinf(to * .5f);
+ float dot = fx * tx + fy * ty;
+ if (dot < 0) { dot = -dot; tx = -tx; ty = -ty; }
+ float w0 = 1 - t, w1 = t;
+ if (dot < 0.9999f) {
+ float b = acosf(dot), sb = sinf(b);
+ w0 = sinf(w0 * b) / sb;
+ w1 = sinf(w1 * b) / sb;
+ }
+ return atan2f(w0 * fy + w1 * ty, w0 * fx + w1 * tx) * 2;
+}
+#define DEG (3.14159265f / 180.0f)
+
+static void set_bounds_for_portal(Game *g, float portal_y) {
+ Player *p = &g->p;
+ float v = (portal_y - (300 + 60) / 2.0f) / 30.0f, c = ceilf(v);
+ if (fabsf(v - roundf(v)) < 1e-6f) c += 1;
+ p->ground_y = c > 0 ? c * 30 : 0;
+ p->ceiling_y = p->ground_y + 300;
+ g->cam_intended_y = (p->ground_y + p->ceiling_y) / 2 - (VIEW_H / 2 - GROUND_OFFSET);
+}
+
+void game_start(Game *g, const Level *L, bool first_attempt) {
+ memset(g, 0, sizeof(*g));
+ g->L = L;
+ Player *p = &g->p;
+ p->x = 0;
+ p->y = 15;
+ p->speed = SPEED_NORMAL;
+ p->ceiling_y = 999999;
+ p->snap_obj = -1;
+ p->coyote = 1 << 30;
+ p->on_ground = true;
+ if (L->start_mode == MODE_SHIP) {
+ p->mode = MODE_SHIP;
+ set_bounds_for_portal(g, 150);
+ }
+ for (int c = 0; c < CH_COUNT; c++) {
+ memcpy(g->ch[c].cur, L->colors[c], 3);
+ memcpy(g->ch[c].to, L->colors[c], 3);
+ }
+ g->attempt_camera = first_attempt;
+ g->cam_x = first_attempt ? 15 : p->x - PLAYER_SCREEN_X;
+ g->ground_x = g->bg_x = g->cam_x;
+ g->death_obj = 0xffff;
+}
+
+float game_progress(const Game *g) {
+ if (g->complete) return 100;
+ float v = g->p.x / g->L->end_x * 100;
+ return clampf(v, 0, 100);
+}
+
+static void clamp_ground(Game *g) {
+ Player *p = &g->p;
+ if (p->y - 15 < p->ground_y) {
+ if (p->ceil_inv <= 0 && p->mode == MODE_CUBE && p->upside) kill(g, -1);
+ if (grav(p, p->vy) <= 0) set_velocity(p, 0, false);
+ p->y = p->ground_y + 15;
+ p->snap_frame = 0;
+ }
+ if (p->y + 15 > p->ceiling_y) {
+ if (p->ceil_inv <= 0 && p->mode == MODE_CUBE && !p->upside) kill(g, -1);
+ if (grav(p, p->vy) >= 0) set_velocity(p, 0, false);
+ p->y = p->ceiling_y - 15;
+ }
+}
+
+static bool overlap(float ax, float ay, float ahw, float ahh, float bx, float by, float bhw, float bhh) {
+ return fabsf(ax - bx) < ahw + bhw && fabsf(ay - by) < ahh + bhh;
+}
+
+static void try_snap(Game *g, unsigned block) {
+ Player *p = &g->p;
+ if (p->snap_obj < 0) return;
+ const LObj *a = &g->L->objs[block], *b = &g->L->objs[p->snap_obj];
+ float dx = (float)a->x - b->x, dy = grav(p, (float)a->y - b->y);
+ static const float stairs[3][2] = {{150, -30}, {120, 30}, {90, 60}};
+ for (int k = 0; k < 3; k++)
+ if (fabsf(dx - stairs[k][0]) <= 1 && fabsf(dy - stairs[k][1]) <= 1) {
+ p->x = clampf(a->x + p->snap_diff, p->x - 1, p->x + 1);
+ return;
+ }
+}
+
+static void solid(Game *g, unsigned i, float ox, float oy, float hw, float hh) {
+ Player *p = &g->p;
+ float clip = (p->mode == MODE_SHIP ? 7.0f : 10.0f) + fabsf(p->vy) * ND_DT;
+ float o_bottom = p->upside ? -(oy + hh) : oy - hh, o_top = p->upside ? -(oy - hh) : oy + hh;
+ bool internal = overlap(p->x, p->y, 4.5f, 4.5f, ox, oy, hw, hh), grav_snap = false;
+ if (p->ceil_inv > 0) {
+ float in_bottom = p->upside ? -(p->y + 4.5f) : p->y - 4.5f, diff = o_bottom - in_bottom;
+ grav_snap = internal && diff >= 0 && diff <= clip;
+ }
+ if (!grav_snap && internal) { kill(g, (int)i); return; }
+ float bottom = grav_bottom(p);
+ if (o_top - bottom <= clip && p->vy <= 0) {
+ p->y = grav(p, o_top) + grav(p, 15);
+ if (p->vy <= 0) p->vy = 0;
+ p->on_ground = true;
+ p->inverse_rot = false;
+ p->time_since_ground = 0;
+ landing(p);
+ if (p->mode == MODE_CUBE) {
+ /* GD nudges x by up to a unit so stair jumps land consistently */
+ if (!g->old_on_ground && p->snap_frame > 0 && p->snap_frame + 1 < p->frame) try_snap(g, i);
+ p->snap_frame = p->frame;
+ p->snap_obj = (int16_t)i;
+ p->snap_diff = p->x - g->L->objs[i].x;
+ }
+ } else if (p->mode != MODE_CUBE || grav_snap) {
+ if ((grav_top(p) - o_bottom <= clip && p->vy >= 0) || grav_snap) {
+ if (!grav_snap) p->on_ceiling = true; else p->vy = 0;
+ p->inverse_rot = false;
+ p->time_since_ground = 0;
+ p->y = grav(p, o_bottom) - grav(p, 15);
+ if (p->vy >= 0) p->vy = 0;
+ }
+ }
+}
+
+static void special(Game *g, unsigned i, const LObj *o, bool hold) {
+ Player *p = &g->p;
+ const ObjDef *d = &objdefs[o->type];
+ int m = p->mode == MODE_SHIP ? 1 : 0;
+ bool used = game_used(g, i);
+ switch (d->special) {
+ case SP_PAD_Y: case SP_PAD_P:
+ if (used) break;
+ p->vy = JUMPS[p->speed][d->special == SP_PAD_Y ? J_YPAD : J_PPAD][m];
+ p->on_ground = false; p->inverse_rot = false; p->left_ground = true; p->jumped = true;
+ set_used(g, i);
+ update_rot_dir(p);
+ fx(g, FX_PAD, d->special == SP_PAD_Y ? 0 : 2, (int)i, o->x, o->y);
+ break;
+ case SP_PAD_B: {
+ if (used) break;
+ int rot = (o->xf & 3) * 90;
+ if (o->xf & 8) rot = (rot + 180) % 360;
+ bool down = rot > 90 && rot < 270;
+ if ((!down && p->upside) || (down && !p->upside)) break;
+ p->left_ground = true;
+ update_rot_dir(p);
+ p->vy = JUMPS[p->speed][J_BPAD][m];
+ p->upside = !p->upside;
+ p->on_ground = false; p->inverse_rot = false; p->ceil_inv = CEILING_INVUL; p->jumped = true;
+ set_used(g, i);
+ fx(g, FX_PAD, 1, (int)i, o->x, o->y);
+ break;
+ }
+ case SP_ORB_Y: case SP_ORB_P: case SP_ORB_B:
+ if (!used && hold && p->buffer == BUF_READY) {
+ int j = d->special == SP_ORB_Y ? J_YORB : d->special == SP_ORB_P ? J_PORB : J_BORB;
+ p->vy = JUMPS[p->speed][j][m];
+ if (d->special == SP_ORB_B) { p->upside = !p->upside; p->ceil_inv = CEILING_INVUL; }
+ p->on_ground = false; p->on_ceiling = false; p->inverse_rot = false; p->left_ground = true;
+ p->buffer = BUF_END; p->jumped = true;
+ update_rot_dir(p);
+ g->jumps++;
+ set_used(g, i);
+ fx(g, FX_ORB, (uint8_t)(d->special - SP_ORB_Y), (int)i, o->x, o->y);
+ }
+ break;
+ case SP_GRAV_N: case SP_GRAV_F:
+ if (used) break;
+ p->ceil_inv = CEILING_INVUL;
+ if (p->upside != (d->special == SP_GRAV_F)) {
+ p->vy /= -2;
+ p->upside = d->special == SP_GRAV_F;
+ p->inverse_rot = false;
+ p->snap_rot = true;
+ p->left_ground = true;
+ fx(g, FX_GRAVITY, d->special == SP_GRAV_F, (int)i, o->x, o->y);
+ }
+ set_used(g, i);
+ break;
+ case SP_PORTAL_CUBE:
+ if (used) break;
+ p->ground_y = 0;
+ p->ceiling_y = 999999;
+ if (p->mode != MODE_CUBE) {
+ p->vy /= 2;
+ p->ceil_inv = CEILING_INVUL;
+ p->snap_rot = true;
+ p->mode = MODE_CUBE;
+ update_rot_dir(p);
+ fx(g, FX_PORTAL, 0, (int)i, o->x, o->y);
+ }
+ set_used(g, i);
+ break;
+ case SP_PORTAL_SHIP:
+ if (used) break;
+ set_bounds_for_portal(g, o->y);
+ if (p->mode != MODE_SHIP) {
+ p->vy /= 2;
+ p->mode = MODE_SHIP;
+ p->inverse_rot = false;
+ p->snap_rot = true;
+ p->vy = clampf(p->vy, SHIP_MIN, SHIP_MAX);
+ fx(g, FX_PORTAL, 1, (int)i, o->x, o->y);
+ }
+ set_used(g, i);
+ break;
+ case SP_COIN:
+ if (used) break;
+ set_used(g, i);
+ g->coins |= (uint8_t)(1u << (game_coin_index(g->L, i) & 7));
+ fx(g, FX_COIN, 0, (int)i, o->x, o->y);
+ break;
+ default: break;
+ }
+}
+
+static void collide(Game *g, bool hold) {
+ Player *p = &g->p;
+ const Level *L = g->L;
+ unsigned first = level_lower_bound(L, (int)(p->x - 60)), end = first;
+ while (end < L->count && L->objs[end].x < p->x + 60) end++;
+ bool touching_orb = false;
+ /* GD resolves special objects, then solids, then hazards. */
+ for (int pass = 0; pass < 3 && !g->dead; pass++)
+ for (unsigned i = first; i < end && !g->dead; i++) {
+ const LObj *o = &L->objs[i];
+ const ObjDef *d = &objdefs[o->type];
+ int want = pass == 0 ? HIT_SPECIAL : pass == 1 ? HIT_SOLID : HIT_HAZARD;
+ if (d->hit != want) continue;
+ if (d->special == SP_COIN && game_used(g, i)) continue;
+ float hw, hh;
+ obj_hitbox(o, &hw, &hh);
+ if (!overlap(p->x, p->y, 15, 15, o->x, o->y, hw, hh)) continue;
+ if (pass == 0) {
+ if (d->special >= SP_ORB_Y && d->special <= SP_ORB_B) {
+ touching_orb = true;
+ if (!g->orb_touching && !game_used(g, i)) fx(g, FX_ORB_TOUCH, 0, (int)i, o->x, o->y);
+ }
+ special(g, i, o, hold);
+ } else if (pass == 1) {
+ solid(g, i, o->x, o->y, hw, hh);
+ } else {
+ kill(g, (int)i);
+ }
+ }
+ g->orb_touching = touching_orb;
+}
+
+static void cube_mode(Game *g, bool hold, bool pressed) {
+ Player *p = &g->p;
+ float mult = p->rot_dir_neg ? -1.0f : 1.0f;
+ p->gravity = CUBE_GRAV[p->speed];
+ if (p->vy < -810) p->vy = -810;
+ if (p->vy > 1080) p->vy = 1080;
+ if (p->y > 2794) kill(g, -1);
+ if (p->snap_rot) p->target_rot = p->rot;
+ if (!p->on_ground) {
+ if (p->inverse_rot) p->target_rot -= ROT_SPEED / 2 * ND_DT * mult;
+ else p->target_rot += ROT_SPEED * ND_DT * mult;
+ }
+ if (p->on_ground) update_rot_dir(p);
+ bool coyote = p->upside && hold && p->coyote < 10;
+ if ((p->on_ground || coyote) && hold) {
+ set_velocity(p, CUBE_JUMP[p->speed], g->hold_prev);
+ p->inverse_rot = false;
+ p->buffer = BUF_END;
+ p->on_ground = false;
+ p->jumped = true;
+ g->jumps++;
+ if (!pressed) p->time_since_ground = DRAG_TIME;
+ fx(g, FX_JUMP, 0, -1, p->x, p->y);
+ }
+ if (p->on_ground) p->target_rot = closest_rotation(p->rot);
+}
+
+static void ship_mode(Game *g, bool hold) {
+ Player *p = &g->p;
+ float t = grav(p, VEL_THRESH[p->speed]);
+ if (hold) {
+ p->buffer = BUF_END;
+ p->gravity = p->vy <= t ? 1397.0491f : 1117.64328f;
+ } else {
+ p->gravity = p->vy >= t ? -1341.1719f : -894.11464f;
+ }
+ if (p->gravity < 0 && p->vy < SHIP_MIN) p->vy = SHIP_MIN;
+ else if (p->gravity > 0 && p->vy > SHIP_MAX) p->vy = SHIP_MAX;
+}
+
+static void run_player(Game *g, const Player *old, bool hold, bool pressed) {
+ Player *p = &g->p;
+ if (!p->left_ground) {
+ if (p->y - 15 <= p->ground_y) {
+ if (p->upside) p->on_ceiling = true; else { p->on_ground = true; landing(p); }
+ p->inverse_rot = false;
+ p->time_since_ground = 0;
+ }
+ if (p->y + 15 >= p->ceiling_y) {
+ if (p->upside) { p->on_ground = true; landing(p); } else p->on_ceiling = true;
+ p->inverse_rot = false;
+ p->time_since_ground = 0;
+ }
+ }
+ if (!old->on_ground && p->on_ground) fx(g, FX_LAND, 0, -1, p->x, p->y);
+ if (grav_bottom(old) > grav_floor(old) && p->upside == old->upside && !p->on_ground && p->vy <= 0) {
+ if (old->on_ground && !g->hold_prev) p->coyote = 0;
+ p->coyote++;
+ } else {
+ p->coyote = 1 << 30;
+ }
+ if (p->mode == MODE_CUBE) cube_mode(g, hold, pressed); else ship_mode(g, hold);
+ p->time_since_ground += ND_DT;
+ if (!p->vel_override) {
+ float nv = p->vy + p->gravity * ND_DT;
+ if (!(p->on_ground || p->on_ceiling) && (old->on_ground || old->on_ceiling) &&
+ ((!hold && g->pressed_prev) || p->buffer == BUF_READY) && grav_bottom(old) > grav_floor(old)) {
+ p->y += grav(old, old->gravity) * ND_DT * ND_DT;
+ if (p->vy == 0) nv += old->gravity * ND_DT;
+ }
+ p->vy = nv;
+ }
+ if (g->ending) return;
+ p->rot = fmodf(p->rot, 360.0f);
+ p->left_ground = false;
+ if (p->ceil_inv > 0) p->ceil_inv -= ND_DT; else p->ceil_inv = 0;
+ clamp_ground(g);
+ if (p->mode == MODE_CUBE) {
+ float lerp = SPEED_MULT[p->speed] * 0.175f;
+ if (p->on_ground) {
+ lerp *= 3;
+ float t = fminf(ND_DT, ND_DT * lerp) * 60;
+ p->rot = slerp_angle(p->rot * DEG, p->target_rot * DEG, t) / DEG;
+ } else {
+ p->rot = p->target_rot;
+ }
+ } else {
+ float dx = p->x - old->x, dy = p->y - old->y, ang = atan2f(-dy, dx);
+ if (p->snap_rot) p->rot = ang / DEG;
+ else if (ND_DT * 72 <= dx * dx + dy * dy) p->rot = slerp_angle(p->rot * DEG, ang, ND_DT * 60 * 0.15f) / DEG;
+ }
+ p->snap_rot = false;
+}
+
+static void ease_channel(Channel *c) {
+ if (c->t >= c->dur) { memcpy(c->cur, c->to, 3); return; }
+ c->t++;
+ for (int k = 0; k < 3; k++) c->cur[k] = (uint8_t)(c->from[k] + ((int)c->to[k] - c->from[k]) * (int)c->t / (int)c->dur);
+}
+static void fire_event(Game *g, const LevelEvent *e) {
+ if (e->kind == EV_COLOR) {
+ int chans[2] = {e->arg, -1};
+ if (e->arg == CH_BG && (e->flags & EVF_TINT_GROUND)) chans[1] = CH_G1;
+ for (int k = 0; k < 2; k++) {
+ if (chans[k] < 0 || chans[k] >= CH_COUNT) continue;
+ Channel *c = &g->ch[chans[k]];
+ memcpy(c->from, c->cur, 3);
+ c->to[0] = e->r; c->to[1] = e->g; c->to[2] = e->b;
+ c->t = 0;
+ c->dur = (uint16_t)((uint32_t)e->dur * ND_HZ / 1000);
+ if (!c->dur) memcpy(c->cur, c->to, 3);
+ }
+ } else if (e->kind == EV_FADE) {
+ g->fade_effect = e->arg;
+ } else if (e->kind == EV_TRAIL) {
+ g->trail = e->arg != 0;
+ }
+}
+static void triggers(Game *g) {
+ const Level *L = g->L;
+ Player *p = &g->p;
+ while (g->next_event < L->event_count) {
+ const LevelEvent *e = &L->events[g->next_event];
+ if (e->x >= p->x) break;
+ if (!(e->flags & EVF_TOUCH)) fire_event(g, e);
+ g->next_event++;
+ }
+ /* touch-triggered events fire once when the player overlaps them */
+ for (unsigned k = 0; k < L->event_count && k < 64; k++) {
+ const LevelEvent *e = &L->events[k];
+ if (!(e->flags & EVF_TOUCH) || (g->touch_done[k >> 3] >> (k & 7) & 1)) continue;
+ if (e->x > p->x + 30 || e->x < p->x - 60) continue;
+ if (overlap(p->x, p->y, 15, 15, e->x, e->y, 15, 15)) {
+ g->touch_done[k >> 3] |= (uint8_t)(1u << (k & 7));
+ fire_event(g, e);
+ }
+ }
+ for (int c = 0; c < CH_COUNT; c++) ease_channel(&g->ch[c]);
+}
+
+static float ease_in_out(float t, float rate) {
+ t *= 2;
+ if (t < 1) return 0.5f * powf(t, rate);
+ return 1 - 0.5f * powf(2 - t, rate);
+}
+
+static void camera(Game *g) {
+ Player *p = &g->p;
+ const Level *L = g->L;
+ if (g->menu_camera) {
+ float v = SPEEDS[SPEED_NORMAL] * ND_DT;
+ g->ground_x += v;
+ g->bg_x += v;
+ g->ground_gfx = 0;
+ return;
+ }
+ float playable = p->ceiling_y - p->ground_y, want_gfx = 0;
+ if (p->mode != MODE_CUBE) want_gfx = (VIEW_H - playable) / 2;
+ g->ground_gfx += (want_gfx - g->ground_gfx) * 0.02f;
+ if (g->wall_y == 0 && g->cam_x + VIEW_W >= L->wall_x - 4.5f * 30) {
+ float mid = g->cam_y + VIEW_H / 2 - GROUND_OFFSET, lo = 60 + (VIEW_H / 2 - GROUND_OFFSET);
+ g->wall_y = mid > lo ? mid : lo;
+ }
+ if (g->wall_y > 0 && g->cam_x + VIEW_W >= L->wall_x - 60) {
+ if (g->cam_wall_t == 0) { g->cam_wall_y0 = g->cam_y; g->bg_wall_x0 = g->bg_x; g->ground_wall_x0 = g->ground_x; }
+ float t = clampf(g->cam_wall_t / 1.0f, 0, 1), e = ease_in_out(t, 2);
+ float fx_ = L->wall_x - VIEW_W, fy = g->wall_y - (VIEW_H / 2 - GROUND_OFFSET);
+ g->cam_x = fx_ - 60 + 60 * e;
+ g->cam_y = g->cam_wall_y0 + (fy - g->cam_wall_y0) * e;
+ g->bg_x = g->bg_wall_x0 + 60 * e;
+ g->ground_x = g->ground_wall_x0 + 60 * e;
+ g->cam_wall_t += ND_DT;
+ return;
+ }
+ float target = g->cam_y;
+ if (p->mode == MODE_CUBE) {
+ float off = p->upside ? -30.0f : 0;
+ if (p->y > g->cam_y + 180 + off) target = p->y - (180 + off);
+ else if (p->y < g->cam_y + 30 + off) target = p->y - (30 + off);
+ } else {
+ target = g->cam_intended_y;
+ }
+ if (target < 0) target = 0;
+ g->cam_y += (target - g->cam_y) / 40.0f;
+ if (g->cam_y < 0) g->cam_y = 0;
+ float want = p->x - PLAYER_SCREEN_X;
+ if (g->attempt_camera && want < 15) want = 15;
+ float moved = want - g->cam_x;
+ g->cam_x = want;
+ if (moved > 0) { g->ground_x += moved; g->bg_x += moved; }
+}
+
+void game_step(Game *g, bool hold) {
+ if (g->dead || g->complete) return;
+ Player *p = &g->p;
+ Player old = *p;
+ bool pressed = hold && !g->hold_prev;
+ g->old_on_ground = p->on_ground;
+ if (hold) { if (p->buffer == BUF_NONE) p->buffer = BUF_READY; }
+ else p->buffer = BUF_NONE;
+ p->on_ground = p->on_ceiling = false;
+ p->vel_override = false;
+ p->x += SPEEDS[p->speed] * ND_DT;
+ p->y += grav(p, p->vy) * ND_DT;
+ clamp_ground(g);
+ p->frame++;
+ g->tick++;
+ if (!g->dead && !g->ending) collide(g, hold);
+ if (!g->dead) {
+ const Level *L = g->L;
+ if (p->x >= L->wall_x - END_START) {
+ if (!g->ending) {
+ g->ending = true;
+ g->end_x0 = p->x;
+ g->end_y0 = p->y;
+ if (g->wall_y == 0) g->wall_y = g->end_y0 > 60 ? g->end_y0 : 60;
+ }
+ float t = clampf(powf(g->end_t, 1.2f), 0, 1), u = 1 - t;
+ float mx = g->end_x0 + 40, my = g->wall_y + 150, ex = L->wall_x + 50, ey = g->wall_y - 20;
+ p->x = u * u * u * g->end_x0 + 3 * u * u * t * g->end_x0 + 3 * u * t * t * mx + t * t * t * ex;
+ p->y = u * u * u * g->end_y0 + 3 * u * u * t * g->end_y0 + 3 * u * t * t * my + t * t * t * ey;
+ float e = g->end_t / 0.5f;
+ p->rot += (e > 1 ? 1 : e * e) * ROT_SPEED * ND_DT;
+ g->end_t += ND_DT;
+ if (p->x > L->wall_x && !g->complete) {
+ g->complete = true;
+ fx(g, FX_WALL, 0, -1, (float)L->wall_x, g->wall_y);
+ }
+ }
+ run_player(g, &old, hold, pressed);
+ }
+ g->hold_prev = hold;
+ g->pressed_prev = pressed;
+ if (!g->dead) {
+ camera(g);
+ triggers(g);
+ }
+}
+
+void game_save_checkpoint(const Game *g, Checkpoint *c) {
+ c->p = g->p;
+ c->cam_x = g->cam_x; c->cam_y = g->cam_y; c->ground_x = g->ground_x; c->bg_x = g->bg_x;
+ c->ground_gfx = g->ground_gfx; c->cam_intended_y = g->cam_intended_y;
+ memcpy(c->ch, g->ch, sizeof(c->ch));
+ c->tick = g->tick; c->next_event = g->next_event; c->jumps = g->jumps;
+ c->fade_effect = g->fade_effect; memcpy(c->touch_done, g->touch_done, sizeof(c->touch_done)); c->trail = g->trail;
+}
+
+void game_load_checkpoint(Game *g, const Checkpoint *c) {
+ const Level *L = g->L;
+ uint8_t coins = g->coins;
+ game_start(g, L, false);
+ g->p = c->p;
+ g->p.buffer = BUF_NONE;
+ g->cam_x = c->cam_x; g->cam_y = c->cam_y; g->ground_x = c->ground_x; g->bg_x = c->bg_x;
+ g->ground_gfx = c->ground_gfx; g->cam_intended_y = c->cam_intended_y;
+ memcpy(g->ch, c->ch, sizeof(g->ch));
+ g->tick = c->tick; g->next_event = c->next_event; g->jumps = c->jumps;
+ g->fade_effect = c->fade_effect; g->trail = c->trail;
+ memcpy(g->touch_done, c->touch_done, sizeof(g->touch_done));
+ g->coins = coins;
+ /* Objects behind the checkpoint can no longer be reached; mark them used
+ * so coins and pads there do not fire again. */
+ for (unsigned i = 0; i < L->count && L->objs[i].x < c->p.x - 60; i++) set_used(g, i);
+}
diff --git a/games/numdash/src/game.h b/games/numdash/src/game.h
new file mode 100644
index 00000000..b021a818
--- /dev/null
+++ b/games/numdash/src/game.h
@@ -0,0 +1,69 @@
+#ifndef NUMDASH_GAME_H
+#define NUMDASH_GAME_H
+#include <stdbool.h>
+#include <stdint.h>
+#include "level.h"
+
+#define ND_HZ 240
+#define ND_DT (1.0f / ND_HZ)
+enum { MODE_CUBE = 0, MODE_SHIP = 1 };
+enum { BUF_NONE = 0, BUF_READY = 1, BUF_END = 2 };
+/* Visible world: 480 x 360 GD units (20 px blocks); ground sits 90 units
+ * above the bottom edge when the camera is at rest, as in GD. */
+#define VIEW_W 480.0f
+#define VIEW_H 360.0f
+#define GROUND_OFFSET 90.0f
+#define PLAYER_SCREEN_X 150.0f
+
+typedef struct {
+ float x, y, vy, gravity, rot, target_rot, time_since_ground, ceil_inv;
+ float ground_y, ceiling_y, snap_diff;
+ int32_t snap_frame, frame, coyote;
+ int16_t snap_obj;
+ uint8_t mode, speed, buffer;
+ bool upside, on_ground, on_ceiling, vel_override, snap_rot, left_ground, inverse_rot, jumped, rot_dir_neg;
+} Player;
+
+typedef struct { uint8_t cur[3], from[3], to[3]; uint16_t t, dur; } Channel; /* t, dur in steps */
+
+enum { FX_JUMP, FX_LAND, FX_PAD, FX_ORB, FX_PORTAL, FX_COIN, FX_DEATH, FX_GRAVITY, FX_ORB_TOUCH, FX_WALL };
+typedef struct { uint8_t kind, arg; int16_t obj; float x, y; } FxEvent;
+
+typedef struct {
+ Player p;
+ const Level *L;
+ float cam_x, cam_y, ground_x, bg_x, ground_gfx, cam_intended_y, wall_y, end_t, end_x0, end_y0, cam_wall_t;
+ float cam_wall_y0, bg_wall_x0, ground_wall_x0, shake_t, shake_amp;
+ Channel ch[CH_COUNT];
+ uint32_t tick;
+ uint16_t next_event, jumps, death_obj;
+ uint8_t fade_effect, coins, attempt_camera, touch_done[8];
+ bool trail, dead, complete, ending, hold_prev, pressed_prev, old_on_ground, orb_touching;
+ bool menu_camera; /* fixed camera, ground scrolling on its own (main menu) */
+ uint8_t used[MAX_OBJECTS / 8];
+ FxEvent fx[24];
+ uint8_t fx_count;
+} Game;
+
+/* Practice checkpoint: everything needed to resume from a point. */
+typedef struct {
+ Player p;
+ float cam_x, cam_y, ground_x, bg_x, ground_gfx, cam_intended_y;
+ Channel ch[CH_COUNT];
+ uint32_t tick;
+ uint16_t next_event, jumps;
+ uint8_t fade_effect, touch_done[8];
+ bool trail;
+} Checkpoint;
+
+void game_start(Game *g, const Level *L, bool first_attempt);
+void game_step(Game *g, bool hold);
+float game_progress(const Game *g);
+bool game_used(const Game *g, unsigned i);
+void game_save_checkpoint(const Game *g, Checkpoint *c);
+void game_load_checkpoint(Game *g, const Checkpoint *c);
+unsigned game_coin_index(const Level *L, unsigned obj);
+/* World -> screen helpers (floating point pixels). */
+static inline float wx_to_sx(const Game *g, float x) { return (x - g->cam_x) * (2.0f / 3.0f); }
+static inline float wy_to_sy(const Game *g, float y) { return 240.0f - (GROUND_OFFSET + y - g->cam_y) * (2.0f / 3.0f); }
+#endif
diff --git a/games/numdash/src/gfx.c b/games/numdash/src/gfx.c
new file mode 100644
index 00000000..008500e2
--- /dev/null
+++ b/games/numdash/src/gfx.c
@@ -0,0 +1,755 @@
+#include "gfx.h"
+#include <math.h>
+#include <string.h>
+
+uint16_t gfx_strip[GFX_W * STRIP_H] __attribute__((aligned(8)));
+int gfx_y0 = 0, gfx_y1 = STRIP_H;
+static int clip_x0 = 0, clip_y0 = 0, clip_x1 = GFX_W, clip_y1 = GFX_H;
+
+void gfx_begin_strip(int index) { gfx_y0 = index * STRIP_H; gfx_y1 = gfx_y0 + STRIP_H; }
+void gfx_clip(int x0, int y0, int x1, int y1) {
+ clip_x0 = x0 < 0 ? 0 : x0; clip_y0 = y0 < 0 ? 0 : y0;
+ clip_x1 = x1 > GFX_W ? GFX_W : x1; clip_y1 = y1 > GFX_H ? GFX_H : y1;
+}
+void gfx_unclip(void) { clip_x0 = 0; clip_y0 = 0; clip_x1 = GFX_W; clip_y1 = GFX_H; }
+
+static bool clip_rect(int *x, int *y, int *w, int *h) {
+ int x0 = *x, y0 = *y, x1 = *x + *w, y1 = *y + *h;
+ int cy0 = clip_y0 > gfx_y0 ? clip_y0 : gfx_y0, cy1 = clip_y1 < gfx_y1 ? clip_y1 : gfx_y1;
+ if (x0 < clip_x0) x0 = clip_x0;
+ if (x1 > clip_x1) x1 = clip_x1;
+ if (y0 < cy0) y0 = cy0;
+ if (y1 > cy1) y1 = cy1;
+ if (x0 >= x1 || y0 >= y1) return false;
+ *x = x0; *y = y0; *w = x1 - x0; *h = y1 - y0;
+ return true;
+}
+static inline uint16_t *pix(int x, int y) { return gfx_strip + (y - gfx_y0) * GFX_W + x; }
+static inline unsigned a32_of(unsigned a256) { return a256 >= 256 ? 32 : (a256 + 4) >> 3; }
+
+color_t c_mix(color_t a, color_t b, unsigned t) {
+ if (t >= 256) return b;
+ return rgb((c_r(a) * (256 - t) + c_r(b) * t) >> 8, (c_g(a) * (256 - t) + c_g(b) * t) >> 8,
+ (c_b(a) * (256 - t) + c_b(b) * t) >> 8);
+}
+color_t c_scale(color_t a, unsigned t) {
+ if (t >= 256) return a;
+ return rgb(c_r(a) * t >> 8, c_g(a) * t >> 8, c_b(a) * t >> 8);
+}
+color_t c_hsv_lighten(color_t c, int sat_delta, int val_delta) {
+ float r = c_r(c) / 255.f, g = c_g(c) / 255.f, b = c_b(c) / 255.f;
+ float mx = r > g ? (r > b ? r : b) : (g > b ? g : b), mn = r < g ? (r < b ? r : b) : (g < b ? g : b);
+ float d = mx - mn, h = 0, s = mx > 0 ? d / mx : 0, v = mx;
+ if (d > 0) {
+ if (mx == r) h = (g - b) / d; else if (mx == g) h = 2 + (b - r) / d; else h = 4 + (r - g) / d;
+ h *= 60; if (h < 0) h += 360;
+ }
+ s += sat_delta / 100.f; v += val_delta / 100.f;
+ if (s < 0) s = 0; if (s > 1) s = 1; if (v < 0) v = 0; if (v > 1) v = 1;
+ float C = v * s, X = C * (1 - fabsf(fmodf(h / 60, 2) - 1)), m = v - C, rr, gg, bb;
+ int sector = (int)(h / 60) % 6;
+ switch (sector) {
+ case 0: rr = C; gg = X; bb = 0; break;
+ case 1: rr = X; gg = C; bb = 0; break;
+ case 2: rr = 0; gg = C; bb = X; break;
+ case 3: rr = 0; gg = X; bb = C; break;
+ case 4: rr = X; gg = 0; bb = C; break;
+ default: rr = C; gg = 0; bb = X; break;
+ }
+ return rgb((unsigned)((rr + m) * 255 + .5f), (unsigned)((gg + m) * 255 + .5f), (unsigned)((bb + m) * 255 + .5f));
+}
+
+void gfx_fill(int x, int y, int w, int h, color_t c) {
+ if (!clip_rect(&x, &y, &w, &h)) return;
+ for (int j = y; j < y + h; j++) {
+ uint16_t *p = pix(x, j);
+ for (int i = 0; i < w; i++) p[i] = c;
+ }
+}
+void gfx_blend(int x, int y, int w, int h, color_t c, unsigned alpha) {
+ unsigned a = a32_of(alpha);
+ if (!a) return;
+ if (a >= 32) { gfx_fill(x, y, w, h, c); return; }
+ if (!clip_rect(&x, &y, &w, &h)) return;
+ for (int j = y; j < y + h; j++) {
+ uint16_t *p = pix(x, j);
+ for (int i = 0; i < w; i++) p[i] = px_mix(p[i], c, a);
+ }
+}
+void gfx_add(int x, int y, int w, int h, color_t c, unsigned alpha) {
+ unsigned a = a32_of(alpha);
+ if (!a || !clip_rect(&x, &y, &w, &h)) return;
+ for (int j = y; j < y + h; j++) {
+ uint16_t *p = pix(x, j);
+ for (int i = 0; i < w; i++) p[i] = px_add(p[i], c, a);
+ }
+}
+void gfx_vgrad(int x, int y, int w, int h, color_t top, color_t bottom) {
+ int x0 = x, y0 = y, w0 = w, h0 = h;
+ if (h0 <= 0 || !clip_rect(&x, &y, &w, &h)) return;
+ for (int j = y; j < y + h; j++) {
+ color_t c = c_mix(top, bottom, h0 > 1 ? (unsigned)((j - y0) * 256 / (h0 - 1)) : 0);
+ uint16_t *p = pix(x, j);
+ for (int i = 0; i < w; i++) p[i] = c;
+ }
+ (void)x0; (void)w0;
+}
+void gfx_vgrad_alpha(int x, int y, int w, int h, color_t c, unsigned at, unsigned ab, int mode) {
+ int y0 = y, h0 = h;
+ if (h0 <= 0 || !clip_rect(&x, &y, &w, &h)) return;
+ for (int j = y; j < y + h; j++) {
+ unsigned a = a32_of(h0 > 1 ? (at * (unsigned)(h0 - 1 - (j - y0)) + ab * (unsigned)(j - y0)) / (unsigned)(h0 - 1) : at);
+ if (!a) continue;
+ uint16_t *p = pix(x, j);
+ if (mode == BLEND_ADD) for (int i = 0; i < w; i++) p[i] = px_add(p[i], c, a);
+ else for (int i = 0; i < w; i++) p[i] = px_mix(p[i], c, a);
+ }
+}
+void gfx_hgrad_alpha(int x, int y, int w, int h, color_t c, unsigned al, unsigned ar, int mode) {
+ int x0 = x, w0 = w;
+ if (w0 <= 0 || !clip_rect(&x, &y, &w, &h)) return;
+ for (int j = y; j < y + h; j++) {
+ uint16_t *p = pix(x, j);
+ for (int i = 0; i < w; i++) {
+ int k = x + i - x0;
+ unsigned a = a32_of(w0 > 1 ? (al * (unsigned)(w0 - 1 - k) + ar * (unsigned)k) / (unsigned)(w0 - 1) : al);
+ if (!a) continue;
+ p[i] = mode == BLEND_ADD ? px_add(p[i], c, a) : px_mix(p[i], c, a);
+ }
+ }
+}
+void gfx_scale_rect(int x, int y, int w, int h, unsigned keep) {
+ unsigned k = a32_of(keep);
+ if (k >= 32 || !clip_rect(&x, &y, &w, &h)) return;
+ for (int j = y; j < y + h; j++) {
+ uint16_t *p = pix(x, j);
+ for (int i = 0; i < w; i++) p[i] = px_mix(0, p[i], k);
+ }
+}
+
+static inline void put(uint16_t *p, color_t c, unsigned a32, int mode) {
+ if (!a32) return;
+ if (mode == BLEND_ADD) *p = px_add(*p, c, a32);
+ else *p = a32 >= 32 ? c : px_mix(*p, c, a32);
+}
+
+/* Discs and rings are processed as per-row spans; only the one-pixel
+ * anti-aliased edge needs a square root. */
+void gfx_disc(int cx16, int cy16, int r16, color_t c, unsigned alpha, int mode) {
+ if (r16 <= 0 || !alpha) return;
+ float cx = cx16 / 16.f, cy = cy16 / 16.f, r = r16 / 16.f;
+ int x = (int)floorf(cx - r - 1), y = (int)floorf(cy - r - 1), w = (int)(2 * r + 3), h = w;
+ if (!clip_rect(&x, &y, &w, &h)) return;
+ const unsigned full = a32_of(alpha);
+ const float ro = r + .5f, ri = r - .5f;
+ for (int j = y; j < y + h; j++) {
+ float dy = j + .5f - cy, dy2 = dy * dy;
+ if (dy2 >= ro * ro) continue;
+ float half = sqrtf(ro * ro - dy2);
+ int i0 = (int)floorf(cx - half - .5f), i1 = (int)ceilf(cx + half + .5f);
+ if (i0 < x) i0 = x;
+ if (i1 > x + w) i1 = x + w;
+ int k0 = i1, k1 = i1; /* fully covered interior */
+ if (ri > 0 && dy2 < ri * ri) {
+ float in = sqrtf(ri * ri - dy2);
+ k0 = (int)ceilf(cx - in + .5f);
+ k1 = (int)floorf(cx + in - .5f) + 1;
+ if (k0 < i0) k0 = i0;
+ if (k1 > i1) k1 = i1;
+ if (k1 < k0) k1 = k0;
+ }
+ uint16_t *p = pix(0, j);
+ for (int i = i0; i < i1; i++) {
+ if (i == k0 && k1 > k0) {
+ for (; i < k1; i++) put(p + i, c, full, mode);
+ if (i >= i1) break;
+ }
+ float dx = i + .5f - cx, d = sqrtf(dx * dx + dy2), cov = r - d + .5f;
+ if (cov <= 0) continue;
+ if (cov > 1) cov = 1;
+ put(p + i, c, a32_of((unsigned)(cov * alpha)), mode);
+ }
+ }
+}
+
+void gfx_ring(int cx16, int cy16, int r16, int t16, color_t c, unsigned alpha, int mode) {
+ if (r16 <= 0 || t16 <= 0 || !alpha) return;
+ float cx = cx16 / 16.f, cy = cy16 / 16.f, r = r16 / 16.f, t = t16 / 32.f;
+ int x = (int)floorf(cx - r - t - 1), y = (int)floorf(cy - r - t - 1), w = (int)(2 * (r + t) + 3), h = w;
+ if (!clip_rect(&x, &y, &w, &h)) return;
+ const float ro = r + t + .5f, ri = r - t - .5f;
+ for (int j = y; j < y + h; j++) {
+ float dy = j + .5f - cy, dy2 = dy * dy;
+ if (dy2 >= ro * ro) continue;
+ float out = sqrtf(ro * ro - dy2), in = ri > 0 && dy2 < ri * ri ? sqrtf(ri * ri - dy2) : -1;
+ /* the band is [cx-out, cx-in] and [cx+in, cx+out] (one span if in < 0) */
+ float spans[2][2] = {{cx - out, in >= 0 ? cx - in : cx + out}, {cx + in, cx + out}};
+ int nspans = in >= 0 ? 2 : 1;
+ uint16_t *p = pix(0, j);
+ for (int sidx = 0; sidx < nspans; sidx++) {
+ int i0 = (int)floorf(spans[sidx][0] - .5f), i1 = (int)ceilf(spans[sidx][1] + .5f);
+ if (i0 < x) i0 = x;
+ if (i1 > x + w) i1 = x + w;
+ for (int i = i0; i < i1; i++) {
+ float dx = i + .5f - cx, d = sqrtf(dx * dx + dy2), cov = t - fabsf(d - r) + .5f;
+ if (cov <= 0) continue;
+ if (cov > 1) cov = 1;
+ put(p + i, c, a32_of((unsigned)(cov * alpha)), mode);
+ }
+ }
+ }
+}
+void gfx_round_rect(int x, int y, int w, int h, int r, color_t c, unsigned alpha) {
+ int x0 = x, y0 = y, w0 = w, h0 = h;
+ if (!clip_rect(&x, &y, &w, &h)) return;
+ for (int j = y; j < y + h; j++) {
+ uint16_t *p = pix(x, j);
+ int ry = j - y0 < r ? r - (j - y0) : (j - y0 >= h0 - r ? (j - y0) - (h0 - r - 1) : 0);
+ for (int i = 0; i < w; i++) {
+ int k = x + i - x0;
+ int rx = k < r ? r - k : (k >= w0 - r ? k - (w0 - r - 1) : 0);
+ unsigned a = alpha;
+ if (rx && ry) {
+ float d = sqrtf((float)((rx - .5f) * (rx - .5f) + (ry - .5f) * (ry - .5f)));
+ float cov = r - d + .5f;
+ if (cov <= 0) continue;
+ if (cov < 1) a = (unsigned)(a * cov);
+ }
+ put(p + i, c, a32_of(a), BLEND_NORMAL);
+ }
+ }
+}
+void gfx_triangle(int x0, int y0, int x1, int y1, int x2, int y2, color_t c, unsigned alpha) {
+ float X[3] = {(float)x0, (float)x1, (float)x2}, Y[3] = {(float)y0, (float)y1, (float)y2};
+ float area = (X[1] - X[0]) * (Y[2] - Y[0]) - (X[2] - X[0]) * (Y[1] - Y[0]);
+ if (area == 0) return;
+ float nx[3], ny[3], nc[3];
+ for (int k = 0; k < 3; k++) {
+ int a = k, b = (k + 1) % 3;
+ float ex = X[b] - X[a], ey = Y[b] - Y[a], L = sqrtf(ex * ex + ey * ey);
+ float s = area > 0 ? 1.f : -1.f;
+ nx[k] = -ey / L * s; ny[k] = ex / L * s; nc[k] = -(nx[k] * X[a] + ny[k] * Y[a]);
+ }
+ int bx0 = (int)floorf(fminf(X[0], fminf(X[1], X[2]))), bx1 = (int)ceilf(fmaxf(X[0], fmaxf(X[1], X[2])));
+ int by0 = (int)floorf(fminf(Y[0], fminf(Y[1], Y[2]))), by1 = (int)ceilf(fmaxf(Y[0], fmaxf(Y[1], Y[2])));
+ int x = bx0, y = by0, w = bx1 - bx0 + 1, h = by1 - by0 + 1;
+ if (!clip_rect(&x, &y, &w, &h)) return;
+ for (int j = y; j < y + h; j++) {
+ uint16_t *p = pix(x, j);
+ for (int i = 0; i < w; i++) {
+ float px_ = x + i + .5f, py_ = j + .5f, m = 1e9f;
+ for (int k = 0; k < 3; k++) { float d = nx[k] * px_ + ny[k] * py_ + nc[k]; if (d < m) m = d; }
+ float cov = m + .5f;
+ if (cov <= 0) continue;
+ if (cov > 1) cov = 1;
+ put(p + i, c, a32_of((unsigned)(cov * alpha)), BLEND_NORMAL);
+ }
+ }
+}
+
+/* ---------------------------------------------------------------- sprites */
+
+typedef struct {
+ const Sprite *s;
+ const uint8_t *data;
+ int stride;
+ uint16_t col[16];
+ uint8_t a32[16];
+} Sampler;
+
+static void sampler_init(Sampler *sm, int spr, color_t tint, unsigned alpha) {
+ const Sprite *s = &sprites[spr];
+ sm->s = s;
+ sm->data = sprite_blob + s->off;
+ sm->stride = s->fmt == 1 ? s->w : (s->w + 1) / 2;
+ unsigned al = alpha > 256 ? 256 : alpha;
+ for (int k = 0; k < 16; k++) {
+ if (s->fmt == 2) {
+ sm->col[k] = sprite_pal_rgb[s->pal][k];
+ if (tint != 0xffff) sm->col[k] = rgb(c_r(sm->col[k]) * c_r(tint) / 255, c_g(sm->col[k]) * c_g(tint) / 255, c_b(sm->col[k]) * c_b(tint) / 255);
+ sm->a32[k] = (uint8_t)((sprite_pal_a[s->pal][k] * al * 32 + 15 * 128) / (15 * 256));
+ } else {
+ sm->col[k] = s->fmt == 1 ? c_scale(tint, (unsigned)(k * 256 / 15)) : tint;
+ sm->a32[k] = (uint8_t)((k * al * 32 + 15 * 128) / (15 * 256));
+ }
+ }
+}
+/* Returns colour and alpha (0..32) of source texel (u, v). */
+static inline unsigned sample(const Sampler *sm, int u, int v, uint16_t *c) {
+ const uint8_t *row = sm->data + v * sm->stride;
+ unsigned idx;
+ if (sm->s->fmt == 1) {
+ uint8_t b = row[u];
+ *c = sm->col[b >> 4];
+ return sm->a32[b & 15];
+ }
+ uint8_t b = row[u >> 1];
+ idx = (u & 1) ? b >> 4 : b & 15;
+ *c = sm->col[idx];
+ return sm->a32[idx];
+}
+
+int gfx_sprite_w(int spr, int xf) { return (xf & 1) ? sprites[spr].h : sprites[spr].w; }
+int gfx_sprite_h(int spr, int xf) { return (xf & 1) ? sprites[spr].w : sprites[spr].h; }
+
+void gfx_sprite(int spr, int x, int y, int xf, color_t tint, unsigned alpha, int mode) {
+ if (spr < 0 || !alpha) return;
+ const Sprite *s = &sprites[spr];
+ int w = s->w, h = s->h, rot = xf & XF_ROT;
+ int ax = (xf & XF_FLIPX) ? w - s->ax : s->ax, ay = (xf & XF_FLIPY) ? h - s->ay : s->ay;
+ int tax, tay, dw = w, dh = h;
+ switch (rot) {
+ case 1: tax = h - ay; tay = ax; dw = h; dh = w; break;
+ case 2: tax = w - ax; tay = h - ay; break;
+ case 3: tax = ay; tay = w - ax; dw = h; dh = w; break;
+ default: tax = ax; tay = ay; break;
+ }
+ int dx0 = x - tax, dy0 = y - tay, cx = dx0, cy = dy0, cw = dw, ch = dh;
+ if (!clip_rect(&cx, &cy, &cw, &ch)) return;
+ Sampler sm;
+ sampler_init(&sm, spr, tint, alpha);
+ for (int j = cy; j < cy + ch; j++) {
+ uint16_t *p = pix(cx, j);
+ int dy = j - dy0;
+ for (int i = 0; i < cw; i++) {
+ int dx = cx + i - dx0, u, v;
+ switch (rot) {
+ case 1: u = dy; v = h - 1 - dx; break;
+ case 2: u = w - 1 - dx; v = h - 1 - dy; break;
+ case 3: u = w - 1 - dy; v = dx; break;
+ default: u = dx; v = dy; break;
+ }
+ if (xf & XF_FLIPX) u = w - 1 - u;
+ if (xf & XF_FLIPY) v = h - 1 - v;
+ uint16_t c;
+ unsigned a = sample(&sm, u, v, &c);
+ put(p + i, c, a, mode);
+ }
+ }
+}
+
+/* Rotated / scaled sprite with bilinear filtering. The inverse transform is
+ * stepped in 16.16 fixed point; each row is clipped to the span where the
+ * sample falls inside the texture. */
+void gfx_sprite_ex(int spr, int x16, int y16, int ang16, int scale256, int flips, color_t tint, unsigned alpha, int mode) {
+ if (spr < 0 || !alpha || scale256 <= 0) return;
+ const Sprite *s = &sprites[spr];
+ float sc = scale256 / 256.f, ang = ang16 / 16.f * 3.14159265f / 180.f;
+ float cs = cosf(ang), sn = sinf(ang), cx = x16 / 16.f, cy = y16 / 16.f;
+ float w = s->w, h = s->h, ax = s->ax, ay = s->ay;
+ float corners[4][2] = {{-ax, -ay}, {w - ax, -ay}, {-ax, h - ay}, {w - ax, h - ay}};
+ float mnx = 1e9f, mny = 1e9f, mxx = -1e9f, mxy = -1e9f;
+ for (int k = 0; k < 4; k++) {
+ float px_ = corners[k][0] * sc, py_ = corners[k][1] * sc;
+ float rx = px_ * cs - py_ * sn + cx, ry = px_ * sn + py_ * cs + cy;
+ if (rx < mnx) mnx = rx; if (rx > mxx) mxx = rx; if (ry < mny) mny = ry; if (ry > mxy) mxy = ry;
+ }
+ int bx = (int)floorf(mnx) - 1, by = (int)floorf(mny) - 1, bw = (int)ceilf(mxx) - bx + 2, bh = (int)ceilf(mxy) - by + 2;
+ if (!clip_rect(&bx, &by, &bw, &bh)) return;
+ Sampler sm;
+ sampler_init(&sm, spr, tint, 256);
+ float inv = 1.f / sc;
+ /* u = (dx*cs + dy*sn)*inv + ax - .5, v = (-dx*sn + dy*cs)*inv + ay - .5 */
+ float dudx = cs * inv, dvdx = -sn * inv, dudy = sn * inv, dvdy = cs * inv;
+ float u0 = ax - .5f, v0 = ay - .5f;
+ if (flips & XF_FLIPX) { dudx = -dudx; dudy = -dudy; u0 = w - 1 - u0; }
+ if (flips & XF_FLIPY) { dvdx = -dvdx; dvdy = -dvdy; v0 = h - 1 - v0; }
+ const int W = s->w, H = s->h;
+ const int32_t sdu = (int32_t)(dudx * 65536), sdv = (int32_t)(dvdx * 65536);
+ const unsigned al = alpha > 256 ? 256 : alpha;
+ for (int j = by; j < by + bh; j++) {
+ float dx0 = bx + .5f - cx, dy = j + .5f - cy;
+ float uf = u0 + dx0 * dudx + dy * dudy, vf = v0 + dx0 * dvdx + dy * dvdy;
+ /* span where -1 < u < W and -1 < v < H */
+ float lo = 0, hi = (float)bw;
+ if (dudx > 1e-6f) { float a = (-1 - uf) / dudx, b = (W - uf) / dudx; if (a > lo) lo = a; if (b < hi) hi = b; }
+ else if (dudx < -1e-6f) { float a = (W - uf) / dudx, b = (-1 - uf) / dudx; if (a > lo) lo = a; if (b < hi) hi = b; }
+ else if (uf <= -1 || uf >= W) continue;
+ if (dvdx > 1e-6f) { float a = (-1 - vf) / dvdx, b = (H - vf) / dvdx; if (a > lo) lo = a; if (b < hi) hi = b; }
+ else if (dvdx < -1e-6f) { float a = (H - vf) / dvdx, b = (-1 - vf) / dvdx; if (a > lo) lo = a; if (b < hi) hi = b; }
+ else if (vf <= -1 || vf >= H) continue;
+ int i0 = (int)ceilf(lo), i1 = (int)ceilf(hi);
+ if (i0 < 0) i0 = 0;
+ if (i1 > bw) i1 = bw;
+ if (i0 >= i1) continue;
+ int32_t u = (int32_t)((uf + i0 * dudx) * 65536), v = (int32_t)((vf + i0 * dvdx) * 65536);
+ uint16_t *p = pix(bx + i0, j);
+ const uint8_t *data = sm.data;
+ const int stride = sm.stride, fmt = s->fmt;
+ for (int i = i0; i < i1; i++, p++, u += sdu, v += sdv) {
+ int32_t uu = u + 65536, vv = v + 65536; /* offset so that -1 < u maps to >= 0 */
+ if (uu < 0 || vv < 0) continue;
+ int ui = (uu >> 16) - 1, vi = (vv >> 16) - 1;
+ unsigned fu = (unsigned)(uu >> 8) & 255, fv = (unsigned)(vv >> 8) & 255;
+ unsigned idx[4];
+ if (ui >= 0 && vi >= 0 && ui + 1 < W && vi + 1 < H) {
+ if (fmt == 1) {
+ const uint8_t *r0 = data + vi * stride + ui, *r1 = r0 + stride;
+ idx[0] = r0[0]; idx[1] = r0[1]; idx[2] = r1[0]; idx[3] = r1[1];
+ } else {
+ const uint8_t *r0 = data + vi * stride, *r1 = r0 + stride;
+ int b0 = ui >> 1, b1 = (ui + 1) >> 1, s0 = (ui & 1) * 4, s1 = ((ui + 1) & 1) * 4;
+ idx[0] = (r0[b0] >> s0) & 15; idx[1] = (r0[b1] >> s1) & 15;
+ idx[2] = (r1[b0] >> s0) & 15; idx[3] = (r1[b1] >> s1) & 15;
+ }
+ } else {
+ for (int k = 0; k < 4; k++) {
+ int x = ui + (k & 1), y = vi + (k >> 1);
+ if (x < 0 || y < 0 || x >= W || y >= H) { idx[k] = 0; continue; }
+ const uint8_t *row = data + y * stride;
+ idx[k] = fmt == 1 ? row[x] : (unsigned)((row[x >> 1] >> ((x & 1) * 4)) & 15);
+ }
+ }
+ if (idx[0] == idx[1] && idx[0] == idx[2] && idx[0] == idx[3]) {
+ /* uniform neighbourhood: no filtering needed */
+ unsigned ix = idx[0], a = fmt == 1 ? sm.a32[ix & 15] : sm.a32[ix];
+ if (!a) continue;
+ color_t c = fmt == 1 ? sm.col[ix >> 4] : sm.col[ix];
+ put(p, c, (a * al + 128) >> 8, mode);
+ continue;
+ }
+ unsigned w00 = (256 - fu) * (256 - fv) >> 8, w10 = fu * (256 - fv) >> 8, w01 = (256 - fu) * fv >> 8, w11 = fu * fv >> 8;
+ unsigned wt[4] = {w00, w10, w01, w11};
+ unsigned ta = 0, tr = 0, tg = 0, tb = 0;
+ if (fmt == 0) {
+ /* A4: one colour, only coverage is filtered */
+ for (int k = 0; k < 4; k++) ta += sm.a32[idx[k]] * wt[k];
+ if (ta < 128) continue;
+ unsigned a32 = (ta * al + 32768) >> 16;
+ put(p, sm.col[0], a32 > 32 ? 32 : a32, mode);
+ continue;
+ }
+ for (int k = 0; k < 4; k++) {
+ unsigned ix = idx[k], a, cc;
+ if (fmt == 1) { a = sm.a32[ix & 15]; cc = sm.col[ix >> 4]; } else { a = sm.a32[ix]; cc = sm.col[ix]; }
+ a *= wt[k];
+ if (!a) continue;
+ ta += a;
+ tr += ((cc >> 11) & 31) * a;
+ tg += ((cc >> 5) & 63) * a;
+ tb += (cc & 31) * a;
+ }
+ if (ta < 128) continue;
+ color_t c = (color_t)(((tr / ta) << 11) | ((tg / ta) << 5) | (tb / ta));
+ unsigned a32 = (ta * al + 32768) >> 16;
+ put(p, c, a32 > 32 ? 32 : a32, mode);
+ }
+ }
+}
+
+/* ---------------------------------------------------------------- text */
+
+static int glyph_of(int font, int ch) {
+ (void)font;
+ if (ch < 32 || ch > 127) return -1;
+ unsigned g = font_charmap[ch - 32];
+ return g == 255 ? -1 : (int)g;
+}
+int gfx_text_width(int font, const char *s) {
+ const Font *f = &fonts[font];
+ int w = 0;
+ for (; *s && *s != '\n'; s++) {
+ int g = glyph_of(font, (unsigned char)*s);
+ w += g < 0 ? f->cap / 2 : f->advance[g];
+ }
+ return w + f->outline * 2;
+}
+
+/* Glyph coverage and its dilation (the black outline). Outline radii are 1
+ * (3x3 square) or 2 (5x5 disc without corners), computed separably. */
+enum { GB_W = 48, GB_H = 56 };
+static uint8_t g_cov[GB_H][GB_W], g_h1[GB_H][GB_W], g_dil[GB_H][GB_W];
+
+/* Fills rows [k0, k1) of the extended glyph box (w x h plus a margin of r). */
+static void glyph_rows(const Sprite *s, int r, int ew, int eh, int k0, int k1) {
+ if (k0 < 0) k0 = 0;
+ if (k1 > eh) k1 = eh;
+ const uint8_t *data = sprite_blob + s->off;
+ int stride = (s->w + 1) / 2;
+ int c0 = k0 - r < 0 ? 0 : k0 - r, c1 = k1 + r > eh ? eh : k1 + r;
+ for (int k = c0; k < c1; k++) {
+ uint8_t *row = g_cov[k];
+ memset(row, 0, (size_t)ew);
+ int v = k - r;
+ if (v >= 0 && v < s->h) {
+ const uint8_t *src = data + v * stride;
+ for (int u = 0; u < s->w; u++) row[u + r] = (u & 1) ? src[u >> 1] >> 4 : src[u >> 1] & 15;
+ }
+ uint8_t *h1 = g_h1[k];
+ for (int i = 0; i < ew; i++) {
+ uint8_t m = row[i];
+ if (i > 0 && row[i - 1] > m) m = row[i - 1];
+ if (i + 1 < ew && row[i + 1] > m) m = row[i + 1];
+ h1[i] = m;
+ }
+ }
+ for (int k = k0; k < k1; k++) {
+ uint8_t *d = g_dil[k];
+ for (int i = 0; i < ew; i++) {
+ uint8_t m = 0;
+ if (r == 1) {
+ for (int dy = -1; dy <= 1; dy++) {
+ int kk = k + dy;
+ if (kk >= 0 && kk < eh && g_h1[kk][i] > m) m = g_h1[kk][i];
+ }
+ } else {
+ for (int dy = -2; dy <= 2; dy++) {
+ int kk = k + dy;
+ if (kk < 0 || kk >= eh) continue;
+ const uint8_t *h = g_h1[kk];
+ uint8_t v = h[i];
+ if (dy > -2 && dy < 2) { /* |dx| <= 2 */
+ if (i > 0 && h[i - 1] > v) v = h[i - 1];
+ if (i + 1 < ew && h[i + 1] > v) v = h[i + 1];
+ }
+ if (v > m) m = v;
+ }
+ }
+ d[i] = m;
+ }
+ }
+}
+
+/* Draw one glyph: shadow, outline then gradient fill. Only rows inside the
+ * current strip are computed. */
+static void draw_glyph(const Font *f, int spr, int x, int baseline, color_t top, color_t bottom, unsigned alpha) {
+ const Sprite *s = &sprites[spr];
+ int r = f->outline, gx = x - s->ax, gy = baseline - s->ay;
+ int sdx = f->sdx > 0 ? f->sdx : 0, sdy = f->sdy > 0 ? f->sdy : 0;
+ int ex0 = gx - r, ey0 = gy - r, ew = s->w + 2 * r + sdx, eh = s->h + 2 * r + sdy;
+ if (ew > GB_W || eh > GB_H) return;
+ int cx = ex0, cy = ey0, cw = ew, ch = eh;
+ if (!clip_rect(&cx, &cy, &cw, &ch)) return;
+ int bw = s->w + 2 * r, bh = s->h + 2 * r; /* dilated box without shadow */
+ int k0 = cy - ey0 - sdy, k1 = cy + ch - ey0;
+ glyph_rows(s, r, bw, bh, k0, k1);
+ unsigned al = alpha > 256 ? 256 : alpha;
+ int cap_top = baseline - f->cap;
+ for (int j = cy; j < cy + ch; j++) {
+ uint16_t *p = pix(cx, j);
+ int t = (j - cap_top) * 256 / (f->cap > 1 ? f->cap : 1);
+ color_t fill = c_mix(top, bottom, (unsigned)(t < 0 ? 0 : t > 256 ? 256 : t));
+ int lj = j - ey0, sj = lj - sdy;
+ for (int i = 0; i < cw; i++) {
+ int li = cx + i - ex0, si = li - sdx;
+ unsigned sh = (si >= 0 && sj >= 0 && si < bw && sj < bh) ? g_dil[sj][si] * f->shadow / 15 : 0;
+ unsigned o = 0, fv = 0;
+ if (li < bw && lj < bh) { o = g_dil[lj][li]; fv = g_cov[lj][li]; }
+ if (sh && o < 15) put(p + i, 0, a32_of(sh * al / 15), BLEND_NORMAL);
+ if (o) put(p + i, 0, a32_of(o * al / 15), BLEND_NORMAL);
+ if (fv) put(p + i, fill, a32_of(fv * al / 15), BLEND_NORMAL);
+ }
+ }
+}
+
+void gfx_text(int font, int x, int baseline, const char *s, color_t top, color_t bottom, unsigned alpha) {
+ const Font *f = &fonts[font];
+ if (baseline + f->cap < gfx_y0 - 8 || baseline - 2 * f->cap > gfx_y1 + 8 || !alpha) return;
+ x += f->outline;
+ for (; *s && *s != '\n'; s++) {
+ int g = glyph_of(font, (unsigned char)*s);
+ if (g < 0) { x += f->cap / 2; continue; }
+ if (*s != ' ') draw_glyph(f, f->base + g, x, baseline, top, bottom, alpha);
+ x += f->advance[g];
+ }
+}
+void gfx_text_center(int font, int cx, int baseline, const char *s, color_t top, color_t bottom, unsigned alpha) {
+ gfx_text(font, cx - gfx_text_width(font, s) / 2, baseline, s, top, bottom, alpha);
+}
+void gfx_text_right(int font, int rx, int baseline, const char *s, color_t top, color_t bottom, unsigned alpha) {
+ gfx_text(font, rx - gfx_text_width(font, s), baseline, s, top, bottom, alpha);
+}
+int gfx_format_uint(char *buf, unsigned long v) {
+ char tmp[12];
+ int n = 0, len = 0;
+ do { tmp[n++] = (char)('0' + v % 10); v /= 10; } while (v && n < 11);
+ while (n) buf[len++] = tmp[--n];
+ buf[len] = 0;
+ return len;
+}
+void gfx_number(int font, int x, int baseline, long v, color_t c) {
+ char buf[16];
+ if (v < 0) { buf[0] = '-'; gfx_format_uint(buf + 1, (unsigned long)(-v)); }
+ else gfx_format_uint(buf, (unsigned long)v);
+ gfx_text(font, x, baseline, buf, c, c, 256);
+}
+
+/* ------------------------------------------------------------ text layer */
+
+/* Text rendered once into coverage nibbles (fill high, outline low) so it
+ * can be drawn scaled each frame: used by the pop-in titles. */
+enum { TL_W = 320, TL_H = 64 };
+static uint8_t tl_buf[TL_W * TL_H];
+static int tl_w, tl_h, tl_font, tl_ox, tl_oy; /* origin: layer pixel of the anchor */
+static int tl_line_top[4], tl_line_cap[4], tl_lines;
+static color_t tl_top[4], tl_bot[4];
+static bool tl_custom[4];
+void gfx_layer_line_color(int line, color_t top, color_t bottom) {
+ if (line < 0 || line >= 4) return;
+ tl_top[line] = top;
+ tl_bot[line] = bottom;
+ tl_custom[line] = true;
+}
+
+void gfx_layer_build(int font, const char *s) {
+ const Font *f = &fonts[font];
+ int r = f->outline, line_h = f->cap + f->cap / 2 + 2 * r + 2;
+ int lines = 1, maxw = 0;
+ for (const char *q = s; *q; q++) if (*q == '\n') lines++;
+ if (lines > 4) lines = 4;
+ const char *q = s;
+ for (int l = 0; l < lines; l++) {
+ int w = gfx_text_width(font, q);
+ if (w > maxw) maxw = w;
+ while (*q && *q != '\n') q++;
+ if (*q) q++;
+ }
+ tl_w = maxw + f->sdx + 2 < TL_W ? maxw + f->sdx + 2 : TL_W;
+ tl_h = lines * line_h + f->sdy < TL_H ? lines * line_h + f->sdy : TL_H;
+ tl_font = font;
+ tl_lines = lines;
+ memset(tl_custom, 0, sizeof(tl_custom));
+ memset(tl_buf, 0, sizeof(tl_buf));
+ q = s;
+ for (int l = 0; l < lines; l++) {
+ int w = gfx_text_width(font, q), pen = (tl_w - w) / 2 + r, base = l * line_h + r + f->cap + 1;
+ tl_line_top[l] = base - f->cap;
+ tl_line_cap[l] = f->cap;
+ for (; *q && *q != '\n'; q++) {
+ int g = glyph_of(font, (unsigned char)*q);
+ if (g < 0) { pen += f->cap / 2; continue; }
+ const Sprite *sp = &sprites[f->base + g];
+ int bw = sp->w + 2 * r, bh = sp->h + 2 * r;
+ if (*q != ' ' && bw <= GB_W && bh <= GB_H) {
+ glyph_rows(sp, r, bw, bh, 0, bh);
+ int ox = pen - sp->ax - r, oy = base - sp->ay - r;
+ for (int k = 0; k < bh; k++) {
+ int y = oy + k;
+ if (y < 0 || y >= tl_h) continue;
+ for (int i = 0; i < bw; i++) {
+ int x = ox + i;
+ if (x < 0 || x >= tl_w) continue;
+ uint8_t *d = &tl_buf[y * TL_W + x];
+ unsigned fo = *d >> 4, oo = *d & 15, fn = g_cov[k][i], on = g_dil[k][i];
+ if (fn > fo) fo = fn;
+ if (on > oo) oo = on;
+ *d = (uint8_t)(fo << 4 | oo);
+ }
+ }
+ }
+ pen += f->advance[g];
+ }
+ if (*q) q++;
+ }
+ tl_ox = tl_w / 2;
+ tl_oy = tl_h / 2;
+}
+
+/* Draws the layer centred on (cx, cy) with scale in 1/256. Gradient colours
+ * run over each line's cap height. Nearest sampling below 1.5x is enough at
+ * this size; the scale animations are short. */
+void gfx_layer_draw(int cx, int cy, int scale256, color_t top, color_t bottom, unsigned alpha) {
+ if (scale256 < 8 || !alpha) return;
+ const Font *f = &fonts[tl_font];
+ int dw = tl_w * scale256 / 256 + 2, dh = tl_h * scale256 / 256 + 2;
+ int x = cx - dw / 2, y = cy - dh / 2, w = dw, h = dh;
+ if (!clip_rect(&x, &y, &w, &h)) return;
+ int inv = 65536 / scale256; /* 1/256 layer px per screen px, *256 */
+ unsigned al = alpha > 256 ? 256 : alpha;
+ int sdx = f->sdx * 256, sdy = f->sdy * 256;
+ for (int j = y; j < y + h; j++) {
+ int v = ((j - cy) * 2 + 1) * inv / 2 + tl_oy * 256; /* 1/256 px */
+ int vi = v >> 8;
+ color_t fill = top;
+ for (int l = 0; l < tl_lines; l++) {
+ if (vi >= tl_line_top[l] - 4 && vi <= tl_line_top[l] + tl_line_cap[l] + 6) {
+ int t = (vi - tl_line_top[l]) * 256 / tl_line_cap[l];
+ fill = c_mix(tl_custom[l] ? tl_top[l] : top, tl_custom[l] ? tl_bot[l] : bottom, (unsigned)(t < 0 ? 0 : t > 256 ? 256 : t));
+ break;
+ }
+ }
+ int vs = (v - sdy) >> 8;
+ bool row_ok = vi >= 0 && vi < tl_h, srow_ok = vs >= 0 && vs < tl_h;
+ if (!row_ok && !srow_ok) continue;
+ uint16_t *p = pix(x, j);
+ for (int i = 0; i < w; i++) {
+ int u = ((x + i - cx) * 2 + 1) * inv / 2 + tl_ox * 256;
+ int ui = u >> 8, us = (u - sdx) >> 8;
+ unsigned sh = 0, o = 0, fv = 0;
+ if (srow_ok && us >= 0 && us < tl_w) sh = (tl_buf[vs * TL_W + us] & 15) * f->shadow / 15;
+ if (row_ok && ui >= 0 && ui < tl_w) { uint8_t b = tl_buf[vi * TL_W + ui]; o = b & 15; fv = b >> 4; }
+ if (sh && o < 15) put(p + i, 0, a32_of(sh * al / 15), BLEND_NORMAL);
+ if (o) put(p + i, 0, a32_of(o * al / 15), BLEND_NORMAL);
+ if (fv) put(p + i, fill, a32_of(fv * al / 15), BLEND_NORMAL);
+ }
+ }
+}
+
+/* ------------------------------------------------------------ polygons */
+
+/* Anti-aliased convex polygon (vertices in pixels, either winding). */
+void gfx_poly(const float *xy, int n, color_t c, unsigned alpha, int mode) {
+ if (n < 3 || n > 8 || !alpha) return;
+ float area = 0, nx[8], ny[8], nc[8];
+ for (int k = 0; k < n; k++) {
+ int b = (k + 1) % n;
+ area += xy[2 * k] * xy[2 * b + 1] - xy[2 * b] * xy[2 * k + 1];
+ }
+ if (area == 0) return;
+ float sgn = area > 0 ? 1.f : -1.f, mnx = 1e9f, mny = 1e9f, mxx = -1e9f, mxy = -1e9f;
+ for (int k = 0; k < n; k++) {
+ int b = (k + 1) % n;
+ float ex = xy[2 * b] - xy[2 * k], ey = xy[2 * b + 1] - xy[2 * k + 1], L = sqrtf(ex * ex + ey * ey);
+ if (L < 1e-6f) { nx[k] = ny[k] = 0; nc[k] = 1e9f; continue; }
+ nx[k] = -ey / L * sgn; ny[k] = ex / L * sgn; nc[k] = -(nx[k] * xy[2 * k] + ny[k] * xy[2 * k + 1]);
+ if (xy[2 * k] < mnx) mnx = xy[2 * k];
+ if (xy[2 * k] > mxx) mxx = xy[2 * k];
+ if (xy[2 * k + 1] < mny) mny = xy[2 * k + 1];
+ if (xy[2 * k + 1] > mxy) mxy = xy[2 * k + 1];
+ }
+ int x = (int)floorf(mnx) - 1, y = (int)floorf(mny) - 1, w = (int)ceilf(mxx) - x + 2, h = (int)ceilf(mxy) - y + 2;
+ if (!clip_rect(&x, &y, &w, &h)) return;
+ const unsigned full = a32_of(alpha);
+ for (int j = y; j < y + h; j++) {
+ uint16_t *p = pix(x, j);
+ float py_ = j + .5f;
+ /* [lo, hi): every edge distance > -0.5 (touched); [flo, fhi): > 0.5 (fully covered) */
+ float lo = (float)x, hi = (float)(x + w), flo = lo, fhi = hi;
+ bool empty = false;
+ for (int k = 0; k < n && !empty; k++) {
+ float a = nx[k], d = ny[k] * py_ + nc[k]; /* distance at px is a*px + d */
+ if (a > 1e-6f) {
+ float t = (-.5f - d) / a, u = (.5f - d) / a;
+ if (t > lo) lo = t;
+ if (u > flo) flo = u;
+ } else if (a < -1e-6f) {
+ float t = (-.5f - d) / a, u = (.5f - d) / a;
+ if (t < hi) hi = t;
+ if (u < fhi) fhi = u;
+ } else {
+ if (d <= -.5f) empty = true;
+ if (d < .5f) fhi = flo - 1;
+ }
+ }
+ if (empty || hi <= lo) continue;
+ int i0 = (int)floorf(lo - .5f) - x, i1 = (int)ceilf(hi + .5f) - x;
+ int f0 = (int)ceilf(flo - .5f) - x, f1 = (int)floorf(fhi - .5f) - x + 1;
+ if (i0 < 0) i0 = 0;
+ if (i1 > w) i1 = w;
+ if (f0 < i0) f0 = i0;
+ if (f1 > i1) f1 = i1;
+ if (f1 < f0) f1 = f0;
+ for (int i = i0; i < i1; i++) {
+ if (i == f0 && f1 > f0) {
+ for (; i < f1; i++) put(p + i, c, full, mode);
+ if (i >= i1) break;
+ }
+ float px_ = x + i + .5f, m = 1e9f;
+ for (int k = 0; k < n; k++) { float d = nx[k] * px_ + ny[k] * py_ + nc[k]; if (d < m) m = d; }
+ float cov = m + .5f;
+ if (cov <= 0) continue;
+ if (cov > 1) cov = 1;
+ put(p + i, c, a32_of((unsigned)(cov * alpha)), mode);
+ }
+ }
+}
diff --git a/games/numdash/src/gfx.h b/games/numdash/src/gfx.h
new file mode 100644
index 00000000..486f8fca
--- /dev/null
+++ b/games/numdash/src/gfx.h
@@ -0,0 +1,83 @@
+#ifndef NUMDASH_GFX_H
+#define NUMDASH_GFX_H
+#include <stdbool.h>
+#include <stdint.h>
+#include "assets.h"
+
+/* The screen is rendered in horizontal strips: every primitive clips to the
+ * current strip, so a full frame needs only one strip of RGB565 memory. */
+enum { GFX_W = 320, GFX_H = 240, STRIP_H = 24, STRIPS = GFX_H / STRIP_H };
+extern uint16_t gfx_strip[GFX_W * STRIP_H];
+extern int gfx_y0, gfx_y1;
+void gfx_begin_strip(int index);
+void gfx_clip(int x0, int y0, int x1, int y1);
+void gfx_unclip(void);
+
+typedef uint16_t color_t;
+static inline color_t rgb(unsigned r, unsigned g, unsigned b) {
+ return (color_t)(((r & 0xf8) << 8) | ((g & 0xfc) << 3) | (b >> 3));
+}
+static inline unsigned c_r(color_t c) { unsigned v = (c >> 11) & 31; return (v << 3) | (v >> 2); }
+static inline unsigned c_g(color_t c) { unsigned v = (c >> 5) & 63; return (v << 2) | (v >> 4); }
+static inline unsigned c_b(color_t c) { unsigned v = c & 31; return (v << 3) | (v >> 2); }
+color_t c_mix(color_t a, color_t b, unsigned t256);
+color_t c_scale(color_t a, unsigned t256);
+color_t c_hsv_lighten(color_t c, int sat_delta, int val_delta);
+static inline uint16_t px_mix(uint16_t d, uint16_t s, unsigned a32) {
+ uint32_t dd = (d | ((uint32_t)d << 16)) & 0x07E0F81Fu;
+ uint32_t ss = (s | ((uint32_t)s << 16)) & 0x07E0F81Fu;
+ uint32_t r = ((ss * a32 + dd * (32 - a32)) >> 5) & 0x07E0F81Fu;
+ return (uint16_t)(r | (r >> 16));
+}
+static inline uint16_t px_add(uint16_t d, uint16_t s, unsigned a32) {
+ uint32_t dd = (d | ((uint32_t)d << 16)) & 0x07E0F81Fu;
+ uint32_t ss = (((s | ((uint32_t)s << 16)) & 0x07E0F81Fu) * a32 >> 5) & 0x07E0F81Fu;
+ uint32_t sum = dd + ss;
+ uint32_t o1 = sum & 0x00010020u, o2 = sum & 0x08000000u;
+ sum |= (o1 - (o1 >> 5)) | (o2 - (o2 >> 6));
+ sum &= 0x07E0F81Fu;
+ return (uint16_t)(sum | (sum >> 16));
+}
+
+enum { BLEND_NORMAL = 0, BLEND_ADD = 1 };
+/* Transform bits: rotation in 90 degree clockwise steps, then flips (applied
+ * to the source first, as in cocos2d). */
+enum { XF_ROT = 3, XF_FLIPX = 4, XF_FLIPY = 8 };
+
+void gfx_fill(int x, int y, int w, int h, color_t c);
+void gfx_blend(int x, int y, int w, int h, color_t c, unsigned alpha256);
+void gfx_add(int x, int y, int w, int h, color_t c, unsigned alpha256);
+void gfx_vgrad(int x, int y, int w, int h, color_t top, color_t bottom);
+void gfx_vgrad_alpha(int x, int y, int w, int h, color_t c, unsigned a_top, unsigned a_bottom, int mode);
+void gfx_hgrad_alpha(int x, int y, int w, int h, color_t c, unsigned a_left, unsigned a_right, int mode);
+void gfx_scale_rect(int x, int y, int w, int h, unsigned keep256);
+/* Anti-aliased discs and rings; coordinates in 1/16 pixel. */
+void gfx_disc(int cx16, int cy16, int r16, color_t c, unsigned alpha256, int mode);
+void gfx_ring(int cx16, int cy16, int r16, int thick16, color_t c, unsigned alpha256, int mode);
+void gfx_round_rect(int x, int y, int w, int h, int r, color_t c, unsigned alpha256);
+void gfx_triangle(int x0, int y0, int x1, int y1, int x2, int y2, color_t c, unsigned alpha256);
+
+void gfx_sprite(int spr, int x, int y, int xform, color_t tint, unsigned alpha256, int mode);
+/* Rotated/scaled sprite, bilinear. Angle in degrees clockwise, positions in
+ * 1/16 px, scale in 1/256. */
+void gfx_sprite_ex(int spr, int x16, int y16, int angle_deg16, int scale256, int flips, color_t tint, unsigned alpha256, int mode);
+int gfx_sprite_w(int spr, int xform);
+int gfx_sprite_h(int spr, int xform);
+
+int gfx_text_width(int font, const char *s);
+/* Draws outlined text with its pen at (x, baseline). top/bottom tint a
+ * vertical gradient over the cap height. */
+void gfx_text(int font, int x, int baseline, const char *s, color_t top, color_t bottom, unsigned alpha256);
+void gfx_text_center(int font, int cx, int baseline, const char *s, color_t top, color_t bottom, unsigned alpha256);
+void gfx_text_right(int font, int rx, int baseline, const char *s, color_t top, color_t bottom, unsigned alpha);
+void gfx_number(int font, int x, int baseline, long v, color_t c);
+/* Writes v in decimal, returns the length. */
+int gfx_format_uint(char *buf, unsigned long v);
+/* One cached text layer (lines separated by '\n') drawn scaled around its
+ * centre; used for the pop-in titles. */
+void gfx_layer_build(int font, const char *s);
+void gfx_layer_draw(int cx, int cy, int scale256, color_t top, color_t bottom, unsigned alpha);
+void gfx_layer_line_color(int line, color_t top, color_t bottom);
+/* Anti-aliased convex polygon, up to 8 vertices (x, y pairs in pixels). */
+void gfx_poly(const float *xy, int n, color_t c, unsigned alpha, int mode);
+#endif
diff --git a/games/numdash/src/inflate.c b/games/numdash/src/inflate.c
new file mode 100644
index 00000000..682ef3d5
--- /dev/null
+++ b/games/numdash/src/inflate.c
@@ -0,0 +1,146 @@
+/* Minimal raw DEFLATE (RFC 1951) decoder used to unpack built-in levels.
+ * Canonical Huffman codes are decoded bit by bit from per-length counts,
+ * which keeps the tables tiny; level data is only a few kilobytes. */
+#include "level.h"
+#include <string.h>
+
+typedef struct {
+ const uint8_t *in;
+ size_t len, pos;
+ uint32_t bits;
+ int nbits;
+ uint8_t *out;
+ size_t cap, n;
+ bool error;
+} Inflater;
+
+typedef struct { uint16_t count[16], symbol[288]; } Huffman;
+
+static int bits(Inflater *s, int need) {
+ while (s->nbits < need) {
+ if (s->pos >= s->len) { s->error = true; return 0; }
+ s->bits |= (uint32_t)s->in[s->pos++] << s->nbits;
+ s->nbits += 8;
+ }
+ int v = (int)(s->bits & ((1u << need) - 1));
+ s->bits >>= need;
+ s->nbits -= need;
+ return v;
+}
+
+static bool build(Huffman *h, const uint8_t *lengths, int n) {
+ uint16_t offs[16];
+ memset(h->count, 0, sizeof(h->count));
+ for (int i = 0; i < n; i++) h->count[lengths[i]]++;
+ h->count[0] = 0;
+ int left = 1;
+ for (int len = 1; len < 16; len++) {
+ left <<= 1;
+ left -= h->count[len];
+ if (left < 0) return false;
+ }
+ offs[1] = 0;
+ for (int len = 1; len < 15; len++) offs[len + 1] = (uint16_t)(offs[len] + h->count[len]);
+ for (int i = 0; i < n; i++)
+ if (lengths[i]) h->symbol[offs[lengths[i]]++] = (uint16_t)i;
+ return true;
+}
+
+static int decode(Inflater *s, const Huffman *h) {
+ int code = 0, first = 0, index = 0;
+ for (int len = 1; len < 16; len++) {
+ code |= bits(s, 1);
+ if (s->error) return -1;
+ int count = h->count[len];
+ if (code - count < first) return h->symbol[index + (code - first)];
+ index += count;
+ first += count;
+ first <<= 1;
+ code <<= 1;
+ }
+ s->error = true;
+ return -1;
+}
+
+static const uint16_t len_base[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
+static const uint8_t len_extra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
+static const uint16_t dist_base[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
+static const uint8_t dist_extra[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
+
+static bool codes(Inflater *s, const Huffman *lit, const Huffman *dist) {
+ for (;;) {
+ int sym = decode(s, lit);
+ if (sym < 0) return false;
+ if (sym < 256) {
+ if (s->n >= s->cap) return false;
+ s->out[s->n++] = (uint8_t)sym;
+ } else if (sym == 256) {
+ return true;
+ } else {
+ sym -= 257;
+ if (sym >= 29) return false;
+ size_t len = len_base[sym] + (size_t)bits(s, len_extra[sym]);
+ int d = decode(s, dist);
+ if (d < 0 || d >= 30) return false;
+ size_t back = dist_base[d] + (size_t)bits(s, dist_extra[d]);
+ if (s->error || back > s->n || s->n + len > s->cap) return false;
+ for (size_t i = 0; i < len; i++, s->n++) s->out[s->n] = s->out[s->n - back];
+ }
+ }
+}
+
+int inflate_raw(uint8_t *out, size_t cap, const uint8_t *in, size_t len) {
+ static Huffman lit, dist;
+ static const uint8_t order[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
+ Inflater s = {in, len, 0, 0, 0, out, cap, 0, false};
+ int last;
+ do {
+ last = bits(&s, 1);
+ int type = bits(&s, 2);
+ if (s.error) return -1;
+ if (type == 0) {
+ s.bits = 0; s.nbits = 0;
+ if (s.pos + 4 > s.len) return -1;
+ unsigned n = s.in[s.pos] | (unsigned)s.in[s.pos + 1] << 8, nn = s.in[s.pos + 2] | (unsigned)s.in[s.pos + 3] << 8;
+ s.pos += 4;
+ if ((n ^ 0xffffu) != nn || s.pos + n > s.len || s.n + n > s.cap) return -1;
+ memcpy(s.out + s.n, s.in + s.pos, n);
+ s.pos += n; s.n += n;
+ } else if (type == 1) {
+ uint8_t lengths[320];
+ int i = 0;
+ for (; i < 144; i++) lengths[i] = 8;
+ for (; i < 256; i++) lengths[i] = 9;
+ for (; i < 280; i++) lengths[i] = 7;
+ for (; i < 288; i++) lengths[i] = 8;
+ build(&lit, lengths, 288);
+ for (i = 0; i < 30; i++) lengths[i] = 5;
+ build(&dist, lengths, 30);
+ if (!codes(&s, &lit, &dist)) return -1;
+ } else if (type == 2) {
+ uint8_t lengths[320];
+ int nlen = bits(&s, 5) + 257, ndist = bits(&s, 5) + 1, ncode = bits(&s, 4) + 4;
+ if (s.error || nlen > 286 || ndist > 30) return -1;
+ for (int i = 0; i < 19; i++) lengths[order[i]] = i < ncode ? (uint8_t)bits(&s, 3) : 0;
+ if (s.error || !build(&lit, lengths, 19)) return -1;
+ int i = 0;
+ while (i < nlen + ndist) {
+ int sym = decode(&s, &lit);
+ if (sym < 0) return -1;
+ if (sym < 16) { lengths[i++] = (uint8_t)sym; continue; }
+ int rep, val = 0;
+ if (sym == 16) { if (!i) return -1; val = lengths[i - 1]; rep = 3 + bits(&s, 2); }
+ else if (sym == 17) rep = 3 + bits(&s, 3);
+ else rep = 11 + bits(&s, 7);
+ if (s.error || i + rep > nlen + ndist) return -1;
+ while (rep--) lengths[i++] = (uint8_t)val;
+ }
+ if (!lengths[256]) return -1;
+ if (!build(&lit, lengths, nlen) || !build(&dist, lengths + nlen, ndist)) return -1;
+ if (!codes(&s, &lit, &dist)) return -1;
+ } else {
+ return -1;
+ }
+ } while (!last);
+ return (int)s.n;
+}
diff --git a/games/numdash/src/level.c b/games/numdash/src/level.c
new file mode 100644
index 00000000..4728b77b
--- /dev/null
+++ b/games/numdash/src/level.c
@@ -0,0 +1,69 @@
+#include "level.h"
+#include <string.h>
+
+LObj level_objs[MAX_OBJECTS];
+
+bool level_load_builtin(Level *L, unsigned index) {
+ if (index >= LEVEL_COUNT) return false;
+ const LevelDef *d = &level_defs[index];
+ if (d->count > MAX_OBJECTS) return false;
+ int n = inflate_raw((uint8_t *)level_objs, sizeof(level_objs), d->data, d->data_len);
+ if (n != (int)(d->count * sizeof(LObj))) return false;
+ unsigned x = 0;
+ for (unsigned i = 0; i < d->count; i++) {
+ x += level_objs[i].x;
+ if (x > 0xffff) return false;
+ level_objs[i].x = (uint16_t)x;
+ }
+ memset(L, 0, sizeof(*L));
+ L->name = d->name;
+ L->objs = level_objs;
+ L->count = d->count;
+ L->events = d->events;
+ L->event_count = d->event_count;
+ L->end_x = d->end_x;
+ L->wall_x = d->wall_x;
+ memcpy(L->colors[CH_BG], d->bg, 3);
+ memcpy(L->colors[CH_G1], d->g1, 3);
+ memcpy(L->colors[CH_LINE], d->line, 3);
+ memcpy(L->colors[CH_OBJ], d->obj, 3);
+ L->bpm = d->bpm;
+ L->start_mode = d->start_mode;
+ L->difficulty = d->difficulty;
+ L->stars = d->stars;
+ level_index_coins(L);
+ return level_valid(L);
+}
+
+void level_index_coins(Level *L) {
+ L->coin_count = 0;
+ for (unsigned i = 0; i < L->count && L->coin_count < 3; i++)
+ if (L->objs[i].type == OT_COIN) L->coin_obj[L->coin_count++] = (uint16_t)i;
+}
+
+unsigned level_lower_bound(const Level *L, int x) {
+ unsigned a = 0, b = L->count;
+ while (a < b) {
+ unsigned m = (a + b) / 2;
+ if (L->objs[m].x < x) a = m + 1; else b = m;
+ }
+ return a;
+}
+
+bool level_valid(const Level *L) {
+ if (!L || !L->objs || L->count > MAX_OBJECTS || L->end_x < 300 || L->wall_x < L->end_x - 30) return false;
+ for (unsigned i = 0; i < L->count; i++) {
+ const LObj *o = &L->objs[i];
+ if (!o->type || o->type >= OT_COUNT || o->y < -600 || o->y > 3000 || (o->xf & 0xf0) || (i && o->x < L->objs[i - 1].x))
+ return false;
+ }
+ for (unsigned i = 0; i < L->event_count; i++)
+ if (!L->events[i].kind || L->events[i].kind > EV_TRAIL) return false;
+ return true;
+}
+
+void obj_hitbox(const LObj *o, float *hw, float *hh) {
+ const ObjDef *d = &objdefs[o->type];
+ float w = d->w10 * 0.05f, h = d->h10 * 0.05f;
+ if (o->xf & 1) { *hw = h; *hh = w; } else { *hw = w; *hh = h; }
+}
diff --git a/games/numdash/src/level.h b/games/numdash/src/level.h
new file mode 100644
index 00000000..6514d31f
--- /dev/null
+++ b/games/numdash/src/level.h
@@ -0,0 +1,49 @@
+#ifndef NUMDASH_LEVEL_H
+#define NUMDASH_LEVEL_H
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#include "objdefs.h"
+
+#define LEVEL_COUNT 7
+#define MAX_OBJECTS 4096
+
+/* Runtime object: GD units, sorted by x. xf: rotation (90 degree steps,
+ * clockwise) in bits 0-1, flip x bit 2, flip y bit 3. Matches the 6-byte
+ * records produced by tools/levels.py, so levels inflate in place. */
+typedef struct { uint16_t x; int16_t y; uint8_t type, xf; } LObj;
+typedef struct { uint16_t x; int16_t y; uint8_t kind, arg, r, g, b, flags; uint16_t dur; } LevelEvent;
+enum { EVF_TOUCH = 1, EVF_TINT_GROUND = 2, EVF_BLEND = 4 };
+enum { CH_BG = 0, CH_G1 = 1, CH_LINE = 2, CH_OBJ = 3, CH_COUNT = 4 };
+
+typedef struct {
+ const char *name;
+ const uint8_t *data;
+ const LevelEvent *events;
+ uint16_t data_len, count, event_count, end_x, wall_x, reserved;
+ uint8_t bg[3], g1[3], line[3], obj[3];
+ uint8_t difficulty, stars, bpm, start_mode;
+} LevelDef;
+extern const LevelDef level_defs[LEVEL_COUNT];
+
+typedef struct {
+ const char *name;
+ const LObj *objs;
+ const LevelEvent *events;
+ uint16_t count, event_count, end_x, wall_x;
+ uint8_t colors[CH_COUNT][3];
+ uint8_t bpm, start_mode, difficulty, stars;
+ uint16_t coin_obj[3]; /* object indices of the secret coins, in order */
+ uint8_t coin_count;
+} Level;
+/* Fills coin_obj / coin_count from the object list. */
+void level_index_coins(Level *L);
+
+extern LObj level_objs[MAX_OBJECTS];
+int inflate_raw(uint8_t *out, size_t cap, const uint8_t *in, size_t len);
+bool level_load_builtin(Level *L, unsigned index);
+unsigned level_lower_bound(const Level *L, int x);
+bool level_valid(const Level *L);
+/* Rotated hitbox half extents in GD units. */
+void obj_hitbox(const LObj *o, float *hw, float *hh);
+#endif
diff --git a/games/numdash/src/leveldata.c b/games/numdash/src/leveldata.c
new file mode 100644
index 00000000..4c653978
--- /dev/null
+++ b/games/numdash/src/leveldata.c
@@ -0,0 +1,580 @@
+/* Generated by tools/levels.py from levels/reference. Do not edit. */
+#include "level.h"
+static const uint8_t level0_data[2247] = {
+ 237,90,49,108,28,69,20,253,179,187,119,222,179,201,158,147,59,159,237,196,62,26,28,132,200,54,32,87,46,40,16,66,202,85,200,13,38,66,40,66,
+ 145,114,21,74,131,145,40,34,132,148,171,32,52,151,6,9,9,41,46,83,37,18,18,13,82,92,166,139,128,138,130,43,221,33,209,115,204,252,191,179,
+ 251,103,103,102,111,239,176,67,130,104,230,70,127,222,255,243,231,207,252,63,127,255,220,185,160,13,9,60,22,77,104,67,31,168,175,90,234,171,86,0,
+ 192,21,232,200,126,0,231,179,22,224,28,172,231,148,20,49,68,111,67,83,182,87,45,124,7,122,57,101,128,248,20,145,132,191,41,199,63,13,138,121,
+ 31,201,54,196,126,80,163,13,35,191,110,179,229,40,77,146,185,228,47,193,6,91,123,136,171,8,66,213,15,176,191,4,167,213,7,105,171,100,1,9,
+ 196,155,162,254,82,195,8,53,20,124,21,230,138,246,161,37,219,119,161,27,171,157,90,3,63,242,22,34,111,72,164,223,38,68,185,139,200,47,75,72,
+ 106,55,240,60,52,51,228,3,68,126,239,68,114,125,0,158,32,242,39,39,146,239,62,192,17,52,66,77,57,130,166,236,143,228,30,1,12,177,29,96,
+ 155,98,219,198,246,8,109,53,66,187,105,235,145,253,85,59,196,150,48,71,104,103,142,28,50,100,138,246,183,49,92,142,15,147,90,210,142,113,247,235,
+ 34,1,78,164,125,234,225,79,208,146,243,201,175,131,244,99,10,11,152,152,178,245,244,25,62,98,94,48,242,216,153,86,109,35,7,37,221,250,108,189,
+ 46,188,173,225,188,120,27,57,116,226,251,14,76,90,210,220,191,246,180,18,99,107,229,63,201,42,38,140,32,138,252,152,81,22,253,234,142,242,221,153,
+ 61,170,125,121,146,197,222,127,31,105,159,67,90,133,251,124,234,81,146,198,49,109,195,199,67,68,70,149,24,183,47,204,139,113,211,129,241,246,157,163,
+ 116,18,2,161,36,71,145,246,244,129,195,199,73,142,127,180,159,97,92,186,5,78,31,247,209,7,168,79,138,109,59,211,45,200,35,252,16,154,98,118,
+ 191,33,124,25,8,221,98,252,230,50,41,229,190,94,117,249,198,228,146,77,138,175,175,238,178,106,164,210,188,60,215,46,210,139,27,150,40,190,62,207,
+ 127,248,104,245,189,111,223,182,186,37,11,208,232,13,207,29,205,103,172,186,247,251,149,55,190,61,187,239,198,199,253,149,174,245,21,92,224,167,34,52,
+ 173,164,206,131,190,233,166,185,85,237,51,99,234,111,159,40,59,91,152,64,24,43,153,170,191,45,178,188,66,226,247,176,127,32,84,54,56,100,241,153,
+ 199,207,9,4,200,171,250,219,98,9,185,84,123,32,10,143,120,17,185,142,209,38,19,136,194,69,120,139,25,39,47,56,239,65,46,193,207,107,115,145,
+ 180,58,188,19,38,161,154,55,181,242,207,250,188,246,125,231,227,173,111,43,91,194,243,198,203,87,253,207,120,195,151,208,23,86,230,231,173,239,125,207,
+ 134,203,117,18,170,185,84,70,97,223,224,19,180,201,20,251,50,102,10,149,123,236,80,204,20,24,51,69,79,242,118,133,226,237,34,94,181,83,217,126,
+ 45,214,100,156,255,76,70,240,14,124,32,103,237,194,125,49,197,186,193,19,252,98,221,22,77,212,170,17,223,17,219,162,33,41,75,66,209,219,208,144,
+ 244,29,137,167,170,130,66,38,241,243,221,119,235,127,71,80,157,228,109,217,87,86,109,176,250,140,217,38,130,172,49,5,37,231,4,239,77,45,217,108,
+ 239,21,242,151,125,210,138,182,153,205,139,58,204,196,243,218,206,0,185,174,75,174,63,60,154,152,237,4,72,255,38,232,157,61,198,181,60,168,88,203,
+ 98,109,172,206,88,11,207,88,11,79,93,75,173,177,219,234,201,190,174,234,152,183,60,221,251,116,203,167,88,243,25,160,143,112,95,224,62,66,126,145,
+ 234,156,246,63,137,36,204,20,254,71,250,144,42,30,242,184,71,145,112,12,175,228,209,47,197,47,47,37,161,135,113,47,62,131,90,226,105,246,117,69,
+ 145,34,146,191,250,74,190,207,163,65,129,236,33,50,118,124,29,12,145,107,144,197,28,205,203,49,17,126,115,93,52,184,70,25,87,57,7,208,55,87,
+ 131,36,199,126,109,117,181,176,145,251,254,235,66,85,170,207,201,88,1,112,77,108,90,85,130,208,170,45,52,242,47,169,162,6,171,37,40,105,9,92,
+ 131,203,176,90,137,161,185,108,57,126,10,223,29,63,165,216,181,114,125,158,125,201,70,186,111,239,221,77,171,170,111,87,125,221,123,7,112,167,242,5,
+ 97,148,237,78,211,201,75,248,251,149,111,10,180,107,35,196,87,203,121,92,41,231,24,229,28,33,190,142,180,223,43,215,53,65,105,199,136,175,47,243,
+ 175,74,153,83,148,73,183,228,188,146,183,68,167,216,59,209,42,205,114,194,42,9,39,208,114,124,137,155,117,140,39,22,230,1,195,248,250,182,199,241,
+ 111,246,187,12,89,244,99,149,25,98,221,190,27,246,242,147,230,174,228,223,102,18,110,103,21,21,119,133,57,151,35,92,249,170,226,229,25,105,92,138,
+ 63,107,89,252,137,81,43,204,28,114,221,184,86,215,81,7,122,33,162,81,162,248,244,177,243,237,235,108,69,3,166,33,105,123,221,218,133,114,109,202,
+ 87,11,2,185,19,45,120,10,229,247,62,142,137,37,87,177,46,170,47,145,204,221,188,46,212,83,24,195,62,144,201,105,231,47,131,102,191,188,251,246,
+ 44,179,228,43,251,199,114,165,5,23,173,122,159,113,237,51,174,66,159,162,213,171,126,154,101,224,71,168,225,8,84,28,254,5,54,97,203,67,255,213,
+ 67,191,104,209,47,122,144,63,122,232,191,101,116,162,208,168,162,71,115,190,201,154,62,69,239,179,190,151,89,59,134,187,223,103,245,203,157,154,165,233,
+ 188,181,197,140,200,207,43,171,124,167,240,235,160,84,253,219,101,163,60,199,88,103,116,245,101,244,200,216,71,173,121,34,47,191,207,97,147,189,53,39,
+ 129,175,79,200,123,134,109,223,148,223,155,137,40,230,226,243,250,251,69,171,78,206,186,236,81,255,85,249,229,18,176,21,205,178,63,89,230,157,138,90,
+ 235,22,124,140,50,111,121,100,22,94,191,5,95,32,242,46,67,250,250,212,210,62,30,99,251,39,108,26,163,122,143,200,122,197,249,52,37,208,121,251,
+ 33,167,171,243,108,70,149,68,218,92,100,81,2,224,27,249,171,110,19,157,23,249,214,146,160,13,87,13,59,15,208,95,20,61,176,120,57,222,247,174,
+ 237,170,192,115,63,218,183,98,230,174,243,46,163,88,234,239,23,167,244,231,204,50,35,92,251,80,122,122,128,244,13,139,14,25,93,181,65,70,39,140,
+ 26,125,67,20,177,218,158,17,224,45,216,244,86,254,19,134,89,157,113,38,185,199,21,50,205,25,73,147,148,237,105,217,139,77,143,254,144,201,41,231,
+ 3,93,156,125,185,134,253,93,154,208,235,63,81,220,190,233,138,48,118,84,220,205,238,232,196,153,177,208,232,85,22,217,232,13,200,126,151,169,158,69,
+ 157,201,132,205,181,234,209,208,165,63,143,159,55,13,77,214,106,190,43,205,126,75,234,226,186,150,243,108,86,224,215,174,192,47,95,193,110,22,213,142,
+ 177,154,167,34,195,182,68,118,176,118,215,193,220,169,131,185,74,71,12,69,155,241,238,96,204,87,149,46,125,114,166,153,52,93,121,208,113,102,194,232,
+ 105,169,30,219,247,208,129,241,62,91,76,29,157,125,235,229,246,161,26,224,78,126,247,1,188,38,206,27,245,118,128,135,216,142,177,61,20,75,207,21,
+ 146,206,225,233,74,174,194,0,188,44,214,165,156,43,98,57,199,31,176,209,49,227,34,57,87,196,74,110,115,58,141,69,45,90,113,169,118,140,237,67,
+ 17,5,122,175,249,14,182,157,53,240,242,140,84,45,23,185,7,13,42,206,134,201,107,174,55,136,235,156,64,211,38,7,76,206,188,18,236,21,157,157,
+ 14,156,247,144,217,237,128,89,67,219,121,71,232,183,170,217,190,102,106,178,87,146,236,243,196,217,22,112,249,169,194,135,57,198,60,219,193,130,116,53,
+ 123,226,241,172,42,204,166,88,251,71,243,22,25,114,17,225,9,67,249,33,33,199,34,12,209,59,194,190,227,187,213,137,15,200,155,234,201,167,213,125,
+ 43,86,43,236,83,53,234,162,43,91,105,222,143,196,133,25,118,147,183,167,88,45,97,232,31,35,101,251,187,164,85,203,153,79,130,73,167,60,199,55,
+ 186,35,54,74,242,191,19,237,192,63,123,157,81,58,237,83,230,113,132,63,182,246,75,173,84,249,203,37,140,120,101,127,172,226,114,229,24,117,102,89,
+ 204,230,62,9,148,203,85,203,209,187,214,64,164,250,127,215,39,162,124,83,211,125,84,87,159,121,232,99,124,37,84,126,7,112,91,116,23,244,14,215,
+ 104,57,182,204,99,91,109,147,176,194,38,26,19,228,255,55,104,235,47,241,124,199,167,248,237,83,70,226,57,140,207,18,79,218,214,197,159,30,114,47,
+ 187,95,66,140,78,145,211,98,123,217,173,116,9,145,65,254,218,110,199,4,194,31,178,117,217,72,58,153,110,36,205,226,138,120,117,36,87,203,108,179,
+ 152,207,227,9,125,103,77,152,77,236,89,124,55,245,108,94,61,251,226,18,158,245,236,97,158,133,74,63,138,204,47,107,30,27,57,111,117,62,80,119,
+ 180,30,157,110,73,59,78,142,241,109,221,150,112,136,121,194,24,223,205,41,91,112,98,2,158,111,199,236,69,30,216,75,125,207,200,250,124,150,177,181,
+ 50,185,138,44,197,252,31,75,57,255,177,241,252,205,183,14,222,45,95,239,66,29,46,29,25,148,245,40,174,214,159,81,242,70,252,44,45,166,237,252,
+ 171,123,31,95,154,230,229,122,15,35,240,89,235,118,40,46,131,206,103,38,134,87,10,86,253,22,136,87,103,114,79,34,123,234,236,173,224,105,92,89,
+ 202,234,27,170,178,241,55,
+};
+static const LevelEvent level0_events[19] = {
+ {135,165,1,1,96,0,185,0,10000},
+ {135,135,1,0,158,3,255,0,10000},
+ {3615,165,2,5,0,0,0,0,0},
+ {7365,405,1,0,0,4,4,0,2000},
+ {7365,375,1,1,0,24,25,0,2000},
+ {7815,405,2,1,0,0,0,0,0},
+ {7965,405,1,0,255,10,114,0,500},
+ {7965,377,1,1,83,0,39,0,500},
+ {12555,405,1,1,138,7,205,0,500},
+ {12555,375,1,0,188,0,255,0,500},
+ {12855,195,2,1,0,0,0,0,0},
+ {14445,315,2,0,0,0,0,0,0},
+ {14595,345,2,5,0,0,0,0,0},
+ {15345,315,1,1,140,0,30,0,500},
+ {15345,285,1,0,241,0,38,0,500},
+ {22965,315,1,1,45,0,38,0,500},
+ {22965,285,1,0,255,0,201,0,500},
+ {24135,375,1,0,255,0,25,1,500},
+ {24135,375,1,1,0,0,0,1,500},
+};
+static const uint8_t level1_data[1486] = {
+ 237,90,79,139,92,69,16,175,55,11,153,201,26,231,109,204,100,116,101,247,33,162,1,33,115,220,131,18,20,15,18,112,192,203,128,224,34,168,4,33,
+ 227,109,133,192,146,28,36,4,178,185,37,32,17,114,240,184,7,15,235,41,224,193,227,30,227,41,32,120,157,111,16,240,3,140,221,85,221,175,171,187,
+ 171,251,181,227,196,120,240,210,52,213,191,174,238,250,63,175,107,30,86,61,216,129,6,106,24,10,227,99,54,31,86,254,106,5,0,151,225,130,154,247,
+ 224,188,25,1,94,134,87,91,202,4,49,53,156,81,227,199,10,57,204,158,213,192,30,156,69,188,180,250,12,74,78,239,195,107,193,233,68,119,119,72,
+ 223,118,138,248,9,34,9,127,29,241,225,77,254,96,243,111,113,60,52,103,77,213,252,7,164,236,195,13,24,246,0,190,71,250,41,108,43,60,205,21,
+ 125,176,5,90,15,67,70,105,18,243,120,111,131,123,97,197,189,249,59,208,46,119,231,167,9,233,36,43,132,90,226,187,174,64,222,238,154,79,163,44,
+ 113,182,181,23,217,209,81,172,189,52,69,154,19,135,82,79,176,152,61,198,129,124,239,2,140,197,85,39,11,231,96,199,186,229,239,223,57,158,79,144,
+ 67,184,42,201,75,60,223,64,91,243,179,82,222,59,99,220,62,130,209,160,17,118,29,48,204,53,133,209,242,94,4,9,121,159,33,111,139,220,98,237,
+ 217,248,37,138,211,164,111,175,208,166,254,184,151,93,157,121,252,47,102,118,145,164,71,173,182,185,135,164,189,104,98,236,91,137,218,142,125,140,235,159,
+ 231,153,73,132,140,181,17,103,155,207,49,70,74,108,205,233,97,142,149,252,191,36,70,66,110,93,146,166,178,101,126,215,220,196,209,153,96,239,205,172,
+ 236,161,151,110,161,44,195,104,30,239,29,50,137,182,178,119,27,10,18,157,34,229,24,179,226,159,42,31,18,135,115,168,183,30,91,221,50,28,100,252,
+ 0,111,56,54,243,56,198,237,220,207,138,15,112,188,135,227,14,142,119,87,172,128,206,55,160,195,175,100,155,150,228,31,107,211,121,196,225,46,243,201,
+ 3,140,53,151,133,94,65,203,158,99,148,198,155,243,248,149,61,199,191,207,140,197,114,106,78,190,68,25,227,253,76,118,141,51,161,159,21,227,204,121,
+ 194,144,39,81,229,34,187,16,135,219,152,123,227,124,117,45,162,83,198,187,218,210,173,206,103,217,60,233,78,244,35,154,231,201,212,220,229,171,56,171,
+ 119,205,167,172,186,165,106,132,211,94,42,219,196,54,149,42,26,113,224,72,210,225,215,98,181,26,171,147,54,7,90,39,187,42,6,201,10,119,2,173,
+ 166,171,97,152,195,249,89,0,159,85,111,246,37,252,18,46,181,57,135,123,239,77,244,58,231,195,20,221,175,103,199,79,217,111,239,235,44,39,124,2,
+ 31,98,182,249,2,249,223,199,223,123,33,229,231,68,141,160,113,7,239,211,43,142,178,6,158,160,236,58,191,249,177,240,132,249,67,60,119,120,27,29,
+ 191,123,28,198,153,8,58,137,226,46,228,208,168,220,171,125,239,36,19,23,214,106,116,214,65,22,73,81,198,227,253,14,243,43,254,59,202,249,91,28,
+ 155,54,114,195,202,30,87,222,84,165,243,115,23,207,183,115,24,110,96,196,109,224,239,150,141,198,216,139,91,240,39,120,219,88,240,189,222,110,165,171,
+ 255,18,87,119,171,190,154,47,112,190,84,119,177,20,170,95,11,164,56,186,214,170,150,49,198,115,110,154,255,190,249,141,97,253,173,207,106,74,191,165,
+ 216,27,246,61,58,192,119,48,194,189,142,50,69,110,181,65,86,166,234,237,67,44,11,221,147,238,182,104,71,137,126,218,142,141,170,212,85,43,99,136,
+ 209,213,135,170,185,219,21,107,230,0,53,195,145,68,15,241,105,204,146,221,182,27,163,199,75,34,50,117,255,148,6,142,255,166,140,199,230,171,80,194,
+ 52,194,46,174,103,78,231,214,9,253,231,202,63,240,31,43,203,220,120,78,184,122,220,242,212,223,5,125,17,249,43,122,32,33,83,24,206,173,4,35,
+ 175,218,189,116,226,81,34,34,230,89,121,99,205,112,189,213,70,183,171,70,125,89,116,228,188,203,121,78,206,187,142,208,226,221,126,184,62,95,77,201,
+ 219,157,223,224,185,249,39,192,143,232,9,105,111,169,58,61,60,183,215,241,95,213,151,14,61,143,154,24,93,185,152,34,45,77,141,110,171,224,14,220,
+ 79,126,131,122,240,63,242,223,71,174,15,179,48,94,244,223,192,0,124,169,104,62,178,102,30,158,71,150,243,124,177,200,114,137,242,72,110,223,117,241,
+ 172,189,250,30,74,183,94,127,232,62,11,212,23,135,254,213,253,21,102,188,110,121,203,36,213,220,136,243,250,228,125,30,178,148,216,247,197,200,146,206,
+ 45,203,168,130,216,234,227,240,203,182,250,0,60,132,183,212,55,220,2,70,149,166,235,113,138,227,68,141,3,252,46,126,234,117,34,194,23,51,233,125,
+ 62,94,77,125,27,218,78,65,238,173,128,222,205,102,65,79,161,251,85,100,220,201,141,191,215,213,237,55,17,117,10,82,29,150,146,206,157,255,5,234,
+ 94,198,248,13,27,207,46,115,246,58,55,99,24,61,142,80,150,77,161,75,146,234,104,16,55,206,95,230,28,235,65,194,196,157,29,249,253,92,210,48,
+ 255,54,47,213,240,101,163,97,95,63,85,251,235,235,23,216,110,123,169,37,152,154,69,65,136,233,234,49,241,183,130,110,100,87,31,42,215,183,146,58,
+ 116,37,239,210,229,183,154,4,47,138,77,66,58,128,15,138,53,67,200,148,231,243,30,214,59,137,62,90,248,194,147,238,245,240,119,194,74,197,3,192,
+ 35,60,157,114,218,249,106,187,125,149,58,197,87,59,194,208,77,136,174,41,252,253,106,132,178,111,26,10,189,144,31,48,111,231,111,236,180,215,205,37,
+ 206,52,127,132,47,105,132,209,183,29,227,41,3,67,121,9,99,246,93,124,121,160,215,84,90,229,241,72,122,152,69,190,196,95,170,229,185,205,36,87,
+ 217,75,90,252,14,22,119,15,87,155,59,143,122,204,186,42,223,180,117,71,91,225,22,218,136,230,68,191,213,198,166,197,135,171,205,74,148,67,49,75,
+ 187,216,119,81,143,90,26,60,131,114,204,81,84,73,29,38,221,9,229,185,55,142,98,238,219,114,87,61,221,87,178,29,198,116,199,176,139,39,207,33,
+ 165,60,253,155,204,217,46,138,196,57,235,193,133,171,182,63,149,250,61,32,223,161,187,199,234,110,235,186,102,62,134,226,122,206,122,214,113,253,242,255,
+ 125,33,85,168,191,0,
+};
+static const LevelEvent level1_events[15] = {
+ {4095,255,2,5,0,0,0,0,0},
+ {4215,225,1,1,167,0,89,0,500},
+ {4215,195,1,0,252,0,131,0,500},
+ {10665,225,1,1,138,0,9,0,10000},
+ {10665,195,1,0,253,0,34,0,10000},
+ {12645,465,2,0,0,0,0,0,0},
+ {12645,435,1,0,130,1,255,0,500},
+ {12645,405,1,1,74,0,144,0,500},
+ {16785,405,2,1,0,0,0,0,0},
+ {16785,375,1,0,255,0,172,0,500},
+ {16785,345,1,1,179,0,110,0,500},
+ {20985,315,2,5,0,0,0,0,0},
+ {21045,375,1,0,0,136,254,0,300},
+ {21045,345,1,1,0,93,196,0,300},
+ {23685,225,2,1,0,0,0,0,0},
+};
+static const uint8_t level2_data[1934] = {
+ 181,25,77,143,84,69,176,122,223,124,185,226,155,1,118,103,119,9,12,68,129,196,132,145,8,26,15,96,144,144,120,112,194,129,16,15,46,168,137,167,
+ 29,53,33,196,203,68,15,196,11,131,39,79,16,141,87,231,232,137,77,8,231,61,234,5,18,195,193,211,254,0,19,18,127,192,218,85,245,250,189,170,
+ 254,120,51,200,122,120,149,78,85,117,117,117,85,117,85,117,191,191,76,11,186,48,0,132,7,224,60,28,135,67,80,97,190,22,212,21,162,46,11,234,
+ 68,80,123,68,205,5,85,195,46,24,0,56,3,135,237,120,9,14,122,112,72,212,174,229,5,194,0,124,148,224,100,234,97,232,91,120,195,174,152,230,
+ 121,23,94,177,240,83,216,80,152,216,152,165,249,252,90,218,107,176,86,98,120,47,231,173,165,112,156,23,48,55,8,1,198,144,119,0,166,196,243,136,
+ 164,197,241,91,5,134,169,146,63,142,255,210,174,126,52,169,91,199,218,112,37,235,23,152,33,52,51,189,247,33,180,178,244,24,161,179,252,136,214,69,
+ 155,72,124,237,216,128,178,82,133,241,199,77,195,90,49,166,143,58,155,78,233,133,213,70,204,155,104,237,73,17,33,168,219,164,176,185,140,153,84,180,
+ 140,108,132,240,90,7,80,190,245,88,60,90,66,105,19,92,43,35,175,101,232,133,60,67,105,134,252,104,148,95,38,34,6,116,108,196,227,118,93,68,
+ 90,43,224,105,89,11,34,245,146,165,174,71,244,228,185,44,77,250,151,253,165,247,110,216,191,229,190,110,89,173,32,33,77,235,185,70,167,99,77,80,
+ 245,30,115,248,67,140,223,177,223,97,56,39,48,95,8,127,221,35,204,135,196,243,1,141,223,42,172,199,113,206,49,95,97,82,227,122,206,23,149,115,
+ 142,78,211,219,86,159,110,134,86,66,56,178,112,213,194,166,103,183,49,237,171,178,79,143,226,42,15,60,171,109,56,78,100,167,42,38,117,86,209,60,
+ 25,233,176,148,161,14,8,111,81,68,141,44,29,241,109,210,173,157,192,100,13,154,107,104,174,113,115,235,52,241,163,116,181,196,140,19,60,109,27,157,
+ 243,180,189,105,45,140,86,205,140,212,71,91,18,45,144,39,34,144,79,129,196,180,224,182,213,103,93,69,169,228,255,133,78,235,99,130,207,232,204,106,
+ 42,198,192,99,130,207,8,182,205,134,23,243,241,213,7,9,127,1,188,31,245,178,140,7,128,235,165,100,93,155,166,20,141,51,210,228,207,96,45,214,
+ 33,172,38,242,84,174,137,108,224,215,86,237,163,184,182,122,71,215,19,217,128,107,101,60,87,12,172,71,42,29,100,228,212,237,61,54,150,154,92,163,
+ 76,53,164,184,194,136,194,252,188,84,70,248,144,34,138,99,251,154,136,109,105,141,75,53,182,74,219,240,82,162,250,179,55,101,238,173,214,61,68,18,
+ 14,4,99,166,118,104,95,253,68,190,173,159,27,203,249,232,211,197,87,143,73,168,236,188,216,220,121,113,190,90,142,195,126,108,6,167,44,254,111,138,
+ 222,87,13,230,210,55,9,190,65,121,181,73,240,115,162,94,182,227,45,131,85,227,1,28,51,134,170,42,142,49,242,159,194,174,133,219,132,7,170,107,
+ 15,136,122,17,118,8,143,179,54,11,158,25,117,11,200,201,181,120,147,234,245,182,146,185,87,226,121,214,69,139,57,109,37,239,208,24,121,6,5,255,
+ 152,164,49,63,235,182,75,99,174,242,188,138,235,28,218,132,65,184,71,18,184,254,238,10,42,103,233,189,146,243,229,120,220,90,255,23,79,85,83,98,
+ 250,184,93,87,252,123,165,77,0,238,195,73,209,89,185,83,92,245,129,75,165,228,52,6,171,24,159,241,186,236,58,136,212,107,230,185,149,236,193,86,
+ 203,94,235,114,89,77,82,89,177,69,81,189,94,91,235,195,61,186,142,116,254,190,194,222,85,106,184,76,245,119,165,230,30,180,106,171,39,102,224,158,
+ 192,231,69,38,159,81,237,216,33,191,252,99,51,91,47,216,69,94,100,134,170,6,113,85,210,210,56,67,62,34,106,85,143,46,98,119,215,113,253,240,
+ 207,116,67,193,238,238,46,193,123,193,29,16,125,116,60,114,55,60,141,247,2,213,123,247,85,254,228,213,79,90,122,95,228,192,16,47,49,64,189,77,
+ 63,33,33,38,179,242,120,47,18,81,91,86,171,88,151,34,43,20,99,216,179,232,229,65,113,239,64,109,15,169,78,73,198,9,74,230,222,201,245,114,
+ 85,180,240,25,116,29,157,140,153,114,150,73,159,139,177,176,42,83,119,161,217,193,115,138,248,179,102,131,172,212,42,118,154,238,10,166,196,63,38,206,
+ 138,95,75,222,35,201,199,12,114,94,53,27,53,253,228,44,208,202,206,178,115,47,208,220,175,12,71,96,43,178,162,147,128,186,233,156,176,67,50,103,
+ 66,230,5,146,249,9,201,252,65,200,212,93,189,147,175,59,82,62,83,186,138,53,147,90,201,189,188,136,197,118,233,236,112,206,60,43,44,198,94,75,
+ 205,218,161,89,156,111,15,138,89,169,28,232,103,0,221,25,14,3,95,164,58,210,110,177,35,221,139,110,211,73,127,16,185,255,166,222,121,194,30,146,
+ 95,27,24,127,2,142,116,52,213,239,72,99,55,166,219,129,204,41,201,100,252,205,82,166,142,195,31,19,221,44,195,223,136,202,145,102,108,22,174,34,
+ 13,37,51,245,39,79,91,119,250,126,39,42,207,242,33,192,55,148,1,62,166,12,240,30,193,13,58,239,12,89,67,87,79,243,66,14,205,106,208,44,
+ 67,179,140,156,197,146,123,246,59,90,242,95,177,89,245,72,209,215,201,92,250,125,153,21,229,237,64,223,20,22,137,222,95,75,255,106,57,99,218,221,
+ 136,246,85,221,7,5,181,65,212,228,125,112,153,44,176,226,69,72,60,182,183,130,186,25,102,227,170,218,214,221,94,247,91,126,24,171,29,81,143,82,
+ 183,254,234,245,172,57,231,45,20,169,153,28,55,210,217,187,94,26,203,65,9,79,189,83,220,140,222,40,235,36,239,135,133,195,250,245,109,241,134,80,
+ 151,111,83,181,134,243,158,206,228,70,212,172,188,227,250,213,171,70,190,164,225,59,228,84,112,166,115,181,89,32,51,27,117,243,74,229,100,119,143,152,
+ 151,135,77,36,15,63,13,48,117,119,231,248,152,243,112,217,189,68,226,89,190,122,133,55,253,120,159,191,120,15,239,191,32,149,120,239,45,75,246,165,
+ 104,79,238,84,87,196,234,203,104,225,226,205,22,74,170,219,233,178,242,44,119,188,104,103,205,19,206,138,99,122,116,154,26,81,78,206,117,206,170,203,
+ 170,123,105,195,49,206,213,157,14,218,161,209,183,99,121,186,49,242,79,89,41,14,243,144,110,205,79,12,238,241,185,57,130,55,44,219,225,232,255,23,
+ 247,233,30,247,144,224,19,211,50,142,122,199,188,158,105,124,152,19,174,216,181,152,202,156,110,110,136,225,181,66,252,21,115,220,195,243,169,231,55,192,
+ 240,236,75,78,190,29,132,152,59,230,244,130,156,114,119,18,115,95,224,75,27,26,105,195,207,136,255,104,1,135,244,218,25,255,135,53,89,248,70,51,
+ 41,110,64,213,109,136,51,173,243,233,203,100,108,217,143,213,103,93,255,86,181,169,242,3,191,138,87,121,67,143,229,220,240,5,50,92,55,94,47,98,
+ 153,223,207,108,48,247,95,91,115,193,23,206,69,234,166,148,188,120,85,146,171,212,247,231,119,107,87,156,82,12,140,41,191,249,61,82,186,214,76,41,
+ 183,248,93,19,202,105,44,133,179,28,191,93,229,63,80,195,125,57,254,54,236,239,90,206,50,139,72,232,10,173,70,69,76,238,191,62,124,35,230,170,
+ 228,115,10,47,148,254,98,223,89,47,100,21,79,70,126,65,239,204,40,243,135,94,43,111,40,196,137,112,68,112,72,176,75,80,159,244,76,252,131,91,
+ 90,96,204,127,91,114,245,231,78,254,63,221,92,56,143,185,213,249,220,225,42,18,242,42,62,30,87,63,67,255,79,135,84,127,71,226,207,41,235,240,
+ 157,61,245,242,206,232,255,63,205,164,52,149,39,169,86,150,175,67,117,231,93,159,89,206,33,39,232,239,185,255,31,147,225,118,249,79,121,94,222,211,
+ 127,172,170,188,39,189,230,191,249,248,121,102,86,252,65,70,249,220,221,177,23,226,248,65,109,85,170,167,2,253,243,126,174,246,235,215,5,157,177,235,
+ 243,91,170,119,149,54,151,252,188,86,181,138,182,222,40,144,63,22,182,170,127,187,112,246,79,175,53,80,171,12,19,107,189,236,142,6,212,185,129,245,
+ 65,139,58,186,22,253,43,105,210,223,144,28,254,5,
+};
+static const LevelEvent level2_events[22] = {
+ {2295,225,1,1,110,163,0,0,0},
+ {2295,195,1,0,172,255,0,0,0},
+ {4155,225,1,1,0,140,116,0,6000},
+ {4155,195,1,0,0,255,159,0,6000},
+ {5955,315,3,1,0,0,0,0,0},
+ {5955,285,1,1,156,0,123,0,0},
+ {5955,255,1,0,255,0,170,0,0},
+ {9675,315,3,0,0,0,0,0,0},
+ {9675,285,1,1,0,0,0,0,500},
+ {9675,255,1,0,0,0,0,0,500},
+ {12285,345,1,0,0,117,134,0,4000},
+ {12285,315,1,1,0,58,59,0,4000},
+ {13305,405,1,0,3,193,255,0,0},
+ {13305,375,1,1,0,124,176,0,0},
+ {20655,255,1,0,11,63,124,0,5000},
+ {20655,225,1,1,14,111,176,0,5000},
+ {22485,105,2,1,0,0,0,0,0},
+ {23715,345,1,0,0,238,48,0,2000},
+ {23715,315,1,1,7,171,8,0,2000},
+ {23835,255,2,0,0,0,0,0,0},
+ {24195,315,2,5,0,0,0,0,0},
+ {26745,135,2,1,0,0,0,0,0},
+};
+static const uint8_t level3_data[1823] = {
+ 189,89,61,108,92,69,16,158,125,239,254,8,199,243,197,119,62,251,34,251,2,129,68,138,148,19,13,20,96,160,70,88,52,80,197,136,130,46,23,20,
+ 164,32,33,25,210,231,136,82,80,17,137,142,2,211,165,179,148,130,242,74,186,72,17,21,82,44,170,20,72,145,160,142,217,253,230,253,204,254,189,187,
+ 203,15,133,71,227,217,217,153,217,153,217,121,51,123,155,201,26,101,52,38,3,191,162,215,52,36,74,169,73,143,169,162,27,216,212,48,161,211,57,36,
+ 122,133,54,75,202,68,175,146,230,105,105,200,171,31,81,223,226,95,215,255,111,80,87,80,88,230,125,200,223,215,18,178,148,104,79,195,177,134,74,75,
+ 152,0,222,160,17,29,128,231,177,176,237,166,192,89,90,15,210,136,206,211,128,58,66,203,16,118,118,114,220,183,214,216,185,79,83,104,159,65,251,20,
+ 122,103,128,247,74,237,190,31,6,144,124,42,151,185,7,153,19,200,148,126,184,82,250,161,71,109,218,210,50,170,179,19,29,10,189,135,66,239,3,173,
+ 151,28,189,25,29,9,252,64,159,212,120,160,173,117,141,233,109,122,41,215,56,246,32,193,243,5,254,41,56,141,87,37,101,156,211,171,200,74,158,177,
+ 182,201,156,232,51,216,252,62,240,179,128,223,194,6,169,203,156,177,240,252,158,240,51,123,230,11,47,58,85,44,58,158,229,45,68,147,224,171,45,231,
+ 68,195,28,207,34,49,101,47,93,16,208,80,82,134,141,59,43,228,118,149,93,89,208,183,149,37,159,35,106,38,111,123,129,88,152,40,80,206,185,87,
+ 230,118,207,185,17,58,29,232,146,230,237,34,43,56,67,214,53,61,1,69,33,103,138,12,97,250,88,64,163,61,179,40,246,234,79,176,80,223,178,14,
+ 33,207,227,156,245,114,42,9,44,179,90,77,21,219,31,243,82,113,198,18,111,248,121,219,209,218,7,233,80,236,53,246,52,211,66,154,206,165,18,159,
+ 194,146,234,182,22,171,242,14,74,158,9,236,172,223,91,104,105,42,147,159,3,213,137,220,38,121,34,225,129,6,123,96,159,118,17,193,203,184,221,187,
+ 208,114,25,240,150,214,181,143,220,187,41,242,240,106,142,251,153,44,117,93,119,110,186,109,207,93,111,85,102,242,35,113,199,159,148,146,237,232,48,133,
+ 229,60,16,85,226,46,170,196,93,33,225,129,168,15,210,146,71,145,90,116,94,85,123,223,85,253,192,45,179,97,91,240,203,51,202,83,92,86,198,159,
+ 187,202,196,241,150,170,236,249,93,240,152,138,100,120,12,231,14,56,191,84,174,229,59,88,61,65,62,124,172,70,129,243,198,163,47,117,61,164,190,85,
+ 3,99,222,91,36,141,229,112,173,80,218,79,68,23,117,21,235,5,234,121,88,242,54,118,37,57,207,134,136,175,107,173,159,57,172,49,164,235,7,232,
+ 114,241,109,122,89,255,145,165,209,205,168,98,215,117,33,193,255,42,205,225,255,99,220,145,211,106,20,248,166,80,254,165,155,129,179,170,132,133,150,75,
+ 240,27,127,91,221,219,253,94,94,175,184,118,153,170,245,68,29,227,150,205,1,119,233,117,72,110,66,114,11,249,96,238,245,9,106,194,11,130,202,166,
+ 204,240,61,101,59,223,161,81,199,216,214,132,79,216,158,101,37,47,41,71,197,96,71,115,102,157,97,29,79,74,224,241,112,101,240,102,73,255,155,78,
+ 91,56,209,159,52,116,86,127,165,126,105,97,33,161,69,181,90,44,124,25,24,218,123,92,106,244,121,90,192,183,128,119,129,175,71,37,207,225,109,206,
+ 198,111,180,183,151,177,97,21,59,151,241,234,95,180,25,92,101,175,50,143,244,170,161,156,194,174,65,84,230,85,196,69,222,8,190,41,174,156,186,88,
+ 111,68,87,123,84,220,190,102,39,91,74,218,211,121,128,181,48,207,252,169,36,240,234,247,240,198,33,188,177,170,31,92,201,61,64,62,117,15,231,202,
+ 68,14,36,186,58,153,206,225,134,134,219,37,133,59,70,174,96,163,206,246,11,204,153,202,87,245,103,36,253,45,222,114,40,225,108,225,92,138,201,25,
+ 32,79,78,69,86,179,220,99,134,146,225,68,189,149,111,16,159,133,235,140,95,97,150,241,12,211,11,153,77,139,226,239,93,7,222,5,125,96,105,55,
+ 122,113,82,53,128,109,140,15,129,119,114,219,38,232,144,117,63,169,207,123,157,206,105,126,179,218,170,86,27,88,69,213,106,170,226,140,107,152,139,221,
+ 126,242,200,155,116,66,253,57,119,98,139,103,88,187,183,153,229,223,217,22,114,178,229,236,253,165,156,194,124,248,47,224,25,97,213,57,204,254,248,106,
+ 151,47,0,213,124,241,161,216,251,48,122,34,87,203,190,182,115,91,227,45,253,95,8,78,244,20,75,145,213,131,72,55,94,200,12,159,171,152,205,93,
+ 105,4,93,97,27,10,249,161,85,55,34,159,208,53,120,233,54,188,116,27,254,185,6,248,155,246,210,91,208,222,211,113,185,16,180,127,150,123,213,244,
+ 63,247,68,215,180,120,34,179,59,58,215,39,49,254,110,254,134,163,35,171,103,213,106,53,19,18,122,129,189,254,60,238,119,212,210,111,117,147,59,229,
+ 62,188,2,59,43,79,218,243,102,145,111,89,249,70,84,204,233,182,255,123,81,159,24,120,70,119,197,231,169,225,237,202,84,113,163,83,220,83,221,80,
+ 224,22,31,232,155,155,162,78,166,232,70,140,231,53,222,189,175,45,73,97,185,161,79,65,215,120,247,72,207,41,41,247,165,154,174,241,6,240,238,62,
+ 73,249,69,125,48,252,97,249,7,70,26,44,52,244,61,208,39,160,135,229,31,233,122,158,34,127,12,253,16,252,51,216,89,188,212,85,183,158,187,247,
+ 19,224,59,170,85,250,234,162,50,85,52,140,19,141,212,134,67,145,211,65,136,127,232,241,155,88,76,203,87,68,178,246,150,254,108,81,222,27,79,40,
+ 75,40,96,67,233,237,102,156,179,168,150,153,66,206,40,90,242,140,195,21,206,232,251,71,230,91,136,255,24,167,158,59,103,47,222,79,88,123,153,15,
+ 41,166,93,126,129,76,200,145,99,222,112,52,79,82,199,147,129,199,62,59,229,111,92,103,213,230,74,126,168,238,236,42,126,88,24,235,52,22,65,240,
+ 40,240,36,117,249,48,4,103,6,206,120,148,253,184,44,242,128,123,94,63,255,199,75,120,181,136,245,33,190,5,54,61,69,212,114,15,36,232,16,104,
+ 28,201,10,240,43,240,39,113,126,142,181,214,165,108,250,137,254,214,60,251,233,150,203,22,25,113,223,243,177,184,75,153,177,184,23,89,17,138,117,188,
+ 218,44,147,177,28,187,58,15,248,153,163,180,13,125,244,153,253,116,167,172,213,73,202,61,161,161,243,253,53,248,142,50,112,23,117,123,138,168,237,225,
+ 133,246,152,18,68,167,141,189,109,212,231,54,106,114,27,175,97,201,202,252,255,23,231,154,224,175,231,228,85,201,95,207,41,109,96,15,204,209,57,63,
+ 47,254,167,183,228,69,201,76,49,29,112,37,79,20,178,69,33,91,52,252,145,222,192,174,70,131,119,237,152,124,67,254,247,149,194,59,57,211,199,14,
+ 94,77,31,118,207,150,74,188,177,202,148,113,136,142,116,142,206,225,31,188,195,203,158,208,238,96,237,119,63,242,126,79,244,223,253,228,239,119,119,44,
+ 105,44,161,248,221,45,235,132,186,77,150,201,116,243,107,212,243,62,145,107,195,157,124,106,11,255,10,176,14,141,93,207,54,251,87,51,83,157,182,106,
+ 127,23,27,71,124,194,18,186,70,75,163,232,216,167,88,245,231,59,247,181,150,172,142,218,248,112,152,219,188,216,63,93,207,171,235,1,251,63,88,56,
+ 121,125,109,77,61,50,91,88,194,31,214,212,19,202,150,239,132,180,43,2,255,89,76,172,103,22,76,211,177,89,169,46,123,237,239,166,123,155,236,183,
+ 116,255,119,85,119,78,183,101,214,207,233,199,176,234,4,86,189,169,70,193,105,46,156,3,227,218,89,137,237,233,121,115,220,86,128,211,124,137,90,214,
+ 239,194,242,151,181,87,241,251,2,255,190,54,193,87,187,30,95,203,39,154,140,254,3,
+};
+static const LevelEvent level3_events[42] = {
+ {15,165,1,0,114,0,6,0,10000},
+ {2415,195,1,0,0,21,114,0,10000},
+ {2415,165,1,1,0,42,149,0,10000},
+ {3945,165,2,1,0,0,0,0,0},
+ {8235,255,1,0,0,0,0,0,1000},
+ {8235,225,1,1,0,0,0,0,1000},
+ {8565,135,1,0,20,70,0,0,500},
+ {8565,105,1,1,5,31,0,0,500},
+ {8655,135,2,5,0,0,0,0,0},
+ {8775,405,1,0,104,255,36,0,500},
+ {8775,375,1,1,40,162,0,0,500},
+ {9255,405,1,0,0,246,176,0,500},
+ {9255,375,1,1,0,155,114,0,500},
+ {9795,405,1,0,107,255,0,0,500},
+ {9795,375,1,1,66,159,0,0,500},
+ {10215,405,1,0,0,253,150,0,500},
+ {10215,375,1,1,0,147,89,0,500},
+ {10845,405,1,0,0,255,12,0,500},
+ {10845,375,1,1,9,139,0,0,500},
+ {11325,405,1,0,135,255,1,0,500},
+ {11325,375,1,1,72,138,0,0,500},
+ {11835,405,1,0,1,255,164,0,500},
+ {11835,375,1,1,0,143,101,0,500},
+ {12375,405,1,0,0,250,36,0,500},
+ {12375,375,1,1,0,159,16,0,500},
+ {12945,405,1,0,255,0,47,0,500},
+ {12945,375,1,1,177,0,38,0,500},
+ {12945,345,2,1,0,0,0,0,0},
+ {16845,345,2,5,0,0,0,0,0},
+ {16995,405,1,0,25,255,0,0,1000},
+ {16995,375,1,1,0,0,0,0,1000},
+ {17535,375,1,0,6,255,153,0,1000},
+ {18045,375,1,0,8,255,0,0,1000},
+ {18555,375,1,0,1,255,122,0,1000},
+ {19065,375,1,0,163,251,0,0,1000},
+ {19605,375,1,0,0,255,106,0,1000},
+ {20115,375,1,0,15,255,17,0,1000},
+ {20625,375,1,0,139,255,0,0,1000},
+ {21225,375,1,0,248,0,165,0,300},
+ {21225,345,1,1,180,0,119,0,300},
+ {23805,195,1,0,154,0,254,0,5000},
+ {23805,165,1,1,95,0,151,0,5000},
+};
+static const uint8_t level4_data[2332] = {
+ 213,27,59,108,28,69,244,205,238,249,178,54,102,239,98,159,207,118,192,23,41,193,145,144,98,165,64,46,80,34,81,164,130,83,10,228,42,66,20,116,
+ 89,62,133,133,80,16,20,116,28,84,167,20,124,82,68,8,137,19,5,114,7,164,0,41,34,7,85,58,36,10,10,36,174,76,5,18,37,197,49,243,
+ 222,206,238,155,223,222,222,57,144,32,75,227,209,123,111,222,111,222,188,121,59,51,247,124,212,130,20,254,4,213,246,176,189,134,237,147,216,190,206,224,
+ 170,21,121,11,112,30,214,225,18,244,33,141,1,50,217,246,100,95,193,51,108,111,194,118,206,167,7,123,32,73,100,63,146,255,6,144,38,0,99,236,
+ 143,32,150,237,68,98,21,77,132,52,39,64,193,35,164,81,125,162,159,72,108,61,26,194,18,37,193,57,101,125,26,46,235,120,52,113,67,209,52,26,
+ 85,250,40,62,99,102,151,105,81,29,108,36,208,159,81,137,141,27,132,45,253,223,48,116,182,251,164,167,226,211,199,217,143,224,36,172,97,219,132,199,
+ 97,19,182,176,111,206,102,253,121,172,158,193,227,99,73,115,169,155,108,47,67,199,242,9,121,67,233,31,201,49,91,185,117,61,214,130,140,214,117,217,
+ 30,192,114,14,73,144,178,155,99,247,17,174,90,112,198,106,14,135,136,125,31,249,76,112,21,156,20,219,168,73,154,104,154,117,216,40,232,15,144,126,
+ 140,148,127,193,54,218,85,82,150,154,104,136,154,133,144,68,31,124,128,171,207,213,115,93,90,197,249,135,250,26,162,252,192,33,17,188,5,167,13,31,
+ 94,146,178,98,92,251,42,30,250,216,238,97,75,113,242,169,164,214,235,46,195,182,159,175,65,90,59,17,180,149,237,242,143,99,91,15,145,166,231,209,
+ 179,197,176,3,140,198,62,179,168,164,209,216,204,225,220,119,176,46,255,17,206,218,128,69,59,167,201,28,26,151,67,54,83,138,194,170,149,146,229,235,
+ 93,101,39,142,237,51,233,90,110,186,48,156,115,214,22,197,184,90,27,13,158,141,235,246,203,149,254,130,19,249,124,141,244,49,38,121,28,106,120,100,
+ 121,140,198,142,242,189,73,175,199,94,161,167,146,72,114,221,213,100,175,142,84,142,90,66,254,77,228,223,204,115,75,59,176,18,171,181,77,243,177,179,
+ 53,9,101,24,51,219,188,139,118,185,216,17,90,77,123,199,47,140,198,134,115,157,33,207,135,47,23,244,225,76,101,75,15,209,235,220,117,211,75,233,
+ 250,124,30,27,93,173,134,12,75,89,113,136,28,110,51,14,67,43,31,106,184,202,174,164,173,134,124,35,179,162,214,95,205,2,207,192,46,125,88,147,
+ 82,7,211,219,156,102,156,239,242,122,151,209,112,130,16,150,195,253,57,63,228,43,189,3,102,208,193,124,222,193,124,222,137,187,18,82,70,169,206,156,
+ 113,172,51,91,198,86,150,198,70,137,9,39,63,112,172,153,223,162,130,134,143,53,51,24,193,99,204,93,106,45,188,35,247,23,212,36,210,52,123,168,
+ 143,187,235,237,193,57,217,174,32,189,144,255,67,49,102,142,218,68,95,61,199,124,181,201,60,105,247,57,101,120,109,238,7,34,65,69,169,174,162,253,
+ 181,129,187,178,56,127,223,14,30,90,221,180,126,67,88,210,36,164,103,149,134,220,82,83,79,226,201,225,251,142,182,3,252,166,24,97,219,194,170,210,
+ 180,66,181,148,139,90,69,93,183,130,156,59,140,207,42,102,137,181,124,236,30,230,100,149,141,103,101,42,202,216,148,189,41,147,95,43,118,153,6,242,
+ 60,229,201,243,89,30,177,77,153,171,69,193,109,11,222,144,57,161,25,148,213,103,178,90,57,159,152,121,184,41,202,190,170,207,109,250,240,110,50,64,
+ 221,10,62,94,89,95,20,118,181,81,183,180,148,5,110,21,103,107,18,25,251,145,189,3,186,118,45,229,235,154,239,131,36,183,41,225,167,101,182,113,
+ 99,204,229,163,235,204,38,139,150,210,75,3,212,205,111,175,29,189,139,218,200,125,101,122,59,228,231,170,253,174,39,163,154,60,211,156,193,1,224,46,
+ 171,118,234,75,36,207,215,209,74,199,124,108,120,12,199,198,14,77,163,156,217,52,152,235,86,225,37,57,179,107,193,28,219,199,29,211,159,49,220,189,
+ 62,101,245,70,155,65,218,140,131,75,19,202,234,171,112,165,208,45,181,78,57,228,215,65,196,33,155,78,14,60,40,190,4,125,185,142,230,119,232,253,
+ 90,212,244,247,188,216,21,185,131,171,76,162,176,29,135,127,27,225,169,177,71,31,73,72,151,81,114,136,107,123,130,28,186,158,140,17,218,167,142,216,
+ 254,66,125,218,19,185,165,84,117,236,8,81,192,175,224,151,239,61,232,36,33,254,156,179,110,93,62,36,107,17,110,186,94,226,218,134,106,57,191,189,
+ 110,101,24,170,9,125,49,112,100,213,150,97,205,239,5,181,82,114,79,8,27,75,163,136,230,178,176,53,217,21,203,86,191,244,128,166,188,138,30,254,
+ 136,249,249,39,244,240,101,97,122,88,107,120,130,241,116,245,225,218,222,199,168,254,16,185,145,148,139,34,181,120,82,228,239,8,85,111,92,68,154,215,
+ 140,74,181,202,39,92,19,219,63,110,31,224,9,145,122,103,89,249,173,153,123,128,108,191,46,245,217,114,188,170,251,87,69,106,248,92,87,146,123,112,
+ 54,14,205,50,249,31,224,25,209,241,234,80,229,85,109,221,184,168,133,202,10,63,45,234,174,55,97,59,161,186,40,36,209,157,71,128,63,196,25,185,
+ 151,81,191,42,67,246,114,110,4,217,174,136,13,128,191,229,218,84,51,174,230,244,58,122,245,75,156,83,191,20,51,90,126,195,177,110,204,220,15,228,
+ 79,138,159,59,56,202,141,34,190,58,252,81,228,206,151,155,229,0,62,11,240,39,154,111,241,11,130,176,68,175,104,76,207,208,168,29,81,86,197,37,
+ 36,197,81,109,7,78,82,82,166,67,219,51,150,164,251,57,212,215,1,101,53,76,219,57,182,212,193,135,45,117,232,5,117,176,237,50,103,63,67,254,
+ 55,216,23,71,198,184,85,245,205,81,138,91,2,159,195,110,112,215,115,107,239,106,184,219,46,203,74,160,133,181,98,11,191,118,91,120,226,173,218,41,
+ 182,59,162,21,111,24,245,85,159,85,224,59,66,65,166,8,159,192,82,225,159,167,197,201,96,95,173,184,13,11,194,179,71,213,216,48,79,126,210,226,
+ 151,194,251,203,185,117,25,179,90,121,96,35,183,136,44,157,74,139,192,224,201,171,77,85,127,46,106,175,173,237,252,246,110,139,238,130,60,151,101,94,
+ 109,225,29,135,158,235,13,105,239,82,49,155,156,167,158,217,38,102,230,38,126,171,214,157,101,85,223,2,156,22,155,53,233,235,198,128,107,187,205,167,
+ 11,97,219,121,156,79,153,7,66,17,78,60,231,141,115,202,3,161,56,36,56,95,173,4,217,21,91,1,110,27,94,75,171,124,155,224,185,150,154,53,
+ 117,186,69,119,91,59,162,60,131,29,67,76,119,109,232,7,245,133,72,247,80,59,162,60,61,30,227,109,212,52,191,141,42,111,214,22,163,153,96,127,
+ 250,191,161,81,103,110,218,174,70,228,163,153,228,52,37,182,149,243,84,240,29,161,224,250,244,187,81,96,229,44,208,41,95,222,199,123,10,227,150,161,
+ 151,159,6,16,54,179,176,230,109,11,209,216,88,243,174,228,184,52,116,47,163,42,34,181,99,254,119,114,31,53,26,53,179,106,199,191,5,157,154,60,
+ 9,59,112,110,145,30,5,27,67,55,104,52,215,90,115,58,119,202,111,211,132,121,187,68,241,160,99,216,190,17,171,128,71,15,7,222,136,193,115,71,
+ 54,193,115,254,41,203,6,122,213,147,151,232,84,223,158,65,202,3,244,229,206,233,77,207,235,140,209,51,36,114,122,78,195,199,134,104,56,31,210,193,
+ 166,244,221,3,218,148,189,160,69,213,52,83,70,121,28,62,174,230,116,179,243,10,174,44,174,191,235,91,242,3,167,113,185,133,110,123,31,148,31,92,
+ 137,89,126,186,165,226,161,154,178,159,191,250,152,61,143,117,104,38,236,110,136,83,82,75,154,79,113,253,42,221,186,146,190,243,88,226,68,200,10,108,
+ 138,115,210,247,110,228,208,41,40,95,5,124,77,133,224,253,252,142,62,173,128,243,253,142,114,14,127,107,97,174,163,134,245,114,192,206,93,62,172,187,
+ 87,250,177,0,95,193,218,49,57,208,141,195,113,56,240,61,37,156,189,249,219,134,200,186,55,167,175,21,170,84,199,240,148,172,64,167,208,17,202,171,
+ 29,145,176,115,221,94,160,31,62,169,182,111,177,103,157,16,242,19,69,251,21,129,123,70,209,134,79,224,108,113,71,51,197,243,159,11,248,77,61,197,
+ 243,159,217,109,152,126,130,89,197,237,251,219,4,105,186,53,56,227,105,85,162,251,191,194,242,204,254,5,60,5,226,163,170,250,0,223,177,177,245,71,
+ 221,90,104,212,123,114,20,192,171,176,62,247,216,250,210,93,139,234,219,88,71,67,87,250,195,245,70,138,214,181,255,53,8,221,74,183,107,104,210,69,
+ 250,100,6,100,84,204,72,226,240,153,181,250,76,137,229,237,57,189,118,160,251,244,103,97,59,169,191,162,31,44,231,197,109,177,165,255,56,87,84,84,
+ 73,81,95,223,38,183,136,245,227,213,121,101,149,167,52,75,115,141,26,179,19,158,17,238,32,31,204,41,119,196,78,135,38,249,93,246,146,181,166,250,
+ 112,6,142,179,154,62,102,239,180,213,174,167,218,23,113,215,14,237,44,124,95,187,198,222,3,236,23,247,140,188,111,238,101,135,108,44,189,215,58,100,
+ 59,166,139,229,58,28,49,44,189,9,185,235,188,229,163,253,113,88,241,230,150,243,49,251,161,123,183,123,142,220,223,153,220,35,71,214,144,209,211,171,
+ 48,174,143,191,175,253,51,204,95,215,164,51,232,195,124,84,85,144,34,135,118,45,250,219,204,207,135,129,138,229,192,177,113,159,81,210,91,190,125,75,
+ 7,243,229,179,191,175,235,31,130,244,153,213,33,122,247,221,160,61,95,237,156,94,189,243,76,13,248,38,198,100,134,171,134,94,4,41,219,191,46,126,
+ 113,32,176,62,164,223,35,204,79,243,51,210,168,251,53,5,191,129,240,31,80,91,63,252,251,0,252,148,3,63,21,160,124,123,78,137,231,197,46,157,
+ 53,33,228,16,177,67,236,223,145,216,127,0,
+};
+static const LevelEvent level4_events[20] = {
+ {2085,135,2,5,0,0,0,0,0},
+ {2085,105,1,1,144,0,183,0,500},
+ {2085,75,1,0,173,0,252,0,500},
+ {4245,315,2,1,0,0,0,0,0},
+ {4245,285,1,1,84,0,49,0,500},
+ {4245,255,1,0,198,0,89,0,500},
+ {8055,255,2,0,0,0,0,0,0},
+ {9015,345,2,1,0,0,0,0,0},
+ {9015,315,1,1,0,0,0,0,500},
+ {9015,285,1,0,0,0,0,0,500},
+ {13793,275,2,5,0,0,0,0,0},
+ {13793,245,1,0,93,0,77,0,500},
+ {13793,215,1,1,39,1,28,0,500},
+ {17985,555,3,1,0,0,0,0,0},
+ {17985,525,2,4,0,0,0,0,0},
+ {17985,495,1,1,54,88,0,0,500},
+ {17985,465,1,0,150,229,19,0,500},
+ {22155,435,1,0,243,18,222,0,500},
+ {22155,405,1,1,110,16,100,0,500},
+ {22155,375,3,0,0,0,0,0,0},
+};
+static const uint8_t level5_data[2049] = {
+ 181,90,77,136,28,69,20,126,213,189,211,233,196,221,217,117,55,78,220,184,219,227,79,146,75,28,188,152,83,80,144,120,137,141,7,141,40,17,61,136,
+ 96,28,20,68,65,66,240,224,45,163,32,228,32,73,60,40,158,6,79,123,90,65,188,58,136,135,156,22,21,15,162,48,228,148,139,139,136,39,145,177,
+ 234,171,174,238,87,85,93,189,61,217,245,82,84,191,122,255,239,213,171,191,62,45,150,169,75,25,13,168,67,68,203,148,200,246,25,90,147,144,136,238,
+ 165,21,180,186,79,18,122,95,209,55,144,51,116,216,129,28,43,33,118,127,141,122,14,230,5,57,74,244,14,173,150,144,37,73,193,113,12,252,221,90,
+ 62,68,99,234,166,68,19,18,178,255,23,173,23,60,109,218,17,112,198,192,249,25,56,3,138,97,105,20,27,28,9,17,128,136,44,96,175,214,129,232,
+ 117,58,26,213,105,184,133,209,47,157,81,155,195,29,224,252,234,225,220,2,124,83,40,61,207,10,165,231,91,98,221,26,205,104,42,99,68,22,164,222,
+ 99,68,215,156,81,14,49,173,43,203,231,156,209,12,126,219,4,206,179,12,231,16,221,95,216,107,48,167,192,156,193,195,143,49,204,107,176,139,199,125,
+ 2,204,41,48,239,101,152,67,68,36,151,17,81,177,80,45,143,142,28,93,192,168,192,104,17,41,162,171,101,150,218,237,136,250,37,103,55,99,195,126,
+ 203,161,131,47,61,135,244,74,110,37,197,205,171,106,70,216,114,135,192,28,1,243,27,96,46,203,185,118,131,252,121,247,156,156,11,27,128,251,237,211,
+ 146,219,134,196,79,228,151,223,246,36,159,62,165,129,209,72,234,208,151,212,26,178,12,77,6,104,115,217,102,178,237,194,183,93,216,216,21,159,43,72,
+ 172,60,175,90,105,105,156,1,83,65,4,113,91,94,40,172,176,91,101,209,163,181,209,209,158,49,115,255,205,0,142,202,177,240,220,247,103,125,85,79,
+ 246,138,78,221,220,143,0,57,164,253,192,49,23,234,106,66,149,57,92,98,15,118,165,150,45,57,252,48,64,100,117,124,53,149,178,250,70,233,255,46,
+ 189,92,102,66,92,98,94,129,254,63,64,243,155,136,145,209,42,17,174,158,29,17,170,87,126,189,181,43,195,5,175,50,240,153,251,35,116,248,19,122,
+ 62,196,42,146,174,39,99,166,67,125,157,49,113,28,151,243,49,219,99,53,185,229,233,243,153,204,90,242,42,91,120,189,152,58,178,52,206,34,106,194,
+ 106,1,31,0,231,172,80,185,189,137,118,134,60,55,117,79,144,169,123,110,133,228,213,190,206,138,179,168,171,23,65,245,49,171,111,119,152,230,154,167,
+ 174,192,245,181,215,240,12,85,96,46,125,43,16,65,53,83,108,185,188,157,5,35,226,174,209,135,196,225,57,172,179,35,50,241,98,81,205,107,95,110,
+ 151,126,66,172,149,31,86,106,116,214,237,101,232,112,29,58,124,207,116,208,85,229,36,211,246,43,140,94,6,230,69,80,249,22,113,90,189,58,187,54,
+ 102,150,141,51,150,243,119,188,108,172,164,251,158,52,240,115,34,28,47,211,127,205,211,240,58,180,218,134,86,183,153,86,74,34,97,133,32,90,144,190,
+ 151,235,47,157,114,70,93,143,249,218,218,178,148,244,30,61,14,110,79,74,206,105,112,182,62,17,41,15,127,1,41,75,106,121,164,93,41,203,198,217,
+ 129,244,93,72,239,3,255,67,97,231,121,143,158,135,172,87,152,172,109,80,237,128,74,128,42,228,147,115,144,126,27,177,86,254,201,10,136,198,212,125,
+ 25,253,50,106,99,234,196,118,220,199,168,168,102,84,245,37,142,160,114,29,233,196,172,95,194,135,37,220,196,110,200,70,115,70,149,83,194,250,122,47,
+ 97,86,132,172,118,245,236,22,235,108,120,116,84,59,106,214,196,106,39,214,158,214,140,142,3,156,181,69,51,172,104,83,234,164,156,63,193,70,134,41,
+ 66,114,249,170,93,47,69,28,176,79,178,98,15,80,79,149,21,250,248,112,237,67,94,255,15,150,150,107,229,247,39,176,40,164,243,40,32,215,141,62,
+ 205,65,203,169,38,136,181,225,217,17,97,77,166,1,110,122,205,170,195,175,56,79,27,57,135,60,60,102,28,198,141,28,124,75,135,140,118,216,66,122,
+ 238,113,24,48,14,131,70,14,121,192,51,238,44,160,90,90,190,111,236,164,97,13,7,141,185,157,55,142,14,3,163,131,66,195,142,174,150,105,88,79,
+ 206,135,239,180,219,235,185,31,90,27,167,31,196,33,156,125,234,51,164,223,192,121,220,56,58,106,180,232,160,168,180,103,248,121,185,142,182,109,86,143,
+ 26,117,107,182,119,210,56,106,235,179,23,102,23,56,43,193,120,229,88,163,67,171,73,187,25,116,55,153,223,198,75,110,219,43,242,83,239,148,20,228,
+ 61,233,201,147,56,105,39,229,121,115,70,49,118,242,29,228,106,34,20,68,173,152,255,119,127,134,189,135,185,217,136,35,156,232,81,237,21,78,142,118,
+ 88,216,146,104,61,23,181,158,100,237,85,52,142,178,137,232,148,88,78,15,174,175,229,170,62,177,186,183,63,158,211,194,150,68,215,49,201,89,143,110,
+ 138,253,113,222,176,206,242,74,219,232,128,189,81,245,213,172,87,103,210,9,238,94,108,120,167,176,43,76,59,195,41,96,94,233,202,63,216,227,165,196,
+ 110,165,108,28,205,95,223,35,221,125,223,220,44,229,176,142,195,115,72,151,117,172,37,207,131,247,188,144,182,175,197,202,207,107,241,166,51,139,19,84,
+ 227,56,166,194,87,234,62,19,51,14,248,73,108,67,102,160,146,248,29,6,215,115,83,120,253,216,244,245,220,28,176,126,57,127,239,9,207,223,18,19,
+ 115,54,142,109,248,192,227,92,91,49,24,92,221,135,107,75,185,230,83,180,54,68,89,167,45,117,108,244,107,81,173,38,166,175,170,147,182,180,217,70,
+ 109,93,14,13,125,27,27,60,188,31,27,163,128,141,98,111,187,106,226,232,215,225,216,139,163,104,23,199,121,251,151,69,140,19,113,130,19,74,82,158,
+ 230,76,237,213,150,170,195,188,202,240,132,110,210,9,90,149,237,35,178,191,35,162,84,221,39,40,110,219,56,233,235,190,134,207,5,137,91,64,196,193,
+ 64,212,142,232,98,113,159,80,193,247,238,31,161,167,68,159,142,182,192,236,21,103,189,169,57,131,75,248,167,180,158,166,115,226,132,248,31,151,250,247,
+ 105,97,78,253,137,206,64,226,9,177,209,18,95,175,251,166,202,53,97,78,176,163,174,31,77,233,111,228,210,47,200,171,111,73,217,94,143,217,197,206,
+ 118,37,56,58,107,28,85,103,204,149,22,16,220,238,166,43,65,15,152,187,38,149,249,187,66,101,254,82,164,218,211,104,207,163,189,20,45,68,230,140,
+ 124,62,82,248,151,162,40,82,124,78,145,238,107,120,86,192,39,236,149,228,37,25,101,162,23,163,141,146,170,106,57,149,238,47,66,202,42,253,46,20,
+ 254,82,164,98,113,26,237,174,80,254,60,31,37,206,205,48,231,83,218,18,195,150,24,182,196,176,37,134,45,49,108,137,87,233,3,228,225,171,197,75,
+ 208,122,186,0,157,237,140,117,33,68,111,64,43,117,167,218,43,108,84,111,49,161,28,94,44,60,160,119,227,15,72,41,171,193,140,210,190,253,131,178,
+ 212,220,42,112,204,253,64,244,155,99,40,250,227,226,85,171,107,233,73,119,137,211,6,50,162,182,181,72,159,79,183,203,218,149,181,164,114,229,134,124,
+ 62,96,123,48,27,94,69,237,223,153,138,154,154,239,139,173,164,143,27,165,79,26,71,219,196,148,191,32,183,209,167,25,115,214,56,170,231,215,188,16,
+ 62,55,155,181,210,190,122,223,203,165,230,74,85,113,118,171,183,32,31,162,171,95,56,7,166,36,168,221,234,48,118,230,178,217,153,112,156,33,187,197,
+ 109,3,215,175,117,243,82,229,229,124,156,87,195,187,243,131,174,78,77,235,102,157,231,219,196,66,85,167,135,169,105,134,86,167,48,14,87,175,9,71,
+ 240,214,118,212,131,187,62,212,103,249,164,230,37,58,171,161,245,223,122,70,224,48,44,206,188,73,237,139,182,190,55,158,21,183,85,230,13,200,126,213,
+ 210,247,87,85,77,206,188,63,46,220,87,146,234,79,143,74,183,69,88,93,189,228,118,138,187,23,219,174,242,191,11,162,192,43,124,22,124,143,214,127,
+ 38,132,113,122,181,56,103,74,136,253,10,239,254,135,144,225,159,40,67,123,204,225,195,239,196,190,179,238,154,52,127,183,175,255,31,224,247,81,87,209,
+ 126,212,234,142,116,80,188,50,116,10,200,170,228,166,234,188,79,235,254,235,101,247,245,59,154,59,106,116,115,223,226,205,159,84,183,224,147,45,248,231,
+ 31,90,111,248,87,161,233,191,5,243,39,201,144,201,242,179,116,132,76,219,129,172,93,200,237,35,27,135,229,27,156,194,73,68,213,239,136,5,252,225,
+ 112,220,243,70,74,87,164,151,122,129,251,192,175,209,126,130,246,56,107,223,70,251,96,241,63,143,250,55,70,233,22,131,42,42,99,113,13,26,110,65,
+ 195,223,164,79,34,133,179,240,31,
+};
+static const LevelEvent level5_events[13] = {
+ {3465,375,2,5,0,0,0,0,0},
+ {3555,345,1,0,225,0,117,0,500},
+ {3555,315,1,1,155,0,75,0,500},
+ {5745,465,1,0,255,0,55,0,4000},
+ {7035,675,1,0,0,0,0,0,200},
+ {7035,645,1,1,0,0,0,0,200},
+ {7125,255,2,1,0,0,0,0,0},
+ {14205,285,2,5,0,0,0,0,0},
+ {17595,375,2,2,0,0,0,0,0},
+ {21465,165,2,1,0,0,0,0,0},
+ {21555,135,1,0,238,0,82,0,500},
+ {21555,105,1,1,205,0,79,0,500},
+ {21945,135,1,0,240,0,82,0,10000},
+};
+static const uint8_t level6_data[2498] = {
+ 229,27,61,111,92,69,112,247,206,62,191,156,204,243,225,92,142,179,113,46,82,18,135,134,19,85,26,28,104,128,2,31,20,8,9,41,32,4,162,178,
+ 211,160,20,8,162,136,214,39,10,68,17,69,8,104,40,48,29,21,5,18,37,87,66,203,15,56,58,106,106,100,118,103,118,223,206,126,190,125,246,157,
+ 19,133,102,181,154,55,51,59,31,251,49,51,187,239,103,190,198,250,236,93,54,102,156,49,118,12,237,6,235,136,118,6,237,28,218,19,104,47,115,217,
+ 238,137,118,196,90,236,105,86,178,167,216,51,172,7,125,132,72,90,201,97,170,184,229,241,209,180,146,155,134,80,121,52,231,102,220,46,178,65,5,153,
+ 0,159,25,225,54,6,90,228,185,199,13,159,19,194,255,64,240,176,121,174,177,97,37,27,149,234,39,128,188,2,28,118,161,93,131,246,111,248,250,59,
+ 211,178,245,65,170,174,226,121,72,248,204,161,63,1,124,42,91,204,242,82,18,109,121,106,165,203,28,237,47,241,15,161,245,121,162,190,191,121,218,93,
+ 100,151,28,136,244,166,237,217,231,43,170,30,248,171,84,248,51,37,63,119,198,10,123,74,122,182,44,182,5,78,201,86,160,143,222,25,2,164,163,184,
+ 73,184,214,110,10,253,22,219,169,252,136,95,231,202,179,101,209,5,218,126,18,82,0,100,64,32,163,232,88,180,47,169,88,45,132,59,16,92,5,135,
+ 208,63,84,246,145,253,207,161,255,1,244,191,134,254,189,236,81,198,206,40,218,206,251,224,151,156,209,239,67,255,125,232,127,9,253,143,51,198,154,37,
+ 189,105,36,193,185,209,146,243,115,101,71,205,147,102,123,66,73,102,224,16,230,100,135,64,66,251,204,172,102,166,165,118,134,124,29,233,122,223,175,86,
+ 129,189,18,207,190,7,250,178,33,28,37,140,201,54,35,43,206,200,166,247,171,152,108,177,125,15,185,165,237,166,119,209,122,187,109,40,110,220,146,205,
+ 151,144,169,89,138,107,211,231,227,239,99,71,14,55,185,207,95,169,44,230,238,102,186,253,164,194,41,65,163,94,0,231,59,118,141,240,25,128,36,171,
+ 109,41,149,156,231,111,242,173,74,102,33,161,130,187,16,206,124,8,99,127,177,139,69,156,86,202,108,195,103,196,239,54,85,39,67,6,179,15,248,243,
+ 208,156,185,148,39,99,119,34,18,82,14,250,124,145,214,160,126,55,84,139,210,145,177,31,147,22,163,144,185,117,14,186,86,210,126,76,113,240,33,39,
+ 74,235,176,132,167,147,13,45,80,205,240,118,30,135,179,200,150,163,123,122,191,154,192,233,128,235,253,223,147,173,34,207,215,249,54,201,177,134,63,115,
+ 252,125,251,16,228,196,56,228,89,102,228,108,106,109,186,11,229,104,106,175,163,48,207,153,183,135,231,207,37,95,247,10,147,211,61,211,134,251,152,49,
+ 200,49,187,74,229,81,240,46,204,156,126,6,7,29,43,110,216,107,16,100,43,219,16,107,181,33,202,66,249,219,52,146,148,152,109,30,62,131,86,139,
+ 248,201,184,65,108,184,79,226,82,121,166,148,86,140,237,159,29,72,117,20,136,129,7,85,255,152,72,46,181,176,181,59,38,57,5,218,255,233,234,92,
+ 160,237,58,156,74,155,53,145,246,93,118,33,64,171,101,160,54,124,91,96,218,114,206,137,36,199,65,73,24,187,9,252,111,2,45,70,107,136,249,39,
+ 219,82,26,133,190,82,105,195,95,243,120,82,219,226,78,98,224,58,142,186,11,16,233,145,94,32,31,52,109,143,253,32,112,90,236,43,129,191,30,61,
+ 235,169,175,39,106,102,150,236,150,178,231,20,188,57,37,22,147,50,35,142,219,114,65,53,1,237,112,46,125,35,48,111,57,56,157,106,111,220,79,204,
+ 40,27,211,141,115,58,236,11,182,43,102,110,71,96,49,118,131,111,136,153,255,127,238,99,38,139,187,10,237,159,168,28,19,33,107,96,189,181,42,178,
+ 10,127,29,85,249,53,126,93,171,190,158,84,56,125,145,139,93,19,185,57,197,68,156,177,131,25,31,37,45,91,76,35,204,188,46,115,147,133,61,41,
+ 125,174,42,18,118,127,172,102,190,107,37,92,59,225,175,186,134,51,247,252,130,180,210,59,155,194,131,87,97,191,173,195,108,238,65,148,109,81,30,148,
+ 173,137,169,244,78,181,24,203,251,217,220,121,248,14,103,120,83,223,153,53,213,21,251,234,53,177,6,235,49,31,143,213,71,243,211,57,107,230,119,115,
+ 118,216,112,29,187,154,147,107,12,115,21,191,94,16,39,95,87,64,110,8,43,25,200,163,147,57,61,67,244,238,202,131,171,219,253,58,10,236,204,250,
+ 124,212,126,44,216,3,118,93,156,165,245,152,76,96,94,117,230,42,245,184,137,24,113,182,132,234,153,244,4,63,0,76,183,182,137,95,187,16,109,246,
+ 171,42,40,102,196,58,6,211,145,143,174,197,133,234,24,126,28,168,171,34,119,157,24,105,148,172,108,132,170,175,166,130,189,14,218,109,6,162,193,116,
+ 133,231,8,116,15,71,209,117,213,227,31,128,182,153,238,84,107,95,158,17,204,91,237,211,23,136,133,117,221,178,147,53,150,59,202,37,199,254,175,139,
+ 204,209,134,76,97,254,199,172,20,203,50,220,252,162,7,54,47,173,156,238,216,201,32,228,142,93,40,76,25,3,111,21,26,255,39,88,241,8,151,103,
+ 7,133,219,55,29,99,230,86,44,253,187,12,204,88,167,36,119,248,7,226,118,41,79,7,70,25,2,102,135,72,50,36,85,59,145,95,243,27,213,87,
+ 41,207,208,178,176,201,7,63,139,196,213,114,133,150,106,85,110,147,190,157,77,24,217,190,37,28,228,141,21,158,161,242,235,125,241,117,31,224,223,123,
+ 163,208,76,179,3,146,175,59,217,89,104,213,224,74,217,1,43,181,84,223,93,221,45,197,33,118,207,50,5,75,226,46,225,210,226,142,177,205,238,9,
+ 235,173,120,125,156,27,67,128,48,145,233,148,138,207,128,64,10,167,242,201,131,25,174,241,123,1,186,12,172,85,111,250,219,208,95,81,26,201,209,187,
+ 36,83,43,162,185,21,221,121,14,188,122,108,253,238,199,60,203,248,217,211,16,98,131,78,53,214,42,100,196,178,253,80,240,144,242,180,218,146,155,108,
+ 39,2,75,126,109,21,248,85,238,21,18,126,153,203,118,143,183,193,86,45,239,4,105,181,12,190,57,71,246,120,171,17,62,234,210,148,234,116,248,248,
+ 213,167,170,197,239,134,112,40,135,179,227,163,29,206,135,42,7,31,49,237,89,177,72,124,138,137,30,121,180,248,122,77,53,163,146,213,54,83,77,53,
+ 115,105,121,35,82,143,211,149,155,166,90,54,62,98,250,26,229,248,8,105,255,96,27,162,255,16,106,170,77,169,22,133,143,217,4,213,8,241,243,45,
+ 240,184,224,247,64,151,242,92,168,206,75,119,103,159,47,66,222,92,20,62,206,132,101,140,66,113,40,173,169,180,228,225,55,229,127,86,252,117,176,201,
+ 166,69,21,195,199,181,47,169,54,161,66,184,222,144,106,180,116,124,186,39,228,243,143,97,210,29,79,226,247,213,91,154,102,163,244,201,105,210,13,80,
+ 209,25,18,27,241,116,114,230,80,197,236,224,75,149,111,49,137,57,80,175,140,206,71,6,31,243,27,56,113,154,201,252,232,48,253,19,42,135,115,26,
+ 7,249,208,117,65,113,144,138,142,69,239,37,167,208,34,173,200,38,224,70,82,182,34,119,224,18,95,182,19,214,94,145,152,171,133,123,87,46,191,138,
+ 252,98,101,32,190,246,185,252,42,219,153,104,139,232,93,152,159,139,97,206,69,115,40,250,42,166,254,125,32,99,183,161,253,180,122,179,20,122,11,116,
+ 76,106,98,126,205,100,131,140,146,226,73,107,74,35,184,143,99,129,190,95,51,153,169,215,71,230,189,65,250,189,98,120,244,46,140,222,247,70,196,186,
+ 83,188,54,149,214,221,127,39,25,30,221,230,76,171,73,71,193,74,139,134,76,73,77,50,54,110,189,55,71,214,205,41,206,156,125,114,115,26,174,16,
+ 150,213,173,150,25,113,22,121,109,69,199,149,247,8,189,100,157,176,140,86,192,230,181,252,123,17,91,149,112,211,221,130,170,66,89,243,178,247,1,219,
+ 109,60,238,227,119,227,57,134,253,199,134,72,45,234,105,241,77,133,11,225,89,58,194,62,220,118,33,185,180,115,143,118,158,160,101,160,163,11,201,29,
+ 171,153,142,103,211,171,233,88,57,122,33,28,33,51,192,183,33,18,223,64,22,101,195,101,204,13,6,247,80,203,153,33,19,15,127,226,89,38,220,215,
+ 154,218,16,158,192,31,123,248,227,36,126,142,215,98,180,19,143,118,178,52,175,53,157,33,205,124,116,150,85,182,28,189,114,86,205,162,230,225,226,245,
+ 26,136,188,242,58,43,130,127,79,216,167,216,200,139,36,221,168,242,82,34,146,76,223,20,204,34,47,204,15,200,91,119,250,191,143,255,6,47,245,138,
+ 190,238,223,156,211,200,99,71,182,233,91,6,253,10,148,87,124,76,148,216,7,189,186,89,47,6,195,30,177,163,107,251,237,217,170,170,192,232,123,171,
+ 75,34,98,190,165,110,210,241,5,53,74,254,11,219,98,219,30,28,255,136,105,121,152,31,41,251,79,128,179,233,191,12,252,95,12,220,181,153,187,111,
+ 219,143,225,251,175,119,85,54,116,88,229,71,218,50,238,171,185,91,129,177,194,17,93,206,75,200,33,123,5,56,175,129,36,187,208,126,40,176,118,128,
+ 255,171,74,158,41,145,74,251,61,36,149,111,225,81,4,126,39,121,111,56,84,55,128,104,189,215,224,235,115,32,219,5,104,223,17,223,236,255,8,238,
+ 193,40,239,193,215,151,160,189,2,45,135,155,232,247,88,201,37,92,182,87,160,229,162,253,53,226,235,157,8,252,40,105,121,219,194,244,95,146,183,132,
+ 15,180,94,107,240,226,208,220,216,198,178,12,228,51,16,124,174,56,183,129,52,35,19,235,122,101,221,195,217,81,255,4,29,194,95,21,250,13,201,106,
+ 219,95,227,163,240,170,111,143,172,151,207,177,119,218,242,189,241,200,122,165,28,235,211,172,103,94,209,234,55,216,49,170,179,140,229,104,244,196,140,213,
+ 212,134,83,143,202,252,109,164,57,220,73,114,160,253,195,36,183,41,225,249,198,25,165,106,34,79,236,31,138,166,242,36,254,29,75,200,227,255,41,54,
+ 107,168,69,211,209,111,67,213,209,64,58,176,147,12,107,32,184,255,208,63,8,170,61,4,94,184,217,112,59,222,72,68,26,92,191,236,66,42,132,184,
+ 125,189,43,210,175,254,57,24,91,77,7,65,254,250,253,24,229,233,203,236,207,177,176,132,174,180,131,160,180,126,37,39,87,218,2,118,254,193,82,164,
+ 197,19,63,199,182,254,238,17,150,182,15,210,118,107,164,141,205,135,148,180,29,245,194,100,145,210,14,225,28,236,68,71,207,172,149,113,253,250,206,229,
+ 160,227,183,211,201,236,115,195,63,88,233,215,116,44,93,69,209,92,191,241,203,145,48,79,235,85,133,191,3,82,181,52,103,192,225,208,62,132,248,225,
+ 83,232,223,198,74,178,104,7,2,34,235,237,183,161,221,19,237,127,
+};
+static const LevelEvent level6_events[46] = {
+ {1485,315,1,0,254,0,212,0,5100},
+ {1485,285,1,1,209,6,197,0,4900},
+ {3195,285,2,5,0,0,0,0,0},
+ {3375,435,1,0,0,248,82,0,0},
+ {3375,405,1,1,7,176,74,0,0},
+ {4875,345,2,1,0,0,0,0,0},
+ {4935,375,1,0,255,7,208,0,0},
+ {4935,345,1,1,153,0,128,0,0},
+ {6615,255,2,5,0,0,0,0,0},
+ {6735,345,1,0,0,78,250,0,0},
+ {6735,315,1,1,0,0,0,0,500},
+ {7561,345,1,0,3,255,2,0,0},
+ {8403,345,1,0,0,99,255,0,0},
+ {9145,345,1,0,0,255,29,0,0},
+ {10065,345,2,1,0,0,0,0,0},
+ {10125,375,1,0,86,64,255,0,0},
+ {10125,345,1,1,53,5,236,0,0},
+ {11385,345,1,0,254,0,181,0,10000},
+ {11385,315,1,1,222,11,179,0,10000},
+ {13425,465,2,5,0,0,0,0,0},
+ {13455,465,3,0,0,0,0,0,0},
+ {13455,435,1,0,255,0,40,0,0},
+ {13455,405,1,1,0,0,0,0,0},
+ {15375,465,1,0,207,0,255,0,4000},
+ {15375,435,1,1,137,0,158,0,4000},
+ {15375,375,2,1,0,0,0,0,0},
+ {16725,465,2,4,0,0,0,0,0},
+ {16815,495,1,0,0,83,255,0,0},
+ {16815,465,1,1,0,0,0,0,0},
+ {16845,495,1,0,179,0,253,0,2000},
+ {17625,525,1,0,255,0,136,0,2000},
+ {18405,495,1,0,255,11,3,0,2000},
+ {19155,465,1,0,226,191,0,0,2000},
+ {19935,465,1,0,63,248,0,0,2000},
+ {20085,375,2,1,0,0,0,0,0},
+ {20655,465,1,0,0,255,215,0,2000},
+ {20805,345,2,5,0,0,0,0,0},
+ {21375,435,1,0,0,127,255,0,2000},
+ {22125,435,1,0,131,3,255,0,2000},
+ {22845,435,1,0,255,9,170,0,2000},
+ {23385,375,2,2,0,0,0,0,0},
+ {23565,435,1,0,253,72,0,0,2000},
+ {24315,435,1,0,118,250,0,0,2000},
+ {25035,435,1,0,0,239,182,0,2000},
+ {25125,405,2,1,0,0,0,0,0},
+ {25725,435,1,0,11,50,146,0,2100},
+};
+const LevelDef level_defs[LEVEL_COUNT] = {
+ {"STEREO MADNESS",level0_data,level0_events,2247,2272,19,26714,26700,0,{40,62,255},{0,19,200},{255,255,255},{255,255,255},1,1,160,0},
+ {"BACK ON TRACK",level1_data,level1_events,1486,1530,15,25335,25320,0,{255,4,181},{226,0,138},{255,255,255},{255,255,255},1,2,130,0},
+ {"POLARGEIST",level2_data,level2_events,1934,1509,22,27975,27960,0,{6,255,0},{7,163,0},{255,255,255},{255,255,255},2,3,165,0},
+ {"DRY OUT",level3_data,level3_events,1823,1402,42,25237,25230,0,{255,40,79},{255,0,51},{255,255,255},{255,255,255},2,4,140,0},
+ {"BASE AFTER BASE",level4_data,level4_events,2332,2126,20,25995,25980,0,{40,125,255},{0,102,255},{255,255,255},{255,255,255},3,5,142,0},
+ {"CAN'T LET GO",level5_data,level5_events,2049,1691,13,25037,25050,0,{213,0,238},{157,0,163},{255,255,255},{255,255,255},3,6,144,0},
+ {"JUMPER",level6_data,level6_events,2498,2767,46,26857,26850,0,{149,26,255},{112,0,200},{255,255,255},{255,255,255},4,7,175,0},
+};
diff --git a/games/numdash/src/main.c b/games/numdash/src/main.c
new file mode 100644
index 00000000..03f97742
--- /dev/null
+++ b/games/numdash/src/main.c
@@ -0,0 +1,57 @@
+/* Main loop: fixed 240 Hz physics, one rendered frame per loop iteration,
+ * drawn in horizontal strips straight to the LCD. */
+#include "app.h"
+#if PLATFORM_DEVICE
+#include <eadk.h>
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "NumDash";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+#endif
+
+int main(int argc, char **argv) {
+ (void)argc;
+ (void)argv;
+ if (!platform_init()) return 1;
+ app_init();
+ uint32_t prev = platform_millis(), acc = 0, fps_start = prev, frames = 0, pending = 0, render_ms = 30;
+ while (app.running) {
+ uint32_t now = platform_millis(), elapsed = now - prev;
+ prev = now;
+ /* never advance further than the player could have seen */
+ if (elapsed > 50) elapsed = 50;
+ acc += elapsed * ND_HZ;
+ uint32_t keys = platform_keys();
+ if (acc < 1000) {
+ pending |= keys;
+ } else {
+ keys |= pending;
+ pending = 0;
+ while (acc >= 1000 && app.running) {
+ app_tick(keys);
+ acc -= 1000;
+ }
+ }
+ if (!app.running) break;
+ app_frame(elapsed / 1000.0f);
+ /* Sync to the LCD refresh when a frame fits comfortably in it. */
+ platform_frame_begin(render_ms < 22);
+ uint32_t t0 = platform_millis();
+ for (int s = 0; s < STRIPS; s++) {
+ gfx_begin_strip(s);
+ app_draw();
+ platform_strip(s * STRIP_H, STRIP_H, gfx_strip);
+ }
+ platform_frame_end();
+ render_ms = (render_ms * 3 + (platform_millis() - t0)) / 4;
+ frames++;
+ if (now - fps_start >= 1000) {
+ app.fps = frames * 1000 / (now - fps_start);
+ frames = 0;
+ fps_start = now;
+ }
+#if !PLATFORM_DEVICE
+ if (elapsed < 8) platform_sleep(8 - elapsed);
+#endif
+ }
+ platform_close();
+ return 0;
+}
diff --git a/games/numdash/src/menu.c b/games/numdash/src/menu.c
new file mode 100644
index 00000000..99a19044
--- /dev/null
+++ b/games/numdash/src/menu.c
@@ -0,0 +1,422 @@
+/* Main menu (with the icon running across it), level select, icon kit and
+ * the settings / stats / how-to-play popups. */
+#include "app.h"
+#include "ui.h"
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* Colours the main menu cycles through and the level select page tints. */
+static const uint8_t page_colors[9][3] = {
+ {0, 0, 232}, {227, 0, 229}, {233, 0, 115}, {233, 0, 0}, {231, 112, 0}, {233, 232, 0}, {0, 231, 0}, {0, 227, 228}, {0, 112, 229}};
+static color_t page_color(int i) {
+ i %= 9;
+ if (i < 0) i += 9;
+ return rgb(page_colors[i][0], page_colors[i][1], page_colors[i][2]);
+}
+static int wrap(int v, int n) { v %= n; return v < 0 ? v + n : v; }
+
+enum { POP_NONE, POP_SETTINGS, POP_STATS, POP_HELP };
+static int popup, popup_sel, help_page;
+static float popup_t;
+
+/* ------------------------------------------------------------ main menu */
+
+static Level menu_level;
+static SceneOpts menu_opts;
+static color_t run_c1, run_c2;
+static bool run_hold;
+static int run_speed_roll;
+static unsigned run_tick;
+
+static void runner_reset(void) {
+ float gx = app.g.ground_x, bx = app.g.bg_x;
+ bool keep = app.g.L == &menu_level;
+ game_start(&app.g, &menu_level, true);
+ app.g.menu_camera = true;
+ app.g.cam_x = 0;
+ app.g.cam_y = 0;
+ if (keep) { app.g.ground_x = gx; app.g.bg_x = bx; }
+ Player *p = &app.g.p;
+ p->x = -120;
+ p->speed = (uint8_t)(frand() * 4) & 3;
+ if (frand() < 0.4f) p->mode = MODE_SHIP;
+ p->ceiling_y = 999999;
+ run_c1 = icon_color((int)(frand() * 42));
+ run_c2 = icon_color((int)(frand() * 42));
+ run_hold = frand() < 0.5f;
+ fx_reset();
+}
+
+static void runner_tick(void) {
+ Game *g = &app.g;
+ bool press = false;
+ if ((run_tick++ & 3) == 0) {
+ int r = (int)(frand() * 16);
+ if (g->p.mode == MODE_CUBE) run_speed_roll = r == 0 ? 4 : run_speed_roll;
+ else if (r == 0) run_hold = !run_hold;
+ }
+ if (g->p.mode == MODE_CUBE) {
+ press = run_speed_roll > 0;
+ if (run_speed_roll > 0) run_speed_roll--;
+ } else {
+ if (g->p.y >= 250) run_hold = false;
+ press = run_hold;
+ }
+ game_step(g, press);
+ if (g->p.x > VIEW_W + 90 || g->dead) runner_reset();
+}
+
+static void menu_colors(float dt) {
+ app.menu_color_t += dt / 4.0f;
+ if (app.menu_color_t >= 1) {
+ app.menu_color_t = 0;
+ app.menu_color = wrap(app.menu_color + 1, 9);
+ }
+ color_t c = c_mix(page_color(app.menu_color), page_color(app.menu_color + 1), (unsigned)(app.menu_color_t * 256));
+ uint8_t rgb3[3] = {(uint8_t)c_r(c), (uint8_t)c_g(c), (uint8_t)c_b(c)};
+ memcpy(app.g.ch[CH_BG].cur, rgb3, 3);
+ memcpy(app.g.ch[CH_G1].cur, rgb3, 3);
+ memset(app.g.ch[CH_LINE].cur, 255, 3);
+ memset(app.g.ch[CH_OBJ].cur, 255, 3);
+}
+
+static float btn_scale(int id) {
+ float s = 1;
+ if (app.sel == id) s = 1.1f + 0.025f * sinf(app.t * 5);
+ if (app.press_id == id) s = 1.1f + 0.16f * ui_ease_bounce_out(fminf(app.press_t / 0.12f, 1));
+ return s;
+}
+
+static void main_activate(int id) {
+ switch (id) {
+ case 0: app_go(SCR_GARAGE); break;
+ case 1: app_go(SCR_SELECT); break;
+ case 2: app_go(SCR_CREATOR); break;
+ case 3: popup = POP_HELP; help_page = 0; popup_t = 0; break;
+ case 4: popup = POP_SETTINGS; popup_sel = 0; popup_t = 0; break;
+ default: popup = POP_STATS; popup_t = 0; break;
+ }
+}
+
+static void main_draw(void) {
+ scene_draw();
+ gfx_layer_draw(160, 38, 256, rgb(215, 255, 100), rgb(70, 180, 10), 256);
+ gfx_text_center(FONT_SMALL, 160, 62, "NUMWORKS EDITION", rgb(255, 255, 255), rgb(200, 230, 255), 230);
+ ui_sprite(SPR_BTN_GARAGE, 62, 118, btn_scale(0), 256);
+ ui_sprite(SPR_BTN_PLAY, 160, 114, btn_scale(1), 256);
+ ui_sprite(SPR_BTN_CREATOR, 258, 118, btn_scale(2), 256);
+ ui_sprite(SPR_BTN_HELP, 112, 208, btn_scale(3), 256);
+ ui_sprite(SPR_BTN_SETTINGS, 160, 208, btn_scale(4), 256);
+ ui_sprite(SPR_BTN_STATS, 208, 208, btn_scale(5), 256);
+}
+
+/* ------------------------------------------------------------ popups */
+
+static const char *const option_names[6] = {"SHOW PERCENT", "PROGRESS BAR", "AUTO CHECKPOINTS", "LOW DETAIL", "SHOW FPS", "NO SHAKE"};
+static const uint8_t option_bits[6] = {OPT_PERCENT, OPT_BAR, OPT_AUTOCHECK, OPT_LOWDETAIL, OPT_FPS, OPT_NOSHAKE};
+
+static void popup_tick(void) {
+ if (app_hit(K_BACK)) {
+ if (popup == POP_SETTINGS) app_save_progress();
+ popup = POP_NONE;
+ return;
+ }
+ if (popup == POP_SETTINGS) {
+ if (app_hit(K_UP)) popup_sel = wrap(popup_sel - 1, 6);
+ if (app_hit(K_DOWN)) popup_sel = wrap(popup_sel + 1, 6);
+ if (app_accept() || app_hit(K_LEFT | K_RIGHT)) progress.options ^= option_bits[popup_sel];
+ } else if (popup == POP_HELP) {
+ if (app_hit(K_LEFT | K_RIGHT)) help_page ^= 1;
+ if (app_accept()) { if (help_page == 0) help_page = 1; else popup = POP_NONE; }
+ } else if (app_accept()) {
+ popup = POP_NONE;
+ }
+}
+
+static void stat_row(int y, const char *label, unsigned long v, int icon) {
+ char buf[16];
+ gfx_format_uint(buf, v);
+ gfx_text(FONT_SMALL, 58, y, label, 0xffff, 0xffff, 256);
+ gfx_text_right(FONT_BIG, icon >= 0 ? 244 : 262, y + 3, buf, 0xffff, 0xffff, 256);
+ if (icon >= 0) gfx_sprite(icon, 256, y - 4, 0, 0xffff, 256, BLEND_NORMAL);
+}
+
+static void popup_draw(void) {
+ float s = ui_ease_elastic_out(popup_t / 0.5f, 0.6f);
+ ui_dim((unsigned)(fminf(popup_t / 0.14f, 1) * 120));
+ int w = (int)(272 * s), h = (int)(200 * s);
+ if (w < 8 || h < 8) return;
+ if (popup == POP_HELP) ui_window_blue(160 - w / 2, 120 - h / 2, w, h);
+ else ui_window_brown(160 - w / 2, 120 - h / 2, w, h);
+ if (s < 0.85f) return;
+ if (popup == POP_SETTINGS) {
+ ui_title(FONT_BIG, 160, 44, "SETTINGS");
+ for (int i = 0; i < 6; i++) {
+ int y = 66 + i * 23;
+ bool on = (progress.options & option_bits[i]) != 0, focus = popup_sel == i;
+ ui_checkbox(92, y, on, focus ? 1.15f + 0.03f * sinf(app.t * 6) : 1.0f);
+ gfx_text(FONT_SMALL, 108, y + 4, option_names[i], focus ? GOLD_TOP : 0xffff, focus ? GOLD_BOTTOM : 0xffff, 256);
+ }
+ gfx_text_center(FONT_SMALL, 160, 208, "OK: TOGGLE BACK: SAVE", rgb(255, 230, 190), rgb(255, 230, 190), 220);
+ } else if (popup == POP_STATS) {
+ ui_title(FONT_BIG, 160, 44, "STATS");
+ unsigned completed = 0, stars = 0, coins = 0;
+ for (int i = 0; i < LEVEL_COUNT; i++) {
+ if (progress.lv[i].normal >= 100) { completed++; stars += level_defs[i].stars; }
+ coins += (unsigned)__builtin_popcount(progress.lv[i].coins);
+ }
+ stat_row(74, "TOTAL JUMPS", progress.jumps, -1);
+ stat_row(98, "TOTAL ATTEMPTS", progress.attempts, -1);
+ stat_row(122, "COMPLETED LEVELS", completed, -1);
+ stat_row(146, "STARS", stars, SPR_STAR_UI);
+ stat_row(170, "SECRET COINS", coins, SPR_COIN_UI);
+ } else {
+ static const char *const pages[2][8] = {
+ {"HOW TO PLAY", "OK, EXE OR UP: JUMP", "HOLD TO KEEP JUMPING OR TO FLY", "TAP IN MID AIR ON AN ORB", "BACK: PAUSE HOME: SAVE AND QUIT",
+ "PRACTICE: 0 PLACES A CHECKPOINT", "BACKSPACE REMOVES THE LAST ONE", "START PRACTICE FROM THE PAUSE MENU"},
+ {"LEVEL EDITOR", "ARROWS: MOVE OK: USE TOOL", "0: BUILD / EDIT / DELETE", "+ - OR TOOLBOX: PICK OBJECT", "SHIFT: ROTATE XNT: COPY",
+ "ALPHA: UNDO BACKSPACE: ERASE", "VAR: SAVE LN: LEVEL SETTINGS", "EXE: PLAYTEST BACK: EXIT"}};
+ ui_title(FONT_BIG, 160, 44, pages[help_page][0]);
+ for (int i = 1; i < 8; i++) gfx_text_center(FONT_SMALL, 160, 58 + i * 18, pages[help_page][i], 0xffff, 0xffff, 256);
+ ui_nav_dots(160, 206, 2, help_page);
+ }
+}
+
+/* ------------------------------------------------------------ level select */
+
+static void select_tick(void) {
+ if (app.press_id >= 0) return;
+ if (app_hit(K_LEFT)) app.select_page--;
+ if (app_hit(K_RIGHT)) app.select_page++;
+ if (app_hit(K_BACK)) { app_go(SCR_MENU); return; }
+ if (app_accept()) app_begin_press(100);
+}
+
+static void select_frame(float dt) {
+ float target = (float)app.select_page, d = target - app.select_scroll;
+ app.select_scroll += d * fminf(1, dt * 9);
+ if (fabsf(d) < 0.002f) app.select_scroll = target;
+ if (app.press_id == 100 && app.press_t >= 0.12f) {
+ app.press_id = -1;
+ app.level = wrap(app.select_page, LEVEL_COUNT);
+ app.practice = false;
+ app.testing = false;
+ app_go(SCR_PLAY);
+ }
+}
+
+static void level_page(int page, int dx) {
+ int i = wrap(page, LEVEL_COUNT);
+ const LevelDef *d = &level_defs[i];
+ const LevelStat *s = &progress.lv[i];
+ int cx = 160 + dx;
+ if (cx < -170 || cx > 490) return;
+ float sc = app.press_id == 100 && page == app.select_page ? 1 + 0.12f * ui_ease_bounce_out(fminf(app.press_t / 0.12f, 1)) : 1;
+ int w = (int)(242 * sc), h = (int)(84 * sc);
+ ui_window_dark(cx - w / 2, 80 - h / 2, w, h, 90);
+ gfx_sprite(SPR_FACE1 + (d->difficulty > 0 ? d->difficulty - 1 : 0), cx - 97, 82, 0, 0xffff, 256, BLEND_NORMAL);
+ gfx_text_center(FONT_BIG, cx + 17, 87, d->name, 0xffff, 0xffff, 256);
+ char buf[8];
+ gfx_format_uint(buf, d->stars);
+ gfx_text_right(FONT_SMALL, cx + 99, 53, buf, 0xffff, 0xffff, 256);
+ gfx_sprite(SPR_STAR_UI, cx + 107, 49, 0, 0xffff, 256, BLEND_NORMAL);
+ for (int k = 0; k < 3; k++)
+ gfx_sprite((s->coins >> k & 1) ? SPR_COIN_UI : SPR_COIN_UI_EMPTY, cx + 72 + k * 17, 108, 0, 0xffff, 256, BLEND_NORMAL);
+ ui_title(FONT_SMALL, cx, 138, "NORMAL MODE");
+ ui_progress_bar(cx, 149, 220, 14, s->normal, rgb(0, 255, 0), true);
+ ui_title(FONT_SMALL, cx, 173, "PRACTICE MODE");
+ ui_progress_bar(cx, 184, 220, 14, s->practice, rgb(0, 255, 255), true);
+}
+
+static void select_draw(void) {
+ float sc = app.select_scroll;
+ int base = (int)floorf(sc);
+ float fr = sc - base;
+ color_t c = c_mix(page_color(wrap(base, LEVEL_COUNT)), page_color(wrap(base + 1, LEVEL_COUNT)), (unsigned)(fr * 256));
+ ui_gradient_bg(c);
+ scene_ground(c, 0xffff, 0, 212, false, true);
+ ui_side_art();
+ ui_top_bar(12, true);
+ level_page(base, (int)(-fr * 320));
+ level_page(base + 1, (int)((1 - fr) * 320));
+ gfx_sprite(SPR_NAV_ARROW, 20, 120, XF_FLIPX, 0xffff, 256, BLEND_NORMAL);
+ gfx_sprite(SPR_NAV_ARROW, 300, 120, 0, 0xffff, 256, BLEND_NORMAL);
+ gfx_sprite(SPR_ARROW_BACK, 22, 26, 0, 0xffff, 256, BLEND_NORMAL);
+ ui_nav_dots(160, 228, LEVEL_COUNT, wrap(app.select_page, LEVEL_COUNT));
+}
+
+/* ------------------------------------------------------------ icon kit */
+
+static void garage_tick(void) {
+ if (app_hit(K_BACK)) { app_save_progress(); app_go(SCR_MENU); return; }
+ if (app.row == 0) {
+ if (app_hit(K_LEFT | K_RIGHT)) app.garage_tab ^= 1;
+ if (app_hit(K_DOWN)) app.row = 1;
+ if (app_accept()) app.garage_tab ^= 1;
+ return;
+ }
+ int c = app.sel % 14, r = app.sel / 14;
+ if (app_hit(K_LEFT)) c = wrap(c - 1, 14);
+ if (app_hit(K_RIGHT)) c = wrap(c + 1, 14);
+ if (app_hit(K_DOWN)) r = r < 2 ? r + 1 : 2;
+ if (app_hit(K_UP)) { if (r == 0) app.row = 0; else r--; }
+ app.sel = r * 14 + c;
+ if (app_accept()) {
+ if (app.garage_tab == 0) progress.color1 = (uint8_t)app.sel;
+ else progress.color2 = (uint8_t)app.sel;
+ }
+}
+
+static void garage_draw(void) {
+ ui_gradient_bg(rgb(170, 170, 170));
+ gfx_sprite(SPR_ARROW_BACK, 22, 26, 0, 0xffff, 256, BLEND_NORMAL);
+ ui_title(FONT_BIG, 160, 30, "ICON KIT");
+ /* preview on a small floor */
+ gfx_round_rect(70, 84, 180, 4, 2, 0, 90);
+ float bob = 0;
+ scene_draw_player_icon(MODE_CUBE, 124, 64 + bob, 0, 1.6f, app_p1(), app_p2(), false, 256);
+ scene_draw_player_icon(MODE_SHIP, 204, 66, 0, 1.3f, app_p1(), app_p2(), false, 256);
+ ui_text_button(118, 108, 84, 22, "COLOR 1", app.garage_tab == 0 ? BTN_GREEN : BTN_GRAY, app.row == 0 && app.garage_tab == 0 ? 1.08f : 1);
+ ui_text_button(202, 108, 84, 22, "COLOR 2", app.garage_tab == 1 ? BTN_GREEN : BTN_GRAY, app.row == 0 && app.garage_tab == 1 ? 1.08f : 1);
+ int cur = app.garage_tab == 0 ? progress.color1 : progress.color2;
+ for (int i = 0; i < 42; i++) {
+ int x = 13 + (i % 14) * 21, y = 128 + (i / 14) * 22;
+ gfx_round_rect(x - 1, y - 1, 20, 20, 3, 0, 256);
+ gfx_round_rect(x + 1, y + 1, 16, 16, 2, icon_color(i), 256);
+ if (i == cur) {
+ gfx_round_rect(x - 3, y - 3, 24, 24, 4, 0xffff, 110);
+ gfx_round_rect(x + 1, y + 1, 16, 16, 2, icon_color(i), 256);
+ gfx_sprite(SPR_CHECK_ON, x + 9, y + 9, 0, 0xffff, 200, BLEND_NORMAL);
+ }
+ if (app.row == 1 && i == app.sel) {
+ gfx_round_rect(x - 4, y - 4, 26, 3, 1, rgb(255, 255, 0), 256);
+ gfx_round_rect(x - 4, y + 19, 26, 3, 1, rgb(255, 255, 0), 256);
+ gfx_fill(x - 4, y - 4, 3, 26, rgb(255, 255, 0));
+ gfx_fill(x + 19, y - 4, 3, 26, rgb(255, 255, 0));
+ }
+ }
+ ui_side_art();
+}
+
+/* ------------------------------------------------------------ loading */
+
+static const char *const tips[] = {
+ "LISTEN TO THE MUSIC TO HELP TIME YOUR JUMPS", "BACK FOR MORE ARE YA?", "USE PRACTICE MODE TO LEARN THE LAYOUT OF A LEVEL",
+ "IF AT FIRST YOU DON'T SUCCEED, TRY, TRY AGAIN...", "CUSTOMIZE YOUR CHARACTER'S ICON AND COLOR!",
+ "SPIKES ARE NOT YOUR FRIENDS. DON'T FORGET TO JUMP", "BUILD YOUR OWN LEVELS USING THE LEVEL EDITOR",
+ "CAN YOU BEAT THEM ALL?", "PRO TIP: DON'T CRASH", "HOLD DOWN TO KEEP JUMPING", "PRO TIP: JUMP",
+ "PLAY, CRASH, RINSE AND REPEAT", "ONLY ONE BUTTON REQUIRED TO CRASH", "IT'S ALL IN THE TIMING", "FAKE SPIKES ARE FAKE",
+ "WHERE DID I PUT THAT COIN...", "CALCULATING CHANCE OF SUCCESS", "LOADING WILL BE FINISHED... SOON"};
+static int tip;
+
+static void loading_draw(void) {
+ scene_background(rgb(0, 102, 255), 0, 0);
+ gfx_layer_draw(160, 96, 256, rgb(215, 255, 100), rgb(70, 180, 10), 256);
+ float t = app.t / 1.2f;
+ if (t > 1) t = 1;
+ int w = 200, x = 60, y = 132;
+ gfx_round_rect(x - 2, y - 2, w + 4, 14, 6, 0, 180);
+ gfx_round_rect(x, y, w, 10, 5, rgb(20, 20, 20), 256);
+ int fw = (int)((w - 4) * t);
+ if (fw > 6) {
+ gfx_round_rect(x + 2, y + 2, fw, 6, 3, rgb(90, 255, 30), 256);
+ gfx_add(x + 4, y + 3, fw - 4, 1, 0xffff, 90);
+ }
+ /* long tips wrap onto two lines at the space nearest the middle */
+ const char *t0 = tips[tip];
+ if (gfx_text_width(FONT_SMALL, t0) <= 300) {
+ gfx_text_center(FONT_SMALL, 160, 170, t0, 0xffff, 0xffff, 256);
+ return;
+ }
+ int n = (int)strlen(t0), cut = -1;
+ for (int i = 0; i < n; i++)
+ if (t0[i] == ' ' && (cut < 0 || abs(i - n / 2) < abs(cut - n / 2))) cut = i;
+ char line[64];
+ memcpy(line, t0, (size_t)cut);
+ line[cut] = 0;
+ gfx_text_center(FONT_SMALL, 160, 166, line, 0xffff, 0xffff, 256);
+ gfx_text_center(FONT_SMALL, 160, 180, t0 + cut + 1, 0xffff, 0xffff, 256);
+}
+
+/* ------------------------------------------------------------ dispatch */
+
+void menu_enter(Screen s) {
+ popup = POP_NONE;
+ if (s == SCR_LOADING) {
+ tip = (int)(frand() * (sizeof(tips) / sizeof(tips[0])));
+ gfx_layer_build(FONT_HUGE, "GEOMETRY DASH");
+ } else if (s == SCR_MENU) {
+ memset(&menu_level, 0, sizeof(menu_level));
+ menu_level.name = "";
+ menu_level.objs = level_objs;
+ menu_level.end_x = menu_level.wall_x = 65000;
+ for (int c = 0; c < CH_COUNT; c++) memset(menu_level.colors[c], 255, 3);
+ app.g.L = NULL;
+ runner_reset();
+ gfx_layer_build(FONT_HUGE, "GEOMETRY DASH");
+ app.sel = 1;
+ } else if (s == SCR_SELECT) {
+ app.select_page = app.level < LEVEL_COUNT ? app.level : 0;
+ app.select_scroll = (float)app.select_page;
+ } else if (s == SCR_GARAGE) {
+ app.row = 1;
+ app.sel = progress.color1;
+ app.garage_tab = 0;
+ }
+}
+
+void menu_tick(void) {
+ switch (app.screen) {
+ case SCR_MENU:
+ runner_tick();
+ if (popup) { popup_tick(); break; }
+ if (app.press_id >= 0) break;
+ if (app_hit(K_BACK)) { app_dialog_quit(); break; }
+ if (app_hit(K_LEFT)) app.sel = app.sel < 3 ? wrap(app.sel - 1, 3) : 3 + wrap(app.sel - 4, 3);
+ if (app_hit(K_RIGHT)) app.sel = app.sel < 3 ? wrap(app.sel + 1, 3) : 3 + wrap(app.sel - 2, 3);
+ if (app_hit(K_DOWN) && app.sel < 3) app.sel = app.sel + 3;
+ if (app_hit(K_UP) && app.sel >= 3) app.sel -= 3;
+ if (app_accept()) app_begin_press(app.sel);
+ break;
+ case SCR_SELECT: select_tick(); break;
+ case SCR_GARAGE: garage_tick(); break;
+ case SCR_LOADING:
+ if (app.t >= 1.35f || (app.hit && app.t > 0.2f)) app_go(SCR_MENU);
+ break;
+ default: break;
+ }
+}
+
+void menu_frame(float dt) {
+ if (popup) popup_t += dt;
+ if (app.screen == SCR_MENU) {
+ menu_colors(dt);
+ fx_update(&app.g, dt, run_c1, run_c2, false);
+ if (app.press_id >= 0 && app.press_t >= 0.12f) {
+ int id = app.press_id;
+ app.press_id = -1;
+ main_activate(id);
+ }
+ memset(&menu_opts, 0, sizeof(menu_opts));
+ menu_opts.p1 = run_c1;
+ menu_opts.p2 = run_c2;
+ menu_opts.time = app.t;
+ scene_prepare(&app.g, &menu_opts);
+ } else if (app.screen == SCR_SELECT) {
+ select_frame(dt);
+ }
+}
+
+void menu_draw(void) {
+ switch (app.screen) {
+ case SCR_MENU:
+ main_draw();
+ if (popup) popup_draw();
+ break;
+ case SCR_SELECT: select_draw(); break;
+ case SCR_GARAGE: garage_draw(); break;
+ case SCR_LOADING: loading_draw(); break;
+ default: break;
+ }
+}
diff --git a/games/numdash/src/objdefs.c b/games/numdash/src/objdefs.c
new file mode 100644
index 00000000..1493fcaf
--- /dev/null
+++ b/games/numdash/src/objdefs.c
@@ -0,0 +1,45 @@
+/* Generated by tools/levels.py. Do not edit. */
+#include "objdefs.h"
+#include "assets.h"
+const ObjDef objdefs[OT_COUNT] = {
+ {0,0,0,0,0,0,0,{{-1,0,0,0,0,0},{-1,0,0,0,0,0}}},
+ {1,1,SP_NONE,300,300,0,2,{{SPR_BLOCK,0,0,LAYER_BLOCK,CT_OBJ,0},{SPR_GLOW_ALL,0,0,LAYER_BLOCK_GLOW,CT_GLOW,0}}},
+ {2,1,SP_NONE,300,300,0,2,{{SPR_GRID_T,0,0,LAYER_BLOCK,CT_OBJ,0},{SPR_GLOW_T,0,0,LAYER_BLOCK_GLOW,CT_GLOW,0}}},
+ {3,1,SP_NONE,300,300,0,2,{{SPR_GRID_TL,0,0,LAYER_BLOCK,CT_OBJ,0},{SPR_GLOW_TL,0,0,LAYER_BLOCK_GLOW,CT_GLOW,0}}},
+ {4,1,SP_NONE,300,300,0,2,{{SPR_GRID_C,0,0,LAYER_BLOCK,CT_OBJ,0},{SPR_GLOW_C,0,0,LAYER_BLOCK_GLOW,CT_GLOW,0}}},
+ {6,1,SP_NONE,300,300,0,2,{{SPR_GRID_LTR,0,0,LAYER_BLOCK,CT_OBJ,0},{SPR_GLOW_LTR,0,0,LAYER_BLOCK_GLOW,CT_GLOW,0}}},
+ {7,1,SP_NONE,300,300,0,2,{{SPR_GRID_LR,0,0,LAYER_BLOCK,CT_OBJ,0},{SPR_GLOW_LR,0,0,LAYER_BLOCK_GLOW,CT_GLOW,0}}},
+ {5,0,SP_NONE,0,0,0,1,{{SPR_GRID_NONE,0,0,LAYER_DECO_BACK,CT_OBJ,0},{-1,0,0,0,0,0}}},
+ {73,0,SP_NONE,0,0,0,1,{{SPR_DIAG_BLOCK,0,0,LAYER_DECO_BACK,CT_OBJ,0},{-1,0,0,0,0,0}}},
+ {40,1,SP_NONE,300,140,8,2,{{SPR_PLANK,0,0,LAYER_BLOCK,CT_OBJ,0},{SPR_GLOW_PLANK,0,0,LAYER_BLOCK_GLOW,CT_GLOW,0}}},
+ {62,1,SP_NONE,300,160,7,1,{{SPR_SLAB0,0,0,LAYER_BLOCK,CT_OBJ,0},{-1,0,0,0,0,0}}},
+ {65,1,SP_NONE,300,160,7,1,{{SPR_SLAB1,0,0,LAYER_BLOCK,CT_OBJ,0},{-1,0,0,0,0,0}}},
+ {66,1,SP_NONE,300,160,7,1,{{SPR_SLAB2,0,0,LAYER_BLOCK,CT_OBJ,0},{-1,0,0,0,0,0}}},
+ {68,1,SP_NONE,300,160,7,1,{{SPR_SLAB3,0,0,LAYER_BLOCK,CT_OBJ,0},{-1,0,0,0,0,0}}},
+ {8,2,SP_NONE,60,120,0,2,{{SPR_SPIKE,0,0,LAYER_BLOCK,CT_OBJ,0},{SPR_GLOW_SPIKE,0,0,LAYER_BLOCK_GLOW,CT_GLOW,0}}},
+ {39,2,SP_NONE,60,56,-9,2,{{SPR_SPIKE_SMALL,0,0,LAYER_BLOCK,CT_OBJ,0},{SPR_GLOW_SPIKE_SMALL,0,0,LAYER_BLOCK_GLOW,CT_GLOW,0}}},
+ {103,2,SP_NONE,40,76,-6,2,{{SPR_SPIKE_MED,0,0,LAYER_BLOCK,CT_OBJ,0},{SPR_GLOW_SPIKE_MED,0,0,LAYER_BLOCK_GLOW,CT_GLOW,0}}},
+ {9,2,SP_NONE,90,108,-13,1,{{SPR_PIT0,0,0,LAYER_BLOCK,CT_BLACK,2},{-1,0,0,0,0,0}}},
+ {15,0,SP_NONE,0,0,6,2,{{SPR_ROD1,0,0,LAYER_RODS,CT_BLACK,0},{SPR_ROD_BALL,0,140,LAYER_ROD_BALLS,CT_P1ADD,1}}},
+ {16,0,SP_NONE,0,0,-1,2,{{SPR_ROD2,0,0,LAYER_RODS,CT_BLACK,0},{SPR_ROD_BALL,0,110,LAYER_ROD_BALLS,CT_P1ADD,1}}},
+ {17,0,SP_NONE,0,0,-8,2,{{SPR_ROD3,0,0,LAYER_RODS,CT_BLACK,0},{SPR_ROD_BALL,0,80,LAYER_ROD_BALLS,CT_P1ADD,1}}},
+ {18,0,SP_NONE,0,0,4,1,{{SPR_DSPIKES1,0,0,LAYER_DETAIL,CT_P1ADD,0},{-1,0,0,0,0,0}}},
+ {19,0,SP_NONE,0,0,4,1,{{SPR_DSPIKES2,0,0,LAYER_DETAIL,CT_P1ADD,0},{-1,0,0,0,0,0}}},
+ {20,0,SP_NONE,0,0,-2,1,{{SPR_DSPIKES3,0,0,LAYER_DETAIL,CT_P1ADD,0},{-1,0,0,0,0,0}}},
+ {21,0,SP_NONE,0,0,-8,1,{{SPR_DSPIKES4,0,0,LAYER_DETAIL,CT_P1ADD,0},{-1,0,0,0,0,0}}},
+ {41,0,SP_NONE,0,0,-12,1,{{SPR_CHAIN,0,0,LAYER_DETAIL,CT_P1ADD,0},{-1,0,0,0,0,0}}},
+ {110,0,SP_NONE,0,0,-13,1,{{SPR_CHAIN_SHORT,0,0,LAYER_DETAIL,CT_P1ADD,0},{-1,0,0,0,0,0}}},
+ {54,0,SP_NONE,0,0,0,1,{{SPR_STAR,0,0,LAYER_DETAIL,CT_P2ADD,0},{-1,0,0,0,0,0}}},
+ {35,3,SP_PAD_Y,250,40,-13,2,{{SPR_PAD_YELLOW,0,0,LAYER_SPECIAL,CT_WHITE,0},{SPR_GLOW_PAD_YELLOW,0,8,LAYER_SPECIAL_GLOW,CT_GLOW_Y,0}}},
+ {67,3,SP_PAD_B,250,60,-12,2,{{SPR_PAD_BLUE,0,0,LAYER_SPECIAL,CT_WHITE,0},{SPR_GLOW_PAD_BLUE,0,8,LAYER_SPECIAL_GLOW,CT_GLOW_B,0}}},
+ {140,3,SP_PAD_P,250,50,-13,2,{{SPR_PAD_PINK,0,0,LAYER_SPECIAL,CT_WHITE,0},{SPR_GLOW_PAD_PINK,0,8,LAYER_SPECIAL_GLOW,CT_GLOW_P,0}}},
+ {36,3,SP_ORB_Y,360,360,0,2,{{SPR_ORB_YELLOW,0,0,LAYER_SPECIAL,CT_WHITE,1},{SPR_GLOW_ORB_YELLOW,0,0,LAYER_SPECIAL_GLOW,CT_GLOW_Y,0}}},
+ {141,3,SP_ORB_P,360,360,0,2,{{SPR_ORB_PINK,0,0,LAYER_SPECIAL,CT_WHITE,1},{SPR_GLOW_ORB_PINK,0,0,LAYER_SPECIAL_GLOW,CT_GLOW_P,0}}},
+ {84,3,SP_ORB_B,360,360,0,2,{{SPR_ORB_BLUE,0,0,LAYER_SPECIAL,CT_WHITE,1},{SPR_GLOW_ORB_BLUE,0,0,LAYER_SPECIAL_GLOW,CT_GLOW_B,0}}},
+ {10,3,SP_GRAV_N,250,750,0,2,{{SPR_PORTAL_GRAV_BLUE_FRONT,16,0,LAYER_PORTAL_FRONT,CT_WHITE,0},{SPR_PORTAL_GRAV_BLUE_BACK,-24,0,LAYER_PORTAL_BACK,CT_WHITE,0}}},
+ {11,3,SP_GRAV_F,250,750,0,2,{{SPR_PORTAL_GRAV_YELLOW_FRONT,16,0,LAYER_PORTAL_FRONT,CT_WHITE,0},{SPR_PORTAL_GRAV_YELLOW_BACK,-24,0,LAYER_PORTAL_BACK,CT_WHITE,0}}},
+ {12,3,SP_PORTAL_CUBE,340,860,0,2,{{SPR_PORTAL_CUBE_FRONT,20,0,LAYER_PORTAL_FRONT,CT_WHITE,0},{SPR_PORTAL_CUBE_BACK,-24,0,LAYER_PORTAL_BACK,CT_WHITE,0}}},
+ {13,3,SP_PORTAL_SHIP,340,860,0,2,{{SPR_PORTAL_SHIP_FRONT,20,0,LAYER_PORTAL_FRONT,CT_WHITE,0},{SPR_PORTAL_SHIP_BACK,-24,0,LAYER_PORTAL_BACK,CT_WHITE,0}}},
+ {1329,3,SP_COIN,400,400,0,1,{{SPR_COIN0,0,0,LAYER_COIN,CT_WHITE,4},{-1,0,0,0,0,0}}},
+};
+const uint8_t editor_types[EDITOR_TYPES] = {OT_BLOCK,OT_GRID_T,OT_GRID_TL,OT_GRID_LTR,OT_GRID_LR,OT_GRID_C,OT_PLANK,OT_SPIKE,OT_SPIKE_SMALL,OT_SPIKE_MED,OT_PIT,OT_PAD_Y,OT_PAD_P,OT_PAD_B,OT_ORB_Y,OT_PORTAL_SHIP,OT_PORTAL_CUBE,OT_GRAV_F,OT_GRAV_N,OT_COIN,OT_GRID_DECO,OT_ROD1,OT_ROD2,OT_ROD3,OT_DSPIKES3,OT_DSPIKES4,OT_CHAIN,OT_STAR};
diff --git a/games/numdash/src/objdefs.h b/games/numdash/src/objdefs.h
new file mode 100644
index 00000000..076d589d
--- /dev/null
+++ b/games/numdash/src/objdefs.h
@@ -0,0 +1,58 @@
+/* Generated by tools/levels.py. Do not edit. */
+#ifndef NUMDASH_OBJDEFS_H
+#define NUMDASH_OBJDEFS_H
+#include <stdint.h>
+enum {
+ OT_NONE = 0,
+ OT_BLOCK = 1,
+ OT_GRID_T = 2,
+ OT_GRID_TL = 3,
+ OT_GRID_C = 4,
+ OT_GRID_LTR = 5,
+ OT_GRID_LR = 6,
+ OT_GRID_DECO = 7,
+ OT_DIAG_DECO = 8,
+ OT_PLANK = 9,
+ OT_SLAB0 = 10,
+ OT_SLAB1 = 11,
+ OT_SLAB2 = 12,
+ OT_SLAB3 = 13,
+ OT_SPIKE = 14,
+ OT_SPIKE_SMALL = 15,
+ OT_SPIKE_MED = 16,
+ OT_PIT = 17,
+ OT_ROD1 = 18,
+ OT_ROD2 = 19,
+ OT_ROD3 = 20,
+ OT_DSPIKES1 = 21,
+ OT_DSPIKES2 = 22,
+ OT_DSPIKES3 = 23,
+ OT_DSPIKES4 = 24,
+ OT_CHAIN = 25,
+ OT_CHAIN_SHORT = 26,
+ OT_STAR = 27,
+ OT_PAD_Y = 28,
+ OT_PAD_B = 29,
+ OT_PAD_P = 30,
+ OT_ORB_Y = 31,
+ OT_ORB_P = 32,
+ OT_ORB_B = 33,
+ OT_GRAV_N = 34,
+ OT_GRAV_F = 35,
+ OT_PORTAL_CUBE = 36,
+ OT_PORTAL_SHIP = 37,
+ OT_COIN = 38,
+ OT_COUNT = 39
+};
+enum { HIT_NONE, HIT_SOLID, HIT_HAZARD, HIT_SPECIAL };
+enum { SP_NONE, SP_PAD_Y, SP_PAD_P, SP_PAD_B, SP_ORB_Y, SP_ORB_P, SP_ORB_B, SP_GRAV_N, SP_GRAV_F, SP_PORTAL_CUBE, SP_PORTAL_SHIP, SP_COIN };
+enum { CT_OBJ, CT_BLACK, CT_WHITE, CT_P1ADD, CT_P2ADD, CT_GLOW, CT_GLOW_Y, CT_GLOW_B, CT_GLOW_P };
+enum { LAYER_DECO_BACK, LAYER_RODS, LAYER_ROD_BALLS, LAYER_DETAIL, LAYER_SPECIAL_GLOW, LAYER_SPECIAL, LAYER_PORTAL_BACK, LAYER_BLOCK_GLOW, LAYER_PLAYER, LAYER_COIN, LAYER_PORTAL_FRONT, LAYER_FILL, LAYER_BLOCK, LAYER_COUNT };
+enum { PF_PULSE = 1, PF_RANDOM3 = 2, PF_COIN = 4, PF_ANIM = 8 };
+enum { EV_COLOR = 1, EV_FADE = 2, EV_TRAIL = 3 };
+typedef struct { int16_t sprite; int8_t dx4, dy4; uint8_t layer, ctype, flags; } ObjPart;
+typedef struct { uint16_t gd_id; uint8_t hit, special; uint16_t w10, h10; int8_t editor_dy; uint8_t nparts; ObjPart parts[2]; } ObjDef;
+extern const ObjDef objdefs[OT_COUNT];
+#define EDITOR_TYPES 28
+extern const uint8_t editor_types[EDITOR_TYPES];
+#endif
diff --git a/games/numdash/src/platform.h b/games/numdash/src/platform.h
new file mode 100644
index 00000000..51d30fbe
--- /dev/null
+++ b/games/numdash/src/platform.h
@@ -0,0 +1,30 @@
+#ifndef NUMDASH_PLATFORM_H
+#define NUMDASH_PLATFORM_H
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+enum { K_LEFT = 1, K_RIGHT = 2, K_UP = 4, K_DOWN = 8, K_OK = 16, K_EXE = 32,
+ K_BACK = 64, K_HOME = 128, K_TOOL = 256, K_SHIFT = 512, K_ERASE = 1024,
+ K_SAVE = 2048, K_UNDO = 4096, K_CHECK = 8192, K_PLUS = 16384, K_MINUS = 32768,
+ K_COPY = 65536, K_PROPS = 131072 };
+
+bool platform_init(void);
+void platform_close(void);
+/* Keys held now, plus keys pressed and released since the previous call. */
+uint32_t platform_keys(void);
+uint32_t platform_millis(void);
+void platform_sleep(unsigned ms);
+uint32_t platform_random(void);
+
+/* A frame is sent as horizontal strips (top to bottom) between begin/end.
+ * vsync asks the device to start on the LCD's vertical blank. */
+void platform_frame_begin(bool vsync);
+void platform_strip(int y, int h, const uint16_t *pixels);
+void platform_frame_end(void);
+
+/* Epsilon's record file system (magic words excluded), or NULL. Writes go
+ * through save.c's move-safe helpers; commit persists them where needed. */
+uint8_t *platform_storage(size_t *size);
+void platform_storage_commit(void);
+#endif
diff --git a/games/numdash/src/platform_eadk.c b/games/numdash/src/platform_eadk.c
new file mode 100644
index 00000000..75f8d9f7
--- /dev/null
+++ b/games/numdash/src/platform_eadk.c
@@ -0,0 +1,107 @@
+#include "platform.h"
+#include <eadk.h>
+#include <string.h>
+
+bool platform_init(void) { return true; }
+void platform_close(void) {}
+uint32_t platform_millis(void) { return (uint32_t)eadk_timing_millis(); }
+void platform_sleep(unsigned ms) { eadk_timing_msleep(ms); }
+uint32_t platform_random(void) { return eadk_random(); }
+
+static uint32_t scan_keys(void) {
+ eadk_keyboard_state_t k = eadk_keyboard_scan();
+ uint32_t out = 0;
+ static const struct { uint8_t key; uint32_t bit; } map[] = {
+ {eadk_key_left, K_LEFT}, {eadk_key_right, K_RIGHT}, {eadk_key_up, K_UP}, {eadk_key_down, K_DOWN},
+ {eadk_key_ok, K_OK}, {eadk_key_exe, K_EXE}, {eadk_key_back, K_BACK}, {eadk_key_home, K_HOME},
+ {eadk_key_on_off, K_HOME}, {eadk_key_toolbox, K_TOOL}, {eadk_key_shift, K_SHIFT},
+ {eadk_key_backspace, K_ERASE}, {eadk_key_var, K_SAVE}, {eadk_key_alpha, K_UNDO},
+ {eadk_key_zero, K_CHECK}, {eadk_key_plus, K_PLUS}, {eadk_key_minus, K_MINUS},
+ {eadk_key_xnt, K_COPY}, {eadk_key_ln, K_PROPS}};
+ for (unsigned i = 0; i < sizeof(map) / sizeof(map[0]); i++)
+ if (eadk_keyboard_key_down(k, (eadk_key_t)map[i].key)) out |= map[i].bit;
+ return out;
+}
+
+/* Keys are also sampled between strip transfers so that a quick tap made
+ * while a frame is being sent is not lost. */
+static uint32_t last_scan, captured;
+static void capture_keys(void) {
+ uint32_t now = scan_keys();
+ captured |= now & ~last_scan;
+ last_scan = now;
+}
+uint32_t platform_keys(void) {
+ capture_keys();
+ uint32_t out = last_scan | captured;
+ captured = 0;
+ return out;
+}
+
+/* Strips whose pixels did not change since the last frame are skipped. */
+static uint32_t strip_hash[32];
+void platform_frame_begin(bool vsync) {
+ capture_keys();
+ if (vsync) eadk_display_wait_for_vblank();
+}
+void platform_strip(int y, int h, const uint16_t *pixels) {
+ const uint32_t *w = (const uint32_t *)pixels;
+ uint32_t hash = 2166136261u;
+ for (int i = 0, n = 320 * h / 2; i < n; i++) hash = (hash ^ w[i]) * 16777619u;
+ int slot = (y / 8) & 31;
+ if (strip_hash[slot] != hash) {
+ strip_hash[slot] = hash;
+ eadk_display_push_rect((eadk_rect_t){0, (uint16_t)y, 320, (uint16_t)h}, pixels);
+ }
+ capture_keys();
+}
+void platform_frame_end(void) { capture_keys(); }
+
+/* Only Epsilon's documented record buffer is used. A SlotInfo pointer is
+ * available after a USB transfer but can be zero after a cold boot, so a
+ * unique validated storage from either firmware slot is accepted too. */
+static uint8_t *storage_at(uint32_t address, size_t *size) {
+#if PLATFORM_DEVICE
+ /* The optional extra-data sector shifts the userland header by 64 KiB. */
+ if (address != 0x90010000 && address != 0x90020000 && address != 0x90410000 && address != 0x90420000) return NULL;
+ const uint32_t *header = (const uint32_t *)(uintptr_t)address;
+ if (header[0] != 0xDEC0EDFE || header[11] != 0xDEC0EDFE) return NULL;
+ uint32_t ram = header[3], length = header[4];
+ if (length < 1024 || length > 65536 || ram < 0x24000010 || ram > 0x24040000 - length - 8 || ram % 4) return NULL;
+ const uint32_t *magic = (const uint32_t *)(uintptr_t)ram;
+ if (*magic != 0xEE0BDDBA) return NULL;
+ uint32_t footer;
+ memcpy(&footer, (const uint8_t *)magic + 4 + length, 4);
+ if (footer != 0xEE0BDDBA) return NULL;
+ *size = length;
+ return (uint8_t *)(uintptr_t)(ram + 4);
+#else
+ (void)address; (void)size;
+ return NULL;
+#endif
+}
+uint8_t *platform_storage(size_t *size) {
+#if !PLATFORM_DEVICE
+ (void)size;
+ return NULL;
+#endif
+ const volatile uint32_t *slot = (const volatile uint32_t *)0x24000000;
+ if (slot[0] == 0xEFEEDBBA && slot[3] == 0xEFEEDBBA) {
+ uint8_t *a = storage_at(slot[2], size);
+ if (a) return a;
+ }
+ static const uint32_t headers[] = {0x90010000, 0x90020000, 0x90410000, 0x90420000};
+ uint8_t *match = NULL;
+ size_t matched = 0;
+ for (unsigned i = 0; i < 4; i++) {
+ size_t bytes = 0;
+ uint8_t *a = storage_at(headers[i], &bytes);
+ if (!a) continue;
+ if (match && (match != a || matched != bytes)) return NULL;
+ match = a;
+ matched = bytes;
+ }
+ if (match) *size = matched;
+ return match;
+}
+void platform_storage_commit(void) {}
diff --git a/games/numdash/src/platform_sdl.c b/games/numdash/src/platform_sdl.c
new file mode 100644
index 00000000..83bf72b9
--- /dev/null
+++ b/games/numdash/src/platform_sdl.c
@@ -0,0 +1,93 @@
+/* Desktop build: SDL2 window, keyboard mapping and a file-backed copy of
+ * the calculator's record storage. */
+#include "platform.h"
+#include <SDL.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static SDL_Window *window;
+static SDL_Renderer *renderer;
+static SDL_Texture *texture;
+static uint16_t frame[320 * 240];
+static bool quit;
+static uint8_t storage[42 * 1024];
+
+static const char *store_path(void) {
+ const char *p = getenv("NUMDASH_STORE");
+ return p ? p : "numdash.store";
+}
+
+bool platform_init(void) {
+ if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER)) return false;
+ window = SDL_CreateWindow("NumDash (Space/Enter/Up: jump Esc: back 0: checkpoint)", SDL_WINDOWPOS_CENTERED,
+ SDL_WINDOWPOS_CENTERED, 960, 720, SDL_WINDOW_RESIZABLE);
+ renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
+ if (!renderer) renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE);
+ if (!renderer) return false;
+ SDL_RenderSetLogicalSize(renderer, 320, 240);
+ SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0");
+ texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGB565, SDL_TEXTUREACCESS_STREAMING, 320, 240);
+ FILE *f = fopen(store_path(), "rb");
+ if (f) {
+ size_t n = fread(storage, 1, sizeof(storage), f);
+ (void)n;
+ fclose(f);
+ }
+ return texture != NULL;
+}
+void platform_close(void) {
+ SDL_DestroyTexture(texture);
+ SDL_DestroyRenderer(renderer);
+ SDL_DestroyWindow(window);
+ SDL_Quit();
+}
+uint32_t platform_millis(void) { return SDL_GetTicks(); }
+void platform_sleep(unsigned ms) { SDL_Delay(ms); }
+uint32_t platform_random(void) { return (uint32_t)rand() ^ ((uint32_t)rand() << 15) ^ ((uint32_t)rand() << 30); }
+
+static uint32_t captured, held;
+static const struct { int key; uint32_t bit; } keymap[] = {
+ {SDL_SCANCODE_LEFT, K_LEFT}, {SDL_SCANCODE_RIGHT, K_RIGHT}, {SDL_SCANCODE_UP, K_UP}, {SDL_SCANCODE_DOWN, K_DOWN},
+ {SDL_SCANCODE_SPACE, K_OK}, {SDL_SCANCODE_RETURN, K_EXE}, {SDL_SCANCODE_ESCAPE, K_BACK}, {SDL_SCANCODE_HOME, K_HOME},
+ {SDL_SCANCODE_TAB, K_TOOL}, {SDL_SCANCODE_LSHIFT, K_SHIFT}, {SDL_SCANCODE_RSHIFT, K_SHIFT},
+ {SDL_SCANCODE_BACKSPACE, K_ERASE}, {SDL_SCANCODE_S, K_SAVE}, {SDL_SCANCODE_Z, K_UNDO}, {SDL_SCANCODE_0, K_CHECK},
+ {SDL_SCANCODE_EQUALS, K_PLUS}, {SDL_SCANCODE_MINUS, K_MINUS}, {SDL_SCANCODE_X, K_COPY}, {SDL_SCANCODE_L, K_PROPS}};
+uint32_t platform_keys(void) {
+ SDL_Event e;
+ while (SDL_PollEvent(&e)) {
+ if (e.type == SDL_QUIT) quit = true;
+ if (e.type == SDL_KEYDOWN && !e.key.repeat)
+ for (unsigned i = 0; i < sizeof(keymap) / sizeof(keymap[0]); i++)
+ if ((int)e.key.keysym.scancode == keymap[i].key) captured |= keymap[i].bit;
+ }
+ const uint8_t *k = SDL_GetKeyboardState(NULL);
+ held = quit ? K_HOME : 0;
+ for (unsigned i = 0; i < sizeof(keymap) / sizeof(keymap[0]); i++)
+ if (k[keymap[i].key]) held |= keymap[i].bit;
+ uint32_t out = held | captured;
+ captured = 0;
+ return out;
+}
+
+void platform_frame_begin(bool vsync) { (void)vsync; }
+void platform_strip(int y, int h, const uint16_t *pixels) { memcpy(frame + y * 320, pixels, (size_t)h * 320 * 2); }
+void platform_frame_end(void) {
+ SDL_UpdateTexture(texture, NULL, frame, 320 * 2);
+ SDL_RenderClear(renderer);
+ SDL_RenderCopy(renderer, texture, NULL, NULL);
+ SDL_RenderPresent(renderer);
+}
+
+uint8_t *platform_storage(size_t *size) {
+ *size = sizeof(storage);
+ return storage;
+}
+void platform_storage_commit(void) {
+ char tmp[1024];
+ if (snprintf(tmp, sizeof(tmp), "%s.tmp", store_path()) >= (int)sizeof(tmp)) return;
+ FILE *f = fopen(tmp, "wb");
+ if (!f) return;
+ bool good = fwrite(storage, 1, sizeof(storage), f) == sizeof(storage);
+ if (fclose(f) == 0 && good) rename(tmp, store_path());
+}
diff --git a/games/numdash/src/play.c b/games/numdash/src/play.c
new file mode 100644
index 00000000..234b7321
--- /dev/null
+++ b/games/numdash/src/play.c
@@ -0,0 +1,541 @@
+/* Gameplay screen: attempts, death and respawn, practice checkpoints, the
+ * pause menu, the new-best popup and the level complete sequence (end wall
+ * rays, rings and fireworks, then the level complete window). Timings follow
+ * Geometry Dash (and the gd3ds recreation). */
+#include "app.h"
+#include "ui.h"
+#include <math.h>
+#include <string.h>
+
+enum { PAUSE_PRACTICE, PAUSE_RESUME, PAUSE_MENU, PAUSE_REPLAY };
+enum { POP_NONE, POP_COMPLETE, POP_NEWBEST };
+#define FIREWORK_TIME 2.0f
+#define MENU_TIME 3.5f
+
+static SceneOpts opts;
+static float shake_t, shake_amp, shake_dx, shake_dy;
+static bool shake_applied;
+static float respawn_t;
+static int respawn_phase; /* counts hide/show half cycles left */
+static float death_len;
+static uint16_t jumps_counted;
+
+/* level complete */
+typedef struct { float delay, dur, h, alpha, angle; } Ray;
+static Ray rays[8];
+static float rays_t, rays_fade_t;
+static bool rays_on, rays_fading;
+static int rings_a, rings_b, fireworks;
+static bool phase2;
+static int popup;
+static float popup_t;
+static float end_t, leave_t;
+static int end_sel, leave_action;
+static bool leaving;
+static uint8_t coins_run, coins_new;
+static bool stars_new;
+static int msg_index;
+
+static const char *const complete_msgs[] = {
+ "AWESOME!", "GOOD JOB!", "WELL DONE!", "IMPRESSIVE!", "AMAZING!", "INCREDIBLE!", "SKILLFUL!", "BRILLIANT!",
+ "NOT BAD!", "WARP SPEED!", "CHALLENGE BREAKER!", "REFLEX MASTER!", "I AM SPEECHLESS...", "YOU ARE... THE ONE!",
+ "HOW IS THIS POSSIBLE!?", "YOU BEAT ME..."};
+
+static color_t white_if_black(color_t c) { return c == 0 ? 0xffff : c; }
+
+static unsigned level_coins(void) { return app.L.coin_count; }
+
+static void flush_jumps(void) {
+ unsigned j = app.g.jumps >= jumps_counted ? app.g.jumps - jumps_counted : 0;
+ jumps_counted = app.g.jumps;
+ app.session_jumps += j;
+ if (!app.testing) {
+ progress.lv[app.level].jumps += j;
+ progress.jumps += j;
+ }
+}
+
+void play_flush(void) { flush_jumps(); }
+
+static void unshake(void) {
+ if (!shake_applied) return;
+ app.g.cam_x -= shake_dx;
+ app.g.cam_y -= shake_dy;
+ shake_applied = false;
+}
+
+static void shake(float t, float amp) {
+ if (progress.options & OPT_NOSHAKE) return;
+ shake_t = t;
+ shake_amp = amp;
+}
+
+static void begin_attempt(bool first) {
+ unshake();
+ if (!first && app.practice && app.checkpoint_count) {
+ game_load_checkpoint(&app.g, &app.checkpoints[app.checkpoint_count - 1]);
+ } else {
+ game_start(&app.g, &app.L, first);
+ }
+ app.attempt++;
+ app.attempt_x = first ? VIEW_W / 2 : app.g.p.x + 150;
+ app.attempt_y = app.g.cam_y + 150;
+ jumps_counted = app.g.jumps;
+ if (!app.testing) {
+ progress.lv[app.level].attempts++;
+ progress.attempts++;
+ }
+ fx_reset();
+ app.death_t = 0;
+ app.auto_check_t = 0;
+ respawn_phase = first ? 0 : 8;
+ respawn_t = 0;
+}
+
+bool play_start(int level, bool practice, bool testing) {
+ app.level = level;
+ app.practice = practice;
+ app.testing = testing;
+ bool ok = level < LEVEL_COUNT ? level_load_builtin(&app.L, (unsigned)level) : editor_load_slot(level - LEVEL_COUNT, &app.L);
+ if (!ok) return false;
+ app.attempt = 0;
+ app.session_jumps = 0;
+ app.session_ticks = 0;
+ app.checkpoint_count = 0;
+ app.paused = false;
+ app.end_menu = false;
+ popup = POP_NONE;
+ shake_t = 0;
+ shake_applied = false;
+ if (level < LEVEL_COUNT && !testing) progress.last_level = (uint8_t)level;
+ begin_attempt(true);
+ return true;
+}
+
+static void place_checkpoint(void) {
+ if (app.g.dead || app.g.complete || app.g.ending) return;
+ if (app.checkpoint_count == MAX_CHECKPOINTS) {
+ memmove(app.checkpoints, app.checkpoints + 1, sizeof(Checkpoint) * (MAX_CHECKPOINTS - 1));
+ app.checkpoint_count--;
+ }
+ game_save_checkpoint(&app.g, &app.checkpoints[app.checkpoint_count++]);
+ app.auto_check_t = 0;
+}
+
+static void leave_level(void) {
+ flush_jumps();
+ if (!app.testing) app_save_progress();
+ app_go(app.testing ? SCR_EDITOR : app.level < LEVEL_COUNT ? SCR_SELECT : SCR_CREATOR);
+}
+
+static void on_death(void) {
+ int pct = (int)game_progress(&app.g);
+ flush_jumps();
+ death_len = 1.0f;
+ if (!app.testing) {
+ LevelStat *s = &progress.lv[app.level];
+ if (app.practice) {
+ if (pct > s->practice) s->practice = (uint8_t)pct;
+ } else if (pct > s->normal) {
+ s->normal = (uint8_t)pct;
+ char buf[24] = "NEW BEST!\n";
+ int n = gfx_format_uint(buf + 10, (unsigned long)pct);
+ buf[10 + n] = '%';
+ buf[11 + n] = 0;
+ gfx_layer_build(FONT_HUGE, buf);
+ gfx_layer_line_color(0, rgb(255, 255, 110), rgb(255, 140, 0));
+ gfx_layer_line_color(1, 0xffff, 0xffff);
+ popup = POP_NEWBEST;
+ popup_t = 0;
+ death_len = 1.4f;
+ }
+ }
+ if (!app.practice) shake(0.15f, 1);
+}
+
+static void init_rays(void) {
+ float angles[8];
+ for (int i = 0; i < 8; i++) angles[i] = -135 + i * 11.25f;
+ for (int i = 7; i > 0; i--) {
+ int j = (int)(frand() * (i + 1));
+ if (j > i) j = i;
+ float t = angles[i]; angles[i] = angles[j]; angles[j] = t;
+ }
+ for (int i = 0; i < 8; i++) {
+ rays[i].delay = i * 0.195f + 0.04f + 0.04f * (frand() * 2 - 1);
+ rays[i].h = 30 + 20 * (frand() * 2 - 1);
+ rays[i].dur = 0.18f + 0.04f * (frand() * 2 - 1);
+ float a = 155 + 100 * (frand() * 2 - 1);
+ rays[i].alpha = a < 0 ? 0 : a > 255 ? 255 : a;
+ rays[i].angle = angles[i] + 11.25f * frand() + 90;
+ }
+ rays_t = 0;
+ rays_on = true;
+ rays_fading = false;
+}
+
+static void on_complete(void) {
+ flush_jumps();
+ app.complete_t = 0;
+ phase2 = false;
+ rings_a = rings_b = fireworks = 0;
+ coins_run = coins_new = 0;
+ for (unsigned k = 0; k < app.L.coin_count; k++)
+ if (game_used(&app.g, app.L.coin_obj[k])) coins_run |= (uint8_t)(1u << k);
+ stars_new = false;
+ if (!app.testing) {
+ LevelStat *s = &progress.lv[app.level];
+ if (app.practice) {
+ s->practice = 100;
+ } else {
+ stars_new = s->normal < 100 && app.level < LEVEL_COUNT && app.L.stars;
+ s->normal = 100;
+ coins_new = coins_run & (uint8_t)~s->coins;
+ s->coins |= coins_run;
+ }
+ app_save_progress();
+ }
+ msg_index = (int)(frand() * (sizeof(complete_msgs) / sizeof(complete_msgs[0])));
+ rays_on = false;
+ if (app.practice) {
+ app.complete_t = FIREWORK_TIME;
+ } else {
+ shake(FIREWORK_TIME, 3);
+ init_rays();
+ }
+}
+
+static void restart_session(void) {
+ app.attempt = 0;
+ app.session_jumps = 0;
+ app.session_ticks = 0;
+ app.checkpoint_count = 0;
+ app.end_menu = false;
+ popup = POP_NONE;
+ begin_attempt(true);
+}
+
+/* ------------------------------------------------------------ input */
+
+static void pause_tick(void) {
+ if (app_hit(K_LEFT)) app.sel = (app.sel + 3) % 4;
+ if (app_hit(K_RIGHT)) app.sel = (app.sel + 1) % 4;
+ if (app_hit(K_BACK)) { app.paused = false; return; }
+ if (!app_accept()) return;
+ switch (app.sel) {
+ case PAUSE_PRACTICE:
+ flush_jumps();
+ app.practice = !app.practice;
+ app.checkpoint_count = 0;
+ app.paused = false;
+ begin_attempt(false);
+ break;
+ case PAUSE_RESUME: app.paused = false; break;
+ case PAUSE_MENU: leave_level(); break;
+ default:
+ flush_jumps();
+ app.paused = false;
+ begin_attempt(false);
+ break;
+ }
+}
+
+static void end_tick(void) {
+ if (leaving || end_t < 0.4f) return;
+ if (app_hit(K_LEFT | K_RIGHT)) end_sel ^= 1;
+ if (app_accept() || app_hit(K_BACK)) {
+ leaving = true;
+ leave_t = 0;
+ leave_action = app_hit(K_BACK) ? 1 : end_sel;
+ }
+}
+
+void play_tick(void) {
+ unshake();
+ if (app.fading_out || app.fade > 0.05f) return;
+ if (app.end_menu) { end_tick(); return; }
+ if (app.paused) { pause_tick(); return; }
+ Game *g = &app.g;
+ if (app_hit(K_BACK) && !g->complete) {
+ app.paused = true;
+ app.sel = PAUSE_RESUME;
+ app.pause_t = 0;
+ return;
+ }
+ if (g->dead || g->complete) return;
+ if (app.practice) {
+ if (app_hit(K_CHECK)) place_checkpoint();
+ if (app_hit(K_ERASE) && app.checkpoint_count) app.checkpoint_count--;
+ }
+ bool hold = (app.keys & (K_OK | K_EXE | K_UP)) != 0;
+ game_step(g, hold);
+ app.session_ticks++;
+ if (g->dead) {
+ on_death();
+ } else if (g->complete) {
+ on_complete();
+ } else if (app.practice && (progress.options & OPT_AUTOCHECK)) {
+ app.auto_check_t += ND_DT;
+ if (app.auto_check_t >= 2.0f && !g->ending && (g->p.mode == MODE_SHIP || (g->p.on_ground && !g->old_on_ground))) place_checkpoint();
+ }
+}
+
+/* ------------------------------------------------------------ per frame */
+
+static void complete_update(float dt) {
+ Game *g = &app.g;
+ float t = app.complete_t, wx = g->L->wall_x, wy = g->wall_y;
+ color_t c1 = white_if_black(app_p1()), c2 = white_if_black(app_p2());
+ if (!app.practice) {
+ while (rings_a < 5 && t >= rings_a * 0.05f) { fx_circle_world(wx, wy, CE_RING_BIG, c1); rings_a++; }
+ }
+ if (t >= FIREWORK_TIME && !phase2) {
+ phase2 = true;
+ rays_fading = true;
+ rays_fade_t = 0;
+ gfx_layer_build(FONT_HUGE, app.practice ? "PRACTICE COMPLETE!" : "LEVEL COMPLETE!");
+ popup = POP_COMPLETE;
+ popup_t = 0;
+ fx_circle_world(wx, wy, CE_WALL2, c1);
+ float cx = g->cam_x + VIEW_W / 2, cy = g->cam_y + VIEW_H / 2 - GROUND_OFFSET;
+ fx_circle_world(cx, cy, CE_TITLE, c1);
+ fx_burst_world(cx, cy, PE_COMPLETE, c1, 100);
+ fx_burst_world(cx, cy, PE_COMPLETE, c2, 100);
+ }
+ if (phase2 && !app.practice) {
+ float u = t - FIREWORK_TIME;
+ while (rings_b < 5 && u >= rings_b * 0.05f) { fx_circle_world(wx, wy, CE_RING_BIG, c1); rings_b++; }
+ while (t <= MENU_TIME && u >= fireworks * 0.23f) {
+ float fx_ = g->cam_x + 100 + frand() * (VIEW_W - 200), fy = g->cam_y - GROUND_OFFSET + frand() * VIEW_H;
+ fx_circle_world(fx_, fy, CE_FIREWORK, c2);
+ fx_burst_world(fx_, fy, PE_FIREWORK, c2, 25);
+ fireworks++;
+ }
+ }
+ if (t >= MENU_TIME && !app.end_menu) {
+ app.end_menu = true;
+ end_t = 0;
+ end_sel = 0;
+ leaving = false;
+ }
+ app.complete_t += dt;
+ if (rays_on) {
+ rays_t += dt;
+ if (rays_fading) {
+ rays_fade_t += dt;
+ if (rays_fade_t > 0.4f) rays_on = false;
+ }
+ }
+}
+
+void play_frame(float dt) {
+ Game *g = &app.g;
+ if (app.paused) {
+ app.pause_t += dt;
+ } else {
+ fx_update(g, dt, app_p1(), app_p2(), app.practice);
+ if (g->dead) {
+ app.death_t += dt;
+ if (app.death_t >= death_len) begin_attempt(false);
+ }
+ if (respawn_phase > 0) {
+ if (respawn_t <= 0 && (respawn_phase & 1) == 0) fx_circle_world(g->p.x, g->p.y, CE_RESPAWN, white_if_black(app_p1()));
+ respawn_t += dt;
+ if (respawn_t >= 0.05f) { respawn_t = 0; respawn_phase--; }
+ }
+ if (g->complete) complete_update(dt);
+ if (popup) popup_t += dt;
+ if (app.end_menu) {
+ end_t += dt;
+ if (leaving) {
+ leave_t += dt;
+ if (leave_t >= 0.5f) {
+ leaving = false;
+ if (leave_action == 0) restart_session();
+ else { app.end_menu = false; leave_level(); }
+ }
+ }
+ }
+ if (shake_t > 0) {
+ shake_t -= dt;
+ shake_dx = shake_amp * (frand() * 2 - 1);
+ shake_dy = shake_amp * (frand() * 2 - 1);
+ g->cam_x += shake_dx;
+ g->cam_y += shake_dy;
+ shake_applied = true;
+ }
+ }
+ memset(&opts, 0, sizeof(opts));
+ opts.p1 = app_p1();
+ opts.p2 = app_p2();
+ opts.practice = app.practice;
+ opts.show_percent = (progress.options & OPT_PERCENT) != 0;
+ opts.show_bar = (progress.options & OPT_BAR) != 0;
+ opts.low_detail = (progress.options & OPT_LOWDETAIL) != 0;
+ opts.hide_player = g->complete || (respawn_phase > 0 && (respawn_phase & 1) == 0);
+ opts.attempt = app.attempt;
+ opts.attempt_x = app.attempt_x;
+ opts.attempt_y = app.attempt_y;
+ opts.time = g->tick / (float)ND_HZ;
+ opts.checkpoints = app.checkpoints;
+ opts.checkpoint_count = app.practice ? app.checkpoint_count : 0;
+ opts.coins_saved = app.testing ? 0 : progress.lv[app.level].coins;
+ scene_prepare(g, &opts);
+}
+
+/* ------------------------------------------------------------ drawing */
+
+static void draw_rays(void) {
+ const Game *g = &app.g;
+ float ox = g->L->wall_x + 30, oy = g->wall_y, len = 632;
+ color_t c = app_p1() ? app_p1() : app_p2();
+ for (int i = 0; i < 8; i++) {
+ const Ray *r = &rays[i];
+ float el = rays_t - r->delay;
+ if (el < 0) continue;
+ float t = el / r->dur;
+ if (t > 1) t = 1;
+ t = t * (2 - t);
+ float a = r->alpha;
+ if (rays_fading) a *= fmaxf(0, 1 - rays_fade_t / 0.4f);
+ float w0 = r->h / 4, w1 = w0 + (r->h - w0) * t, l = len * t;
+ float ca = cosf(r->angle * 3.14159265f / 180), sa = sinf(r->angle * 3.14159265f / 180);
+ float lx[4] = {0, 0, -l, -l}, ly[4] = {w0 / 2, -w0 / 2, -w1 / 2, w1 / 2}, xy[8];
+ for (int k = 0; k < 4; k++) {
+ float wx = ox + lx[k] * ca - ly[k] * sa, wy = oy + lx[k] * sa + ly[k] * ca;
+ xy[2 * k] = wx_to_sx(g, wx);
+ xy[2 * k + 1] = wy_to_sy(g, wy);
+ }
+ gfx_poly(xy, 4, c, (unsigned)(a * 0.8f), BLEND_ADD);
+ }
+}
+
+static void draw_popup(void) {
+ float s;
+ if (popup == POP_COMPLETE) {
+ if (popup_t < 0.66f) s = 0.01f + 1.09f * ui_ease_elastic_out(popup_t / 0.66f, 0.3f);
+ else if (popup_t < 1.54f) s = 1.1f;
+ else if (popup_t < 1.76f) { float u = (popup_t - 1.54f) / 0.22f; s = 1.1f - 1.09f * u * u; }
+ else { popup = POP_NONE; return; }
+ color_t top = app.practice ? rgb(170, 255, 255) : rgb(210, 255, 90), bot = app.practice ? rgb(0, 200, 255) : rgb(60, 200, 0);
+ gfx_layer_draw(160, 116, (int)(s * 256), top, bot, 256);
+ } else if (popup == POP_NEWBEST) {
+ if (popup_t < 0.4f) s = 0.01f + 0.99f * ui_ease_elastic_out(popup_t / 0.4f, 0.3f);
+ else if (popup_t < 1.1f) s = 1;
+ else if (popup_t < 1.3f) { float u = (popup_t - 1.1f) / 0.2f; s = 1 - 0.99f * u * u; }
+ else { popup = POP_NONE; return; }
+ gfx_layer_draw(160, 112, (int)(s * 256), 0xffff, 0xffff, 256);
+ }
+}
+
+static float sel_scale(int id, int sel) { return id == sel ? 1.12f + 0.03f * sinf(app.t * 6) : 1.0f; }
+
+static void pause_draw(void) {
+ ui_dim(70);
+ ui_window_dark(10, 8, 300, 224, 130);
+ ui_title(FONT_BIG, 160, 34, app.L.name);
+ const LevelStat *s = &progress.lv[app.level];
+ ui_title(FONT_SMALL, 160, 56, "NORMAL MODE");
+ ui_progress_bar(160, 67, 210, 14, app.testing ? 0 : s->normal, rgb(0, 255, 0), true);
+ ui_title(FONT_SMALL, 160, 90, "PRACTICE MODE");
+ ui_progress_bar(160, 101, 210, 14, app.testing ? 0 : s->practice, rgb(0, 255, 255), true);
+ unsigned nc = level_coins();
+ if (nc && !app.testing)
+ for (unsigned i = 0; i < nc; i++)
+ gfx_sprite((s->coins >> i & 1) ? SPR_COIN_UI : SPR_COIN_UI_EMPTY, 160 + ((int)i * 2 - (int)nc + 1) * 12, 126, 0, 0xffff, 256, BLEND_NORMAL);
+ ui_sprite(app.practice ? SPR_BTN_NORMAL : SPR_BTN_PRACTICE, 56, 176, sel_scale(PAUSE_PRACTICE, app.sel), 256);
+ ui_sprite(SPR_BTN_RESUME, 130, 176, sel_scale(PAUSE_RESUME, app.sel), 256);
+ ui_sprite(SPR_BTN_MENU, 204, 176, sel_scale(PAUSE_MENU, app.sel), 256);
+ ui_sprite(SPR_BTN_REPLAY, 268, 176, sel_scale(PAUSE_REPLAY, app.sel), 256);
+ static const char *const hints[4] = {"PRACTICE MODE", "RESUME", "MENU", "RESTART"};
+ const char *h = hints[app.sel];
+ if (app.sel == PAUSE_PRACTICE && app.practice) h = "NORMAL MODE";
+ gfx_text_center(FONT_SMALL, 160, 222, h, rgb(255, 255, 140), rgb(255, 200, 0), 256);
+}
+
+static void draw_chain(int x, int y0, int y1) {
+ for (int y = y0; y < y1; y += 12) {
+ gfx_round_rect(x - 4, y, 8, 11, 3, rgb(60, 60, 64), 256);
+ gfx_round_rect(x - 3, y + 1, 6, 9, 2, rgb(190, 190, 200), 256);
+ gfx_round_rect(x - 1, y + 3, 2, 5, 1, rgb(60, 60, 64), 256);
+ }
+}
+
+static void end_draw(void) {
+ float drop = ui_ease_bounce_out(end_t / 1.0f);
+ float cy = -100 + 224 * drop;
+ if (leaving) {
+ float u = leave_t / 0.5f;
+ cy += (-130 - cy) * u * u;
+ }
+ ui_dim((unsigned)(fminf(end_t, 0.6f) * 256 * (leaving ? 1 - leave_t / 0.5f : 1)));
+ int y = (int)cy, top = y - 100;
+ draw_chain(64, -8, top + 6);
+ draw_chain(256, -8, top + 6);
+ ui_window_navy(26, top, 268, 204);
+ y -= 6;
+ if (app.practice) gfx_text_center(FONT_BIG, 160, y - 66, "PRACTICE COMPLETE!", rgb(170, 255, 255), rgb(0, 200, 255), 256);
+ else gfx_text_center(FONT_BIG, 160, y - 66, "LEVEL COMPLETE!", rgb(210, 255, 90), rgb(60, 200, 0), 256);
+ char buf[32];
+ int n;
+ memcpy(buf, "ATTEMPTS: ", 10);
+ gfx_format_uint(buf + 10, app.attempt);
+ ui_gold(FONT_BIG, 160, y - 42, buf);
+ memcpy(buf, "JUMPS: ", 7);
+ gfx_format_uint(buf + 7, app.session_jumps);
+ ui_gold(FONT_BIG, 160, y - 24, buf);
+ unsigned secs = app.session_ticks / ND_HZ;
+ memcpy(buf, "TIME: ", 6);
+ n = 6;
+ if (secs >= 3600) { n += gfx_format_uint(buf + n, secs / 3600); buf[n++] = ':'; }
+ buf[n++] = (char)('0' + secs / 600 % 6);
+ buf[n++] = (char)('0' + secs / 60 % 10);
+ buf[n++] = ':';
+ buf[n++] = (char)('0' + secs % 60 / 10);
+ buf[n++] = (char)('0' + secs % 10);
+ buf[n] = 0;
+ ui_gold(FONT_BIG, 160, y - 6, buf);
+ unsigned nc = level_coins();
+ if (app.practice) {
+ ui_title(FONT_SMALL, 160, y + 14, "WELL DONE... NOW TRY TO COMPLETE");
+ ui_title(FONT_SMALL, 160, y + 26, "IT WITHOUT ANY CHECKPOINTS!");
+ } else if (nc && !app.testing) {
+ for (unsigned i = 0; i < nc; i++) {
+ int x = 160 + ((int)i * 2 - (int)nc + 1) * 22;
+ bool got = coins_run >> i & 1;
+ float sc = 1;
+ if ((coins_new >> i & 1)) {
+ float t = end_t - 0.6f - 0.35f * (float)__builtin_popcount(coins_new & ((1u << i) - 1));
+ if (t < 0) got = false;
+ else if (t < 0.35f) sc = 3 - 2 * ui_ease_bounce_out(t / 0.35f);
+ }
+ if (got && sc > 1.01f) gfx_sprite(SPR_COIN_BIG_EMPTY, x, y + 20, 0, 0xffff, 256, BLEND_NORMAL);
+ ui_sprite(got ? SPR_COIN_BIG : SPR_COIN_BIG_EMPTY, (float)x, (float)(y + 20), sc, 256);
+ }
+ } else {
+ ui_title(FONT_BIG, 160, y + 26, complete_msgs[msg_index]);
+ }
+ if (stars_new) {
+ float t = end_t - 0.6f - 0.35f * (float)__builtin_popcount(coins_new);
+ if (t > 0) {
+ float sc = t < 0.35f ? 3 - 2 * ui_ease_bounce_out(t / 0.35f) : 1;
+ ui_sprite(SPR_STAR_BIG, 262, (float)(y - 24), sc, (unsigned)fminf(256, t / 0.1f * 256));
+ char sb[8] = "+";
+ gfx_format_uint(sb + 1, app.L.stars);
+ if (t > 0.1f) gfx_text_center(FONT_BIG, 262, y + 2, sb, 0xffff, 0xffff, 256);
+ }
+ }
+ float bs = ui_ease_elastic_out(end_t / 1.0f, 0.3f) * 0.9f;
+ ui_sprite(SPR_BTN_REPLAY, 112, (float)(y + 68), bs * sel_scale(0, end_sel), 256);
+ ui_sprite(SPR_BTN_MENU, 208, (float)(y + 68), bs * sel_scale(1, end_sel), 256);
+}
+
+void play_draw(void) {
+ scene_draw();
+ if (rays_on) draw_rays();
+ fx_draw_screen();
+ if (popup) draw_popup();
+ if (!app.paused && !app.end_menu && !app.g.complete) gfx_sprite(SPR_BTN_PAUSE, 302, 16, 0, 0xffff, 110, BLEND_NORMAL);
+ if (app.paused) pause_draw();
+ if (app.end_menu) end_draw();
+}
diff --git a/games/numdash/src/save.c b/games/numdash/src/save.c
new file mode 100644
index 00000000..107f880e
--- /dev/null
+++ b/games/numdash/src/save.c
@@ -0,0 +1,344 @@
+/* Progress, settings and custom levels in Epsilon's record storage.
+ *
+ * Epsilon caches a pointer to the last record it looked up, so moving a
+ * record behind its back could make it read or write the wrong bytes after
+ * NumDash exits. Records are therefore only ever appended, rewritten in
+ * place with the same size, or resized when they are the very last one. */
+#include "save.h"
+#include <string.h>
+
+uint32_t nd_crc32(const uint8_t *p, size_t n) {
+ uint32_t c = ~0u;
+ while (n--) {
+ c ^= *p++;
+ for (int j = 0; j < 8; j++) c = (c >> 1) ^ (0xedb88320u & (0u - (c & 1)));
+ }
+ return ~c;
+}
+static unsigned rd16(const uint8_t *p) { return p[0] | (unsigned)p[1] << 8; }
+static uint32_t rd32(const uint8_t *p) { return rd16(p) | (uint32_t)rd16(p + 2) << 16; }
+static void wr16(uint8_t *p, unsigned v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); }
+static void wr32(uint8_t *p, uint32_t v) { wr16(p, v & 0xffff); wr16(p + 2, v >> 16); }
+
+/* ------------------------------------------------------------ progress */
+
+void progress_defaults(Progress *p) {
+ memset(p, 0, sizeof(*p));
+ p->color1 = 0;
+ p->color2 = 3;
+ p->options = OPT_PERCENT | OPT_BAR;
+}
+
+void progress_encode(const Progress *p, uint8_t out[PROGRESS_BYTES]) {
+ memset(out, 0, PROGRESS_BYTES);
+ memcpy(out, "NDS1", 4);
+ out[8] = 1;
+ out[9] = LEVEL_COUNT;
+ out[10] = CUSTOM_SLOTS;
+ uint8_t *q = out + 12;
+ for (int i = 0; i < LEVEL_SLOTS; i++, q += 12) {
+ const LevelStat *s = &p->lv[i];
+ q[0] = s->normal; q[1] = s->practice; q[2] = s->coins;
+ wr32(q + 4, s->attempts);
+ wr32(q + 8, s->jumps);
+ }
+ wr32(q, p->attempts); wr32(q + 4, p->jumps);
+ q[8] = p->color1; q[9] = p->color2; q[10] = p->options; q[11] = p->last_level;
+ wr32(out + 4, nd_crc32(out + 8, PROGRESS_BYTES - 8));
+}
+
+bool progress_decode(Progress *p, const uint8_t *in, size_t len) {
+ if (len < PROGRESS_BYTES || memcmp(in, "NDS1", 4) || rd32(in + 4) != nd_crc32(in + 8, PROGRESS_BYTES - 8)) return false;
+ if (in[8] != 1 || in[9] != LEVEL_COUNT || in[10] != CUSTOM_SLOTS) return false;
+ const uint8_t *q = in + 12;
+ for (int i = 0; i < LEVEL_SLOTS; i++, q += 12)
+ if (q[0] > 100 || q[1] > 100 || q[2] > 7) return false;
+ progress_defaults(p);
+ q = in + 12;
+ for (int i = 0; i < LEVEL_SLOTS; i++, q += 12) {
+ LevelStat *s = &p->lv[i];
+ s->normal = q[0]; s->practice = q[1]; s->coins = q[2];
+ s->attempts = rd32(q + 4);
+ s->jumps = rd32(q + 8);
+ }
+ p->attempts = rd32(q); p->jumps = rd32(q + 4);
+ p->color1 = q[8] < 42 ? q[8] : 0;
+ p->color2 = q[9] < 42 ? q[9] : 3;
+ p->options = q[10];
+ p->last_level = q[11] < LEVEL_SLOTS ? q[11] : 0;
+ return true;
+}
+
+/* ------------------------------------------------------------ custom levels */
+
+static size_t put_varint(uint8_t *out, size_t pos, size_t cap, uint32_t v) {
+ do {
+ if (pos >= cap) return 0;
+ out[pos++] = (uint8_t)((v & 127) | (v > 127 ? 128 : 0));
+ v >>= 7;
+ } while (v);
+ return pos;
+}
+static bool get_varint(const uint8_t *in, size_t len, size_t *pos, uint32_t *v) {
+ uint32_t r = 0;
+ for (int shift = 0; shift < 21; shift += 7) {
+ if (*pos >= len) return false;
+ uint8_t b = in[(*pos)++];
+ r |= (uint32_t)(b & 127) << shift;
+ if (!(b & 128)) { *v = r; return true; }
+ }
+ return false;
+}
+
+size_t custom_encode(const LObj *objs, unsigned count, const CustomMeta *m, uint8_t *out, size_t cap) {
+ if (cap < 16 || count > CUSTOM_MAX) return 0;
+ memcpy(out, "NDL1", 4);
+ wr16(out + 10, count);
+ wr16(out + 12, m->end_x);
+ out[14] = m->theme;
+ out[15] = m->flags;
+ size_t n = 16;
+ int px = 0, py = 0;
+ for (unsigned i = 0; i < count; i++) {
+ const LObj *o = &objs[i];
+ if (o->x < px) return 0;
+ int dy = o->y - py;
+ n = put_varint(out, n, cap, (uint32_t)(o->x - px));
+ if (n) n = put_varint(out, n, cap, dy >= 0 ? (uint32_t)dy * 2 : (uint32_t)(-dy) * 2 - 1);
+ if (!n || n + 2 > cap) return 0;
+ out[n++] = o->type;
+ out[n++] = o->xf;
+ px = o->x;
+ py = o->y;
+ }
+ wr16(out + 8, (unsigned)(n - 16));
+ wr32(out + 4, nd_crc32(out + 8, n - 8));
+ return n;
+}
+
+bool custom_decode(const uint8_t *in, size_t len, LObj *objs, unsigned cap, CustomMeta *m) {
+ if (len < 16 || memcmp(in, "NDL1", 4)) return false;
+ size_t n = 16 + rd16(in + 8);
+ unsigned count = rd16(in + 10);
+ if (n > len || rd32(in + 4) != nd_crc32(in + 8, n - 8) || count > CUSTOM_MAX || count > cap) return false;
+ size_t pos = 16;
+ int x = 0, y = 0;
+ for (unsigned i = 0; i < count; i++) {
+ uint32_t dx, zy;
+ if (!get_varint(in, n, &pos, &dx) || !get_varint(in, n, &pos, &zy) || pos + 2 > n) return false;
+ x += (int)dx;
+ y += (zy & 1) ? -(int)((zy + 1) / 2) : (int)(zy / 2);
+ uint8_t type = in[pos++], xf = in[pos++];
+ if (x > 0xffff || y < -600 || y > 3000 || !type || type >= OT_COUNT || (xf & 0xf0)) return false;
+ objs[i] = (LObj){(uint16_t)x, (int16_t)y, type, xf};
+ }
+ if (pos != n) return false;
+ m->count = (uint16_t)count;
+ m->end_x = (uint16_t)rd16(in + 12);
+ m->theme = in[14];
+ m->flags = in[15];
+ m->exists = true;
+ return true;
+}
+
+/* ------------------------------------------------------------ legacy saves */
+
+static uint8_t type_for_gd(unsigned id) {
+ for (unsigned t = 1; t < OT_COUNT; t++) if (objdefs[t].gd_id == id) return (uint8_t)t;
+ return 0;
+}
+
+bool legacy_decode(const uint8_t *in, size_t size, Progress *p, LObj *objs, unsigned cap, unsigned counts[CUSTOM_SLOTS],
+ CustomMeta metas[CUSTOM_SLOTS]) {
+ if (size < 108) return false;
+ bool v2 = !memcmp(in, "NDASH002", 8);
+ if (!v2 && memcmp(in, "NDASH003", 8)) return false;
+ if (rd32(in + 8) != size || nd_crc32(in + 16, size - 16) != rd32(in + 12)) return false;
+ unsigned stride = v2 ? 12 : 8;
+ for (size_t n = 16; n < 86; n += 7) if (in[n] > 100 || in[n + 1] > 100 || in[n + 2] > 3) return false;
+ progress_defaults(p);
+ /* The first four built-in levels are unchanged; the old 5-7 were others. */
+ for (int i = 0; i < 4; i++) {
+ const uint8_t *q = in + 16 + i * 7;
+ p->lv[i].normal = q[0];
+ p->lv[i].practice = q[1];
+ p->lv[i].coins = (uint8_t)((1u << q[2]) - 1);
+ p->lv[i].attempts = rd32(q + 3);
+ }
+ for (int i = 0; i < 10; i++) p->attempts += rd32(in + 16 + i * 7 + 3);
+ if (!(v2 ? 1 : in[87])) p->options &= (uint8_t)~OPT_PERCENT;
+ if (in[88]) p->options |= OPT_FPS;
+ size_t n = 90;
+ unsigned used = 0;
+ for (int s = 0; s < CUSTOM_SLOTS; s++) {
+ if (n + 6 > size) return false;
+ unsigned count = rd16(in + n), length = rd16(in + n + 2);
+ metas[s] = (CustomMeta){0, (uint16_t)length, in[n + 4], 0, count > 0};
+ counts[s] = 0;
+ n += 6;
+ for (unsigned j = 0; j < count; j++, n += stride) {
+ if (n + stride > size) return false;
+ int x = (int16_t)rd16(in + n), y = (int16_t)rd16(in + n + 2);
+ uint8_t t = type_for_gd(rd16(in + n + 4));
+ if (!t || x < 0 || used >= cap) continue;
+ objs[used++] = (LObj){(uint16_t)x, (int16_t)y, t, (uint8_t)(in[n + 6] & 3)};
+ counts[s]++;
+ }
+ metas[s].count = (uint16_t)counts[s];
+ }
+ return true;
+}
+
+/* ------------------------------------------------------------ records */
+
+/* Locates `name`; `end` is the offset of the terminating zero size. Rejects
+ * malformed storage (overlong records, missing names, duplicates). */
+static bool scan(const uint8_t *a, size_t size, const char *name, size_t *found, size_t *end) {
+ if (!a || !name || size < 2) return false;
+ *found = SIZE_MAX;
+ size_t p = 0;
+ while (p + 2 <= size) {
+ size_t len = rd16(a + p);
+ if (!len) { *end = p; return true; }
+ if (len < 4 || len > size - p - 2) return false;
+ const uint8_t *zero = memchr(a + p + 2, 0, len - 2);
+ if (!zero) return false;
+ if (!strcmp((const char *)a + p + 2, name)) {
+ if (*found != SIZE_MAX) return false;
+ *found = p;
+ }
+ p += len;
+ }
+ return false;
+}
+
+const uint8_t *storage_read(const uint8_t *a, size_t size, const char *name, size_t *len) {
+ size_t found, end;
+ if (!scan(a, size, name, &found, &end) || found == SIZE_MAX) return NULL;
+ size_t head = 2 + strlen(name) + 1, total = rd16(a + found);
+ if (total < head) return NULL;
+ *len = total - head;
+ return a + found + head;
+}
+
+bool storage_put(uint8_t *a, size_t size, const char *name, const uint8_t *data, size_t len, size_t granule) {
+ size_t found, end, nlen = name ? strlen(name) : 0;
+ if (!data || !nlen || nlen > 32 || !scan(a, size, name, &found, &end)) return false;
+ size_t head = 2 + nlen + 1, need = head + len;
+ if (granule < 1) granule = 1;
+ size_t rounded = (need + granule - 1) / granule * granule;
+ if (need > 0xffff) return false;
+ if (rounded > 0xffff) rounded = need;
+ size_t at, total;
+ if (found != SIZE_MAX) {
+ size_t old = rd16(a + found);
+ bool last = found + old == end;
+ if (need <= old && !(last && rounded < old)) {
+ total = old; /* same size, padded */
+ } else if (last) {
+ total = rounded; /* only the end marker moves */
+ if (found + total + 2 > size) {
+ total = need;
+ if (found + total + 2 > size) return false;
+ }
+ } else {
+ return false;
+ }
+ at = found;
+ if (total != old) wr16(a + found + total, 0);
+ } else {
+ total = rounded;
+ if (end + total + 2 > size) total = need;
+ if (end + total + 2 > size) return false;
+ at = end;
+ wr16(a + at + total, 0);
+ }
+ wr16(a + at, (unsigned)total);
+ memcpy(a + at + 2, name, nlen + 1);
+ memcpy(a + at + head, data, len);
+ memset(a + at + head + len, 0, total - head - len);
+ return true;
+}
+
+bool storage_remove_last(uint8_t *a, size_t size, const char *name) {
+ size_t found, end;
+ if (!scan(a, size, name, &found, &end) || found == SIZE_MAX) return false;
+ if (found + rd16(a + found) != end) return false;
+ wr16(a + found, 0);
+ return true;
+}
+
+/* ------------------------------------------------------------ platform glue */
+
+#include "platform.h"
+
+static const char *slot_name(int slot) {
+ static const char *names[CUSTOM_SLOTS] = {"numdash1.ndl", "numdash2.ndl", "numdash3.ndl"};
+ return names[slot];
+}
+
+bool save_write_progress(const Progress *p) {
+ size_t size;
+ uint8_t *a = platform_storage(&size);
+ uint8_t buf[PROGRESS_BYTES];
+ progress_encode(p, buf);
+ if (!a || !storage_put(a, size, "numdash.nds", buf, sizeof(buf), 1)) return false;
+ platform_storage_commit();
+ return true;
+}
+
+static uint8_t level_buf[16 + CUSTOM_MAX * 8];
+
+bool save_write_custom(int slot, const LObj *objs, unsigned count, const CustomMeta *m) {
+ size_t size;
+ uint8_t *a = platform_storage(&size);
+ size_t n = custom_encode(objs, count, m, level_buf, sizeof(level_buf));
+ if (!a || !n || !storage_put(a, size, slot_name(slot), level_buf, n, 512)) return false;
+ platform_storage_commit();
+ return true;
+}
+
+bool save_read_custom(int slot, LObj *objs, unsigned cap, CustomMeta *m) {
+ size_t size, len;
+ const uint8_t *a = platform_storage(&size), *d;
+ if (!a || !(d = storage_read(a, size, slot_name(slot), &len))) return false;
+ return custom_decode(d, len, objs, cap, m);
+}
+
+bool save_load_all(Progress *p, CustomMeta metas[CUSTOM_SLOTS]) {
+ progress_defaults(p);
+ memset(metas, 0, sizeof(CustomMeta) * CUSTOM_SLOTS);
+ size_t size, len;
+ uint8_t *a = platform_storage(&size);
+ if (!a) return false;
+ const uint8_t *d = storage_read(a, size, "numdash.nds", &len);
+ if (d) {
+ bool ok = progress_decode(p, d, len);
+ for (int s = 0; s < CUSTOM_SLOTS; s++) {
+ CustomMeta m;
+ if (save_read_custom(s, level_objs, MAX_OBJECTS, &m)) metas[s] = m;
+ }
+ return ok;
+ }
+ d = storage_read(a, size, "numdash.ndd", &len);
+ if (!d) return true; /* first run */
+ unsigned counts[CUSTOM_SLOTS];
+ if (!legacy_decode(d, len, p, level_objs, MAX_OBJECTS, counts, metas)) { progress_defaults(p); return false; }
+ /* Everything is decoded: drop the old record if nothing follows it. */
+ storage_remove_last(a, size, "numdash.ndd");
+ unsigned first = 0;
+ for (int s = 0; s < CUSTOM_SLOTS; s++) {
+ if (counts[s]) {
+ CustomMeta m = metas[s];
+ unsigned last_x = level_objs[first + counts[s] - 1].x;
+ if (m.end_x < last_x + 300) m.end_x = (uint16_t)(last_x + 300 > 0xfff0 ? 0xfff0 : last_x + 300);
+ m.theme %= 6;
+ metas[s] = m;
+ if (!save_write_custom(s, level_objs + first, counts[s], &m)) metas[s].exists = false;
+ } else {
+ metas[s].exists = false;
+ }
+ first += counts[s];
+ }
+ return save_write_progress(p);
+}
diff --git a/games/numdash/src/save.h b/games/numdash/src/save.h
new file mode 100644
index 00000000..b86617b7
--- /dev/null
+++ b/games/numdash/src/save.h
@@ -0,0 +1,58 @@
+#ifndef NUMDASH_SAVE_H
+#define NUMDASH_SAVE_H
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#include "level.h"
+
+#define CUSTOM_SLOTS 3
+#define CUSTOM_MAX 800
+#define LEVEL_SLOTS (LEVEL_COUNT + CUSTOM_SLOTS)
+enum { OPT_PERCENT = 1, OPT_BAR = 2, OPT_FPS = 4, OPT_AUTOCHECK = 8, OPT_LOWDETAIL = 16, OPT_NOSHAKE = 32 };
+
+typedef struct {
+ uint8_t normal, practice, coins; /* best percentages, coin bits */
+ uint32_t attempts, jumps;
+} LevelStat;
+
+typedef struct {
+ LevelStat lv[LEVEL_SLOTS];
+ uint32_t attempts, jumps; /* totals */
+ uint8_t color1, color2, options, last_level;
+} Progress;
+
+typedef struct {
+ uint16_t count, end_x;
+ uint8_t theme, flags;
+ bool exists;
+} CustomMeta;
+
+void progress_defaults(Progress *p);
+/* Serialised progress record: fixed size so it never moves other records. */
+#define PROGRESS_BYTES 192
+void progress_encode(const Progress *p, uint8_t out[PROGRESS_BYTES]);
+bool progress_decode(Progress *p, const uint8_t *in, size_t len);
+/* Custom level record; returns bytes written or 0. */
+size_t custom_encode(const LObj *objs, unsigned count, const CustomMeta *m, uint8_t *out, size_t cap);
+bool custom_decode(const uint8_t *in, size_t len, LObj *objs, unsigned cap, CustomMeta *m);
+/* Reads a save of the previous NumDash release (NDASH002/003) into the new
+ * structures; custom objects are converted when their type still exists. */
+bool legacy_decode(const uint8_t *in, size_t len, Progress *p, LObj *objs, unsigned cap, unsigned counts[CUSTOM_SLOTS],
+ CustomMeta metas[CUSTOM_SLOTS]);
+
+/* Epsilon record storage (the arena excludes both magic words). */
+const uint8_t *storage_read(const uint8_t *a, size_t size, const char *name, size_t *len);
+/* Writes without moving any other record: a record is only resized when it
+ * is the last one; otherwise it keeps its size (padded) or the write fails.
+ * New records are appended with their size rounded up to `granule`. */
+bool storage_put(uint8_t *a, size_t size, const char *name, const uint8_t *data, size_t len, size_t granule);
+/* Removes a record only if it is the last one (nothing moves). */
+bool storage_remove_last(uint8_t *a, size_t size, const char *name);
+uint32_t nd_crc32(const uint8_t *data, size_t size);
+
+/* High level: platform storage. */
+bool save_load_all(Progress *p, CustomMeta metas[CUSTOM_SLOTS]);
+bool save_write_progress(const Progress *p);
+bool save_write_custom(int slot, const LObj *objs, unsigned count, const CustomMeta *m);
+bool save_read_custom(int slot, LObj *objs, unsigned cap, CustomMeta *m);
+#endif
diff --git a/games/numdash/src/scene.c b/games/numdash/src/scene.c
new file mode 100644
index 00000000..17fe21e9
--- /dev/null
+++ b/games/numdash/src/scene.c
@@ -0,0 +1,355 @@
+#include "scene.h"
+#include "fx.h"
+#include <math.h>
+#include <string.h>
+
+#define PX (2.0f / 3.0f) /* screen pixels per GD unit */
+#define FADE_W 75.0f
+
+/* ------------------------------------------------------------ background */
+
+void scene_background(color_t bg, float bg_x, float cam_y) {
+ const float tex = 0.9f, tile = 512 * tex;
+ float off = fmodf(bg_x * 0.1f, tile);
+ if (off < 0) off += tile;
+ float top = cam_y * 0.111f - 200;
+ int y0 = gfx_y0, y1 = gfx_y1;
+ for (int y = y0; y < y1; y++) {
+ float ty = (y + .5f - top) / tex;
+ if (ty < 0) ty = 0;
+ if (ty > 511) ty = 511;
+ float g = ty / 384.f;
+ if (g > 1) g = 1;
+ unsigned gi = (unsigned)(g * 256);
+ color_t gap = c_scale(bg, gi), sq = c_scale(bg, gi * 216 / 256), sh = c_scale(bg, gi * 182 / 256);
+ gfx_fill(0, y, GFX_W, 1, gap);
+ int ity = (int)ty;
+ for (float base = -off; base < GFX_W; base += tile) {
+ for (int k = 0; k < BG_RECTS; k++) {
+ const uint16_t *r = bg_rects[k];
+ if (ity < r[1] || ity >= r[1] + r[3]) continue;
+ int a = (int)floorf(base + r[0] * tex + .5f), b = (int)floorf(base + (r[0] + r[2]) * tex + .5f);
+ if (b <= 0 || a >= GFX_W) continue;
+ gfx_fill(a, y, b - a - 1, 1, sq);
+ gfx_fill(b - 1, y, 1, 1, sh);
+ }
+ }
+ }
+}
+
+static const uint8_t line_profile[23] = {3, 44, 87, 128, 170, 195, 204, 214, 223, 232, 241, 250, 243, 233, 224, 215, 206, 197, 176, 135, 92, 51, 9};
+
+/* Ground band whose top edge (or bottom edge for a ceiling) is at top_y. */
+void scene_ground(color_t g1, color_t line, float ground_x, int top_y, bool ceiling, bool shadows) {
+ const float tile = 128 * PX;
+ float off = fmodf(ground_x * PX, tile);
+ if (off < 0) off += tile;
+ int ya = ceiling ? 0 : top_y, yb = ceiling ? top_y : GFX_H;
+ if (ya < gfx_y0) ya = gfx_y0;
+ if (yb > gfx_y1) yb = gfx_y1;
+ for (int y = ya; y < yb; y++) {
+ float d = ceiling ? (top_y - 1 - y) : (y - top_y); /* depth in px */
+ float t = d * 1.5f; /* depth in units */
+ float in = t < 2 ? 1.0f : 0.85f - (t - 2) / 126.f * 0.65f;
+ if (in < 0.2f) in = 0.2f;
+ color_t base = c_scale(g1, (unsigned)(in * 256)), seam = c_scale(g1, (unsigned)((in + 0.13f > 1 ? 1 : in + 0.13f) * 256));
+ gfx_fill(0, y, GFX_W, 1, base);
+ for (float x = -off; x < GFX_W + tile; x += tile) {
+ int s = (int)floorf(x + .5f);
+ gfx_fill(s - 4, y, 8, 1, seam);
+ }
+ }
+ if (shadows) {
+ int h = ceiling ? top_y : GFX_H - top_y;
+ int y = ceiling ? 0 : top_y;
+ gfx_hgrad_alpha(0, y, 86, h, 0, 100, 0, BLEND_NORMAL);
+ gfx_hgrad_alpha(GFX_W - 86, y, 86, h, 0, 0, 100, BLEND_NORMAL);
+ }
+ /* floor line: additive, brightest in the middle of the screen */
+ int ly = ceiling ? top_y - 1 : top_y;
+ if (ly >= gfx_y0 - 1 && ly < gfx_y1 + 1) {
+ const int len = 296, x0 = (GFX_W - len) / 2;
+ for (int i = 0; i < len; i++) {
+ float f = i * 22.f / (len - 1);
+ int k = (int)f;
+ float fr = f - k;
+ unsigned a = (unsigned)(line_profile[k] * (1 - fr) + line_profile[k < 22 ? k + 1 : 22] * fr);
+ gfx_add(x0 + i, ly, 1, 1, line, a);
+ gfx_add(x0 + i, ceiling ? ly - 1 : ly + 1, 1, 1, line, a / 3);
+ }
+ }
+}
+
+/* ------------------------------------------------------------ objects */
+
+typedef struct {
+ int16_t x, y; /* anchor position, px */
+ uint8_t spr, xf, ct, alpha, layer, kind;
+ uint16_t scale; /* 256 = 1 */
+} Item;
+enum { K_SPRITE, K_SCALED, K_PLAYER };
+#define MAX_ITEMS 1100
+static Item items[MAX_ITEMS];
+static uint16_t order[MAX_ITEMS];
+static int nitems;
+static color_t tint_obj, tint_p1, tint_p2;
+static const Game *G;
+static SceneOpts O;
+static float player_sx, player_sy;
+static color_t bg_col, g1_col, line_col;
+static int ground_top, ceil_bottom, floor_bottom;
+static bool draw_gfx_grounds;
+
+color_t scene_channel(const Game *g, int ch) { return rgb(g->ch[ch].cur[0], g->ch[ch].cur[1], g->ch[ch].cur[2]); }
+
+static int fade_at(const Level *L, float x) {
+ int eff = 0;
+ for (unsigned k = 0; k < L->event_count; k++) {
+ const LevelEvent *e = &L->events[k];
+ if (e->x >= x) break;
+ if (e->kind == EV_FADE) eff = e->arg;
+ }
+ return eff;
+}
+
+static void push(int x, int y, int spr, int xf, int ct, int alpha, int layer, int kind, int scale) {
+ if (nitems >= MAX_ITEMS || spr < 0) return;
+ items[nitems++] = (Item){(int16_t)x, (int16_t)y, (uint8_t)spr, (uint8_t)xf, (uint8_t)ct, (uint8_t)(alpha > 255 ? 255 : alpha),
+ (uint8_t)layer, (uint8_t)kind, (uint16_t)scale};
+}
+
+static float pulse_amount(void) {
+ unsigned bpm = G && G->L->bpm ? G->L->bpm : 120;
+ float beat = O.time * bpm / 60.f;
+ float ph = beat - floorf(beat);
+ return ph < 0.25f ? 1 - ph * 4 : 0;
+}
+
+/* Rotate a part offset (units) by the object's transform. */
+static void part_offset(int xf, float dx, float dy, float *ox, float *oy) {
+ if (xf & XF_FLIPX) dx = -dx;
+ if (xf & XF_FLIPY) dy = -dy;
+ switch (xf & 3) {
+ case 1: *ox = dy; *oy = -dx; break; /* clockwise 90: (x,y) -> (y,-x) in y-up space */
+ case 2: *ox = -dx; *oy = -dy; break;
+ case 3: *ox = -dy; *oy = dx; break;
+ default: *ox = dx; *oy = dy; break;
+ }
+}
+
+void scene_prepare(const Game *g, const SceneOpts *o) {
+ G = g;
+ O = *o;
+ nitems = 0;
+ const Level *L = g->L;
+ bg_col = scene_channel(g, CH_BG);
+ g1_col = scene_channel(g, CH_G1);
+ line_col = scene_channel(g, CH_LINE);
+ tint_obj = scene_channel(g, CH_OBJ);
+ tint_p1 = o->p1;
+ tint_p2 = o->p2;
+ float cam_x = g->cam_x;
+ unsigned i = level_lower_bound(L, (int)(cam_x - 90));
+ float pulse = pulse_amount();
+ unsigned coin_frame = (unsigned)(o->time * 8) & 3;
+ for (; i < L->count && L->objs[i].x < cam_x + VIEW_W + 90; i++) {
+ const LObj *ob = &L->objs[i];
+ const ObjDef *d = &objdefs[ob->type];
+ if (d->special == SP_COIN && game_used(g, i)) continue;
+ if (o->low_detail && d->hit == HIT_NONE && !o->editor) continue;
+ float rel = ob->x - cam_x;
+ float fade = o->editor ? 1 : rel < 0 || rel > VIEW_W ? 0 : rel < FADE_W ? rel / FADE_W : rel > VIEW_W - FADE_W ? (VIEW_W - rel) / FADE_W : 1;
+ if (fade <= 0) continue;
+ float offx = 0, offy = 0, sc = 1;
+ if (fade < 1) {
+ int eff = fade_at(L, rel < VIEW_W / 2 ? ob->x + 75 : ob->x - (VIEW_W - PLAYER_SCREEN_X) + 75);
+ float off = (1 - fade) * 127.5f;
+ switch (eff) {
+ case 1: offy = -off; break; /* rises into place from below */
+ case 2: offy = off; break;
+ case 3: offx = -off; break;
+ case 4: offx = off; break;
+ case 5: sc = fade; break;
+ case 6: sc = 1 + (1 - fade) / 2; break;
+ default: break;
+ }
+ }
+ float wx = ob->x + offx, wy = ob->y + offy;
+ int alpha = (int)(fade * 255 + .5f);
+ if (d->special == SP_COIN && (o->coins_saved >> game_coin_index(L, i) & 1)) alpha = alpha * 2 / 5;
+ for (int k = 0; k < d->nparts; k++) {
+ const ObjPart *pt = &d->parts[k];
+ if (o->low_detail && pt->ctype >= CT_GLOW) continue;
+ int spr = pt->sprite;
+ if (pt->flags & PF_RANDOM3) spr += (int)(i % 3);
+ if (pt->flags & PF_COIN) spr += (int)coin_frame;
+ float ox, oy;
+ part_offset(ob->xf, pt->dx4 / 4.f * sc, pt->dy4 / 4.f * sc, &ox, &oy);
+ float sx = (wx + ox - cam_x) * PX, sy = 240 - (GROUND_OFFSET + wy + oy - g->cam_y) * PX;
+ int psc = (int)(sc * 256);
+ if (pt->flags & PF_PULSE) psc = (int)(psc * (1 + 0.22f * pulse));
+ int kind = psc != 256 ? K_SCALED : K_SPRITE;
+ push((int)floorf(sx + .5f), (int)floorf(sy + .5f), spr, ob->xf, pt->ctype, alpha, pt->layer, kind, psc);
+ }
+ }
+ /* the player */
+ player_sx = wx_to_sx(g, g->p.x);
+ player_sy = wy_to_sy(g, g->p.y);
+ if (!g->dead && !o->hide_player) push(0, 0, 0, 0, 0, 255, LAYER_PLAYER, K_PLAYER, 256);
+ /* sort by layer, stable */
+ uint16_t count[LAYER_COUNT + 1] = {0};
+ for (int k = 0; k < nitems; k++) count[items[k].layer + 1]++;
+ for (int k = 1; k <= LAYER_COUNT; k++) count[k] += count[k - 1];
+ for (int k = 0; k < nitems; k++) order[count[items[k].layer]++] = (uint16_t)k;
+ /* ground positions */
+ ground_top = (int)floorf(wy_to_sy(g, 0) + .5f);
+ draw_gfx_grounds = g->ground_gfx > 2;
+ floor_bottom = (int)floorf(240 - g->ground_gfx * PX + .5f);
+ ceil_bottom = (int)floorf(g->ground_gfx * PX + .5f);
+}
+
+static void tint_for(int ct, color_t *c, int *mode) {
+ *mode = BLEND_NORMAL;
+ switch (ct) {
+ case CT_OBJ: *c = tint_obj; break;
+ case CT_BLACK: *c = 0; break;
+ case CT_WHITE: *c = 0xffff; break;
+ case CT_P1ADD: *c = tint_p1; *mode = BLEND_ADD; break;
+ case CT_P2ADD: *c = tint_p2; *mode = BLEND_ADD; break;
+ case CT_GLOW: *c = tint_obj; *mode = BLEND_ADD; break;
+ case CT_GLOW_Y: *c = rgb(255, 255, 0); *mode = BLEND_ADD; break;
+ case CT_GLOW_B: *c = rgb(0, 255, 255); *mode = BLEND_ADD; break;
+ default: *c = rgb(255, 0, 255); *mode = BLEND_ADD; break;
+ }
+}
+
+void scene_draw_player_icon(int mode, float cx, float cy, float rot, float scale, color_t p1, color_t p2, bool upside, unsigned alpha) {
+ int x16 = (int)(cx * 16), y16 = (int)(cy * 16), a16 = (int)(rot * 16);
+ if (mode == MODE_SHIP) {
+ float r = rot * 3.14159265f / 180.f, s = upside ? -1.f : 1.f;
+ /* the pilot sits in the cockpit, scaled down with the ship */
+ float lx = 0, ly = -6.5f * PX * s * scale;
+ float px_ = cx + lx * cosf(r) - ly * sinf(r), py_ = cy + lx * sinf(r) + ly * cosf(r);
+ int fl = upside ? XF_FLIPY : 0;
+ gfx_sprite_ex(SPR_CUBE1_S, (int)(px_ * 16), (int)(py_ * 16), a16, (int)(128 * scale), fl, p2, alpha, BLEND_NORMAL);
+ gfx_sprite_ex(SPR_CUBE1_P, (int)(px_ * 16), (int)(py_ * 16), a16, (int)(128 * scale), fl, p1, alpha, BLEND_NORMAL);
+ gfx_sprite_ex(SPR_SHIP1_S, x16, y16 + (int)(2 * 16 * s * scale), a16, (int)(256 * scale), fl, p2, alpha, BLEND_NORMAL);
+ gfx_sprite_ex(SPR_SHIP1_P, x16, y16 + (int)(2 * 16 * s * scale), a16, (int)(256 * scale), fl, p1, alpha, BLEND_NORMAL);
+ return;
+ }
+ gfx_sprite_ex(SPR_CUBE1_S, x16, y16, a16, (int)(256 * scale), 0, p2, alpha, BLEND_NORMAL);
+ gfx_sprite_ex(SPR_CUBE1_P, x16, y16, a16, (int)(256 * scale), 0, p1, alpha, BLEND_NORMAL);
+}
+
+static void draw_player(void) {
+ const Player *p = &G->p;
+ fx_draw_player_trail();
+ scene_draw_player_icon(p->mode, player_sx, player_sy, p->rot, 1, O.p1, O.p2, p->upside, 256);
+}
+
+static void draw_end_wall(void) {
+ if (G->wall_y <= 0) return;
+ int x = (int)floorf(wx_to_sx(G, G->L->wall_x) + .5f);
+ if (x > GFX_W + 20) return;
+ float oy = fmodf(G->cam_y, 30);
+ for (float wy = -30; wy < VIEW_H + 60; wy += 30) {
+ int y = (int)floorf(240 - (wy - oy + 15) * PX + .5f);
+ gfx_sprite(SPR_GRID_T, x, y, 3, tint_obj, 255, BLEND_NORMAL);
+ }
+ gfx_hgrad_alpha(x - 26, 0, 20, GFX_H, O.p1, 0, 170, BLEND_ADD);
+}
+
+static void draw_attempt(void) {
+ if (O.editor || !O.attempt) return;
+ float sx = wx_to_sx(G, O.attempt_x);
+ if (sx < -200 || sx > 520) return;
+ char buf[24] = "ATTEMPT ";
+ gfx_format_uint(buf + 8, O.attempt);
+ int base = (int)floorf(wy_to_sy(G, O.attempt_y) + fonts[FONT_HUGE].cap / 2 + .5f);
+ gfx_text_center(FONT_HUGE, (int)sx, base, buf, 0xffff, 0xffff, 256);
+}
+
+static void draw_hud(void) {
+ if (O.editor) return;
+ /* progress bar, top centre */
+ float prog = game_progress(G);
+ const int bw = 160, bh = 8, bx = (GFX_W - bw) / 2, by = 5;
+ if (O.show_bar) {
+ gfx_round_rect(bx - 2, by - 2, bw + 4, bh + 4, 5, 0xffff, 170);
+ gfx_round_rect(bx, by, bw, bh, 4, 0, 200);
+ int fw = (int)(prog / 100 * (bw - 2));
+ if (fw > 0) {
+ color_t c = O.p1 ? O.p1 : 0xffff; /* the player's colour, as in 2.2 */
+ int w = fw < 6 ? 6 : fw;
+ gfx_round_rect(bx + 1, by + 1, w, bh - 2, 3, c, 256);
+ gfx_add(bx + 3, by + 2, w - 4, 1, 0xffff, 90);
+ }
+ }
+ if (O.show_percent) {
+ char buf[8];
+ int n = gfx_format_uint(buf, (unsigned long)prog);
+ buf[n++] = '%';
+ buf[n] = 0;
+ if (O.show_bar) gfx_text(FONT_SMALL, bx + bw + 6, by + 8, buf, 0xffff, 0xffff, 256);
+ else gfx_text_center(FONT_SMALL, GFX_W / 2, by + 8, buf, 0xffff, 0xffff, 256);
+ }
+ /* practice checkpoints: green diamonds */
+ for (unsigned k = 0; k < O.checkpoint_count; k++) {
+ const Checkpoint *c = &O.checkpoints[k];
+ float sx = wx_to_sx(G, c->p.x), sy = wy_to_sy(G, c->p.y);
+ if (sx < -10 || sx > GFX_W + 10 || sy < gfx_y0 - 12 || sy > gfx_y1 + 12) continue;
+ float d0[8] = {sx, sy - 10, sx + 7, sy, sx, sy + 10, sx - 7, sy};
+ float d1[8] = {sx, sy - 7.5f, sx + 5, sy, sx, sy + 7.5f, sx - 5, sy};
+ float d2[6] = {sx, sy - 7.5f, sx + 5, sy, sx - 5, sy};
+ gfx_poly(d0, 4, 0, 256, BLEND_NORMAL);
+ gfx_poly(d1, 4, rgb(0, 190, 40), 256, BLEND_NORMAL);
+ gfx_poly(d2, 3, rgb(120, 255, 120), 256, BLEND_NORMAL);
+ }
+}
+
+/* Editor grid: 30 unit cells above the ground. */
+static void draw_grid(void) {
+ float x0 = fmodf(-G->cam_x, 30);
+ if (x0 > 0) x0 -= 30;
+ for (float wx = x0; wx < VIEW_W + 30; wx += 30) {
+ int sx = (int)floorf(wx * PX + .5f);
+ gfx_blend(sx, 0, 1, ground_top, 0, 70);
+ }
+ for (int row = 0; row < 90; row++) {
+ int sy = (int)floorf(wy_to_sy(G, row * 30.0f) + .5f);
+ if (sy < gfx_y0 - 1) break;
+ if (sy <= gfx_y1) gfx_blend(0, sy, GFX_W, 1, 0, 70);
+ }
+}
+
+void scene_draw(void) {
+ if (!G) return;
+ scene_background(bg_col, G->bg_x, G->cam_y);
+ if (O.editor) draw_grid();
+ for (int k = 0; k < nitems; k++) {
+ const Item *it = &items[order[k]];
+ if (it->kind == K_PLAYER) { draw_player(); continue; }
+ const Sprite *s = &sprites[it->spr];
+ int ext = (s->w > s->h ? s->w : s->h) * (it->scale > 256 ? it->scale : 256) / 256 + 2;
+ if (it->y + ext < gfx_y0 || it->y - ext > gfx_y1) continue;
+ color_t c;
+ int mode;
+ tint_for(it->ct, &c, &mode);
+ if (it->kind == K_SCALED) {
+ /* 90 degree transforms are expressed as rotation + flips for the bilinear path */
+ gfx_sprite_ex(it->spr, it->x * 16, it->y * 16, (it->xf & 3) * 90 * 16, it->scale, it->xf & (XF_FLIPX | XF_FLIPY), c, it->alpha + 1, mode);
+ } else {
+ gfx_sprite(it->spr, it->x, it->y, it->xf, c, it->alpha + 1, mode);
+ }
+ }
+ draw_end_wall();
+ draw_attempt();
+ if (ground_top < GFX_H) scene_ground(g1_col, line_col, G->ground_x, ground_top, false, true);
+ if (draw_gfx_grounds) {
+ if (floor_bottom < ground_top) scene_ground(g1_col, line_col, G->ground_x, floor_bottom, false, true);
+ scene_ground(g1_col, line_col, G->ground_x, ceil_bottom, true, true);
+ }
+ fx_draw();
+ draw_hud();
+ if (O.fade > 0) gfx_scale_rect(0, 0, GFX_W, GFX_H, (unsigned)((1 - O.fade) * 256));
+}
diff --git a/games/numdash/src/scene.h b/games/numdash/src/scene.h
new file mode 100644
index 00000000..54e4b3e6
--- /dev/null
+++ b/games/numdash/src/scene.h
@@ -0,0 +1,27 @@
+#ifndef NUMDASH_SCENE_H
+#define NUMDASH_SCENE_H
+#include "game.h"
+#include "gfx.h"
+
+typedef struct {
+ color_t p1, p2; /* icon colours */
+ uint8_t icon_cube, icon_ship;
+ bool practice, show_percent, show_bar, hide_player, paused, editor, low_detail;
+ unsigned attempt;
+ float attempt_x, attempt_y; /* world position of the "Attempt N" label */
+ uint8_t coins_saved; /* coins collected on an earlier run: drawn faded */
+ float time; /* seconds since level start (pulses) */
+ float fade; /* 0..1 whole-screen fade to black */
+ const Checkpoint *checkpoints;
+ unsigned checkpoint_count;
+} SceneOpts;
+
+/* Background and ground used by gameplay and menus. */
+void scene_background(color_t bg, float bg_x, float cam_y);
+void scene_ground(color_t g1, color_t line, float ground_x, int top_y, bool ceiling, bool shadows);
+
+void scene_prepare(const Game *g, const SceneOpts *o);
+void scene_draw(void);
+void scene_draw_player_icon(int mode, float cx, float cy, float rot, float scale, color_t p1, color_t p2, bool upside, unsigned alpha);
+color_t scene_channel(const Game *g, int ch);
+#endif
diff --git a/games/numdash/src/ui.c b/games/numdash/src/ui.c
new file mode 100644
index 00000000..e95994ef
--- /dev/null
+++ b/games/numdash/src/ui.c
@@ -0,0 +1,146 @@
+#include "ui.h"
+#include <math.h>
+
+void ui_gradient_bg(color_t c) {
+ /* GJ_gradientBG: white at the top fading to 44% grey, tinted */
+ gfx_vgrad(0, 0, GFX_W, GFX_H, c, c_scale(c, 113));
+}
+
+void ui_dim(unsigned alpha) { gfx_blend(0, 0, GFX_W, GFX_H, 0, alpha); }
+
+/* Rounded rectangle with a vertical gradient (corners without AA). */
+static void round_vgrad(int x, int y, int w, int h, int r, color_t top, color_t bottom) {
+ int j0 = y > gfx_y0 ? y : gfx_y0, j1 = y + h < gfx_y1 ? y + h : gfx_y1;
+ for (int j = j0; j < j1; j++) {
+ int k = j - y, d = k < r ? r - k : (k >= h - r ? k - (h - r - 1) : 0), in = 0;
+ if (d) {
+ float dy = d - .5f;
+ in = (int)(r - sqrtf((float)(r * r) - dy * dy) + .5f);
+ }
+ gfx_fill(x + in, j, w - 2 * in, 1, c_mix(top, bottom, (unsigned)(k * 256 / (h > 1 ? h - 1 : 1))));
+ }
+}
+
+static void box(int x, int y, int w, int h, int r, color_t body, color_t hi, color_t lo) {
+ gfx_round_rect(x, y, w, h, r, 0, 256);
+ gfx_round_rect(x + 2, y + 2, w - 4, h - 4, r - 1, lo, 256);
+ gfx_round_rect(x + 2, y + 2, w - 4, h - 7, r - 1, body, 256);
+ gfx_round_rect(x + 2, y + 2, w - 4, 4, r - 1 < 2 ? 2 : r - 1, hi, 256);
+ gfx_blend(x + r, y + 5, w - 2 * r, 2, hi, 110);
+}
+
+void ui_window_brown(int x, int y, int w, int h) { box(x, y, w, h, 7, rgb(153, 85, 51), rgb(187, 118, 60), rgb(85, 51, 17)); }
+void ui_window_blue(int x, int y, int w, int h) { box(x, y, w, h, 7, rgb(51, 68, 153), rgb(70, 72, 187), rgb(17, 17, 85)); }
+void ui_window_dark(int x, int y, int w, int h, unsigned alpha) { gfx_round_rect(x, y, w, h, 6, 0, alpha); }
+
+void ui_window_navy(int x, int y, int w, int h) {
+ gfx_round_rect(x, y, w, h, 9, rgb(90, 92, 96), 256);
+ gfx_round_rect(x + 1, y + 1, w - 2, h - 2, 8, rgb(215, 215, 228), 256);
+ gfx_round_rect(x + 3, y + 3, w - 6, h - 6, 7, rgb(140, 142, 148), 256);
+ gfx_round_rect(x + 4, y + 4, w - 8, h - 8, 6, rgb(0, 17, 34), 256);
+ gfx_round_rect(x + 6, y + 6, w - 12, h - 12, 5, rgb(0, 36, 70), 256);
+ /* bolts in the corners */
+ const int bx[2] = {x + 6, x + w - 6}, by[2] = {y + 6, y + h - 6};
+ for (int i = 0; i < 2; i++)
+ for (int j = 0; j < 2; j++) {
+ gfx_disc(bx[i] * 16, by[j] * 16, 6 * 16, rgb(70, 72, 76), 256, BLEND_NORMAL);
+ gfx_disc(bx[i] * 16, by[j] * 16, 5 * 16, rgb(205, 205, 218), 256, BLEND_NORMAL);
+ gfx_disc(bx[i] * 16 - 16, by[j] * 16 - 16, 2 * 16, 0xffff, 200, BLEND_NORMAL);
+ }
+}
+
+void ui_text_button(int cx, int cy, int w, int h, const char *s, int style, float scale) {
+ const int font = h >= 24 ? FONT_BIG : FONT_SMALL;
+ static const uint8_t cols[4][2][3] = {
+ {{190, 255, 80}, {60, 170, 0}}, {{130, 255, 255}, {0, 160, 210}}, {{255, 150, 255}, {210, 40, 210}}, {{200, 200, 200}, {110, 110, 110}}};
+ w = (int)(w * scale);
+ h = (int)(h * scale);
+ int x = cx - w / 2, y = cy - h / 2;
+ gfx_round_rect(x + 1, y + 2, w, h, 6, 0, 110);
+ gfx_round_rect(x, y, w, h, 6, 0, 256);
+ color_t top = rgb(cols[style][0][0], cols[style][0][1], cols[style][0][2]);
+ color_t bot = rgb(cols[style][1][0], cols[style][1][1], cols[style][1][2]);
+ round_vgrad(x + 2, y + 2, w - 4, h - 4, 4, top, bot);
+ gfx_blend(x + 5, y + 3, w - 10, 2, 0xffff, 90);
+ int base = cy + fonts[font].cap / 2;
+ gfx_text_center(font, cx, base, s, GOLD_TOP, GOLD_BOTTOM, 256);
+}
+
+void ui_progress_bar(int cx, int cy, int w, int h, int percent, color_t fill, bool label) {
+ int x = cx - w / 2, y = cy - h / 2, r = h / 2;
+ gfx_round_rect(x, y, w, h, r, 0, 128);
+ if (percent > 0) {
+ int fw = (w - 4) * (percent > 100 ? 100 : percent) / 100;
+ if (fw < h - 4) fw = h - 4;
+ gfx_round_rect(x + 2, y + 2, fw, h - 4, r - 2, fill, 256);
+ }
+ if (label) {
+ char buf[8];
+ int n = gfx_format_uint(buf, (unsigned long)percent);
+ buf[n] = '%';
+ buf[n + 1] = 0;
+ gfx_text_center(FONT_SMALL, cx, cy + fonts[FONT_SMALL].cap / 2, buf, 0xffff, 0xffff, 256);
+ }
+}
+
+void ui_checkbox(int cx, int cy, bool on, float scale) { ui_sprite(on ? SPR_CHECK_ON : SPR_CHECK_OFF, (float)cx, (float)cy, scale, 256); }
+
+void ui_top_bar(int cy, bool center) {
+ const int x0 = 46, x1 = 274, y0 = cy - 14, y1 = cy + 7;
+ color_t lime_t = rgb(190, 242, 72), lime_b = rgb(80, 150, 30), cyan_t = rgb(120, 250, 250), cyan_b = rgb(0, 170, 180);
+ gfx_round_rect(x0 - 3, y0 - 3, x1 - x0 + 6, y1 - y0 + 5, 4, rgb(24, 75, 153), 200);
+ gfx_round_rect(x0 - 2, y0 - 2, x1 - x0 + 4, y1 - y0 + 3, 3, rgb(242, 245, 250), 256);
+ gfx_fill(x0, y0, x1 - x0, y1 - y0, 0);
+ gfx_vgrad(x0 + 1, y0, x1 - x0 - 2, y1 - y0 - 1, lime_t, lime_b);
+ /* cyan caps and the deeper centre block */
+ gfx_fill(x0, y0, 16, y1 - y0 - 4, 0);
+ gfx_vgrad(x0 + 1, y0, 14, y1 - y0 - 5, cyan_t, cyan_b);
+ gfx_fill(x1 - 16, y0, 16, y1 - y0 - 4, 0);
+ gfx_vgrad(x1 - 15, y0, 14, y1 - y0 - 5, cyan_t, cyan_b);
+ int cxm = (x0 + x1) / 2;
+ if (center) {
+ gfx_fill(cxm - 18, y0, 36, y1 - y0 + 5, 0);
+ gfx_vgrad(cxm - 17, y0, 34, y1 - y0 + 4, cyan_t, cyan_b);
+ }
+ gfx_blend(x0 + 1, y0, x1 - x0 - 2, 2, 0xffff, 80);
+}
+
+void ui_side_art(void) {
+ gfx_sprite(SPR_SIDE_ART, 0, GFX_H, 0, 0xffff, 256, BLEND_NORMAL);
+ gfx_sprite(SPR_SIDE_ART, GFX_W, GFX_H, XF_FLIPX, 0xffff, 256, BLEND_NORMAL);
+}
+
+void ui_nav_dots(int cx, int cy, int n, int cur) {
+ const int step = 12;
+ int x = cx - (n - 1) * step / 2;
+ for (int i = 0; i < n; i++, x += step) {
+ gfx_disc(x * 16, cy * 16, 4 * 16, 0, 200, BLEND_NORMAL);
+ gfx_disc(x * 16, cy * 16, 3 * 16, i == cur ? rgb(0, 255, 255) : rgb(125, 125, 125), 256, BLEND_NORMAL);
+ }
+}
+
+void ui_sprite(int spr, float cx, float cy, float scale, unsigned alpha) {
+ if (fabsf(scale - 1) < 0.01f)
+ gfx_sprite(spr, (int)floorf(cx + .5f), (int)floorf(cy + .5f), 0, 0xffff, alpha, BLEND_NORMAL);
+ else
+ gfx_sprite_ex(spr, (int)(cx * 16), (int)(cy * 16), 0, (int)(scale * 256), 0, 0xffff, alpha, BLEND_NORMAL);
+}
+
+void ui_title(int font, int cx, int baseline, const char *s) { gfx_text_center(font, cx, baseline, s, 0xffff, 0xffff, 256); }
+void ui_gold(int font, int cx, int baseline, const char *s) { gfx_text_center(font, cx, baseline, s, GOLD_TOP, GOLD_BOTTOM, 256); }
+
+float ui_ease_elastic_out(float t, float period) {
+ if (t <= 0) return 0;
+ if (t >= 1) return 1;
+ float s = period / 4;
+ return powf(2, -10 * t) * sinf((t - s) * 6.2831853f / period) + 1;
+}
+
+float ui_ease_bounce_out(float t) {
+ if (t >= 1) return 1;
+ if (t < 1 / 2.75f) return 7.5625f * t * t;
+ if (t < 2 / 2.75f) { t -= 1.5f / 2.75f; return 7.5625f * t * t + .75f; }
+ if (t < 2.5f / 2.75f) { t -= 2.25f / 2.75f; return 7.5625f * t * t + .9375f; }
+ t -= 2.625f / 2.75f;
+ return 7.5625f * t * t + .984375f;
+}
diff --git a/games/numdash/src/ui.h b/games/numdash/src/ui.h
new file mode 100644
index 00000000..431c7290
--- /dev/null
+++ b/games/numdash/src/ui.h
@@ -0,0 +1,29 @@
+#ifndef NUMDASH_UI_H
+#define NUMDASH_UI_H
+#include "gfx.h"
+#include <stdbool.h>
+
+/* Widgets in the style of Geometry Dash's menus. */
+enum { BTN_GREEN, BTN_CYAN, BTN_PINK, BTN_GRAY };
+#define GOLD_TOP rgb(255, 255, 140)
+#define GOLD_BOTTOM rgb(255, 170, 0)
+
+void ui_gradient_bg(color_t c);
+void ui_dim(unsigned alpha256);
+void ui_window_brown(int x, int y, int w, int h);
+void ui_window_blue(int x, int y, int w, int h);
+void ui_window_dark(int x, int y, int w, int h, unsigned alpha256);
+void ui_window_navy(int x, int y, int w, int h);
+void ui_text_button(int cx, int cy, int w, int h, const char *s, int style, float scale);
+void ui_progress_bar(int cx, int cy, int w, int h, int percent, color_t fill, bool label);
+void ui_checkbox(int cx, int cy, bool on, float scale);
+void ui_top_bar(int cy, bool center);
+void ui_side_art(void);
+void ui_nav_dots(int cx, int cy, int n, int cur);
+/* Sprite drawn at scale; exact 1:1 when scale is 1. */
+void ui_sprite(int spr, float cx, float cy, float scale, unsigned alpha);
+void ui_title(int font, int cx, int baseline, const char *s);
+void ui_gold(int font, int cx, int baseline, const char *s);
+float ui_ease_elastic_out(float t, float period);
+float ui_ease_bounce_out(float t);
+#endif
diff --git a/games/numdash/tests/replays/level1.txt b/games/numdash/tests/replays/level1.txt
new file mode 100644
index 00000000..cf742a81
--- /dev/null
+++ b/games/numdash/tests/replays/level1.txt
@@ -0,0 +1,358 @@
+input=381,1
+input=385,0
+input=733,1
+input=737,0
+input=1097,1
+input=1101,0
+input=1189,1
+input=1193,0
+input=1281,1
+input=1285,0
+input=1809,1
+input=1813,0
+input=1973,1
+input=1977,0
+input=2181,1
+input=2185,0
+input=2341,1
+input=2345,0
+input=2505,1
+input=2509,0
+input=2713,1
+input=2717,0
+input=2897,1
+input=2901,0
+input=2989,1
+input=2993,0
+input=3081,1
+input=3085,0
+input=3173,1
+input=3177,0
+input=3265,1
+input=3269,0
+input=3353,1
+input=3357,0
+input=3541,1
+input=3545,0
+input=3725,1
+input=3729,0
+input=4141,1
+input=4145,0
+input=4233,1
+input=4237,0
+input=4497,1
+input=4501,0
+input=4601,1
+input=4605,0
+input=4785,1
+input=4789,0
+input=4969,1
+input=4973,0
+input=5061,1
+input=5065,0
+input=5153,1
+input=5157,0
+input=5245,1
+input=5249,0
+input=5337,1
+input=5341,0
+input=7197,1
+input=7233,0
+input=7305,1
+input=7321,0
+input=7325,1
+input=7329,0
+input=7333,1
+input=7337,0
+input=7341,1
+input=7345,0
+input=7357,1
+input=7365,0
+input=7377,1
+input=7381,0
+input=7385,1
+input=7389,0
+input=7393,1
+input=7397,0
+input=7405,1
+input=7409,0
+input=7417,1
+input=7421,0
+input=7425,1
+input=7429,0
+input=7437,1
+input=7441,0
+input=7445,1
+input=7449,0
+input=7457,1
+input=7461,0
+input=7465,1
+input=7469,0
+input=7477,1
+input=7481,0
+input=7489,1
+input=7493,0
+input=7497,1
+input=7501,0
+input=7505,1
+input=7509,0
+input=7521,1
+input=7529,0
+input=7541,1
+input=7545,0
+input=7549,1
+input=7553,0
+input=7557,1
+input=7561,0
+input=7569,1
+input=7573,0
+input=7581,1
+input=7585,0
+input=7589,1
+input=7593,0
+input=7605,1
+input=7609,0
+input=7821,1
+input=7889,0
+input=8353,1
+input=8397,0
+input=8473,1
+input=8533,0
+input=8613,1
+input=8673,0
+input=9233,1
+input=9313,0
+input=9317,1
+input=9321,0
+input=10005,1
+input=10009,0
+input=10097,1
+input=10101,0
+input=10281,1
+input=10285,0
+input=10533,1
+input=10537,0
+input=10625,1
+input=10629,0
+input=10717,1
+input=10721,0
+input=10809,1
+input=10813,0
+input=10901,1
+input=10905,0
+input=10993,1
+input=10997,0
+input=11085,1
+input=11089,0
+input=11429,1
+input=11433,0
+input=11689,1
+input=11693,0
+input=12053,1
+input=12057,0
+input=12145,1
+input=12149,0
+input=12329,1
+input=12333,0
+input=12425,1
+input=12429,0
+input=12609,1
+input=12613,0
+input=12769,1
+input=12773,0
+input=12957,1
+input=12961,0
+input=13137,1
+input=13141,0
+input=13309,1
+input=13313,0
+input=13509,1
+input=13513,0
+input=13601,1
+input=13605,0
+input=13693,1
+input=13697,0
+input=13785,1
+input=13789,0
+input=14129,1
+input=14133,0
+input=14501,1
+input=14505,0
+input=14729,1
+input=14733,0
+input=14845,1
+input=14849,0
+input=14937,1
+input=14941,0
+input=15029,1
+input=15033,0
+input=15121,1
+input=15125,0
+input=15453,1
+input=15457,0
+input=15545,1
+input=15549,0
+input=15661,1
+input=15665,0
+input=15929,1
+input=15933,0
+input=16093,1
+input=16097,0
+input=16365,1
+input=16369,0
+input=16461,1
+input=16465,0
+input=16561,1
+input=16565,0
+input=16689,1
+input=16693,0
+input=16781,1
+input=16785,0
+input=17013,1
+input=17017,0
+input=17105,1
+input=17109,0
+input=17265,1
+input=17269,0
+input=17381,1
+input=17385,0
+input=17473,1
+input=17477,0
+input=17609,1
+input=17613,0
+input=17869,1
+input=17917,0
+input=17925,1
+input=17937,0
+input=17941,1
+input=17957,0
+input=17961,1
+input=17965,0
+input=18197,1
+input=18241,0
+input=18257,1
+input=18289,0
+input=18293,1
+input=18297,0
+input=18301,1
+input=18309,0
+input=18313,1
+input=18333,0
+input=18337,1
+input=18353,0
+input=18361,1
+input=18373,0
+input=18601,1
+input=18705,0
+input=18709,1
+input=18713,0
+input=18717,1
+input=18725,0
+input=18901,1
+input=18949,0
+input=18953,1
+input=18965,0
+input=18969,1
+input=18977,0
+input=18985,1
+input=18989,0
+input=18993,1
+input=18997,0
+input=19005,1
+input=19009,0
+input=19017,1
+input=19021,0
+input=19025,1
+input=19029,0
+input=19037,1
+input=19041,0
+input=19045,1
+input=19049,0
+input=19057,1
+input=19061,0
+input=19065,1
+input=19069,0
+input=19077,1
+input=19081,0
+input=19089,1
+input=19093,0
+input=19097,1
+input=19101,0
+input=19109,1
+input=19117,0
+input=19133,1
+input=19141,0
+input=19149,1
+input=19153,0
+input=19157,1
+input=19161,0
+input=19169,1
+input=19173,0
+input=19181,1
+input=19185,0
+input=19189,1
+input=19193,0
+input=19201,1
+input=19205,0
+input=19209,1
+input=19213,0
+input=19221,1
+input=19225,0
+input=19229,1
+input=19233,0
+input=19241,1
+input=19245,0
+input=19253,1
+input=19257,0
+input=19261,1
+input=19265,0
+input=19269,1
+input=19273,0
+input=19285,1
+input=19293,0
+input=19305,1
+input=19309,0
+input=19313,1
+input=19317,0
+input=19321,1
+input=19325,0
+input=19333,1
+input=19337,0
+input=19345,1
+input=19349,0
+input=19353,1
+input=19357,0
+input=19365,1
+input=19369,0
+input=19373,1
+input=19377,0
+input=19385,1
+input=19417,0
+input=19421,1
+input=19425,0
+input=19429,1
+input=19449,0
+input=19453,1
+input=19465,0
+input=19565,1
+input=19585,0
+input=19589,1
+input=19593,0
+input=19601,1
+input=19609,0
+input=19633,1
+input=19693,0
+input=19697,1
+input=19709,0
+input=19797,1
+input=19821,0
+input=19829,1
+input=19837,0
+input=19849,1
+input=19853,0
+input=19857,1
+input=19861,0
+input=19913,1
+input=19973,0
+input=19977,1
+input=19993,0
diff --git a/games/numdash/tests/replays/level2.txt b/games/numdash/tests/replays/level2.txt
new file mode 100644
index 00000000..0caf8ad6
--- /dev/null
+++ b/games/numdash/tests/replays/level2.txt
@@ -0,0 +1,282 @@
+input=517,1
+input=521,0
+input=749,1
+input=753,0
+input=841,1
+input=845,0
+input=1257,1
+input=1261,0
+input=1465,1
+input=1469,0
+input=1557,1
+input=1561,0
+input=1649,1
+input=1653,0
+input=1741,1
+input=1745,0
+input=1929,1
+input=1933,0
+input=2041,1
+input=2045,0
+input=2249,1
+input=2253,0
+input=2353,1
+input=2357,0
+input=2457,1
+input=2461,0
+input=2561,1
+input=2565,0
+input=2757,1
+input=2761,0
+input=2965,1
+input=2969,0
+input=3057,1
+input=3061,0
+input=3497,1
+input=3501,0
+input=3633,1
+input=3637,0
+input=3773,1
+input=3777,0
+input=4005,1
+input=4009,0
+input=4097,1
+input=4101,0
+input=4373,1
+input=4377,0
+input=4465,1
+input=4469,0
+input=4673,1
+input=4677,0
+input=4785,1
+input=4789,0
+input=4877,1
+input=4881,0
+input=5201,1
+input=5205,0
+input=5293,1
+input=5297,0
+input=5385,1
+input=5389,0
+input=5653,1
+input=5657,0
+input=5741,1
+input=5745,0
+input=5945,1
+input=5949,0
+input=6081,1
+input=6085,0
+input=6185,1
+input=6189,0
+input=6309,1
+input=6313,0
+input=6401,1
+input=6405,0
+input=6493,1
+input=6497,0
+input=6585,1
+input=6589,0
+input=6745,1
+input=6749,0
+input=7069,1
+input=7073,0
+input=7321,1
+input=7325,0
+input=7553,1
+input=7557,0
+input=7669,1
+input=7673,0
+input=7761,1
+input=7765,0
+input=8505,1
+input=8509,0
+input=8609,1
+input=8613,0
+input=8829,1
+input=8833,0
+input=8893,1
+input=8897,0
+input=9193,1
+input=9197,0
+input=9333,1
+input=9337,0
+input=9677,1
+input=9681,0
+input=10313,1
+input=10381,0
+input=10393,1
+input=10405,0
+input=10413,1
+input=10425,0
+input=10937,1
+input=11005,0
+input=11017,1
+input=11029,0
+input=11037,1
+input=11049,0
+input=11057,1
+input=11073,0
+input=11537,1
+input=11605,0
+input=11621,1
+input=11629,0
+input=11633,1
+input=11653,0
+input=11665,1
+input=11673,0
+input=11817,1
+input=11861,0
+input=11889,1
+input=11909,0
+input=11913,1
+input=11917,0
+input=11933,1
+input=11937,0
+input=11941,1
+input=11945,0
+input=11949,1
+input=11961,0
+input=11973,1
+input=11981,0
+input=11989,1
+input=11993,0
+input=12001,1
+input=12005,0
+input=12013,1
+input=12021,0
+input=12033,1
+input=12037,0
+input=12041,1
+input=12045,0
+input=12049,1
+input=12053,0
+input=12065,1
+input=12073,0
+input=12081,1
+input=12085,0
+input=12093,1
+input=12097,0
+input=12105,1
+input=12113,0
+input=12125,1
+input=12129,0
+input=12133,1
+input=12137,0
+input=12145,1
+input=12149,0
+input=12153,1
+input=12157,0
+input=12165,1
+input=12169,0
+input=12173,1
+input=12177,0
+input=12185,1
+input=12189,0
+input=12193,1
+input=12197,0
+input=12205,1
+input=12209,0
+input=12217,1
+input=12221,0
+input=12225,1
+input=12229,0
+input=12237,1
+input=12241,0
+input=12245,1
+input=12249,0
+input=12257,1
+input=12261,0
+input=12265,1
+input=12269,0
+input=12273,1
+input=12289,0
+input=12293,1
+input=12321,0
+input=12409,1
+input=12433,0
+input=12441,1
+input=12453,0
+input=12465,1
+input=12469,0
+input=12477,1
+input=12485,0
+input=12497,1
+input=12501,0
+input=12505,1
+input=12509,0
+input=12513,1
+input=12517,0
+input=12525,1
+input=12529,0
+input=12537,1
+input=12541,0
+input=12545,1
+input=12549,0
+input=13077,1
+input=13081,0
+input=13189,1
+input=13193,0
+input=13305,1
+input=13309,0
+input=13397,1
+input=13401,0
+input=13561,1
+input=13565,0
+input=13973,1
+input=13977,0
+input=14065,1
+input=14069,0
+input=14529,1
+input=14533,0
+input=14965,1
+input=14969,0
+input=15129,1
+input=15133,0
+input=15289,1
+input=15293,0
+input=15521,1
+input=15525,0
+input=15637,1
+input=15641,0
+input=15753,1
+input=15757,0
+input=15937,1
+input=15941,0
+input=16029,1
+input=16033,0
+input=16257,1
+input=16261,0
+input=16537,1
+input=16541,0
+input=16745,1
+input=16749,0
+input=16873,1
+input=16877,0
+input=16977,1
+input=16981,0
+input=17221,1
+input=17225,0
+input=17325,1
+input=17329,0
+input=17577,1
+input=17581,0
+input=17805,1
+input=17809,0
+input=18013,1
+input=18017,0
+input=18221,1
+input=18225,0
+input=18361,1
+input=18365,0
+input=18453,1
+input=18457,0
+input=18613,1
+input=18617,0
+input=18705,1
+input=18709,0
+input=18841,1
+input=18845,0
+input=18957,1
+input=18961,0
+input=19049,1
+input=19053,0
diff --git a/games/numdash/tests/replays/level3.txt b/games/numdash/tests/replays/level3.txt
new file mode 100644
index 00000000..dba6a5f5
--- /dev/null
+++ b/games/numdash/tests/replays/level3.txt
@@ -0,0 +1,266 @@
+input=349,1
+input=353,0
+input=421,1
+input=425,0
+input=697,1
+input=701,0
+input=777,1
+input=781,0
+input=1057,1
+input=1061,0
+input=1121,1
+input=1125,0
+input=1233,1
+input=1237,0
+input=1325,1
+input=1329,0
+input=1421,1
+input=1425,0
+input=1581,1
+input=1585,0
+input=1697,1
+input=1701,0
+input=1905,1
+input=1909,0
+input=2009,1
+input=2013,0
+input=2297,1
+input=2301,0
+input=2505,1
+input=2509,0
+input=2757,1
+input=2761,0
+input=2829,1
+input=2833,0
+input=2921,1
+input=2925,0
+input=3197,1
+input=3201,0
+input=3289,1
+input=3293,0
+input=3433,1
+input=3437,0
+input=3521,1
+input=3525,0
+input=3729,1
+input=3733,0
+input=3909,1
+input=3913,0
+input=4009,1
+input=4013,0
+input=4213,1
+input=4217,0
+input=4317,1
+input=4321,0
+input=4717,1
+input=4721,0
+input=4809,1
+input=4813,0
+input=4909,1
+input=4913,0
+input=5117,1
+input=5121,0
+input=5209,1
+input=5213,0
+input=5625,1
+input=5629,0
+input=5717,1
+input=5721,0
+input=5945,1
+input=5949,0
+input=6041,1
+input=6045,0
+input=6201,1
+input=6205,0
+input=6385,1
+input=6389,0
+input=6641,1
+input=6645,0
+input=6793,1
+input=6797,0
+input=6929,1
+input=6933,0
+input=7069,1
+input=7073,0
+input=7209,1
+input=7213,0
+input=7289,1
+input=7293,0
+input=7381,1
+input=7385,0
+input=7405,1
+input=7409,0
+input=7853,1
+input=7897,0
+input=8385,1
+input=8429,0
+input=8885,1
+input=8905,0
+input=8909,1
+input=8917,0
+input=8921,1
+input=8925,0
+input=9197,1
+input=9237,0
+input=9541,1
+input=9585,0
+input=9961,1
+input=9977,0
+input=9981,1
+input=9989,0
+input=10009,1
+input=10049,0
+input=10057,1
+input=10061,0
+input=10065,1
+input=10085,0
+input=10089,1
+input=10093,0
+input=10377,1
+input=10381,0
+input=10469,1
+input=10473,0
+input=10573,1
+input=10577,0
+input=10665,1
+input=10677,0
+input=10821,1
+input=10825,0
+input=10901,1
+input=10905,0
+input=11213,1
+input=11217,0
+input=11317,1
+input=11321,0
+input=11429,1
+input=11433,0
+input=11517,1
+input=11521,0
+input=11613,1
+input=11617,0
+input=11709,1
+input=11713,0
+input=11885,1
+input=11889,0
+input=12001,1
+input=12005,0
+input=12093,1
+input=12097,0
+input=12185,1
+input=12189,0
+input=12273,1
+input=12277,0
+input=12365,1
+input=12369,0
+input=12805,1
+input=12809,0
+input=12921,1
+input=12925,0
+input=13013,1
+input=13017,0
+input=13105,1
+input=13109,0
+input=13197,1
+input=13201,0
+input=13289,1
+input=13293,0
+input=13473,1
+input=13477,0
+input=13761,1
+input=13765,0
+input=13913,1
+input=13917,0
+input=14097,1
+input=14101,0
+input=14257,1
+input=14261,0
+input=14357,1
+input=14361,0
+input=14533,1
+input=14537,0
+input=14813,1
+input=14817,0
+input=14905,1
+input=14909,0
+input=14997,1
+input=15001,0
+input=15085,1
+input=15089,0
+input=15669,1
+input=15673,0
+input=15781,1
+input=15785,0
+input=15893,1
+input=15897,0
+input=16009,1
+input=16013,0
+input=16281,1
+input=16285,0
+input=16401,1
+input=16405,0
+input=16493,1
+input=16497,0
+input=16757,1
+input=16761,0
+input=16845,1
+input=16849,0
+input=16961,1
+input=16965,0
+input=17049,1
+input=17053,0
+input=17165,1
+input=17169,0
+input=17269,1
+input=17273,0
+input=17373,1
+input=17377,0
+input=17465,1
+input=17469,0
+input=17625,1
+input=17629,0
+input=17793,1
+input=17797,0
+input=17925,1
+input=17929,0
+input=18085,1
+input=18089,0
+input=18177,1
+input=18181,0
+input=18269,1
+input=18273,0
+input=18361,1
+input=18365,0
+input=18705,1
+input=18709,0
+input=18869,1
+input=18873,0
+input=19057,1
+input=19061,0
+input=19149,1
+input=19153,0
+input=19261,1
+input=19265,0
+input=19561,1
+input=19565,0
+input=19677,1
+input=19681,0
+input=19813,1
+input=19817,0
+input=20161,1
+input=20165,0
+input=20301,1
+input=20305,0
+input=20425,1
+input=20429,0
+input=20529,1
+input=20533,0
+input=20737,1
+input=20741,0
+input=20829,1
+input=20833,0
+input=20969,1
+input=20973,0
+input=21105,1
+input=21109,0
+input=21233,1
+input=21237,0
diff --git a/games/numdash/tests/replays/level4.txt b/games/numdash/tests/replays/level4.txt
new file mode 100644
index 00000000..1a2cc4eb
--- /dev/null
+++ b/games/numdash/tests/replays/level4.txt
@@ -0,0 +1,408 @@
+input=385,1
+input=389,0
+input=485,1
+input=489,0
+input=681,1
+input=685,0
+input=773,1
+input=777,0
+input=865,1
+input=869,0
+input=1073,1
+input=1077,0
+input=1281,1
+input=1285,0
+input=1453,1
+input=1457,0
+input=1557,1
+input=1561,0
+input=1649,1
+input=1653,0
+input=1881,1
+input=1885,0
+input=1973,1
+input=1977,0
+input=2109,1
+input=2113,0
+input=2273,1
+input=2277,0
+input=2373,1
+input=2377,0
+input=2457,1
+input=2461,0
+input=2585,1
+input=2589,0
+input=2805,1
+input=2809,0
+input=2905,1
+input=2909,0
+input=3101,1
+input=3105,0
+input=3193,1
+input=3197,0
+input=3301,1
+input=3305,0
+input=3389,1
+input=3393,0
+input=3589,1
+input=3593,0
+input=3773,1
+input=3777,0
+input=3957,1
+input=3961,0
+input=4069,1
+input=4073,0
+input=4257,1
+input=4261,0
+input=4533,1
+input=4537,0
+input=4637,1
+input=4641,0
+input=4741,1
+input=4745,0
+input=4809,1
+input=4813,0
+input=4881,1
+input=4885,0
+input=4949,1
+input=4953,0
+input=5133,1
+input=5137,0
+input=5201,1
+input=5205,0
+input=5269,1
+input=5273,0
+input=5545,1
+input=5549,0
+input=5809,1
+input=5813,0
+input=5913,1
+input=5917,0
+input=6017,1
+input=6021,0
+input=7145,1
+input=7149,0
+input=7305,1
+input=7309,0
+input=7445,1
+input=7449,0
+input=7557,1
+input=7561,0
+input=7649,1
+input=7653,0
+input=7749,1
+input=7753,0
+input=7925,1
+input=7929,0
+input=8025,1
+input=8029,0
+input=8225,1
+input=8229,0
+input=8341,1
+input=8345,0
+input=8433,1
+input=8437,0
+input=8525,1
+input=8529,0
+input=8601,1
+input=8605,0
+input=8781,1
+input=8785,0
+input=8873,1
+input=8877,0
+input=8969,1
+input=8973,0
+input=9145,1
+input=9149,0
+input=9241,1
+input=9245,0
+input=9333,1
+input=9337,0
+input=9405,1
+input=9409,0
+input=9581,1
+input=9585,0
+input=9649,1
+input=9653,0
+input=9765,1
+input=9769,0
+input=9861,1
+input=9865,0
+input=10033,1
+input=10037,0
+input=10137,1
+input=10141,0
+input=10277,1
+input=10281,0
+input=10369,1
+input=10373,0
+input=10437,1
+input=10441,0
+input=10505,1
+input=10509,0
+input=10737,1
+input=10741,0
+input=10889,1
+input=10893,0
+input=11085,1
+input=11089,0
+input=11177,1
+input=11181,0
+input=11433,1
+input=11437,0
+input=11545,1
+input=11549,0
+input=11853,1
+input=11857,0
+input=11941,1
+input=11945,0
+input=12033,1
+input=12037,0
+input=12205,1
+input=12209,0
+input=12309,1
+input=12313,0
+input=12445,1
+input=12449,0
+input=12537,1
+input=12541,0
+input=12701,1
+input=12705,0
+input=12793,1
+input=12797,0
+input=12885,1
+input=12889,0
+input=12985,1
+input=12989,0
+input=13193,1
+input=13261,0
+input=13749,1
+input=13817,0
+input=14405,1
+input=14449,0
+input=14485,1
+input=14505,0
+input=14509,1
+input=14517,0
+input=14521,1
+input=14529,0
+input=14537,1
+input=14545,0
+input=14549,1
+input=14557,0
+input=14685,1
+input=14721,0
+input=14725,1
+input=14749,0
+input=14761,1
+input=14769,0
+input=14781,1
+input=14789,0
+input=14801,1
+input=14805,0
+input=14809,1
+input=14813,0
+input=14817,1
+input=14821,0
+input=14833,1
+input=14841,0
+input=14849,1
+input=14853,0
+input=14861,1
+input=14865,0
+input=14873,1
+input=14881,0
+input=14893,1
+input=14897,0
+input=14901,1
+input=14905,0
+input=14909,1
+input=14913,0
+input=14925,1
+input=14933,0
+input=14945,1
+input=14953,0
+input=14965,1
+input=14969,0
+input=14973,1
+input=14977,0
+input=14981,1
+input=14985,0
+input=14997,1
+input=15005,0
+input=15013,1
+input=15017,0
+input=15025,1
+input=15029,0
+input=15037,1
+input=15045,0
+input=15057,1
+input=15061,0
+input=15065,1
+input=15069,0
+input=15073,1
+input=15077,0
+input=15089,1
+input=15097,0
+input=15109,1
+input=15117,0
+input=15129,1
+input=15133,0
+input=15137,1
+input=15141,0
+input=15145,1
+input=15149,0
+input=15161,1
+input=15169,0
+input=15177,1
+input=15181,0
+input=15189,1
+input=15193,0
+input=15201,1
+input=15209,0
+input=15221,1
+input=15225,0
+input=15229,1
+input=15233,0
+input=15237,1
+input=15241,0
+input=15253,1
+input=15261,0
+input=15273,1
+input=15281,0
+input=15293,1
+input=15297,0
+input=15301,1
+input=15305,0
+input=15309,1
+input=15313,0
+input=15325,1
+input=15333,0
+input=15341,1
+input=15345,0
+input=15353,1
+input=15357,0
+input=15365,1
+input=15373,0
+input=15385,1
+input=15389,0
+input=15393,1
+input=15397,0
+input=15401,1
+input=15405,0
+input=15417,1
+input=15425,0
+input=15437,1
+input=15445,0
+input=15457,1
+input=15461,0
+input=15465,1
+input=15469,0
+input=15473,1
+input=15477,0
+input=15489,1
+input=15497,0
+input=15505,1
+input=15509,0
+input=15517,1
+input=15521,0
+input=15529,1
+input=15537,0
+input=15549,1
+input=15553,0
+input=15557,1
+input=15561,0
+input=15565,1
+input=15569,0
+input=15581,1
+input=15589,0
+input=15601,1
+input=15609,0
+input=15621,1
+input=15625,0
+input=15629,1
+input=15633,0
+input=15637,1
+input=15641,0
+input=15653,1
+input=15661,0
+input=15669,1
+input=15673,0
+input=15681,1
+input=15685,0
+input=15689,1
+input=15693,0
+input=15701,1
+input=15705,0
+input=15713,1
+input=15717,0
+input=15721,1
+input=15725,0
+input=15729,1
+input=15733,0
+input=15745,1
+input=15753,0
+input=15765,1
+input=15773,0
+input=15785,1
+input=15789,0
+input=15793,1
+input=15797,0
+input=15801,1
+input=15805,0
+input=15813,1
+input=15817,0
+input=15825,1
+input=15829,0
+input=15833,1
+input=15837,0
+input=15845,1
+input=15877,0
+input=15881,1
+input=15885,0
+input=15889,1
+input=15909,0
+input=15917,1
+input=15933,0
+input=15957,1
+input=15961,0
+input=15965,1
+input=15973,0
+input=15985,1
+input=16009,0
+input=16485,1
+input=16489,0
+input=16693,1
+input=16697,0
+input=16813,1
+input=16817,0
+input=16949,1
+input=16953,0
+input=17133,1
+input=17137,0
+input=17253,1
+input=17257,0
+input=17381,1
+input=17385,0
+input=17473,1
+input=17477,0
+input=17597,1
+input=17601,0
+input=17661,1
+input=17665,0
+input=18017,1
+input=18021,0
+input=18181,1
+input=18185,0
+input=18285,1
+input=18289,0
+input=18429,1
+input=18433,0
+input=18541,1
+input=18545,0
+input=18701,1
+input=18705,0
+input=18769,1
+input=18773,0
+input=18941,1
+input=18945,0
diff --git a/games/numdash/tests/replays/level5.txt b/games/numdash/tests/replays/level5.txt
new file mode 100644
index 00000000..06d85aa2
--- /dev/null
+++ b/games/numdash/tests/replays/level5.txt
@@ -0,0 +1,304 @@
+input=425,1
+input=429,0
+input=609,1
+input=613,0
+input=713,1
+input=717,0
+input=817,1
+input=821,0
+input=1037,1
+input=1041,0
+input=1317,1
+input=1321,0
+input=1409,1
+input=1413,0
+input=1649,1
+input=1653,0
+input=1813,1
+input=1817,0
+input=1949,1
+input=1953,0
+input=2041,1
+input=2045,0
+input=2201,1
+input=2205,0
+input=2297,1
+input=2301,0
+input=2549,1
+input=2553,0
+input=2689,1
+input=2693,0
+input=2917,1
+input=2921,0
+input=3057,1
+input=3061,0
+input=3161,1
+input=3165,0
+input=3289,1
+input=3293,0
+input=3497,1
+input=3501,0
+input=3589,1
+input=3593,0
+input=3677,1
+input=3681,0
+input=3841,1
+input=3845,0
+input=3957,1
+input=3961,0
+input=4049,1
+input=4053,0
+input=4717,1
+input=4721,0
+input=4809,1
+input=4813,0
+input=5065,1
+input=5069,0
+input=5317,1
+input=5321,0
+input=5409,1
+input=5413,0
+input=5501,1
+input=5505,0
+input=5609,1
+input=5613,0
+input=5709,1
+input=5713,0
+input=5869,1
+input=5873,0
+input=5977,1
+input=5981,0
+input=6149,1
+input=6153,0
+input=6241,1
+input=6245,0
+input=6469,1
+input=6473,0
+input=6585,1
+input=6589,0
+input=6697,1
+input=6701,0
+input=6849,1
+input=6853,0
+input=6945,1
+input=6949,0
+input=7373,1
+input=7377,0
+input=7465,1
+input=7469,0
+input=7533,1
+input=7537,0
+input=7601,1
+input=7605,0
+input=7669,1
+input=7673,0
+input=7837,1
+input=7841,0
+input=7929,1
+input=7933,0
+input=8045,1
+input=8049,0
+input=8177,1
+input=8181,0
+input=8385,1
+input=8389,0
+input=8545,1
+input=8549,0
+input=8637,1
+input=8641,0
+input=8729,1
+input=8733,0
+input=8797,1
+input=8801,0
+input=8937,1
+input=8941,0
+input=9213,1
+input=9217,0
+input=9305,1
+input=9309,0
+input=9421,1
+input=9425,0
+input=9605,1
+input=9609,0
+input=9765,1
+input=9769,0
+input=10065,1
+input=10069,0
+input=10181,1
+input=10185,0
+input=10285,1
+input=10289,0
+input=10389,1
+input=10393,0
+input=10685,1
+input=10737,0
+input=10757,1
+input=10777,0
+input=10789,1
+input=10809,0
+input=10813,1
+input=10829,0
+input=10833,1
+input=10837,0
+input=10841,1
+input=10893,0
+input=11049,1
+input=11105,0
+input=11109,1
+input=11117,0
+input=11121,1
+input=11169,0
+input=11173,1
+input=11193,0
+input=11201,1
+input=11205,0
+input=11397,1
+input=11437,0
+input=11441,1
+input=11449,0
+input=11453,1
+input=11469,0
+input=11485,1
+input=11517,0
+input=11521,1
+input=11529,0
+input=11609,1
+input=11625,0
+input=11629,1
+input=11641,0
+input=11645,1
+input=11649,0
+input=11653,1
+input=11657,0
+input=11665,1
+input=11669,0
+input=11677,1
+input=11685,0
+input=11697,1
+input=11701,0
+input=11705,1
+input=11709,0
+input=11717,1
+input=11721,0
+input=11725,1
+input=11729,0
+input=11737,1
+input=11741,0
+input=11745,1
+input=11781,0
+input=11789,1
+input=11841,0
+input=11849,1
+input=11853,0
+input=12021,1
+input=12085,0
+input=12089,1
+input=12125,0
+input=12129,1
+input=12133,0
+input=12341,1
+input=12409,0
+input=12421,1
+input=12433,0
+input=12781,1
+input=12825,0
+input=12953,1
+input=13005,0
+input=13017,1
+input=13025,0
+input=13041,1
+input=13049,0
+input=13053,1
+input=13057,0
+input=13313,1
+input=13353,0
+input=13437,1
+input=13465,0
+input=13469,1
+input=13481,0
+input=13489,1
+input=13497,0
+input=13529,1
+input=13577,0
+input=13581,1
+input=13609,0
+input=13925,1
+input=13929,0
+input=14017,1
+input=14021,0
+input=14109,1
+input=14113,0
+input=14453,1
+input=14457,0
+input=14577,1
+input=14581,0
+input=14685,1
+input=14689,0
+input=14805,1
+input=14809,0
+input=14897,1
+input=14901,0
+input=14989,1
+input=14993,0
+input=15085,1
+input=15089,0
+input=15265,1
+input=15269,0
+input=15401,1
+input=15405,0
+input=15501,1
+input=15505,0
+input=15685,1
+input=15689,0
+input=15809,1
+input=15813,0
+input=15953,1
+input=15957,0
+input=16161,1
+input=16165,0
+input=16297,1
+input=16301,0
+input=16437,1
+input=16441,0
+input=16537,1
+input=16541,0
+input=16665,1
+input=16669,0
+input=16761,1
+input=16765,0
+input=16853,1
+input=16857,0
+input=16949,1
+input=16953,0
+input=17241,1
+input=17245,0
+input=17309,1
+input=17313,0
+input=17453,1
+input=17457,0
+input=17565,1
+input=17569,0
+input=17701,1
+input=17705,0
+input=17817,1
+input=17821,0
+input=18049,1
+input=18053,0
+input=18153,1
+input=18157,0
+input=18453,1
+input=18457,0
+input=18557,1
+input=18561,0
+input=18809,1
+input=18813,0
+input=18973,1
+input=18977,0
+input=19157,1
+input=19161,0
+input=19325,1
+input=19329,0
+input=19457,1
+input=19461,0
+input=19697,1
+input=19701,0
diff --git a/games/numdash/tests/replays/level6.txt b/games/numdash/tests/replays/level6.txt
new file mode 100644
index 00000000..32285693
--- /dev/null
+++ b/games/numdash/tests/replays/level6.txt
@@ -0,0 +1,336 @@
+input=205,1
+input=209,0
+input=273,1
+input=277,0
+input=449,1
+input=453,0
+input=517,1
+input=521,0
+input=725,1
+input=729,0
+input=793,1
+input=797,0
+input=861,1
+input=865,0
+input=977,1
+input=981,0
+input=1117,1
+input=1121,0
+input=1345,1
+input=1349,0
+input=1441,1
+input=1445,0
+input=1741,1
+input=1745,0
+input=1809,1
+input=1813,0
+input=2057,1
+input=2061,0
+input=2361,1
+input=2365,0
+input=2477,1
+input=2481,0
+input=2549,1
+input=2553,0
+input=2733,1
+input=2737,0
+input=2849,1
+input=2853,0
+input=3077,1
+input=3081,0
+input=3149,1
+input=3153,0
+input=3309,1
+input=3313,0
+input=3377,1
+input=3381,0
+input=3481,1
+input=3485,0
+input=3793,1
+input=3797,0
+input=3885,1
+input=3889,0
+input=4069,1
+input=4073,0
+input=4137,1
+input=4141,0
+input=4233,1
+input=4237,0
+input=4429,1
+input=4433,0
+input=4741,1
+input=4745,0
+input=4833,1
+input=4837,0
+input=5685,1
+input=5689,0
+input=5777,1
+input=5781,0
+input=5869,1
+input=5873,0
+input=6009,1
+input=6013,0
+input=6213,1
+input=6217,0
+input=6353,1
+input=6357,0
+input=6445,1
+input=6449,0
+input=6537,1
+input=6541,0
+input=6629,1
+input=6633,0
+input=6721,1
+input=6725,0
+input=6857,1
+input=6861,0
+input=6997,1
+input=7001,0
+input=7133,1
+input=7137,0
+input=7273,1
+input=7277,0
+input=7365,1
+input=7369,0
+input=7457,1
+input=7461,0
+input=7617,1
+input=7621,0
+input=7801,1
+input=7805,0
+input=7961,1
+input=7965,0
+input=8145,1
+input=8149,0
+input=8237,1
+input=8241,0
+input=8377,1
+input=8381,0
+input=8489,1
+input=8493,0
+input=8581,1
+input=8585,0
+input=8745,1
+input=8749,0
+input=8905,1
+input=8909,0
+input=9045,1
+input=9049,0
+input=9161,1
+input=9165,0
+input=9229,1
+input=9233,0
+input=9325,1
+input=9329,0
+input=9417,1
+input=9421,0
+input=9577,1
+input=9581,0
+input=9737,1
+input=9741,0
+input=9897,1
+input=9901,0
+input=9989,1
+input=9993,0
+input=10085,1
+input=10089,0
+input=10177,1
+input=10181,0
+input=10313,1
+input=10317,0
+input=10417,1
+input=10421,0
+input=10521,1
+input=10525,0
+input=10657,1
+input=10661,0
+input=10749,1
+input=10753,0
+input=10841,1
+input=10845,0
+input=11201,1
+input=11249,0
+input=11281,1
+input=11285,0
+input=11325,1
+input=11333,0
+input=11337,1
+input=11341,0
+input=11345,1
+input=11349,0
+input=11357,1
+input=11361,0
+input=11429,1
+input=11485,0
+input=11489,1
+input=11521,0
+input=11645,1
+input=11657,0
+input=11661,1
+input=11669,0
+input=11673,1
+input=11749,0
+input=11753,1
+input=11757,0
+input=11761,1
+input=11769,0
+input=11773,1
+input=11777,0
+input=11781,1
+input=11789,0
+input=11793,1
+input=11797,0
+input=11933,1
+input=11969,0
+input=11973,1
+input=11993,0
+input=12005,1
+input=12017,0
+input=12029,1
+input=12037,0
+input=12049,1
+input=12053,0
+input=12057,1
+input=12081,0
+input=12089,1
+input=12101,0
+input=12109,1
+input=12121,0
+input=12125,1
+input=12137,0
+input=12141,1
+input=12145,0
+input=12253,1
+input=12281,0
+input=12285,1
+input=12297,0
+input=12301,1
+input=12309,0
+input=12313,1
+input=12317,0
+input=12321,1
+input=12325,0
+input=12337,1
+input=12341,0
+input=12345,1
+input=12349,0
+input=12353,1
+input=12357,0
+input=12365,1
+input=12369,0
+input=12377,1
+input=12381,0
+input=12385,1
+input=12389,0
+input=12393,1
+input=12397,0
+input=12409,1
+input=12413,0
+input=12417,1
+input=12421,0
+input=12425,1
+input=12429,0
+input=12437,1
+input=12441,0
+input=12445,1
+input=12449,0
+input=12457,1
+input=12461,0
+input=12469,1
+input=12473,0
+input=12477,1
+input=12481,0
+input=12489,1
+input=12493,0
+input=12497,1
+input=12501,0
+input=12509,1
+input=12513,0
+input=12521,1
+input=12577,0
+input=12581,1
+input=12585,0
+input=12657,1
+input=12685,0
+input=12693,1
+input=12697,0
+input=12701,1
+input=12745,0
+input=13001,1
+input=13069,0
+input=13325,1
+input=13393,0
+input=13537,1
+input=13569,0
+input=13573,1
+input=13589,0
+input=13593,1
+input=13597,0
+input=13845,1
+input=13849,0
+input=13949,1
+input=13953,0
+input=14121,1
+input=14125,0
+input=14297,1
+input=14301,0
+input=14525,1
+input=14529,0
+input=14773,1
+input=14777,0
+input=15069,1
+input=15073,0
+input=15209,1
+input=15213,0
+input=15321,1
+input=15325,0
+input=15481,1
+input=15485,0
+input=15669,1
+input=15673,0
+input=15901,1
+input=15905,0
+input=16065,1
+input=16069,0
+input=16161,1
+input=16165,0
+input=16277,1
+input=16281,0
+input=16525,1
+input=16529,0
+input=16641,1
+input=16645,0
+input=16709,1
+input=16713,0
+input=17101,1
+input=17105,0
+input=17309,1
+input=17313,0
+input=17469,1
+input=17473,0
+input=17541,1
+input=17545,0
+input=17689,1
+input=17693,0
+input=17793,1
+input=17797,0
+input=17885,1
+input=17889,0
+input=17985,1
+input=17989,0
+input=18093,1
+input=18097,0
+input=18257,1
+input=18261,0
+input=18353,1
+input=18357,0
+input=18473,1
+input=18477,0
+input=18649,1
+input=18653,0
+input=18757,1
+input=18761,0
+input=18881,1
+input=18885,0
+input=18973,1
+input=18977,0
diff --git a/games/numdash/tests/replays/level7.txt b/games/numdash/tests/replays/level7.txt
new file mode 100644
index 00000000..023f0a2f
--- /dev/null
+++ b/games/numdash/tests/replays/level7.txt
@@ -0,0 +1,820 @@
+input=361,1
+input=365,0
+input=493,1
+input=497,0
+input=585,1
+input=589,0
+input=749,1
+input=753,0
+input=817,1
+input=821,0
+input=1001,1
+input=1005,0
+input=1301,1
+input=1305,0
+input=1461,1
+input=1465,0
+input=1645,1
+input=1649,0
+input=1773,1
+input=1777,0
+input=1877,1
+input=1881,0
+input=2037,1
+input=2041,0
+input=2201,1
+input=2205,0
+input=2293,1
+input=2297,0
+input=2421,1
+input=2425,0
+input=2505,1
+input=2509,0
+input=2677,1
+input=2681,0
+input=2745,1
+input=2749,0
+input=2813,1
+input=2817,0
+input=3009,1
+input=3013,0
+input=3169,1
+input=3173,0
+input=3261,1
+input=3265,0
+input=3421,1
+input=3425,0
+input=3561,1
+input=3565,0
+input=3725,1
+input=3729,0
+input=3881,1
+input=3885,0
+input=3973,1
+input=3977,0
+input=4133,1
+input=4137,0
+input=4213,1
+input=4217,0
+input=4525,1
+input=4529,0
+input=4605,1
+input=4609,0
+input=4849,1
+input=4853,0
+input=5009,1
+input=5013,0
+input=5101,1
+input=5105,0
+input=5245,1
+input=5281,0
+input=5285,1
+input=5305,0
+input=5309,1
+input=5317,0
+input=5321,1
+input=5325,0
+input=5329,1
+input=5333,0
+input=5341,1
+input=5345,0
+input=5349,1
+input=5353,0
+input=5361,1
+input=5365,0
+input=5369,1
+input=5373,0
+input=5381,1
+input=5385,0
+input=5393,1
+input=5397,0
+input=5401,1
+input=5405,0
+input=5409,1
+input=5413,0
+input=5425,1
+input=5433,0
+input=5445,1
+input=5453,0
+input=5465,1
+input=5469,0
+input=5473,1
+input=5477,0
+input=5485,1
+input=5489,0
+input=5493,1
+input=5497,0
+input=5501,1
+input=5505,0
+input=5517,1
+input=5521,0
+input=5525,1
+input=5529,0
+input=5533,1
+input=5537,0
+input=5545,1
+input=5549,0
+input=5557,1
+input=5565,0
+input=5577,1
+input=5581,0
+input=5585,1
+input=5589,0
+input=5597,1
+input=5601,0
+input=5609,1
+input=5617,0
+input=5629,1
+input=5633,0
+input=5637,1
+input=5641,0
+input=5649,1
+input=5657,0
+input=5661,1
+input=5681,0
+input=5685,1
+input=5689,0
+input=5697,1
+input=5729,0
+input=5733,1
+input=5737,0
+input=5765,1
+input=5781,0
+input=5949,1
+input=5961,0
+input=5965,1
+input=5969,0
+input=5977,1
+input=5993,0
+input=5997,1
+input=6001,0
+input=6005,1
+input=6013,0
+input=6021,1
+input=6029,0
+input=6033,1
+input=6037,0
+input=6041,1
+input=6049,0
+input=6057,1
+input=6065,0
+input=6069,1
+input=6073,0
+input=6077,1
+input=6081,0
+input=6085,1
+input=6089,0
+input=6093,1
+input=6101,0
+input=6109,1
+input=6117,0
+input=6121,1
+input=6125,0
+input=6129,1
+input=6137,0
+input=6145,1
+input=6153,0
+input=6157,1
+input=6161,0
+input=6165,1
+input=6169,0
+input=6173,1
+input=6177,0
+input=6181,1
+input=6189,0
+input=6197,1
+input=6205,0
+input=6209,1
+input=6213,0
+input=6217,1
+input=6225,0
+input=6233,1
+input=6241,0
+input=6245,1
+input=6249,0
+input=6253,1
+input=6257,0
+input=6261,1
+input=6265,0
+input=6269,1
+input=6277,0
+input=6285,1
+input=6293,0
+input=6297,1
+input=6301,0
+input=6305,1
+input=6321,0
+input=6325,1
+input=6361,0
+input=6373,1
+input=6381,0
+input=6401,1
+input=6421,0
+input=6425,1
+input=6429,0
+input=6585,1
+input=6629,0
+input=6633,1
+input=6637,0
+input=6641,1
+input=6661,0
+input=6805,1
+input=6845,0
+input=6849,1
+input=6865,0
+input=6877,1
+input=6885,0
+input=6893,1
+input=6901,0
+input=6905,1
+input=6933,0
+input=6941,1
+input=6961,0
+input=6977,1
+input=6997,0
+input=7001,1
+input=7005,0
+input=7161,1
+input=7213,0
+input=7217,1
+input=7229,0
+input=7233,1
+input=7241,0
+input=7357,1
+input=7377,0
+input=7381,1
+input=7413,0
+input=7417,1
+input=7441,0
+input=7445,1
+input=7457,0
+input=7465,1
+input=7477,0
+input=7481,1
+input=7485,0
+input=7493,1
+input=7517,0
+input=7617,1
+input=7649,0
+input=7653,1
+input=7693,0
+input=7697,1
+input=7701,0
+input=7717,1
+input=7737,0
+input=7741,1
+input=7745,0
+input=7853,1
+input=7857,0
+input=7945,1
+input=7949,0
+input=8081,1
+input=8085,0
+input=8269,1
+input=8273,0
+input=8337,1
+input=8341,0
+input=8497,1
+input=8501,0
+input=8637,1
+input=8641,0
+input=8809,1
+input=8813,0
+input=8965,1
+input=8969,0
+input=9145,1
+input=9149,0
+input=9237,1
+input=9241,0
+input=9377,1
+input=9381,0
+input=9525,1
+input=9529,0
+input=9649,1
+input=9653,0
+input=9741,1
+input=9745,0
+input=9809,1
+input=9813,0
+input=9925,1
+input=9929,0
+input=10109,1
+input=10113,0
+input=10205,1
+input=10209,0
+input=10369,1
+input=10373,0
+input=10505,1
+input=10509,0
+input=10693,1
+input=10697,0
+input=10829,1
+input=10833,0
+input=10897,1
+input=10901,0
+input=11005,1
+input=11009,0
+input=11153,1
+input=11157,0
+input=11277,1
+input=11281,0
+input=11421,1
+input=11425,0
+input=11565,1
+input=11569,0
+input=11689,1
+input=11693,0
+input=11893,1
+input=11897,0
+input=11985,1
+input=11989,0
+input=12145,1
+input=12149,0
+input=12285,1
+input=12289,0
+input=12445,1
+input=12449,0
+input=12621,1
+input=12625,0
+input=12713,1
+input=12717,0
+input=12873,1
+input=12877,0
+input=13045,1
+input=13089,0
+input=13093,1
+input=13101,0
+input=13105,1
+input=13117,0
+input=13125,1
+input=13129,0
+input=13133,1
+input=13141,0
+input=13153,1
+input=13161,0
+input=13169,1
+input=13173,0
+input=13181,1
+input=13185,0
+input=13189,1
+input=13193,0
+input=13201,1
+input=13205,0
+input=13213,1
+input=13221,0
+input=13233,1
+input=13237,0
+input=13241,1
+input=13245,0
+input=13253,1
+input=13257,0
+input=13261,1
+input=13265,0
+input=13273,1
+input=13277,0
+input=13281,1
+input=13285,0
+input=13293,1
+input=13297,0
+input=13301,1
+input=13305,0
+input=13313,1
+input=13317,0
+input=13325,1
+input=13329,0
+input=13333,1
+input=13337,0
+input=13345,1
+input=13349,0
+input=13353,1
+input=13357,0
+input=13365,1
+input=13369,0
+input=13373,1
+input=13377,0
+input=13385,1
+input=13389,0
+input=13397,1
+input=13401,0
+input=13405,1
+input=13409,0
+input=13417,1
+input=13421,0
+input=13425,1
+input=13429,0
+input=13437,1
+input=13441,0
+input=13445,1
+input=13449,0
+input=13457,1
+input=13461,0
+input=13465,1
+input=13469,0
+input=13477,1
+input=13481,0
+input=13489,1
+input=13493,0
+input=13497,1
+input=13501,0
+input=13509,1
+input=13513,0
+input=13517,1
+input=13521,0
+input=13529,1
+input=13533,0
+input=13537,1
+input=13541,0
+input=13549,1
+input=13553,0
+input=13561,1
+input=13565,0
+input=13569,1
+input=13573,0
+input=13581,1
+input=13585,0
+input=13589,1
+input=13593,0
+input=13597,1
+input=13601,0
+input=13613,1
+input=13617,0
+input=13621,1
+input=13625,0
+input=13629,1
+input=13633,0
+input=13641,1
+input=13645,0
+input=13653,1
+input=13657,0
+input=13661,1
+input=13665,0
+input=13673,1
+input=13677,0
+input=13681,1
+input=13685,0
+input=13693,1
+input=13697,0
+input=13701,1
+input=13705,0
+input=13713,1
+input=13717,0
+input=13725,1
+input=13729,0
+input=13733,1
+input=13737,0
+input=13741,1
+input=13745,0
+input=13757,1
+input=13765,0
+input=13777,1
+input=13781,0
+input=13785,1
+input=13789,0
+input=13793,1
+input=13797,0
+input=13805,1
+input=13809,0
+input=13817,1
+input=13821,0
+input=13825,1
+input=13829,0
+input=13837,1
+input=13841,0
+input=13845,1
+input=13849,0
+input=13857,1
+input=13861,0
+input=13865,1
+input=13869,0
+input=13877,1
+input=13881,0
+input=13889,1
+input=13893,0
+input=13897,1
+input=13901,0
+input=13905,1
+input=13909,0
+input=13921,1
+input=13929,0
+input=13941,1
+input=13945,0
+input=13949,1
+input=13953,0
+input=13957,1
+input=13961,0
+input=13969,1
+input=13973,0
+input=13981,1
+input=13985,0
+input=13989,1
+input=13993,0
+input=14001,1
+input=14005,0
+input=14009,1
+input=14013,0
+input=14021,1
+input=14025,0
+input=14029,1
+input=14033,0
+input=14041,1
+input=14045,0
+input=14053,1
+input=14061,0
+input=14073,1
+input=14077,0
+input=14085,1
+input=14093,0
+input=14105,1
+input=14113,0
+input=14125,1
+input=14129,0
+input=14133,1
+input=14137,0
+input=14145,1
+input=14149,0
+input=14153,1
+input=14157,0
+input=14161,1
+input=14165,0
+input=14177,1
+input=14181,0
+input=14185,1
+input=14189,0
+input=14193,1
+input=14197,0
+input=14205,1
+input=14209,0
+input=14217,1
+input=14225,0
+input=14237,1
+input=14241,0
+input=14249,1
+input=14257,0
+input=14269,1
+input=14277,0
+input=14289,1
+input=14293,0
+input=14297,1
+input=14301,0
+input=14309,1
+input=14317,0
+input=14329,1
+input=14333,0
+input=14341,1
+input=14349,0
+input=14361,1
+input=14365,0
+input=14369,1
+input=14373,0
+input=14377,1
+input=14381,0
+input=14393,1
+input=14401,0
+input=14409,1
+input=14413,0
+input=14421,1
+input=14425,0
+input=14433,1
+input=14441,0
+input=14453,1
+input=14457,0
+input=14461,1
+input=14465,0
+input=14469,1
+input=14473,0
+input=14485,1
+input=14493,0
+input=14505,1
+input=14513,0
+input=14525,1
+input=14529,0
+input=14533,1
+input=14537,0
+input=14541,1
+input=14545,0
+input=14553,1
+input=14557,0
+input=14565,1
+input=14569,0
+input=14573,1
+input=14577,0
+input=14585,1
+input=14589,0
+input=14593,1
+input=14597,0
+input=14605,1
+input=14609,0
+input=14617,1
+input=14621,0
+input=14625,1
+input=14629,0
+input=14633,1
+input=14637,0
+input=14649,1
+input=14657,0
+input=14669,1
+input=14677,0
+input=14689,1
+input=14693,0
+input=14697,1
+input=14701,0
+input=14705,1
+input=14709,0
+input=14717,1
+input=14721,0
+input=14729,1
+input=14733,0
+input=14737,1
+input=14741,0
+input=14749,1
+input=14753,0
+input=14757,1
+input=14761,0
+input=14769,1
+input=14773,0
+input=14781,1
+input=14785,0
+input=14789,1
+input=14793,0
+input=14797,1
+input=14801,0
+input=14813,1
+input=14821,0
+input=14833,1
+input=14841,0
+input=14853,1
+input=14857,0
+input=14861,1
+input=14865,0
+input=14869,1
+input=14873,0
+input=14881,1
+input=14885,0
+input=14893,1
+input=14897,0
+input=14901,1
+input=14905,0
+input=14913,1
+input=14917,0
+input=14921,1
+input=14925,0
+input=14933,1
+input=14937,0
+input=14945,1
+input=14953,0
+input=14965,1
+input=14969,0
+input=14973,1
+input=14977,0
+input=14985,1
+input=14989,0
+input=14993,1
+input=14997,0
+input=15005,1
+input=15009,0
+input=15017,1
+input=15025,0
+input=15037,1
+input=15041,0
+input=15045,1
+input=15049,0
+input=15057,1
+input=15061,0
+input=15065,1
+input=15069,0
+input=15077,1
+input=15081,0
+input=15085,1
+input=15089,0
+input=15097,1
+input=15101,0
+input=15109,1
+input=15117,0
+input=15129,1
+input=15133,0
+input=15137,1
+input=15141,0
+input=15149,1
+input=15153,0
+input=15157,1
+input=15161,0
+input=15169,1
+input=15173,0
+input=15181,1
+input=15189,0
+input=15201,1
+input=15205,0
+input=15209,1
+input=15213,0
+input=15221,1
+input=15225,0
+input=15229,1
+input=15233,0
+input=15241,1
+input=15245,0
+input=15249,1
+input=15253,0
+input=15261,1
+input=15265,0
+input=15269,1
+input=15273,0
+input=15285,1
+input=15293,0
+input=15301,1
+input=15305,0
+input=15313,1
+input=15317,0
+input=15321,1
+input=15325,0
+input=15333,1
+input=15337,0
+input=15341,1
+input=15345,0
+input=15353,1
+input=15357,0
+input=15365,1
+input=15369,0
+input=15373,1
+input=15377,0
+input=15385,1
+input=15389,0
+input=15393,1
+input=15397,0
+input=15405,1
+input=15409,0
+input=15413,1
+input=15425,0
+input=15429,1
+input=15477,0
+input=15481,1
+input=15497,0
+input=15501,1
+input=15505,0
+input=15589,1
+input=15593,0
+input=15773,1
+input=15777,0
+input=15865,1
+input=15869,0
+input=16001,1
+input=16005,0
+input=16165,1
+input=16169,0
+input=16393,1
+input=16397,0
+input=16509,1
+input=16513,0
+input=16669,1
+input=16673,0
+input=16761,1
+input=16765,0
+input=16845,1
+input=16849,0
+input=17041,1
+input=17045,0
+input=17145,1
+input=17149,0
+input=17237,1
+input=17241,0
+input=17489,1
+input=17493,0
+input=17617,1
+input=17621,0
+input=17709,1
+input=17713,0
+input=17869,1
+input=17873,0
+input=17961,1
+input=17965,0
+input=18197,1
+input=18201,0
+input=18357,1
+input=18361,0
+input=18521,1
+input=18525,0
+input=18681,1
+input=18685,0
+input=18773,1
+input=18777,0
+input=18841,1
+input=18845,0
+input=19001,1
+input=19005,0
+input=19233,1
+input=19237,0
+input=19393,1
+input=19397,0
+input=19481,1
+input=19485,0
+input=19645,1
+input=19649,0
+input=19805,1
+input=19809,0
+input=19965,1
+input=19969,0
+input=20057,1
+input=20061,0
+input=20217,1
+input=20221,0
+input=20349,1
+input=20353,0
diff --git a/games/numdash/tests/test.c b/games/numdash/tests/test.c
new file mode 100644
index 00000000..65b7f732
--- /dev/null
+++ b/games/numdash/tests/test.c
@@ -0,0 +1,527 @@
+/* Host tests: level data, physics, saves and storage safety, and the app
+ * driven through its real input path. Extra modes:
+ * tests --replay <level> <file> complete a level with a recorded input
+ * tests --shots <dir> render every screen to PPM files */
+#include "app.h"
+#include "ui.h"
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* ------------------------------------------------------------ platform */
+
+static uint8_t store[42 * 1024];
+static uint16_t fb[GFX_W * GFX_H];
+static unsigned frame_ticks;
+uint8_t *platform_storage(size_t *size) { *size = sizeof(store); return store; }
+void platform_storage_commit(void) {}
+bool platform_init(void) { return true; }
+void platform_close(void) {}
+uint32_t platform_keys(void) { return 0; }
+uint32_t platform_millis(void) { return 0; }
+void platform_sleep(unsigned ms) { (void)ms; }
+uint32_t platform_random(void) { return 12345; }
+void platform_frame_begin(bool vsync) { (void)vsync; }
+void platform_strip(int y, int h, const uint16_t *px) { memcpy(fb + y * GFX_W, px, (size_t)h * GFX_W * 2); }
+void platform_frame_end(void) {}
+
+static void render(void) {
+ for (int s = 0; s < STRIPS; s++) {
+ gfx_begin_strip(s);
+ app_draw();
+ platform_strip(s * STRIP_H, STRIP_H, gfx_strip);
+ }
+}
+static void save_ppm(const char *dir, const char *name) {
+ char path[512];
+ snprintf(path, sizeof(path), "%s/%s.ppm", dir, name);
+ FILE *f = fopen(path, "wb");
+ assert(f);
+ fprintf(f, "P6\n%d %d\n255\n", GFX_W, GFX_H);
+ for (int i = 0; i < GFX_W * GFX_H; i++) {
+ uint8_t c[3] = {(uint8_t)c_r(fb[i]), (uint8_t)c_g(fb[i]), (uint8_t)c_b(fb[i])};
+ fwrite(c, 1, 3, f);
+ }
+ fclose(f);
+}
+/* Runs the app for n physics ticks with keys held, 40 frames per second,
+ * drawing every frame like the device does. */
+static bool draw_frames = true;
+static void run(uint32_t keys, int n) {
+ for (int i = 0; i < n; i++) {
+ app_tick(keys);
+ if (++frame_ticks % 6 == 0) {
+ app_frame(6.0f / ND_HZ);
+ if (draw_frames) render();
+ }
+ }
+}
+static void tap(uint32_t k) { run(k, 6); run(0, 6); }
+static void settle(void) { run(0, 240); }
+static void fresh_app(void) {
+ memset(store, 0, sizeof(store));
+ app_init();
+ assert(app.screen == SCR_LOADING);
+ run(0, 240 * 2 + 60); /* loading screen, then the fade into the menu */
+ assert(app.screen == SCR_MENU);
+}
+
+/* ------------------------------------------------------------ unit tests */
+
+static void test_levels(void) {
+ static Level L;
+ static const uint16_t counts[LEVEL_COUNT] = {2272, 1530, 1509, 1402, 2126, 1691, 2767};
+ for (unsigned i = 0; i < LEVEL_COUNT; i++) {
+ assert(level_load_builtin(&L, i));
+ assert(L.count == counts[i]);
+ assert(level_valid(&L));
+ unsigned coins = 0;
+ for (unsigned k = 0; k < L.count; k++) coins += L.objs[k].type == OT_COIN;
+ assert(coins <= 3);
+ }
+ assert(!level_load_builtin(&L, LEVEL_COUNT));
+ uint8_t out[8];
+ static const uint8_t bad[] = {0xff, 0xff, 0xff};
+ assert(inflate_raw(out, sizeof(out), bad, sizeof(bad)) < 0);
+}
+
+static void test_physics(void) {
+ static Level L;
+ static Game a, b;
+ memset(&L, 0, sizeof(L));
+ L.objs = level_objs;
+ L.end_x = L.wall_x = 60000;
+ game_start(&a, &L, false);
+ float peak = 0;
+ for (int i = 0; i < 240; i++) {
+ game_step(&a, i < 4);
+ if (a.p.y > peak) peak = a.p.y;
+ }
+ /* A GD cube jump peaks a little over two blocks above the ground. */
+ assert(peak > 15 + 60 && peak < 15 + 90);
+ assert(a.p.on_ground && !a.dead && a.jumps == 1);
+ game_start(&a, &L, false);
+ game_start(&b, &L, false);
+ for (int i = 0; i < 2000; i++) {
+ bool h = (i / 37) % 3 == 0;
+ game_step(&a, h);
+ game_step(&b, h);
+ }
+ assert(!memcmp(&a, &b, sizeof(a)));
+ Checkpoint c;
+ game_save_checkpoint(&a, &c);
+ for (int i = 0; i < 100; i++) game_step(&a, i % 20 < 5);
+ game_load_checkpoint(&a, &c);
+ game_load_checkpoint(&b, &c);
+ for (int i = 0; i < 300; i++) { game_step(&a, i % 30 < 8); game_step(&b, i % 30 < 8); }
+ assert(!memcmp(&a.p, &b.p, sizeof(a.p)));
+ /* a spike on the ground kills */
+ level_objs[0] = (LObj){300, 15, OT_SPIKE, 0};
+ L.count = 1;
+ game_start(&a, &L, false);
+ for (int i = 0; i < 400 && !a.dead; i++) game_step(&a, false);
+ assert(a.dead && a.death_obj == 0);
+ /* landing on a block is safe */
+ level_objs[0] = (LObj){300, 15, OT_BLOCK, 0};
+ game_start(&a, &L, false);
+ for (int i = 0; i < 400 && !a.dead; i++) game_step(&a, i >= 150 && i < 154);
+ assert(!a.dead && a.p.x > 400);
+}
+
+static void test_storage(void) {
+ static uint8_t arena[4096];
+ memset(arena, 0, sizeof(arena));
+ const uint8_t small[3] = {7, 8, 9};
+ uint8_t prog[PROGRESS_BYTES];
+ Progress p;
+ progress_defaults(&p);
+ p.lv[2].normal = 57;
+ p.lv[2].attempts = 123456;
+ p.jumps = 99;
+ p.options = OPT_FPS | OPT_BAR;
+ progress_encode(&p, prog);
+ assert(storage_put(arena, sizeof(arena), "a.py", small, 3, 1));
+ assert(storage_put(arena, sizeof(arena), "numdash.nds", prog, sizeof(prog), 1));
+ assert(storage_put(arena, sizeof(arena), "b.py", small, 3, 1));
+ size_t len;
+ const uint8_t *bpy = storage_read(arena, sizeof(arena), "b.py", &len);
+ assert(bpy && len == 3 && !memcmp(bpy, small, 3));
+ /* rewriting with the same size leaves every other record in place */
+ p.lv[2].normal = 58;
+ progress_encode(&p, prog);
+ assert(storage_put(arena, sizeof(arena), "numdash.nds", prog, sizeof(prog), 1));
+ assert(storage_read(arena, sizeof(arena), "b.py", &len) == bpy);
+ Progress q;
+ const uint8_t *d = storage_read(arena, sizeof(arena), "numdash.nds", &len);
+ assert(d && progress_decode(&q, d, len) && q.lv[2].normal == 58 && q.lv[2].attempts == 123456 && q.options == (OPT_FPS | OPT_BAR));
+ /* a record that is not the last one never grows */
+ uint32_t crc = nd_crc32(arena, sizeof(arena));
+ uint8_t big[400] = {1};
+ assert(!storage_put(arena, sizeof(arena), "numdash.nds", big, sizeof(big), 1));
+ assert(crc == nd_crc32(arena, sizeof(arena)));
+ /* but it can shrink in place (padded) */
+ assert(storage_put(arena, sizeof(arena), "numdash.nds", small, 3, 1));
+ assert(storage_read(arena, sizeof(arena), "b.py", &len) == bpy);
+ d = storage_read(arena, sizeof(arena), "numdash.nds", &len);
+ assert(d && len == PROGRESS_BYTES && d[0] == 7 && d[3] == 0);
+ assert(!storage_remove_last(arena, sizeof(arena), "numdash.nds"));
+ /* the last record is resized freely */
+ assert(storage_put(arena, sizeof(arena), "c.ndl", big, sizeof(big), 512));
+ assert(storage_put(arena, sizeof(arena), "c.ndl", big, 1000 > sizeof(big) ? sizeof(big) : 0, 512));
+ static uint8_t huge[1500];
+ assert(storage_put(arena, sizeof(arena), "c.ndl", huge, sizeof(huge), 512));
+ assert(storage_read(arena, sizeof(arena), "b.py", &len) == bpy);
+ assert(storage_read(arena, sizeof(arena), "c.ndl", &len) && len >= sizeof(huge));
+ assert(storage_remove_last(arena, sizeof(arena), "c.ndl"));
+ assert(!storage_read(arena, sizeof(arena), "c.ndl", &len));
+ assert(storage_read(arena, sizeof(arena), "b.py", &len) == bpy);
+ /* full storage */
+ static uint8_t giant[4000];
+ assert(!storage_put(arena, sizeof(arena), "d.ndl", giant, sizeof(giant), 1));
+ /* malformed storage is rejected, never written */
+ memset(arena, 0xff, 64);
+ assert(!storage_put(arena, sizeof(arena), "numdash.nds", prog, sizeof(prog), 1));
+ for (int j = 0; j < 3000; j++) {
+ size_t size = (unsigned)(j * 7) % sizeof(arena);
+ for (size_t i = 0; i < size; i++) arena[i] = (uint8_t)(i * 31 + j * 17 + (i >> 3));
+ storage_read(arena, size, "numdash.nds", &len);
+ storage_put(arena, size, "numdash.nds", prog, sizeof(prog), 1);
+ }
+ /* corrupted progress is rejected */
+ progress_encode(&p, prog);
+ for (int i = 0; i < PROGRESS_BYTES; i += 7) {
+ prog[i] ^= 0x10;
+ assert(!progress_decode(&q, prog, sizeof(prog)));
+ prog[i] ^= 0x10;
+ }
+ assert(progress_decode(&q, prog, sizeof(prog)));
+}
+
+static void test_custom(void) {
+ static LObj a[CUSTOM_MAX], b[CUSTOM_MAX];
+ static uint8_t buf[16 + CUSTOM_MAX * 8];
+ unsigned n = 0, x = 15;
+ for (unsigned i = 0; i < 600; i++) {
+ x += (i * 7) % 3 == 0 ? 30 : 0;
+ a[n++] = (LObj){(uint16_t)x, (int16_t)(15 + (i % 9) * 30 - (i % 4 == 0 ? 13 : 0)), (uint8_t)(1 + i % (OT_COUNT - 1)), (uint8_t)(i & 3)};
+ }
+ CustomMeta m = {(uint16_t)n, 9000, 3, 1, true}, m2;
+ size_t len = custom_encode(a, n, &m, buf, sizeof(buf));
+ assert(len > 16 && len < n * 5 + 16);
+ assert(custom_decode(buf, len, b, CUSTOM_MAX, &m2));
+ assert(m2.count == n && m2.theme == 3 && m2.flags == 1 && m2.end_x == 9000);
+ assert(!memcmp(a, b, n * sizeof(LObj)));
+ for (size_t i = 0; i < len; i += 5) {
+ buf[i] ^= 4;
+ assert(!custom_decode(buf, len, b, CUSTOM_MAX, &m2));
+ buf[i] ^= 4;
+ }
+ assert(!custom_encode(a, n, &m, buf, 64));
+}
+
+/* Builds a save of the previous NumDash release (format NDASH003). */
+static size_t legacy_save(uint8_t *out) {
+ static const struct { int16_t x, y; uint16_t id; uint8_t rot; } objs[3] = {{15, 15, 1, 0}, {45, 15, 8, 0}, {75, 2, 35, 0}};
+ size_t n = 16;
+ memcpy(out, "NDASH003", 8);
+ for (int i = 0; i < 10; i++) {
+ out[n++] = (uint8_t)(i == 1 ? 64 : 0);
+ out[n++] = (uint8_t)(i == 1 ? 100 : 0);
+ out[n++] = (uint8_t)(i == 1 ? 2 : 0);
+ uint32_t att = i == 1 ? 321 : 0;
+ memcpy(out + n, &att, 4);
+ n += 4;
+ }
+ out[n++] = 1; out[n++] = 1; out[n++] = 0; out[n++] = 0;
+ for (int s = 0; s < 3; s++) {
+ unsigned c = s == 0 ? 3 : 0;
+ out[n] = (uint8_t)c; out[n + 1] = 0; out[n + 2] = 0x08; out[n + 3] = 0x07; out[n + 4] = 1; out[n + 5] = 128;
+ n += 6;
+ for (unsigned j = 0; j < c; j++) {
+ memcpy(out + n, &objs[j].x, 2); memcpy(out + n + 2, &objs[j].y, 2); memcpy(out + n + 4, &objs[j].id, 2);
+ out[n + 6] = objs[j].rot; out[n + 7] = 0;
+ n += 8;
+ }
+ }
+ uint32_t size = (uint32_t)n, crc = nd_crc32(out + 16, n - 16);
+ memcpy(out + 8, &size, 4);
+ memcpy(out + 12, &crc, 4);
+ return n;
+}
+
+static void test_legacy(void) {
+ static uint8_t old[512];
+ size_t n = legacy_save(old);
+ memset(store, 0, sizeof(store));
+ assert(storage_put(store, sizeof(store), "numdash.ndd", old, n, 1));
+ Progress p;
+ CustomMeta metas[CUSTOM_SLOTS];
+ assert(save_load_all(&p, metas));
+ assert(p.lv[1].normal == 64 && p.lv[1].practice == 100 && p.lv[1].coins == 3 && p.lv[1].attempts == 321);
+ assert(metas[0].exists && metas[0].count == 3 && !metas[1].exists);
+ size_t len;
+ assert(storage_read(store, sizeof(store), "numdash.nds", &len));
+ assert(!storage_read(store, sizeof(store), "numdash.ndd", &len)); /* it was last: removed */
+ static LObj objs[8];
+ CustomMeta m;
+ assert(save_read_custom(0, objs, 8, &m) && m.count == 3 && objs[1].type == OT_SPIKE && objs[2].type == OT_PAD_Y);
+ /* the second load uses the new records */
+ assert(save_load_all(&p, metas) && p.lv[1].attempts == 321);
+}
+
+/* ------------------------------------------------------------ app flow */
+
+static void test_app(void) {
+ fresh_app();
+ assert(app.screen == SCR_MENU && app.sel == 1);
+ tap(K_OK);
+ settle();
+ assert(app.screen == SCR_SELECT);
+ tap(K_RIGHT);
+ tap(K_LEFT);
+ tap(K_EXE);
+ settle();
+ assert(app.screen == SCR_PLAY && app.level == 0 && app.attempt == 1);
+ run(0, 240 * 8); /* no input: the first spike kills */
+ assert(app.attempt >= 2 && progress.lv[0].attempts >= 2 && progress.lv[0].normal > 0);
+ tap(K_BACK);
+ assert(app.paused);
+ run(0, 100);
+ tap(K_BACK);
+ assert(!app.paused);
+ /* practice: checkpoint then restart from it */
+ tap(K_BACK);
+ app.sel = 0;
+ tap(K_OK);
+ assert(app.practice && !app.paused);
+ run(0, 200);
+ tap(K_CHECK);
+ assert(app.checkpoint_count == 1);
+ tap(K_ERASE);
+ assert(app.checkpoint_count == 0);
+ tap(K_BACK);
+ app.sel = 2; /* menu */
+ tap(K_OK);
+ settle();
+ assert(app.screen == SCR_SELECT);
+ size_t len;
+ const uint8_t *d = storage_read(store, sizeof(store), "numdash.nds", &len);
+ Progress p;
+ assert(d && progress_decode(&p, d, len) && p.lv[0].attempts == progress.lv[0].attempts);
+ tap(K_BACK);
+ settle();
+ assert(app.screen == SCR_MENU);
+ /* quit dialog */
+ tap(K_BACK);
+ assert(app.dialog == DLG_QUIT);
+ tap(K_BACK);
+ assert(!app.dialog && app.running);
+ /* settings popup toggles and saves */
+ app.sel = 4;
+ tap(K_OK);
+ run(0, 60);
+ uint8_t before = progress.options;
+ tap(K_OK);
+ assert(progress.options == (before ^ OPT_PERCENT));
+ tap(K_BACK);
+ d = storage_read(store, sizeof(store), "numdash.nds", &len);
+ assert(d && progress_decode(&p, d, len) && p.options == progress.options);
+}
+
+static void test_editor(void) {
+ fresh_app();
+ app.sel = 2;
+ tap(K_OK);
+ settle();
+ assert(app.screen == SCR_CREATOR);
+ tap(K_OK);
+ settle();
+ assert(app.screen == SCR_EDITOR);
+ for (int i = 0; i < 5; i++) { tap(K_RIGHT); tap(K_OK); }
+ tap(K_PLUS);
+ for (int i = 0; i < 6; i++) tap(K_PLUS);
+ tap(K_RIGHT); tap(K_RIGHT); tap(K_OK);
+ assert(editor_object_count() == 6);
+ tap(K_UNDO);
+ assert(editor_object_count() == 5);
+ tap(K_ERASE); /* nothing under the cursor now */
+ tap(K_LEFT); tap(K_LEFT);
+ tap(K_ERASE);
+ assert(editor_object_count() == 4);
+ tap(K_SAVE);
+ CustomMeta m;
+ static LObj objs[16];
+ assert(save_read_custom(0, objs, 16, &m) && m.count == 4);
+ tap(K_EXE);
+ settle();
+ assert(app.screen == SCR_PLAY && app.testing);
+ run(K_OK, 240);
+ tap(K_BACK);
+ app.sel = 2;
+ tap(K_OK);
+ settle();
+ assert(app.screen == SCR_EDITOR && editor_object_count() == 4);
+ tap(K_BACK);
+ settle();
+ assert(app.screen == SCR_CREATOR && custom_meta[0].count == 4);
+}
+
+/* ------------------------------------------------------------ replay */
+
+static int replay(int index, const char *path) {
+ static Level L;
+ static Game g;
+ if (!level_load_builtin(&L, (unsigned)index)) return 2;
+ FILE *f = fopen(path, "r");
+ if (!f) return 2;
+ static int ticks[8192], vals[8192];
+ int n = 0, t, v;
+ while (n < 8192 && fscanf(f, "input=%d,%d\n", &t, &v) == 2) { ticks[n] = t; vals[n++] = v; }
+ fclose(f);
+ game_start(&g, &L, false);
+ bool held = false;
+ for (int i = 1, pos = 0; i < 200 * ND_HZ && !g.dead && !g.complete; i++) {
+ while (pos < n && ticks[pos] <= i) held = vals[pos++] != 0;
+ game_step(&g, held);
+ g.fx_count = 0;
+ }
+ printf("%s: %s at %.0f%% (x=%.0f)\n", L.name, g.complete ? "COMPLETE" : "FAILED", game_progress(&g), g.p.x);
+ return g.complete ? 0 : 1;
+}
+
+/* ------------------------------------------------------------ screenshots */
+
+static int shots(const char *dir) {
+ fresh_app();
+ progress.lv[0].normal = 64;
+ progress.lv[0].practice = 100;
+ progress.lv[0].coins = 5;
+ progress.lv[1].normal = 12;
+ run(0, 240 * 3);
+ render(); save_ppm(dir, "01_menu");
+ app.sel = 4; tap(K_OK); run(0, 120);
+ render(); save_ppm(dir, "02_settings");
+ tap(K_BACK); app.sel = 5; tap(K_OK); run(0, 120);
+ render(); save_ppm(dir, "03_stats");
+ tap(K_BACK); app.sel = 3; tap(K_OK); run(0, 120);
+ render(); save_ppm(dir, "04_help");
+ tap(K_BACK); app.sel = 1; tap(K_OK); settle();
+ render(); save_ppm(dir, "05_select");
+ tap(K_RIGHT); run(0, 30);
+ render(); save_ppm(dir, "06_select_scroll");
+ settle();
+ tap(K_LEFT); settle();
+ tap(K_OK); settle();
+ render(); save_ppm(dir, "07_play_start");
+ run(0, 240 * 2 + 150);
+ render(); save_ppm(dir, "08_play_death");
+ run(0, 240);
+ render(); save_ppm(dir, "09_play_attempt2");
+ tap(K_BACK); run(0, 60);
+ render(); save_ppm(dir, "10_pause");
+ tap(K_BACK);
+ /* level complete: replay level 1 */
+ FILE *f = fopen("tests/replays/level1.txt", "r");
+ static int ticks[8192], vals[8192];
+ int n = 0, t, v;
+ while (f && n < 8192 && fscanf(f, "input=%d,%d\n", &t, &v) == 2) { ticks[n] = t; vals[n++] = v; }
+ if (f) fclose(f);
+ app.checkpoint_count = 0;
+ app.practice = false;
+ app.attempt = 0;
+ app.g.dead = true;
+ app.death_t = 10;
+ run(0, 6);
+ bool held = false;
+ int pos = 0;
+ draw_frames = false;
+ for (int i = 1; i < 200 * ND_HZ && !app.g.complete; i++) {
+ while (pos < n && ticks[pos] <= i) held = vals[pos++] != 0;
+ run(held ? K_OK : 0, 1);
+ if (i == 3000) { render(); save_ppm(dir, "11_play_mid"); }
+ if (i == 12000) { render(); save_ppm(dir, "12_play_ship"); }
+ }
+ draw_frames = true;
+ run(0, 120);
+ render(); save_ppm(dir, "13_complete_rays");
+ run(0, 240 * 2 - 120 + 60);
+ render(); save_ppm(dir, "14_complete_title");
+ run(0, 240 * 3);
+ render(); save_ppm(dir, "15_complete_window");
+ tap(K_RIGHT); tap(K_OK); settle(); settle();
+ tap(K_BACK); settle();
+ app.sel = 0; tap(K_OK); settle();
+ render(); save_ppm(dir, "16_garage");
+ tap(K_BACK); settle();
+ app.sel = 2; tap(K_OK); settle();
+ render(); save_ppm(dir, "17_creator");
+ tap(K_OK); settle();
+ for (int i = 0; i < 6; i++) { tap(K_RIGHT); tap(K_OK); }
+ tap(K_UP); tap(K_PLUS); tap(K_PLUS); tap(K_PLUS); tap(K_PLUS); tap(K_PLUS); tap(K_PLUS); tap(K_PLUS);
+ tap(K_RIGHT); tap(K_OK); tap(K_RIGHT);
+ render(); save_ppm(dir, "18_editor");
+ tap(K_PROPS); run(0, 30);
+ render(); save_ppm(dir, "19_editor_settings");
+ puts("shots written");
+ return 0;
+}
+
+/* ------------------------------------------------------------ monkey */
+
+/* Random input across every screen, drawing every frame, with storage that
+ * is either empty or nearly full of other records. */
+static int monkey(unsigned seed, long ticks) {
+ static const uint32_t keys[] = {K_LEFT, K_RIGHT, K_UP, K_DOWN, K_OK, K_EXE, K_BACK, K_TOOL, K_SHIFT, K_ERASE,
+ K_SAVE, K_UNDO, K_CHECK, K_PLUS, K_MINUS, K_COPY, K_PROPS};
+ uint32_t r = seed * 2654435761u + 1;
+ memset(store, 0, sizeof(store));
+ if (seed & 1) {
+ /* fill all but a few hundred bytes with other apps' records */
+ static uint8_t junk[2000];
+ char name[16];
+ for (int i = 0; ; i++) {
+ snprintf(name, sizeof(name), "junk%d.py", i);
+ if (!storage_put(store, sizeof(store) - 600, name, junk, sizeof(junk), 1)) break;
+ }
+ }
+ app_init();
+ uint32_t held = 0;
+ unsigned restarts = 0;
+ static long visits[8];
+ memset(visits, 0, sizeof(visits));
+ for (long t = 0; t < ticks; t++) {
+ visits[app.screen & 7]++;
+ r ^= r << 13; r ^= r >> 17; r ^= r << 5;
+ if (r % 40 == 0) held = 0;
+ if (r % 23 == 0) held ^= keys[(r >> 8) % (sizeof(keys) / sizeof(keys[0]))];
+ /* mostly hold jump while playing so levels progress */
+ uint32_t k = held;
+ if (app.screen == SCR_PLAY && (r >> 20) % 3 == 0) k |= K_OK;
+ /* leave long play sessions through Home so every screen gets visited */
+ static long in_play;
+ in_play = app.screen == SCR_PLAY ? in_play + 1 : 0;
+ if (in_play > 240 * 15) { k = K_HOME; in_play = 0; }
+ run(k, 1);
+ if (!app.running) { app_init(); restarts++; }
+ }
+ printf("monkey %u: %ld ticks, %u quits; ticks per screen: menu %ld select %ld play %ld garage %ld creator %ld editor %ld loading %ld\n",
+ seed, ticks, restarts, visits[SCR_MENU], visits[SCR_SELECT], visits[SCR_PLAY], visits[SCR_GARAGE], visits[SCR_CREATOR],
+ visits[SCR_EDITOR], visits[SCR_LOADING]);
+ return 0;
+}
+
+int main(int argc, char **argv) {
+ if (argc == 4 && !strcmp(argv[1], "--replay")) return replay(atoi(argv[2]), argv[3]);
+ if (argc == 4 && !strcmp(argv[1], "--monkey")) return monkey((unsigned)atoi(argv[2]), atol(argv[3]));
+ if (argc == 3 && !strcmp(argv[1], "--shots")) return shots(argv[2]);
+ test_levels();
+ test_physics();
+ test_storage();
+ test_custom();
+ test_legacy();
+ test_app();
+ test_editor();
+ puts("PASS: levels, physics, checkpoints, storage safety, saves, legacy migration, menus, gameplay, editor");
+ return 0;
+}
diff --git a/games/numdash/tools/art.py b/games/numdash/tools/art.py
new file mode 100644
index 00000000..67802a38
--- /dev/null
+++ b/games/numdash/tools/art.py
@@ -0,0 +1,124 @@
+"""Procedural drawing helpers for NumDash's pixel art.
+
+All artwork is drawn from geometric primitives at 8x supersampling and
+downsampled, so the calculator sprites are anti-aliased without shipping any
+bitmap from the original game. Coordinates are in Geometry Dash units (30 per
+block) relative to the sprite anchor unless noted; S converts them to pixels.
+"""
+import math
+import numpy as np
+from PIL import Image, ImageDraw
+
+S = 2.0 / 3.0 # screen pixels per GD unit (20 px blocks)
+SS = 8 # supersampling factor
+
+
+class Art:
+ """RGBA float canvas with an integer pixel anchor.
+
+ w, h: size in pixels; ax, ay: anchor pixel (object origin). Drawing calls
+ take unit coordinates relative to the anchor with y pointing up."""
+
+ def __init__(self, w, h, ax=None, ay=None):
+ self.w, self.h = int(w), int(h)
+ self.ax = self.w // 2 if ax is None else int(ax)
+ self.ay = self.h // 2 if ay is None else int(ay)
+ self.rgb = np.zeros((self.h * SS, self.w * SS, 3), np.float32)
+ self.a = np.zeros((self.h * SS, self.w * SS), np.float32)
+
+ # unit -> supersampled pixel coordinates
+ def X(self, u):
+ return (self.ax + u * S) * SS
+
+ def Y(self, v):
+ return (self.ay - v * S) * SS
+
+ def mask(self, fn):
+ """Rasterize a PIL drawing callback into a float coverage mask."""
+ im = Image.new('L', (self.w * SS, self.h * SS), 0)
+ fn(ImageDraw.Draw(im))
+ return np.asarray(im).astype(np.float32) / 255.0
+
+ def poly_mask(self, pts):
+ return self.mask(lambda d: d.polygon([(self.X(x), self.Y(y)) for x, y in pts], fill=255))
+
+ def rect_mask(self, x0, y0, x1, y1):
+ return self.poly_mask([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])
+
+ def ellipse_mask(self, cx, cy, rx, ry):
+ return self.mask(lambda d: d.ellipse([self.X(cx - rx), self.Y(cy + ry), self.X(cx + rx), self.Y(cy - ry)], fill=255))
+
+ def grid(self):
+ """Unit coordinates (u, v) of every supersample centre."""
+ ys, xs = np.mgrid[0:self.h * SS, 0:self.w * SS].astype(np.float32)
+ u = ((xs + 0.5) / SS - self.ax) / S
+ v = (self.ay - (ys + 0.5) / SS) / S
+ return u, v
+
+ def paint(self, mask, color, alpha=1.0):
+ """Composite colour (rgb tuple 0..1 or HxWx3 array) over the canvas."""
+ m = np.clip(mask * alpha, 0, 1)
+ col = np.asarray(color, np.float32)
+ if col.ndim == 1:
+ col = col.reshape(1, 1, 3)
+ self.rgb = self.rgb * (1 - m[..., None]) + col * m[..., None]
+ self.a = self.a + (1 - self.a) * m
+
+ def erase(self, mask):
+ self.a = self.a * (1 - np.clip(mask, 0, 1))
+
+ def image(self):
+ """Downsample to (h, w, 4) float RGBA with premultiplied-correct colour."""
+ h, w = self.h, self.w
+ a = self.a.reshape(h, SS, w, SS).mean(axis=(1, 3))
+ prem = (self.rgb * self.a[..., None]).reshape(h, SS, w, SS, 3).mean(axis=(1, 3))
+ rgb = np.where(a[..., None] > 1e-6, prem / np.maximum(a[..., None], 1e-6), 0)
+ return np.concatenate([np.clip(rgb, 0, 1), np.clip(a, 0, 1)[..., None]], axis=2)
+
+
+def stroke_mask(art, pts, width, closed=True):
+ """Polyline stroke of the given width (units), with round joins."""
+ wpx = max(1, int(round(width * S * SS)))
+ seq = pts + ([pts[0]] if closed else [])
+
+ def fn(d):
+ xy = [(art.X(x), art.Y(y)) for x, y in seq]
+ d.line(xy, fill=255, width=wpx)
+ r = wpx / 2
+ for x, y in xy:
+ d.ellipse([x - r, y - r, x + r, y + r], fill=255)
+ return art.mask(fn)
+
+
+def inset_polygon(pts, d):
+ """Offset a convex counter-clockwise polygon inwards by d units."""
+ n = len(pts)
+ lines = []
+ for i in range(n):
+ (x0, y0), (x1, y1) = pts[i], pts[(i + 1) % n]
+ ex, ey = x1 - x0, y1 - y0
+ L = math.hypot(ex, ey)
+ nx, ny = -ey / L, ex / L # inward normal for CCW order
+ lines.append((x0 + nx * d, y0 + ny * d, ex, ey))
+ out = []
+ for i in range(n):
+ x0, y0, dx0, dy0 = lines[i - 1]
+ x1, y1, dx1, dy1 = lines[i]
+ det = dx0 * dy1 - dy0 * dx1
+ t = ((x1 - x0) * dy1 - (y1 - y0) * dx1) / det
+ out.append((x0 + dx0 * t, y0 + dy0 * t))
+ return out
+
+
+def lerp(a, b, t):
+ return a + (b - a) * t
+
+
+def smooth(t):
+ t = np.clip(t, 0, 1)
+ return t * t * (3 - 2 * t)
+
+
+def hexc(s):
+ s = s.lstrip('#')
+ return tuple(int(s[i:i + 2], 16) / 255.0 for i in (0, 2, 4))
diff --git a/games/numdash/tools/assets.py b/games/numdash/tools/assets.py
new file mode 100644
index 00000000..02fde38a
--- /dev/null
+++ b/games/numdash/tools/assets.py
@@ -0,0 +1,188 @@
+#!/usr/bin/env python3
+"""Build src/assets.c and src/assets.h from the procedural artwork.
+
+Formats (see gfx.h): A4 = 4-bit coverage tinted at draw time, LA44 = 4-bit
+luminance + 4-bit alpha tinted at draw time, PAL4 = 4-bit index into a
+16-entry RGB565+alpha palette. Rows are byte aligned.
+"""
+import sys
+from pathlib import Path
+import numpy as np
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from sprites_game import game_sprites # noqa: E402
+from sprites_ui import ui_sprites # noqa: E402
+from fonts import build_fonts # noqa: E402
+import background # noqa: E402
+
+FMT = {'A4': 0, 'LA44': 1, 'PAL4': 2}
+
+
+def rgb565(r, g, b):
+ return (int(round(r * 31)) << 11) | (int(round(g * 63)) << 5) | int(round(b * 31))
+
+
+def trim(img, ax, ay):
+ a = img[..., 3]
+ ys, xs = np.nonzero(a > 1.0 / 32)
+ if len(xs) == 0:
+ return img[:1, :1], 0, 0
+ x0, x1, y0, y1 = xs.min(), xs.max() + 1, ys.min(), ys.max() + 1
+ return img[y0:y1, x0:x1], ax - x0, ay - y0
+
+
+def quant4(x):
+ return np.clip(np.round(x * 15), 0, 15).astype(np.uint8)
+
+
+def pack_nibbles(idx):
+ h, w = idx.shape
+ stride = (w + 1) // 2
+ out = np.zeros((h, stride), np.uint8)
+ for x in range(w):
+ if x & 1:
+ out[:, x >> 1] |= idx[:, x] << 4
+ else:
+ out[:, x >> 1] |= idx[:, x]
+ return out.tobytes()
+
+
+def palette_quantize(img, n=15, iters=12):
+ """k-means over opaque-ish pixels in (r,g,b,a); index 0 = transparent."""
+ h, w = img.shape[:2]
+ flat = img.reshape(-1, 4)
+ a4 = quant4(flat[:, 3])
+ vis = a4 > 0
+ pts = flat[vis]
+ idx = np.zeros(h * w, np.uint8)
+ pal = [(0, 0, 0, 0)]
+ if len(pts):
+ feats = np.concatenate([pts[:, :3], pts[:, 3:4] * 1.5], 1)
+ uniq = np.unique(np.round(feats, 3), axis=0)
+ k = min(n, len(uniq))
+ # init: farthest-point sampling for stable, deterministic results
+ cent = [uniq[np.argmax(uniq[:, 3])]]
+ for _ in range(1, k):
+ d = np.min([((uniq - c) ** 2).sum(1) for c in cent], axis=0)
+ cent.append(uniq[np.argmax(d)])
+ cent = np.array(cent)
+ for _ in range(iters):
+ d = ((feats[:, None, :] - cent[None]) ** 2).sum(2)
+ lab = d.argmin(1)
+ for j in range(k):
+ sel = feats[lab == j]
+ if len(sel):
+ cent[j] = sel.mean(0)
+ d = ((feats[:, None, :] - cent[None]) ** 2).sum(2)
+ lab = d.argmin(1)
+ idx[vis] = lab + 1
+ for c in cent:
+ pal.append((c[0], c[1], c[2], min(1.0, c[3] / 1.5)))
+ while len(pal) < 16:
+ pal.append((0, 0, 0, 0))
+ return idx.reshape(h, w), pal
+
+
+class Packer:
+ def __init__(self):
+ self.blob = bytearray()
+ self.sprites = [] # (name, w, h, ax, ay, fmt, pal, off)
+ self.palettes = []
+
+ def add(self, name, img, ax, ay, fmt):
+ img, ax, ay = trim(img, ax, ay)
+ h, w = img.shape[:2]
+ off = len(self.blob)
+ pal_i = 0
+ if fmt == 'A4':
+ data = pack_nibbles(quant4(img[..., 3]))
+ elif fmt == 'LA44':
+ lum = img[..., :3].mean(2)
+ l4 = quant4(lum)
+ a4 = quant4(img[..., 3])
+ data = ((l4 << 4) | a4).astype(np.uint8).tobytes()
+ else:
+ idx, pal = palette_quantize(img)
+ data = pack_nibbles(idx)
+ pal_i = len(self.palettes)
+ self.palettes.append(pal)
+ self.blob += data
+ self.sprites.append((name, w, h, ax, ay, FMT[fmt], pal_i, off))
+ return len(self.sprites) - 1
+
+
+def c_ident(name):
+ return 'SPR_' + ''.join(ch.upper() if ch.isalnum() else '_' for ch in name)
+
+
+def main():
+ pk = Packer()
+ for name, art, fmt in game_sprites() + ui_sprites():
+ pk.add(name, art.image(), art.ax, art.ay, fmt)
+ fonts = build_fonts(pk)
+ names = [s[0] for s in pk.sprites]
+ assert len(set(names)) == len(names), 'duplicate sprite names'
+
+ h = ['/* Generated by tools/assets.py. Do not edit. */',
+ '#ifndef NUMDASH_ASSETS_H', '#define NUMDASH_ASSETS_H', '#include <stdint.h>',
+ 'typedef struct { uint16_t w, h; int16_t ax, ay; uint8_t fmt, pal; uint32_t off; } Sprite;',
+ 'typedef struct { uint8_t cap, outline; int8_t sdx, sdy; uint8_t shadow; uint16_t base; const uint8_t *advance; } Font;',
+ 'enum {']
+ for i, n in enumerate(names):
+ if not n.startswith('glyph_'):
+ h.append(' %s = %d,' % (c_ident(n), i))
+ h.append(' SPR_COUNT = %d' % len(names))
+ h.append('};')
+ h.append('extern const Sprite sprites[SPR_COUNT];')
+ h.append('extern const uint8_t sprite_blob[];')
+ h.append('extern const uint16_t sprite_pal_rgb[][16];')
+ h.append('extern const uint8_t sprite_pal_a[][16];')
+ h.append('enum { %s };' % ', '.join('FONT_%s' % f['name'].upper() for f in fonts))
+ h.append('extern const Font fonts[%d];' % len(fonts))
+ h.append('extern const uint8_t font_charmap[96];')
+ rects = background.layout()
+ h.append('#define BG_RECTS %d' % len(rects))
+ h.append('extern const uint16_t bg_rects[BG_RECTS][4];')
+ h.append('#endif')
+ (ROOT / 'src/assets.h').write_text('\n'.join(h) + '\n')
+
+ c = ['/* Generated by tools/assets.py. Do not edit. */', '#include "assets.h"',
+ 'const Sprite sprites[SPR_COUNT] = {']
+ for (n, w, hh, ax, ay, fmt, pal, off) in pk.sprites:
+ c.append(' {%d,%d,%d,%d,%d,%d,%d},' % (w, hh, ax, ay, fmt, pal, off))
+ c.append('};')
+ c.append('const uint16_t sprite_pal_rgb[][16] = {')
+ for pal in pk.palettes or [[(0, 0, 0, 0)] * 16]:
+ c.append(' {' + ','.join('0x%04x' % rgb565(*p[:3]) for p in pal) + '},')
+ c.append('};')
+ c.append('const uint8_t sprite_pal_a[][16] = {')
+ for pal in pk.palettes or [[(0, 0, 0, 0)] * 16]:
+ c.append(' {' + ','.join(str(int(round(p[3] * 15))) for p in pal) + '},')
+ c.append('};')
+ for f in fonts:
+ c.append('static const uint8_t adv_%s[] = {%s};' % (f['name'], ','.join(str(a) for a in f['advance'])))
+ c.append('const Font fonts[%d] = {' % len(fonts))
+ for f in fonts:
+ c.append(' {%d,%d,%d,%d,%d,%d,adv_%s},' % (f['cap'], f['outline'], f['sdx'], f['sdy'], f['sa'], f['base'], f['name']))
+ c.append('};')
+ from fonts import CHARS
+ cmap = [255] * 96
+ for i, ch in enumerate(CHARS):
+ cmap[ord(ch) - 32] = i
+ for ch in 'abcdefghijklmnopqrstuvwxyz':
+ cmap[ord(ch) - 32] = CHARS.index(ch.upper())
+ c.append('const uint8_t font_charmap[96] = {' + ','.join(str(v) for v in cmap) + '};')
+ c.append('const uint16_t bg_rects[BG_RECTS][4] = {' + ','.join('{%d,%d,%d,%d}' % r for r in rects) + '};')
+ c.append('const uint8_t sprite_blob[] = {')
+ blob = bytes(pk.blob)
+ for i in range(0, len(blob), 32):
+ c.append(' ' + ','.join(str(b) for b in blob[i:i + 32]) + ',')
+ c.append('};')
+ (ROOT / 'src/assets.c').write_text('\n'.join(c) + '\n')
+ print('sprites: %d, blob: %d bytes, palettes: %d' % (len(pk.sprites), len(blob), len(pk.palettes)))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/games/numdash/tools/background.py b/games/numdash/tools/background.py
new file mode 100644
index 00000000..601639de
--- /dev/null
+++ b/games/numdash/tools/background.py
@@ -0,0 +1,58 @@
+"""Background tile layout: rectangles of assorted sizes separated by bright
+seams, in the style of Geometry Dash's default backdrop (tile 512 texels,
+displayed at 0.9 px per texel)."""
+import random
+
+TILE = 512
+GAP = 8
+
+
+def split(x, y, w, h, rnd, depth, out):
+ """Recursively split a region into panels; big panels stay whole."""
+ big = w * h
+ if depth > 3 or (w < 90 and h < 90) or (big < 42000 and rnd.random() < 0.55):
+ out.append((x, y, w, h))
+ return
+ if w >= h:
+ cut = rnd.choice([0.33, 0.4, 0.5, 0.6, 0.67])
+ a = int(w * cut) // 8 * 8
+ split(x, y, a, h, rnd, depth + 1, out)
+ split(x + a, y, w - a, h, rnd, depth + 1, out)
+ else:
+ cut = rnd.choice([0.3, 0.4, 0.5, 0.6, 0.7])
+ a = int(h * cut) // 8 * 8
+ split(x, y, w, a, rnd, depth + 1, out)
+ split(x, y + a, w, h - a, rnd, depth + 1, out)
+
+
+def layout(seed=7):
+ rnd = random.Random(seed)
+ cols = [96, 128, 160, 128]
+ out = []
+ x = 0
+ for cw in cols:
+ y = 0
+ while y < TILE:
+ h = min(TILE - y, rnd.choice([112, 144, 176, 208, 96]))
+ if TILE - y - h < 64:
+ h = TILE - y
+ split(x, y, cw, h, rnd, 0, out)
+ y += h
+ x += cw
+ # shrink by the seam so neighbours are separated by GAP texels
+ rects = []
+ for (x, y, w, h) in out:
+ rects.append((x + GAP // 2, y + GAP // 2, w - GAP, h - GAP))
+ return rects
+
+
+if __name__ == '__main__':
+ from PIL import Image
+ import numpy as np
+ img = np.ones((TILE, TILE)) * 1.0
+ for (x, y, w, h) in layout():
+ img[y:y + h, x:x + w] = 0.843
+ img[y:y + h, x + w - 1] = 0.71
+ grad = np.clip(np.arange(TILE) / 384.0, 0, 1)[:, None]
+ Image.fromarray((img * grad * 255).astype('uint8')).save('/tmp/bg_layout.png')
+ print(len(layout()))
diff --git a/games/numdash/tools/dev/bench.c b/games/numdash/tools/dev/bench.c
new file mode 100644
index 00000000..b070a0c0
--- /dev/null
+++ b/games/numdash/tools/dev/bench.c
@@ -0,0 +1,64 @@
+/* Development helper: runs the app headless for instruction counting under
+ * qemu-arm (no libc start-up; exits with a raw Linux syscall).
+ * bench <scenario> <frames> scenario: 0 menu, 1 gameplay, 2 complete */
+#include "app.h"
+#include <string.h>
+
+static uint8_t store[4096];
+uint8_t *platform_storage(size_t *size) { *size = sizeof(store); return store; }
+void platform_storage_commit(void) {}
+bool platform_init(void) { return true; }
+void platform_close(void) {}
+uint32_t platform_keys(void) { return 0; }
+uint32_t platform_millis(void) { return 0; }
+void platform_sleep(unsigned ms) { (void)ms; }
+uint32_t platform_random(void) { return 12345; }
+void platform_frame_begin(bool vsync) { (void)vsync; }
+void platform_strip(int y, int h, const uint16_t *px) { (void)y; (void)h; (void)px; }
+void platform_frame_end(void) {}
+
+static unsigned ticks;
+static void run(uint32_t keys, int n) {
+ for (int i = 0; i < n; i++) {
+ app_tick(keys);
+ if (++ticks % 6 == 0) app_frame(6.0f / ND_HZ);
+ }
+}
+static void frame(void) {
+ run(app.keys, 6);
+ for (int s = 0; s < STRIPS; s++) { gfx_begin_strip(s); app_draw(); platform_strip(s * STRIP_H, STRIP_H, gfx_strip); }
+}
+static int atoi_(const char *s) { int v = 0; while (*s >= '0' && *s <= '9') v = v * 10 + (*s++ - '0'); return v; }
+
+/* inputs of tests/replays/level1.txt up to the ship section, compiled in */
+extern const int bench_ticks[], bench_vals[], bench_n;
+
+static int bench(int scenario, int frames) {
+ app_init();
+ run(0, 240 * 3); /* past the loading screen */
+ if (scenario >= 1) {
+ app.level = 0; app.practice = false; app.testing = false;
+ app_go(SCR_PLAY);
+ run(0, 120);
+ int pos = 0, stop = scenario == 1 ? 7000 : 30000;
+ bool held = false;
+ for (int i = 1; i < stop && !app.g.complete; i++) {
+ while (pos < bench_n && bench_ticks[pos] <= i) held = bench_vals[pos++] != 0;
+ run(held ? K_OK : 0, 1);
+ if (app.g.dead) return 3;
+ }
+ if (scenario == 2) run(0, 240 * 2 + 60);
+ }
+ for (int f = 0; f < frames; f++) frame();
+ return 0;
+}
+
+__attribute__((used)) static void cstart(uint32_t *sp) {
+ char **argv = (char **)(sp + 1);
+ int code = bench(atoi_(argv[1]), atoi_(argv[2]));
+ register int r0 __asm__("r0") = code;
+ register int r7 __asm__("r7") = 1;
+ __asm__ volatile("svc 0" ::"r"(r0), "r"(r7));
+ for (;;) {}
+}
+__attribute__((naked)) void _start(void) { __asm__ volatile("mov r0, sp\n bl cstart\n"); }
diff --git a/games/numdash/tools/dev/icon.c b/games/numdash/tools/dev/icon.c
new file mode 100644
index 00000000..dea6efd0
--- /dev/null
+++ b/games/numdash/tools/dev/icon.c
@@ -0,0 +1,31 @@
+/* Development helper: renders the home screen icon (55 x 56) with the game's
+ * own artwork. usage: icon out.ppm (then convert to assets/icon.png) */
+#include "scene.h"
+#include <stdio.h>
+#include <string.h>
+static uint16_t fb[GFX_W * GFX_H];
+int main(int argc, char **argv) {
+ if (argc < 2) return 1;
+ const int x0 = 132, y0 = 92, w = 55, h = 56;
+ color_t bg = rgb(40, 125, 255), g1 = rgb(0, 102, 255);
+ for (int s = 0; s < STRIPS; s++) {
+ gfx_begin_strip(s);
+ scene_background(bg, 1180, 0);
+ scene_ground(g1, 0xffff, 40, y0 + 42, false, false);
+ float cx = x0 + 27.5f, cy = y0 + 42 - 14;
+ gfx_sprite_ex(SPR_CUBE1_S, (int)(cx * 16), (int)(cy * 16), 0, 360, 0, rgb(0, 255, 255), 256, BLEND_NORMAL);
+ gfx_sprite_ex(SPR_CUBE1_P, (int)(cx * 16), (int)(cy * 16), 0, 360, 0, rgb(125, 255, 0), 256, BLEND_NORMAL);
+ memcpy(fb + s * STRIP_H * GFX_W, gfx_strip, sizeof(gfx_strip));
+ }
+ FILE *f = fopen(argv[1], "wb");
+ if (!f) return 1;
+ fprintf(f, "P6\n%d %d\n255\n", w, h);
+ for (int y = y0; y < y0 + h; y++)
+ for (int x = x0; x < x0 + w; x++) {
+ uint16_t c = fb[y * GFX_W + x];
+ uint8_t p[3] = {(uint8_t)c_r(c), (uint8_t)c_g(c), (uint8_t)c_b(c)};
+ fwrite(p, 1, 3, f);
+ }
+ fclose(f);
+ return 0;
+}
diff --git a/games/numdash/tools/dev/shot.c b/games/numdash/tools/dev/shot.c
new file mode 100644
index 00000000..98f499fb
--- /dev/null
+++ b/games/numdash/tools/dev/shot.c
@@ -0,0 +1,43 @@
+/* Development helper: render gameplay frames to PPM. usage: shot level tick out.ppm [replay] */
+#include "scene.h"
+#include "fx.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+static uint16_t fb[GFX_W * GFX_H];
+static void render(void) {
+ for (int s = 0; s < STRIPS; s++) {
+ gfx_begin_strip(s);
+ scene_draw();
+ memcpy(fb + s * STRIP_H * GFX_W, gfx_strip, sizeof(gfx_strip));
+ }
+}
+static void save(const char *path) {
+ FILE *f = fopen(path, "wb");
+ fprintf(f, "P6\n%d %d\n255\n", GFX_W, GFX_H);
+ for (int i = 0; i < GFX_W * GFX_H; i++) { uint8_t c[3] = {c_r(fb[i]), c_g(fb[i]), c_b(fb[i])}; fwrite(c, 1, 3, f); }
+ fclose(f);
+}
+int main(int argc, char **argv) {
+ int lvl = atoi(argv[1]), tick = atoi(argv[2]);
+ static Level L; static Game g;
+ if (!level_load_builtin(&L, (unsigned)lvl)) { puts("load fail"); return 1; }
+ int ticks[6000], vals[6000], n = 0;
+ if (argc > 4) { FILE *f = fopen(argv[4], "r"); int t, v; while (f && fscanf(f, "input=%d,%d\n", &t, &v) == 2) { ticks[n] = t; vals[n++] = v; } if (f) fclose(f); }
+ game_start(&g, &L, argc > 5);
+ fx_reset();
+ int pos = 0; bool held = false;
+ for (int i = 1; i <= tick; i++) {
+ while (pos < n && ticks[pos] <= i) held = vals[pos++];
+ game_step(&g, held);
+ if (i % 6 == 0) fx_update(&g, 6.0f / 240, rgb(125, 255, 0), rgb(0, 255, 255), false);
+ if (g.dead) { printf("dead at %d x=%.1f\n", i, g.p.x); break; }
+ }
+ SceneOpts o = {0};
+ o.p1 = rgb(125, 255, 0); o.p2 = rgb(0, 255, 255); o.show_percent = true; o.attempt = 1; o.time = tick / 240.f;
+ scene_prepare(&g, &o);
+ render();
+ save(argv[3]);
+ printf("x=%.1f y=%.1f cam=(%.1f,%.1f) mode=%d\n", g.p.x, g.p.y, g.cam_x, g.cam_y, g.p.mode);
+ return 0;
+}
diff --git a/games/numdash/tools/fonts.py b/games/numdash/tools/fonts.py
new file mode 100644
index 00000000..ed8ca63d
--- /dev/null
+++ b/games/numdash/tools/fonts.py
@@ -0,0 +1,97 @@
+"""Bitmap fonts in the style of Geometry Dash's outlined title lettering.
+
+Glyphs are rasterized from two SIL Open Font License typefaces (Rammetto One
+for display text, Nunito Black for small labels; see LICENSES/).
+Only the 4-bit fill coverage is stored (A4 sprites); the renderer derives the
+black outline and drop shadow at draw time, which keeps the fonts small.
+"""
+from pathlib import Path
+import hashlib
+import urllib.request
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+
+HERE = Path(__file__).resolve().parent / 'fonts'
+UP = 4 # supersampling for rasterization
+
+SOURCES = {
+ 'RammettoOne-Regular.ttf': ('https://raw.githubusercontent.com/google/fonts/main/ofl/rammettoone/RammettoOne-Regular.ttf',
+ '0063c5480f7868be5dd95dd668575643ff953199541dce65fe5a88310bd7733f'),
+ 'Nunito-Black.ttf': ('https://raw.githubusercontent.com/google/fonts/main/ofl/nunito/Nunito%5Bwght%5D.ttf',
+ 'bb55a5ca5c2042335b3991af27c4d0705d0ef41cac6164ac737fd8f2a1e85207'),
+}
+
+# name, file, cap height px, outline radius px, shadow dx, dy, alpha (0..15), variation
+SPECS = [
+ ('small', 'Nunito-Black.ttf', 7, 1, 1, 1, 8, [1000]),
+ ('big', 'RammettoOne-Regular.ttf', 13, 1, 1, 2, 9, None),
+ ('huge', 'RammettoOne-Regular.ttf', 19, 2, 2, 2, 9, None),
+]
+CHARS = " !%'()+,-./0123456789:?ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+
+
+def font_path(fname):
+ p = HERE / fname
+ if not p.exists():
+ url, digest = SOURCES[fname]
+ HERE.mkdir(exist_ok=True)
+ data = urllib.request.urlopen(url).read()
+ if hashlib.sha256(data).hexdigest() != digest:
+ raise RuntimeError('unexpected font data for ' + fname)
+ p.write_bytes(data)
+ return p
+
+
+def load_font(fname, cap, var):
+ for size in range(4, 200):
+ f = ImageFont.truetype(str(font_path(fname)), size * UP)
+ if var:
+ try:
+ f.set_variation_by_axes(var)
+ except Exception:
+ pass
+ bb = f.getbbox('H')
+ if bb[3] - bb[1] >= cap * UP - UP // 2:
+ return f
+ raise RuntimeError('font size')
+
+
+def render_glyph(font, ch):
+ """Fill coverage at 1x with the pen origin on a pixel corner.
+ Returns (RGBA float image, anchor x, anchor y (baseline), advance)."""
+ adv = font.getlength(ch) / UP
+ if not ch.strip():
+ return np.zeros((1, 1, 4), np.float32), 0, 0, adv
+ bb = font.getbbox(ch, anchor='ls')
+ pad = 2 * UP
+ x_org = pad - bb[0]
+ y_org = pad - bb[1]
+ # align origin to the UP grid so the baseline lands on a pixel boundary
+ x_org += (-x_org) % UP
+ y_org += (-y_org) % UP
+ W = x_org + bb[2] + pad
+ H = y_org + bb[3] + pad
+ W += (-W) % UP
+ H += (-H) % UP
+ im = Image.new('L', (W, H), 0)
+ ImageDraw.Draw(im).text((x_org, y_org), ch, font=font, fill=255, anchor='ls')
+ a = np.asarray(im).astype(np.float32) / 255
+ a = a.reshape(H // UP, UP, W // UP, UP).mean(axis=(1, 3))
+ img = np.zeros(a.shape + (4,), np.float32)
+ img[..., :3] = 1
+ img[..., 3] = a
+ return img, x_org // UP, y_org // UP, adv
+
+
+def build_fonts(packer):
+ out = []
+ for name, fname, cap, outline, sdx, sdy, sa, var in SPECS:
+ font = load_font(fname, cap, var)
+ base = len(packer.sprites)
+ adv = []
+ for ch in CHARS:
+ img, ax, ay, a = render_glyph(font, ch)
+ packer.add('glyph_%s_%d' % (name, ord(ch)), img, ax, ay, 'A4')
+ adv.append(max(1, int(round(a))))
+ out.append(dict(name=name, cap=cap, outline=outline, sdx=sdx, sdy=sdy, sa=sa, base=base, advance=adv))
+ return out
diff --git a/games/numdash/tools/levels.py b/games/numdash/tools/levels.py
new file mode 100644
index 00000000..56b7f797
--- /dev/null
+++ b/games/numdash/tools/levels.py
@@ -0,0 +1,197 @@
+#!/usr/bin/env python3
+"""Compile the checked-in GMD level exports to compressed C data.
+
+Objects become 6-byte records {dx:u16, y:i16, type:u8, xform:u8} sorted by x
+and stored as raw DEFLATE; the runtime inflates them straight into its object
+array and prefix-sums dx. Colour, enter-effect and trail triggers become a
+small uncompressed event list. Also emits the C object catalogue.
+"""
+import base64
+import collections
+import gzip
+import hashlib
+import json
+import struct
+import sys
+import zlib
+from pathlib import Path
+import xml.etree.ElementTree as ET
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+import objdefs as od # noqa: E402
+
+GD_SOURCE = 'https://github.com/AleFunky/gd3ds/tree/cdea1c2fad3d67fa17d2cfa781013b0ee58bb280/romfs/main_levels'
+# file, title, difficulty (1 easy .. 5 insane), stars, pulse bpm
+LEVELS = [
+ ('StereoMadness', 'STEREO MADNESS', 1, 1, 160),
+ ('BackOnTrack', 'BACK ON TRACK', 1, 2, 130),
+ ('Polargeist', 'POLARGEIST', 2, 3, 165),
+ ('DryOut', 'DRY OUT', 2, 4, 140),
+ ('BaseAfterBase', 'BASE AFTER BASE', 3, 5, 142),
+ ('CantLetGo', "CAN'T LET GO", 3, 6, 144),
+ ('Jumper', 'JUMPER', 4, 7, 175),
+]
+
+
+def decode(path):
+ nodes = list(ET.parse(path).getroot()[0])
+ props = {nodes[i].text: nodes[i + 1].text for i in range(0, len(nodes), 2)}
+ enc = props['k4']
+ raw = gzip.decompress(base64.urlsafe_b64decode(enc + '=' * (-len(enc) % 4))).decode()
+ parts = raw.split(';')
+ header = dict(zip(parts[0].split(',')[::2], parts[0].split(',')[1::2]))
+ colors = {}
+ for ch in header.get('kS38', '').split('|'):
+ if not ch:
+ continue
+ it = ch.split('_')
+ d = dict(zip(it[::2], it[1::2]))
+ colors[int(d['6'])] = (int(d.get('1', 255)), int(d.get('2', 255)), int(d.get('3', 255)))
+ objs = []
+ for p in parts[1:]:
+ it = p.split(',')
+ d = dict(zip(it[::2], it[1::2]))
+ if '1' in d:
+ objs.append(d)
+ return header, colors, objs
+
+
+def compile_level(path):
+ header, colors, raw = decode(path)
+ objects, events, skipped = [], [], collections.Counter()
+ for order, d in enumerate(raw):
+ gid = int(d['1'])
+ x = int(round(float(d.get('2', 0))))
+ y = int(round(float(d.get('3', 0))))
+ if gid in od.COLOR_TRIGGERS:
+ chan = od.COLOR_TRIGGERS[gid]
+ dur = int(round(float(d.get('10', 0)) * 1000))
+ flags = (1 if d.get('11') == '1' else 0) | (2 if d.get('14') == '1' else 0) | (4 if d.get('17') == '1' else 0)
+ events.append((x, y, od.EV_COLOR, chan, int(d.get('7', 255)), int(d.get('8', 255)), int(d.get('9', 255)), flags, dur, order))
+ continue
+ if gid in od.FADE_TRIGGERS:
+ events.append((x, y, od.EV_FADE, od.FADE_TRIGGERS[gid], 0, 0, 0, 0, 0, order))
+ continue
+ if gid in od.TRAIL_TRIGGERS:
+ events.append((x, y, od.EV_TRAIL, od.TRAIL_TRIGGERS[gid], 0, 0, 0, 0, 0, order))
+ continue
+ t = od.BY_ID.get(gid)
+ if not t:
+ skipped[gid] += 1
+ continue
+ rot = int(round(float(d.get('6', 0)) / 90)) % 4
+ xf = rot | (4 if d.get('4') == '1' else 0) | (8 if d.get('5') == '1' else 0)
+ objects.append((x, y, t, xf, order))
+ objects.sort(key=lambda o: (o[0], o[4]))
+ # GD triggers fire in x order, ties broken by higher y first
+ events.sort(key=lambda e: (e[0], -e[1], e[9]))
+ return header, colors, objects, events, skipped
+
+
+def records(objects):
+ out = bytearray()
+ px = 0
+ for (x, y, t, xf, _) in objects:
+ assert 0 <= x < 65536 and -32768 <= y < 32768 and x >= px
+ out += struct.pack('<HhBB', x - px, y, t, xf)
+ px = x
+ return bytes(out)
+
+
+def deflate(data):
+ c = zlib.compressobj(9, zlib.DEFLATED, -15, 9)
+ return c.compress(data) + c.flush()
+
+
+def c_bytes(name, data):
+ lines = ['static const uint8_t %s[%d] = {' % (name, len(data))]
+ for i in range(0, len(data), 40):
+ lines.append(' ' + ','.join(str(b) for b in data[i:i + 40]) + ',')
+ lines.append('};')
+ return lines
+
+
+def emit_objdefs():
+ h = ['/* Generated by tools/levels.py. Do not edit. */', '#ifndef NUMDASH_OBJDEFS_H', '#define NUMDASH_OBJDEFS_H',
+ '#include <stdint.h>', 'enum {', ' OT_NONE = 0,']
+ for i, o in enumerate(od.OBJECTS):
+ h.append(' OT_%s = %d,' % (o[0], i + 1))
+ h.append(' OT_COUNT = %d' % (len(od.OBJECTS) + 1))
+ h.append('};')
+ h.append('enum { HIT_NONE, HIT_SOLID, HIT_HAZARD, HIT_SPECIAL };')
+ h.append('enum { ' + ', '.join('SP_' + s for s in od.SP) + ' };')
+ h.append('enum { ' + ', '.join('CT_' + s for s in od.CT) + ' };')
+ h.append('enum { ' + ', '.join('LAYER_' + s for s in od.LAYERS) + ', LAYER_COUNT };')
+ h.append('enum { PF_PULSE = 1, PF_RANDOM3 = 2, PF_COIN = 4, PF_ANIM = 8 };')
+ h.append('enum { EV_COLOR = 1, EV_FADE = 2, EV_TRAIL = 3 };')
+ h.append('typedef struct { int16_t sprite; int8_t dx4, dy4; uint8_t layer, ctype, flags; } ObjPart;')
+ h.append('typedef struct { uint16_t gd_id; uint8_t hit, special; uint16_t w10, h10; int8_t editor_dy; uint8_t nparts; ObjPart parts[2]; } ObjDef;')
+ h.append('extern const ObjDef objdefs[OT_COUNT];')
+ h.append('#define EDITOR_TYPES %d' % len(od.EDITOR))
+ h.append('extern const uint8_t editor_types[EDITOR_TYPES];')
+ h.append('#endif')
+ (ROOT / 'src/objdefs.h').write_text('\n'.join(h) + '\n')
+
+ c = ['/* Generated by tools/levels.py. Do not edit. */', '#include "objdefs.h"', '#include "assets.h"',
+ 'const ObjDef objdefs[OT_COUNT] = {', ' {0,0,0,0,0,0,0,{{-1,0,0,0,0,0},{-1,0,0,0,0,0}}},']
+ for (name, ids, hit, w, hh, sp, edy, parts) in od.OBJECTS:
+ ps = []
+ for (spr, dx, dy, layer, ct, fl) in parts:
+ ident = 'SPR_' + ''.join(ch.upper() if ch.isalnum() else '_' for ch in spr)
+ ps.append('{%s,%d,%d,LAYER_%s,CT_%s,%d}' % (ident, int(round(dx * 4)), int(round(dy * 4)), layer, ct, fl))
+ while len(ps) < 2:
+ ps.append('{-1,0,0,0,0,0}')
+ c.append(' {%d,%d,SP_%s,%d,%d,%d,%d,{%s}},' % (ids[0], hit, sp, int(round(w * 10)), int(round(hh * 10)), edy, len(parts), ','.join(ps)))
+ c.append('};')
+ c.append('const uint8_t editor_types[EDITOR_TYPES] = {' + ','.join('OT_' + n for n in od.EDITOR) + '};')
+ (ROOT / 'src/objdefs.c').write_text('\n'.join(c) + '\n')
+
+
+def main():
+ emit_objdefs()
+ out = ['/* Generated by tools/levels.py from levels/reference. Do not edit. */', '#include "level.h"']
+ table, manifest = [], []
+ total_raw = total_z = 0
+ for i, (fname, title, diff, stars, bpm) in enumerate(LEVELS):
+ path = ROOT / 'levels/reference' / (fname + '.gmd')
+ header, colors, objects, events, skipped = compile_level(path)
+ rec = records(objects)
+ z = deflate(rec)
+ assert zlib.decompress(z, -15) == rec
+ total_raw += len(rec)
+ total_z += len(z)
+ last_x = max(o[0] for o in objects)
+ end_x = last_x + 330
+ wall_x = int(round(end_x / 30.0)) * 30
+ bg = colors.get(1000, (40, 125, 255))
+ g1 = colors.get(1001, (0, 102, 255))
+ line = colors.get(1002, (255, 255, 255))
+ obj = colors.get(1004, (255, 255, 255))
+ out += c_bytes('level%d_data' % i, z)
+ out.append('static const LevelEvent level%d_events[%d] = {' % (i, max(1, len(events))))
+ for (x, y, kind, arg, r, g, b, flags, dur, _) in events:
+ out.append(' {%d,%d,%d,%d,%d,%d,%d,%d,%d},' % (x, y, kind, arg, r, g, b, flags, dur))
+ if not events:
+ out.append(' {0,0,0,0,0,0,0,0,0},')
+ out.append('};')
+ start_mode = int(header.get('kA2', 0))
+ table.append(' {"%s",level%d_data,level%d_events,%d,%d,%d,%d,%d,%d,{%d,%d,%d},{%d,%d,%d},{%d,%d,%d},{%d,%d,%d},%d,%d,%d,%d},' % (
+ title.replace('"', '\\"'), i, i, len(z), len(objects), len(events), end_x, wall_x, 0,
+ *bg, *g1, *line, *obj, diff, stars, bpm, start_mode))
+ manifest.append({'name': title, 'file': 'levels/reference/%s.gmd' % fname,
+ 'sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
+ 'objects': len(objects), 'events': len(events), 'compressed_bytes': len(z),
+ 'skipped_ids': {str(k): v for k, v in sorted(skipped.items())}})
+ if skipped:
+ print('%s: skipped ids %s' % (title, dict(skipped)))
+ out.append('const LevelDef level_defs[LEVEL_COUNT] = {')
+ out += table
+ out.append('};')
+ (ROOT / 'src/leveldata.c').write_text('\n'.join(out) + '\n')
+ (ROOT / 'levels/manifest.json').write_text(json.dumps({'source': GD_SOURCE, 'levels': manifest}, indent=2) + '\n')
+ print('levels: %d records, %d bytes raw -> %d bytes deflated' % (sum(m['objects'] for m in manifest), total_raw, total_z))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/games/numdash/tools/objdefs.py b/games/numdash/tools/objdefs.py
new file mode 100644
index 00000000..c4919881
--- /dev/null
+++ b/games/numdash/tools/objdefs.py
@@ -0,0 +1,81 @@
+"""Object catalogue shared by the level compiler and the C runtime.
+
+Hitboxes and draw layers follow Geometry Dash 2.x: hitbox sizes are in GD
+units before rotation; layer ranks encode GD's z-layer / blending / z-order
+sort so that decorations, glows, the player, portals and blocks overlap in
+the same order as the original game.
+"""
+
+# Collision kinds
+NONE, SOLID, HAZARD, SPECIAL = range(4)
+# Special behaviours
+SP = ['NONE', 'PAD_Y', 'PAD_P', 'PAD_B', 'ORB_Y', 'ORB_P', 'ORB_B', 'GRAV_N', 'GRAV_F',
+ 'PORTAL_CUBE', 'PORTAL_SHIP', 'COIN']
+# Colour types for draw parts
+CT = ['OBJ', 'BLACK', 'WHITE', 'P1ADD', 'P2ADD', 'GLOW', 'GLOW_Y', 'GLOW_B', 'GLOW_P']
+# Layer ranks (drawing order); the player is drawn at LAYER_PLAYER.
+LAYERS = ['DECO_BACK', 'RODS', 'ROD_BALLS', 'DETAIL', 'SPECIAL_GLOW', 'SPECIAL', 'PORTAL_BACK',
+ 'BLOCK_GLOW', 'PLAYER', 'COIN', 'PORTAL_FRONT', 'FILL', 'BLOCK']
+# Part flags
+F_PULSE, F_RANDOM3, F_COIN, F_ANIM = 1, 2, 4, 8
+
+# name, gd ids, collision, hitbox w, h, special, editor y offset, parts
+# part: (sprite, dx, dy, layer, colour type, flags)
+OBJECTS = [
+ ('BLOCK', [1], SOLID, 30, 30, 'NONE', 0, [('block', 0, 0, 'BLOCK', 'OBJ', 0), ('glow_all', 0, 0, 'BLOCK_GLOW', 'GLOW', 0)]),
+ ('GRID_T', [2], SOLID, 30, 30, 'NONE', 0, [('grid_t', 0, 0, 'BLOCK', 'OBJ', 0), ('glow_t', 0, 0, 'BLOCK_GLOW', 'GLOW', 0)]),
+ ('GRID_TL', [3], SOLID, 30, 30, 'NONE', 0, [('grid_tl', 0, 0, 'BLOCK', 'OBJ', 0), ('glow_tl', 0, 0, 'BLOCK_GLOW', 'GLOW', 0)]),
+ ('GRID_C', [4], SOLID, 30, 30, 'NONE', 0, [('grid_c', 0, 0, 'BLOCK', 'OBJ', 0), ('glow_c', 0, 0, 'BLOCK_GLOW', 'GLOW', 0)]),
+ ('GRID_LTR', [6], SOLID, 30, 30, 'NONE', 0, [('grid_ltr', 0, 0, 'BLOCK', 'OBJ', 0), ('glow_ltr', 0, 0, 'BLOCK_GLOW', 'GLOW', 0)]),
+ ('GRID_LR', [7], SOLID, 30, 30, 'NONE', 0, [('grid_lr', 0, 0, 'BLOCK', 'OBJ', 0), ('glow_lr', 0, 0, 'BLOCK_GLOW', 'GLOW', 0)]),
+ ('GRID_DECO', [5], NONE, 0, 0, 'NONE', 0, [('grid_none', 0, 0, 'DECO_BACK', 'OBJ', 0)]),
+ ('DIAG_DECO', [73], NONE, 0, 0, 'NONE', 0, [('diag_block', 0, 0, 'DECO_BACK', 'OBJ', 0)]),
+ ('PLANK', [40], SOLID, 30, 14, 'NONE', 8, [('plank', 0, 0, 'BLOCK', 'OBJ', 0), ('glow_plank', 0, 0, 'BLOCK_GLOW', 'GLOW', 0)]),
+ ('SLAB0', [62], SOLID, 30, 16, 'NONE', 7, [('slab0', 0, 0, 'BLOCK', 'OBJ', 0)]),
+ ('SLAB1', [65], SOLID, 30, 16, 'NONE', 7, [('slab1', 0, 0, 'BLOCK', 'OBJ', 0)]),
+ ('SLAB2', [66], SOLID, 30, 16, 'NONE', 7, [('slab2', 0, 0, 'BLOCK', 'OBJ', 0)]),
+ ('SLAB3', [68], SOLID, 30, 16, 'NONE', 7, [('slab3', 0, 0, 'BLOCK', 'OBJ', 0)]),
+ ('SPIKE', [8], HAZARD, 6, 12, 'NONE', 0, [('spike', 0, 0, 'BLOCK', 'OBJ', 0), ('glow_spike', 0, 0, 'BLOCK_GLOW', 'GLOW', 0)]),
+ ('SPIKE_SMALL', [39], HAZARD, 6, 5.6, 'NONE', -9, [('spike_small', 0, 0, 'BLOCK', 'OBJ', 0), ('glow_spike_small', 0, 0, 'BLOCK_GLOW', 'GLOW', 0)]),
+ ('SPIKE_MED', [103], HAZARD, 4, 7.6, 'NONE', -6, [('spike_med', 0, 0, 'BLOCK', 'OBJ', 0), ('glow_spike_med', 0, 0, 'BLOCK_GLOW', 'GLOW', 0)]),
+ ('PIT', [9], HAZARD, 9, 10.8, 'NONE', -13, [('pit0', 0, 0, 'BLOCK', 'BLACK', F_RANDOM3)]),
+ ('ROD1', [15], NONE, 0, 0, 'NONE', 6, [('rod1', 0, 0, 'RODS', 'BLACK', 0), ('rod_ball', 0, 35, 'ROD_BALLS', 'P1ADD', F_PULSE)]),
+ ('ROD2', [16], NONE, 0, 0, 'NONE', -1, [('rod2', 0, 0, 'RODS', 'BLACK', 0), ('rod_ball', 0, 27.5, 'ROD_BALLS', 'P1ADD', F_PULSE)]),
+ ('ROD3', [17], NONE, 0, 0, 'NONE', -8, [('rod3', 0, 0, 'RODS', 'BLACK', 0), ('rod_ball', 0, 20, 'ROD_BALLS', 'P1ADD', F_PULSE)]),
+ ('DSPIKES1', [18], NONE, 0, 0, 'NONE', 4, [('dspikes1', 0, 0, 'DETAIL', 'P1ADD', 0)]),
+ ('DSPIKES2', [19], NONE, 0, 0, 'NONE', 4, [('dspikes2', 0, 0, 'DETAIL', 'P1ADD', 0)]),
+ ('DSPIKES3', [20], NONE, 0, 0, 'NONE', -2, [('dspikes3', 0, 0, 'DETAIL', 'P1ADD', 0)]),
+ ('DSPIKES4', [21], NONE, 0, 0, 'NONE', -8, [('dspikes4', 0, 0, 'DETAIL', 'P1ADD', 0)]),
+ ('CHAIN', [41], NONE, 0, 0, 'NONE', -12, [('chain', 0, 0, 'DETAIL', 'P1ADD', 0)]),
+ ('CHAIN_SHORT', [110], NONE, 0, 0, 'NONE', -13, [('chain_short', 0, 0, 'DETAIL', 'P1ADD', 0)]),
+ ('STAR', [54], NONE, 0, 0, 'NONE', 0, [('star', 0, 0, 'DETAIL', 'P2ADD', 0)]),
+ ('PAD_Y', [35], SPECIAL, 25, 4, 'PAD_Y', -13, [('pad_yellow', 0, 0, 'SPECIAL', 'WHITE', 0), ('glow_pad_yellow', 0, 2, 'SPECIAL_GLOW', 'GLOW_Y', 0)]),
+ ('PAD_B', [67], SPECIAL, 25, 6, 'PAD_B', -12, [('pad_blue', 0, 0, 'SPECIAL', 'WHITE', 0), ('glow_pad_blue', 0, 2, 'SPECIAL_GLOW', 'GLOW_B', 0)]),
+ ('PAD_P', [140], SPECIAL, 25, 5, 'PAD_P', -13, [('pad_pink', 0, 0, 'SPECIAL', 'WHITE', 0), ('glow_pad_pink', 0, 2, 'SPECIAL_GLOW', 'GLOW_P', 0)]),
+ ('ORB_Y', [36], SPECIAL, 36, 36, 'ORB_Y', 0, [('orb_yellow', 0, 0, 'SPECIAL', 'WHITE', F_PULSE), ('glow_orb_yellow', 0, 0, 'SPECIAL_GLOW', 'GLOW_Y', 0)]),
+ ('ORB_P', [141], SPECIAL, 36, 36, 'ORB_P', 0, [('orb_pink', 0, 0, 'SPECIAL', 'WHITE', F_PULSE), ('glow_orb_pink', 0, 0, 'SPECIAL_GLOW', 'GLOW_P', 0)]),
+ ('ORB_B', [84], SPECIAL, 36, 36, 'ORB_B', 0, [('orb_blue', 0, 0, 'SPECIAL', 'WHITE', F_PULSE), ('glow_orb_blue', 0, 0, 'SPECIAL_GLOW', 'GLOW_B', 0)]),
+ ('GRAV_N', [10], SPECIAL, 25, 75, 'GRAV_N', 0, [('portal_grav_blue_front', 4, 0, 'PORTAL_FRONT', 'WHITE', 0), ('portal_grav_blue_back', -6, 0, 'PORTAL_BACK', 'WHITE', 0)]),
+ ('GRAV_F', [11], SPECIAL, 25, 75, 'GRAV_F', 0, [('portal_grav_yellow_front', 4, 0, 'PORTAL_FRONT', 'WHITE', 0), ('portal_grav_yellow_back', -6, 0, 'PORTAL_BACK', 'WHITE', 0)]),
+ ('PORTAL_CUBE', [12], SPECIAL, 34, 86, 'PORTAL_CUBE', 0, [('portal_cube_front', 5, 0, 'PORTAL_FRONT', 'WHITE', 0), ('portal_cube_back', -6, 0, 'PORTAL_BACK', 'WHITE', 0)]),
+ ('PORTAL_SHIP', [13], SPECIAL, 34, 86, 'PORTAL_SHIP', 0, [('portal_ship_front', 5, 0, 'PORTAL_FRONT', 'WHITE', 0), ('portal_ship_back', -6, 0, 'PORTAL_BACK', 'WHITE', 0)]),
+ ('COIN', [1329, 142], SPECIAL, 40, 40, 'COIN', 0, [('coin0', 0, 0, 'COIN', 'WHITE', F_COIN)]),
+]
+
+# Level trigger objects become events rather than objects.
+EV_COLOR, EV_FADE, EV_TRAIL = 1, 2, 3
+COLOR_TRIGGERS = {29: 0, 30: 1, 104: 2, 105: 3} # BG, G1, LINE, OBJ
+FADE_TRIGGERS = {22: 0, 23: 1, 24: 2, 25: 3, 26: 4, 27: 5, 28: 6, 55: 7, 56: 8, 57: 9, 58: 10, 59: 11}
+TRAIL_TRIGGERS = {32: 1, 33: 0}
+
+# Palette offered by the level editor, in GD's build-tab order.
+EDITOR = ['BLOCK', 'GRID_T', 'GRID_TL', 'GRID_LTR', 'GRID_LR', 'GRID_C', 'PLANK',
+ 'SPIKE', 'SPIKE_SMALL', 'SPIKE_MED', 'PIT', 'PAD_Y', 'PAD_P', 'PAD_B', 'ORB_Y',
+ 'PORTAL_SHIP', 'PORTAL_CUBE', 'GRAV_F', 'GRAV_N', 'COIN', 'GRID_DECO', 'ROD1', 'ROD2',
+ 'ROD3', 'DSPIKES3', 'DSPIKES4', 'CHAIN', 'STAR']
+
+INDEX = {o[0]: i + 1 for i, o in enumerate(OBJECTS)} # type 0 = none
+BY_ID = {}
+for i, o in enumerate(OBJECTS):
+ for gid in o[1]:
+ BY_ID[gid] = i + 1
diff --git a/games/numdash/tools/solve.c b/games/numdash/tools/solve.c
new file mode 100644
index 00000000..64c40c4c
--- /dev/null
+++ b/games/numdash/tools/solve.c
@@ -0,0 +1,83 @@
+/* Desktop-only reachability search. Produces real input replays through the
+ * unmodified physics (no collision bypass) to prove each shipped course can
+ * be completed. Usage: solve <level index> [output]. */
+#include "game.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#define WIDTH 3000
+#define LAYERS 9000
+#define STEP 4
+#define HASH 65536
+typedef struct { uint16_t parent; uint8_t down; } Edge;
+static Game *cur, *next;
+static Edge *parents;
+static uint64_t keys[HASH];
+static uint8_t occupied[HASH];
+static uint64_t key(const Game *g) {
+ const Player *p = &g->p;
+ uint64_t y = (uint64_t)(int64_t)(p->y * 4), v = (uint64_t)(int64_t)(p->vy * 2);
+ uint64_t k = (y & 0xffff) | ((v & 0xffff) << 16) | ((uint64_t)p->mode << 32) | ((uint64_t)p->upside << 33) |
+ ((uint64_t)p->on_ground << 34) | ((uint64_t)g->hold_prev << 35) | ((uint64_t)p->buffer << 36);
+ unsigned first = level_lower_bound(g->L, (int)p->x - 120) / 8;
+ for (unsigned i = first; i < first + 6 && i < MAX_OBJECTS / 8; i++) k = (k ^ g->used[i]) * 1099511628211ull;
+ return k;
+}
+static int insert(uint64_t k) {
+ unsigned i = (unsigned)((k ^ (k >> 29)) * 2654435761u) & (HASH - 1);
+ while (occupied[i]) { if (keys[i] == k) return 0; i = (i + 1) & (HASH - 1); }
+ occupied[i] = 1; keys[i] = k; return 1;
+}
+int main(int argc, char **argv) {
+ int index = argc > 1 ? atoi(argv[1]) : 0;
+ static Level L;
+ if (index < 0 || index >= LEVEL_COUNT || !level_load_builtin(&L, (unsigned)index)) return 2;
+ cur = calloc(WIDTH, sizeof(Game)); next = calloc(WIDTH * 2, sizeof(Game));
+ parents = calloc((size_t)LAYERS * WIDTH, sizeof(Edge));
+ Edge *pending = calloc(WIDTH * 2, sizeof(Edge));
+ if (!cur || !next || !parents || !pending) return 2;
+ game_start(&cur[0], &L, false);
+ int count = 1, finish = -1, layer = 0;
+ for (; layer < LAYERS; layer++) {
+ memset(occupied, 0, sizeof(occupied));
+ int n = 0;
+ for (int i = 0; i < count && finish < 0; i++)
+ for (int down = 0; down < 2; down++) {
+ Game *g = &next[n];
+ *g = cur[i];
+ for (int t = 0; t < STEP; t++) { g->fx_count = 0; game_step(g, down != 0); }
+ if (g->dead || !insert(key(g))) continue;
+ pending[n] = (Edge){(uint16_t)i, (uint8_t)down};
+ if (g->complete) { finish = n; n++; break; }
+ n++;
+ }
+ if (!n) {
+ fprintf(stderr, "NO PATH: %s at x=%.1f layer=%d\n", L.name, cur[0].p.x, layer);
+ return 1;
+ }
+ if (finish >= 0) { parents[(size_t)layer * WIDTH] = pending[finish]; finish = 0; break; }
+ int keep = n > WIDTH ? WIDTH : n;
+ for (int i = 0; i < keep; i++) {
+ int chosen = (int)((int64_t)i * n / keep);
+ cur[i] = next[chosen];
+ parents[(size_t)layer * WIDTH + i] = pending[chosen];
+ }
+ count = keep;
+ if (layer % 500 == 0) fprintf(stderr, "%s: %.0f%%, %d states\n", L.name, game_progress(&cur[0]), count);
+ }
+ if (finish < 0) return 1;
+ static uint8_t inputs[LAYERS];
+ int node = finish;
+ for (int j = layer; j >= 0; j--) { Edge e = parents[(size_t)j * WIDTH + node]; inputs[j] = e.down; node = e.parent; }
+ char path[256];
+ if (argc > 2) snprintf(path, sizeof(path), "%s", argv[2]);
+ else snprintf(path, sizeof(path), "tests/replays/level%d.txt", index + 1);
+ FILE *f = fopen(path, "w");
+ if (!f) return 2;
+ int prev = 0;
+ for (int j = 0; j <= layer; j++)
+ if (inputs[j] != prev) { fprintf(f, "input=%d,%d\n", j * STEP + 1, inputs[j]); prev = inputs[j]; }
+ fclose(f);
+ printf("COMPLETE: %s, %d ticks -> %s\n", L.name, (layer + 1) * STEP, path);
+ return 0;
+}
diff --git a/games/numdash/tools/sprites_game.py b/games/numdash/tools/sprites_game.py
new file mode 100644
index 00000000..be448e73
--- /dev/null
+++ b/games/numdash/tools/sprites_game.py
@@ -0,0 +1,571 @@
+"""Gameplay artwork: blocks, hazards, decorations, pads, orbs, portals, coins, icons.
+
+Each function returns (Art, format) where format is 'A4' (tinted coverage),
+'LA44' (tinted luminance + alpha) or 'PAL4' (full colour). Shapes follow the
+Geometry Dash 2.x look (black gradient blocks with bright outlines, glowing
+decorations) and are redrawn from geometric primitives at calculator scale.
+"""
+import math
+import random
+import numpy as np
+from art import Art, S, SS, stroke_mask, inset_polygon, lerp, smooth, hexc
+
+WHITE = (1.0, 1.0, 1.0)
+BLACK = (0.0, 0.0, 0.0)
+
+
+def px(u):
+ return int(math.ceil(u * S))
+
+
+def block_art(edges='ltrb', size=30, grid=False, glowpad=0):
+ """30x30 block. edges: which outline sides are drawn (l, t, r, b).
+ grid: 3x3 tile pattern (IDs 2-7) instead of a vertical gradient."""
+ half = size / 2
+ w = px(size + 2 * glowpad)
+ a = Art(w, w)
+ u, v = a.grid()
+ inside = (np.abs(u) < half) & (np.abs(v) < half)
+ if grid:
+ # three rows of cells: 80%, 60%, 40% black; thin transparent seams
+ cell = size / 3
+ row = np.clip(((half - v) // cell), 0, 2)
+ alpha = np.choose(row.astype(int), [0.80, 0.60, 0.40])
+ fu = (u + half) % cell
+ fv = (half - v) % cell
+ seam = (np.minimum(fu, cell - fu) < 0.6) | (np.minimum(fv, cell - fv) < 0.6)
+ mask = inside & ~seam
+ a.paint(mask.astype(np.float32), BLACK, 1.0)
+ a.a = np.where(mask, alpha, a.a).astype(np.float32)
+ else:
+ t = np.clip((half - 3 - v) / (size - 6), 0, 1) # 0 at top, 1 at bottom
+ alpha = 1.0 - 0.87 * t
+ m = inside.astype(np.float32)
+ a.paint(m, BLACK, 1.0)
+ a.a = np.where(inside, alpha, a.a).astype(np.float32)
+ bw = 2.0 # outline width in units
+ E = np.zeros_like(u, dtype=bool)
+ if 'l' in edges: E |= inside & (u < -half + bw)
+ if 'r' in edges: E |= inside & (u > half - bw)
+ if 't' in edges: E |= inside & (v > half - bw)
+ if 'b' in edges: E |= inside & (v < -half + bw)
+ if 'c' in edges: # inside-corner nub (ID 4)
+ E |= inside & (u < -half + bw) & (v > half - bw)
+ a.paint(E.astype(np.float32), WHITE, 1.0)
+ return a
+
+
+def glow_art(edges='ltrb', size=30, reach=6.0, peak=0.55, height=None):
+ """Soft additive light along the outlined edges of a block. Each edge
+ glows only across its own span, and outlined corners get a round join,
+ so neighbouring blocks tile without doubled-up bright spots."""
+ half = size / 2
+ hh = (height if height else size) / 2
+ a = Art(px(size + 2 * reach) + 1, px(2 * hh + 2 * reach) + 1)
+ u, v = a.grid()
+ d = np.full_like(u, 1e9)
+ inl = np.abs(v) <= hh
+ inb = np.abs(u) <= half
+ L, T, R, B = ('l' in edges), ('t' in edges), ('r' in edges), ('b' in edges)
+ if L: d = np.minimum(d, np.where(inl, np.abs(u + half), 1e9))
+ if R: d = np.minimum(d, np.where(inl, np.abs(u - half), 1e9))
+ if T: d = np.minimum(d, np.where(inb, np.abs(v - hh), 1e9))
+ if B: d = np.minimum(d, np.where(inb, np.abs(v + hh), 1e9))
+ corners = [((-half, hh), L and T), ((half, hh), R and T), ((-half, -hh), L and B), ((half, -hh), R and B)]
+ for (cx, cy), on in corners:
+ if on:
+ outside = (np.sign(u - cx) == np.sign(cx)) & (np.sign(v - cy) == np.sign(cy))
+ d = np.minimum(d, np.where(outside, np.hypot(u - cx, v - cy), 1e9))
+ if 'c' in edges:
+ d = np.minimum(d, np.hypot(u + half, v - hh))
+ g = np.clip(1 - d / reach, 0, 1) ** 1.6 * peak
+ a.rgb[:] = 1.0
+ a.a = g.astype(np.float32)
+ return a
+
+
+def spike_art(w_u=30.0, h_u=30.0, bottom=-15.0):
+ """Triangle spike, apex up, with a bright outline and gradient body."""
+ top = bottom + h_u
+ W = px(30)
+ H = px(30)
+ a = Art(W, H)
+ tri = [(-w_u / 2, bottom), (w_u / 2, bottom), (0, top)]
+ outer = a.poly_mask(tri)
+ inner_pts = inset_polygon(tri, 1.6)
+ inner = a.poly_mask(inner_pts)
+ u, v = a.grid()
+ t = np.clip((top - 0.45 * h_u - v) / (0.55 * h_u), 0, 1)
+ body_alpha = 1.0 - 0.70 * t
+ a.paint(outer, WHITE, 1.0)
+ a.rgb = np.where(inner[..., None] > 0.5, 0.0, a.rgb).astype(np.float32)
+ a.a = (outer * (1 - inner) + inner * body_alpha).astype(np.float32)
+ return a
+
+
+def spike_glow_art(w_u=30.0, h_u=30.0, bottom=-15.0, reach=6.0, peak=0.5):
+ top = bottom + h_u
+ a = Art(px(30 + 2 * reach) + 1, px(30 + 2 * reach) + 1)
+ u, v = a.grid()
+ P = [(-w_u / 2, bottom), (w_u / 2, bottom), (0, top)]
+
+ def seg(p, q):
+ (x0, y0), (x1, y1) = p, q
+ dx, dy = x1 - x0, y1 - y0
+ t = np.clip(((u - x0) * dx + (v - y0) * dy) / (dx * dx + dy * dy), 0, 1)
+ return np.hypot(u - (x0 + t * dx), v - (y0 + t * dy))
+ d = np.minimum(np.minimum(seg(P[0], P[2]), seg(P[1], P[2])), seg(P[0], P[1]) + 2.5)
+ a.rgb[:] = 1.0
+ a.a = (np.clip(1 - d / reach, 0, 1) ** 1.6 * peak).astype(np.float32)
+ return a
+
+
+def pit_art(seed):
+ """Row of jagged ground spikes (ID 9), drawn black by the level."""
+ rnd = random.Random(seed)
+ a = Art(px(30), px(27))
+ # anchor centre of the 30x27 sprite; the object sits at y=2 so its body
+ # reaches ~15 units above the ground and continues below it.
+ base_top = 2.0 # units above the anchor where the solid band ends
+ pts = [(-15, -13.5)]
+ x = -15.0
+ pts.append((x, base_top + rnd.uniform(1, 4)))
+ while x < 15:
+ step = rnd.uniform(2.6, 4.6)
+ tall = rnd.random() < 0.35
+ peak = base_top + (rnd.uniform(8.0, 12.0) if tall else rnd.uniform(3.0, 6.5))
+ valley = base_top + rnd.uniform(-1.0, 1.5)
+ pts.append((min(15, x + step * 0.5), peak))
+ x += step
+ pts.append((min(15, x), valley))
+ pts.append((15, -13.5))
+ m = a.poly_mask(pts)
+ u, v = a.grid()
+ fade = np.clip((v + 13.5) / 7.0, 0, 1) # fade out towards the bottom
+ a.paint(m, WHITE, 1.0)
+ a.a = (m * fade).astype(np.float32)
+ return a
+
+
+def plank_art():
+ """Half-height slab (ID 40): outline plus black gradient fill."""
+ a = Art(px(30), px(14) + 1)
+ u, v = a.grid()
+ inside = (np.abs(u) < 15) & (np.abs(v) < 7)
+ t = np.clip((6 - v) / 12, 0, 1)
+ a.paint(inside.astype(np.float32), BLACK, 1.0)
+ a.a = np.where(inside, 1.0 - 0.8 * t, 0).astype(np.float32)
+ edge = inside & ((np.abs(u) > 13) | (np.abs(v) > 5))
+ a.paint(edge.astype(np.float32), WHITE, 1.0)
+ return a
+
+
+def slab_wave_art(variant):
+ """Wavy 1.0-era slabs (IDs 62/65/66/68): black body, bright top line."""
+ a = Art(px(30), px(16) + 2)
+ u, v = a.grid()
+ # bottom profile: rounded bumps whose shape depends on the variant
+ shapes = {
+ 0: lambda x: -2 + 3.2 * np.cos((x + 15) / 30 * 2 * math.pi) ** 2,
+ 1: lambda x: -3 + 4.0 * np.abs(np.sin((x + 15) / 30 * math.pi * 1.5)),
+ 2: lambda x: -1.5 + 3.5 * np.cos((x + 5) / 30 * 2 * math.pi) ** 2,
+ 3: lambda x: -4 + 5.5 * np.abs(np.cos((x + 15) / 30 * math.pi)),
+ }
+ prof = shapes[variant](u)
+ body = (np.abs(u) < 15) & (v < 8) & (v > prof - 4)
+ a.paint(body.astype(np.float32), BLACK, 1.0)
+ lip = (np.abs(u) < 15) & (v > prof - 4) & (v < prof - 1.5)
+ a.a = np.where(lip, 0.55, a.a).astype(np.float32)
+ top = (np.abs(u) < 15) & (v >= 6) & (v < 8)
+ a.paint(top.astype(np.float32), WHITE, 1.0)
+ return a
+
+
+def rod_art(length):
+ """Pulse rod pole, drawn black by the level (IDs 15-17)."""
+ w_u = 6.5
+ a = Art(px(w_u) + 2, px(length) + 1)
+ u, v = a.grid()
+ pole = (np.abs(u) < 1.6) & (np.abs(v) < length / 2 - 2)
+ # segmented pole (small gaps every 5 units), fading upwards
+ seg = ((v + length / 2) % 5.5) > 1.0
+ alpha = np.clip(0.35 + 0.65 * (length / 2 - v) / length, 0, 1)
+ a.paint((pole & seg).astype(np.float32), WHITE, 1.0)
+ a.a = np.where(pole & seg, alpha, a.a).astype(np.float32)
+ foot = (np.abs(u) < 3.2) & (v < -length / 2 + 2.2) & (v > -length / 2)
+ a.paint(foot.astype(np.float32), WHITE, 1.0)
+ return a
+
+
+def ball_art(r=15.0):
+ a = Art(px(2 * r) + 1, px(2 * r) + 1)
+ m = a.ellipse_mask(0, 0, r - 0.5, r - 0.5)
+ a.paint(m, WHITE, 1.0)
+ return a
+
+
+def mountains_art(w_u, h_u, peaks, seed):
+ """Decorative spiky silhouettes (IDs 18-21), white with vertical fade."""
+ rnd = random.Random(seed)
+ a = Art(px(w_u) + 1, px(h_u) + 1)
+ pts = [(-w_u / 2, -h_u / 2)]
+ xs = sorted(rnd.uniform(-w_u / 2 + 3, w_u / 2 - 3) for _ in range(peaks))
+ prev = -w_u / 2
+ for x in xs:
+ mid = (prev + x) / 2
+ pts.append((mid, -h_u / 2 + rnd.uniform(0, h_u * 0.18)))
+ pts.append((x, -h_u / 2 + rnd.uniform(0.35, 1.0) * h_u))
+ prev = x
+ pts.append((w_u / 2, -h_u / 2))
+ m = a.poly_mask(pts)
+ u, v = a.grid()
+ fade = np.clip((v + h_u / 2) / (h_u * 0.9), 0, 1) ** 0.8
+ a.paint(m, WHITE, 1.0)
+ a.a = (m * (0.25 + 0.75 * fade)).astype(np.float32)
+ return a
+
+
+def chain_art(length, links):
+ a = Art(px(20) + 1, px(length) + 1)
+ top = length / 2
+ link_h = (length - 8) / links
+ for i in range(links):
+ cy = top - link_h * (i + 0.5)
+ horizontal = False
+ rx, ry = (3.6, link_h * 0.62)
+ outer = a.ellipse_mask(0, cy, rx, ry)
+ inner = a.ellipse_mask(0, cy, rx - 1.7, ry - 1.9)
+ ring = np.clip(outer - inner, 0, 1)
+ a.paint(ring, WHITE, 0.85)
+ base = a.rect_mask(-7, -top, 7, -top + 3)
+ hook = a.ellipse_mask(0, -top + 4.5, 3.2, 3.2) - a.ellipse_mask(0, -top + 4.5, 1.6, 1.6)
+ a.paint(np.clip(base + np.clip(hook, 0, 1), 0, 1), WHITE, 1.0)
+ return a
+
+
+def star_art(r_out=14.0, r_in=6.0):
+ a = Art(px(30) + 1, px(30) + 1)
+ pts = []
+ for i in range(10):
+ ang = math.pi / 2 + i * math.pi / 5
+ r = r_out if i % 2 == 0 else r_in
+ pts.append((r * math.cos(ang), r * math.sin(ang) - 1))
+ a.paint(a.poly_mask(pts), WHITE, 1.0)
+ return a
+
+
+def diag_block_art():
+ """ID 73 decorative block: four shaded triangles."""
+ a = Art(px(30), px(30))
+ u, v = a.grid()
+ inside = (np.abs(u) < 15) & (np.abs(v) < 15)
+ left = (u < v) & (u < -v)
+ top = (v > u) & (v > -u)
+ right = (u > v) & (u > -v)
+ alpha = np.where(left, 0.85, np.where(top, 0.55, np.where(right, 0.35, 0.2)))
+ a.paint(inside.astype(np.float32), BLACK, 1.0)
+ a.a = np.where(inside, alpha, 0).astype(np.float32)
+ return a
+
+
+# ---------------------------------------------------------------- pads / orbs
+
+PAD_COLORS = {
+ 'yellow': (hexc('ffe600'), hexc('ffb000')),
+ 'blue': (hexc('4cf7ff'), hexc('00a8ff')),
+ 'pink': (hexc('ff7cff'), hexc('e03cff')),
+}
+
+
+def pad_art(kind):
+ """Jump pad dome (IDs 35, 67, 140). Anchor = object centre."""
+ top_c, bot_c = PAD_COLORS[kind]
+ h_u = 6.0 if kind == 'blue' else 5.0
+ a = Art(px(30) + 1, px(12) + 1)
+ u, v = a.grid()
+ base = -h_u / 2
+ dome = ((u / 12.5) ** 2 + ((v - base) / h_u) ** 2 < 1) & (v >= base)
+ t = np.clip((v - base) / h_u, 0, 1)
+ col = np.stack([lerp(bot_c[i], top_c[i], t) for i in range(3)], -1)
+ a.paint(dome.astype(np.float32), col, 1.0)
+ rim = dome & ((u / 12.5) ** 2 + ((v - base) / h_u) ** 2 > 0.55)
+ a.paint(rim.astype(np.float32), tuple(min(1, c * 0.5 + 0.5) for c in top_c), 0.7)
+ return a
+
+
+def pad_glow_art(kind):
+ top_c, _ = PAD_COLORS[kind]
+ a = Art(px(36) + 1, px(18) + 1)
+ u, v = a.grid()
+ d = np.sqrt((u / 15.0) ** 2 + ((v + 3) / 8.0) ** 2)
+ g = np.clip(1 - d, 0, 1) ** 1.4 * 0.75 * (v > -3.5)
+ a.rgb[:] = top_c
+ a.a = g.astype(np.float32)
+ return a
+
+
+def orb_art(kind='yellow'):
+ """Jump orb (ID 36): filled core inside a thin bright ring."""
+ core = {'yellow': (hexc('fff34a'), hexc('ffc800')), 'pink': (hexc('ff9cff'), hexc('f040ff')),
+ 'blue': (hexc('8ff9ff'), hexc('14c8ff'))}[kind]
+ a = Art(px(30) + 1, px(30) + 1)
+ u, v = a.grid()
+ r = np.hypot(u, v)
+ ring = (r > 12.3) & (r < 14.4)
+ body = r < 9.6
+ t = np.clip((v + 9) / 18, 0, 1)
+ col = np.stack([lerp(core[1][i], core[0][i], t) for i in range(3)], -1)
+ a.paint(ring.astype(np.float32), WHITE, 1.0)
+ a.paint(body.astype(np.float32), col, 1.0)
+ rim = (r > 8.2) & (r < 9.6)
+ a.paint(rim.astype(np.float32), tuple(min(1, c * 0.6 + 0.4) for c in core[0]), 0.9)
+ return a
+
+
+def orb_glow_art(kind='yellow'):
+ c = {'yellow': hexc('ffff00'), 'pink': hexc('ff00ff'), 'blue': hexc('00ffff')}[kind]
+ a = Art(px(40) + 1, px(40) + 1)
+ u, v = a.grid()
+ r = np.hypot(u, v)
+ g = np.clip(1 - np.abs(r - 13.5) / 6.5, 0, 1) ** 1.5 * 0.6
+ a.rgb[:] = c
+ a.a = g.astype(np.float32)
+ return a
+
+
+# ---------------------------------------------------------------- portals
+
+PORTAL_STYLE = {
+ # light, mid, dark rim colours
+ 'grav_blue': (hexc('b8ffff'), hexc('3ad4ff'), hexc('0078ff')),
+ 'grav_yellow': (hexc('fffbb0'), hexc('ffdc30'), hexc('ff9c00')),
+ 'cube': (hexc('c8ffc0'), hexc('3cff3c'), hexc('00b400')),
+ 'ship': (hexc('ffc8ff'), hexc('ff5cff'), hexc('d000d0')),
+}
+
+
+def portal_arc(a, cx, rx, ry, thick, colors, alpha=1.0):
+ """Bright crescent: outer ellipse minus a shifted inner ellipse."""
+ light, mid, dark = colors
+ u, v = a.grid()
+ e_out = ((u - cx) / rx) ** 2 + (v / ry) ** 2
+ e_in = ((u - cx - thick) / (rx - thick * 0.4)) ** 2 + (v / (ry - 2.5)) ** 2
+ cres = (e_out < 1) & (e_in > 1) & (u < cx + rx * 0.2)
+ # colour: bright core line near the outer edge, darker towards the tips
+ t = np.clip(np.abs(v) / ry, 0, 1)
+ col = np.stack([lerp(lerp(light[i], mid[i], 0.35), dark[i], t ** 1.6) for i in range(3)], -1)
+ a.paint(cres.astype(np.float32), col, alpha)
+ edge = cres & (e_out > 0.80)
+ a.paint(edge.astype(np.float32), WHITE, 0.85 * alpha)
+
+
+def gravity_portal_art(style, part):
+ """Gravity portals (IDs 10/11): crescent with black teeth on the right."""
+ colors = PORTAL_STYLE[style]
+ a = Art(px(34) + 1, px(80) + 1)
+ u, v = a.grid()
+ if part == 'back':
+ portal_arc(a, -2.0, 10.0, 37.0, 6.0, colors, 0.95)
+ return a
+ # front: crescent plus the stepped black shell with teeth
+ for i in range(7):
+ y0 = -30 + i * 9
+ tooth = a.rect_mask(2.5, y0, 6.5 + 2.5 * math.cos((y0 + 4) / 38 * math.pi / 2) , y0 + 6.5)
+ a.paint(tooth, BLACK, 0.95)
+ shell = ((u - 1.5) / 5.5) ** 2 + (v / 34.0) ** 2 < 1
+ a.paint(shell.astype(np.float32), BLACK, 0.9)
+ portal_arc(a, -4.0, 9.5, 37.0, 6.0, colors, 1.0)
+ return a
+
+
+def mode_portal_art(style, part):
+ """Cube / ship portals (IDs 12/13): crescent, black cage with windows, dots."""
+ colors = PORTAL_STYLE[style]
+ light, mid, dark = colors
+ a = Art(px(40) + 1, px(92) + 1)
+ u, v = a.grid()
+ if part == 'back':
+ portal_arc(a, -4.0, 11.0, 38.0, 6.5, colors, 0.95)
+ cage = ((u - 1.0) / 8.0) ** 2 + (v / 34.0) ** 2 < 1
+ a.paint(cage.astype(np.float32), BLACK, 0.85)
+ return a
+ cage = ((u - 3.5) / 10.5) ** 2 + (v / 38.0) ** 2 < 1
+ a.paint(cage.astype(np.float32), BLACK, 0.95)
+ # window slots
+ for row in range(-3, 4):
+ for col in range(2):
+ x0 = 1.5 + col * 5.0
+ y0 = row * 9.5 - 1.8
+ slot = a.rect_mask(x0, y0, x0 + 3.2, y0 + 3.6)
+ a.paint(slot, mid, 0.55)
+ portal_arc(a, -5.5, 10.5, 39.0, 6.5, colors, 1.0)
+ for (dx, dy) in ((1.5, 43.0), (1.5, -43.0), (9.5, 14.0), (9.5, -14.0)):
+ dot = a.ellipse_mask(dx, dy, 2.6, 2.6)
+ a.paint(dot, mid, 1.0)
+ a.paint(a.ellipse_mask(dx - 0.6, dy + 0.6, 1.0, 1.0), light, 0.9)
+ return a
+
+
+# ---------------------------------------------------------------- coins
+
+GOLD = (hexc('ffe25a'), hexc('ffb000'), hexc('c86400'), hexc('3a1e00'))
+
+
+def coin_art(frame):
+ """Secret coin, four spin frames (0 face, 1 3/4, 2 edge, 3 back 3/4)."""
+ light, mid, dark, rim = GOLD
+ a = Art(px(40) + 1, px(40) + 1)
+ u, v = a.grid()
+ sx = [1.0, 0.75, 0.2, 0.75][frame]
+ r = 19.0
+ e = (u / (r * sx)) ** 2 + (v / r) ** 2
+ disc = e < 1
+ a.paint(disc.astype(np.float32), rim, 1.0)
+ inner = (u / (r * sx - 2.2 * max(sx, 0.4))) ** 2 + (v / (r - 2.2)) ** 2 < 1
+ t = np.clip((v + r) / (2 * r), 0, 1)
+ col = np.stack([lerp(dark[i], light[i], t) for i in range(3)], -1)
+ a.paint(inner.astype(np.float32), col, 1.0)
+ if frame != 2:
+ face = (u / (r * sx - 5.5 * sx)) ** 2 + (v / (r - 5.5)) ** 2 < 1
+ a.paint(face.astype(np.float32), mid, 0.9)
+ pts = []
+ for i in range(10):
+ ang = math.pi / 2 + i * math.pi / 5
+ rr = 10.0 if i % 2 == 0 else 4.2
+ pts.append((rr * math.cos(ang) * sx, rr * math.sin(ang) - 0.8))
+ star = a.poly_mask(pts)
+ a.paint(star, dark if frame == 3 else hexc('ffd23c'), 1.0)
+ a.paint(np.clip(star - a.poly_mask([(x * 0.7, y * 0.7 + 0.8) for x, y in pts]), 0, 1), dark, 0.6)
+ else:
+ a.paint(a.rect_mask(-2.0, -r + 2, 2.0, r - 2), light, 0.8)
+ shine = a.ellipse_mask(-6 * sx, 9, 3.5 * sx + 0.5, 2.2)
+ a.paint(shine, WHITE, 0.55)
+ return a
+
+
+# ---------------------------------------------------------------- player icons
+
+def cube_layers():
+ """Default cube: primary (green) frame and secondary (cyan) centre.
+ Returns (primary LA44 art, secondary LA44 art) drawn at 1x."""
+ p = Art(px(30), px(30))
+ u, v = p.grid()
+ au, av = np.abs(u), np.abs(v)
+ m = np.maximum(au, av)
+ body = m < 15
+ p.paint(body.astype(np.float32), WHITE, 1.0)
+ # outer black outline and a slightly darker bevel just inside it
+ p.paint((body & (m > 13.6)).astype(np.float32), BLACK, 1.0)
+ p.paint((body & (m > 12.4) & (m <= 13.6)).astype(np.float32), (0.72, 0.72, 0.72), 1.0)
+ # inner square: black border, transparent ring, black border around centre
+ p.paint(((m > 5.4) & (m < 8.0)).astype(np.float32), BLACK, 1.0)
+ p.erase(((m <= 5.4) & (m > 4.2)).astype(np.float32))
+ p.paint(((m <= 4.2) & (m > 2.9)).astype(np.float32), BLACK, 1.0)
+ p.erase((m <= 2.9).astype(np.float32))
+ s = Art(px(30), px(30))
+ s.paint((m <= 4.0).astype(np.float32), WHITE, 1.0)
+ return p, s
+
+
+def ship_layers():
+ """Default ship in the layout of Geometry Dash's first ship: a long hull
+ with panel lines and a rounded nose, an exhaust block at the back, and a
+ sloped deck with a tail fin in the secondary colour. Drawn in a 37 x 23
+ unit box (x right, y down) centred on the anchor."""
+ p = Art(px(38) + 2, px(24) + 2)
+ s = Art(px(38) + 2, px(24) + 2)
+
+ def poly(pts):
+ return [(x - 18.5, 11.5 - y) for x, y in pts]
+
+ hull = poly([(4, 10.5), (30, 10.5), (34.5, 11.5), (36.8, 13.2), (36.8, 16.8), (34.5, 19), (4, 19)])
+ exhaust = poly([(0.2, 9.8), (5, 9.8), (5, 18.6), (0.2, 18.6)])
+ thruster = poly([(3.6, 18), (9.6, 18), (8.6, 21.4), (4.6, 21.4)])
+ deck = poly([(5, 4.6), (18, 4.4), (27, 6.2), (32, 8.4), (35, 11.5), (5, 11.5)])
+ fin = poly([(6.2, 0.1), (11.2, 0.1), (11.2, 5.5), (6.2, 5.5)])
+ w = 1.6
+ for shape in (fin, deck, exhaust, thruster, hull):
+ p.paint(p.poly_mask(shape), BLACK, 1.0)
+ fin_in, deck_in = inset_polygon(fin[::-1], w)[::-1], inset_polygon(deck[::-1], w)[::-1]
+ p.erase(p.poly_mask(fin_in))
+ p.erase(p.poly_mask(deck_in))
+ p.paint(p.poly_mask(inset_polygon(exhaust[::-1], w)[::-1]), (0.62, 0.62, 0.62), 1.0)
+ p.paint(p.poly_mask(inset_polygon(thruster[::-1], w)[::-1]), (0.5, 0.5, 0.5), 1.0)
+ hull_in = inset_polygon(hull[::-1], w)[::-1]
+ p.paint(p.poly_mask(hull_in), WHITE, 1.0)
+ # soft shade along the bottom of the hull, then the panel lines
+ u, v = p.grid()
+ shade = np.clip((-(v) - 3.2) / 4.0, 0, 1) * p.poly_mask(hull_in)
+ p.paint(shade, (0.72, 0.72, 0.72), 0.8)
+ for x in (12.2, 25.2):
+ p.paint(p.poly_mask(poly([(x - 0.8, 11), (x + 0.8, 11), (x + 0.8, 18.5), (x - 0.8, 18.5)])), BLACK, 1.0)
+ s.paint(np.maximum(s.poly_mask(fin_in), s.poly_mask(deck_in)), WHITE, 1.0)
+ # a lighter band on the deck like the original's highlight
+ s.paint(s.poly_mask(poly([(7, 8.2), (18, 8.0), (27, 9.0), (30, 10.0), (7, 10.0)])), (0.8, 0.8, 0.8), 0.45)
+ return p, s
+
+
+# ---------------------------------------------------------------- registry
+
+def game_sprites():
+ """Ordered list of (name, art, fmt)."""
+ out = []
+ add = lambda n, a, f: out.append((n, a, f))
+ add('block', block_art('ltrb'), 'LA44')
+ add('grid_t', block_art('t', grid=True), 'LA44')
+ add('grid_tl', block_art('tl', grid=True), 'LA44')
+ add('grid_c', block_art('c', grid=True), 'LA44')
+ add('grid_none', block_art('', grid=True), 'LA44')
+ add('grid_ltr', block_art('ltr', grid=True), 'LA44')
+ add('grid_lr', block_art('lr', grid=True), 'LA44')
+ add('glow_all', glow_art('ltrb'), 'A4')
+ add('glow_t', glow_art('t'), 'A4')
+ add('glow_tl', glow_art('tl'), 'A4')
+ add('glow_c', glow_art('c', reach=5.0), 'A4')
+ add('glow_ltr', glow_art('ltr'), 'A4')
+ add('glow_lr', glow_art('lr'), 'A4')
+ add('spike', spike_art(), 'LA44')
+ add('spike_small', spike_art(30.0, 14.0, -7.0), 'LA44')
+ add('spike_med', spike_art(20.0, 19.0, -9.5), 'LA44')
+ add('glow_spike', spike_glow_art(), 'A4')
+ add('glow_spike_small', spike_glow_art(30.0, 14.0, -7.0), 'A4')
+ add('glow_spike_med', spike_glow_art(20.0, 19.0, -9.5), 'A4')
+ for i in range(3):
+ add('pit%d' % i, pit_art(11 + i * 7), 'A4')
+ add('plank', plank_art(), 'LA44')
+ add('glow_plank', glow_art('ltrb', size=30, reach=5.0, height=14), 'A4')
+ for i in range(4):
+ add('slab%d' % i, slab_wave_art(i), 'LA44')
+ add('rod1', rod_art(42.0), 'A4')
+ add('rod2', rod_art(27.0), 'A4')
+ add('rod3', rod_art(13.0), 'A4')
+ add('rod_ball', ball_art(15.0), 'A4')
+ add('dspikes1', mountains_art(128, 42, 9, 1), 'A4')
+ add('dspikes2', mountains_art(104, 37, 7, 2), 'A4')
+ add('dspikes3', mountains_art(73, 29, 6, 3), 'A4')
+ add('dspikes4', mountains_art(42, 13, 4, 4), 'A4')
+ add('chain', chain_art(70.0, 5), 'A4')
+ add('chain_short', chain_art(34.0, 2), 'A4')
+ add('star', star_art(), 'A4')
+ add('diag_block', diag_block_art(), 'LA44')
+ for k in ('yellow', 'blue', 'pink'):
+ add('pad_' + k, pad_art(k), 'PAL4')
+ add('glow_pad_' + k, pad_glow_art(k), 'A4')
+ for k in ('yellow', 'blue', 'pink'):
+ add('orb_' + k, orb_art(k), 'PAL4')
+ add('glow_orb_' + k, orb_glow_art(k), 'A4')
+ for st in ('grav_blue', 'grav_yellow'):
+ add('portal_%s_back' % st, gravity_portal_art(st, 'back'), 'PAL4')
+ add('portal_%s_front' % st, gravity_portal_art(st, 'front'), 'PAL4')
+ for st in ('cube', 'ship'):
+ add('portal_%s_back' % st, mode_portal_art(st, 'back'), 'PAL4')
+ add('portal_%s_front' % st, mode_portal_art(st, 'front'), 'PAL4')
+ for f in range(4):
+ add('coin%d' % f, coin_art(f), 'PAL4')
+ cp, cs = cube_layers()
+ add('cube1_p', cp, 'LA44')
+ add('cube1_s', cs, 'LA44')
+ sp, ssec = ship_layers()
+ add('ship1_p', sp, 'LA44')
+ add('ship1_s', ssec, 'LA44')
+ return out
diff --git a/games/numdash/tools/sprites_ui.py b/games/numdash/tools/sprites_ui.py
new file mode 100644
index 00000000..d8cd47eb
--- /dev/null
+++ b/games/numdash/tools/sprites_ui.py
@@ -0,0 +1,399 @@
+"""User-interface artwork in the style of Geometry Dash's menus: cross-shaped
+play/garage/creator buttons, round green buttons with gold icons, difficulty
+faces, coins, stars, arrows and the stepped side art. Drawn from primitives
+in pixel coordinates (y down) at 8x supersampling."""
+import math
+import numpy as np
+from PIL import Image, ImageDraw
+from art import SS, hexc, inset_polygon
+
+WHITE = (1.0, 1.0, 1.0)
+BLACK = (0.0, 0.0, 0.0)
+G_LIGHT = hexc('b4ff3c')
+G_MID = hexc('5ad200')
+G_DARK = hexc('2f8c00')
+CYAN_L = hexc('9dffff')
+CYAN = hexc('14e1ff')
+CYAN_D = hexc('0090d0')
+GOLD_L = hexc('fff45a')
+GOLD = hexc('ffc800')
+GOLD_D = hexc('e07800')
+
+
+class Px:
+ """RGBA canvas addressed in pixels (y down) with an anchor pixel."""
+
+ def __init__(self, w, h, ax=None, ay=None):
+ self.w, self.h = int(w), int(h)
+ self.ax = self.w // 2 if ax is None else int(ax)
+ self.ay = self.h // 2 if ay is None else int(ay)
+ self.rgb = np.zeros((self.h * SS, self.w * SS, 3), np.float32)
+ self.a = np.zeros((self.h * SS, self.w * SS), np.float32)
+ ys, xs = np.mgrid[0:self.h * SS, 0:self.w * SS].astype(np.float32)
+ self.gx = (xs + 0.5) / SS
+ self.gy = (ys + 0.5) / SS
+
+ def mask(self, fn):
+ im = Image.new('L', (self.w * SS, self.h * SS), 0)
+ fn(ImageDraw.Draw(im))
+ return np.asarray(im).astype(np.float32) / 255.0
+
+ def poly(self, pts):
+ return self.mask(lambda d: d.polygon([(x * SS, y * SS) for x, y in pts], fill=255))
+
+ def ellipse(self, cx, cy, rx, ry=None):
+ ry = rx if ry is None else ry
+ return self.mask(lambda d: d.ellipse([(cx - rx) * SS, (cy - ry) * SS, (cx + rx) * SS, (cy + ry) * SS], fill=255))
+
+ def rect(self, x0, y0, x1, y1):
+ return self.poly([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])
+
+ def line(self, pts, width):
+ def fn(d):
+ xy = [(x * SS, y * SS) for x, y in pts]
+ d.line(xy, fill=255, width=max(1, int(width * SS)))
+ r = width * SS / 2
+ for x, y in xy:
+ d.ellipse([x - r, y - r, x + r, y + r], fill=255)
+ return self.mask(fn)
+
+ def paint(self, m, color, alpha=1.0):
+ m = np.clip(m * alpha, 0, 1)
+ col = np.asarray(color, np.float32)
+ if col.ndim == 1:
+ col = col.reshape(1, 1, 3)
+ self.rgb = self.rgb * (1 - m[..., None]) + col * m[..., None]
+ self.a = self.a + (1 - self.a) * m
+
+ def vgrad(self, top, bottom, y0, y1):
+ t = np.clip((self.gy - y0) / max(1e-6, y1 - y0), 0, 1)[..., None]
+ return np.asarray(top, np.float32) * (1 - t) + np.asarray(bottom, np.float32) * t
+
+ def image(self):
+ h, w = self.h, self.w
+ a = self.a.reshape(h, SS, w, SS).mean(axis=(1, 3))
+ prem = (self.rgb * self.a[..., None]).reshape(h, SS, w, SS, 3).mean(axis=(1, 3))
+ rgb = np.where(a[..., None] > 1e-6, prem / np.maximum(a[..., None], 1e-6), 0)
+ return np.concatenate([np.clip(rgb, 0, 1), np.clip(a, 0, 1)[..., None]], axis=2)
+
+
+def grow(m, px_):
+ """Dilate a supersampled mask by px_ pixels."""
+ from PIL import ImageFilter
+ im = Image.fromarray((m * 255).astype(np.uint8))
+ r = int(round(px_ * SS))
+ k = 2 * r + 1
+ while k > 1:
+ step = min(k, 9)
+ if step % 2 == 0:
+ step -= 1
+ im = im.filter(ImageFilter.MaxFilter(step))
+ k -= step - 1
+ return np.asarray(im).astype(np.float32) / 255.0
+
+
+def outlined(c, m, fill, outline=1.6, shadow=0.0):
+ """Black outline (and optional drop shadow) around a shape, then its fill."""
+ o = grow(m, outline)
+ if shadow:
+ sh = np.roll(np.roll(o, int(shadow * SS), 0), int(shadow * SS * 0.6), 1)
+ c.paint(sh, BLACK, 0.45)
+ c.paint(o, BLACK)
+ c.paint(m, fill)
+
+
+# ------------------------------------------------------------ icon glyphs
+
+def tri_right(cx, cy, s):
+ return [(cx - s * 0.55, cy - s * 0.75), (cx + s * 0.8, cy), (cx - s * 0.55, cy + s * 0.75)]
+
+
+def draw_play(c, cx, cy, s):
+ m = c.poly(tri_right(cx, cy, s))
+ outlined(c, m, c.vgrad(GOLD_L, GOLD_D, cy - s, cy + s), outline=max(1.2, s * 0.12))
+
+
+def draw_gear(c, cx, cy, s):
+ teeth = []
+ for i in range(16):
+ ang = i * math.pi / 8
+ r = s * (1.0 if i % 2 == 0 else 0.78)
+ teeth.append((cx + r * math.cos(ang + 0.2), cy + r * math.sin(ang + 0.2)))
+ teeth.append((cx + r * math.cos(ang - 0.2 + math.pi / 8), cy + r * math.sin(ang - 0.2 + math.pi / 8)))
+ m = np.clip(c.poly(teeth) - c.ellipse(cx, cy, s * 0.36), 0, 1)
+ outlined(c, m, c.vgrad(GOLD_L, GOLD_D, cy - s, cy + s), outline=1.3)
+
+
+def draw_bars(c, cx, cy, s):
+ m = np.zeros_like(c.a)
+ for i, hgt in enumerate((0.9, 1.5, 1.15)):
+ x0 = cx - s * 0.95 + i * s * 0.68
+ m = np.maximum(m, c.rect(x0, cy + s * 0.8 - s * hgt, x0 + s * 0.5, cy + s * 0.8))
+ outlined(c, m, c.vgrad(GOLD_L, GOLD_D, cy - s, cy + s), outline=1.3)
+
+
+def draw_question(c, cx, cy, s):
+ arc = c.line([(cx - s * 0.5, cy - s * 0.35), (cx - s * 0.35, cy - s * 0.8), (cx + s * 0.2, cy - s * 0.9),
+ (cx + s * 0.55, cy - s * 0.55), (cx + s * 0.4, cy - s * 0.1), (cx, cy + s * 0.15), (cx, cy + s * 0.35)], s * 0.38)
+ dot = c.ellipse(cx, cy + s * 0.8, s * 0.22)
+ outlined(c, np.maximum(arc, dot), c.vgrad(GOLD_L, GOLD_D, cy - s, cy + s), outline=1.3)
+
+
+def draw_arrow_left(c, cx, cy, s):
+ pts = [(cx - s * 0.9, cy), (cx - s * 0.05, cy - s * 0.8), (cx - s * 0.05, cy - s * 0.32), (cx + s * 0.85, cy - s * 0.32),
+ (cx + s * 0.85, cy + s * 0.32), (cx - s * 0.05, cy + s * 0.32), (cx - s * 0.05, cy + s * 0.8)]
+ outlined(c, c.poly(pts), c.vgrad(GOLD_L, GOLD_D, cy - s, cy + s), outline=1.3)
+
+
+def draw_replay(c, cx, cy, s):
+ ring = np.clip(c.ellipse(cx, cy, s * 0.85) - c.ellipse(cx, cy, s * 0.48), 0, 1)
+ ring *= 1 - c.poly([(cx, cy), (cx + s * 1.2, cy - s * 1.2), (cx + s * 1.2, cy - s * 0.1)])
+ head = c.poly([(cx + s * 0.28, cy - s * 0.95), (cx + s * 1.02, cy - s * 0.52), (cx + s * 0.4, cy - s * 0.02)])
+ m = np.clip(ring + head, 0, 1)
+ outlined(c, m, c.vgrad(CYAN_L, CYAN_D, cy - s, cy + s), outline=1.3)
+
+
+def draw_list(c, cx, cy, s):
+ m = np.zeros_like(c.a)
+ for i in range(3):
+ y = cy - s * 0.6 + i * s * 0.6
+ m = np.maximum(m, c.ellipse(cx - s * 0.62, y, s * 0.2))
+ m = np.maximum(m, c.rect(cx - s * 0.28, y - s * 0.17, cx + s * 0.85, y + s * 0.17))
+ outlined(c, m, c.vgrad(CYAN_L, CYAN_D, cy - s, cy + s), outline=1.3)
+
+
+def draw_diamond(c, cx, cy, s, cross=False):
+ pts = [(cx, cy - s), (cx + s * 0.6, cy), (cx, cy + s), (cx - s * 0.6, cy)]
+ m = c.poly(pts)
+ outlined(c, m, hexc('46ff5a'), outline=1.3)
+ c.paint(c.poly([(cx, cy - s), (cx + s * 0.6, cy), (cx, cy)]), hexc('c8ffc8'), 0.9)
+ c.paint(c.poly([(cx, cy + s), (cx - s * 0.6, cy), (cx, cy)]), hexc('00b432'), 0.9)
+ if cross:
+ ring = np.clip(c.ellipse(cx, cy, s * 0.95) - c.ellipse(cx, cy, s * 0.72), 0, 1)
+ bar = c.poly([(cx - s * 0.62, cy - s * 0.78), (cx - s * 0.78, cy - s * 0.62), (cx + s * 0.62, cy + s * 0.78), (cx + s * 0.78, cy + s * 0.62)])
+ outlined(c, np.clip(ring + bar, 0, 1), hexc('ff2828'), outline=1.0)
+
+
+def draw_face_icon(c, cx, cy, s):
+ m = c.rect(cx - s, cy - s, cx + s, cy + s)
+ outlined(c, m, c.vgrad(GOLD_L, GOLD_D, cy - s, cy + s), outline=1.4)
+ for dx in (-0.45, 0.45):
+ c.paint(c.rect(cx + dx * s - s * 0.2, cy - s * 0.45, cx + dx * s + s * 0.2, cy - s * 0.05), BLACK)
+ c.paint(c.rect(cx - s * 0.55, cy + s * 0.3, cx + s * 0.55, cy + s * 0.52), BLACK)
+
+
+def draw_tools(c, cx, cy, s):
+ ham = c.poly([(cx - s * 0.9, cy - s * 0.55), (cx - s * 0.2, cy - s * 0.95), (cx + s * 0.05, cy - s * 0.55), (cx - s * 0.55, cy - s * 0.15)])
+ handle = c.line([(cx - s * 0.35, cy - s * 0.45), (cx + s * 0.75, cy + s * 0.8)], s * 0.3)
+ wrench = c.line([(cx + s * 0.55, cy - s * 0.55), (cx - s * 0.6, cy + s * 0.7)], s * 0.3)
+ jaw = np.clip(c.ellipse(cx + s * 0.62, cy - s * 0.62, s * 0.38) - c.poly([(cx + s * 0.62, cy - s * 0.62), (cx + s * 1.2, cy - s * 1.1), (cx + s * 1.2, cy - s * 0.3)]), 0, 1)
+ m = np.clip(ham + handle + wrench + jaw, 0, 1)
+ outlined(c, m, c.vgrad(GOLD_L, GOLD_D, cy - s, cy + s), outline=1.3)
+
+
+# ------------------------------------------------------------ buttons
+
+def round_button(d, icon, color='green', ring=False):
+ pad = 3 if ring else 0
+ c = Px(d + 3 + 2 * pad, d + 3 + 2 * pad)
+ r = d / 2 - 1
+ cx = cy = d / 2 + 0.5 + pad
+ disc = c.ellipse(cx, cy, r)
+ outer = grow(disc, 1.2 + (2.2 if ring else 0))
+ c.paint(np.roll(np.roll(outer, int(1.5 * SS), 0), int(SS), 1), BLACK, 0.45)
+ if ring:
+ c.paint(outer, hexc('f0f0f0'))
+ c.paint(grow(disc, 1.2), BLACK)
+ body = c.vgrad(G_LIGHT, G_DARK, cy - r, cy + r) if color == 'green' else c.vgrad(CYAN_L, CYAN_D, cy - r, cy + r)
+ c.paint(disc, body)
+ rim = np.clip(c.ellipse(cx, cy, r) - c.ellipse(cx, cy, r - max(2.0, r * 0.14)), 0, 1)
+ c.paint(rim, hexc('d8ff9c') if color == 'green' else CYAN_L, 0.55)
+ c.paint(c.ellipse(cx - r * 0.3, cy - r * 0.45, r * 0.35, r * 0.2), WHITE, 0.35)
+ if icon:
+ icon(c, cx, cy, r * 0.55)
+ return c
+
+
+def cross_button(d, icon):
+ """GD's plus-shaped main menu buttons: green arms, cyan inner corners."""
+ c = Px(d + 4, d + 4)
+ cx = cy = d / 2 + 1
+ a = d / 2 - 1 # half size
+ b = a * 0.42 # half arm width
+ arms = np.clip(c.rect(cx - b, cy - a, cx + b, cy + a) + c.rect(cx - a, cy - b, cx + a, cy + b), 0, 1)
+ corners = np.zeros_like(arms)
+ k = a * 0.52
+ for sx in (-1, 1):
+ for sy in (-1, 1):
+ x0, y0 = cx + sx * b, cy + sy * b
+ corners = np.maximum(corners, c.rect(min(x0, x0 + sx * (k - b) * 1.9), min(y0, y0 + sy * (k - b) * 1.9),
+ max(x0, x0 + sx * (k - b) * 1.9), max(y0, y0 + sy * (k - b) * 1.9)))
+ shape = np.clip(arms + corners, 0, 1)
+ c.paint(np.roll(np.roll(grow(shape, 1.8), int(2 * SS), 0), int(1.5 * SS), 1), BLACK, 0.45)
+ c.paint(grow(shape, 1.8), BLACK)
+ c.paint(corners, c.vgrad(CYAN_L, CYAN_D, cy - a, cy + a))
+ c.paint(grow(corners, 0.9) * (1 - grow(corners, 0.0)), BLACK, 0.8)
+ c.paint(arms, c.vgrad(G_LIGHT, G_DARK, cy - a, cy + a))
+ # bevel: light top-left inner edge, darker lower right
+ inner = grow(arms, 0) - np.clip(np.roll(np.roll(arms, int(2 * SS), 0), int(2 * SS), 1), 0, 1)
+ c.paint(np.clip(inner, 0, 1), hexc('e6ffb4'), 0.55)
+ if icon:
+ icon(c, cx, cy, a * 0.5)
+ return c
+
+
+def arrow_back(w, h):
+ """GD's green triangle back arrow (points left)."""
+ c = Px(w + 4, h + 4)
+ pts = [(w + 1, 2), (2, h / 2 + 2), (w + 1, h + 2)]
+ m = c.poly(pts)
+ c.paint(np.roll(np.roll(grow(m, 1.6), int(1.5 * SS), 0), int(SS), 1), BLACK, 0.45)
+ c.paint(grow(m, 1.6), BLACK)
+ c.paint(m, c.vgrad(hexc('c8ff5a'), hexc('3ca000'), 2, h + 2))
+ inner = c.poly(inset_polygon(pts[::-1], 2.4)[::-1])
+ c.paint(np.clip(m - inner, 0, 1), hexc('e6ffaa'), 0.5)
+ return c
+
+
+def pause_icon(c, cx, cy, s):
+ m = np.maximum(c.rect(cx - s * 0.62, cy - s * 0.7, cx - s * 0.16, cy + s * 0.7), c.rect(cx + s * 0.16, cy - s * 0.7, cx + s * 0.62, cy + s * 0.7))
+ outlined(c, m, c.vgrad(CYAN_L, CYAN_D, cy - s, cy + s), outline=1.0)
+
+
+def nav_arrow(w, h):
+ c = Px(w + 3, h + 3)
+ pts = [(1, 1), (w - 1, h / 2), (1, h - 1)]
+ m = c.poly(pts)
+ c.paint(np.roll(np.roll(m, int(2 * SS), 0), int(2 * SS), 1), BLACK, 0.5)
+ c.paint(m, c.vgrad(WHITE, hexc('c8c8c8'), 0, h))
+ c.paint(np.clip(m - c.poly(inset_polygon([(1, h - 1), (w - 1, h / 2), (1, 1)], 2.2)[::-1]), 0, 1), hexc('ffffff'), 0.6)
+ return c
+
+
+def diff_face(kind):
+ """Difficulty faces: easy, normal, hard, harder, insane."""
+ cols = {1: (hexc('7cf2ff'), hexc('00a8ff')), 2: (hexc('8cff64'), hexc('20c800')), 3: (hexc('ffd264'), hexc('ff9600')),
+ 4: (hexc('ff8c64'), hexc('e61e1e')), 5: (hexc('ff9cff'), hexc('dc28dc'))}[kind]
+ d = 26
+ c = Px(d + 3, d + 3)
+ cx = cy = d / 2 + 0.5
+ r = d / 2 - 1
+ head = c.ellipse(cx, cy, r)
+ c.paint(grow(head, 1.2), BLACK)
+ c.paint(head, c.vgrad(cols[0], cols[1], cy - r, cy + r))
+ c.paint(c.ellipse(cx - r * 0.35, cy - r * 0.5, r * 0.3, r * 0.16), WHITE, 0.4)
+ # eyes
+ for sx in (-1, 1):
+ ex = cx + sx * r * 0.38
+ if kind >= 4:
+ brow = c.poly([(ex - r * 0.3, cy - r * 0.45 - (0.1 if sx < 0 else -0.1) * r * 3), (ex + r * 0.3, cy - r * 0.45 + (0.1 if sx < 0 else -0.1) * r * 3),
+ (ex + r * 0.3, cy - r * 0.25 + (0.1 if sx < 0 else -0.1) * r * 3), (ex - r * 0.3, cy - r * 0.25 - (0.1 if sx < 0 else -0.1) * r * 3)])
+ c.paint(brow, BLACK)
+ c.paint(c.ellipse(ex, cy - r * 0.1, r * 0.2, r * 0.24), WHITE)
+ c.paint(c.ellipse(ex + sx * r * 0.04, cy - r * 0.08, r * 0.11), BLACK)
+ # mouth
+ if kind <= 2:
+ smile = c.ellipse(cx, cy + r * 0.22, r * 0.45, r * 0.38) * c.rect(0, cy + r * 0.22, 999, 999)
+ c.paint(smile, BLACK)
+ if kind == 1:
+ c.paint(c.ellipse(cx, cy + r * 0.48, r * 0.22, r * 0.1), hexc('ff5a78'))
+ elif kind == 3:
+ c.paint(c.rect(cx - r * 0.4, cy + r * 0.38, cx + r * 0.4, cy + r * 0.52), BLACK)
+ else:
+ frown = c.ellipse(cx, cy + r * 0.62, r * 0.45, r * 0.32) * c.rect(0, 0, 999, cy + r * 0.62)
+ c.paint(frown, BLACK)
+ if kind == 5:
+ for tx in (-0.25, 0.0, 0.25):
+ c.paint(c.poly([(cx + (tx - 0.09) * r, cy + r * 0.34), (cx + (tx + 0.09) * r, cy + r * 0.34), (cx + tx * r, cy + r * 0.5)]), WHITE)
+ return c
+
+
+def star(d, color=GOLD):
+ c = Px(d + 2, d + 2)
+ cx = cy = d / 2 + 1
+ pts = []
+ for i in range(10):
+ ang = -math.pi / 2 + i * math.pi / 5
+ r = d / 2 - 0.5 if i % 2 == 0 else d * 0.21
+ pts.append((cx + r * math.cos(ang), cy + r * math.sin(ang)))
+ m = c.poly(pts)
+ outlined(c, m, c.vgrad(GOLD_L, GOLD_D, cy - d / 2, cy + d / 2) if color == GOLD else color, outline=1.0)
+ return c
+
+
+def coin_icon(d, filled=True):
+ c = Px(d + 2, d + 2)
+ cx = cy = d / 2 + 1
+ r = d / 2 - 0.5
+ disc = c.ellipse(cx, cy, r)
+ c.paint(grow(disc, 0.8), hexc('3a1e00') if filled else hexc('202020'))
+ if filled:
+ c.paint(disc, c.vgrad(hexc('ffe25a'), hexc('d27800'), cy - r, cy + r))
+ else:
+ c.paint(disc, c.vgrad(hexc('9a9a9a'), hexc('505050'), cy - r, cy + r))
+ pts = []
+ for i in range(10):
+ ang = -math.pi / 2 + i * math.pi / 5
+ rr = r * 0.62 if i % 2 == 0 else r * 0.26
+ pts.append((cx + rr * math.cos(ang), cy + rr * math.sin(ang) + 0.3))
+ c.paint(c.poly(pts), hexc('c86400') if filled else hexc('3a3a3a'), 0.9)
+ return c
+
+
+def side_art(n):
+ """Stepped corner decoration (lime and cyan blocks)."""
+ s = 10
+ c = Px(n * s + 3, n * s + 3, 0, n * s + 3)
+ for col in range(n):
+ for row in range(n - col):
+ x0, y0 = col * s + 1, (n - 1 - row) * s + 1
+ m = c.rect(x0, y0, x0 + s - 1, y0 + s - 1)
+ colr = CYAN if (col + row) % 2 == 0 else G_LIGHT
+ c.paint(grow(m, 0.9), BLACK)
+ c.paint(m, c.vgrad(colr, tuple(v * 0.7 for v in colr), y0, y0 + s))
+ return c
+
+
+def checkbox(on):
+ d = 18
+ c = Px(d + 2, d + 2)
+ m = c.rect(1.5, 1.5, d - 0.5, d - 0.5)
+ c.paint(grow(m, 1.0), BLACK)
+ c.paint(m, c.vgrad(hexc('c8c8c8'), hexc('787878'), 0, d))
+ if on:
+ tick = c.line([(4.5, 10), (8, 14), (15.5, 4.5)], 3.2)
+ outlined(c, tick, c.vgrad(hexc('a0ff50'), hexc('28b400'), 0, d), outline=1.0)
+ return c
+
+
+def ui_sprites():
+ out = []
+ add = lambda n, c, f='PAL4': out.append((n, c, f))
+ add('btn_play', cross_button(74, draw_play))
+ add('btn_garage', cross_button(50, draw_face_icon))
+ add('btn_creator', cross_button(50, draw_tools))
+ add('btn_settings', round_button(34, draw_gear))
+ add('btn_stats', round_button(34, draw_bars))
+ add('btn_help', round_button(34, draw_question))
+ add('btn_back', round_button(30, draw_arrow_left))
+ add('btn_resume', round_button(62, draw_play, ring=True))
+ add('btn_replay', round_button(46, draw_replay, ring=True))
+ add('btn_menu', round_button(46, draw_list, ring=True))
+ add('btn_practice', round_button(46, lambda c, x, y, s: draw_diamond(c, x, y, s * 1.2), ring=True))
+ add('btn_normal', round_button(46, lambda c, x, y, s: draw_diamond(c, x, y, s * 1.2, True), ring=True))
+ add('btn_settings_small', round_button(28, draw_gear))
+ add('btn_pause', round_button(22, pause_icon))
+ add('arrow_back', arrow_back(20, 26))
+ add('nav_arrow', nav_arrow(22, 50))
+ for k in range(1, 6):
+ add('face%d' % k, diff_face(k))
+ add('star_ui', star(12))
+ add('star_big', star(22))
+ add('coin_ui', coin_icon(14))
+ add('coin_ui_empty', coin_icon(14, False))
+ add('coin_big', coin_icon(26))
+ add('coin_big_empty', coin_icon(26, False))
+ add('side_art', side_art(4))
+ add('check_on', checkbox(True))
+ add('check_off', checkbox(False))
+ return out
diff --git a/games/numdrive/.gitignore b/games/numdrive/.gitignore
new file mode 100644
index 00000000..5721931b
--- /dev/null
+++ b/games/numdrive/.gitignore
@@ -0,0 +1,6 @@
+output/
+host/nd
+host/nd_*
+host/out*/
+host/test_inflate
+src/pack.c
diff --git a/games/numdrive/Makefile b/games/numdrive/Makefile
new file mode 100644
index 00000000..db3c8164
--- /dev/null
+++ b/games/numdrive/Makefile
@@ -0,0 +1,75 @@
+# NumDrive: a Drive Mad inspired game for the NumWorks calculator
+# make -> output/device/numdrive.nwa
+# make PLATFORM=simulator -> output/simulator/numdrive.nwb (for the Epsilon simulator)
+Q ?= @
+PLATFORM ?= device
+NWLINK ?= npx --yes -- nwlink
+BUILD_DIR = output/$(PLATFORM)
+
+SOURCES = main.c world.c vm.c physics.c render.c inflate.c gfx.c ui.c save.c font.c platform_eadk.c
+OBJECTS = $(addprefix $(BUILD_DIR)/,$(SOURCES:.c=.o)) $(BUILD_DIR)/pack_data.o
+
+CFLAGS = -std=gnu11 -Wall -Wno-unused-function -fsingle-precision-constant
+
+ifeq ($(PLATFORM),device)
+CC = arm-none-eabi-gcc
+TARGET = $(BUILD_DIR)/numdrive.nwa
+CFLAGS += $(shell $(NWLINK) eadk-cflags-device) -O2
+CFLAGS += -flto -flto-partition=one -fno-fat-lto-objects -fwhole-program -fvisibility=internal -fno-math-errno -fno-ident
+LDFLAGS = $(shell $(NWLINK) eadk-ldflags-device) --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level -Wl,--gc-sections
+LDFLAGS += -flinker-output=nolto-rel
+EXTRA = $(BUILD_DIR)/icon.o
+else
+CC = gcc
+TARGET = $(BUILD_DIR)/numdrive.nwb
+CFLAGS += $(shell $(NWLINK) eadk-cflags-simulator) -O2 -DNO_STORAGE
+LDFLAGS = $(shell $(NWLINK) eadk-ldflags-simulator)
+EXTRA =
+endif
+
+.PHONY: build clean
+build: $(TARGET)
+
+$(TARGET): $(OBJECTS) $(EXTRA)
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $^ $(LDFLAGS) -lm -o $@
+ifeq ($(PLATFORM),device)
+ $(Q) arm-none-eabi-strip --strip-unneeded -R .comment $@
+endif
+
+$(BUILD_DIR)/%.o: src/%.c src/*.h | $(BUILD_DIR)
+ @echo "CC $<"
+ $(Q) $(CC) $(CFLAGS) -c $< -o $@
+
+$(BUILD_DIR)/pack_data.o: src/pack_data.S src/pack.bin | $(BUILD_DIR)
+ @echo "AS $<"
+ $(Q) $(CC) $(CFLAGS) -Wa,-Isrc -c $< -o $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+clean:
+ $(Q) rm -rf output
+
+# NumPlay launcher: the game as a module (see ../../tools/npmodule.py) for the
+# calculator, and as a relocatable object for the simulator build.
+.PHONY: module sim-module
+module: output/device/module.o
+output/device/module.o: $(addprefix output/device/,$(SOURCES:.c=.o)) output/device/pack_data.o
+ @echo "LD $@"
+ $(Q) arm-none-eabi-gcc $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel $^ -o $@
+
+sim-module: output/npsim/sim-module.o
+output/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 \
+ $(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) ld -r output/npsim/*.o -exported_symbol _np_numdrive_main -o $@
diff --git a/games/numdrive/README.md b/games/numdrive/README.md
new file mode 100644
index 00000000..658c4c61
--- /dev/null
+++ b/games/numdrive/README.md
@@ -0,0 +1,47 @@
+# NumDrive: Drive Mad for NumWorks
+
+NumDrive is a Drive Mad style driving game for the NumWorks N0120 calculator.
+
+157 levels of cars, physics puzzles, bridges and water, in a 240 KB app.
+
+<p align="center">
+ <img src="docs/shot1.png" width="320"> <img src="docs/shot2.png" width="320">
+ <img src="docs/shot3.png" width="320"> <img src="docs/shot4.png" width="320">
+ <img src="docs/shot5.png" width="320"> <img src="docs/shot6.png" width="320">
+</p>
+
+## Install
+
+1. Download `NumDrive.nwa` from the [latest release](https://github.com/Mason363/NumDrive/releases/latest).
+2. Plug your calculator into a computer and open [my.numworks.com/apps](https://my.numworks.com/apps) in Chrome or Edge.
+3. Upload `NumDrive.nwa` and send it to the calculator.
+4. Open NumDrive from the home screen.
+
+## Controls
+
+| Key | Action |
+| --- | --- |
+| Right arrow | Drive forward |
+| Left arrow | Brake and reverse |
+| OK or Back | Pause |
+| Arrows, then OK | Pick a button or a level |
+| Back on a card | Level list |
+| Home | Quit |
+
+Your progress is saved on the calculator.
+
+## Build
+
+You need `arm-none-eabi-gcc` and Node.js.
+
+```
+make
+```
+
+The app is written to `output/device/numdrive.nwa`.
+
+## Credits
+
+Made by Mason Chen. Inspired by Drive Mad.
+
+This is an unofficial fan game and is not affiliated with the makers of Drive Mad.
diff --git a/games/numdrive/VERSION b/games/numdrive/VERSION
new file mode 100644
index 00000000..9084fa2f
--- /dev/null
+++ b/games/numdrive/VERSION
@@ -0,0 +1 @@
+1.1.0
diff --git a/games/numdrive/docs/shot1.png b/games/numdrive/docs/shot1.png
new file mode 100644
index 00000000..2f62178a
Binary files /dev/null and b/games/numdrive/docs/shot1.png differ
diff --git a/games/numdrive/docs/shot2.png b/games/numdrive/docs/shot2.png
new file mode 100644
index 00000000..9e5e80e0
Binary files /dev/null and b/games/numdrive/docs/shot2.png differ
diff --git a/games/numdrive/docs/shot3.png b/games/numdrive/docs/shot3.png
new file mode 100644
index 00000000..f9a8c582
Binary files /dev/null and b/games/numdrive/docs/shot3.png differ
diff --git a/games/numdrive/docs/shot4.png b/games/numdrive/docs/shot4.png
new file mode 100644
index 00000000..a1f42ce0
Binary files /dev/null and b/games/numdrive/docs/shot4.png differ
diff --git a/games/numdrive/docs/shot5.png b/games/numdrive/docs/shot5.png
new file mode 100644
index 00000000..646754c9
Binary files /dev/null and b/games/numdrive/docs/shot5.png differ
diff --git a/games/numdrive/docs/shot6.png b/games/numdrive/docs/shot6.png
new file mode 100644
index 00000000..b06a2147
Binary files /dev/null and b/games/numdrive/docs/shot6.png differ
diff --git a/games/numdrive/host/Makefile b/games/numdrive/host/Makefile
new file mode 100644
index 00000000..05d184b5
--- /dev/null
+++ b/games/numdrive/host/Makefile
@@ -0,0 +1,13 @@
+SRC = ../src/main.c ../src/world.c ../src/vm.c ../src/physics.c ../src/render.c ../src/inflate.c ../src/pack_data.S ../src/gfx.c ../src/ui.c ../src/save.c ../src/font.c platform_host.c
+CFLAGS = -O2 -g -Wall -Wno-unused-function -DHOST -DARENA_SIZE=600000 -I../src -Wa,-I../src
+
+nd: $(SRC) ../src/*.h ../src/pack.bin
+ gcc $(CFLAGS) -o nd $(SRC) -lm
+
+clean:
+ rm -f nd
+
+# 32-bit ARM build of the harness, run under qemu-arm (exact device memory layout)
+nd_arm: $(SRC) ../src/*.h ../src/pack.bin
+ arm-none-eabi-gcc -mcpu=cortex-a9 -mthumb -mfloat-abi=hard -mfpu=vfpv3-d16 --specs=rdimon.specs -O2 -DARMTEST \
+ -DHOST -DARENA_PROFILE -I../src -Wa,-I../src -o nd_arm $(SRC) -lm
diff --git a/games/numdrive/host/armcheck.sh b/games/numdrive/host/armcheck.sh
new file mode 100755
index 00000000..aa5ae7d6
--- /dev/null
+++ b/games/numdrive/host/armcheck.sh
@@ -0,0 +1,9 @@
+#!/bin/sh
+# Run every level on the 32-bit ARM harness (qemu-arm) with the device arena; report failures.
+cd "$(dirname "$0")"
+one() {
+ r=$(timeout 600 qemu-arm ./nd_arm ND_NORENDER=1 ND_STATS=1 ND_LEVEL=$1 ND_FRAMES=${FRAMES:-600} ND_KEYS=${KEYS:-RIGHT:5:900} 2>&1 | grep -v PROF | tr '\n' ' ')
+ echo "$1 $r"
+}
+if [ -n "$1" ]; then one "$1"; exit; fi
+seq 0 $((${NLEVELS:-157} - 1)) | xargs -P 8 -I{} "$0" {} | sort -n
diff --git a/games/numdrive/host/caps.sh b/games/numdrive/host/caps.sh
new file mode 100755
index 00000000..7e6a8d28
--- /dev/null
+++ b/games/numdrive/host/caps.sh
@@ -0,0 +1,18 @@
+#!/bin/sh
+# Measure per-level peak object / body / joint counts under several input patterns.
+# Output: ../tools/caps.txt ("level objects bodies joints"), read by tools/pack.py.
+cd "$(dirname "$0")"
+one() {
+ i=$1; mo=0; mb=0; mj=0
+ for keys in "RIGHT:5:900" "LEFT:5:900" "RIGHT:5:120,LEFT:120:240,RIGHT:240:900" "RIGHT:300:301"; do
+ r=$(ND_NORENDER=1 ND_NOCAPS=1 ND_STATS=1 ND_LEVEL=$i ND_FRAMES=900 ND_KEYS=$keys timeout 120 ./nd 2>/dev/null | grep -o 'STATS arena.*')
+ o=$(echo "$r" | sed -n 's/.* obj=\([0-9]*\).*/\1/p'); b=$(echo "$r" | sed -n 's/.* bodies=\([0-9]*\).*/\1/p'); j=$(echo "$r" | sed -n 's/.* joints=\([0-9]*\).*/\1/p')
+ [ -n "$o" ] && [ "$o" -gt "$mo" ] && mo=$o
+ [ -n "$b" ] && [ "$b" -gt "$mb" ] && mb=$b
+ [ -n "$j" ] && [ "$j" -gt "$mj" ] && mj=$j
+ done
+ echo "$i $mo $mb $mj"
+}
+if [ -n "$1" ]; then one "$1"; exit; fi
+seq 0 199 | xargs -P 3 -I{} "$0" {} | sort -n > ../tools/caps.txt.tmp
+mv ../tools/caps.txt.tmp ../tools/caps.txt
diff --git a/games/numdrive/host/platform_host.c b/games/numdrive/host/platform_host.c
new file mode 100644
index 00000000..82c8a58e
--- /dev/null
+++ b/games/numdrive/host/platform_host.c
@@ -0,0 +1,261 @@
+/* Headless host platform for automated testing.
+ * Env vars: ND_FRAMES (stop after N frames), ND_SHOTS ("1,20,50" or "all"), ND_OUT (dir),
+ * ND_KEYS ("RIGHT:0:120,LEFT:200:260,OK:5:6") key holds by frame range. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "../src/platform.h"
+#include "../src/render.h"
+#ifndef ARMTEST
+#include <sys/mman.h>
+#include <unistd.h>
+#include <signal.h>
+#include <sys/prctl.h>
+#include <math.h>
+#include <semaphore.h>
+#endif
+
+static uint16_t fb[SCREEN_W * SCREEN_H];
+static int frame;
+static int max_frames = 600;
+static char shots[4096];
+static char keys[4096];
+static const char *outdir = "out";
+static int inited;
+
+#ifndef ARMTEST
+/* ND_SEARCH="seg,beam,frames": beam search over held keys (none / right / left per segment) for a win.
+ Workers are forked processes paused at segment ends; the first process coordinates. */
+#define SW 512
+#define SPATH 256
+typedef struct {
+ volatile int cmd[SW], arg[SW][3], done[SW], status[SW];
+ volatile float score[SW], cy[SW];
+ volatile unsigned char path[SW][SPATH];
+ volatile int plen[SW];
+ sem_t go[SW], done_sem; /* a worker sleeps on go[id]; the coordinator on done_sem */
+} Search;
+static Search *sr;
+static int s_seg, s_beam, s_frames, s_id = -1, s_act, s_outcome;
+static void s_checkpoint(void);
+#endif
+void host_outcome(int won) {
+#ifndef ARMTEST
+ if (!s_outcome) s_outcome = won;
+#else
+ (void)won;
+#endif
+}
+
+static void init(void) {
+ if (inited) return;
+ inited = 1;
+ const char *s;
+ if ((s = getenv("ND_FRAMES"))) max_frames = atoi(s);
+ if ((s = getenv("ND_SHOTS"))) snprintf(shots, sizeof shots, ",%s,", s);
+ if ((s = getenv("ND_KEYS"))) snprintf(keys, sizeof keys, "%s", s);
+ if ((s = getenv("ND_OUT"))) outdir = s;
+#ifndef ARMTEST
+ if ((s = getenv("ND_SEARCH"))) {
+ s_seg = 20, s_beam = 8, s_frames = 1800;
+ sscanf(s, "%d,%d,%d", &s_seg, &s_beam, &s_frames);
+ max_frames = 1 << 30;
+ sr = mmap(0, sizeof(Search), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
+ memset((void *)sr, 0, sizeof(Search));
+ for (int i = 0; i < SW; i++) sem_init(&sr->go[i], 1, 0);
+ sem_init(&sr->done_sem, 1, 0);
+ }
+#endif
+}
+
+int host_frame(void) { return frame; }
+
+void plat_push(int x, int y, int w, int h, const uint16_t *px) {
+ for (int j = 0; j < h; j++)
+ for (int i = 0; i < w; i++)
+ if (x + i >= 0 && x + i < SCREEN_W && y + j >= 0 && y + j < SCREEN_H) fb[(y + j) * SCREEN_W + x + i] = px[j * w + i];
+}
+
+void plat_fill(int x, int y, int w, int h, uint16_t c) {
+ for (int j = 0; j < h; j++)
+ for (int i = 0; i < w; i++)
+ if (x + i >= 0 && x + i < SCREEN_W && y + j >= 0 && y + j < SCREEN_H) fb[(y + j) * SCREEN_W + x + i] = c;
+}
+
+void plat_pull(int x, int y, int w, int h, uint16_t *px) {
+ for (int j = 0; j < h; j++)
+ for (int i = 0; i < w; i++) px[j * w + i] = fb[(y + j) * SCREEN_W + x + i];
+}
+
+static int keycode(const char *n) {
+ if (!strncmp(n, "RIGHT", 5)) return K_RIGHT;
+ if (!strncmp(n, "LEFT", 4)) return K_LEFT;
+ if (!strncmp(n, "UP", 2)) return K_UP;
+ if (!strncmp(n, "DOWN", 4)) return K_DOWN;
+ if (!strncmp(n, "OK", 2)) return K_OK;
+ if (!strncmp(n, "BACK", 4)) return K_BACK;
+ if (!strncmp(n, "EXE", 3)) return K_EXE;
+ return -1;
+}
+
+uint64_t plat_keys(void) {
+ init();
+#ifndef ARMTEST
+ if (sr) {
+ if (s_id < 0) s_checkpoint(); /* frame 0: become the coordinator and the first worker */
+ return s_act == 1 ? KEY(K_RIGHT) : s_act == 2 ? KEY(K_LEFT) : 0;
+ }
+#endif
+ uint64_t k = 0;
+ char buf[4096];
+ snprintf(buf, sizeof buf, "%s", keys);
+ for (char *tok = strtok(buf, ","); tok; tok = strtok(NULL, ",")) {
+ int a = 0, b = 0;
+ char name[16] = {0};
+ if (sscanf(tok, "%15[A-Z]:%d:%d", name, &a, &b) == 3 && frame >= a && frame < b) {
+ int c = keycode(name);
+ if (c >= 0) k |= KEY(c);
+ }
+ }
+ return k;
+}
+
+uint32_t plat_millis(void) { return (uint32_t)(frame * 1000 / 60); }
+void plat_vblank(void) {}
+void plat_sleep(int ms) { (void)ms; }
+uint32_t plat_random(void) {
+ static uint32_t s = 12345;
+ s = s * 1103515245u + 12345u;
+ return s >> 1;
+}
+
+static void save(void) {
+ char path[512];
+ snprintf(path, sizeof path, "%s/f%05d.ppm", outdir, frame);
+ FILE *f = fopen(path, "wb");
+ if (!f) return;
+ fprintf(f, "P6\n%d %d\n255\n", SCREEN_W, SCREEN_H);
+ for (int i = 0; i < SCREEN_W * SCREEN_H; i++) {
+ uint16_t c = fb[i];
+ unsigned char rgb[3] = {(unsigned char)(((c >> 11) & 31) * 255 / 31), (unsigned char)(((c >> 5) & 63) * 255 / 63),
+ (unsigned char)((c & 31) * 255 / 31)};
+ fwrite(rgb, 1, 3, f);
+ }
+ fclose(f);
+}
+
+void plat_frame_done(void) {
+ init();
+ char tag[32];
+ snprintf(tag, sizeof tag, ",%d,", frame);
+ if (strstr(shots, ",all,") || strstr(shots, tag)) save();
+ frame++;
+#ifndef ARMTEST
+ if (sr && (frame % s_seg == 0 || s_outcome)) s_checkpoint();
+#endif
+ if (frame >= max_frames) exit(0);
+}
+#ifndef ARMTEST
+
+static void s_wait_cmd(void) {
+ for (;;) {
+ while (sem_wait(&sr->go[s_id]) != 0) {
+ }
+ int c = sr->cmd[s_id];
+ sr->cmd[s_id] = 0;
+ if (c == 2) _exit(0);
+ /* expand: a child per action; this process is done */
+ for (int a = 0; a < 3; a++) {
+ int id = sr->arg[s_id][a];
+ if (fork() == 0) {
+ memcpy((void *)sr->path[id], (void *)sr->path[s_id], SPATH);
+ sr->plen[id] = sr->plen[s_id];
+ if (sr->plen[id] < SPATH) sr->path[id][sr->plen[id]++] = (unsigned char)a;
+ s_id = id;
+ s_act = a;
+ return;
+ }
+ }
+ _exit(0);
+ }
+}
+
+static void s_report(void) {
+ static float s_dir;
+ if (!s_dir) s_dir = getenv("ND_SDIR") ? atof(getenv("ND_SDIR")) : 1;
+ sr->score[s_id] = s_outcome == 1 ? 1e6f - frame : s_outcome == 2 ? -1e6f : cam.focus.x * s_dir;
+ sr->cy[s_id] = cam.focus.y;
+ sr->status[s_id] = s_outcome;
+ __sync_synchronize();
+ sr->done[s_id] = 1;
+ sem_post(&sr->done_sem);
+}
+
+static void s_coordinate(void) {
+ int beam[64], nb = 1, next = 1;
+ if (s_beam > 64) s_beam = 64;
+ beam[0] = 0;
+ while (sem_wait(&sr->done_sem) != 0) {
+ }
+ for (int gen = 0; gen * s_seg < s_frames; gen++) {
+ int kids[192], nk = 0;
+ for (int i = 0; i < nb; i++) {
+ for (int a = 0; a < 3; a++) {
+ int id = next++ % SW;
+ if (id == 0) id = next++ % SW;
+ sr->done[id] = 0;
+ sr->arg[beam[i]][a] = id;
+ kids[nk++] = id;
+ }
+ __sync_synchronize();
+ sr->cmd[beam[i]] = 1;
+ sem_post(&sr->go[beam[i]]);
+ }
+ for (int i = 0; i < nk; i++)
+ while (sem_wait(&sr->done_sem) != 0) {
+ }
+ /* best first; a win ends the search */
+ for (int i = 0; i < nk; i++)
+ for (int j = i + 1; j < nk; j++)
+ if (sr->score[kids[j]] > sr->score[kids[i]]) {
+ int t = kids[i];
+ kids[i] = kids[j];
+ kids[j] = t;
+ }
+ int best = kids[0];
+ if (sr->status[best] == 1 || (gen + 1) * s_seg >= s_frames || sr->status[best] == 2) {
+ printf("search %s gen %d score %.2f path ", sr->status[best] == 1 ? "win" : "none", gen, sr->score[best]);
+ for (int i = 0; i < sr->plen[best]; i++) putchar(".RL"[sr->path[best][i]]);
+ putchar('\n');
+ fflush(stdout);
+ for (int i = 0; i < nk; i++) sr->cmd[kids[i]] = 2, sem_post(&sr->go[kids[i]]);
+ usleep(100000); /* let the workers go before their reaper does */
+ exit(0);
+ }
+ /* keep the best, but at most two per spot so the beam spreads over where the car can get */
+ nb = 0;
+ for (int i = 0; i < nk; i++) {
+ int k = kids[i], same = 0;
+ for (int j = 0; j < nb; j++)
+ same += (int)floorf(sr->score[beam[j]]) == (int)floorf(sr->score[k]) && (int)floorf(sr->cy[beam[j]]) == (int)floorf(sr->cy[k]);
+ if (nb < s_beam && sr->status[k] == 0 && same < 2) beam[nb++] = k;
+ else sr->cmd[k] = 2, sem_post(&sr->go[k]);
+ }
+ }
+ exit(0);
+}
+
+static void s_checkpoint(void) {
+ if (s_id < 0) {
+ /* orphaned workers are adopted and reaped here */
+ signal(SIGCHLD, SIG_IGN);
+ prctl(PR_SET_CHILD_SUBREAPER, 1);
+ s_id = 0;
+ if (fork() != 0) s_coordinate();
+ s_act = 0;
+ }
+ s_report();
+ s_wait_cmd();
+ sr->done[s_id] = 0;
+}
+#endif
diff --git a/games/numdrive/host/run.sh b/games/numdrive/host/run.sh
new file mode 100755
index 00000000..31e217c1
--- /dev/null
+++ b/games/numdrive/host/run.sh
@@ -0,0 +1,9 @@
+#!/bin/sh
+# usage: run.sh <outdir> <level> <frames> <shots> <keys>
+OUT=/home/user/NumDrive/host/$1
+mkdir -p "$OUT"
+find "$OUT" -maxdepth 1 -name '*.p?m' -delete
+find "$OUT" -maxdepth 1 -name 'f*.png' -delete
+ND_LEVEL=$2 ND_FRAMES=$3 ND_SHOTS=$4 ND_KEYS=$5 ND_OUT="$OUT" /home/user/NumDrive/host/nd
+for f in "$OUT"/f*.ppm; do convert "$f" "${f%.ppm}.png"; done
+montage "$OUT"/f*.png -tile 4x -geometry 320x240+2+2 "$OUT/montage.png"
diff --git a/games/numdrive/host/test_inflate.c b/games/numdrive/host/test_inflate.c
new file mode 100644
index 00000000..55ad50ca
--- /dev/null
+++ b/games/numdrive/host/test_inflate.c
@@ -0,0 +1,17 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include "../src/inflate.h"
+extern const uint8_t pack_data[]; extern const uint32_t pack_size;
+int main(void){
+ uint16_t n = pack_data[4] | pack_data[5]<<8;
+ const uint8_t *offs = pack_data+6, *raws = offs + 4*(n+1);
+ uint8_t *buf = malloc(1<<20); int bad=0;
+ for (int i=0;i<n;i++){
+ uint32_t o0=*(uint32_t*)(offs+4*i), o1=*(uint32_t*)(offs+4*i+4), rs=*(uint32_t*)(raws+4*i);
+ int r = inflate_raw(pack_data+o0, o1-o0, buf, rs);
+ if (r != (int)rs) { printf("record %d: got %d expected %u\n", i, r, rs); bad++; }
+ }
+ printf("%d records, %d bad\n", n, bad);
+ return bad;
+}
diff --git a/games/numdrive/src/fmath.h b/games/numdrive/src/fmath.h
new file mode 100644
index 00000000..5d958542
--- /dev/null
+++ b/games/numdrive/src/fmath.h
@@ -0,0 +1,69 @@
+#ifndef FMATH_H
+#define FMATH_H
+
+#include <math.h>
+#include <stdint.h>
+
+#define PI_F 3.14159265f
+#define DEG2RAD (PI_F / 180.0f)
+#define RAD2DEG (180.0f / PI_F)
+
+typedef struct { float x, y, z; } vec3;
+typedef struct { float x, y, z, w; } quat;
+
+static inline vec3 v3(float x, float y, float z) { vec3 r = {x, y, z}; return r; }
+static inline vec3 vadd(vec3 a, vec3 b) { return v3(a.x + b.x, a.y + b.y, a.z + b.z); }
+static inline vec3 vsub(vec3 a, vec3 b) { return v3(a.x - b.x, a.y - b.y, a.z - b.z); }
+static inline vec3 vscale(vec3 a, float s) { return v3(a.x * s, a.y * s, a.z * s); }
+static inline float vdot(vec3 a, vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
+static inline vec3 vcross(vec3 a, vec3 b) {
+ return v3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
+}
+static inline float vlen(vec3 a) { return sqrtf(vdot(a, a)); }
+static inline vec3 vnorm(vec3 a) {
+ float l = vlen(a);
+ return l > 1e-12f ? vscale(a, 1.0f / l) : v3(0, 0, 0);
+}
+static inline float clampf(float v, float lo, float hi) { return v < lo ? lo : (v > hi ? hi : v); }
+
+static inline quat qident(void) { quat q = {0, 0, 0, 1}; return q; }
+static inline quat qmul(quat a, quat b) {
+ quat r;
+ r.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;
+ r.x = a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y;
+ r.y = a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x;
+ r.z = a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w;
+ return r;
+}
+static inline quat qconj(quat a) { quat r = {-a.x, -a.y, -a.z, a.w}; return r; }
+static inline quat qnorm(quat a) {
+ float l = sqrtf(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w);
+ if (l < 1e-12f) return qident();
+ l = 1.0f / l;
+ quat r = {a.x * l, a.y * l, a.z * l, a.w * l};
+ return r;
+}
+static inline vec3 qrot(quat q, vec3 v) {
+ vec3 u = v3(q.x, q.y, q.z);
+ vec3 t = vscale(vcross(u, v), 2.0f);
+ return vadd(vadd(v, vscale(t, q.w)), vcross(u, t));
+}
+static inline quat qaxis(vec3 axis, float rad) {
+ float s = sinf(rad * 0.5f), c = cosf(rad * 0.5f);
+ quat r = {axis.x * s, axis.y * s, axis.z * s, c};
+ return r;
+}
+/* System.Numerics CreateFromYawPitchRoll (yaw about Y, pitch about X, roll about Z), degrees */
+static inline quat qeuler(float xdeg, float ydeg, float zdeg) {
+ float hr = zdeg * 0.5f * DEG2RAD, hp = xdeg * 0.5f * DEG2RAD, hy = ydeg * 0.5f * DEG2RAD;
+ float sr = sinf(hr), cr = cosf(hr), sp = sinf(hp), cp = cosf(hp), sy = sinf(hy), cy = cosf(hy);
+ quat q;
+ q.x = cy * sp * cr + sy * cp * sr;
+ q.y = sy * cp * cr - cy * sp * sr;
+ q.z = cy * cp * sr - sy * sp * cr;
+ q.w = cy * cp * cr + sy * sp * sr;
+ return q;
+}
+static inline quat qrotz(float rad) { return qaxis(v3(0, 0, 1), rad); }
+
+#endif
diff --git a/games/numdrive/src/font.c b/games/numdrive/src/font.c
new file mode 100644
index 00000000..0839bff2
--- /dev/null
+++ b/games/numdrive/src/font.c
@@ -0,0 +1,257 @@
+/* generated by tools/font.py from Baloo 2 ExtraBold (SIL Open Font License) */
+#include "font.h"
+
+static const uint8_t font_s_data[] = {93,219,117,88,215,1,218,184,167,13,144,24,244,45,253,127,180,30,254,127,189,27,40,7,160,64,47,189,215,2,248,2,185,153,219,47,224,0,40,20,168,178,160,234,0,218,5,192,250,128,115,71,135,15,224,2,110,64,75,225,231,173,127,219,139,191,3,234,14,16,120,60,45,29,29,45,45,120,16,79,203,242,60,219,122,5,40,126,61,160,0,14,253,155,111,224,0,5,157,247,4,85,126,158,7,144,240,180,116,56,44,45,30,14,4,228,2,239,211,226,117,120,29,30,223,67,127,0,104,190,181,180,180,180,180,184,193,126,128,7,61,184,208,91,253,7,185,145,62,208,131,47,208,83,125,253,2,128,2,126,184,215,118,238,159,190,64,7,168,210,42,93,208,63,148,151,121,253,2,224,198,107,109,209,191,29,223,182,244,7,169,146,126,208,2,30,244,128,11,56,0,232,226,186,94,203,63,94,235,186,253,7,184,225,122,94,235,191,164,75,121,253,1,132,231,1,158,7,68,219,1,88,235,21,128,226,235,134,31,228,3,5,254,87,21,169,162,42,25,248,6,62,253,126,20,0,185,165,15,61,190,100,144,128,3,0,20,0,144,255,7,244,86,47,124,105,60,109,239,121,157,215,121,157,235,62,45,174,31,184,0,0,224,63,0,0,21,0,160,2,253,129,123,240,44,189,143,235,231,209,2,232,70,239,211,230,244,47,109,94,155,199,191,0,224,138,235,45,208,1,45,192,155,228,15,248,70,239,215,210,182,240,45,108,155,199,191,0,168,214,107,109,209,127,109,209,87,252,11,168,214,107,45,208,43,189,210,2,45,0,160,27,174,218,2,116,189,45,61,111,79,254,2,25,88,11,219,210,246,191,125,110,11,219,194,2,89,219,182,109,219,2,160,240,240,240,240,245,126,25,73,219,215,190,244,11,253,71,219,211,226,1,25,208,2,45,208,2,45,208,22,252,7,104,100,188,188,253,253,237,238,173,235,109,230,45,224,40,88,31,219,223,182,187,173,111,203,219,226,2,224,10,188,46,45,120,29,120,45,120,124,61,244,27,248,210,251,45,222,250,253,214,2,45,0,224,10,188,46,45,120,29,120,45,120,124,61,244,31,0,190,0,100,248,70,239,211,226,244,46,253,71,219,210,226,1,228,210,107,109,128,127,144,155,185,253,2,170,170,175,240,0,15,240,0,15,240,0,25,89,75,219,210,182,180,45,45,159,71,191,0,9,152,71,219,226,241,60,184,11,253,1,62,0,9,64,226,17,120,109,207,211,246,61,188,239,130,175,47,244,245,1,9,233,246,248,71,47,248,211,182,30,14,10,234,241,189,139,63,240,1,14,224,0,169,150,126,208,67,31,124,224,86,254,11,20,125,30,30,30,30,30,30,125,20,14,30,29,44,56,116,176,96,132,143,227,56,142,227,126,6,80,224,195,110,231,68,1,85,245,127,78,11,84,208,63,148,215,127,174,215,127,4,224,1,110,224,127,110,239,241,173,139,111,80,240,235,130,7,110,225,11,0,1,176,80,203,191,94,235,177,110,139,127,80,208,63,158,231,107,110,130,63,80,244,215,130,127,110,120,224,65,7,80,208,127,94,235,181,253,75,186,153,139,47,4,224,1,110,225,127,110,235,181,30,219,177,89,71,116,109,219,182,93,71,116,109,219,182,222,3,4,224,1,30,225,121,254,226,31,238,215,181,68,219,182,109,219,182,80,20,244,255,231,186,173,215,182,94,219,118,109,11,80,208,127,110,235,181,30,219,177,80,192,127,94,239,241,110,139,47,80,208,127,110,239,241,174,235,127,30,208,1,80,193,191,94,235,177,110,139,191,64,11,176,80,244,231,130,7,30,116,0,80,244,219,22,190,217,247,11,25,110,254,46,30,109,188,4,225,177,30,235,181,109,139,127,5,229,181,109,199,58,248,66,31,4,64,120,93,215,185,93,187,59,252,253,224,226,2,0,225,117,252,130,31,253,226,120,5,225,177,93,203,122,248,3,31,184,128,3,84,248,75,31,46,125,249,15,16,120,44,44,46,46,44,44,124,20,68,215,182,109,219,182,109,7,4,46,44,44,124,120,44,44,46,5,105,231,127,68,1};
+static const Glyph font_s_glyphs[] = {
+ {32, 2, -1, 0, 0, 0, 0},
+ {33, 3, 0, 5, 3, 7, 0},
+ {34, 5, 0, 5, 5, 3, 6},
+ {35, 8, 0, 5, 8, 7, 10},
+ {36, 6, 0, 4, 6, 9, 24},
+ {37, 9, 0, 5, 9, 7, 38},
+ {38, 7, 0, 5, 7, 7, 54},
+ {39, 2, 0, 5, 2, 3, 67},
+ {40, 3, 0, 4, 4, 10, 69},
+ {41, 3, 0, 5, 3, 9, 79},
+ {42, 4, 0, 5, 4, 3, 86},
+ {43, 6, 0, 6, 6, 6, 89},
+ {44, 3, 0, 10, 3, 4, 98},
+ {45, 4, 0, 8, 4, 2, 101},
+ {46, 3, 0, 10, 3, 2, 103},
+ {47, 4, 0, 4, 4, 10, 105},
+ {48, 7, 0, 5, 7, 7, 115},
+ {49, 4, 0, 5, 4, 7, 128},
+ {50, 6, 0, 5, 6, 7, 135},
+ {51, 6, 0, 5, 6, 7, 146},
+ {52, 7, 0, 5, 6, 7, 157},
+ {53, 6, 0, 5, 6, 7, 168},
+ {54, 6, 0, 5, 6, 7, 179},
+ {55, 5, 0, 5, 6, 7, 190},
+ {56, 6, 0, 5, 6, 7, 201},
+ {57, 6, 0, 5, 6, 7, 212},
+ {58, 3, 0, 6, 3, 6, 223},
+ {59, 3, 0, 6, 3, 8, 228},
+ {60, 5, 0, 6, 5, 6, 234},
+ {61, 6, 0, 7, 6, 4, 242},
+ {62, 5, 0, 6, 5, 6, 248},
+ {63, 5, 0, 5, 5, 7, 256},
+ {64, 12, 0, 4, 12, 11, 265},
+ {65, 7, 0, 5, 7, 7, 298},
+ {66, 7, 0, 5, 7, 7, 311},
+ {67, 6, 0, 5, 6, 7, 324},
+ {68, 7, 0, 5, 7, 7, 335},
+ {69, 6, 0, 5, 6, 7, 348},
+ {70, 6, 0, 5, 6, 7, 359},
+ {71, 7, 0, 5, 7, 7, 370},
+ {72, 7, 0, 5, 7, 7, 383},
+ {73, 3, 0, 5, 3, 7, 396},
+ {74, 5, 0, 5, 4, 7, 402},
+ {75, 7, 0, 5, 7, 7, 409},
+ {76, 6, 0, 5, 6, 7, 422},
+ {77, 9, 0, 5, 8, 7, 433},
+ {78, 7, 0, 5, 7, 7, 447},
+ {79, 8, 0, 5, 8, 7, 460},
+ {80, 6, 0, 5, 6, 7, 474},
+ {81, 8, 0, 5, 8, 9, 485},
+ {82, 7, 0, 5, 7, 7, 503},
+ {83, 6, 0, 5, 6, 7, 516},
+ {84, 6, 0, 5, 6, 7, 527},
+ {85, 7, 0, 5, 7, 7, 538},
+ {86, 7, 0, 5, 7, 7, 551},
+ {87, 9, 0, 5, 10, 7, 564},
+ {88, 7, 0, 5, 6, 7, 582},
+ {89, 6, 0, 5, 6, 7, 593},
+ {90, 6, 0, 5, 6, 7, 604},
+ {91, 3, 0, 4, 4, 10, 615},
+ {92, 4, 0, 5, 4, 8, 625},
+ {93, 3, 0, 4, 3, 10, 633},
+ {94, 5, 0, 4, 5, 5, 641},
+ {95, 6, 0, 12, 6, 2, 648},
+ {96, 3, 0, 4, 3, 2, 651},
+ {97, 6, 0, 6, 6, 6, 653},
+ {98, 6, 0, 4, 6, 8, 662},
+ {99, 5, 0, 6, 5, 6, 674},
+ {100, 6, 0, 4, 6, 8, 682},
+ {101, 6, 0, 6, 6, 6, 694},
+ {102, 5, 0, 4, 5, 8, 703},
+ {103, 6, 0, 6, 6, 8, 713},
+ {104, 6, 0, 4, 6, 8, 725},
+ {105, 3, 0, 4, 3, 8, 737},
+ {106, 3, 0, 4, 3, 10, 743},
+ {107, 6, 0, 4, 6, 8, 751},
+ {108, 3, 0, 4, 3, 8, 763},
+ {109, 9, 0, 6, 9, 6, 769},
+ {110, 6, 0, 6, 6, 6, 783},
+ {111, 6, 0, 6, 6, 6, 792},
+ {112, 6, 0, 6, 6, 8, 801},
+ {113, 6, 0, 6, 6, 8, 813},
+ {114, 5, 0, 6, 5, 6, 825},
+ {115, 5, 0, 6, 5, 6, 833},
+ {116, 4, 0, 5, 4, 7, 841},
+ {117, 6, 0, 6, 6, 6, 848},
+ {118, 6, 0, 6, 6, 6, 857},
+ {119, 9, 0, 6, 9, 6, 866},
+ {120, 6, 0, 6, 6, 6, 880},
+ {121, 6, 0, 6, 6, 8, 889},
+ {122, 5, 0, 6, 5, 6, 901},
+ {123, 4, 0, 4, 4, 10, 909},
+ {124, 3, 0, 4, 3, 10, 919},
+ {125, 4, 0, 4, 4, 10, 927},
+ {126, 6, 0, 8, 6, 3, 937},
+};
+const Font font_s = {19, 12, 5, 95, font_s_glyphs, font_s_data};
+
+static const uint8_t font_m_data[] = {20,125,125,125,124,60,20,124,125,20,89,226,121,158,211,57,64,65,0,56,30,228,251,198,255,191,228,246,65,174,31,253,255,135,239,27,180,60,0,69,1,128,1,244,129,255,246,170,125,0,255,2,254,2,244,173,126,255,7,62,0,5,84,64,65,191,240,208,57,30,180,223,2,248,61,1,128,247,7,180,222,3,139,247,208,209,31,0,64,0,64,5,128,63,64,95,0,124,16,244,231,245,190,215,226,95,95,127,248,255,67,21,5,153,235,118,240,184,124,61,45,45,45,61,60,184,244,30,61,124,184,184,184,184,184,124,61,46,4,32,228,230,95,63,68,0,208,3,208,3,233,43,254,127,212,23,208,3,128,2,84,239,126,10,253,165,6,132,235,83,128,65,15,46,120,240,209,131,11,31,61,184,224,66,6,64,1,244,47,188,126,61,184,61,244,61,244,61,248,188,189,244,47,64,5,64,228,235,111,185,224,130,11,46,184,224,66,5,80,1,255,135,245,2,184,128,31,248,130,31,244,106,253,47,85,1,80,65,255,146,250,1,124,244,11,253,7,224,106,189,254,15,85,0,0,21,0,254,0,253,3,188,15,184,61,244,249,209,255,31,169,31,0,61,0,80,0,84,225,127,175,246,5,255,167,190,64,191,253,255,71,5,64,5,240,47,252,42,125,5,253,47,189,126,61,124,188,126,244,47,80,5,254,95,234,7,244,0,47,208,7,188,64,31,224,3,80,0,80,5,248,47,189,126,124,124,248,47,188,63,61,124,189,126,248,47,80,5,64,1,248,31,189,62,61,124,189,126,248,127,80,125,88,62,252,31,80,1,40,125,45,0,4,61,125,20,40,125,45,0,20,125,61,46,10,64,30,249,215,111,244,1,253,6,244,7,144,1,84,69,255,155,170,81,85,253,111,170,5,109,64,191,1,254,1,125,248,79,127,128,1,0,84,129,255,146,245,1,125,244,15,190,0,1,208,3,244,1,20,0,0,249,111,0,224,255,191,0,127,0,190,224,131,42,61,124,252,47,95,143,79,139,215,227,226,242,245,248,190,62,124,252,255,7,126,20,84,0,190,21,0,0,254,15,0,0,84,1,0,64,5,128,127,0,255,2,189,15,184,124,240,246,209,255,139,175,62,46,240,81,64,1,84,1,255,31,175,63,31,61,191,31,255,47,111,125,111,62,255,47,84,1,0,5,224,127,248,106,125,0,61,0,61,0,125,0,252,101,244,191,64,21,84,1,255,31,175,126,31,188,31,248,31,248,31,184,111,126,255,31,84,1,84,197,255,243,170,188,0,255,203,255,242,2,188,42,255,31,85,1,4,128,255,247,171,124,0,175,198,255,242,22,124,0,31,64,1,0,0,21,128,255,131,175,94,31,0,61,253,245,244,219,7,46,127,189,224,255,1,85,0,5,20,31,124,31,188,47,188,255,191,255,191,31,188,31,188,31,188,5,20,197,247,189,239,251,125,31,1,64,129,15,62,248,224,131,15,126,253,254,81,1,5,4,31,61,95,63,239,31,255,7,255,3,239,11,95,47,31,126,21,20,5,240,1,31,240,2,47,240,2,31,240,106,255,75,21,84,64,5,127,244,195,47,254,240,207,63,188,187,95,223,223,215,227,243,245,80,124,61,0,31,5,0,1,21,84,127,184,191,184,255,185,239,186,159,187,95,191,31,190,31,189,4,16,0,5,0,254,11,248,250,210,7,62,61,208,215,3,125,125,208,195,95,47,244,191,0,84,1,84,193,255,247,246,126,248,111,239,255,247,22,124,0,31,0,1,0,64,5,0,254,11,248,250,210,7,62,61,208,215,3,125,125,208,195,95,47,244,191,0,212,111,0,224,11,0,20,84,193,255,242,250,126,248,111,239,255,243,250,124,189,31,126,1,5,64,5,254,219,171,246,1,253,11,249,11,224,183,249,253,31,84,0,64,1,254,191,233,107,208,7,208,7,208,7,208,7,208,7,208,7,64,1,20,80,244,208,215,71,95,31,125,125,244,245,209,215,71,31,111,62,244,127,0,21,0,46,240,249,208,215,135,15,47,62,248,124,192,251,0,254,2,244,7,64,5,0,20,0,16,61,0,184,125,20,184,125,189,188,188,253,124,184,254,125,184,239,62,244,219,47,240,199,31,64,1,1,20,80,125,248,252,189,244,63,224,15,240,31,248,63,189,188,61,244,4,16,4,16,46,184,125,188,184,61,244,47,224,15,192,7,192,7,192,7,0,1,84,21,253,63,169,63,64,47,208,11,240,3,248,0,189,106,253,127,84,21,252,245,210,67,15,61,244,208,67,15,61,244,194,31,30,184,208,3,31,120,208,66,15,124,224,66,11,190,190,184,184,184,184,184,184,184,189,190,224,2,253,193,187,180,60,29,30,255,127,170,42,4,30,125,100,164,6,255,75,225,227,255,189,126,159,207,255,66,21,61,0,125,0,189,10,253,63,125,189,125,184,125,184,189,126,248,47,80,5,144,10,254,215,75,244,0,61,64,111,134,255,1,21,0,124,0,188,144,190,248,191,125,188,61,188,61,188,189,125,248,127,80,5,144,6,248,47,125,61,253,127,189,5,188,37,244,63,64,5,64,65,191,188,218,3,253,215,107,125,208,7,125,208,7,16,0,144,26,248,63,125,124,61,124,61,124,252,127,228,127,4,125,252,63,248,11,61,0,125,0,189,26,253,127,125,125,125,188,125,188,125,188,125,188,20,20,40,125,40,40,125,125,125,125,125,124,16,40,125,40,40,125,125,125,125,125,125,125,62,30,61,0,125,0,125,24,125,62,189,31,253,7,253,15,125,63,125,125,16,0,61,125,125,125,125,125,125,125,125,20,144,150,6,252,255,47,125,126,62,125,125,125,125,125,125,125,125,125,125,125,125,20,20,20,144,6,252,63,125,125,125,188,125,188,125,188,125,188,20,84,144,10,248,63,125,189,61,184,61,184,189,125,248,47,80,5,144,6,252,63,125,189,125,184,125,184,125,125,253,47,189,6,125,0,124,0,144,22,248,127,189,189,61,188,61,188,189,189,248,191,144,190,0,188,0,120,160,198,191,125,208,7,125,208,7,125,0,1,164,70,255,211,87,244,27,160,95,214,215,255,80,5,4,244,208,87,255,189,245,209,71,111,252,67,5,40,40,125,124,125,188,125,188,125,188,188,189,248,127,80,5,25,40,46,125,61,61,124,46,184,31,244,15,240,11,64,1,25,0,153,139,143,219,243,231,242,253,121,188,187,15,254,252,67,47,190,64,5,5,24,88,159,143,255,193,47,244,75,239,219,210,19,16,25,36,61,124,125,124,188,61,248,46,240,31,224,15,208,7,244,2,180,0,164,70,255,71,253,128,31,244,65,191,214,255,81,21,244,248,184,184,125,62,125,184,184,184,244,241,255,255,255,255,255,10,45,244,129,11,46,184,208,135,31,46,184,244,209,7,1,105,153,255,219,250,1};
+static const Glyph font_m_glyphs[] = {
+ {32, 3, -1, 0, 0, 0, 0},
+ {33, 4, 0, 6, 4, 10, 0},
+ {34, 6, 0, 6, 6, 4, 10},
+ {35, 10, 0, 6, 10, 10, 16},
+ {36, 8, 0, 5, 7, 12, 41},
+ {37, 11, 0, 6, 11, 10, 62},
+ {38, 9, 0, 6, 9, 10, 90},
+ {39, 3, 0, 6, 3, 4, 113},
+ {40, 4, 0, 6, 4, 11, 116},
+ {41, 4, 0, 6, 4, 12, 127},
+ {42, 5, 0, 6, 5, 5, 139},
+ {43, 8, 0, 8, 8, 7, 146},
+ {44, 3, 0, 12, 3, 5, 160},
+ {45, 5, 0, 11, 5, 2, 164},
+ {46, 3, 0, 12, 3, 4, 167},
+ {47, 5, 0, 5, 5, 12, 170},
+ {48, 8, 0, 6, 8, 10, 185},
+ {49, 6, 0, 6, 5, 10, 205},
+ {50, 7, 0, 6, 7, 10, 218},
+ {51, 7, 0, 6, 7, 10, 236},
+ {52, 8, 0, 6, 9, 10, 254},
+ {53, 7, 1, 6, 6, 10, 277},
+ {54, 8, 0, 6, 8, 10, 292},
+ {55, 7, 0, 7, 7, 9, 312},
+ {56, 8, 0, 6, 8, 10, 328},
+ {57, 8, 0, 6, 8, 10, 348},
+ {58, 4, 0, 8, 4, 8, 368},
+ {59, 4, 0, 8, 4, 9, 376},
+ {60, 7, 0, 8, 7, 7, 385},
+ {61, 7, 0, 8, 7, 6, 398},
+ {62, 7, 0, 8, 7, 7, 409},
+ {63, 7, 0, 6, 7, 10, 422},
+ {64, 15, 0, 6, 15, 13, 440},
+ {65, 9, 0, 6, 9, 10, 489},
+ {66, 9, 1, 6, 8, 10, 512},
+ {67, 8, 0, 6, 8, 10, 532},
+ {68, 9, 1, 6, 8, 10, 552},
+ {69, 8, 1, 6, 7, 10, 572},
+ {70, 7, 1, 6, 7, 10, 590},
+ {71, 9, 0, 6, 9, 10, 608},
+ {72, 9, 1, 6, 8, 10, 631},
+ {73, 4, 1, 6, 3, 10, 651},
+ {74, 6, 0, 6, 5, 10, 659},
+ {75, 9, 1, 6, 8, 10, 672},
+ {76, 7, 1, 6, 6, 10, 692},
+ {77, 11, 0, 6, 11, 10, 707},
+ {78, 10, 1, 6, 8, 10, 735},
+ {79, 10, 0, 6, 10, 10, 755},
+ {80, 8, 1, 6, 7, 10, 780},
+ {81, 10, 0, 6, 10, 12, 798},
+ {82, 9, 1, 6, 7, 10, 828},
+ {83, 8, 0, 6, 7, 10, 846},
+ {84, 8, 0, 6, 8, 10, 864},
+ {85, 9, 0, 6, 9, 10, 884},
+ {86, 9, 0, 7, 9, 9, 907},
+ {87, 12, 0, 6, 12, 10, 928},
+ {88, 8, 0, 6, 8, 10, 958},
+ {89, 8, 0, 6, 8, 10, 978},
+ {90, 8, 0, 6, 8, 10, 998},
+ {91, 4, 0, 6, 5, 11, 1018},
+ {92, 5, 0, 6, 5, 10, 1032},
+ {93, 4, 0, 6, 4, 11, 1045},
+ {94, 7, 0, 6, 7, 5, 1056},
+ {95, 7, 0, 16, 8, 2, 1065},
+ {96, 4, 0, 4, 4, 4, 1069},
+ {97, 8, 0, 8, 7, 8, 1073},
+ {98, 8, 0, 6, 8, 10, 1087},
+ {99, 7, 0, 8, 7, 8, 1107},
+ {100, 8, 0, 6, 8, 10, 1121},
+ {101, 8, 0, 8, 8, 8, 1141},
+ {102, 6, 0, 5, 6, 11, 1157},
+ {103, 8, 0, 8, 8, 10, 1174},
+ {104, 8, 0, 6, 8, 10, 1194},
+ {105, 4, 0, 5, 4, 11, 1214},
+ {106, 4, 0, 5, 4, 13, 1225},
+ {107, 8, 0, 6, 8, 10, 1238},
+ {108, 4, 0, 6, 4, 10, 1258},
+ {109, 12, 0, 8, 12, 8, 1268},
+ {110, 8, 0, 8, 8, 8, 1292},
+ {111, 8, 0, 8, 8, 8, 1308},
+ {112, 8, 0, 8, 8, 10, 1324},
+ {113, 8, 0, 8, 8, 10, 1344},
+ {114, 6, 0, 8, 6, 8, 1364},
+ {115, 7, 0, 8, 7, 8, 1376},
+ {116, 6, 0, 6, 5, 10, 1390},
+ {117, 8, 0, 8, 8, 8, 1403},
+ {118, 8, 0, 8, 8, 8, 1419},
+ {119, 11, 0, 8, 11, 8, 1435},
+ {120, 7, 0, 8, 7, 8, 1457},
+ {121, 8, 0, 8, 8, 10, 1471},
+ {122, 7, 0, 8, 7, 8, 1491},
+ {123, 5, 0, 6, 4, 11, 1505},
+ {124, 4, 1, 5, 2, 13, 1516},
+ {125, 5, 0, 6, 5, 12, 1523},
+ {126, 7, 0, 10, 7, 3, 1538},
+};
+const Font font_m = {23, 15, 6, 95, font_m_glyphs, font_m_data};
+
+static const uint8_t font_l_data[] = {184,244,215,31,46,0,170,1,208,255,11,244,255,31,248,131,63,252,65,127,253,1,127,253,1,127,253,1,127,252,65,127,248,130,63,244,235,47,224,255,11,64,190,1,64,5,254,231,255,249,127,197,31,240,7,252,1,127,192,47,240,11,252,1,127,128,31,144,90,64,255,47,248,255,71,66,191,0,224,11,64,127,0,253,2,248,11,224,47,128,127,0,253,255,203,255,191,168,170,6,160,42,192,255,31,253,255,67,128,127,0,244,3,234,47,240,255,0,254,63,0,244,71,0,127,190,254,215,255,47,228,111,0,0,80,1,0,252,11,0,254,11,64,255,11,208,239,11,240,231,11,248,227,11,253,229,27,253,255,127,253,255,127,84,229,31,0,208,11,0,208,11,84,85,244,255,231,255,159,95,21,126,0,252,255,241,255,95,171,191,0,248,23,224,255,235,239,255,63,248,47,0,0,169,1,244,255,1,255,191,224,31,4,252,85,0,255,255,209,255,255,244,155,127,252,193,31,127,240,71,191,255,128,255,31,64,191,1,84,85,209,255,127,253,255,71,149,127,0,252,2,208,31,0,255,0,244,7,128,63,0,253,2,224,15,0,191,0,144,6,0,144,191,1,253,255,193,191,255,244,71,127,252,209,15,254,255,1,255,127,240,171,127,253,192,111,63,240,219,191,255,226,255,47,144,191,1,64,106,0,252,191,128,255,191,240,71,63,253,193,31,191,245,135,255,255,193,255,127,64,213,31,0,248,67,235,191,208,255,11,224,111,0,16,224,215,47,191,164,0,0,0,126,253,246,139,31,164,106,0,254,255,7,254,255,31,190,208,63,190,64,127,190,0,127,190,0,127,190,0,127,190,64,127,190,208,63,254,250,31,254,255,11,232,191,1,0,164,26,0,254,255,2,254,255,15,254,6,25,252,2,0,240,7,170,210,31,254,95,127,244,127,252,2,252,225,31,240,71,255,235,31,244,255,127,0,249,107,0,41,0,248,2,224,11,128,47,0,190,0,248,2,224,11,128,47,0,190,0,248,2,224,255,175,255,191,168,170,1,80,0,80,208,63,208,47,253,7,254,227,191,240,127,254,79,255,231,251,249,126,190,238,235,235,219,127,190,191,252,227,251,139,47,190,191,80,224,255,11,0,254,126,0,208,11,64,85,64,255,255,235,255,255,166,254,26,64,127,0,208,31,0,244,7,0,253,1,64,127,0,208,31,0,244,7,0,253,1,0,126,0,64,21,128,255,31,252,255,71,86,191,64,229,75,255,191,253,251,219,11,190,253,250,203,255,191,224,191,1,0,64,5,0,240,7,0,252,2,16,191,208,255,47,253,255,203,127,253,246,7,191,253,192,111,63,240,219,31,252,242,175,127,244,255,31,224,191,0,0,4,0,244,127,64,255,127,240,155,63,253,229,95,255,255,211,191,26,244,7,0,248,171,11,253,255,2,232,47,0,0,20,0,244,191,129,255,255,240,95,127,253,193,95,63,240,215,15,252,245,91,127,252,255,31,252,255,7,84,253,81,64,63,248,255,11,254,255,0,169,6,0,20,190,191,125,0,127,127,191,191,191,191,191,191,191,125,21,190,190,190,190,190,190,190,190,190,190,190,190,185,64,5,84,0,254,239,255,226,255,255,255,254,230,111,254,127,244,135,255,31,253,225,255,71,127,248,255,209,31,254,127,244,135,255,31,253,209,223,7,46,224,2,64,21,128,255,31,255,255,243,91,127,127,240,247,7,191,127,240,251,7,191,127,240,251,7,191,125,208,7,0,20,0,244,191,64,255,191,240,159,127,253,129,111,63,224,223,15,248,247,7,191,252,251,31,253,255,2,248,27,0,244,175,255,255,175,253,1,127,192,31,240,7,252,1,127,128,31,0,64,21,64,255,31,252,255,210,95,25,252,6,128,255,11,144,255,67,64,127,188,254,195,255,47,228,111,0,21,192,31,240,7,252,43,255,223,255,243,7,252,1,127,192,47,240,175,248,127,248,11,189,128,95,63,240,199,31,253,225,75,63,244,227,11,252,253,1,190,63,64,255,11,192,255,0,208,31,0};
+static const Glyph font_l_glyphs[] = {
+ {32, 4, -1, 0, 0, 0, 0},
+ {46, 5, 0, 18, 5, 4, 0},
+ {48, 12, 0, 9, 12, 13, 5},
+ {49, 8, 0, 9, 7, 13, 44},
+ {50, 10, 0, 9, 10, 13, 67},
+ {51, 10, 0, 9, 10, 13, 100},
+ {52, 12, 0, 9, 12, 13, 133},
+ {53, 10, 1, 9, 9, 13, 172},
+ {54, 11, 0, 9, 11, 13, 202},
+ {55, 10, 0, 9, 10, 13, 238},
+ {56, 11, 0, 9, 11, 13, 271},
+ {57, 11, 0, 9, 11, 13, 307},
+ {58, 5, 0, 11, 5, 11, 343},
+ {68, 13, 1, 9, 12, 13, 357},
+ {71, 13, 0, 9, 13, 13, 396},
+ {76, 10, 1, 9, 9, 13, 439},
+ {77, 16, 1, 9, 14, 13, 469},
+ {84, 11, 0, 9, 11, 13, 515},
+ {97, 11, 0, 11, 10, 11, 551},
+ {100, 12, 0, 8, 11, 14, 579},
+ {101, 11, 0, 11, 11, 11, 618},
+ {103, 11, 0, 11, 11, 15, 649},
+ {105, 6, 1, 7, 4, 15, 691},
+ {108, 6, 1, 8, 4, 14, 706},
+ {109, 17, 1, 11, 15, 11, 720},
+ {110, 12, 1, 11, 10, 11, 762},
+ {111, 12, 0, 11, 11, 11, 790},
+ {114, 8, 1, 12, 7, 10, 821},
+ {115, 10, 0, 11, 10, 11, 839},
+ {116, 8, 1, 9, 7, 13, 867},
+ {118, 11, 0, 12, 11, 10, 890},
+};
+const Font font_l = {33, 21, 9, 31, font_l_glyphs, font_l_data};
+
+static const uint8_t ic_pause_o_data[] = {228,7,249,65,255,219,255,226,255,251,255,252,255,255,127,255,255,255,223,255,255,255,247,255,255,255,253,255,255,127,255,255,255,223,255,255,255,247,255,255,255,253,255,255,127,255,255,255,223,255,255,255,211,255,246,191,224,47,248,11,64,0,16,0};
+const Icon ic_pause_o = {15, 17, 0, 0, 15, 17, ic_pause_o_data};
+static const uint8_t ic_pause_f_data[] = {164,0,41,253,66,191,254,131,255,254,131,255,254,131,255,254,131,255,254,131,255,254,131,255,254,131,255,254,131,255,254,131,255,254,131,255,254,130,191,184,1,110};
+const Icon ic_pause_f = {15, 17, 1, 1, 12, 14, ic_pause_f_data};
+static const uint8_t ic_play_data[] = {2,0,0,47,0,0,255,1,0,255,27,0,255,191,0,255,255,11,255,255,127,255,255,191,255,255,11,255,255,1,255,47,0,255,2,0,111,0,0,7,0,0};
+const Icon ic_play = {14, 15, 1, 0, 12, 14, ic_play_data};
+static const uint8_t ic_restart_data[] = {0,27,0,0,253,7,0,254,255,1,254,239,15,125,47,188,184,28,208,243,1,0,223,7,0,124,46,0,244,248,0,224,194,31,228,7,253,255,7,128,255,6,0,80,0,0};
+const Icon ic_restart = {14, 14, 1, 0, 13, 14, ic_restart_data};
+static const uint8_t ic_back_data[] = {0,32,0,184,0,190,64,47,208,15,244,7,252,1,126,0,127,0,253,1,244,2,224,11,128,47,0,190,0,248,0,36};
+const Icon ic_back = {10, 17, 1, 0, 8, 16, ic_back_data};
+static const uint8_t ic_next_data[] = {20,0,244,1,208,31,0,189,0,224,11,0,190,0,224,11,0,62,0,248,1,248,2,244,2,244,3,244,7,240,7,224,7,0,9,0};
+const Icon ic_next = {10, 17, 1, 0, 9, 16, ic_next_data};
+static const uint8_t ic_left_data[] = {64,130,235,175,191,244,2,10};
+const Icon ic_left = {6, 6, 1, 0, 5, 6, ic_left_data};
+static const uint8_t ic_right_data[] = {5,224,6,254,226,127,190,160,0};
+const Icon ic_right = {6, 6, 0, 0, 6, 6, ic_right_data};
+static const uint8_t ic_lock_data[] = {64,47,0,173,11,224,224,0,11,29,248,255,231,255,191,254,255,235,255,191,254,255,235,255,191,253,255,7};
+const Icon ic_lock = {10, 11, 0, 0, 10, 11, ic_lock_data};
diff --git a/games/numdrive/src/font.h b/games/numdrive/src/font.h
new file mode 100644
index 00000000..5b6e97b2
--- /dev/null
+++ b/games/numdrive/src/font.h
@@ -0,0 +1,28 @@
+#ifndef FONT_H
+#define FONT_H
+#include <stdint.h>
+
+typedef struct {
+ uint8_t code, adv;
+ int8_t xoff;
+ uint8_t y0, w, h;
+ uint16_t off;
+} Glyph;
+
+typedef struct {
+ uint8_t h, base, cap_top, n;
+ const Glyph *g;
+ const uint8_t *data;
+} Font;
+
+typedef struct {
+ uint8_t w, h;
+ int8_t xoff, y0;
+ uint8_t gw, gh;
+ const uint8_t *data;
+} Icon;
+
+extern const Font font_s, font_m, font_l;
+extern const Icon ic_pause_o, ic_pause_f, ic_play, ic_restart, ic_back, ic_next, ic_left, ic_right, ic_lock;
+
+#endif
diff --git a/games/numdrive/src/gfx.c b/games/numdrive/src/gfx.c
new file mode 100644
index 00000000..daadf0dd
--- /dev/null
+++ b/games/numdrive/src/gfx.c
@@ -0,0 +1,127 @@
+/* Minimal anti-aliased 2D drawing into screen strips (UI, menus, HUD). */
+#include <math.h>
+#include "gfx.h"
+#include "platform.h"
+
+Canvas gc;
+
+void g_begin(uint16_t *px, int y0, int n) {
+ gc.px = px;
+ gc.y0 = y0;
+ gc.y1 = y0 + n;
+}
+
+static inline void put(int x, int y, uint16_t c, int a) {
+ if (x < 0 || x >= SCREEN_W || y < gc.y0 || y >= gc.y1 || a <= 0) return;
+ uint16_t *p = gc.px + (y - gc.y0) * SCREEN_W + x;
+ *p = a >= 32 ? c : mix565(*p, c, a);
+}
+
+static void span(int x0, int x1, int y, uint16_t c, int a) {
+ if (y < gc.y0 || y >= gc.y1) return;
+ if (x0 < 0) x0 = 0;
+ if (x1 > SCREEN_W) x1 = SCREEN_W;
+ uint16_t *p = gc.px + (y - gc.y0) * SCREEN_W;
+ if (a >= 32)
+ for (int x = x0; x < x1; x++) p[x] = c;
+ else
+ for (int x = x0; x < x1; x++) p[x] = mix565(p[x], c, a);
+}
+
+void g_rect(int x, int y, int w, int h, uint16_t c, int a) {
+ int ya = y < gc.y0 ? gc.y0 : y, yb = y + h > gc.y1 ? gc.y1 : y + h;
+ for (int yy = ya; yy < yb; yy++) span(x, x + w, yy, c, a);
+}
+
+void g_rrect(int x, int y, int w, int h, int r, uint16_t c, int a) {
+ if (r * 2 > h) r = h / 2;
+ if (r * 2 > w) r = w / 2;
+ int ya = y < gc.y0 ? gc.y0 : y, yb = y + h > gc.y1 ? gc.y1 : y + h;
+ for (int yy = ya; yy < yb; yy++) {
+ int dy = yy < y + r ? y + r - yy : (yy >= y + h - r ? yy - (y + h - r) + 1 : 0);
+ if (!dy) {
+ span(x, x + w, yy, c, a);
+ continue;
+ }
+ float cy = dy - 0.5f;
+ /* corner pixels with coverage, straight middle */
+ for (int dx = r; dx > 0; dx--) {
+ float cx = dx - 0.5f;
+ float d = sqrtf(cx * cx + cy * cy);
+ float cov = (float)r - d + 0.5f;
+ if (cov <= 0) continue;
+ int aa = cov >= 1 ? a : (int)(a * cov);
+ put(x + r - dx, yy, c, aa);
+ put(x + w - r + dx - 1, yy, c, aa);
+ }
+ span(x + r, x + w - r, yy, c, a);
+ }
+}
+
+void g_button(int x, int y, int w, int h, int r, uint16_t top, uint16_t bottom, int halo) {
+ if (halo) g_rrect(x - 2, y - 2, w + 4, h + 4, r + 2, C_WHITE, 32);
+ g_rrect(x - 1, y - 1, w + 2, h + 2, r + 1, C_BLACK, 32);
+ g_rrect(x, y, w, h, r, bottom, 32);
+ g_rrect(x, y, w, h - 3, r, top, 32);
+}
+
+const Glyph *font_glyph(const Font *f, int ch) {
+ /* glyphs are sorted by code; the small and medium fonts are a contiguous range */
+ int d = ch - f->g[0].code;
+ if (d >= 0 && d < f->n && f->g[d].code == ch) return &f->g[d];
+ int lo = 0, hi = f->n - 1;
+ while (lo <= hi) {
+ int m = (lo + hi) >> 1, c = f->g[m].code;
+ if (c == ch) return &f->g[m];
+ if (c < ch) lo = m + 1;
+ else hi = m - 1;
+ }
+ return 0;
+}
+
+int glyph_alpha(const Font *f, const Glyph *g, int x, int y) {
+ x -= g->xoff;
+ y -= g->y0;
+ if (x < 0 || y < 0 || x >= g->w || y >= g->h) return 0;
+ int i = y * g->w + x;
+ return (f->data[g->off + (i >> 2)] >> ((i & 3) * 2)) & 3;
+}
+
+int g_text_w(const Font *f, const char *s) {
+ int w = 0;
+ for (; *s; s++) {
+ const Glyph *g = font_glyph(f, (unsigned char)*s);
+ if (g) w += g->adv;
+ }
+ return w;
+}
+
+static void blit2(const uint8_t *data, int gw, int gh, int x, int y, uint16_t c, int a) {
+ int ya = y < gc.y0 ? gc.y0 : y, yb = y + gh > gc.y1 ? gc.y1 : y + gh;
+ for (int yy = ya; yy < yb; yy++) {
+ for (int xx = 0; xx < gw; xx++) {
+ int i = (yy - y) * gw + xx;
+ int v = (data[i >> 2] >> ((i & 3) * 2)) & 3;
+ if (v) put(x + xx, yy, c, v == 3 ? a : a * v / 3);
+ }
+ }
+}
+
+void g_text(const Font *f, int x, int y, const char *s, uint16_t c, int a) {
+ if (y >= gc.y1 || y + f->h <= gc.y0) return;
+ for (; *s; s++) {
+ const Glyph *g = font_glyph(f, (unsigned char)*s);
+ if (!g) continue;
+ if (g->w) blit2(f->data + g->off, g->w, g->h, x + g->xoff, y + g->y0, c, a);
+ x += g->adv;
+ }
+}
+
+void g_text_c(const Font *f, int cx, int y, const char *s, uint16_t c, int a) {
+ g_text(f, cx - g_text_w(f, s) / 2, y, s, c, a);
+}
+
+void g_icon(const Icon *ic, int x, int y, uint16_t c, int a) {
+ if (y >= gc.y1 || y + ic->h <= gc.y0) return;
+ blit2(ic->data, ic->gw, ic->gh, x + ic->xoff, y + ic->y0, c, a);
+}
diff --git a/games/numdrive/src/gfx.h b/games/numdrive/src/gfx.h
new file mode 100644
index 00000000..e54cf84d
--- /dev/null
+++ b/games/numdrive/src/gfx.h
@@ -0,0 +1,36 @@
+#ifndef GFX_H
+#define GFX_H
+#include <stdint.h>
+#include "font.h"
+
+/* Drawing happens into horizontal strips of the screen (rows [y0, y1), full width). */
+typedef struct {
+ uint16_t *px;
+ int y0, y1;
+} Canvas;
+extern Canvas gc;
+
+#define RGB(r, g, b) ((uint16_t)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
+#define C_WHITE 0xFFFF
+#define C_BLACK 0x0000
+
+static inline uint16_t mix565(uint16_t d, uint16_t s, int a) { /* a: 0..32 */
+ uint32_t dd = (d | (uint32_t)d << 16) & 0x07E0F81Fu;
+ uint32_t ss = (s | (uint32_t)s << 16) & 0x07E0F81Fu;
+ uint32_t r = (dd + (((ss - dd) * (uint32_t)a) >> 5)) & 0x07E0F81Fu;
+ return (uint16_t)(r | r >> 16);
+}
+
+void g_begin(uint16_t *px, int y0, int n);
+void g_rect(int x, int y, int w, int h, uint16_t c, int a);
+void g_rrect(int x, int y, int w, int h, int r, uint16_t c, int a);
+/* rounded rectangle with a darker bottom band, black outline and optional white halo */
+void g_button(int x, int y, int w, int h, int r, uint16_t top, uint16_t bottom, int halo);
+int g_text_w(const Font *f, const char *s);
+void g_text(const Font *f, int x, int y, const char *s, uint16_t c, int a);
+void g_text_c(const Font *f, int cx, int y, const char *s, uint16_t c, int a);
+void g_icon(const Icon *ic, int x, int y, uint16_t c, int a);
+int glyph_alpha(const Font *f, const Glyph *g, int x, int y); /* 0..3 */
+const Glyph *font_glyph(const Font *f, int ch);
+
+#endif
diff --git a/games/numdrive/src/icon.png b/games/numdrive/src/icon.png
new file mode 100644
index 00000000..262c0580
Binary files /dev/null and b/games/numdrive/src/icon.png differ
diff --git a/games/numdrive/src/inflate.c b/games/numdrive/src/inflate.c
new file mode 100644
index 00000000..1e6a299f
--- /dev/null
+++ b/games/numdrive/src/inflate.c
@@ -0,0 +1,157 @@
+/* Minimal raw DEFLATE (RFC 1951) decoder, one-shot into a caller buffer. */
+#include "inflate.h"
+
+typedef struct {
+ const uint8_t *src, *end;
+ uint32_t bits;
+ int nbits;
+ uint8_t *out, *out_end, *out_start;
+} St;
+
+typedef struct {
+ uint16_t count[16];
+ uint16_t sym[288];
+} Huff;
+
+static int getbit(St *s) {
+ if (!s->nbits) {
+ s->bits = s->src < s->end ? *s->src++ : 0;
+ s->nbits = 8;
+ }
+ int b = s->bits & 1;
+ s->bits >>= 1;
+ s->nbits--;
+ return b;
+}
+
+static uint32_t getbits(St *s, int n) {
+ uint32_t v = 0;
+ for (int i = 0; i < n; i++) v |= (uint32_t)getbit(s) << i;
+ return v;
+}
+
+static void build(Huff *h, const uint8_t *len, int n) {
+ uint16_t offs[16];
+ for (int i = 0; i < 16; i++) h->count[i] = 0;
+ for (int i = 0; i < n; i++) h->count[len[i]]++;
+ h->count[0] = 0;
+ offs[1] = 0;
+ for (int i = 1; i < 15; i++) offs[i + 1] = offs[i] + h->count[i];
+ for (int i = 0; i < n; i++)
+ if (len[i]) h->sym[offs[len[i]]++] = i;
+}
+
+static int decode(St *s, const Huff *h) {
+ int code = 0, first = 0, index = 0;
+ for (int l = 1; l < 16; l++) {
+ code |= getbit(s);
+ int c = h->count[l];
+ if (code - c < first) return h->sym[index + (code - first)];
+ index += c;
+ first += c;
+ first <<= 1;
+ code <<= 1;
+ }
+ return -1;
+}
+
+static const uint16_t lbase[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
+ 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
+static const uint8_t lext[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
+ 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
+static const uint16_t dbase[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129,
+ 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097,
+ 6145, 8193, 12289, 16385, 24577};
+static const uint8_t dext[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6,
+ 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
+
+static int block(St *s, const Huff *lh, const Huff *dh) {
+ for (;;) {
+ int sym = decode(s, lh);
+ if (sym < 0) return -1;
+ if (sym < 256) {
+ if (s->out >= s->out_end) return -1;
+ *s->out++ = sym;
+ } else if (sym == 256) {
+ return 0;
+ } else {
+ sym -= 257;
+ if (sym >= 29) return -1;
+ int len = lbase[sym] + getbits(s, lext[sym]);
+ int ds = decode(s, dh);
+ if (ds < 0 || ds >= 30) return -1;
+ int dist = dbase[ds] + getbits(s, dext[ds]);
+ if (dist > s->out - s->out_start || s->out + len > s->out_end) return -1;
+ uint8_t *p = s->out - dist;
+ while (len--) *s->out++ = *p++;
+ }
+ }
+}
+
+int inflate_raw(const uint8_t *src, uint32_t srclen, uint8_t *dst, uint32_t dstlen) {
+ St s;
+ Huff lh, dh;
+ uint8_t lens[320];
+ s.src = src;
+ s.end = src + srclen;
+ s.nbits = 0;
+ s.bits = 0;
+ s.out = s.out_start = dst;
+ s.out_end = dst + dstlen;
+ int last;
+ do {
+ last = getbit(&s);
+ int type = getbits(&s, 2);
+ if (type == 0) {
+ s.nbits = 0;
+ if (s.src + 4 > s.end) return -1;
+ uint16_t len = s.src[0] | s.src[1] << 8;
+ s.src += 4;
+ if (s.src + len > s.end || s.out + len > s.out_end) return -1;
+ while (len--) *s.out++ = *s.src++;
+ } else if (type == 1) {
+ int i = 0;
+ for (; i < 144; i++) lens[i] = 8;
+ for (; i < 256; i++) lens[i] = 9;
+ for (; i < 280; i++) lens[i] = 7;
+ for (; i < 288; i++) lens[i] = 8;
+ build(&lh, lens, 288);
+ for (i = 0; i < 30; i++) lens[i] = 5;
+ build(&dh, lens, 30);
+ if (block(&s, &lh, &dh)) return -1;
+ } else if (type == 2) {
+ static const uint8_t ord[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
+ int nlen = getbits(&s, 5) + 257, ndist = getbits(&s, 5) + 1, ncode = getbits(&s, 4) + 4;
+ uint8_t cl[19] = {0};
+ for (int i = 0; i < ncode; i++) cl[ord[i]] = getbits(&s, 3);
+ build(&lh, cl, 19);
+ int i = 0;
+ while (i < nlen + ndist) {
+ int sym = decode(&s, &lh);
+ if (sym < 0) return -1;
+ if (sym < 16) {
+ lens[i++] = sym;
+ } else {
+ int rep, val = 0;
+ if (sym == 16) {
+ if (!i) return -1;
+ val = lens[i - 1];
+ rep = 3 + getbits(&s, 2);
+ } else if (sym == 17) {
+ rep = 3 + getbits(&s, 3);
+ } else {
+ rep = 11 + getbits(&s, 7);
+ }
+ if (i + rep > nlen + ndist) return -1;
+ while (rep--) lens[i++] = val;
+ }
+ }
+ build(&lh, lens, nlen);
+ build(&dh, lens + nlen, ndist);
+ if (block(&s, &lh, &dh)) return -1;
+ } else {
+ return -1;
+ }
+ } while (!last);
+ return (int)(s.out - s.out_start);
+}
diff --git a/games/numdrive/src/inflate.h b/games/numdrive/src/inflate.h
new file mode 100644
index 00000000..a5179b7a
--- /dev/null
+++ b/games/numdrive/src/inflate.h
@@ -0,0 +1,8 @@
+#ifndef INFLATE_H
+#define INFLATE_H
+#include <stdint.h>
+
+/* Decode a raw DEFLATE stream. Returns the number of bytes written, or -1 on error. */
+int inflate_raw(const uint8_t *src, uint32_t srclen, uint8_t *dst, uint32_t dstlen);
+
+#endif
diff --git a/games/numdrive/src/main.c b/games/numdrive/src/main.c
new file mode 100644
index 00000000..198c85ae
--- /dev/null
+++ b/games/numdrive/src/main.c
@@ -0,0 +1,246 @@
+#include <stdlib.h>
+#include <string.h>
+#ifdef HOST
+#include <stdio.h>
+#endif
+#include "platform.h"
+#include "world.h"
+#include "vm.h"
+#include "physics.h"
+#include "render.h"
+#include "ui.h"
+#include "save.h"
+
+#ifndef HOST
+#include <eadk.h>
+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
+
+enum { ST_PLAY, ST_CARD, ST_LEVELS };
+#define SHOT_FRAMES 10 /* viewfinder shown before the photo */
+
+static int win_timer = -1, lose_timer = -1;
+#ifdef HOST
+void host_outcome(int won);
+#endif
+void game_win(int delay) {
+#ifdef HOST
+ if (win_timer < 0 && lose_timer < 0) host_outcome(1);
+#endif
+ if (win_timer < 0 && lose_timer < 0) win_timer = delay > SHOT_FRAMES ? delay : SHOT_FRAMES;
+}
+void game_lose(int delay) {
+#ifdef HOST
+ if (getenv("ND_WDBG") && win_timer < 0 && lose_timer < 0) fprintf(stderr, "lose at frame %d\n", vm_frame_count);
+ if (win_timer < 0 && lose_timer < 0) host_outcome(2);
+#endif
+ if (win_timer < 0 && lose_timer < 0) lose_timer = delay > SHOT_FRAMES ? delay : SHOT_FRAMES;
+}
+
+static int cur;
+static bool start_level(int i) {
+ if (i < 0) i = 0;
+ if (i >= nlevels) i = nlevels - 1;
+ cur = i;
+ win_timer = lose_timer = -1;
+ phys_reset();
+ cam_default();
+ if (!world_load_level(i)) return false;
+ phys_start();
+ if (!render_init_level()) return false;
+ hud_reset();
+ if (progress.last != i) {
+ progress.last = (uint8_t)i;
+ save_store();
+ }
+ return true;
+}
+
+static void sim_step(uint8_t buttons) {
+ vm_buttons = buttons;
+ vm_frame();
+#ifdef HOST
+ if (getenv("ND_ODBG") && vm_frame_count <= 1) {
+ const char *l = getenv("ND_ODBG");
+ while (*l) {
+ int o = atoi(l);
+ if (o >= 0 && o < nobj) fprintf(stderr, "f%d obj%d pos=(%.2f %.2f %.2f) rot=(%.3f %.3f %.3f %.3f) flags=%x\n", vm_frame_count, o, objs[o].pos.x, objs[o].pos.y, objs[o].pos.z, objs[o].rot.x, objs[o].rot.y, objs[o].rot.z, objs[o].rot.w, objs[o].flags);
+ while (*l && *l != ',') l++;
+ if (*l) l++;
+ }
+ }
+#endif
+ phys_step();
+#ifdef HOST
+ if (getenv("ND_OBJHIST") && vm_frame_count == atoi(getenv("ND_OBJHIST"))) {
+ for (int i = 0; i < nobj; i++)
+ fprintf(stderr, "OBJ %d src %d np %d flags %x pos %.1f %.1f %.1f\n", i, objs[i].src, objs[i].shape->np, objs[i].flags, objs[i].pos.x, objs[i].pos.y, objs[i].pos.z);
+ }
+#endif
+#ifdef HOST
+ {
+ extern void phys_debug(int);
+ phys_debug(vm_frame_count);
+ }
+#endif
+ vm_late();
+}
+
+static int shot_t;
+static void hud_post(uint16_t *px, int y, int n) {
+ if (shot_t > 0) viewfinder_draw(px, y, n, SHOT_FRAMES - shot_t);
+ else hud_draw(px, y, n);
+}
+
+extern bool level_unlocked(int i);
+
+#ifdef ARMTEST
+extern char **environ;
+#endif
+
+int main(int argc, char **argv) {
+ (void)argc;
+ (void)argv;
+#ifdef ARMTEST
+ environ = argv + 1; /* semihosting has no environment: pass KEY=VALUE arguments */
+#endif
+ if (!world_init()) return 1;
+ save_load();
+ int lvl = progress.last < nlevels ? progress.last : 0;
+#ifdef HOST
+ if (getenv("ND_LEVEL")) lvl = atoi(getenv("ND_LEVEL"));
+#endif
+ if (!start_level(lvl)) {
+ plat_fill(0, 0, SCREEN_W, SCREEN_H, 0xF800);
+ plat_sleep(2000);
+ return 1;
+ }
+ int state = ST_PLAY, kind = CARD_PAUSE, anim = 0, sel = 1, lsel = 0, lscroll = 0;
+ bool dirty = true;
+ uint64_t prev = 0;
+ uint32_t last = plat_millis();
+ int acc = 0;
+ for (;;) {
+ uint64_t k = plat_keys();
+ uint64_t hit = k & ~prev;
+ prev = k;
+ if (k & KEY(K_HOME)) break;
+ /* frame pacing: fixed 60 Hz simulation, catching up when rendering is slow */
+ int steps = 1;
+#ifndef HOST
+ uint32_t now = plat_millis();
+ if (now - last < 16) {
+ plat_sleep((int)(16 - (now - last)));
+ now = plat_millis();
+ }
+ acc += (int)(now - last) * 3;
+ last = now;
+ steps = acc / 50;
+ if (steps < 1) steps = 1;
+ if (steps > 3) steps = 3, acc = 0;
+ acc -= steps * 50;
+ if (acc < 0) acc = 0;
+#else
+ (void)last;
+ (void)acc;
+#endif
+ if (state == ST_PLAY) {
+ if (hit & (KEY(K_BACK) | KEY(K_OK))) {
+ shot_t = 0;
+ ui_capture_background();
+ card_setup(CARD_PAUSE, cur);
+ kind = CARD_PAUSE;
+ state = ST_CARD;
+ anim = 0;
+ sel = 1;
+ continue;
+ }
+ uint8_t b = ((k & KEY(K_LEFT)) ? 1 : 0) | ((k & KEY(K_RIGHT)) ? 2 : 0);
+ bool ending = false;
+ for (int s = 0; s < steps && !ending; s++) {
+ sim_step(win_timer >= 0 || lose_timer >= 0 ? 0 : b);
+ hud_tick(b);
+ if (win_timer > 0) win_timer--;
+ if (lose_timer > 0) lose_timer--;
+ ending = win_timer == 0 || lose_timer == 0;
+ }
+ int t = win_timer >= 0 ? win_timer : lose_timer;
+ shot_t = t > 0 && t <= SHOT_FRAMES ? t : 0;
+ if (ending) {
+ kind = win_timer == 0 ? CARD_WIN : CARD_LOSE;
+ if (kind == CARD_WIN && !lvl_done(cur)) {
+ lvl_set_done(cur);
+ save_store();
+ }
+ ui_capture_background();
+ card_setup(kind, cur);
+ state = ST_CARD;
+ anim = 0;
+ sel = 1;
+ win_timer = lose_timer = -1;
+ continue;
+ }
+#ifdef HOST
+ static int norender = -1;
+ if (norender < 0) norender = getenv("ND_NORENDER") != 0;
+ if (!norender)
+#endif
+ render_frame(hud_post);
+ } else if (state == ST_CARD) {
+ if (card_buttons() == 2) {
+ if ((hit & KEY(K_LEFT)) && sel) sel = 0, dirty = true;
+ if ((hit & KEY(K_RIGHT)) && !sel) sel = 1, dirty = true;
+ } else {
+ sel = 1;
+ }
+ if (hit & (KEY(K_OK) | KEY(K_EXE))) {
+ if (kind == CARD_PAUSE && sel == 1) {
+ state = ST_PLAY;
+ } else {
+ int next = kind == CARD_WIN && sel == 1 ? cur + 1 : cur;
+ start_level(next < nlevels ? next : cur);
+ state = ST_PLAY;
+ }
+ continue;
+ }
+ if (hit & KEY(K_BACK)) { /* the "<" arrow: level list */
+ state = ST_LEVELS;
+ lsel = cur;
+ lscroll = lsel / 5 - 2 < 0 ? 0 : lsel / 5 - 2;
+ dirty = true;
+ continue;
+ }
+ if (kind != CARD_PAUSE)
+ for (int s = 0; s < steps; s++) sim_step(0);
+ bool full = dirty || anim <= 13;
+ if (kind != CARD_PAUSE || full) card_draw(anim, sel, full);
+ dirty = false;
+ anim++;
+ } else {
+ int old = lsel;
+ if (hit & KEY(K_LEFT)) lsel--;
+ if (hit & KEY(K_RIGHT)) lsel++;
+ if (hit & KEY(K_UP)) lsel -= 5;
+ if (hit & KEY(K_DOWN)) lsel += 5;
+ if (lsel < 0 || lsel >= nlevels || !level_unlocked(lsel)) lsel = old;
+ if (lsel != old) dirty = true;
+ if (lsel / 5 < lscroll) lscroll = lsel / 5, dirty = true;
+ if (lsel / 5 > lscroll + 3) lscroll = lsel / 5 - 3, dirty = true;
+ if (hit & (KEY(K_OK) | KEY(K_EXE))) {
+ start_level(lsel);
+ state = ST_PLAY;
+ continue;
+ }
+ if (hit & KEY(K_BACK)) {
+ state = ST_CARD;
+ dirty = true;
+ continue;
+ }
+ if (dirty) levels_draw(lsel, lscroll);
+ dirty = false;
+ }
+ plat_frame_done();
+ }
+ return 0;
+}
diff --git a/games/numdrive/src/ops.h b/games/numdrive/src/ops.h
new file mode 100644
index 00000000..513f7d46
--- /dev/null
+++ b/games/numdrive/src/ops.h
@@ -0,0 +1,267 @@
+/* Generated by tools/ops.py. Do not edit. */
+#ifndef OPS_H
+#define OPS_H
+
+enum {
+ OP_NUMBER, /* 36: ins [] outs ['Number'] execs [] */
+ OP_VECTOR, /* 38: ins [] outs ['Vector'] execs [] */
+ OP_ROTATION, /* 42: ins [] outs ['Rotation'] execs [] */
+ OP_TRUE, /* 449: ins [] outs ['True'] execs [] */
+ OP_FALSE, /* 451: ins [] outs ['False'] execs [] */
+ OP_GET_VAR_NUM, /* 46: ins [] outs ['Number'] execs [] */
+ OP_GET_VAR_VEC, /* 48: ins [] outs ['Vector'] execs [] */
+ OP_GET_VAR_ROT, /* 50: ins [] outs ['Rotation'] execs [] */
+ OP_GET_VAR_TRU, /* 52: ins [] outs ['Truth'] execs [] */
+ OP_GET_VAR_OBJ, /* 54: ins [] outs ['Object'] execs [] */
+ OP_GET_VAR_CON, /* 56: ins [] outs ['Constraint'] execs [] */
+ OP_SET_VAR_NUM, /* 428: ins ['Value'] outs [] execs [] */
+ OP_SET_VAR_VEC, /* 430: ins ['Value'] outs [] execs [] */
+ OP_SET_VAR_ROT, /* 432: ins ['Value'] outs [] execs [] */
+ OP_SET_VAR_TRU, /* 434: ins ['Value'] outs [] execs [] */
+ OP_SET_VAR_OBJ, /* 436: ins ['Value'] outs [] execs [] */
+ OP_SET_VAR_CON, /* 438: ins ['Value'] outs [] execs [] */
+ OP_SET_PTR_NUM, /* 58: ins ['Variable', 'Value'] outs [] execs [] */
+ OP_SET_PTR_VEC, /* 62: ins ['Variable', 'Value'] outs [] execs [] */
+ OP_SET_PTR_ROT, /* 66: ins ['Variable', 'Value'] outs [] execs [] */
+ OP_SET_PTR_TRU, /* 70: ins ['Variable', 'Value'] outs [] execs [] */
+ OP_SET_PTR_OBJ, /* 74: ins ['Variable', 'Value'] outs [] execs [] */
+ OP_SET_PTR_CON, /* 78: ins ['Variable', 'Value'] outs [] execs [] */
+ OP_LIST_NUM, /* 82: ins ['Variable', 'Index'] outs ['Element'] execs [] */
+ OP_LIST_OBJ, /* 86: ins ['Variable', 'Index'] outs ['Element'] execs [] */
+ OP_LIST_VEC, /* 461: ins ['Variable', 'Index'] outs ['Element'] execs [] */
+ OP_LIST_ROT, /* 465: ins ['Variable', 'Index'] outs ['Element'] execs [] */
+ OP_LIST_TRU, /* 469: ins ['Variable', 'Index'] outs ['Element'] execs [] */
+ OP_LIST_CON, /* 473: ins ['Variable', 'Index'] outs ['Element'] execs [] */
+ OP_INCREASE_NUMBER, /* 556: ins ['Variable'] outs [] execs [] */
+ OP_DECREASE_NUMBER, /* 558: ins ['Variable'] outs [] execs [] */
+ OP_NEGATE, /* 90: ins ['Num'] outs ['-Num'] execs [] */
+ OP_ADD_NUMBERS, /* 92: ins ['Num1', 'Num2'] outs ['Num1 + Num2'] execs [] */
+ OP_ADD_VECTORS, /* 96: ins ['Vec1', 'Vec2'] outs ['Vec1 + Vec2'] execs [] */
+ OP_SUBTRACT_NUMBERS, /* 100: ins ['Num1', 'Num2'] outs ['Num1 - Num2'] execs [] */
+ OP_SUBTRACT_VECTORS, /* 104: ins ['Vec1', 'Vec2'] outs ['Vec1 - Vec2'] execs [] */
+ OP_MULTIPLY, /* 108: ins ['Num1', 'Num2'] outs ['Num1 * Num2'] execs [] */
+ OP_SCALE, /* 112: ins ['Vec', 'Num'] outs ['Vec * Num'] execs [] */
+ OP_ROTATE, /* 116: ins ['Vec', 'Rot'] outs ['Rot * Vec'] execs [] */
+ OP_COMBINE, /* 120: ins ['Rot1', 'Rot2'] outs ['Rot1 * Rot2'] execs [] */
+ OP_DIVIDE, /* 124: ins ['Num1', 'Num2'] outs ['Num1 / Num2'] execs [] */
+ OP_LESS_THAN, /* 128: ins ['Num1', 'Num2'] outs ['Num1 < Num2'] execs [] */
+ OP_EQUALS_NUMBERS, /* 132: ins ['Num1', 'Num2'] outs ['Num1 = Num2'] execs [] */
+ OP_EQUALS_VECTORS, /* 136: ins ['Vec1', 'Vec2'] outs ['Vec1 = Vec2'] execs [] */
+ OP_EQUALS_OBJECTS, /* 140: ins ['Obj1', 'Obj2'] outs ['Obj1 = Obj2'] execs [] */
+ OP_NOT, /* 144: ins ['Tru'] outs ['Not Tru'] execs [] */
+ OP_AND, /* 146: ins ['Tru1', 'Tru2'] outs ['Tru1 & Tru2'] execs [] */
+ OP_MAKE_VECTOR, /* 150: ins ['X', 'Y', 'Z'] outs ['Vector'] execs [] */
+ OP_BREAK_VECTOR, /* 156: ins ['Vector'] outs ['X', 'Y', 'Z'] execs [] */
+ OP_MAKE_ROTATION, /* 162: ins ['X angle', 'Y angle', 'Z angle'] outs ['Rotation'] execs [] */
+ OP_RANDOM, /* 168: ins ['Min', 'Max'] outs ['Random'] execs [] */
+ OP_MODULO, /* 172: ins ['a', 'b'] outs ['mod(a,b)'] execs [] */
+ OP_MIN, /* 176: ins ['Num1', 'Num2'] outs ['Smaller'] execs [] */
+ OP_MAX, /* 180: ins ['Num1', 'Num2'] outs ['Bigger'] execs [] */
+ OP_ROUND, /* 184: ins ['Number'] outs ['Rounded'] execs [] */
+ OP_FLOOR, /* 186: ins ['Number'] outs ['Floor'] execs [] */
+ OP_CEILING, /* 188: ins ['Number'] outs ['Ceiling'] execs [] */
+ OP_DISTANCE, /* 190: ins ['Vector', 'Vector'] outs ['Distance'] execs [] */
+ OP_LERP, /* 194: ins ['From', 'To', 'Amount'] outs ['Rotation'] execs [] */
+ OP_AXIS_ANGLE, /* 200: ins ['Axis', 'Angle'] outs ['Rotation'] execs [] */
+ OP_LOOK_ROTATION, /* 204: ins ['Direction', 'Up'] outs ['Rotation'] execs [] */
+ OP_LINE_VS_PLANE, /* 208: ins ['Line From', 'Line To', 'Plane Point', 'Plane Normal'] outs ['Intersection'] execs [] */
+ OP_SIN, /* 413: ins ['Num'] outs ['Sin(Num)'] execs [] */
+ OP_OR, /* 417: ins ['Tru1', 'Tru2'] outs ['Tru1 | Tru2'] execs [] */
+ OP_EQUALS_TRUTHS, /* 421: ins ['Tru1', 'Tru2'] outs ['Tru1 = Tru2'] execs [] */
+ OP_INVERSE, /* 440: ins ['Rot'] outs ['Rot Inverse'] execs [] */
+ OP_BREAK_ROTATION, /* 442: ins ['Rotation'] outs ['X angle', 'Y angle', 'Z angle'] execs [] */
+ OP_COS, /* 453: ins ['Num'] outs ['Cos(Num)'] execs [] */
+ OP_ABSOLUTE, /* 455: ins ['Num'] outs ['|Num|'] execs [] */
+ OP_POWER, /* 457: ins ['Base', 'Exponent'] outs ['Base ^ Exponent'] execs [] */
+ OP_GREATER_THAN, /* 481: ins ['Num1', 'Num2'] outs ['Num1 > Num2'] execs [] */
+ OP_DOT_PRODUCT, /* 570: ins ['Vector', 'Vector'] outs ['Dot Product'] execs [] */
+ OP_CROSS_PRODUCT, /* 574: ins ['Vector', 'Vector'] outs ['Cross Product'] execs [] */
+ OP_NORMALIZE, /* 578: ins ['Vector'] outs ['Normalized'] execs [] */
+ OP_LOGARITHM, /* 580: ins ['Number', 'Base'] outs ['Logarithm'] execs [] */
+ OP_SCREEN_TO_WORLD, /* 216: ins ['Screen X', 'Screen Y'] outs ['World Near', 'World Far'] execs [] */
+ OP_SCREEN_SIZE, /* 220: ins [] outs ['Width', 'Height'] execs [] */
+ OP_ACCELEROMETER, /* 224: ins [] outs ['Direction'] execs [] */
+ OP_WORLD_TO_SCREEN, /* 477: ins ['World Pos'] outs ['Screen X', 'Screen Y'] execs [] */
+ OP_CURRENT_FRAME, /* 564: ins [] outs ['Counter'] execs [] */
+ OP_RAYCAST, /* 228: ins ['From', 'To'] outs ['Hit?', 'Hit Pos', 'Hit Obj'] execs [] */
+ OP_GET_POSITION, /* 278: ins ['Object'] outs ['Position', 'Rotation'] execs [] */
+ OP_GET_VELOCITY, /* 288: ins ['Object'] outs ['Velocity', 'Spin'] execs [] */
+ OP_GET_SIZE, /* 489: ins ['Object'] outs ['Min', 'Max'] execs [] */
+ OP_IF, /* 234: ins ['Condition'] outs [] execs ['True', 'False'] */
+ OP_PLAY_SENSOR, /* 238: ins [] outs [] execs ['On Play'] */
+ OP_TOUCH_SENSOR, /* 242: ins [] outs ['Screen X', 'Screen Y'] execs ['Touched'] */
+ OP_SWIPE_SENSOR, /* 248: ins [] outs ['Direction'] execs ['Swiped'] */
+ OP_LATE_UPDATE, /* 566: ins [] outs [] execs ['After Physics'] */
+ OP_BOX_ART_SENSOR, /* 409: ins [] outs [] execs ['On Screenshot'] */
+ OP_BUTTON, /* 588: ins [] outs [] execs ['Button'] */
+ OP_JOYSTICK, /* 592: ins [] outs ['Joy Dir'] execs [] */
+ OP_COLLISION, /* 401: ins ['1st Object'] outs ['2nd Object', 'Impulse', 'Normal'] execs ['Collided'] */
+ OP_LOOP, /* 560: ins ['Start', 'Stop'] outs ['Counter'] execs ['Do'] */
+ OP_WIN, /* 252: ins [] outs [] execs [] */
+ OP_LOSE, /* 256: ins [] outs [] execs [] */
+ OP_SET_SCORE, /* 260: ins ['Score', 'Coins'] outs [] execs [] */
+ OP_SET_CAMERA, /* 268: ins ['Position', 'Rotation', 'Range'] outs [] execs [] */
+ OP_SET_LIGHT, /* 274: ins ['Position', 'Rotation'] outs [] execs [] */
+ OP_SET_POSITION, /* 282: ins ['Object', 'Position', 'Rotation'] outs [] execs [] */
+ OP_SET_VELOCITY, /* 292: ins ['Object', 'Velocity', 'Spin'] outs [] execs [] */
+ OP_ADD_FORCE, /* 298: ins ['Object', 'Force', 'Apply at', 'Torque'] outs [] execs [] */
+ OP_SET_VISIBLE, /* 306: ins ['Object', 'Visible'] outs [] execs [] */
+ OP_SET_LOCKED, /* 310: ins ['Object', 'Position', 'Rotation'] outs [] execs [] */
+ OP_CREATE_OBJECT, /* 316: ins ['Object'] outs ['Copy'] execs [] */
+ OP_DESTROY_OBJECT, /* 320: ins ['Object'] outs [] execs [] */
+ OP_SET_GRAVITY, /* 324: ins ['Gravity'] outs [] execs [] */
+ OP_SET_MASS, /* 328: ins ['Object', 'Mass'] outs [] execs [] */
+ OP_SET_FRICTION, /* 332: ins ['Object', 'Friction'] outs [] execs [] */
+ OP_SET_BOUNCINESS, /* 336: ins ['Object', 'Bounciness'] outs [] execs [] */
+ OP_ADD_CONSTRAINT, /* 340: ins ['Base', 'Part', 'Pivot'] outs ['Constraint'] execs [] */
+ OP_LINEAR_LIMITS, /* 346: ins ['Constraint', 'Lower', 'Upper'] outs [] execs [] */
+ OP_ANGULAR_LIMITS, /* 352: ins ['Constraint', 'Lower', 'Upper'] outs [] execs [] */
+ OP_LINEAR_SPRING, /* 358: ins ['Constraint', 'Stiffness', 'Damping'] outs [] execs [] */
+ OP_ANGULAR_SPRING, /* 364: ins ['Constraint', 'Stiffness', 'Damping'] outs [] execs [] */
+ OP_LINEAR_MOTOR, /* 370: ins ['Constraint', 'Speed', 'Force'] outs [] execs [] */
+ OP_ANGULAR_MOTOR, /* 376: ins ['Constraint', 'Speed', 'Force'] outs [] execs [] */
+ OP_PLAY_SOUND, /* 264: ins ['Volume', 'Pitch'] outs ['Channel'] execs [] */
+ OP_VOLUME_PITCH, /* 391: ins ['Channel', 'Volume', 'Pitch'] outs [] execs [] */
+ OP_STOP_SOUND, /* 397: ins ['Channel'] outs [] execs [] */
+ OP_RANDOM_SEED, /* 485: ins ['Seed'] outs [] execs [] */
+ OP_INSPECT_16, /* 16: ins ['Number'] outs [] execs [] */
+ OP_INSPECT_20, /* 20: ins ['Vector'] outs [] execs [] */
+ OP_INSPECT_24, /* 24: ins ['Rotation'] outs [] execs [] */
+ OP_INSPECT_28, /* 28: ins ['Truth'] outs [] execs [] */
+ OP_INSPECT_32, /* 32: ins ['Object'] outs [] execs [] */
+ OP_CUSTOM,
+ OP_COUNT
+};
+
+/* per op: number of value inputs, value outputs, extra exec outputs, flags (1 = active) */
+static const unsigned char op_shape[OP_COUNT][4] = {
+ {0, 1, 0, 0}, /* Number */
+ {0, 1, 0, 0}, /* Vector */
+ {0, 1, 0, 0}, /* Rotation */
+ {0, 1, 0, 0}, /* True */
+ {0, 1, 0, 0}, /* False */
+ {0, 1, 0, 0}, /* Variable */
+ {0, 1, 0, 0}, /* Variable */
+ {0, 1, 0, 0}, /* Variable */
+ {0, 1, 0, 0}, /* Variable */
+ {0, 1, 0, 0}, /* Variable */
+ {0, 1, 0, 0}, /* Variable */
+ {1, 0, 0, 1}, /* Set Variable */
+ {1, 0, 0, 1}, /* Set Variable */
+ {1, 0, 0, 1}, /* Set Variable */
+ {1, 0, 0, 1}, /* Set Variable */
+ {1, 0, 0, 1}, /* Set Variable */
+ {1, 0, 0, 1}, /* Set Variable */
+ {2, 0, 0, 1}, /* Set Number */
+ {2, 0, 0, 1}, /* Set Vector */
+ {2, 0, 0, 1}, /* Set Rotation */
+ {2, 0, 0, 1}, /* Set Truth */
+ {2, 0, 0, 1}, /* Set Object */
+ {2, 0, 0, 1}, /* Set Constraint */
+ {2, 1, 0, 0}, /* List Number */
+ {2, 1, 0, 0}, /* List Object */
+ {2, 1, 0, 0}, /* List Vector */
+ {2, 1, 0, 0}, /* List Rotation */
+ {2, 1, 0, 0}, /* List Truth */
+ {2, 1, 0, 0}, /* List Constraint */
+ {1, 0, 0, 1}, /* Increase Number */
+ {1, 0, 0, 1}, /* Decrease Number */
+ {1, 1, 0, 0}, /* Negate */
+ {2, 1, 0, 0}, /* Add Numbers */
+ {2, 1, 0, 0}, /* Add Vectors */
+ {2, 1, 0, 0}, /* Subtract Numbers */
+ {2, 1, 0, 0}, /* Subtract Vectors */
+ {2, 1, 0, 0}, /* Multiply */
+ {2, 1, 0, 0}, /* Scale */
+ {2, 1, 0, 0}, /* Rotate */
+ {2, 1, 0, 0}, /* Combine */
+ {2, 1, 0, 0}, /* Divide */
+ {2, 1, 0, 0}, /* Less Than */
+ {2, 1, 0, 0}, /* Equals Numbers */
+ {2, 1, 0, 0}, /* Equals Vectors */
+ {2, 1, 0, 0}, /* Equals Objects */
+ {1, 1, 0, 0}, /* Not */
+ {2, 1, 0, 0}, /* AND */
+ {3, 1, 0, 0}, /* Make Vector */
+ {1, 3, 0, 0}, /* Break Vector */
+ {3, 1, 0, 0}, /* Make Rotation */
+ {2, 1, 0, 0}, /* Random */
+ {2, 1, 0, 0}, /* Modulo */
+ {2, 1, 0, 0}, /* Min */
+ {2, 1, 0, 0}, /* Max */
+ {1, 1, 0, 0}, /* Round */
+ {1, 1, 0, 0}, /* Floor */
+ {1, 1, 0, 0}, /* Ceiling */
+ {2, 1, 0, 0}, /* Distance */
+ {3, 1, 0, 0}, /* LERP */
+ {2, 1, 0, 0}, /* Axis Angle */
+ {2, 1, 0, 0}, /* Look Rotation */
+ {4, 1, 0, 0}, /* Line vs Plane */
+ {1, 1, 0, 0}, /* Sin */
+ {2, 1, 0, 0}, /* OR */
+ {2, 1, 0, 0}, /* Equals Truths */
+ {1, 1, 0, 0}, /* Inverse */
+ {1, 3, 0, 0}, /* Break Rotation */
+ {1, 1, 0, 0}, /* Cos */
+ {1, 1, 0, 0}, /* Absolute */
+ {2, 1, 0, 0}, /* Power */
+ {2, 1, 0, 0}, /* Greater Than */
+ {2, 1, 0, 0}, /* Dot Product */
+ {2, 1, 0, 0}, /* Cross Product */
+ {1, 1, 0, 0}, /* Normalize */
+ {2, 1, 0, 0}, /* Logarithm */
+ {2, 2, 0, 0}, /* Screen To World */
+ {0, 2, 0, 0}, /* Screen Size */
+ {0, 1, 0, 0}, /* Accelerometer */
+ {1, 2, 0, 0}, /* World To Screen */
+ {0, 1, 0, 0}, /* Current Frame */
+ {2, 3, 0, 0}, /* Raycast */
+ {1, 2, 0, 0}, /* Get Position */
+ {1, 2, 0, 0}, /* Get Velocity */
+ {1, 2, 0, 0}, /* Get Size */
+ {1, 0, 2, 1}, /* If */
+ {0, 0, 1, 1}, /* Play Sensor */
+ {0, 2, 1, 1}, /* Touch Sensor */
+ {0, 1, 1, 1}, /* Swipe Sensor */
+ {0, 0, 1, 1}, /* Late Update */
+ {0, 0, 1, 1}, /* Box Art Sensor */
+ {0, 0, 1, 1}, /* Button */
+ {0, 1, 0, 1}, /* Joystick */
+ {1, 3, 1, 1}, /* Collision */
+ {2, 1, 1, 1}, /* Loop */
+ {0, 0, 0, 1}, /* Win */
+ {0, 0, 0, 1}, /* Lose */
+ {2, 0, 0, 1}, /* Set Score */
+ {3, 0, 0, 1}, /* Set Camera */
+ {2, 0, 0, 1}, /* Set Light */
+ {3, 0, 0, 1}, /* Set Position */
+ {3, 0, 0, 1}, /* Set Velocity */
+ {4, 0, 0, 1}, /* Add Force */
+ {2, 0, 0, 1}, /* Set Visible */
+ {3, 0, 0, 1}, /* Set Locked */
+ {1, 1, 0, 1}, /* Create Object */
+ {1, 0, 0, 1}, /* Destroy Object */
+ {1, 0, 0, 1}, /* Set Gravity */
+ {2, 0, 0, 1}, /* Set Mass */
+ {2, 0, 0, 1}, /* Set Friction */
+ {2, 0, 0, 1}, /* Set Bounciness */
+ {3, 1, 0, 1}, /* Add Constraint */
+ {3, 0, 0, 1}, /* Linear Limits */
+ {3, 0, 0, 1}, /* Angular Limits */
+ {3, 0, 0, 1}, /* Linear Spring */
+ {3, 0, 0, 1}, /* Angular Spring */
+ {3, 0, 0, 1}, /* Linear Motor */
+ {3, 0, 0, 1}, /* Angular Motor */
+ {2, 1, 0, 1}, /* Play Sound */
+ {3, 0, 0, 1}, /* Volume Pitch */
+ {1, 0, 0, 1}, /* Stop Sound */
+ {1, 0, 0, 1}, /* Random Seed */
+ {1, 0, 0, 1}, /* Inspect Number */
+ {1, 0, 0, 1}, /* Inspect Vector */
+ {1, 0, 0, 1}, /* Inspect Rotation */
+ {1, 0, 0, 1}, /* Inspect Truth */
+ {1, 0, 0, 1}, /* Inspect Object */
+ {0, 0, 0, 1}, /* custom */
+};
+
+#endif
diff --git a/games/numdrive/src/pack.bin b/games/numdrive/src/pack.bin
new file mode 100644
index 00000000..5d790d81
Binary files /dev/null and b/games/numdrive/src/pack.bin differ
diff --git a/games/numdrive/src/pack_data.S b/games/numdrive/src/pack_data.S
new file mode 100644
index 00000000..0e209587
--- /dev/null
+++ b/games/numdrive/src/pack_data.S
@@ -0,0 +1,14 @@
+/* the game data pack produced by tools/pack.py */
+ .section .rodata.pack_data, "a"
+ .balign 4
+ .global pack_data
+pack_data:
+ .incbin "pack.bin"
+pack_end:
+ .balign 4
+ .global pack_size
+pack_size:
+ .word pack_end - pack_data
+#if defined(__linux__) && defined(__ELF__)
+ .section .note.GNU-stack, "", %progbits
+#endif
diff --git a/games/numdrive/src/physics.c b/games/numdrive/src/physics.c
new file mode 100644
index 00000000..1f1171ca
--- /dev/null
+++ b/games/numdrive/src/physics.c
@@ -0,0 +1,2120 @@
+/* 2D rigid body physics (motion in the xy plane, rotation about z) for Fancade objects.
+ * Collision shapes keep their z extents so only overlapping depth ranges interact. */
+#include <string.h>
+#ifdef HOST
+#include <stdlib.h>
+#endif
+#include "physics.h"
+#include "world.h"
+
+vec3 phys_gravity = {0, -9.8f, 0};
+
+#define DT (1.0f / PHYS_HZ)
+#define MAX_ELEMS 128 /* collision elements considered per body */
+#define MAX_CONTACTS 1024
+#define MAX_EVENTS 64
+#define ITER 10
+
+/* tunables (calibrated against the original game) */
+float k_mass_scale = 1.0f;
+float k_default_friction = 0.5f;
+float k_motor_scale = 60.0f; /* Fancade's Bullet takes the motor force as the impulse per 1/60 s step */
+float k_lin_motor_scale = 60.0f;
+float k_linear_damping = 0.0f;
+float k_angular_damping = 0.0f;
+
+typedef struct {
+ uint8_t circle;
+ float cx, cy; /* centre relative to com, in the body base frame (boxes are axis aligned there) */
+ float hx, hy; /* half extents (box) or radius in hx (circle) */
+ float z0, z1; /* z range relative to the com */
+} Elem;
+
+typedef struct Body {
+ int obj;
+ float invm, invi, mass, inertia;
+ float x, y, z; /* com */
+ float a; /* accumulated rotation about z (radians) */
+ quat rot; /* full orientation (object rotation) */
+ float m00, m01, m10, m11, m02, m12; /* xy rows of the rotation matrix */
+ float m20, m21, m22; /* z row */
+ float vx, vy, w;
+ float pvx, pvy, pw; /* split-impulse pseudo velocities (position correction only) */
+ float fx, fy, tq;
+ float lockx, locky, lockr; /* 1 free, 0 locked */
+ float vz, pvz, lockz; /* depth: only bodies free of joints and locks move in z */
+ vec3 spin3; /* extra free rotation (deg/s) about x,y for tumbling */
+ uint8_t nel;
+ uint8_t zmark; /* scratch: already shifted in z */
+ int16_t wgrp; /* scratch: bodies welded into one rigid assembly share it */
+ Elem *el;
+ float bound; /* bounding radius around com */
+ float zmin, zmax;
+} Body;
+
+typedef struct {
+ int16_t a, b; /* body indices; b may be -1 for static */
+ int16_t sobj; /* static object id when b == -1 */
+ uint8_t acirc; /* a touches with a circle: its lever reaches its own surface, p - n * depth */
+ uint8_t z3; /* a body that can move in z takes part: normal and friction in 3D (2: a ball
+ touches, which rolls across instead of sliding) */
+ float px, py; /* world contact point (on b's surface) */
+ float nx, ny; /* normal from a to b (pointing out of b into a) */
+ float nz, jz; /* z3 only: the normal's depth part, friction impulse along z */
+ float depth;
+ float mu, rest;
+ float jn, jt, jp;
+ float mn, mt, bias, pbias;
+ float rax, ray, rbx, rby;
+} Contact;
+
+/* last step's contact impulses, to start the solver from (Bullet's warm starting) */
+typedef struct {
+ int16_t a, o; /* body, other body (>= 0) or -2 - static object, -1 for the floor */
+ int16_t lx, ly; /* point in a's frame, 1/256 units */
+ float jn, jt;
+} Warm;
+
+/* springs and motors, allocated for the joints that get one */
+typedef struct {
+ float k[3], c[3]; /* spring stiffness and damping */
+ float mv[3], mf[3]; /* motor target velocity and max force */
+} JointExt;
+
+typedef struct {
+ int16_t a, b; /* body indices (a = base, -1 = static base object sobj), b = part, < 0 detached */
+ int16_t sobj; /* static base object (moves with Set Position), -1 = none */
+ uint8_t spring; /* bit k: dof k has a spring */
+ JointExt *ext;
+ vec3 la, lb; /* anchors in rest frames (relative to com) */
+ vec3 axx; /* base frame x axis in the base rest frame */
+ float ref; /* reference relative angle */
+ float lo[3], hi[3]; /* x, y, angle limits (lo > hi = free) */
+} Joint;
+
+/* solver state of one step, kept in the free arena with the contacts */
+typedef struct {
+ float accl[3]; /* accumulated limit / lock impulses */
+} JointTmp;
+typedef struct {
+ float acc[3], accm[3]; /* accumulated spring and motor impulses */
+ float spt[3], splo[3], sphi[3]; /* spring row target velocity and impulse range */
+} JointExtTmp;
+
+/* per level pools (arena) */
+static Body *bodies;
+static int nbodies, body_cap;
+static int nelems;
+static Contact *con; /* scratch space, valid during a step */
+static int ncon, con_cap;
+static Warm *warm;
+static int nwarm, warm_cap;
+static Joint *joints;
+static int njoints, joint_cap;
+static JointTmp *jtmp;
+static JointExtTmp *etmp;
+static struct { int16_t a, b; float imp; float nx, ny; } events[MAX_EVENTS];
+static int nevents;
+
+/* ---------------------------------------------------------------- raycast */
+static bool ray_box(vec3 o, vec3 d, vec3 mn, vec3 mx, float *tin) {
+ float t0 = -1e30f, t1 = 1e30f;
+ float oo[3] = {o.x, o.y, o.z}, dd[3] = {d.x, d.y, d.z}, a[3] = {mn.x, mn.y, mn.z}, b[3] = {mx.x, mx.y, mx.z};
+ for (int k = 0; k < 3; k++) {
+ if (fabsf(dd[k]) < 1e-12f) {
+ if (oo[k] < a[k] || oo[k] > b[k]) return false;
+ } else {
+ float inv = 1.0f / dd[k];
+ float ta = (a[k] - oo[k]) * inv, tb = (b[k] - oo[k]) * inv;
+ if (ta > tb) {
+ float t = ta;
+ ta = tb;
+ tb = t;
+ }
+ if (ta > t0) t0 = ta;
+ if (tb < t1) t1 = tb;
+ if (t0 > t1) return false;
+ }
+ }
+ /* a ray starting inside a box, or on its surface, does not hit it */
+ if (t1 < 0 || t0 <= 1e-5f) return false;
+ *tin = t0;
+ return true;
+}
+
+static bool ray_sphere(vec3 o, vec3 d, vec3 c, float r, float *tin) {
+ vec3 m = vsub(o, c);
+ float a = vdot(d, d), b = vdot(m, d), cc = vdot(m, m) - r * r;
+ if (cc < 0 || b > 0) return false;
+ float disc = b * b - a * cc;
+ if (disc < 0) return false;
+ *tin = (-b - sqrtf(disc)) / a;
+ return *tin >= 0;
+}
+
+static void part_sphere(const Block *b, int comp, uint32_t k, vec3 *c, float *r) {
+ const uint8_t *bb = b->bb + comp * 6;
+ float ex = (bb[3] - bb[0] + 1) * 0.5f, ey = (bb[4] - bb[1] + 1) * 0.5f;
+ *r = (ex > ey ? ex : ey) / 8.0f;
+ *c = v3(PK_X(k) + (bb[0] + bb[3] + 1) / 16.0f, PK_Y(k) + (bb[1] + bb[4] + 1) / 16.0f, PK_Z(k) + (bb[2] + bb[5] + 1) / 16.0f);
+}
+
+/* is the rest-space point inside a box collider of the shape? */
+static bool shape_solid_at(const Shape *sh, vec3 l) {
+ int cx = (int)floorf(l.x), cy = (int)floorf(l.y), cz = (int)floorf(l.z);
+ int pj = shape_find(sh, cx, cy, cz);
+ for (int j = pj; pj >= 0 && j < sh->np && (sh->key[j] & ~7u) == (sh->key[pj] & ~7u); j++) {
+ const Block *nb = blocks[sh->blk[j]];
+ if ((nb->flags & 3) != 1) continue;
+ const uint8_t *bb = nb->bb + PK_C(sh->key[j]) * 6;
+ float vx = (l.x - cx) * 8, vy = (l.y - cy) * 8, vz = (l.z - cz) * 8;
+ if (vx >= bb[0] && vx <= bb[3] + 1 && vy >= bb[1] && vy <= bb[4] + 1 && vz >= bb[2] && vz <= bb[5] + 1) return true;
+ }
+ return false;
+}
+
+static bool ray_part(const Shape *s, int pi, vec3 o, vec3 d, float *best) {
+ const Block *b = blocks[s->blk[pi]];
+ int coll = b->flags & 3;
+ if (!coll) return false;
+ uint32_t k = s->key[pi];
+ float cx = PK_X(k), cy = PK_Y(k), cz = PK_Z(k);
+ int comp = PK_C(k);
+ bool hit = false;
+ float t;
+ if (coll == 2) {
+ vec3 c;
+ float r;
+ part_sphere(b, comp, k, &c, &r);
+ if (ray_sphere(o, d, c, r, &t) && t < *best) {
+ *best = t;
+ hit = true;
+ }
+ return hit;
+ }
+ /* Fancade box colliders are the bounds of the block's voxels */
+ const uint8_t *bb = b->bb + comp * 6;
+ if (bb[0] > bb[3]) return false;
+ vec3 mn = v3(cx + bb[0] / 8.0f, cy + bb[1] / 8.0f, cz + bb[2] / 8.0f);
+ vec3 mx = v3(cx + (bb[3] + 1) / 8.0f, cy + (bb[4] + 1) / 8.0f, cz + (bb[5] + 1) / 8.0f);
+ if (ray_box(o, d, mn, mx, &t) && t < *best) {
+ /* entering through a face shared with another box of the object (Fancade merges them) */
+ float dl = sqrtf(vdot(d, d));
+ float e = dl > 1e-9f ? 0.01f / dl : 0;
+ if (shape_solid_at(s, t > e ? vadd(o, vscale(d, t - e)) : o)) return false;
+ *best = t;
+ hit = true;
+ }
+ return hit;
+}
+
+static bool ray_shape(const Shape *s, vec3 o, vec3 d, float *best) {
+ {
+ float t0 = 0, t1 = 1;
+ float oo[3] = {o.x, o.y, o.z}, dd[3] = {d.x, d.y, d.z}, a[3] = {s->bmin.x, s->bmin.y, s->bmin.z},
+ b[3] = {s->bmax.x, s->bmax.y, s->bmax.z};
+ for (int k = 0; k < 3; k++) {
+ if (fabsf(dd[k]) < 1e-12f) {
+ if (oo[k] < a[k] || oo[k] > b[k]) return false;
+ } else {
+ float inv = 1.0f / dd[k];
+ float ta = (a[k] - oo[k]) * inv, tb = (b[k] - oo[k]) * inv;
+ if (ta > tb) {
+ float tt = ta;
+ ta = tb;
+ tb = tt;
+ }
+ if (ta > t0) t0 = ta;
+ if (tb < t1) t1 = tb;
+ if (t0 > t1) return false;
+ }
+ }
+ }
+ bool hit = false;
+ if (s->np <= 24) {
+ for (int i = 0; i < s->np; i++)
+ if (ray_part(s, i, o, d, best)) hit = true;
+ return hit;
+ }
+ int x = (int)floorf(o.x), y = (int)floorf(o.y), z = (int)floorf(o.z);
+ int sx = d.x > 0 ? 1 : -1, sy = d.y > 0 ? 1 : -1, sz = d.z > 0 ? 1 : -1;
+ float tdx = fabsf(d.x) > 1e-12f ? fabsf(1.0f / d.x) : 1e30f;
+ float tdy = fabsf(d.y) > 1e-12f ? fabsf(1.0f / d.y) : 1e30f;
+ float tdz = fabsf(d.z) > 1e-12f ? fabsf(1.0f / d.z) : 1e30f;
+ float tmx = tdx < 1e29f ? ((sx > 0 ? x + 1 - o.x : o.x - x) * tdx) : 1e30f;
+ float tmy = tdy < 1e29f ? ((sy > 0 ? y + 1 - o.y : o.y - y) * tdy) : 1e30f;
+ float tmz = tdz < 1e29f ? ((sz > 0 ? z + 1 - o.z : o.z - z) * tdz) : 1e30f;
+ float tcur = 0;
+ int bz = tdz > 1e29f && fabsf(o.z - roundf(o.z)) < 1e-5f;
+ int by = tdy > 1e29f && fabsf(o.y - roundf(o.y)) < 1e-5f;
+ for (int guard = 0; guard < 4096; guard++) {
+ if (tcur > *best || tcur > 1.0f) break;
+ for (int dz = 0; dz <= bz; dz++)
+ for (int dy = 0; dy <= by; dy++) {
+ int pi = shape_find(s, x, y - dy, z - dz);
+ if (pi < 0) continue;
+ for (int j = pi; j < s->np && (s->key[j] & ~7u) == (s->key[pi] & ~7u); j++)
+ if (ray_part(s, j, o, d, best)) hit = true;
+ }
+ if (tmx < tmy && tmx < tmz) {
+ tcur = tmx;
+ tmx += tdx;
+ x += sx;
+ } else if (tmy < tmz) {
+ tcur = tmy;
+ tmy += tdy;
+ y += sy;
+ } else {
+ tcur = tmz;
+ tmz += tdz;
+ z += sz;
+ }
+ if (tcur > 1e29f) break;
+ }
+ return hit;
+}
+
+bool phys_raycast_ex(vec3 from, vec3 to, vec3 *hit, int *obj, int ignore) {
+ float best = 1.0f;
+ int bo = -1;
+ vec3 seg = vsub(to, from);
+ float sl = vdot(seg, seg), isl = sl > 1e-12f ? 1.0f / sl : 0;
+ for (int i = 0; i < nobj; i++) {
+ Obj *ob = &objs[i];
+ if (!(ob->flags & OF_COLLIDE) || (ob->flags & OF_DEAD) || i == ignore) continue;
+ /* quick reject: the segment misses the sphere around the object's bounds */
+ const Shape *sh = ob->shape;
+ vec3 lo = vsub(sh->bmin, sh->origin), hi = vsub(sh->bmax, sh->origin);
+ vec3 ext = v3(fmaxf(-lo.x, hi.x), fmaxf(-lo.y, hi.y), fmaxf(-lo.z, hi.z));
+ vec3 rel = vsub(ob->pos, from);
+ float u = clampf(vdot(rel, seg) * isl, 0, 1);
+ vec3 dd = vsub(rel, vscale(seg, u));
+ if (vdot(dd, dd) > vdot(ext, ext) * 1.0001f + 1e-4f) continue;
+ vec3 o = obj_local(ob, from), t = obj_local(ob, to);
+ float b = best;
+ if (ray_shape(ob->shape, o, vsub(t, o), &b) && b < best) {
+ best = b;
+ bo = i;
+ }
+ }
+ if (bo < 0) return false;
+ *hit = vadd(from, vscale(vsub(to, from), best));
+ *obj = bo;
+ return true;
+}
+
+bool phys_raycast(vec3 from, vec3 to, vec3 *hit, int *obj) { return phys_raycast_ex(from, to, hit, obj, -1); }
+
+/* ----------------------------------------------------------------- bodies */
+static inline float cross2(float ax, float ay, float bx, float by) { return ax * by - ay * bx; }
+
+static void body_matrix(Body *b) {
+ quat q = b->rot;
+ float xx = q.x * q.x, yy = q.y * q.y, zz = q.z * q.z, xy = q.x * q.y, xz = q.x * q.z, yz = q.y * q.z;
+ float wx = q.w * q.x, wy = q.w * q.y, wz = q.w * q.z;
+ b->m00 = 1 - 2 * (yy + zz);
+ b->m01 = 2 * (xy - wz);
+ b->m02 = 2 * (xz + wy);
+ b->m10 = 2 * (xy + wz);
+ b->m11 = 1 - 2 * (xx + zz);
+ b->m12 = 2 * (yz - wx);
+ b->m20 = 2 * (xz - wy);
+ b->m21 = 2 * (yz + wx);
+ b->m22 = 1 - 2 * (xx + yy);
+}
+
+static void sync_obj(Body *b) {
+ Obj *o = &objs[b->obj];
+ o->rot = b->rot;
+ vec3 comw = v3(b->x, b->y, b->z);
+ o->pos = vsub(comw, qrot(o->rot, vsub(o->shape->com, o->shape->origin)));
+}
+
+static void sync_body(Body *b) {
+ Obj *o = &objs[b->obj];
+ b->rot = o->rot;
+ body_matrix(b);
+ vec3 c = obj_world(o, o->shape->com);
+ b->x = c.x;
+ b->y = c.y;
+ b->z = c.z;
+}
+
+/* add collision elements for a shape, expressed in the body base frame relative to the com */
+static bool build_elems(Body *b) {
+ Obj *o = &objs[b->obj];
+ const Shape *s = o->shape;
+ int cap = 0;
+ for (int i = 0; i < s->np; i++) {
+ const Block *bk = blocks[s->blk[i]];
+ if (bk->flags & 3) cap++;
+ }
+ if (cap > 255) cap = 255;
+ uint32_t mark = arena_mark();
+ b->el = arena_alloc(sizeof(Elem) * (cap ? cap : 1));
+ if (!b->el) return false;
+ b->nel = 0;
+ for (int i = 0; i < s->np && b->nel < cap; i++) {
+ const Block *bk = blocks[s->blk[i]];
+ int coll = bk->flags & 3;
+ if (!coll) continue;
+ uint32_t k = s->key[i];
+ int comp = PK_C(k);
+ if (coll == 2) {
+ vec3 c;
+ float rad;
+ part_sphere(bk, comp, k, &c, &rad);
+ Elem *e = &b->el[b->nel++];
+ e->circle = 1;
+ e->cx = c.x - s->com.x;
+ e->cy = c.y - s->com.y;
+ e->hx = rad;
+ e->hy = rad;
+ e->z0 = c.z - s->com.z - rad;
+ e->z1 = c.z - s->com.z + rad;
+ continue;
+ }
+ const uint8_t *bb = bk->bb + comp * 6;
+ if (bb[0] > bb[3]) continue;
+ float mnx = PK_X(k) + bb[0] / 8.0f, mny = PK_Y(k) + bb[1] / 8.0f, mnz = PK_Z(k) + bb[2] / 8.0f;
+ float mxx = PK_X(k) + (bb[3] + 1) / 8.0f, mxy = PK_Y(k) + (bb[4] + 1) / 8.0f, mxz = PK_Z(k) + (bb[5] + 1) / 8.0f;
+ Elem *e = &b->el[b->nel++];
+ e->circle = 0;
+ e->cx = (mnx + mxx) * 0.5f - s->com.x;
+ e->cy = (mny + mxy) * 0.5f - s->com.y;
+ e->hx = (mxx - mnx) * 0.5f;
+ e->hy = (mxy - mny) * 0.5f;
+ e->z0 = mnz - s->com.z;
+ e->z1 = mxz - s->com.z;
+ }
+ /* merge boxes sharing an edge */
+ for (int i = 0; i < b->nel; i++) {
+ Elem *e = &b->el[i];
+ if (e->circle) continue;
+ for (int j = i + 1; j < b->nel; j++) {
+ Elem *f = &b->el[j];
+ if (f->circle || fabsf(e->z0 - f->z0) > 1e-4f || fabsf(e->z1 - f->z1) > 1e-4f) continue;
+ int merged = 0;
+ if (fabsf(e->cx - f->cx) < 1e-4f && fabsf(e->hx - f->hx) < 1e-4f && fabsf(fabsf(e->cy - f->cy) - (e->hy + f->hy)) < 1e-4f) {
+ float y0 = fminf(e->cy - e->hy, f->cy - f->hy), y1 = fmaxf(e->cy + e->hy, f->cy + f->hy);
+ e->cy = (y0 + y1) * 0.5f;
+ e->hy = (y1 - y0) * 0.5f;
+ merged = 1;
+ } else if (fabsf(e->cy - f->cy) < 1e-4f && fabsf(e->hy - f->hy) < 1e-4f && fabsf(fabsf(e->cx - f->cx) - (e->hx + f->hx)) < 1e-4f) {
+ float x0 = fminf(e->cx - e->hx, f->cx - f->hx), x1 = fmaxf(e->cx + e->hx, f->cx + f->hx);
+ e->cx = (x0 + x1) * 0.5f;
+ e->hx = (x1 - x0) * 0.5f;
+ merged = 1;
+ }
+ if (merged) {
+ *f = b->el[b->nel - 1];
+ b->nel--;
+ j = i;
+ }
+ }
+ }
+ arena_release(mark);
+ arena_alloc(sizeof(Elem) * (b->nel ? b->nel : 1)); /* keep only the merged elements */
+ nelems += b->nel;
+ b->bound = 0;
+ for (int i = 0; i < b->nel; i++) {
+ Elem *e = &b->el[i];
+ float cz = (e->z0 + e->z1) * 0.5f, hz = (e->z1 - e->z0) * 0.5f;
+ float r = sqrtf(e->cx * e->cx + e->cy * e->cy + cz * cz) + (e->circle ? e->hx : sqrtf(e->hx * e->hx + e->hy * e->hy + hz * hz));
+ if (r > b->bound) b->bound = r;
+ }
+ return true;
+}
+
+static void body_zrange(Body *b) {
+ b->zmin = 1e9f;
+ b->zmax = -1e9f;
+ for (int i = 0; i < b->nel; i++) {
+ const Elem *e = &b->el[i];
+ float cz = (e->z0 + e->z1) * 0.5f, hz = (e->z1 - e->z0) * 0.5f;
+ float zc = b->z + b->m20 * e->cx + b->m21 * e->cy + b->m22 * cz;
+ float ez = e->circle ? hz : fabsf(b->m20) * e->hx + fabsf(b->m21) * e->hy + fabsf(b->m22) * hz;
+ if (zc - ez < b->zmin) b->zmin = zc - ez;
+ if (zc + ez > b->zmax) b->zmax = zc + ez;
+ }
+}
+
+static void body_mass(Body *b) {
+ Obj *o = &objs[b->obj];
+ const Shape *s = o->shape;
+ b->mass = o->mass * k_mass_scale;
+ if (b->mass <= 0) b->mass = 0.01f;
+ /* Bullet's compound shape: the inertia of a solid box the size of the colliders' bounds */
+ float lo[3] = {1e9f, 1e9f, 1e9f}, hi[3] = {-1e9f, -1e9f, -1e9f};
+ for (int i = 0; i < s->np; i++) {
+ const Block *bk = blocks[s->blk[i]];
+ int coll = bk->flags & 3;
+ if (!coll) continue;
+ uint32_t k = s->key[i];
+ float a[3], c[3];
+ if (coll == 2) {
+ vec3 cc;
+ float r;
+ part_sphere(bk, PK_C(k), k, &cc, &r);
+ a[0] = cc.x - r, a[1] = cc.y - r, a[2] = cc.z - r, c[0] = cc.x + r, c[1] = cc.y + r, c[2] = cc.z + r;
+ } else {
+ const uint8_t *bb = bk->bb + PK_C(k) * 6;
+ if (bb[0] > bb[3]) continue;
+ int p[3] = {PK_X(k), PK_Y(k), PK_Z(k)};
+ for (int d = 0; d < 3; d++) a[d] = p[d] + bb[d] / 8.0f, c[d] = p[d] + (bb[d + 3] + 1) / 8.0f;
+ }
+ for (int d = 0; d < 3; d++) {
+ if (a[d] < lo[d]) lo[d] = a[d];
+ if (c[d] > hi[d]) hi[d] = c[d];
+ }
+ }
+ if (lo[0] > hi[0]) {
+ /* no colliders: the bounds of its voxels */
+ lo[0] = s->bmin.x, lo[1] = s->bmin.y, lo[2] = s->bmin.z;
+ hi[0] = s->bmax.x, hi[1] = s->bmax.y, hi[2] = s->bmax.z;
+ }
+ float lx = hi[0] - lo[0], ly = hi[1] - lo[1], lz = hi[2] - lo[2], k = b->mass / 12;
+ float ix = k * (ly * ly + lz * lz), iy = k * (lx * lx + lz * lz), iz = k * (lx * lx + ly * ly);
+ /* about the world z axis (the body may be turned about x or y) */
+ b->inertia = b->m20 * b->m20 * ix + b->m21 * b->m21 * iy + b->m22 * b->m22 * iz;
+ if (b->inertia < 1e-4f) b->inertia = 1e-4f;
+ b->invm = 1.0f / b->mass;
+ b->invi = 1.0f / b->inertia;
+}
+
+void phys_make_dynamic(int o) {
+ if (o < 0 || o >= nobj) return;
+ Obj *ob = &objs[o];
+ if ((ob->flags & OF_DYNAMIC) || (ob->flags & OF_DEAD)) return;
+ if (nbodies >= body_cap) {
+ OOM("bodies");
+ return;
+ }
+ Body *b = &bodies[nbodies];
+ memset(b, 0, sizeof *b);
+ b->obj = o;
+ sync_body(b);
+ b->lockx = (ob->lockp & 1) ? 1.0f : 0.0f;
+ b->locky = (ob->lockp & 2) ? 1.0f : 0.0f;
+ b->lockr = (ob->lockr & 4) ? 1.0f : 0.0f;
+ body_mass(b);
+ if (!build_elems(b)) return;
+ body_zrange(b);
+ ob->flags |= OF_DYNAMIC;
+ ob->body = (int16_t)nbodies++;
+ /* joints made while this object was static now pull on its body */
+ for (int ji = 0; ji < njoints; ji++) {
+ Joint *j = &joints[ji];
+ if (j->a >= 0 || j->sobj != o) continue;
+ vec3 w = obj_world(ob, j->la), ax = qrot(ob->rot, j->axx);
+ float a0 = atan2f(ax.y, ax.x);
+ j->a = ob->body;
+ j->sobj = -1;
+ j->la = qrot(qconj(b->rot), vsub(w, v3(b->x, b->y, b->z)));
+ j->axx = qrot(qconj(b->rot), ax);
+ j->ref += a0 - b->a;
+ }
+}
+
+static Body *body(int o) {
+ if (o < 0 || o >= nobj || !(objs[o].flags & OF_DYNAMIC)) return 0;
+ int bi = objs[o].body;
+ if (bi < 0 || bi >= nbodies || bodies[bi].obj != o) return 0;
+ return &bodies[bi];
+}
+
+#ifdef HOST
+#include <stdio.h>
+#include <stdlib.h>
+static float k_fmul = 1.0f;
+static void host_tunables(void) {
+ if (getenv("ND_KMOTOR")) k_motor_scale = atof(getenv("ND_KMOTOR"));
+ if (getenv("ND_KLMOTOR")) k_lin_motor_scale = atof(getenv("ND_KLMOTOR"));
+ if (getenv("ND_KMASS")) k_mass_scale = atof(getenv("ND_KMASS"));
+ if (getenv("ND_KFRIC")) k_default_friction = atof(getenv("ND_KFRIC"));
+ if (getenv("ND_FMUL")) k_fmul = atof(getenv("ND_FMUL"));
+}
+#endif
+
+void phys_reset(void) {
+#ifdef HOST
+ host_tunables();
+#endif
+ phys_gravity = v3(0, -9.8f, 0);
+ nbodies = body_cap = 0;
+ warm = 0;
+ nwarm = warm_cap = 0;
+ nelems = 0;
+ njoints = joint_cap = 0;
+ ncon = 0;
+ nevents = 0;
+}
+
+void phys_start(void) {
+ /* pools sized from the capacities measured for this level */
+ int nphys = 0;
+ for (int i = 0; i < nobj; i++)
+ if (objs[i].flags & OF_PHYSICS) nphys++;
+ body_cap = level.body_cap > nphys ? level.body_cap : nphys;
+ joint_cap = level.joint_cap;
+ bodies = arena_alloc(sizeof(Body) * (body_cap ? body_cap : 1));
+ joints = arena_alloc(sizeof(Joint) * (joint_cap ? joint_cap : 1));
+ if (!bodies || !joints) body_cap = joint_cap = 0;
+ for (int i = 0; i < nobj; i++) {
+ Obj *o = &objs[i];
+ if ((o->flags & OF_PHYSICS) && !(o->flags & (OF_TEMPLATE | OF_DEAD))) phys_make_dynamic(i);
+ }
+}
+
+void phys_get_velocity(int o, vec3 *vel, vec3 *spin) {
+ Body *b = body(o);
+ if (!b) {
+ *vel = v3(0, 0, 0);
+ *spin = v3(0, 0, 0);
+ return;
+ }
+ *vel = v3(b->vx, b->vy, 0);
+ *spin = v3(b->spin3.x, b->spin3.y, b->w * RAD2DEG);
+}
+
+/* like Fancade, physics blocks turn a plain object into a physics object */
+static Body *wake(int o) {
+ if (o >= 0 && o < nobj && !(objs[o].flags & (OF_DYNAMIC | OF_TEMPLATE | OF_DEAD))) {
+#ifdef HOST
+ if (getenv("ND_WAKE")) fprintf(stderr, "wake obj%d np=%d\n", o, objs[o].shape ? objs[o].shape->np : -1);
+#endif
+ phys_make_dynamic(o);
+ }
+ return body(o);
+}
+
+void phys_set_velocity(int o, const vec3 *vel, const vec3 *spin) {
+#ifdef HOST
+ if (getenv("ND_PDBG")) fprintf(stderr, "setvel obj%d v=%s(%.2f %.2f %.2f) w=%s(%.2f %.2f %.2f)\n", o, vel ? "" : "-", vel ? vel->x : 0, vel ? vel->y : 0, vel ? vel->z : 0, spin ? "" : "-", spin ? spin->x : 0, spin ? spin->y : 0, spin ? spin->z : 0);
+#endif
+ Body *b = wake(o);
+ if (!b) return;
+ if (vel) {
+ b->vx = vel->x;
+ b->vy = vel->y;
+ b->vz = vel->z;
+ }
+ if (spin) {
+ b->w = spin->z * DEG2RAD;
+ b->spin3.x = spin->x;
+ b->spin3.y = spin->y;
+ }
+}
+
+void phys_add_force(int o, const vec3 *f, const vec3 *at, const vec3 *t) {
+ Body *b = wake(o);
+#ifdef HOST
+ if (getenv("ND_FDBG")) fprintf(stderr, "force obj%d b=%d f=%s(%.2f,%.2f,%.2f) at=%s(%.2f,%.2f,%.2f) t=%s\n", o, b ? (int)(b - bodies) : -1, f ? "" : "-", f ? f->x : 0, f ? f->y : 0, f ? f->z : 0, at ? "" : "-", at ? at->x : 0, at ? at->y : 0, at ? at->z : 0, t ? "y" : "-");
+#endif
+ if (!b) return;
+ if (f) {
+ b->fx += f->x;
+ b->fy += f->y;
+ if (at) b->tq += cross2(at->x - b->x, at->y - b->y, f->x, f->y);
+ }
+ if (t) b->tq += t->z * DEG2RAD;
+}
+
+void phys_set_locked(int o, const vec3 *p, const vec3 *r) {
+#ifdef HOST
+ if (getenv("ND_PDBG")) fprintf(stderr, "setlocked obj%d p=%s(%.1f %.1f %.1f) r=%s(%.1f %.1f %.1f)\n", o, p ? "" : "-", p ? p->x : 0, p ? p->y : 0, p ? p->z : 0, r ? "" : "-", r ? r->x : 0, r ? r->y : 0, r ? r->z : 0);
+#endif
+ Obj *ob = &objs[o];
+ if (p) ob->lockp = (p->x != 0 ? 1 : 0) | (p->y != 0 ? 2 : 0) | (p->z != 0 ? 4 : 0);
+ if (r) ob->lockr = (r->x != 0 ? 1 : 0) | (r->y != 0 ? 2 : 0) | (r->z != 0 ? 4 : 0);
+ Body *b = wake(o);
+ if (!b) return;
+ b->lockx = (ob->lockp & 1) ? 1.0f : 0.0f;
+ b->locky = (ob->lockp & 2) ? 1.0f : 0.0f;
+ b->lockr = (ob->lockr & 4) ? 1.0f : 0.0f;
+ if (!b->lockx) b->vx = 0;
+ if (!b->locky) b->vy = 0;
+ if (!b->lockr) b->w = 0;
+}
+
+void phys_set_mass(int o, float m) {
+#ifdef HOST
+ if (getenv("ND_PDBG")) fprintf(stderr, "setmass obj%d %.3f\n", o, m);
+#endif
+#ifdef HOST
+ {
+ static float sm = -1;
+ if (sm < 0) sm = getenv("ND_SETMASS") ? atof(getenv("ND_SETMASS")) : 1;
+ m *= sm;
+ }
+#endif
+ objs[o].mass = m;
+ Body *b = wake(o);
+ if (b) body_mass(b);
+}
+void phys_set_friction(int o, float f) {
+#ifdef HOST
+ if (getenv("ND_PDBG")) fprintf(stderr, "setfriction obj%d %.3f\n", o, f);
+#endif
+ objs[o].mat = mat_find(f, obj_bounce(&objs[o]));
+}
+void phys_set_bounce(int o, float v) {
+#ifdef HOST
+ if (getenv("ND_PDBG")) fprintf(stderr, "setbounce obj%d %.3f\n", o, v);
+#endif
+ objs[o].mat = mat_find(obj_friction(&objs[o]), v);
+}
+void phys_set_gravity(vec3 g) { phys_gravity = g; }
+
+void phys_moved(int o) {
+ Body *b = body(o);
+ if (!b) return;
+ float m02 = b->m02, m12 = b->m12, m20 = b->m20, m21 = b->m21, z0 = b->z;
+ sync_body(b);
+ /* the joints hold depth: bodies jointed to a body moved in z go with it */
+ float dz = b->z - z0;
+ if (fabsf(dz) > 1e-4f) {
+ for (int i = 0; i < nbodies; i++) bodies[i].zmark = 0;
+ b->zmark = 1;
+ for (bool more = true; more;) {
+ more = false;
+ for (int ji = 0; ji < njoints; ji++) {
+ Joint *j = &joints[ji];
+ if (j->a < 0 || j->b < 0 || bodies[j->a].zmark == bodies[j->b].zmark) continue;
+ Body *m = bodies[j->a].zmark ? &bodies[j->b] : &bodies[j->a];
+ if (m->obj < 0) continue;
+ m->zmark = 1;
+ m->z += dz;
+ sync_obj(m);
+ body_zrange(m);
+ more = true;
+ }
+ }
+ body_zrange(b);
+ }
+ /* turned about x or y: the inertia about the plane normal changes */
+ if (fabsf(m02 - b->m02) + fabsf(m12 - b->m12) + fabsf(m20 - b->m20) + fabsf(m21 - b->m21) > 1e-3f) {
+ body_mass(b);
+ body_zrange(b);
+ }
+}
+
+/* hiding an object takes it out of the physics world, which drops its constraints */
+void phys_hidden(int o) {
+ Body *b = body(o);
+ int bi = b ? (int)(b - bodies) : -2;
+ for (int j = 0; j < njoints; j++)
+ if (joints[j].a == bi || joints[j].b == bi || (joints[j].a < 0 && joints[j].sobj == o)) joints[j].b = -2;
+}
+
+void phys_destroyed(int o) {
+ Body *b = body(o);
+ if (!b) return;
+ int bi = (int)(b - bodies);
+ /* detach joints */
+ for (int j = 0; j < njoints; j++)
+ if (joints[j].a == bi || joints[j].b == bi) joints[j].b = -2;
+ b->obj = -1;
+ objs[o].body = -1;
+}
+
+/* ----------------------------------------------------------------- joints */
+int phys_add_constraint(int base, int part, vec3 pivot) {
+ if (njoints >= joint_cap) {
+ OOM("joints");
+ return -1;
+ }
+ /* like Fancade, a constraint needs a base object */
+ if (base < 0 || base >= nobj || part < 0 || part >= nobj || base == part) return -1;
+ phys_make_dynamic(part);
+ Body *pb = body(part);
+ if (!pb) return -1;
+ Body *bb = body(base);
+ Joint *j = &joints[njoints];
+ memset(j, 0, sizeof *j);
+ j->b = (int16_t)(pb - bodies);
+ j->a = (int16_t)(bb ? (int)(bb - bodies) : -1);
+ j->sobj = (int16_t)(bb ? -1 : base);
+ if (bb) {
+ j->la = qrot(qconj(bb->rot), vsub(pivot, v3(bb->x, bb->y, bb->z)));
+ j->axx = qrot(qconj(bb->rot), v3(1, 0, 0));
+ j->ref = pb->a - bb->a;
+ } else {
+ /* static base: anchor kept in its rest frame so it follows the object when scripts move it */
+ Obj *so = &objs[base];
+ j->la = obj_local(so, pivot);
+ j->axx = qrot(qconj(so->rot), v3(1, 0, 0));
+ vec3 ax = qrot(so->rot, j->axx);
+ j->ref = pb->a - atan2f(ax.y, ax.x);
+ }
+ j->lb = qrot(qconj(pb->rot), vsub(pivot, v3(pb->x, pb->y, pb->z)));
+ return njoints++;
+}
+
+void phys_con_limits(int c, bool ang, vec3 lo, vec3 hi) {
+ if (c < 0 || c >= njoints) return;
+ Joint *j = &joints[c];
+#ifdef HOST
+ if (getenv("ND_CDBG")) fprintf(stderr, "limits c%d %s lo=(%.3f %.3f %.3f) hi=(%.3f %.3f %.3f)\n", c, ang ? "ang" : "lin", lo.x, lo.y, lo.z, hi.x, hi.y, hi.z);
+#endif
+ if (ang) {
+ j->lo[2] = lo.z * DEG2RAD;
+ j->hi[2] = hi.z * DEG2RAD;
+ } else {
+ j->lo[0] = lo.x;
+ j->hi[0] = hi.x;
+ j->lo[1] = lo.y;
+ j->hi[1] = hi.y;
+ }
+}
+
+static JointExt *joint_ext(int c) {
+ if (c < 0 || c >= njoints) return 0;
+ Joint *j = &joints[c];
+ if (!j->ext) {
+ j->ext = arena_alloc(sizeof(JointExt));
+ if (j->ext) memset(j->ext, 0, sizeof(JointExt));
+ }
+ return j->ext;
+}
+
+void phys_con_spring(int c, bool ang, vec3 k, vec3 d) {
+ JointExt *x = joint_ext(c);
+ if (!x) return;
+#ifdef HOST
+ {
+ static float ks = -1, kd = -1;
+ if (ks < 0) ks = getenv("ND_KSPR") ? atof(getenv("ND_KSPR")) : 1, kd = getenv("ND_KDMP") ? atof(getenv("ND_KDMP")) : 1;
+ k = vscale(k, ks);
+ d = vscale(d, kd);
+ }
+#endif
+ Joint *j = &joints[c];
+ if (ang) {
+ x->k[2] = k.z;
+ x->c[2] = d.z;
+ j->spring = (uint8_t)((j->spring & 3) | (k.z > 0 || d.z > 0) << 2);
+ } else {
+ x->k[0] = k.x;
+ x->c[0] = d.x;
+ x->k[1] = k.y;
+ x->c[1] = d.y;
+ j->spring = (uint8_t)((j->spring & 4) | (k.x > 0 || d.x > 0) | (k.y > 0 || d.y > 0) << 1);
+ }
+}
+
+void phys_con_motor(int c, bool ang, vec3 v, vec3 f) {
+ JointExt *x = joint_ext(c);
+ if (!x) return;
+ if (ang) {
+ x->mv[2] = v.z * DEG2RAD;
+ x->mf[2] = fabsf(f.z) * k_motor_scale;
+ } else {
+ x->mv[0] = v.x;
+ x->mf[0] = fabsf(f.x) * k_lin_motor_scale;
+ x->mv[1] = v.y;
+ x->mf[1] = fabsf(f.y) * k_lin_motor_scale;
+ }
+}
+
+/* --------------------------------------------------------------- contacts */
+static int cur_a, cur_b, cur_sobj;
+static uint8_t cur_acirc, cur_bcirc;
+static float cur_mu, cur_rest;
+static float cur_zc; /* a body free in depth: its com's z in the static object's frame (else NAN) */
+
+static void add_contact(float px, float py, float nx, float ny, float depth) {
+ if (ncon >= con_cap) {
+ OOM("contacts");
+ return;
+ }
+ Contact *c = &con[ncon++];
+ memset(c, 0, sizeof *c);
+ c->a = cur_a;
+ c->b = cur_b;
+ c->sobj = cur_sobj;
+ c->acirc = cur_acirc | (cur_bcirc ? 2 : 0);
+ c->px = px;
+ c->py = py;
+ c->nx = nx;
+ c->ny = ny;
+ c->depth = depth;
+ c->mu = cur_mu;
+ c->rest = cur_rest;
+ c->z3 = bodies[cur_a].lockz != 0 || (cur_b >= 0 && bodies[cur_b].lockz != 0);
+ if (c->z3 && (cur_acirc || cur_bcirc)) c->z3 = 2;
+}
+
+/* world-space 2D element */
+typedef struct {
+ uint8_t circle;
+ float cx, cy, ux, uy, hx, hy, z0, z1;
+} WElem;
+
+static void elem_world(const Body *b, const Elem *e, WElem *w) {
+ float cz = (e->z0 + e->z1) * 0.5f, hz = (e->z1 - e->z0) * 0.5f;
+ w->circle = e->circle;
+ w->cx = b->x + b->m00 * e->cx + b->m01 * e->cy + b->m02 * cz;
+ w->cy = b->y + b->m10 * e->cx + b->m11 * e->cy + b->m12 * cz;
+ float zc = b->z + b->m20 * e->cx + b->m21 * e->cy + b->m22 * cz;
+ if (e->circle) {
+ w->ux = 1;
+ w->uy = 0;
+ w->hx = w->hy = e->hx;
+ w->z0 = zc - hz;
+ w->z1 = zc + hz;
+ return;
+ }
+ /* the box turned by any 3D rotation, as a rectangle in the plane: oriented along its x axis (or its
+ y axis turned a quarter when x points along z), extents of all three axes projected */
+ float ux = b->m00, uy = b->m10;
+ float l = sqrtf(ux * ux + uy * uy);
+ if (l < 0.5f) {
+ ux = b->m11;
+ uy = -b->m01;
+ l = sqrtf(ux * ux + uy * uy);
+ }
+ if (l < 1e-4f) {
+ ux = 1;
+ uy = 0;
+ } else {
+ ux /= l;
+ uy /= l;
+ }
+ w->ux = ux;
+ w->uy = uy;
+ w->hx = fabsf(b->m00 * ux + b->m10 * uy) * e->hx + fabsf(b->m01 * ux + b->m11 * uy) * e->hy + fabsf(b->m02 * ux + b->m12 * uy) * hz;
+ w->hy = fabsf(b->m10 * ux - b->m00 * uy) * e->hx + fabsf(b->m11 * ux - b->m01 * uy) * e->hy + fabsf(b->m12 * ux - b->m02 * uy) * hz;
+ float ez = fabsf(b->m20) * e->hx + fabsf(b->m21) * e->hy + fabsf(b->m22) * hz;
+ w->z0 = zc - ez;
+ w->z1 = zc + ez;
+}
+
+/* contacts between circle A and circle B, normal points from B to A */
+static void col_cc(const WElem *a, const WElem *b) {
+ float dx = a->cx - b->cx, dy = a->cy - b->cy, r = a->hx + b->hx;
+ float d2 = dx * dx + dy * dy;
+ if (d2 >= r * r) return;
+ float d = sqrtf(d2);
+ float nx = d > 1e-6f ? dx / d : 0, ny = d > 1e-6f ? dy / d : 1;
+ add_contact(b->cx + nx * b->hx, b->cy + ny * b->hx, nx, ny, r - d);
+}
+
+/* circle A vs box B, normal from B to A */
+static void col_cb(const WElem *a, const WElem *b, bool flip) {
+ float dx = a->cx - b->cx, dy = a->cy - b->cy;
+ float vx = b->uy * -1, vy = b->ux; /* box y axis */
+ float lx = dx * b->ux + dy * b->uy, ly = dx * vx + dy * vy;
+ float qx = clampf(lx, -b->hx, b->hx), qy = clampf(ly, -b->hy, b->hy);
+ float nx, ny, depth;
+ if (lx == qx && ly == qy) {
+ /* centre inside: push out along smallest penetration */
+ float px = b->hx - fabsf(lx), py = b->hy - fabsf(ly);
+ if (px < py) {
+ nx = lx > 0 ? 1 : -1;
+ ny = 0;
+ depth = px + a->hx;
+ qx = lx > 0 ? b->hx : -b->hx;
+ } else {
+ nx = 0;
+ ny = ly > 0 ? 1 : -1;
+ depth = py + a->hx;
+ qy = ly > 0 ? b->hy : -b->hy;
+ }
+ } else {
+ float ex = lx - qx, ey = ly - qy;
+ float d2 = ex * ex + ey * ey;
+ if (d2 >= a->hx * a->hx) return;
+ float d = sqrtf(d2);
+ nx = ex / d;
+ ny = ey / d;
+ depth = a->hx - d;
+ }
+ float wx = nx * b->ux + ny * vx, wy = nx * b->uy + ny * vy;
+ float px = b->cx + qx * b->ux + qy * vx, py = b->cy + qx * b->uy + qy * vy;
+ if (flip) add_contact(px - wx * depth, py - wy * depth, -wx, -wy, depth);
+ else add_contact(px, py, wx, wy, depth);
+}
+
+/* box A vs box B (SAT + clipping, Box2D-lite style). normal from B to A */
+static void col_bb(const WElem *A, const WElem *B) {
+ float ax[2][2] = {{A->ux, A->uy}, {-A->uy, A->ux}};
+ float bx[2][2] = {{B->ux, B->uy}, {-B->uy, B->ux}};
+ float ha[2] = {A->hx, A->hy}, hb[2] = {B->hx, B->hy};
+ float dx = A->cx - B->cx, dy = A->cy - B->cy;
+ float best = 1e30f;
+ int bi = -1;
+ float bnx = 0, bny = 0;
+ for (int k = 0; k < 4; k++) {
+ float nx = k < 2 ? ax[k][0] : bx[k - 2][0], ny = k < 2 ? ax[k][1] : bx[k - 2][1];
+ float ra = ha[0] * fabsf(ax[0][0] * nx + ax[0][1] * ny) + ha[1] * fabsf(ax[1][0] * nx + ax[1][1] * ny);
+ float rb = hb[0] * fabsf(bx[0][0] * nx + bx[0][1] * ny) + hb[1] * fabsf(bx[1][0] * nx + bx[1][1] * ny);
+ float d = dx * nx + dy * ny;
+ float sep = fabsf(d) - (ra + rb);
+ if (sep > 0) return;
+ /* prefer B's axes slightly to stabilise resting on static boxes */
+ float score = -sep * (k >= 2 ? 0.98f : 1.0f);
+ if (score < best) {
+ best = score;
+ bi = k;
+ bnx = d < 0 ? -nx : nx;
+ bny = d < 0 ? -ny : ny;
+ }
+ }
+ /* reference box: the one owning the axis. incident: the other */
+ const WElem *ref = bi >= 2 ? B : A, *inc = bi >= 2 ? A : B;
+ float nx = bi >= 2 ? bnx : -bnx, ny = bi >= 2 ? bny : -bny; /* normal pointing from ref to inc */
+ /* incident edge: the edge of inc most anti-parallel to n */
+ float ix[2][2] = {{inc->ux, inc->uy}, {-inc->uy, inc->ux}};
+ float hi[2] = {inc->hx, inc->hy};
+ int ie = 0;
+ float mind = 1e30f;
+ for (int k = 0; k < 4; k++) {
+ float ex = (k & 1 ? -1 : 1) * ix[k >> 1][0], ey = (k & 1 ? -1 : 1) * ix[k >> 1][1];
+ float d = ex * nx + ey * ny;
+ if (d < mind) {
+ mind = d;
+ ie = k;
+ }
+ }
+ float fnx = (ie & 1 ? -1 : 1) * ix[ie >> 1][0], fny = (ie & 1 ? -1 : 1) * ix[ie >> 1][1];
+ float tnx = -fny, tny = fnx; /* along the face */
+ float fh = hi[ie >> 1], th = hi[1 - (ie >> 1)];
+ float c0x = inc->cx + fnx * fh + tnx * th, c0y = inc->cy + fny * fh + tny * th;
+ float c1x = inc->cx + fnx * fh - tnx * th, c1y = inc->cy + fny * fh - tny * th;
+ /* reference face */
+ float rx[2][2] = {{ref->ux, ref->uy}, {-ref->uy, ref->ux}};
+ float rh[2] = {ref->hx, ref->hy};
+ int ra = fabsf(rx[0][0] * nx + rx[0][1] * ny) > fabsf(rx[1][0] * nx + rx[1][1] * ny) ? 0 : 1;
+ float sideX = rx[1 - ra][0], sideY = rx[1 - ra][1], sideH = rh[1 - ra];
+ float faceD = (ref->cx * nx + ref->cy * ny) + rh[ra];
+ float cs = ref->cx * sideX + ref->cy * sideY;
+ /* clip against side planes */
+ float px[2] = {c0x, c1x}, py[2] = {c0y, c1y};
+ for (int side = 0; side < 2; side++) {
+ float sx = side ? -sideX : sideX, sy = side ? -sideY : sideY;
+ float off = (side ? -cs : cs) + sideH;
+ float d0 = px[0] * sx + py[0] * sy - off, d1 = px[1] * sx + py[1] * sy - off;
+ if (d0 > 0 && d1 > 0) return;
+ if (d0 > 0 || d1 > 0) {
+ float t = d0 / (d0 - d1);
+ float qx = px[0] + (px[1] - px[0]) * t, qy = py[0] + (py[1] - py[0]) * t;
+ if (d0 > 0) {
+ px[0] = qx;
+ py[0] = qy;
+ } else {
+ px[1] = qx;
+ py[1] = qy;
+ }
+ }
+ }
+ for (int k = 0; k < 2; k++) {
+ float sep = px[k] * nx + py[k] * ny - faceD;
+ if (sep <= 0.001f) {
+ /* contact point on inc; normal convention: from B to A */
+ if (ref == B) add_contact(px[k], py[k], nx, ny, -sep);
+ else add_contact(px[k] - nx * sep, py[k] - ny * sep, -nx, -ny, -sep);
+ }
+ }
+}
+
+static void collide_elems(const WElem *a, const WElem *b) {
+ if (a->z1 <= b->z0 + 1e-4f || b->z1 <= a->z0 + 1e-4f) return;
+ cur_acirc = a->circle;
+ cur_bcirc = b->circle;
+ if (a->circle && b->circle) col_cc(a, b);
+ else if (a->circle) col_cb(a, b, false);
+ else if (b->circle) col_cb(b, a, true);
+ else col_bb(a, b);
+}
+
+/* a box with half axes a, b, e (any 3D orientation) as a rectangle in the plane: its outline along
+ the axis that projects longest, and its z range */
+static void box_welem(vec3 c, vec3 a, vec3 b, vec3 e, WElem *w) {
+ float la = a.x * a.x + a.y * a.y, lb = b.x * b.x + b.y * b.y, le = e.x * e.x + e.y * e.y;
+ float ux = a.x, uy = a.y, l = la;
+ if (lb > l) ux = b.x, uy = b.y, l = lb;
+ if (le > l) ux = e.x, uy = e.y, l = le;
+ l = sqrtf(l);
+ if (l < 1e-6f) ux = 1, uy = 0;
+ else ux /= l, uy /= l;
+ w->circle = 0;
+ w->cx = c.x;
+ w->cy = c.y;
+ w->ux = ux;
+ w->uy = uy;
+ w->hx = fabsf(a.x * ux + a.y * uy) + fabsf(b.x * ux + b.y * uy) + fabsf(e.x * ux + e.y * uy);
+ w->hy = fabsf(a.y * ux - a.x * uy) + fabsf(b.y * ux - b.x * uy) + fabsf(e.y * ux - e.x * uy);
+ float hz = fabsf(a.z) + fabsf(b.z) + fabsf(e.z);
+ w->z0 = c.z - hz;
+ w->z1 = c.z + hz;
+}
+
+/* dynamic element vs a static object turned about x or y: its parts' outlines in world space */
+static void collide_static_3d(const WElem *we, int so) {
+ Obj *s = &objs[so];
+ const Shape *sh = s->shape;
+ vec3 ax = qrot(s->rot, v3(1, 0, 0)), ay = qrot(s->rot, v3(0, 1, 0)), az = qrot(s->rot, v3(0, 0, 1));
+ float ext = we->circle ? we->hx : sqrtf(we->hx * we->hx + we->hy * we->hy);
+ for (int i = 0; i < sh->np; i++) {
+ const Block *bk = blocks[sh->blk[i]];
+ int coll = bk->flags & 3;
+ if (!coll) continue;
+ uint32_t k = sh->key[i];
+ int comp = PK_C(k);
+ WElem se;
+ if (coll == 2) {
+ vec3 c;
+ float r;
+ part_sphere(bk, comp, k, &c, &r);
+ c = obj_world(s, c);
+ if (fabsf(c.x - we->cx) > r + ext || fabsf(c.y - we->cy) > r + ext) continue;
+ se.circle = 1;
+ se.cx = c.x;
+ se.cy = c.y;
+ se.hx = se.hy = r;
+ se.ux = 1;
+ se.uy = 0;
+ se.z0 = c.z - r;
+ se.z1 = c.z + r;
+ } else {
+ const uint8_t *bb = bk->bb + comp * 6;
+ if (bb[0] > bb[3]) continue;
+ float hx = (bb[3] + 1 - bb[0]) / 16.0f, hy = (bb[4] + 1 - bb[1]) / 16.0f, hz = (bb[5] + 1 - bb[2]) / 16.0f;
+ vec3 lc = v3(PK_X(k) + (bb[0] + bb[3] + 1) / 16.0f, PK_Y(k) + (bb[1] + bb[4] + 1) / 16.0f, PK_Z(k) + (bb[2] + bb[5] + 1) / 16.0f);
+ vec3 c = obj_world(s, lc);
+ float r = hx + hy + hz;
+ if (fabsf(c.x - we->cx) > r + ext || fabsf(c.y - we->cy) > r + ext) continue;
+ box_welem(c, vscale(ax, hx), vscale(ay, hy), vscale(az, hz), &se);
+ }
+ int before = ncon;
+ collide_elems(we, &se);
+ /* faces against another part of the object are internal */
+ float zm = (fmaxf(we->z0, se.z0) + fminf(we->z1, se.z1)) * 0.5f;
+ for (int c = before; c < ncon; c++) {
+ vec3 q = obj_local(s, v3(con[c].px + con[c].nx * 0.02f, con[c].py + con[c].ny * 0.02f, zm));
+ if (!shape_solid_at(sh, q)) continue;
+ con[c] = con[ncon - 1];
+ ncon--;
+ c--;
+ }
+ }
+}
+
+/* dynamic element vs static object parts */
+static void collide_static(Body *bd, const WElem *we, int so) {
+ Obj *s = &objs[so];
+ const Shape *sh = s->shape;
+ /* transform element into the static object's rest frame */
+ quat inv = qconj(s->rot);
+ vec3 cl = obj_local(s, v3(we->cx, we->cy, (we->z0 + we->z1) * 0.5f));
+ vec3 ul = qrot(inv, v3(we->ux, we->uy, 0));
+ float hz = (we->z1 - we->z0) * 0.5f;
+ /* in-plane check: static rotation must keep the xy plane */
+ vec3 zl = qrot(inv, v3(0, 0, 1));
+ if (fabsf(zl.z) < 0.99f) {
+ collide_static_3d(we, so);
+ return;
+ }
+ WElem le = *we;
+ le.cx = cl.x;
+ le.cy = cl.y;
+ float l = sqrtf(ul.x * ul.x + ul.y * ul.y);
+ le.ux = ul.x / l;
+ le.uy = ul.y / l;
+ le.z0 = cl.z - hz;
+ le.z1 = cl.z + hz;
+ float ext = we->circle ? we->hx : fabsf(le.ux) * we->hx + fabsf(le.uy) * we->hy;
+ float exty = we->circle ? we->hx : fabsf(le.uy) * we->hx + fabsf(le.ux) * we->hy;
+ int x0 = (int)floorf(cl.x - ext - 0.05f), x1 = (int)floorf(cl.x + ext + 0.05f);
+ int y0 = (int)floorf(cl.y - exty - 0.05f), y1 = (int)floorf(cl.y + exty + 0.05f);
+ int z0 = (int)floorf(le.z0), z1 = (int)floorf(le.z1 - 1e-4f);
+ if (x1 < 0 || y1 < 0 || z1 < 0) return;
+ if (x0 < 0) x0 = 0;
+ if (y0 < 0) y0 = 0;
+ if (z0 < 0) z0 = 0;
+ /* contacts are generated in local space; transform back */
+ int start = ncon;
+ for (int x = x0; x <= x1; x++)
+ for (int y = y0; y <= y1; y++)
+ for (int z = z0; z <= z1; z++) {
+ int pi = shape_find(sh, x, y, z);
+ if (pi < 0) continue;
+ for (int j = pi; j < sh->np && (sh->key[j] & ~7u) == (sh->key[pi] & ~7u); j++) {
+ const Block *bk = blocks[sh->blk[j]];
+ int coll = bk->flags & 3;
+ if (!coll) continue;
+ int comp = PK_C(sh->key[j]);
+ WElem se;
+ if (coll == 2) {
+ vec3 c;
+ float r;
+ part_sphere(bk, comp, sh->key[j], &c, &r);
+ /* a body free in depth rests only on parts under its com (past an edge it would tip off) */
+ if (fabsf(cur_zc - c.z) > r) continue;
+ se.circle = 1;
+ se.cx = c.x;
+ se.cy = c.y;
+ se.hx = r;
+ se.ux = 1;
+ se.uy = 0;
+ se.z0 = c.z - r;
+ se.z1 = c.z + r;
+ collide_elems(&le, &se);
+ continue;
+ }
+ /* Fancade box colliders are the bounds of the block's voxels */
+ const uint8_t *bbx = bk->bb + comp * 6;
+ if (bbx[0] > bbx[3]) continue;
+ float mnx = x + bbx[0] / 8.0f, mny = y + bbx[1] / 8.0f, mnz = z + bbx[2] / 8.0f;
+ float mxx = x + (bbx[3] + 1) / 8.0f, mxy = y + (bbx[4] + 1) / 8.0f, mxz = z + (bbx[5] + 1) / 8.0f;
+ if (cur_zc < mnz || cur_zc > mxz) continue;
+ se.circle = 0;
+ se.cx = (mnx + mxx) * 0.5f;
+ se.cy = (mny + mxy) * 0.5f;
+ se.ux = 1;
+ se.uy = 0;
+ se.hx = (mxx - mnx) * 0.5f;
+ se.hy = (mxy - mny) * 0.5f;
+ se.z0 = mnz;
+ se.z1 = mxz;
+ int before = ncon;
+ collide_elems(&le, &se);
+ /* faces shared with a neighbouring collider are internal: drop contacts pushing through them, and
+ at a corner where one of the two faces is internal, push along the other face only */
+ /* a sphere touches at its centre's depth; a box anywhere in the shared depth */
+ float qz = le.circle ? fminf(fmaxf((le.z0 + le.z1) * 0.5f, mnz), mxz) : (fmaxf(le.z0, mnz) + fminf(le.z1, mxz)) * 0.5f;
+ for (int c = before; c < ncon; c++) {
+ Contact *k = &con[c];
+ float nx = k->nx, ny = k->ny, px = k->px, py = k->py;
+ bool drop = false;
+ if (fabsf(nx) < 0.02f || fabsf(ny) < 0.02f) {
+ /* the point is on the body: sample the neighbour just past the collider's face, level with
+ the collider (never on its edges) */
+ if (fabsf(nx) < 0.02f) drop = shape_solid_at(sh, v3(fminf(fmaxf(px, mnx + 0.02f), mxx - 0.02f), (ny > 0 ? mxy : mny) + ny * 0.02f, qz));
+ else drop = shape_solid_at(sh, v3((nx > 0 ? mxx : mnx) + nx * 0.02f, fminf(fmaxf(py, mny + 0.02f), mxy - 0.02f), qz));
+ } else {
+ float sx = nx > 0 ? 1.0f : -1.0f, sy = ny > 0 ? 1.0f : -1.0f;
+ bool inx = shape_solid_at(sh, v3(px + sx * 0.02f, py, qz)), iny = shape_solid_at(sh, v3(px, py + sy * 0.02f, qz));
+ if (inx && iny) drop = true;
+ else if ((inx || iny) && le.circle) {
+ float r = le.hx, ccx = px + nx * (r - k->depth), ccy = py + ny * (r - k->depth);
+ float dep = iny ? r - (ccx - px) * sx : r - (ccy - py) * sy;
+ if (dep <= 0) drop = true;
+ else if (iny) k->nx = sx, k->ny = 0, k->py = ccy, k->depth = dep;
+ else k->nx = 0, k->ny = sy, k->px = ccx, k->depth = dep;
+ } else if (inx || iny) {
+ /* a box on a tiled surface: push along the surface's face, from the box's deepest corner */
+ float fx = iny ? sx : 0, fy = iny ? 0 : sy;
+ float face = fx > 0 ? mxx : fx < 0 ? -mnx : fy > 0 ? mxy : -mny;
+ float ex = fabsf(le.ux * fx + le.uy * fy) * le.hx + fabsf(-le.uy * fx + le.ux * fy) * le.hy;
+ float dep = face - ((le.cx * fx + le.cy * fy) - ex);
+ if (dep <= 0) drop = true;
+ else {
+ /* the corner of the box furthest against the face */
+ float ax = (le.ux * fx + le.uy * fy) > 0 ? -1.0f : 1.0f, ay = (-le.uy * fx + le.ux * fy) > 0 ? -1.0f : 1.0f;
+ float qx = le.cx + ax * le.hx * le.ux - ay * le.hy * le.uy, qy = le.cy + ax * le.hx * le.uy + ay * le.hy * le.ux;
+ k->nx = fx, k->ny = fy, k->depth = dep;
+ if (fx != 0) k->px = fx > 0 ? mxx : mnx, k->py = fminf(fmaxf(qy, mny), mxy);
+ else k->py = fy > 0 ? mxy : mny, k->px = fminf(fmaxf(qx, mnx), mxx);
+ }
+ }
+ }
+ if (drop) {
+ con[c] = con[ncon - 1];
+ ncon--;
+ c--;
+ }
+ }
+ }
+ }
+ /* transform new contacts back to world */
+ for (int c = start; c < ncon; c++) {
+ vec3 p = obj_world(s, v3(con[c].px, con[c].py, cl.z));
+ vec3 n = qrot(s->rot, v3(con[c].nx, con[c].ny, 0));
+ con[c].px = p.x;
+ con[c].py = p.y;
+ float l = sqrtf(n.x * n.x + n.y * n.y);
+ con[c].nx = n.x / l;
+ con[c].ny = n.y / l;
+ }
+ (void)bd;
+}
+
+static bool joined(int a, int b) {
+ /* parts welded into one assembly behave as one body: they never push each other apart */
+ if (bodies[a].wgrp == bodies[b].wgrp) return true;
+ for (int j = 0; j < njoints; j++)
+ if ((joints[j].a == a && joints[j].b == b) || (joints[j].a == b && joints[j].b == a)) return true;
+ return false;
+}
+
+static int wroot(int i) {
+ while (bodies[i].wgrp != i) i = bodies[i].wgrp = bodies[bodies[i].wgrp].wgrp;
+ return i;
+}
+
+static void weld_groups(void) {
+ for (int i = 0; i < nbodies; i++) bodies[i].wgrp = (int16_t)i;
+ for (int k = 0; k < njoints; k++) {
+ const Joint *j = &joints[k];
+ if (j->a < 0 || j->b < 0 || j->spring || j->lo[0] != j->hi[0] || j->lo[1] != j->hi[1] || j->lo[2] != j->hi[2]) continue;
+ int ra = wroot(j->a), rb = wroot(j->b);
+ if (ra != rb) bodies[ra].wgrp = (int16_t)rb;
+ }
+ for (int i = 0; i < nbodies; i++) bodies[i].wgrp = (int16_t)wroot(i);
+}
+
+/* like Bullet, a body does not collide with the static object its constraint is attached to */
+static bool joined_static(int bi, int s) {
+ for (int j = 0; j < njoints; j++)
+ if (joints[j].a < 0 && joints[j].sobj == s && joints[j].b == bi) return true;
+ return false;
+}
+
+static float mix_friction(float a, float b) {
+ float f = a * b; /* Bullet's combined friction */
+#ifdef HOST
+ f *= k_fmul;
+#endif
+ return f > 10 ? 10 : f;
+}
+
+/* is the world point inside a box collider of a static object other than skip? */
+static bool static_solid_at(vec3 w, int skip) {
+ for (int s = 0; s < nobj; s++) {
+ const Obj *os = &objs[s];
+ if (s == skip || (os->flags & (OF_DYNAMIC | OF_DEAD | OF_TEMPLATE | OF_COLLIDE | OF_VISIBLE)) != (OF_COLLIDE | OF_VISIBLE)) continue;
+ const Shape *sh = os->shape;
+ vec3 l = obj_local(os, w);
+ if (l.x < sh->bmin.x || l.y < sh->bmin.y || l.z < sh->bmin.z || l.x > sh->bmax.x || l.y > sh->bmax.y || l.z > sh->bmax.z) continue;
+ int cx = (int)floorf(l.x), cy = (int)floorf(l.y), cz = (int)floorf(l.z);
+ int pj = shape_find(sh, cx, cy, cz);
+ for (int j = pj; pj >= 0 && j < sh->np && (sh->key[j] & ~7u) == (sh->key[pj] & ~7u); j++) {
+ const Block *nb = blocks[sh->blk[j]];
+ if ((nb->flags & 3) != 1) continue;
+ const uint8_t *bb = nb->bb + PK_C(sh->key[j]) * 6;
+ float vx = (l.x - cx) * 8, vy = (l.y - cy) * 8, vz = (l.z - cz) * 8;
+ if (vx >= bb[0] && vx <= bb[3] + 1 && vy >= bb[1] && vy <= bb[4] + 1 && vz >= bb[2] && vz <= bb[5] + 1) return true;
+ }
+ }
+ return false;
+}
+
+/* bodies turned out of the plane are outlined generously in 2D: check their parts really meet in 3D */
+static bool tilted(const Body *b) { return fabsf(b->m20) > 1e-3f || fabsf(b->m21) > 1e-3f; }
+
+static void elem_frame(const Body *b, const Elem *e, float c[3], float u[3][3], float h[3]) {
+ float cz = (e->z0 + e->z1) * 0.5f;
+ c[0] = b->x + b->m00 * e->cx + b->m01 * e->cy + b->m02 * cz;
+ c[1] = b->y + b->m10 * e->cx + b->m11 * e->cy + b->m12 * cz;
+ c[2] = b->z + b->m20 * e->cx + b->m21 * e->cy + b->m22 * cz;
+ float m[3][3] = {{b->m00, b->m10, b->m20}, {b->m01, b->m11, b->m21}, {b->m02, b->m12, b->m22}};
+ memcpy(u, m, sizeof m);
+ h[0] = e->hx, h[1] = e->circle ? e->hx : e->hy, h[2] = (e->z1 - e->z0) * 0.5f;
+}
+
+/* do the parts really meet in 3D? n (when given) gets the axis of least overlap, pointing from B's part into
+ A's, and that overlap */
+static bool elems_meet3d(const Body *A, const Elem *ea, const Body *B, const Elem *eb, float n[4]) {
+ const float M = 0.05f;
+ float ca[3], ua[3][3], ha[3], cb[3], ub[3][3], hb[3];
+ elem_frame(A, ea, ca, ua, ha);
+ elem_frame(B, eb, cb, ub, hb);
+ float t[3] = {cb[0] - ca[0], cb[1] - ca[1], cb[2] - ca[2]};
+ if (ea->circle && eb->circle) {
+ float d = sqrtf(t[0] * t[0] + t[1] * t[1] + t[2] * t[2]), o = ha[0] + hb[0] - d;
+ if (d < 1e-6f) {
+ n[0] = 0, n[1] = 1, n[2] = 0, n[3] = o;
+ return true;
+ }
+ n[0] = -t[0] / d, n[1] = -t[1] / d, n[2] = -t[2] / d, n[3] = o;
+ return o > -M;
+ }
+ if (ea->circle || eb->circle) {
+ /* sphere against a box: the box's closest point */
+ const float(*u)[3] = ea->circle ? ub : ua;
+ const float *h = ea->circle ? hb : ha, *cs = ea->circle ? ca : cb, *cx = ea->circle ? cb : ca;
+ float r = ea->circle ? ha[0] : hb[0], q[3] = {cx[0], cx[1], cx[2]}, d2 = 0, best = 1e9f;
+ int bi = 0;
+ for (int i = 0; i < 3; i++) {
+ float p = (cs[0] - cx[0]) * u[i][0] + (cs[1] - cx[1]) * u[i][1] + (cs[2] - cx[2]) * u[i][2];
+ float cl = fminf(fmaxf(p, -h[i]), h[i]), e = fabsf(p) - h[i];
+ if (e > 0) d2 += e * e;
+ if (-e < best) best = -e, bi = i;
+ for (int k = 0; k < 3; k++) q[k] += cl * u[i][k];
+ }
+ if (d2 >= (r + M) * (r + M)) return false;
+ /* from the box to the sphere, then turned to point into A */
+ float v[3] = {cs[0] - q[0], cs[1] - q[1], cs[2] - q[2]}, d = sqrtf(d2), sg = ea->circle ? 1.0f : -1.0f, o = r - d;
+ if (d < 1e-6f) {
+ float p = (cs[0] - cx[0]) * u[bi][0] + (cs[1] - cx[1]) * u[bi][1] + (cs[2] - cx[2]) * u[bi][2];
+ for (int k = 0; k < 3; k++) v[k] = u[bi][k] * (p < 0 ? -1.0f : 1.0f);
+ d = 1, o = r + best;
+ }
+ n[0] = sg * v[0] / d, n[1] = sg * v[1] / d, n[2] = sg * v[2] / d, n[3] = o;
+ return true;
+ }
+ /* box against box: separating axes */
+ float R[3][3], AR[3][3], ta[3];
+ for (int i = 0; i < 3; i++) {
+ ta[i] = t[0] * ua[i][0] + t[1] * ua[i][1] + t[2] * ua[i][2];
+ for (int j = 0; j < 3; j++) {
+ R[i][j] = ua[i][0] * ub[j][0] + ua[i][1] * ub[j][1] + ua[i][2] * ub[j][2];
+ AR[i][j] = fabsf(R[i][j]) + 1e-5f;
+ }
+ }
+ float best = 1e9f, bd = 0, bl[3] = {0, 1, 0};
+ for (int i = 0; i < 3; i++) {
+ float o = ha[i] + hb[0] * AR[i][0] + hb[1] * AR[i][1] + hb[2] * AR[i][2] - fabsf(ta[i]);
+ if (o < -M) return false;
+ if (o < best) best = o, bd = ta[i], memcpy(bl, ua[i], sizeof bl);
+ }
+ for (int j = 0; j < 3; j++) {
+ float d = ta[0] * R[0][j] + ta[1] * R[1][j] + ta[2] * R[2][j];
+ float o = ha[0] * AR[0][j] + ha[1] * AR[1][j] + ha[2] * AR[2][j] + hb[j] - fabsf(d);
+ if (o < -M) return false;
+ if (o < best) best = o, bd = d, memcpy(bl, ub[j], sizeof bl);
+ }
+ for (int i = 0; i < 3; i++) {
+ int i1 = (i + 1) % 3, i2 = (i + 2) % 3;
+ for (int j = 0; j < 3; j++) {
+ int j1 = (j + 1) % 3, j2 = (j + 2) % 3;
+ float ra = ha[i1] * AR[i2][j] + ha[i2] * AR[i1][j], rb = hb[j1] * AR[i][j2] + hb[j2] * AR[i][j1];
+ float d = ta[i2] * R[i1][j] - ta[i1] * R[i2][j], o = ra + rb - fabsf(d);
+ if (o < -M) return false;
+ float l = sqrtf(fmaxf(1 - R[i][j] * R[i][j], 0));
+ /* edge against edge only when clearly the least: faces are steadier */
+ if (l > 1e-3f && o / l * 1.05f + 0.01f < best) {
+ best = o / l, bd = d;
+ bl[0] = (ua[i][1] * ub[j][2] - ua[i][2] * ub[j][1]) / l;
+ bl[1] = (ua[i][2] * ub[j][0] - ua[i][0] * ub[j][2]) / l;
+ bl[2] = (ua[i][0] * ub[j][1] - ua[i][1] * ub[j][0]) / l;
+ }
+ }
+ }
+ float sg = bd > 0 ? -1.0f : 1.0f;
+ n[0] = sg * bl[0], n[1] = sg * bl[1], n[2] = sg * bl[2], n[3] = best;
+ return true;
+}
+
+static void gen_contacts(void) {
+ ncon = 0;
+ weld_groups();
+ for (int i = 0; i < nbodies; i++) {
+ Body *A = &bodies[i];
+ if (A->obj < 0 || (objs[A->obj].flags & (OF_COLLIDE | OF_VISIBLE)) != (OF_COLLIDE | OF_VISIBLE)) continue;
+ Obj *oa = &objs[A->obj];
+ int first = ncon;
+ WElem wa[MAX_ELEMS];
+ int na = A->nel < MAX_ELEMS ? A->nel : MAX_ELEMS;
+ for (int e = 0; e < na; e++) elem_world(A, &A->el[e], &wa[e]);
+ /* static objects */
+ for (int s = 0; s < nobj; s++) {
+ Obj *os = &objs[s];
+ if ((os->flags & (OF_DYNAMIC | OF_DEAD | OF_TEMPLATE | OF_COLLIDE | OF_VISIBLE)) != (OF_COLLIDE | OF_VISIBLE)) continue;
+ if (joined_static(i, s)) continue;
+ /* AABB check in world */
+ const Shape *sh = os->shape;
+ vec3 c = obj_world(os, vscale(vadd(sh->bmin, sh->bmax), 0.5f));
+ vec3 h = vscale(vsub(sh->bmax, sh->bmin), 0.5f);
+ float r = sqrtf(h.x * h.x + h.y * h.y);
+ if (fabsf(c.x - A->x) > r + A->bound || fabsf(c.y - A->y) > r + A->bound) continue;
+ float zc = c.z, hz = fabsf(qrot(os->rot, v3(0, 0, 1)).z) * h.z + 1;
+ if (A->zmax < zc - hz || A->zmin > zc + hz) continue;
+ cur_a = i;
+ cur_b = -1;
+ cur_sobj = s;
+ cur_mu = mix_friction(obj_friction(oa), obj_friction(os));
+ cur_rest = obj_bounce(oa) * obj_bounce(os);
+ cur_zc = A->lockz ? obj_local(os, v3(A->x, A->y, A->z)).z : NAN;
+ for (int e = 0; e < na; e++) collide_static(A, &wa[e], s);
+ }
+ /* faces buried in another static object (overlapping track pieces) are internal too */
+ for (int c = first; c < ncon; c++) {
+ float zc = (A->zmin + A->zmax) * 0.5f;
+ if (!static_solid_at(v3(con[c].px + con[c].nx * 0.02f, con[c].py + con[c].ny * 0.02f, zc), con[c].sobj)) continue;
+ con[c] = con[ncon - 1];
+ ncon--;
+ c--;
+ }
+ /* Fancade's floor: an endless plane at y = 0 */
+ if (A->y - A->bound < 0) {
+ cur_a = i;
+ cur_b = -1;
+ cur_sobj = -1;
+ cur_mu = mix_friction(obj_friction(oa), 0.5f);
+ cur_rest = 0;
+ for (int e = 0; e < na; e++) {
+ const WElem *w = &wa[e];
+ cur_acirc = w->circle;
+ cur_bcirc = 0;
+ if (w->circle) {
+ if (w->cy < w->hx) add_contact(w->cx, 0, 0, 1, w->hx - w->cy);
+ continue;
+ }
+ for (int c = 0; c < 4; c++) {
+ float sx = c & 1 ? w->hx : -w->hx, sy = c & 2 ? w->hy : -w->hy;
+ float px = w->cx + w->ux * sx - w->uy * sy, py = w->cy + w->uy * sx + w->ux * sy;
+ if (py < 0) add_contact(px, 0, 0, 1, -py);
+ }
+ }
+ }
+ /* other bodies */
+ for (int j = i + 1; j < nbodies; j++) {
+ Body *B = &bodies[j];
+ if (B->obj < 0 || (objs[B->obj].flags & (OF_COLLIDE | OF_VISIBLE)) != (OF_COLLIDE | OF_VISIBLE)) continue;
+ float dx = B->x - A->x, dy = B->y - A->y, rr = A->bound + B->bound;
+ if (dx * dx + dy * dy > rr * rr) continue;
+ if (A->zmax <= B->zmin || B->zmax <= A->zmin) continue;
+ if (joined(i, j)) continue;
+ Obj *ob = &objs[B->obj];
+ cur_a = i;
+ cur_b = j;
+ cur_sobj = -1;
+ cur_mu = mix_friction(obj_friction(oa), obj_friction(ob));
+ cur_rest = obj_bounce(oa) * obj_bounce(ob);
+ WElem wb[MAX_ELEMS];
+ int nb = B->nel < MAX_ELEMS ? B->nel : MAX_ELEMS;
+ for (int e = 0; e < nb; e++) elem_world(B, &B->el[e], &wb[e]);
+ bool zf = A->lockz || B->lockz, t3 = zf || tilted(A) || tilted(B);
+ for (int e = 0; e < na; e++)
+ for (int f = 0; f < nb; f++) {
+ float n3[4];
+ if (!t3) collide_elems(&wa[e], &wb[f]);
+ else if (elems_meet3d(A, &A->el[e], B, &B->el[f], n3)) {
+ int before = ncon;
+ collide_elems(&wa[e], &wb[f]);
+ /* a part free to move in depth is pushed along the parts' real 3D normal */
+ if (zf && fabsf(n3[2]) > 0.1f)
+ for (int c = before; c < ncon; c++) con[c].nx = n3[0], con[c].ny = n3[1], con[c].nz = n3[2], con[c].depth = n3[3];
+ }
+ }
+ }
+ }
+}
+
+/* ----------------------------------------------------------------- solver */
+static inline void vel_at(const Body *b, float rx, float ry, float *vx, float *vy) {
+ *vx = b->vx - b->w * ry;
+ *vy = b->vy + b->w * rx;
+}
+
+static inline void apply(Body *b, float rx, float ry, float jx, float jy) {
+ b->vx += jx * b->invm * b->lockx;
+ b->vy += jy * b->invm * b->locky;
+ b->w += cross2(rx, ry, jx, jy) * b->invi * b->lockr;
+}
+
+static float eff_mass(const Body *a, float rax, float ray, const Body *b, float rbx, float rby, float nx, float ny) {
+ float k = 0;
+ if (a) {
+ float rn = cross2(rax, ray, nx, ny);
+ k += a->invm * (nx * nx * a->lockx + ny * ny * a->locky) + a->invi * a->lockr * rn * rn;
+ }
+ if (b) {
+ float rn = cross2(rbx, rby, nx, ny);
+ k += b->invm * (nx * nx * b->lockx + ny * ny * b->locky) + b->invi * b->lockr * rn * rn;
+ }
+ return k > 1e-9f ? 1.0f / k : 0;
+}
+
+/* contacts with a body free in depth: the normal and a second friction direction reach into z (bodies
+ still only turn about z) */
+static inline void apply3(Body *b, float rx, float ry, float jx, float jy, float jz) {
+ apply(b, rx, ry, jx, jy);
+ b->vz += jz * b->invm * b->lockz;
+}
+
+static float eff_mass3(const Body *a, float rax, float ray, const Body *b, float rbx, float rby, float nx, float ny, float nz) {
+ float k = 0;
+ if (a) {
+ float rn = cross2(rax, ray, nx, ny);
+ k += a->invm * (nx * nx * a->lockx + ny * ny * a->locky + nz * nz * a->lockz) + a->invi * a->lockr * rn * rn;
+ }
+ if (b) {
+ float rn = cross2(rbx, rby, nx, ny);
+ k += b->invm * (nx * nx * b->lockx + ny * ny * b->locky + nz * nz * b->lockz) + b->invi * b->lockr * rn * rn;
+ }
+ return k > 1e-9f ? 1.0f / k : 0;
+}
+
+/* the in-plane tangent and the one across it */
+static void tangents3(const Contact *c, float t1[3], float t2[3]) {
+ float l = sqrtf(c->nx * c->nx + c->ny * c->ny);
+ t1[0] = l > 1e-4f ? -c->ny / l : 1.0f, t1[1] = l > 1e-4f ? c->nx / l : 0.0f, t1[2] = 0;
+ t2[0] = -c->nz * t1[1], t2[1] = c->nz * t1[0], t2[2] = c->nx * t1[1] - c->ny * t1[0];
+}
+
+static void solve_contact3(Contact *c) {
+ Body *A = &bodies[c->a];
+ Body *B = c->b >= 0 ? &bodies[c->b] : 0;
+ float vax, vay, vbx = 0, vby = 0;
+ vel_at(A, c->rax, c->ray, &vax, &vay);
+ if (B) vel_at(B, c->rbx, c->rby, &vbx, &vby);
+ float d[3] = {vax - vbx, vay - vby, A->vz - (B ? B->vz : 0)};
+ float vn = d[0] * c->nx + d[1] * c->ny + d[2] * c->nz;
+ float dj = c->mn * (-vn + c->bias), j0 = c->jn;
+ c->jn = fmaxf(j0 + dj, 0);
+ dj = c->jn - j0;
+ apply3(A, c->rax, c->ray, c->nx * dj, c->ny * dj, c->nz * dj);
+ if (B) apply3(B, c->rbx, c->rby, -c->nx * dj, -c->ny * dj, -c->nz * dj);
+ float t[2][3], lim = c->mu * c->jn;
+ tangents3(c, t[0], t[1]);
+ for (int k = 0; k < (c->z3 == 2 ? 1 : 2); k++) {
+ const float *u = t[k];
+ vel_at(A, c->rax, c->ray, &vax, &vay);
+ if (B) vel_at(B, c->rbx, c->rby, &vbx, &vby);
+ float vt = (vax - vbx) * u[0] + (vay - vby) * u[1] + (A->vz - (B ? B->vz : 0)) * u[2];
+ float m = eff_mass3(A, c->rax, c->ray, B, c->rbx, c->rby, u[0], u[1], u[2]);
+ float *acc = k ? &c->jz : &c->jt, a0 = *acc;
+ *acc = clampf(a0 + m * -vt, -lim, lim);
+ float dt = *acc - a0;
+ apply3(A, c->rax, c->ray, u[0] * dt, u[1] * dt, u[2] * dt);
+ if (B) apply3(B, c->rbx, c->rby, -u[0] * dt, -u[1] * dt, -u[2] * dt);
+ }
+}
+
+static inline int warm_other(const Contact *c) { return c->b >= 0 ? c->b : c->sobj >= 0 ? -2 - c->sobj : -1; }
+
+static inline void warm_point(const Contact *c, int *lx, int *ly) {
+ const Body *A = &bodies[c->a];
+ float dx = c->px - A->x, dy = c->py - A->y;
+ float x = (A->m00 * dx + A->m10 * dy) * 256, y = (A->m01 * dx + A->m11 * dy) * 256;
+ *lx = x > 32767 ? 32767 : x < -32767 ? -32767 : (int)x;
+ *ly = y > 32767 ? 32767 : y < -32767 ? -32767 : (int)y;
+}
+
+/* start each contact from the impulses of the same contact last step (both lists run in body order) */
+static void warm_start(void) {
+ int w = 0;
+ for (int i = 0; i < ncon; i++) {
+ Contact *c = &con[i];
+ while (w < nwarm && warm[w].a < c->a) w++;
+ /* wheels keep the cold start their handling was matched with */
+ if (c->acirc) continue;
+ int o = warm_other(c), lx, ly;
+ warm_point(c, &lx, &ly);
+ for (int k = w; k < nwarm && warm[k].a == c->a; k++) {
+ Warm *m = &warm[k];
+ int dx = m->lx - lx, dy = m->ly - ly;
+ /* the same point: within Bullet's contact breaking threshold, 0.02 */
+ if (m->o != o || dx * dx + dy * dy > 5 * 5) continue;
+ c->jn = m->jn * 0.85f;
+ c->jt = m->jt * 0.85f;
+ m->o = -32768; /* used */
+ break;
+ }
+ }
+}
+
+static void warm_store(void) {
+ nwarm = 0;
+ for (int i = 0; i < ncon && nwarm < warm_cap; i++) {
+ const Contact *c = &con[i];
+ Warm *m = &warm[nwarm++];
+ int lx, ly;
+ warm_point(c, &lx, &ly);
+ m->a = c->a, m->o = (int16_t)warm_other(c), m->lx = (int16_t)lx, m->ly = (int16_t)ly;
+ m->jn = c->jn, m->jt = c->jt;
+ }
+}
+
+static void prep_contacts(void) {
+ for (int i = 0; i < ncon; i++) {
+ Contact *c = &con[i];
+ Body *A = &bodies[c->a];
+ Body *B = c->b >= 0 ? &bodies[c->b] : 0;
+ /* like Bullet, a wheel rolls on its full radius however deep it sits */
+ float sa = (c->acirc & 1) ? c->depth : 0;
+ c->rax = c->px - c->nx * sa - A->x;
+ c->ray = c->py - c->ny * sa - A->y;
+ if (B) {
+ c->rbx = c->px - B->x;
+ c->rby = c->py - B->y;
+ }
+ c->mn = c->z3 ? eff_mass3(A, c->rax, c->ray, B, c->rbx, c->rby, c->nx, c->ny, c->nz)
+ : eff_mass(A, c->rax, c->ray, B, c->rbx, c->rby, c->nx, c->ny);
+ c->mt = eff_mass(A, c->rax, c->ray, B, c->rbx, c->rby, -c->ny, c->nx);
+ float vax, vay, vbx = 0, vby = 0;
+ vel_at(A, c->rax, c->ray, &vax, &vay);
+ if (B) vel_at(B, c->rbx, c->rby, &vbx, &vby);
+ float vn = (vax - vbx) * c->nx + (vay - vby) * c->ny + (c->z3 ? (A->vz - (B ? B->vz : 0)) * c->nz : 0);
+ /* parts only near each other in 3D may close the gap first */
+ c->bias = c->z3 && c->depth < 0 ? c->depth / DT : 0;
+ c->pbias = 0.2f / DT * fmaxf(0, c->depth - 0.005f);
+ if (!c->acirc) {
+ /* between boxes, like Bullet: shallow penetration is pushed out in the velocity solve (erp 0.2),
+ deep with split impulses (erp2 0.8), and parts just apart may close their gap */
+ if (c->depth < 0) c->bias = c->depth / DT, c->pbias = 0;
+ else if (c->depth < 0.04f) c->bias = 0.2f * c->depth / DT, c->pbias = 0;
+ else c->bias = 0, c->pbias = 0.8f * c->depth / DT;
+ }
+ if (c->rest > 0 && vn < -1.0f) c->bias += -c->rest * vn;
+ if (c->jn > 0 || c->jt != 0) {
+ /* the warm start: last step's impulses, applied up front */
+ float jx = c->nx * c->jn - c->ny * c->jt, jy = c->ny * c->jn + c->nx * c->jt;
+ if (c->z3) {
+ float t[2][3];
+ tangents3(c, t[0], t[1]);
+ jx = c->nx * c->jn + t[0][0] * c->jt, jy = c->ny * c->jn + t[0][1] * c->jt;
+ apply3(A, c->rax, c->ray, jx, jy, c->nz * c->jn);
+ if (B) apply3(B, c->rbx, c->rby, -jx, -jy, -c->nz * c->jn);
+ } else {
+ apply(A, c->rax, c->ray, jx, jy);
+ if (B) apply(B, c->rbx, c->rby, -jx, -jy);
+ }
+ }
+ }
+}
+
+static void solve_contacts(void) {
+ for (int i = 0; i < ncon; i++) {
+ Contact *c = &con[i];
+ if (c->z3) {
+ solve_contact3(c);
+ continue;
+ }
+ Body *A = &bodies[c->a];
+ Body *B = c->b >= 0 ? &bodies[c->b] : 0;
+ float vax, vay, vbx = 0, vby = 0;
+ vel_at(A, c->rax, c->ray, &vax, &vay);
+ if (B) vel_at(B, c->rbx, c->rby, &vbx, &vby);
+ float dvx = vax - vbx, dvy = vay - vby;
+ /* normal */
+ float vn = dvx * c->nx + dvy * c->ny;
+ float dj = c->mn * (-vn + c->bias);
+ float jn0 = c->jn;
+ c->jn = fmaxf(jn0 + dj, 0);
+ dj = c->jn - jn0;
+ apply(A, c->rax, c->ray, c->nx * dj, c->ny * dj);
+ if (B) apply(B, c->rbx, c->rby, -c->nx * dj, -c->ny * dj);
+ /* friction */
+ vel_at(A, c->rax, c->ray, &vax, &vay);
+ if (B) vel_at(B, c->rbx, c->rby, &vbx, &vby);
+ float tx = -c->ny, ty = c->nx;
+ float vt = (vax - vbx) * tx + (vay - vby) * ty;
+ float dt = c->mt * -vt;
+ float lim = c->mu * c->jn;
+ float jt0 = c->jt;
+ c->jt = clampf(jt0 + dt, -lim, lim);
+ dt = c->jt - jt0;
+ apply(A, c->rax, c->ray, tx * dt, ty * dt);
+ if (B) apply(B, c->rbx, c->rby, -tx * dt, -ty * dt);
+ }
+}
+
+static inline void apply_p(Body *b, float rx, float ry, float jx, float jy) {
+ b->pvx += jx * b->invm * b->lockx;
+ b->pvy += jy * b->invm * b->locky;
+ b->pw += cross2(rx, ry, jx, jy) * b->invi * b->lockr;
+}
+
+/* split impulse: push penetrating contacts apart without adding kinetic energy */
+static void solve_split(void) {
+ for (int i = 0; i < ncon; i++) {
+ Contact *c = &con[i];
+ if (c->pbias <= 0) continue;
+ Body *A = &bodies[c->a];
+ Body *B = c->b >= 0 ? &bodies[c->b] : 0;
+ float vx = A->pvx - A->pw * c->ray, vy = A->pvy + A->pw * c->rax;
+ if (B) {
+ vx -= B->pvx - B->pw * c->rby;
+ vy -= B->pvy + B->pw * c->rbx;
+ }
+ float vn = vx * c->nx + vy * c->ny;
+ if (c->z3) vn += (A->pvz - (B ? B->pvz : 0)) * c->nz;
+ float dj = c->mn * (c->pbias - vn);
+ float j0 = c->jp;
+ c->jp = fmaxf(j0 + dj, 0);
+ dj = c->jp - j0;
+ apply_p(A, c->rax, c->ray, c->nx * dj, c->ny * dj);
+ if (B) apply_p(B, c->rbx, c->rby, -c->nx * dj, -c->ny * dj);
+ if (c->z3) {
+ A->pvz += c->nz * dj * A->invm * A->lockz;
+ if (B) B->pvz -= c->nz * dj * B->invm * B->lockz;
+ }
+ }
+}
+
+/* joints: solved per degree of freedom in the base frame */
+static inline void rot2(const Body *b, vec3 v, float *x, float *y) {
+ *x = b->m00 * v.x + b->m01 * v.y + b->m02 * v.z;
+ *y = b->m10 * v.x + b->m11 * v.y + b->m12 * v.z;
+}
+
+static void joint_frame(Joint *j, Body **pa, Body **pb, float *rax, float *ray, float *rbx, float *rby, float *axx,
+ float *axy, float *ex, float *ey, float *ang) {
+ Body *A = j->a >= 0 ? &bodies[j->a] : 0;
+ Body *B = &bodies[j->b];
+ *pa = A;
+ *pb = B;
+ float wax, way, cx, cy;
+ if (A) {
+ rot2(A, j->la, rax, ray);
+ wax = A->x + *rax;
+ way = A->y + *ray;
+ rot2(A, j->axx, &cx, &cy);
+ float l = sqrtf(cx * cx + cy * cy);
+ if (l > 1e-4f) {
+ cx /= l;
+ cy /= l;
+ } else {
+ cx = 1;
+ cy = 0;
+ }
+ } else {
+ *rax = *ray = 0;
+ const Obj *so = &objs[j->sobj];
+ vec3 w = obj_world(so, j->la), ax = qrot(so->rot, j->axx);
+ wax = w.x;
+ way = w.y;
+ float l = sqrtf(ax.x * ax.x + ax.y * ax.y);
+ cx = l > 1e-4f ? ax.x / l : 1;
+ cy = l > 1e-4f ? ax.y / l : 0;
+ }
+ rot2(B, j->lb, rbx, rby);
+ float wbx = B->x + *rbx, wby = B->y + *rby;
+ *axx = cx;
+ *axy = cy;
+ float dx = wbx - wax, dy = wby - way;
+ *ex = dx * cx + dy * cy;
+ *ey = -dx * cy + dy * cx;
+ *ang = B->a - (A ? A->a : atan2f(cy, cx)) - j->ref;
+}
+
+static void solve_joints(bool first) {
+ JointExtTmp *et = etmp;
+ for (int ji = 0; ji < njoints; ji++) {
+ Joint *j = &joints[ji];
+ JointExt *x = j->ext;
+ JointExtTmp *t = x ? et++ : 0;
+ JointTmp *jt = &jtmp[ji];
+ if (j->b < 0 || bodies[j->b].obj < 0 || (j->a >= 0 && bodies[j->a].obj < 0)) continue;
+ Body *A, *B;
+ float rax, ray, rbx, rby, cx, cy, ex, ey, ang;
+ joint_frame(j, &A, &B, &rax, &ray, &rbx, &rby, &cx, &cy, &ex, &ey, &ang);
+ float err[3] = {ex, ey, ang};
+ for (int k = 0; k < 3; k++) {
+ float nx = 0, ny = 0;
+ float m;
+ if (k < 2) {
+ nx = k == 0 ? cx : -cy;
+ ny = k == 0 ? cy : cx;
+ m = eff_mass(A, rax, ray, B, rbx, rby, nx, ny);
+ } else {
+ float ik = (A ? A->invi * A->lockr : 0) + B->invi * B->lockr;
+ m = ik > 1e-9f ? 1.0f / ik : 0;
+ }
+ if (m <= 0) continue;
+ /* relative velocity along dof (B relative to A) */
+ float rv;
+ if (k < 2) {
+ float vax = 0, vay = 0, vbx, vby;
+ if (A) vel_at(A, rax, ray, &vax, &vay);
+ vel_at(B, rbx, rby, &vbx, &vby);
+ rv = (vbx - vax) * nx + (vby - vay) * ny;
+ } else {
+ rv = B->w - (A ? A->w : 0);
+ }
+ float lo = j->lo[k], hi = j->hi[k];
+ bool free_ = lo > hi;
+ float imp = 0;
+ /* motor */
+ if (x && x->mf[k] > 0) {
+ float maxi = x->mf[k] * DT;
+ float d = m * (x->mv[k] - rv);
+ float old = t->accm[k];
+ t->accm[k] = clampf(old + d, -maxi, maxi);
+ imp += t->accm[k] - old;
+ rv += (t->accm[k] - old) / m;
+ }
+ /* spring: Bullet's 6DofSpring2 row, velocity target rv0 + f with the impulse clamped to f */
+ if (x && (j->spring >> k & 1) && (free_ || lo < hi)) {
+ if (first) {
+ /* Bullet limits stiff springs to what the time step can sample, and over-damping, by the lighter body */
+ float mr = 1.0f / B->invm;
+ if (A && A->mass < mr) mr = A->mass;
+ float ks = x->k[k], kd = x->c[k];
+ if (0.25f < sqrtf(ks / mr) * DT) ks = mr / (DT * DT * 16.0f);
+ if (kd * DT > mr) kd = mr / DT;
+ /* Fancade's Bullet takes the spring's velocity from the bodies' centres, not the anchors */
+ float rs = k < 2 ? (B->vx - (A ? A->vx : 0)) * nx + (B->vy - (A ? A->vy : 0)) * ny : rv;
+ float fd = -kd * rs * DT, f = -ks * err[k] * DT + fd;
+ t->spt[k] = rs + f;
+ t->splo[k] = fminf(fminf(f, fd), 0);
+ t->sphi[k] = fmaxf(fmaxf(f, fd), 0);
+ }
+ float d = m * (t->spt[k] - rv);
+ float old = t->acc[k];
+ t->acc[k] = clampf(old + d, t->splo[k], t->sphi[k]);
+ d = t->acc[k] - old;
+ imp += d;
+ rv += d / m;
+ }
+ /* limits / lock */
+ if (!free_) {
+ float target;
+ if (lo == hi) {
+ target = -0.2f / DT * (err[k] - lo);
+ float d = m * (target - rv);
+ jt->accl[k] += d;
+ imp += d;
+ } else if (err[k] <= lo) {
+ target = -0.2f / DT * (err[k] - lo);
+ float d = m * (fmaxf(target, 0) - rv);
+ float old = jt->accl[k];
+ jt->accl[k] = fmaxf(old + d, 0);
+ imp += jt->accl[k] - old;
+ } else if (err[k] >= hi) {
+ target = -0.2f / DT * (err[k] - hi);
+ float d = m * (fminf(target, 0) - rv);
+ float old = jt->accl[k];
+ jt->accl[k] = fminf(old + d, 0);
+ imp += jt->accl[k] - old;
+ }
+ }
+ if (imp == 0) continue;
+ if (k < 2) {
+ if (A) apply(A, rax, ray, -nx * imp, -ny * imp);
+ apply(B, rbx, rby, nx * imp, ny * imp);
+ } else {
+ if (A) A->w -= imp * A->invi * A->lockr;
+ B->w += imp * B->invi * B->lockr;
+ }
+ }
+ }
+ (void)first;
+}
+
+/* ------------------------------------------------------------------- step */
+void phys_step(void) {
+ /* joint solver state and contacts live in the free arena space: nothing is allocated during a step
+ (but for the warm start cache, once: an eighth of the space left after the level is set up) */
+ uint32_t avail;
+ uint8_t *top = arena_top(&avail);
+ if (!warm && nbodies) {
+ int cap = (int)(avail / 8 / sizeof(Warm));
+ if (cap > MAX_CONTACTS) cap = MAX_CONTACTS;
+ warm = cap > 0 ? arena_alloc(sizeof(Warm) * cap) : 0;
+ warm_cap = warm ? cap : 0;
+ nwarm = 0;
+ top = arena_top(&avail);
+ }
+ int next = 0;
+ for (int ji = 0; ji < njoints; ji++)
+ if (joints[ji].ext) next++;
+ uint32_t jbytes = (uint32_t)(njoints * sizeof(JointTmp) + next * sizeof(JointExtTmp) + 7) & ~7u;
+ bool jok = jbytes <= avail;
+ if (!jok) {
+ OOM("joint state");
+ jbytes = 0;
+ }
+ memset(top, 0, jbytes);
+ jtmp = (JointTmp *)top;
+ etmp = (JointExtTmp *)(top + njoints * sizeof(JointTmp));
+ con = (Contact *)(top + jbytes);
+ avail -= jbytes;
+ con_cap = (int)(avail / sizeof(Contact));
+ if (con_cap > MAX_CONTACTS) con_cap = MAX_CONTACTS;
+ /* like Fancade's Bullet bodies, one left free of joints and locks also moves in depth */
+ for (int i = 0; i < nbodies; i++) bodies[i].lockz = bodies[i].obj >= 0 && (objs[bodies[i].obj].lockp & 4) ? 1.0f : 0.0f;
+ for (int j = 0; j < njoints; j++) {
+ if (joints[j].a >= 0) bodies[joints[j].a].lockz = 0;
+ if (joints[j].b >= 0) bodies[joints[j].b].lockz = 0;
+ }
+ /* external forces */
+ for (int i = 0; i < nbodies; i++) {
+ Body *b = &bodies[i];
+ if (!b->lockz) b->vz = 0;
+ if (b->obj < 0 || !(objs[b->obj].flags & OF_VISIBLE)) continue;
+ b->vx += (phys_gravity.x + b->fx * b->invm) * DT * b->lockx;
+ b->vy += (phys_gravity.y + b->fy * b->invm) * DT * b->locky;
+ b->w += b->tq * b->invi * DT * b->lockr;
+ b->fx = b->fy = b->tq = 0;
+ if (k_linear_damping > 0) {
+ float f = 1 - k_linear_damping * DT;
+ b->vx *= f;
+ b->vy *= f;
+ }
+ if (k_angular_damping > 0) b->w *= 1 - k_angular_damping * DT;
+ }
+ gen_contacts();
+ warm_start();
+ prep_contacts();
+ for (int it = 0; it < ITER; it++) {
+ if (jok) solve_joints(it == 0);
+ solve_contacts();
+ }
+ warm_store();
+ for (int i = 0; i < nbodies; i++) bodies[i].pvx = bodies[i].pvy = bodies[i].pw = bodies[i].pvz = 0;
+ for (int it = 0; it < ITER; it++) solve_split();
+ /* events */
+ nevents = 0;
+ for (int i = 0; i < ncon; i++) {
+ Contact *c = &con[i];
+ int oa = bodies[c->a].obj, ob = c->b >= 0 ? bodies[c->b].obj : c->sobj;
+ int k;
+ for (k = 0; k < nevents; k++)
+ if (events[k].a == oa && events[k].b == ob) break;
+ if (k == nevents) {
+ if (nevents >= MAX_EVENTS) continue;
+ events[k].a = oa;
+ events[k].b = ob;
+ events[k].imp = 0;
+ nevents++;
+ }
+ if (c->jn >= events[k].imp) {
+ events[k].imp = c->jn;
+ events[k].nx = c->nx;
+ events[k].ny = c->ny;
+ }
+ }
+ /* integrate */
+ for (int i = 0; i < nbodies; i++) {
+ Body *b = &bodies[i];
+ if (b->obj < 0 || !(objs[b->obj].flags & OF_VISIBLE)) continue;
+ b->x += (b->vx + b->pvx) * DT;
+ b->y += (b->vy + b->pvy) * DT;
+ b->z += (b->vz + b->pvz) * DT;
+ b->a += (b->w + b->pw) * DT;
+ vec3 s = v3(b->spin3.x * DEG2RAD * DT, b->spin3.y * DEG2RAD * DT, (b->w + b->pw) * DT);
+ float l = vlen(s);
+ if (l > 1e-9f) b->rot = qnorm(qmul(qaxis(vscale(s, 1 / l), l), b->rot));
+ body_matrix(b);
+ body_zrange(b);
+ sync_obj(b);
+ }
+}
+
+bool phys_collision(int o, int *other, float *impulse, vec3 *normal) {
+ float best = -1;
+ for (int k = 0; k < nevents; k++) {
+ if (events[k].a == o || events[k].b == o) {
+ if (events[k].imp > best) {
+ best = events[k].imp;
+ *other = events[k].a == o ? events[k].b : events[k].a;
+ float s = events[k].a == o ? 1.0f : -1.0f;
+ *normal = v3(events[k].nx * s, events[k].ny * s, 0);
+ *impulse = events[k].imp;
+ }
+ }
+ }
+ return best >= 0;
+}
+
+#ifdef HOST
+#include <stdio.h>
+#include <stdlib.h>
+int st_bodies, st_joints, st_con, st_elems, st_obj, st_elem_body;
+long st_slack = 1L << 30;
+uint32_t st_slack_pos;
+int st_slack_con, st_slack_obj;
+static void stats_dump(void) {
+ extern uint32_t arena_peak;
+ extern int st_obj_setup;
+ extern uint32_t st_arena_setup;
+ printf("STATS setup_arena=%u setup_obj=%d ", st_arena_setup, st_obj_setup);
+ printf("SLACK %ld pos %u con %d obj %d ", st_slack, st_slack_pos, st_slack_con, st_slack_obj);
+ printf("STATS arena=%u obj=%d bodies=%d joints=%d con=%d elems=%d maxel=%d\n", arena_peak, st_obj, st_bodies,
+ st_joints, st_con, st_elems, st_elem_body);
+}
+void phys_debug(int frame) {
+ static int reg;
+ if (!reg && getenv("ND_STATS")) {
+ reg = 1;
+ atexit(stats_dump);
+ }
+ if (nbodies > st_bodies) st_bodies = nbodies;
+ if (njoints > st_joints) st_joints = njoints;
+ if (ncon > st_con) st_con = ncon;
+ {
+ extern uint32_t arena_free(void);
+ long slack = (long)arena_free() - (long)(ncon * sizeof(Contact));
+ if (slack < st_slack) {
+ st_slack = slack;
+ extern uint32_t arena_used(void);
+ st_slack_pos = arena_used();
+ st_slack_con = ncon;
+ st_slack_obj = nobj;
+ }
+ }
+ if (nelems > st_elems) st_elems = nelems;
+ if (nobj > st_obj) st_obj = nobj;
+ for (int i = 0; i < nbodies; i++)
+ if (bodies[i].nel > st_elem_body) st_elem_body = bodies[i].nel;
+ static int on = -1, tr = -1;
+ if (tr < 0) tr = getenv("ND_TRACK") != 0;
+ if (tr && nbodies && frame % (getenv("ND_T5") ? 5 : 10) == 0) {
+ static float x0, y0;
+ Body *b = &bodies[0];
+ if (getenv("ND_TOBJ") && body(atoi(getenv("ND_TOBJ")))) b = body(atoi(getenv("ND_TOBJ")));
+ if (frame == 0) {
+ x0 = b->x;
+ y0 = b->y;
+ }
+ printf("%d:%.2f,%.2f,%.0f ", frame, b->x - x0, b->y - y0, b->a * 57.3f);
+ if (frame % 100 == 0) printf("\n");
+ fflush(stdout);
+ }
+ if (getenv("ND_JDBG") && frame >= atoi(getenv("ND_JDBG")) && frame < atoi(getenv("ND_JDBG")) + 70) {
+ printf("f%d", frame);
+ for (int ji = 0; ji < njoints; ji++) {
+ Joint *j = &joints[ji];
+ Body *A, *B;
+ float rax, ray, rbx, rby, cx, cy, ex, ey, ang;
+ joint_frame(j, &A, &B, &rax, &ray, &rbx, &rby, &cx, &cy, &ex, &ey, &ang);
+ printf(" j%d:%.3f", ji, ey);
+ }
+ printf(" ncon=%d\n", ncon);
+ }
+ if (getenv("ND_GEO") && frame == 0) {
+ float g0, g1, g2, g3;
+ sscanf(getenv("ND_GEO"), "%f,%f,%f,%f", &g0, &g1, &g2, &g3);
+ for (int so = 0; so < nobj; so++) {
+ Obj *os = &objs[so];
+ if (os->flags & (OF_DYNAMIC | OF_DEAD | OF_TEMPLATE)) continue;
+ const Shape *sh = os->shape;
+ if (!sh) continue;
+ for (int i = 0; i < sh->np; i++) {
+ const Block *bk = blocks[sh->blk[i]];
+ if (!(bk->flags & 3)) continue;
+ uint32_t k = sh->key[i];
+ const uint8_t *bb = bk->bb + PK_C(k) * 6;
+ vec3 mn = obj_world(os, v3(PK_X(k) + bb[0] / 8.0f, PK_Y(k) + bb[1] / 8.0f, PK_Z(k) + bb[2] / 8.0f));
+ vec3 mx = obj_world(os, v3(PK_X(k) + (bb[3] + 1) / 8.0f, PK_Y(k) + (bb[4] + 1) / 8.0f, PK_Z(k) + (bb[5] + 1) / 8.0f));
+ if (fmaxf(mn.x, mx.x) < g0 || fminf(mn.x, mx.x) > g2 || fmaxf(mn.y, mx.y) < g1 || fminf(mn.y, mx.y) > g3) continue;
+ printf("geo s%d coll%d x[%.3f,%.3f] y[%.3f,%.3f] z[%.3f,%.3f]\n", so, bk->flags & 3, mn.x, mx.x, mn.y, mx.y, mn.z, mx.z);
+ }
+ }
+ }
+ if (getenv("ND_CON") && frame >= atoi(getenv("ND_CON")) && frame < atoi(getenv("ND_CON")) + 80) {
+ printf("f%d:", frame);
+ for (int i = 0; i < ncon; i++) {
+ Contact *c = &con[i];
+ printf(" b%d-%c%d(%.2f,%.2f p=%.2f,%.2f jn=%.2f jt=%.2f mu=%.2f)", c->a, c->b >= 0 ? (char)98 : (char)115, c->b >= 0 ? c->b : c->sobj, c->nx, c->ny, c->px, c->py, c->jn, c->jt, c->mu);
+ }
+ printf("\n");
+ }
+ if (on < 0) on = getenv("ND_DEBUG") != 0;
+ if (!on) return;
+ printf("frame %d bodies %d joints %d contacts %d\n", frame, nbodies, njoints, ncon);
+ for (int i = 0; i < nbodies; i++) {
+ Body *b = &bodies[i];
+ if (b->obj < 0) continue;
+ printf(" b%d obj%d m=%.2f I=%.3f pos=(%.3f,%.3f,%.3f) a=%.3f v=(%.3f,%.3f) w=%.3f nel=%d z=[%.2f,%.2f] lock=%g%g%g\n", i, b->obj,
+ b->mass, b->inertia, b->x, b->y, b->z, b->a, b->vx, b->vy, b->w, b->nel, b->zmin, b->zmax, b->lockx, b->locky, b->lockr);
+ if (frame == 0)
+ for (int k = 0; k < b->nel; k++)
+ printf(" el%d %s c=(%.3f,%.3f) h=(%.3f,%.3f) z=[%.3f,%.3f] fr=%.2f\n", k, b->el[k].circle ? "circ" : "box", b->el[k].cx, b->el[k].cy,
+ b->el[k].hx, b->el[k].hy, b->el[k].z0, b->el[k].z1, obj_friction(&objs[b->obj]));
+ }
+ for (int j = 0; j < njoints; j++) {
+ Joint *jt = &joints[j];
+ JointExt z = {{0}}, *x = jt->ext ? jt->ext : &z;
+ printf(" j%d a=%d b=%d lo=(%.2f,%.2f,%.2f) hi=(%.2f,%.2f,%.2f) k=(%.1f,%.1f,%.1f) c=%.1f mv=%.2f mf=%.2f\n", j, jt->a, jt->b, jt->lo[0],
+ jt->lo[1], jt->lo[2], jt->hi[0], jt->hi[1], jt->hi[2], x->k[0], x->k[1], x->k[2], x->c[1], x->mv[2], x->mf[2]);
+ if (frame == 0) printf(" la=(%.3f,%.3f,%.3f) lb=(%.3f,%.3f,%.3f)\n", jt->la.x, jt->la.y, jt->la.z, jt->lb.x, jt->lb.y, jt->lb.z);
+ }
+}
+#endif
diff --git a/games/numdrive/src/physics.h b/games/numdrive/src/physics.h
new file mode 100644
index 00000000..b5458794
--- /dev/null
+++ b/games/numdrive/src/physics.h
@@ -0,0 +1,36 @@
+#ifndef PHYSICS_H
+#define PHYSICS_H
+#include <stdbool.h>
+#include "fmath.h"
+
+#define PHYS_HZ 60
+
+void phys_reset(void);
+void phys_step(void);
+void phys_start(void); /* after scripts' first frame: create bodies for physics objects */
+
+bool phys_raycast(vec3 from, vec3 to, vec3 *hit, int *obj);
+bool phys_raycast_ex(vec3 from, vec3 to, vec3 *hit, int *obj, int ignore);
+void phys_get_velocity(int o, vec3 *vel, vec3 *spin);
+void phys_set_velocity(int o, const vec3 *vel, const vec3 *spin);
+void phys_add_force(int o, const vec3 *force, const vec3 *at, const vec3 *torque);
+void phys_set_locked(int o, const vec3 *pos, const vec3 *rot);
+void phys_set_mass(int o, float m);
+void phys_set_friction(int o, float f);
+void phys_set_bounce(int o, float b);
+void phys_set_gravity(vec3 g);
+void phys_moved(int o); /* object teleported by script */
+void phys_make_dynamic(int o);
+void phys_destroyed(int o);
+void phys_hidden(int o);
+
+int phys_add_constraint(int base, int part, vec3 pivot);
+void phys_con_limits(int c, bool angular, vec3 lower, vec3 upper);
+void phys_con_spring(int c, bool angular, vec3 stiffness, vec3 damping);
+void phys_con_motor(int c, bool angular, vec3 speed, vec3 force);
+
+bool phys_collision(int o, int *other, float *impulse, vec3 *normal);
+
+extern vec3 phys_gravity;
+
+#endif
diff --git a/games/numdrive/src/platform.h b/games/numdrive/src/platform.h
new file mode 100644
index 00000000..0bdde46d
--- /dev/null
+++ b/games/numdrive/src/platform.h
@@ -0,0 +1,27 @@
+#ifndef PLATFORM_H
+#define PLATFORM_H
+#include <stdint.h>
+#include <stdbool.h>
+
+#define SCREEN_W 320
+#define SCREEN_H 240
+
+/* key bits follow eadk_key_t */
+enum {
+ K_LEFT = 0, K_UP = 1, K_DOWN = 2, K_RIGHT = 3, K_OK = 4, K_BACK = 5, K_HOME = 6,
+ K_SHIFT = 12, K_ALPHA = 13, K_BACKSPACE = 17, K_FOUR = 36, K_SIX = 38, K_ONE = 42,
+ K_TWO = 43, K_THREE = 44, K_PLUS = 45, K_MINUS = 46, K_ZERO = 48, K_EXE = 52
+};
+#define KEY(k) ((uint64_t)1 << (k))
+
+void plat_push(int x, int y, int w, int h, const uint16_t *px);
+void plat_fill(int x, int y, int w, int h, uint16_t c);
+void plat_pull(int x, int y, int w, int h, uint16_t *px);
+uint64_t plat_keys(void);
+uint32_t plat_millis(void);
+void plat_vblank(void);
+void plat_sleep(int ms);
+uint32_t plat_random(void);
+void plat_frame_done(void); /* host harness hook (captures frames) */
+
+#endif
diff --git a/games/numdrive/src/platform_eadk.c b/games/numdrive/src/platform_eadk.c
new file mode 100644
index 00000000..a11c230f
--- /dev/null
+++ b/games/numdrive/src/platform_eadk.c
@@ -0,0 +1,24 @@
+#include <eadk.h>
+#include "platform.h"
+
+void plat_push(int x, int y, int w, int h, const uint16_t *px) {
+ eadk_rect_t r = {(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h};
+ eadk_display_push_rect(r, px);
+}
+
+void plat_fill(int x, int y, int w, int h, uint16_t c) {
+ eadk_rect_t r = {(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h};
+ eadk_display_push_rect_uniform(r, c);
+}
+
+void plat_pull(int x, int y, int w, int h, uint16_t *px) {
+ eadk_rect_t r = {(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h};
+ eadk_display_pull_rect(r, px);
+}
+
+uint64_t plat_keys(void) { return eadk_keyboard_scan(); }
+uint32_t plat_millis(void) { return (uint32_t)eadk_timing_millis(); }
+void plat_vblank(void) { eadk_display_wait_for_vblank(); }
+void plat_sleep(int ms) { eadk_timing_msleep(ms); }
+uint32_t plat_random(void) { return eadk_random(); }
+void plat_frame_done(void) {}
diff --git a/games/numdrive/src/render.c b/games/numdrive/src/render.c
new file mode 100644
index 00000000..54c15070
--- /dev/null
+++ b/games/numdrive/src/render.c
@@ -0,0 +1,770 @@
+/* Strip-based z-buffered renderer for Fancade voxel objects (orthographic camera). */
+#include <string.h>
+#include <math.h>
+#ifdef HOST
+#include <stdio.h>
+#include <stdlib.h>
+#endif
+#include "render.h"
+#include "world.h"
+#include "platform.h"
+#include "vm.h"
+#include "physics.h"
+
+const uint8_t palette_rgb[34][3] = {
+ {0, 0, 0}, {29, 29, 40}, {63, 63, 80}, {101, 103, 121}, {144, 147, 164}, {191, 194, 205}, {255, 255, 255},
+ {148, 83, 94}, {192, 109, 128}, {225, 153, 152}, {253, 181, 168}, {255, 219, 197}, {255, 243, 242},
+ {192, 54, 80}, {255, 74, 104}, {255, 154, 154}, {201, 80, 64}, {255, 112, 83}, {255, 168, 129},
+ {232, 168, 0}, {255, 213, 0}, {255, 255, 122}, {0, 136, 76}, {66, 195, 79}, {181, 255, 110},
+ {0, 108, 218}, {0, 142, 255}, {0, 193, 255}, {104, 83, 162}, {140, 111, 217}, {176, 138, 255},
+ {235, 112, 171}, {255, 149, 206}, {255, 185, 232}};
+
+Camera cam;
+uint16_t sky565;
+static vec3 light_to; /* direction towards the light */
+static const float AMB[3] = {0.764f, 0.773f, 0.839f};
+static const float LEFF[3] = {0.444f, 0.423f, 0.304f};
+
+static uint16_t cbuf[SCREEN_W * STRIP_H] __attribute__((aligned(4)));
+static uint16_t zbuf[SCREEN_W * STRIP_H] __attribute__((aligned(4)));
+typedef uint32_t __attribute__((may_alias)) u32a;
+static int strip_y0, strip_y1; /* current strip rows [y0, y1) */
+static int clip_x0, clip_x1;
+/* per object, per frame: screen rows covered and part cache offset */
+typedef struct {
+ int16_t ymin, ymax;
+ uint16_t pcache;
+} RObj;
+static RObj *robj;
+
+uint16_t rgb565(int r, int g, int b) {
+ if (r > 255) r = 255;
+ if (g > 255) g = 255;
+ if (b > 255) b = 255;
+ if (r < 0) r = 0;
+ if (g < 0) g = 0;
+ if (b < 0) b = 0;
+ return (uint16_t)((r >> 3) << 11 | (g >> 2) << 5 | (b >> 3));
+}
+
+void shade_color(int pal, vec3 n, int *r, int *g, int *b) {
+ float k = vdot(n, light_to);
+ if (k < 0) k = 0;
+ const uint8_t *c = palette_rgb[pal];
+ *r = (int)(c[0] * (AMB[0] + k * LEFF[0]) + 0.5f);
+ *g = (int)(c[1] * (AMB[1] + k * LEFF[1]) + 0.5f);
+ *b = (int)(c[2] * (AMB[2] + k * LEFF[2]) + 0.5f);
+}
+
+static uint16_t axis_col[34 * 6];
+static uint8_t axis_ok[34 * 6 / 8 + 1];
+
+void light_set(const quat *rot) {
+ vec3 d = qrot(*rot, v3(0, 0, 1));
+ light_to = vscale(d, -1);
+ memset(axis_ok, 0, sizeof axis_ok);
+}
+
+/* ------------------------------------------------------------------ camera */
+void cam_default(void) {
+ cam.focus = v3(0, 0, 0);
+ cam.rot = qeuler(22.5f, 22.5f, 0);
+ cam.range = 50;
+ cam.perspective = 0;
+ cam.shake = v3(0, 0, 0);
+ cam.cx = SCREEN_W * 0.5f;
+ cam.cy = SCREEN_H * 0.5f;
+ cam.zoom_mul = 1;
+ cam.roll = 0;
+ quat l = qeuler(45, -45, 0);
+ light_set(&l);
+ cam_update();
+}
+
+void cam_update(void) {
+ cam.right = qrot(cam.rot, v3(1, 0, 0));
+ cam.up = qrot(cam.rot, v3(0, 1, 0));
+ cam.fwd = qrot(cam.rot, v3(0, 0, 1));
+ float zoom = cam.range * 0.1f;
+ if (zoom < 0.1f) zoom = 0.1f;
+ cam.scale = (SCREEN_H * 0.5f) / zoom * cam.zoom_mul;
+ if (cam.roll != 0) {
+ float c = cosf(cam.roll), sn = sinf(cam.roll);
+ vec3 r = cam.right, u = cam.up;
+ cam.right = vadd(vscale(r, c), vscale(u, sn));
+ cam.up = vsub(vscale(u, c), vscale(r, sn));
+ }
+}
+
+void cam_view(float cx, float cy, float zoom_mul, float roll) {
+ cam.cx = cx;
+ cam.cy = cy;
+ cam.zoom_mul = zoom_mul;
+ cam.roll = roll;
+ cam_update();
+}
+
+void cam_set(const vec3 *pos, const quat *rot, const float *range, int perspective) {
+ if (pos) cam.focus = *pos;
+ if (rot) cam.rot = qnorm(*rot);
+ if (range) cam.range = *range;
+ cam.perspective = perspective;
+ cam_update();
+}
+
+vec3 cam_world_to_screen(vec3 p) {
+ vec3 d = vsub(p, cam.focus);
+ return v3(cam.cx + vdot(d, cam.right) * cam.scale, cam.cy - vdot(d, cam.up) * cam.scale,
+ vdot(d, cam.fwd));
+}
+
+void cam_screen_to_world(float sx, float sy, vec3 *near, vec3 *far) {
+ float x = (sx - cam.cx) / cam.scale, y = (cam.cy - sy) / cam.scale;
+ vec3 b = vadd(cam.focus, vadd(vscale(cam.right, x), vscale(cam.up, y)));
+ *near = vsub(b, vscale(cam.fwd, 50));
+ *far = vadd(b, vscale(cam.fwd, 150));
+}
+
+/* --------------------------------------------------------------- raster */
+#define ZOFF 48.0f
+#define ZSCALE 512.0f
+
+static inline int iceil(float v) {
+ int i = (int)v;
+ return i + (v > (float)i);
+}
+
+/* Rasterise the parallelogram P0 + s*U + t*V (s, t in [0,1)) with a planar depth.
+ * ds/dx, ds/dy, dt/dx, dt/dy map screen offsets from P0 to (s, t); ix* are 1/(ds/dx), 1/(dt/dx). */
+typedef struct {
+ float dsdx, dsdy, dtdx, dtdy, isx, itx;
+} PInv;
+
+/* Fancade's floor, an endless plane at y = 0, hides whatever is below it: while an object reaching below it is
+ * drawn, world y at a pixel is fl_k + fl_x * x + fl_y * y + fl_z * depth */
+static bool fl_on;
+static float fl_k, fl_x, fl_y, fl_z;
+
+static void raster(float X0, float Y0, float ux, float uy, float vx, float vy, const PInv *pi, float z0, float zx,
+ float zy, uint16_t color) {
+ float ymin = Y0, ymax = Y0;
+ float ya = Y0 + uy, yb = Y0 + vy, yc2 = Y0 + uy + vy;
+ if (ya < ymin) ymin = ya;
+ if (ya > ymax) ymax = ya;
+ if (yb < ymin) ymin = yb;
+ if (yb > ymax) ymax = yb;
+ if (yc2 < ymin) ymin = yc2;
+ if (yc2 > ymax) ymax = yc2;
+ int y0 = iceil(ymin - 0.5f), y1 = iceil(ymax - 0.5f);
+ if (y0 < strip_y0) y0 = strip_y0;
+ if (y1 > strip_y1) y1 = strip_y1;
+ if (y0 >= y1) return;
+ /* depth in fixed point: Z(x,y) = (z0 + zx*(x - X0) + zy*(y - Y0) + ZOFF) * ZSCALE */
+ float zbase = (z0 + ZOFF - zx * X0 - zy * Y0) * ZSCALE;
+ int32_t dz = (int32_t)(zx * ZSCALE * 256.0f);
+ float dy = y0 + 0.5f - Y0;
+ float sr = pi->dsdy * dy, tr = pi->dtdy * dy; /* s, t at (X0, row centre) */
+ for (int y = y0; y < y1; y++, sr += pi->dsdy, tr += pi->dtdy) {
+ float xl, xr;
+ if (pi->isx != 0) {
+ float a = -sr * pi->isx, b = (1 - sr) * pi->isx;
+ if (a < b) xl = a, xr = b;
+ else xl = b, xr = a;
+ } else {
+ if (sr < 0 || sr >= 1) continue;
+ xl = -1e9f, xr = 1e9f;
+ }
+ if (pi->itx != 0) {
+ float a = -tr * pi->itx, b = (1 - tr) * pi->itx;
+ if (a > b) {
+ float t = a;
+ a = b;
+ b = t;
+ }
+ if (a > xl) xl = a;
+ if (b < xr) xr = b;
+ } else if (tr < 0 || tr >= 1) {
+ continue;
+ }
+ if (xl >= xr) continue;
+ int x0 = iceil(X0 + xl - 0.5f), x1 = iceil(X0 + xr - 0.5f);
+ if (x0 < clip_x0) x0 = clip_x0;
+ if (x1 > clip_x1) x1 = clip_x1;
+ float yc = y + 0.5f;
+ if (fl_on) {
+ /* world y along the row: a + b * (pixel centre x) */
+ float a = fl_k + fl_y * yc + fl_z * (z0 - zx * X0 + zy * (yc - Y0)), b = fl_x + fl_z * zx, e = -0.01f - a;
+ if (b > 1e-7f) {
+ int xa = iceil(e / b - 0.5f);
+ if (xa > x0) x0 = xa;
+ } else if (b < -1e-7f) {
+ int xb = iceil(e / b - 0.5f);
+ if (xb < x1) x1 = xb;
+ } else if (e > 0) {
+ continue;
+ }
+ }
+ if (x0 >= x1) continue;
+ float zs = zbase + (zx * (x0 + 0.5f) + zy * yc) * ZSCALE;
+ if (zs < 0) zs = 0;
+ int32_t z = (int32_t)(zs * 256.0f);
+ int row = (y - strip_y0) * SCREEN_W;
+ uint16_t *c = cbuf + row + x0, *ce = cbuf + row + x1;
+ uint16_t *zp = zbuf + row + x0;
+ int32_t zend = z + dz * (x1 - x0 - 1);
+ if (z >= 0 && zend >= 0 && z < (65535 << 8) && zend < (65535 << 8)) {
+ for (; c < ce; c++, zp++, z += dz) {
+ uint16_t zz = (uint16_t)(z >> 8);
+ if (zz <= *zp) {
+ *zp = zz;
+ *c = color;
+ }
+ }
+ } else {
+ for (; c < ce; c++, zp++, z += dz) {
+ int32_t zz = z >> 8;
+ if (zz < 0) zz = 0;
+ if (zz > 65535) zz = 65535;
+ if ((uint16_t)zz <= *zp) {
+ *zp = (uint16_t)zz;
+ *c = color;
+ }
+ }
+ }
+ }
+}
+
+/* --------------------------------------------------------- object drawing */
+typedef struct {
+ float ox, oy, oz; /* screen x, y, depth of rest origin (0,0,0) */
+ float bx[3], by[3], bz[3]; /* screen delta per rest unit along x,y,z */
+ uint8_t vis; /* visible local face directions */
+ uint16_t col[34 * 6]; /* shaded colours cache: filled lazily */
+ uint8_t colok[34 * 6 / 8 + 1];
+ vec3 n[6];
+ float zx[6], zy[6];
+ float fa[6], fb[6], fc[6], fd[6], fia[6], fic[6]; /* per face: (s,t) per screen unit, for 1 voxel quads */
+ uint8_t ident; /* unrotated: shared colour cache */
+} ObjXf;
+
+static ObjXf xf;
+
+static void setup_xf(const Obj *o) {
+ const Shape *s = o->shape;
+ vec3 ax[3] = {qrot(o->rot, v3(1, 0, 0)), qrot(o->rot, v3(0, 1, 0)), qrot(o->rot, v3(0, 0, 1))};
+ for (int k = 0; k < 3; k++) {
+ xf.bx[k] = vdot(ax[k], cam.right) * cam.scale;
+ xf.by[k] = -vdot(ax[k], cam.up) * cam.scale;
+ xf.bz[k] = vdot(ax[k], cam.fwd);
+ }
+ /* origin of rest space: world = pos + R*(rest - com) => rest 0 maps to pos - R*com */
+ vec3 w0 = vsub(o->pos, qrot(o->rot, s->origin));
+ vec3 d = vsub(w0, vadd(cam.focus, cam.shake));
+ xf.ox = cam.cx + vdot(d, cam.right) * cam.scale;
+ xf.oy = cam.cy - vdot(d, cam.up) * cam.scale;
+ xf.oz = vdot(d, cam.fwd);
+ {
+ vec3 lo = vsub(s->bmin, s->origin), hi = vsub(s->bmax, s->origin);
+ vec3 m = v3(fmaxf(-lo.x, hi.x), fmaxf(-lo.y, hi.y), fmaxf(-lo.z, hi.z));
+ fl_on = o->pos.y * o->pos.y < vdot(m, m) || o->pos.y < 0;
+ vec3 f = vadd(cam.focus, cam.shake);
+ fl_x = cam.right.y / cam.scale;
+ fl_y = -cam.up.y / cam.scale;
+ fl_z = cam.fwd.y;
+ fl_k = f.y - fl_x * cam.cx - fl_y * cam.cy;
+ }
+ xf.vis = 0;
+ for (int f = 0; f < 6; f++) {
+ vec3 n = vscale(ax[f >> 1], (f & 1) ? -1.0f : 1.0f);
+ xf.n[f] = n;
+ float nf = vdot(n, cam.fwd);
+ if (nf < -1e-4f) {
+ int axis = f >> 1, ua = axis == 0 ? 1 : 0, va = axis == 2 ? 1 : 2;
+ float eux = xf.bx[ua] * 0.125f, euy = xf.by[ua] * 0.125f, evx = xf.bx[va] * 0.125f, evy = xf.by[va] * 0.125f;
+ float det = eux * evy - euy * evx;
+ if (fabsf(det) < 1e-6f) continue;
+ float id = 1.0f / det;
+ xf.fa[f] = evy * id;
+ xf.fb[f] = -evx * id;
+ xf.fc[f] = -euy * id;
+ xf.fd[f] = eux * id;
+ xf.fia[f] = fabsf(xf.fa[f]) > 1e-6f ? 1.0f / xf.fa[f] : 0;
+ xf.fic[f] = fabsf(xf.fc[f]) > 1e-6f ? 1.0f / xf.fc[f] : 0;
+ xf.vis |= 1 << f;
+ float nr = vdot(n, cam.right), nu = vdot(n, cam.up);
+ xf.zx[f] = -nr / (cam.scale * nf);
+ xf.zy[f] = nu / (cam.scale * nf);
+ }
+ }
+ xf.ident = fabsf(o->rot.x) + fabsf(o->rot.y) + fabsf(o->rot.z) < 1e-5f;
+ if (!xf.ident) memset(xf.colok, 0, sizeof xf.colok);
+}
+
+static uint16_t face_color(int pal, int f) {
+ int i = pal * 6 + f;
+ if (xf.ident) {
+ if (!(axis_ok[i >> 3] & (1 << (i & 7)))) {
+ int r, g, b;
+ shade_color(pal, xf.n[f], &r, &g, &b);
+ axis_col[i] = rgb565(r, g, b);
+ axis_ok[i >> 3] |= 1 << (i & 7);
+ }
+ return axis_col[i];
+ }
+ if (!(xf.colok[i >> 3] & (1 << (i & 7)))) {
+ int r, g, b;
+ shade_color(pal, xf.n[f], &r, &g, &b);
+ xf.col[i] = rgb565(r, g, b);
+ xf.colok[i >> 3] |= 1 << (i & 7);
+ }
+ return xf.col[i];
+}
+
+/* project rest-space point given in voxel units */
+static inline void proj(float vx, float vy, float vz, float *sx, float *sy, float *sz) {
+ vx *= 0.125f;
+ vy *= 0.125f;
+ vz *= 0.125f;
+ *sx = xf.ox + xf.bx[0] * vx + xf.bx[1] * vy + xf.bx[2] * vz;
+ *sy = xf.oy + xf.by[0] * vx + xf.by[1] * vy + xf.by[2] * vz;
+ *sz = xf.oz + xf.bz[0] * vx + xf.bz[1] * vy + xf.bz[2] * vz;
+}
+
+static const float inv_n[9] = {0, 1, 0.5f, 1.0f / 3, 0.25f, 0.2f, 1.0f / 6, 1.0f / 7, 0.125f};
+
+static void draw_part(const Shape *s, int pi) {
+ uint32_t k = s->key[pi];
+ const Block *b = blocks[s->blk[pi]];
+ int cx = PK_X(k) * 8, cy = PK_Y(k) * 8, cz = PK_Z(k) * 8, comp = PK_C(k);
+ /* quick strip reject using the cell centre (rows first) */
+ float r = 0.9f * cam.scale;
+ float vx = (cx + 4) * 0.125f, vy = (cy + 4) * 0.125f, vz = (cz + 4) * 0.125f;
+ float sy = xf.oy + xf.by[0] * vx + xf.by[1] * vy + xf.by[2] * vz;
+ if (sy + r < strip_y0 || sy - r > strip_y1) return;
+ float sx = xf.ox + xf.bx[0] * vx + xf.bx[1] * vy + xf.bx[2] * vz;
+ if (sx + r < clip_x0 || sx - r > clip_x1) return;
+ uint8_t occ = s->occ ? s->occ[pi] : 0;
+ for (int f = 0; f < 6; f++) {
+ if (!(xf.vis & (1 << f)) || !b->nq[f]) continue;
+ const uint8_t *q = b->fq[f];
+ int axis = f >> 1, ua = axis == 0 ? 1 : 0, va = axis == 2 ? 1 : 2;
+ int pos = !(f & 1);
+ float eux = xf.bx[ua] * 0.125f, euy = xf.by[ua] * 0.125f, evx = xf.bx[va] * 0.125f, evy = xf.by[va] * 0.125f;
+ for (int i = 0; i < b->nq[f]; i++, q += 3) {
+ uint32_t w = q[0] | q[1] << 8 | (uint32_t)q[2] << 16;
+ int layer = w & 7, u = (w >> 3) & 7, v = (w >> 6) & 7, du = ((w >> 9) & 7) + 1, dv = ((w >> 12) & 7) + 1;
+ int col = (w >> 15) & 63, qc = (w >> 21) & 7;
+ if (qc != comp) continue;
+ if ((occ & (1 << f)) && layer == (pos ? 7 : 0)) continue;
+ float p[3];
+ p[axis] = (float)(layer + pos);
+ p[ua] = (float)u;
+ p[va] = (float)v;
+ float X, Y, Z;
+ proj(cx + p[0], cy + p[1], cz + p[2], &X, &Y, &Z);
+ PInv pv;
+ float iu = inv_n[du], iv = inv_n[dv];
+ pv.dsdx = xf.fa[f] * iu;
+ pv.dsdy = xf.fb[f] * iu;
+ pv.dtdx = xf.fc[f] * iv;
+ pv.dtdy = xf.fd[f] * iv;
+ pv.isx = xf.fia[f] * du;
+ pv.itx = xf.fic[f] * dv;
+ raster(X, Y, eux * du, euy * du, evx * dv, evy * dv, &pv, Z, xf.zx[f], xf.zy[f], face_color(col, f));
+ }
+ }
+}
+
+/* per frame cache of the strips each part may touch (one byte per part: first << 4 | last), kept in
+ * the free arena space which is untouched while rendering */
+static uint8_t *pc_base;
+static uint32_t pc_avail, pc_used;
+
+
+static void draw_object(Obj *ob, RObj *o) {
+ setup_xf(ob);
+ const Shape *s = ob->shape;
+ if (o->pcache == 0xFFFF && pc_used + s->np <= pc_avail && pc_used + s->np < 0xFFFF) {
+ uint8_t *pc = pc_base + pc_used;
+ float r = 0.9f * cam.scale;
+ for (int i = 0; i < s->np; i++) {
+ uint32_t k = s->key[i];
+ float vy = PK_Y(k) + 0.5f, vx = PK_X(k) + 0.5f, vz = PK_Z(k) + 0.5f;
+ float sy = xf.oy + xf.by[0] * vx + xf.by[1] * vy + xf.by[2] * vz;
+ int a = (int)floorf((sy - r) * (1.0f / STRIP_H)), b = (int)floorf((sy + r) * (1.0f / STRIP_H));
+ if (b < 0 || a > SCREEN_H / STRIP_H - 1) {
+ pc[i] = 0xF0;
+ continue;
+ }
+ if (a < 0) a = 0;
+ if (b > 15) b = 15;
+ pc[i] = (uint8_t)(a << 4 | b);
+ }
+ o->pcache = (uint16_t)pc_used;
+ pc_used += s->np;
+ }
+ if (o->pcache != 0xFFFF) {
+ const uint8_t *pc = pc_base + o->pcache;
+ int st = strip_y0 / STRIP_H;
+ for (int i = 0; i < s->np; i++)
+ if (st >= (pc[i] >> 4) && st <= (pc[i] & 15)) draw_part(s, i);
+ } else {
+ for (int i = 0; i < s->np; i++) draw_part(s, i);
+ }
+ fl_on = false;
+}
+
+/* ------------------------------------------------------------------ frame */
+static bool obj_screen_bounds(const Obj *o, int *y0, int *y1, int *x0, int *x1);
+
+bool render_init_level(void) {
+ robj = arena_alloc(sizeof(RObj) * (obj_cap ? obj_cap : 1));
+ if (!robj) return false;
+ int r = palette_rgb[level.bg][0], g = palette_rgb[level.bg][1], b = palette_rgb[level.bg][2];
+ r = r + (255 - r) * 2 / 5;
+ g = g + (255 - g) * 2 / 5;
+ b = b + (255 - b) * 2 / 5;
+ /* the background of the levels built on Fancade's floor, as seen in the original */
+ static const uint8_t floor_bg[][4] = {
+ {2, 63, 63, 77}, {4, 132, 135, 153}, {5, 172, 175, 191}, {7, 89, 58, 73}, {8, 150, 87, 102}, {22, 18, 114, 76}};
+ for (unsigned i = 0; i < sizeof floor_bg / sizeof floor_bg[0]; i++)
+ if (floor_bg[i][0] == level.bg) r = floor_bg[i][1], g = floor_bg[i][2], b = floor_bg[i][3];
+ sky565 = rgb565(r, g, b);
+ return true;
+}
+
+static bool obj_screen_bounds(const Obj *o, int *y0, int *y1, int *x0, int *x1) {
+ const Shape *s = o->shape;
+ float mnx = 1e9f, mxx = -1e9f, mny = 1e9f, mxy = -1e9f;
+ for (int c = 0; c < 8; c++) {
+ vec3 pt = v3(c & 1 ? s->bmax.x : s->bmin.x, c & 2 ? s->bmax.y : s->bmin.y, c & 4 ? s->bmax.z : s->bmin.z);
+ vec3 w = obj_world(o, pt);
+ vec3 d = vsub(w, vadd(cam.focus, cam.shake));
+ float sx = cam.cx + vdot(d, cam.right) * cam.scale;
+ float sy = cam.cy - vdot(d, cam.up) * cam.scale;
+ if (sx < mnx) mnx = sx;
+ if (sx > mxx) mxx = sx;
+ if (sy < mny) mny = sy;
+ if (sy > mxy) mxy = sy;
+ }
+ *x0 = (int)mnx - 1;
+ *x1 = (int)mxx + 1;
+ *y0 = (int)mny - 1;
+ *y1 = (int)mxy + 1;
+ return !(mxx < 0 || mnx > SCREEN_W || mxy < 0 || mny > SCREEN_H);
+}
+
+
+/* ------------------------------------------------------------------ shadows */
+/* Moving objects (and the props following them, like the tyres) cast Fancade style shadows on the
+ * ground below: the box faces lit by the sun are projected along the light onto the plane found by a
+ * raycast, and ground pixels at that depth are darkened to their ambient only colour. */
+#define MAX_CASTERS 32
+#define SHADOW_TOL 40 /* depth units */
+static struct {
+ int16_t obj, floor;
+ float ground;
+} casters[MAX_CASTERS];
+static int ncasters;
+static uint8_t smask[SCREEN_W * STRIP_H / 8];
+typedef struct {
+ float X, Y, ux, uy, vx, vy, z;
+ int16_t y0, y1;
+ uint8_t floor; /* on Fancade's floor: also darkens the background */
+} SQuad;
+static SQuad *squads; /* projected shadow faces for this frame (scratch) */
+static int nsquads, squad_cap;
+#ifdef HOST
+#include <stdio.h>
+#include <stdlib.h>
+static int st_sq_max, st_sq_drop, st_sq_cap = 1 << 30;
+static void sq_dump(void) { printf("SQUADS max %d dropped %d mincap %d\n", st_sq_max, st_sq_drop, st_sq_cap); }
+#endif
+static float sh_zx, sh_zy; /* screen depth gradient of a horizontal plane */
+static bool sh_any;
+
+static void find_casters(void) {
+ ncasters = 0;
+ vec3 d = vscale(light_to, -1);
+ if (d.y > -0.05f) return;
+ vec3 n = v3(0, 1, 0);
+ float nf = vdot(n, cam.fwd);
+ if (fabsf(nf) < 1e-4f) return;
+ sh_zx = -vdot(n, cam.right) / (cam.scale * nf);
+ sh_zy = vdot(n, cam.up) / (cam.scale * nf);
+ /* dynamic objects first, then small moved props close to them */
+ int ndyn = 0;
+ for (int pass = 0; pass < 2; pass++, ndyn = ncasters)
+ for (int i = 0; i < nobj && ncasters < MAX_CASTERS; i++) {
+ const Obj *o = &objs[i];
+ if (!(o->flags & OF_VISIBLE) || (o->flags & (OF_DEAD | OF_TEMPLATE)) || robj[i].ymin > robj[i].ymax) continue;
+ if (pass == 0 && !(o->flags & OF_DYNAMIC)) continue;
+ if (pass == 1) {
+ if ((o->flags & OF_DYNAMIC) || !(o->flags & OF_MOVED) || o->shape->np > 48) continue;
+ bool near = false;
+ for (int c = 0; c < ndyn && !near; c++) {
+ const Obj *q = &objs[casters[c].obj];
+ float dx = q->pos.x - o->pos.x, dy = q->pos.y - o->pos.y;
+ near = dx * dx + dy * dy < 9;
+ }
+ if (!near) continue;
+ }
+ const Shape *s = o->shape;
+ vec3 from = obj_world(o, vscale(vadd(s->bmin, s->bmax), 0.5f)), hit;
+ int ho;
+ bool fl = false;
+ if (!phys_raycast_ex(from, v3(from.x, from.y - 12, from.z), &hit, &ho, i)) {
+ if (from.y > 12 || from.y < 0) continue;
+ hit.y = 0; /* Fancade's floor */
+ fl = true;
+ }
+ casters[ncasters].obj = (int16_t)i;
+ casters[ncasters].floor = fl;
+ casters[ncasters].ground = hit.y;
+ ncasters++;
+ }
+}
+
+/* mark pixels of the parallelogram whose stored depth matches the plane */
+static void raster_mark(float X0, float Y0, float ux, float uy, float vx, float vy, float z0, bool floor) {
+ float det = ux * vy - uy * vx;
+ if (fabsf(det) < 1e-3f) return;
+ float id = 1.0f / det;
+ PInv pv;
+ pv.dsdx = vy * id;
+ pv.dsdy = -vx * id;
+ pv.dtdx = -uy * id;
+ pv.dtdy = ux * id;
+ pv.isx = fabsf(pv.dsdx) > 1e-6f ? 1.0f / pv.dsdx : 0;
+ pv.itx = fabsf(pv.dtdx) > 1e-6f ? 1.0f / pv.dtdx : 0;
+ const PInv *pi = &pv;
+ float ymin = Y0, ymax = Y0;
+ float ya = Y0 + uy, yb = Y0 + vy, yc2 = Y0 + uy + vy;
+ if (ya < ymin) ymin = ya;
+ if (ya > ymax) ymax = ya;
+ if (yb < ymin) ymin = yb;
+ if (yb > ymax) ymax = yb;
+ if (yc2 < ymin) ymin = yc2;
+ if (yc2 > ymax) ymax = yc2;
+ int y0 = iceil(ymin - 0.5f), y1 = iceil(ymax - 0.5f);
+ if (y0 < strip_y0) y0 = strip_y0;
+ if (y1 > strip_y1) y1 = strip_y1;
+ if (y0 >= y1) return;
+ float zbase = (z0 + ZOFF - sh_zx * X0 - sh_zy * Y0) * ZSCALE;
+ float dy = y0 + 0.5f - Y0;
+ float sr = pi->dsdy * dy, tr = pi->dtdy * dy;
+ for (int y = y0; y < y1; y++, sr += pi->dsdy, tr += pi->dtdy) {
+ float xl, xr;
+ if (pi->isx != 0) {
+ float a = -sr * pi->isx, b = (1 - sr) * pi->isx;
+ if (a < b) xl = a, xr = b;
+ else xl = b, xr = a;
+ } else {
+ if (sr < 0 || sr >= 1) continue;
+ xl = -1e9f, xr = 1e9f;
+ }
+ if (pi->itx != 0) {
+ float a = -tr * pi->itx, b = (1 - tr) * pi->itx;
+ if (a > b) {
+ float t = a;
+ a = b;
+ b = t;
+ }
+ if (a > xl) xl = a;
+ if (b < xr) xr = b;
+ } else if (tr < 0 || tr >= 1) {
+ continue;
+ }
+ if (xl >= xr) continue;
+ int x0 = iceil(X0 + xl - 0.5f), x1 = iceil(X0 + xr - 0.5f);
+ if (x0 < clip_x0) x0 = clip_x0;
+ if (x1 > clip_x1) x1 = clip_x1;
+ if (x0 >= x1) continue;
+ float zs = zbase + (sh_zx * (x0 + 0.5f) + sh_zy * (y + 0.5f)) * ZSCALE;
+ float dz = sh_zx * ZSCALE;
+ int row = (y - strip_y0) * SCREEN_W;
+ const uint16_t *zp = zbuf + row;
+ for (int x = x0; x < x1; x++, zs += dz) {
+ int d = (int)zs - zp[x];
+ if ((d <= SHADOW_TOL && d >= -SHADOW_TOL) || (floor && zp[x] == 0xFFFF)) smask[(row + x) >> 3] |= (uint8_t)(1 << ((row + x) & 7));
+ }
+ sh_any = true;
+ }
+}
+
+/* project a lit face (corner p, edges u, v in world space) onto the plane y = g */
+static void shadow_face(vec3 p, vec3 u, vec3 v, float g, vec3 d, bool floor) {
+ float k = (g - p.y) / d.y;
+#ifdef HOST
+ if (k >= 0 && nsquads >= squad_cap) st_sq_drop++;
+#endif
+ if (k < 0 || nsquads >= squad_cap) return; /* face below the ground plane */
+ vec3 p0 = vadd(p, vscale(d, k));
+ vec3 u0 = vsub(u, vscale(d, u.y / d.y)), v0 = vsub(v, vscale(d, v.y / d.y));
+ vec3 q = vsub(p0, vadd(cam.focus, cam.shake));
+ SQuad *sq = &squads[nsquads];
+ sq->X = cam.cx + vdot(q, cam.right) * cam.scale;
+ sq->Y = cam.cy - vdot(q, cam.up) * cam.scale;
+ sq->z = vdot(q, cam.fwd) - 0.01f;
+ sq->ux = vdot(u0, cam.right) * cam.scale;
+ sq->uy = -vdot(u0, cam.up) * cam.scale;
+ sq->vx = vdot(v0, cam.right) * cam.scale;
+ sq->vy = -vdot(v0, cam.up) * cam.scale;
+ float ymin = sq->Y + fminf(0, sq->uy) + fminf(0, sq->vy), ymax = sq->Y + fmaxf(0, sq->uy) + fmaxf(0, sq->vy);
+ if (ymax < 0 || ymin > SCREEN_H) return;
+ sq->y0 = (int16_t)(ymin - 1);
+ sq->y1 = (int16_t)(ymax + 1);
+ sq->floor = floor;
+ nsquads++;
+}
+
+/* project the shadows of all casters once per frame */
+static void build_shadows(void) {
+#ifdef HOST
+ if (nsquads > st_sq_max) st_sq_max = nsquads;
+#endif
+ nsquads = 0;
+ if (!ncasters) return;
+ vec3 d = vscale(light_to, -1);
+ for (int c = 0; c < ncasters; c++) {
+ const Obj *o = &objs[casters[c].obj];
+ const Shape *s = o->shape;
+ float g = casters[c].ground;
+ vec3 ax[3] = {qrot(o->rot, v3(1, 0, 0)), qrot(o->rot, v3(0, 1, 0)), qrot(o->rot, v3(0, 0, 1))};
+ bool lit[6];
+ for (int f = 0; f < 6; f++) lit[f] = vdot(ax[f >> 1], light_to) * ((f & 1) ? -1.0f : 1.0f) > 1e-3f;
+ for (int i = 0; i < s->np; i++) {
+ uint32_t k = s->key[i];
+ const Block *b = blocks[s->blk[i]];
+ int comp = PK_C(k);
+ uint8_t occ = s->occ ? s->occ[i] : 0;
+ /* use the collision boxes, or the component bounds when the block has none */
+ int nb = b->nbox;
+ for (int j = 0; j < (nb ? nb : 1); j++) {
+ float lo[3], hi[3];
+ if (nb) {
+ const uint8_t *bx = b->boxes + 3 * j;
+ uint32_t w = bx[0] | bx[1] << 8 | (uint32_t)bx[2] << 16;
+ if ((int)(w & 7) != comp) continue;
+ lo[0] = ((w >> 3) & 7), lo[1] = ((w >> 6) & 7), lo[2] = ((w >> 9) & 7);
+ hi[0] = ((w >> 12) & 7) + 1, hi[1] = ((w >> 15) & 7) + 1, hi[2] = ((w >> 18) & 7) + 1;
+ } else {
+ const uint8_t *bb = b->bb + comp * 6;
+ if (bb[0] > bb[3]) continue;
+ lo[0] = bb[0], lo[1] = bb[1], lo[2] = bb[2];
+ hi[0] = bb[3] + 1, hi[1] = bb[4] + 1, hi[2] = bb[5] + 1;
+ }
+ vec3 rest = v3(PK_X(k) + lo[0] / 8, PK_Y(k) + lo[1] / 8, PK_Z(k) + lo[2] / 8);
+ vec3 p0 = obj_world(o, rest);
+ vec3 e[3] = {vscale(ax[0], (hi[0] - lo[0]) / 8), vscale(ax[1], (hi[1] - lo[1]) / 8),
+ vscale(ax[2], (hi[2] - lo[2]) / 8)};
+ for (int f = 0; f < 6; f++) {
+ if (!lit[f]) continue;
+ int a = f >> 1, ua = a == 0 ? 1 : 0, va = a == 2 ? 1 : 2;
+ /* a face against a full face of the same object adds nothing to its shadow */
+ if ((occ >> f & 1) && ((f & 1) ? lo[a] == 0 : hi[a] == 8)) continue;
+ vec3 p = (f & 1) ? p0 : vadd(p0, e[a]);
+ shadow_face(p, e[ua], e[va], g, d, casters[c].floor);
+ }
+ }
+ }
+ }
+}
+
+static void draw_shadows(void) {
+ if (!nsquads) return;
+ memset(smask, 0, sizeof smask);
+ sh_any = false;
+ for (int i = 0; i < nsquads; i++) {
+ const SQuad *q = &squads[i];
+ if (q->y1 < strip_y0 || q->y0 >= strip_y1) continue;
+ raster_mark(q->X, q->Y, q->ux, q->uy, q->vx, q->vy, q->z, q->floor);
+ }
+ if (!sh_any) return;
+ int n = (strip_y1 - strip_y0) * SCREEN_W;
+ for (int i = 0; i < n; i += 8) {
+ uint8_t m = smask[i >> 3];
+ if (!m) continue;
+ for (int k = 0; k < 8; k++)
+ if (m & (1 << k)) {
+ uint16_t c = cbuf[i + k];
+ int r = (c >> 11) * 23 >> 5, gg = ((c >> 5) & 63) * 23 >> 5, bl = (c & 31) * 26 >> 5;
+ cbuf[i + k] = (uint16_t)(r << 11 | gg << 5 | bl);
+ }
+ }
+}
+
+void render_prepare(int rx0, int rx1) {
+ uint32_t avail;
+ uint8_t *scr = arena_top(&avail);
+ squads = (SQuad *)scr;
+ squad_cap = (int)((avail / 3) / sizeof(SQuad)); /* at most a third of the free space */
+ if (squad_cap > 512) squad_cap = 512;
+#ifdef HOST
+ {
+ static int reg;
+ if (!reg++ && getenv("ND_STATS")) atexit(sq_dump);
+ if (squad_cap < st_sq_cap) st_sq_cap = squad_cap;
+ }
+#endif
+ uint32_t used = (uint32_t)squad_cap * sizeof(SQuad);
+ pc_base = scr + used;
+ pc_avail = avail - used;
+ pc_used = 0;
+ for (int i = 0; i < nobj; i++) {
+ Obj *o = &objs[i];
+ RObj *r = &robj[i];
+ r->pcache = 0xFFFF;
+ r->ymin = 1;
+ r->ymax = 0;
+ if (!(o->flags & OF_VISIBLE) || (o->flags & OF_DEAD) || !o->shape->np) continue;
+ int y0, y1, x0, x1;
+ if (!obj_screen_bounds(o, &y0, &y1, &x0, &x1)) continue;
+ if (x1 < rx0 || x0 > rx1) continue;
+ r->ymin = (int16_t)(y0 < -32000 ? -32000 : y0);
+ r->ymax = (int16_t)(y1 > 32000 ? 32000 : y1);
+ }
+ find_casters();
+ build_shadows();
+}
+
+uint16_t *render_buffer(void) { return cbuf; }
+void *render_scratch(void) { return zbuf; } /* depth buffer, free between frames */
+
+uint16_t *render_strip(int sy, int n, int x0, int x1) {
+ strip_y0 = sy;
+ strip_y1 = sy + n;
+ clip_x0 = x0;
+ clip_x1 = x1;
+ if (x0 == 0 && x1 == SCREEN_W) {
+ /* whole rows: fill two pixels per word */
+ uint32_t sky2 = sky565 | (uint32_t)sky565 << 16;
+ u32a *c = (u32a *)cbuf, *z = (u32a *)zbuf;
+ for (int i = 0; i < n * SCREEN_W / 2; i++) c[i] = sky2, z[i] = 0xFFFFFFFFu;
+ } else {
+ for (int r = 0; r < n; r++) {
+ uint16_t *c = cbuf + r * SCREEN_W, *z = zbuf + r * SCREEN_W;
+ for (int x = x0; x < x1; x++) {
+ c[x] = sky565;
+ z[x] = 0xFFFF;
+ }
+ }
+ }
+ for (int i = 0; i < nobj; i++) {
+ RObj *r = &robj[i];
+ if (r->ymin > r->ymax || r->ymax < strip_y0 || r->ymin >= strip_y1) continue;
+ draw_object(&objs[i], r);
+ }
+ draw_shadows();
+ return cbuf;
+}
+
+void render_frame(void (*post)(uint16_t *px, int y, int n)) {
+ render_prepare(0, SCREEN_W);
+ for (int sy = 0; sy < SCREEN_H; sy += STRIP_H) {
+ int n = SCREEN_H - sy < STRIP_H ? SCREEN_H - sy : STRIP_H;
+ render_strip(sy, n, 0, SCREEN_W);
+ if (post) post(cbuf, sy, n);
+ plat_push(0, sy, SCREEN_W, n, cbuf);
+ }
+}
diff --git a/games/numdrive/src/render.h b/games/numdrive/src/render.h
new file mode 100644
index 00000000..48c926cd
--- /dev/null
+++ b/games/numdrive/src/render.h
@@ -0,0 +1,39 @@
+#ifndef RENDER_H
+#define RENDER_H
+#include <stdint.h>
+#include <stdbool.h>
+#include "fmath.h"
+
+#define STRIP_H 16
+
+typedef struct {
+ vec3 focus;
+ quat rot;
+ float range;
+ int perspective;
+ vec3 right, up, fwd;
+ float scale; /* pixels per world unit (ortho) */
+ vec3 shake;
+ float cx, cy; /* screen position of the focus */
+ float zoom_mul; /* extra magnification (photos) */
+ float roll; /* extra roll in radians (photos) */
+} Camera;
+
+extern Camera cam;
+extern uint16_t sky565;
+
+bool render_init_level(void); /* per level renderer data (arena) */
+void render_frame(void (*post)(uint16_t *px, int y, int n)); /* full screen, post draws overlays */
+void render_prepare(int x0, int x1); /* per-view object culling */
+uint16_t *render_strip(int y, int n, int x0, int x1); /* world into the strip buffer */
+uint16_t *render_buffer(void);
+void *render_scratch(void); /* SCREEN_W * STRIP_H * 2 bytes, free outside rendering */
+void cam_default(void);
+void cam_view(float cx, float cy, float zoom_mul, float roll);
+void cam_update(void);
+uint16_t rgb565(int r, int g, int b);
+void shade_color(int pal, vec3 n, int *r, int *g, int *b);
+
+extern const uint8_t palette_rgb[34][3];
+
+#endif
diff --git a/games/numdrive/src/save.c b/games/numdrive/src/save.c
new file mode 100644
index 00000000..7501d578
--- /dev/null
+++ b/games/numdrive/src/save.c
@@ -0,0 +1,113 @@
+/* Progress persistence. On the calculator the progress lives in a small record
+ * ("drivemad.sav") of the Epsilon file storage, located through the userland header. */
+#include <string.h>
+#include "save.h"
+
+Progress progress;
+
+
+#if defined(HOST) || defined(NO_STORAGE)
+#ifdef HOST
+#include <stdio.h>
+#include <stdlib.h>
+#endif
+void save_load(void) {
+ memset(&progress, 0, sizeof progress);
+#ifdef HOST
+ const char *f = getenv("ND_SAVE");
+ FILE *fp = f ? fopen(f, "rb") : 0;
+ if (fp) {
+ if (fread(&progress, sizeof progress, 1, fp) != 1) memset(&progress, 0, sizeof progress);
+ fclose(fp);
+ }
+#endif
+}
+void save_store(void) {
+#ifdef HOST
+ const char *f = getenv("ND_SAVE");
+ FILE *fp = f ? fopen(f, "wb") : 0;
+ if (fp) {
+ fwrite(&progress, sizeof progress, 1, fp);
+ fclose(fp);
+ }
+#endif
+}
+#else
+
+static const char rec_name[] = "drivemad.sav";
+#define SAVE_MAGIC 0x444Du
+#define USERLAND_MAGIC 0xDEC0EDFEu
+#define STORAGE_MAGIC 0xEE0BDDBAu
+
+static uint8_t *storage_buf;
+static uint32_t storage_size;
+
+static bool find_storage(void) {
+ static const uint32_t cand[] = {0x90010000u, 0x90410000u};
+ for (int i = 0; i < 2; i++) {
+ const uint32_t *h = (const uint32_t *)cand[i];
+ if (h[0] != USERLAND_MAGIC || h[11] != USERLAND_MAGIC) continue;
+ uint32_t addr = h[3], size = h[4];
+ if (addr < 0x20000000u || addr >= 0x24080000u || size < 1024 || size > 0x20000) continue;
+ const uint32_t *fs = (const uint32_t *)addr;
+ if (fs[0] != STORAGE_MAGIC) continue;
+ uint32_t foot;
+ memcpy(&foot, (const uint8_t *)addr + 4 + size, 4);
+ if (foot != STORAGE_MAGIC) continue;
+ storage_buf = (uint8_t *)addr + 4;
+ storage_size = size;
+ return true;
+ }
+ return false;
+}
+
+static inline uint16_t rd16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); }
+static inline void wr16(uint8_t *p, uint16_t v) {
+ p[0] = (uint8_t)v;
+ p[1] = (uint8_t)(v >> 8);
+}
+
+/* walk records; returns our record (or 0) and the end of used space */
+static uint8_t *find_record(uint8_t **end) {
+ uint8_t *p = storage_buf, *lim = storage_buf + storage_size, *found = 0;
+ while (p + 2 <= lim) {
+ uint16_t sz = rd16(p);
+ if (sz == 0) break;
+ if (sz < 3 || p + sz > lim) return *end = 0, (uint8_t *)0; /* corrupt: do not touch */
+ if (!found && strcmp((const char *)p + 2, rec_name) == 0) found = p;
+ p += sz;
+ }
+ *end = p;
+ return found;
+}
+
+#define REC_SIZE (2 + sizeof rec_name + 2 + sizeof(Progress))
+
+void save_load(void) {
+ memset(&progress, 0, sizeof progress);
+ if (!storage_buf && !find_storage()) return;
+ uint8_t *end, *r = find_record(&end);
+ if (!r || rd16(r) != REC_SIZE) return;
+ const uint8_t *d = r + 2 + sizeof rec_name;
+ if (rd16(d) != SAVE_MAGIC) return;
+ memcpy(&progress, d + 2, sizeof progress);
+}
+
+void save_store(void) {
+ if (!storage_buf && !find_storage()) return;
+ uint8_t *end, *r = find_record(&end);
+ if (!end) return;
+ if (r && rd16(r) != REC_SIZE) return;
+ if (!r) {
+ /* append, keeping a comfortable margin and the terminating zero size */
+ if ((uint32_t)(end - storage_buf) + REC_SIZE + 2 + 256 > storage_size) return;
+ r = end;
+ wr16(r, REC_SIZE);
+ memcpy(r + 2, rec_name, sizeof rec_name);
+ wr16(r + REC_SIZE, 0);
+ }
+ uint8_t *d = r + 2 + sizeof rec_name;
+ wr16(d, SAVE_MAGIC);
+ memcpy(d + 2, &progress, sizeof progress);
+}
+#endif
diff --git a/games/numdrive/src/save.h b/games/numdrive/src/save.h
new file mode 100644
index 00000000..ac23c136
--- /dev/null
+++ b/games/numdrive/src/save.h
@@ -0,0 +1,20 @@
+#ifndef SAVE_H
+#define SAVE_H
+#include <stdint.h>
+#include <stdbool.h>
+
+/* progress: one bit per completed level, plus the last played level */
+typedef struct {
+ uint8_t done[25];
+ uint8_t last;
+ uint8_t pad[2];
+} Progress;
+
+extern Progress progress;
+void save_load(void);
+void save_store(void);
+
+static inline bool lvl_done(int i) { return (progress.done[i >> 3] >> (i & 7)) & 1; }
+static inline void lvl_set_done(int i) { progress.done[i >> 3] |= (uint8_t)(1 << (i & 7)); }
+
+#endif
diff --git a/games/numdrive/src/ui.c b/games/numdrive/src/ui.c
new file mode 100644
index 00000000..5e89c92d
--- /dev/null
+++ b/games/numdrive/src/ui.c
@@ -0,0 +1,592 @@
+/* In-game HUD, photo cards (pause / win / lose) and the level list, drawn like Fancade's UI. */
+#include <math.h>
+#include <string.h>
+#include "ui.h"
+#include "gfx.h"
+#include "render.h"
+#include "world.h"
+#include "save.h"
+#include "platform.h"
+
+/* palette sampled from the original */
+#define C_OUTLINE RGB(0x39, 0x39, 0x4c)
+#define C_PILL_TXT RGB(0xb1, 0xc0, 0xd3)
+#define C_CAPTION RGB(0xa4, 0xb2, 0xc4)
+#define C_BLUE RGB(0x00, 0x8c, 0xff)
+#define C_BLUE_D RGB(0x00, 0x6a, 0xd8)
+#define C_GRAY RGB(0xb2, 0xb7, 0xcb)
+#define C_GRAY_D RGB(0x7a, 0x81, 0x99)
+#define C_PANEL RGB(0x00, 0xb9, 0xff)
+#define C_PANEL_D RGB(0x00, 0x8b, 0xbf)
+#define C_PANEL_TXT RGB(0xb4, 0xe4, 0xff)
+#define C_GREEN RGB(0x39, 0xc7, 0x46)
+#define C_GREEN_D RGB(0x26, 0x8f, 0x34)
+#define C_TILE_B RGB(0x00, 0x7a, 0xee)
+#define C_TILE_BD RGB(0x00, 0x58, 0xc0)
+#define C_LOCK RGB(0x68, 0x76, 0x95)
+#define C_LOCK_D RGB(0x56, 0x62, 0x7e)
+#define C_SHADOW RGB(0x10, 0x1c, 0x58)
+#define C_TITLE_O RGB(0x19, 0x1a, 0x1b)
+
+/* ------------------------------------------------------------------- HUD */
+static int hud_t;
+static uint8_t hud_btn, hud_used;
+static int fade_l, fade_r;
+float hud_score, hud_coins;
+
+void hud_reset(void) {
+ hud_t = 0;
+ hud_score = hud_coins = -1;
+ hud_btn = hud_used = 0;
+ fade_l = fade_r = 32;
+}
+
+void hud_tick(uint8_t buttons) {
+ hud_t++;
+ hud_btn = buttons;
+ hud_used |= buttons;
+ if ((hud_used & 1) && fade_l > 0) fade_l -= 4;
+ if ((hud_used & 2) && fade_r > 0) fade_r -= 4;
+}
+
+static void hint_box(int x, int y, const Icon *ic, bool on) {
+ if (on) {
+ g_rect(x, y, 18, 18, C_WHITE, 29);
+ g_icon(ic, x + 6, y + 6, sky565, 32);
+ } else {
+ g_rect(x + 2, y + 2, 14, 14, C_WHITE, 10);
+ g_rect(x, y, 18, 2, C_WHITE, 20);
+ g_rect(x, y + 16, 18, 2, C_WHITE, 20);
+ g_rect(x, y + 2, 2, 14, C_WHITE, 20);
+ g_rect(x + 16, y + 2, 2, 14, C_WHITE, 20);
+ g_icon(ic, x + 6, y + 6, C_WHITE, 24);
+ }
+}
+
+/* Set Score counter text: white halo, dark outline and a face with a darker extruded bottom */
+static void counter_text(const Font *f, int xr, int y, const char *s, uint16_t face, uint16_t side, uint16_t outl,
+ int depth) {
+ int x = xr - g_text_w(f, s);
+ for (int dy = -2; dy <= depth + 2; dy++)
+ for (int dx = -2; dx <= 2; dx++)
+ if ((dx != -2 && dx != 2) || (dy != -2 && dy != depth + 2)) g_text(f, x + dx, y + dy, s, C_WHITE, 32);
+ for (int dy = -1; dy <= depth + 1; dy++)
+ for (int dx = -1; dx <= 1; dx++) g_text(f, x + dx, y + dy, s, outl, 32);
+ for (int dy = depth; dy > 0; dy--) g_text(f, x, y + dy, s, side, 32);
+ g_text(f, x, y, s, face, 32);
+}
+
+/* the gold coin next to the coin count: a diamond with a raised rim and a thick lower edge */
+static void coin_icon(int cx, int cy) {
+ enum { R = 5, E = 2 };
+ for (int y = cy - R - 2; y <= cy + R + E + 2; y++) {
+ if (y < gc.y0 || y >= gc.y1) continue;
+ for (int x = cx - R - 2; x <= cx + R + 2; x++) {
+ int dx = x - cx, dy = y - cy, ax = dx < 0 ? -dx : dx;
+ int d = ax + (dy < 0 ? -dy : dy);
+ int de = ax + (dy < 0 ? -dy : dy > E ? dy - E : 0);
+ uint16_t c;
+ int a = 32;
+ if (de > R + 2) continue;
+ if (de == R + 2) c = C_WHITE, a = 24;
+ else if (de == R + 1) c = C_OUTLINE;
+ else if (d > R) c = RGB(0xca, 0x84, 0x00);
+ else if (d == R) c = dx + dy < 0 ? RGB(0xff, 0xff, 0x80) : RGB(0xff, 0xd8, 0x00);
+ else if (d > 2) c = RGB(0xff, 0xd8, 0x00);
+ else if (d == 2) c = dx + dy < 0 ? RGB(0xca, 0x84, 0x00) : RGB(0xff, 0xe0, 0x00);
+ else c = RGB(0xed, 0xaf, 0x00);
+ g_rect(x, y, 1, 1, c, a);
+ }
+ }
+}
+
+static char *fmt_uint(char *p, unsigned v) {
+ char t[10];
+ int n = 0;
+ do t[n++] = (char)('0' + v % 10), v /= 10;
+ while (v && n < 10);
+ while (n) *p++ = t[--n];
+ return p;
+}
+
+static void draw_counters(void) {
+ char buf[16];
+ if (hud_score >= 0 && gc.y0 < 38) {
+ unsigned t = hud_score < 9e7f ? (unsigned)(hud_score * 10 + 0.5f) : 999999999u;
+ char *p = fmt_uint(buf, t / 10);
+ *p++ = '.';
+ *p++ = (char)('0' + t % 10);
+ *p = 0;
+ counter_text(&font_l, 312, 18 - font_l.cap_top, buf, C_WHITE, RGB(0xb8, 0xbe, 0xcc), C_OUTLINE, 2);
+ }
+ if (hud_coins >= 0 && gc.y1 > 28 && gc.y0 < 48) {
+ *fmt_uint(buf, hud_coins < 4e9f ? (unsigned)(hud_coins + 0.5f) : 0) = 0;
+ counter_text(&font_s, 300, 34 - font_s.cap_top, buf, RGB(0xff, 0xd8, 0x00), RGB(0xc0, 0x99, 0x00),
+ RGB(0x3f, 0x30, 0x00), 1);
+ coin_icon(306, 38);
+ }
+}
+
+static void draw_pill(const char *txt, int y) {
+ int w = g_text_w(&font_s, txt) + 22;
+ int x = 160 - w / 2;
+ g_rrect(x - 1, y - 1, w + 2, 14, 7, C_BLACK, 32);
+ g_rrect(x, y, w, 12, 6, C_WHITE, 32);
+ g_text_c(&font_s, 160, y + 6 - (font_s.cap_top + font_s.base) / 2, txt, C_PILL_TXT, 32);
+}
+
+void hud_draw(uint16_t *px, int y, int n) {
+ g_begin(px, y, n);
+ if (y < 30) {
+ g_icon(&ic_pause_o, 7, 6, C_OUTLINE, 32);
+ g_icon(&ic_pause_f, 7, 6, C_WHITE, 32);
+ if (hud_t < 150 + 12) {
+ int py = 7 - (hud_t > 150 ? (hud_t - 150) * 2 : 0);
+ static char buf[40];
+ const char *nm = level.name;
+ int i = 0;
+ const char *pre = "Level ";
+ while (*pre) buf[i++] = *pre++;
+ int num = level_index + 1;
+ if (num >= 100) buf[i++] = (char)('0' + num / 100);
+ if (num >= 10) buf[i++] = (char)('0' + num / 10 % 10);
+ buf[i++] = (char)('0' + num % 10);
+ buf[i++] = ':';
+ buf[i++] = ' ';
+ while (*nm && i < 38) buf[i++] = *nm++;
+ buf[i] = 0;
+ draw_pill(buf, py);
+ }
+ }
+ draw_counters();
+ if (y + n > 104 && y < 122) {
+ hint_box(16, 104, &ic_left, hud_btn & 1);
+ hint_box(286, 104, &ic_right, (hud_btn & 2) != 0);
+ }
+ if (y + n > 180 && y < 216) {
+ if (fade_l > 0) {
+ g_icon(&ic_back, 36, 184, C_WHITE, fade_l * 14 / 32);
+ g_icon(&ic_back, 37, 184, C_WHITE, fade_l * 14 / 32);
+ }
+ if (fade_r > 0) {
+ g_icon(&ic_next, 274, 184, C_WHITE, fade_r * 14 / 32);
+ g_icon(&ic_next, 275, 184, C_WHITE, fade_r * 14 / 32);
+ }
+ }
+}
+
+/* viewfinder brackets shown just before the photo is taken */
+void viewfinder_draw(uint16_t *px, int y, int n, int t) {
+ g_begin(px, y, n);
+ int m = 6 - t / 2; /* brackets tighten slightly */
+ if (m < 0) m = 0;
+ int x0 = 40 + m, x1 = 280 - m, y0 = m, y1 = 240 - m, L = 34, T = 3;
+ g_rect(x0, y0, L, T, C_WHITE, 32);
+ g_rect(x0, y0, T, L, C_WHITE, 32);
+ g_rect(x1 - L, y0, L, T, C_WHITE, 32);
+ g_rect(x1 - T, y0, T, L, C_WHITE, 32);
+ g_rect(x0, y1 - T, L, T, C_WHITE, 32);
+ g_rect(x0, y1 - L, T, L, C_WHITE, 32);
+ g_rect(x1 - L, y1 - T, L, T, C_WHITE, 32);
+ g_rect(x1 - T, y1 - L, T, L, C_WHITE, 32);
+ /* focus arc */
+ const float R = 28;
+ for (int yy = y; yy < y + n; yy++) {
+ float dy = yy + 0.5f - 120;
+ if (fabsf(dy) > R + 2) continue;
+ for (int xx = 130; xx < 190; xx++) {
+ float dx = xx + 0.5f - 160, d = sqrtf(dx * dx + dy * dy), e = fabsf(d - R);
+ if (e > 1.2f || dy > 0 || dx < -6) continue;
+ int a = (int)((1.2f - e) * 14);
+ uint16_t *p = px + (yy - y) * SCREEN_W + xx;
+ *p = mix565(*p, C_WHITE, a);
+ }
+ }
+}
+
+/* ------------------------------------------------------------ background */
+#define BW 40
+#define BH 30
+static uint8_t (*blur)[BW][3]; /* allocated from the level arena when a menu first opens */
+
+void ui_capture_background(void) {
+ static uint16_t acc[BW][3];
+ static int blur_level = -1;
+ if (!blur || blur_level != level_serial) {
+ blur = arena_keep_alloc(sizeof(uint8_t) * BH * BW * 3);
+ blur_level = level_serial;
+ }
+ if (!blur) return;
+ cam_view(SCREEN_W * 0.5f, SCREEN_H * 0.5f, 1, 0);
+ render_prepare(0, SCREEN_W);
+ for (int sy = 0; sy < SCREEN_H; sy += STRIP_H) {
+ int n = SCREEN_H - sy < STRIP_H ? SCREEN_H - sy : STRIP_H;
+ uint16_t *b = render_strip(sy, n, 0, SCREEN_W);
+ for (int by = 0; by < n / 8; by++) { /* STRIP_H is a multiple of 8 */
+ memset(acc, 0, sizeof acc);
+ for (int r = 0; r < 8; r++) {
+ const uint16_t *row = b + (by * 8 + r) * SCREEN_W;
+ for (int x = 0; x < SCREEN_W; x++) {
+ uint16_t c = row[x];
+ acc[x >> 3][0] += c >> 11;
+ acc[x >> 3][1] += (c >> 5) & 63;
+ acc[x >> 3][2] += c & 31;
+ }
+ }
+ uint8_t(*o)[3] = blur[sy / 8 + by];
+ for (int i = 0; i < BW; i++) {
+ o[i][0] = (uint8_t)(acc[i][0] * 255 / (64 * 31));
+ o[i][1] = (uint8_t)(acc[i][1] * 255 / (64 * 63));
+ o[i][2] = (uint8_t)(acc[i][2] * 255 / (64 * 31));
+ }
+ }
+ }
+ /* soften: two separable box passes */
+ uint8_t(*t)[BW][3] = render_scratch();
+ for (int pass = 0; pass < 2; pass++) {
+ for (int y = 0; y < BH; y++)
+ for (int x = 0; x < BW; x++)
+ for (int k = 0; k < 3; k++) {
+ int a = x > 0 ? x - 1 : 0, b2 = x < BW - 1 ? x + 1 : BW - 1;
+ t[y][x][k] = (uint8_t)((blur[y][a][k] + 2 * blur[y][x][k] + blur[y][b2][k]) >> 2);
+ }
+ for (int y = 0; y < BH; y++)
+ for (int x = 0; x < BW; x++)
+ for (int k = 0; k < 3; k++) {
+ int a = y > 0 ? y - 1 : 0, b2 = y < BH - 1 ? y + 1 : BH - 1;
+ blur[y][x][k] = (uint8_t)((t[a][x][k] + 2 * t[y][x][k] + t[b2][x][k]) >> 2);
+ }
+ }
+}
+
+/* one screen row of the blurred background, columns [x0, x1) */
+static void bg_row(uint16_t *dst, int y, int x0, int x1) {
+ static uint16_t row[BW][3];
+ if (!blur) {
+ for (int x = x0; x < x1; x++) dst[x] = sky565;
+ return;
+ }
+ int ty = 2 * y + 1 - 8, iy = ty >> 4, wy = ty & 15;
+ if (iy < 0) iy = 0, wy = 0;
+ if (iy >= BH - 1) iy = BH - 2, wy = 16;
+ for (int i = 0; i < BW; i++)
+ for (int k = 0; k < 3; k++) row[i][k] = (uint16_t)(blur[iy][i][k] * (16 - wy) + blur[iy + 1][i][k] * wy);
+ for (int x = x0; x < x1; x++) {
+ int tx = 2 * x + 1 - 8, ix = tx >> 4, wx = tx & 15;
+ if (ix < 0) ix = 0, wx = 0;
+ if (ix >= BW - 1) ix = BW - 2, wx = 16;
+ int r = (row[ix][0] * (16 - wx) + row[ix + 1][0] * wx) >> 8;
+ int g = (row[ix][1] * (16 - wx) + row[ix + 1][1] * wx) >> 8;
+ int b = (row[ix][2] * (16 - wx) + row[ix + 1][2] * wx) >> 8;
+ dst[x] = RGB(r, g, b);
+ }
+}
+
+/* ------------------------------------------------------------------ cards */
+typedef struct {
+ int16_t x0, y0, x1, y1;
+ uint16_t c;
+} Box;
+typedef struct {
+ const Font *f;
+ int16_t x, y, w;
+ uint16_t c;
+ const char *s;
+} Run;
+
+static struct {
+ int kind, level;
+ float w, h, ang;
+ float cx, cy;
+ Box photo;
+ Box box[3];
+ int nbox;
+ Run run[12];
+ int nrun;
+ char txt[4][24];
+} cd;
+
+static void add_run(const Font *f, int x, int baseline, const char *s, uint16_t c, bool center) {
+ Run *r = &cd.run[cd.nrun++];
+ r->f = f;
+ r->w = (int16_t)g_text_w(f, s);
+ r->x = (int16_t)(center ? x - r->w / 2 : x);
+ r->y = (int16_t)(baseline - f->base);
+ r->c = c;
+ r->s = s;
+}
+
+static const char *const desc[] = {"Drive silly cars at high", "speeds in dangerous", "terrain. Oh, and you",
+ "can't steer. Good luck!"};
+
+void card_setup(int kind, int lvl) {
+ memset(&cd, 0, sizeof cd);
+ cd.kind = kind;
+ cd.level = lvl;
+ if (kind == CARD_PAUSE) {
+ cd.w = 206;
+ cd.h = 166;
+ cd.ang = -5.4f * 3.14159265f / 180;
+ cd.cx = 160;
+ cd.cy = 92;
+ /* content: x in [-91, 91], y in [-71, 47] */
+ cd.box[0] = (Box){-91, -71, 44, 12, C_PANEL};
+ cd.box[1] = (Box){-91, 12, 44, 47, C_PANEL_D};
+ cd.nbox = 2;
+ cd.photo = (Box){44, -71, 91, 47, 0};
+ for (int i = 0; i < 4; i++) add_run(&font_s, -86, -58 + i * 10, desc[i], C_WHITE, false);
+ add_run(&font_s, -86, 4, "Inspired by Drive Mad", C_WHITE, false);
+ add_run(&font_s, -86, 24, "Made by Mason Chen", C_WHITE, false);
+ char *t = cd.txt[0];
+ int n = lvl + 1, i = 0;
+ const char *pre = "Level ";
+ while (*pre) t[i++] = *pre++;
+ if (n >= 100) t[i++] = (char)('0' + n / 100);
+ if (n >= 10) t[i++] = (char)('0' + n / 10 % 10);
+ t[i++] = (char)('0' + n % 10);
+ t[i] = 0;
+ add_run(&font_s, -86, 34, t, C_PANEL_TXT, false);
+ strcpy(cd.txt[1], level_name(lvl));
+ add_run(&font_s, -86, 43, cd.txt[1], C_PANEL_TXT, false);
+ add_run(&font_m, 0, 66, "NumDrive", C_CAPTION, true);
+ } else {
+ cd.w = 143;
+ cd.h = 156;
+ cd.ang = -10.5f * 3.14159265f / 180;
+ cd.cx = 160;
+ cd.cy = 91;
+ cd.photo = (Box){-59, -66, 59, 52, 0};
+ add_run(&font_m, 0, 69, kind == CARD_WIN ? "Good game" : "Terminated", C_CAPTION, true);
+ }
+}
+
+int card_buttons(void) { return cd.kind == CARD_LOSE ? 1 : 2; }
+
+/* 2x2 bilinear sample of a text run, returns alpha 0..32 */
+static int run_texel(const Run *r, int x, int y) {
+ if (y < 0 || y >= r->f->h) return 0;
+ int pos = 0;
+ for (const char *s = r->s; *s; s++) {
+ const Glyph *g = font_glyph(r->f, (unsigned char)*s);
+ if (!g) continue;
+ if (x >= pos + g->xoff && x < pos + g->xoff + g->w) {
+ int a = glyph_alpha(r->f, g, x - pos, y);
+ if (a) return a;
+ }
+ pos += g->adv;
+ if (pos + 4 < x) continue;
+ if (pos > x + 4) break;
+ }
+ return 0;
+}
+
+static int run_alpha(const Run *r, float u, float v) {
+ float tx = u - r->x - 0.5f, ty = v - r->y - 0.5f;
+ if (tx < -2 || tx > r->w + 2 || ty < -1 || ty > r->f->h) return 0;
+ int ix = (int)floorf(tx), iy = (int)floorf(ty);
+ float fx = tx - ix, fy = ty - iy;
+ float a = run_texel(r, ix, iy) * (1 - fx) * (1 - fy) + run_texel(r, ix + 1, iy) * fx * (1 - fy) +
+ run_texel(r, ix, iy + 1) * (1 - fx) * fy + run_texel(r, ix + 1, iy + 1) * fx * fy;
+ return (int)(a * 32 / 3 + 0.5f);
+}
+
+static float ease_back(float t) {
+ if (t >= 1) return 1;
+ float s = 1.9f;
+ t -= 1;
+ return t * t * ((s + 1) * t + s) + 1;
+}
+
+/* buttons below the card */
+static void card_btns(int sel, int yb) {
+ const int x0 = 89, w = 142, h = 30, r = 6;
+ if (cd.kind == CARD_LOSE) {
+ g_button(x0, yb, w, h, r, C_BLUE, C_BLUE_D, 0);
+ g_icon(&ic_play, 160 - 6, yb + 3, C_WHITE, 32);
+ g_text_c(&font_s, 160, yb + 25 - font_s.base, "Retry", C_WHITE, 32);
+ } else {
+ const int ws = 46;
+ g_rrect(x0 - 1, yb - 1, w + 2, h + 2, r + 1, C_BLACK, 32);
+ g_rrect(x0, yb, w, h, r, C_BLUE_D, 32);
+ g_rrect(x0, yb, w, h - 3, r, C_BLUE, 32);
+ /* grey restart segment on the left */
+ for (int yy = yb; yy < yb + h; yy++) {
+ if (yy < gc.y0 || yy >= gc.y1) continue;
+ uint16_t *p = gc.px + (yy - gc.y0) * SCREEN_W;
+ for (int x = x0; x < x0 + ws; x++) {
+ uint16_t c = p[x];
+ if (c == C_BLUE) p[x] = C_GRAY;
+ else if (c == C_BLUE_D) p[x] = C_GRAY_D;
+ else if (c != C_BLACK) p[x] = mix565(c, C_GRAY, 20);
+ }
+ }
+ g_icon(&ic_restart, x0 + ws / 2 - 7, yb + 3, C_WHITE, 32);
+ g_text_c(&font_s, x0 + ws / 2, yb + 25 - font_s.base, "Restart", C_WHITE, 32);
+ int cx = x0 + ws + (w - ws) / 2;
+ g_icon(&ic_play, cx - 7, yb + 3, C_WHITE, 32);
+ g_text_c(&font_s, cx, yb + 25 - font_s.base, cd.kind == CARD_PAUSE ? "Resume" : "Next Level", C_WHITE, 32);
+ /* focus ring */
+ int fx = sel == 0 ? x0 : x0 + ws, fw = sel == 0 ? ws : w - ws;
+ g_rect(fx + 1, yb + 1, fw - 2, 1, C_WHITE, 26);
+ g_rect(fx + 1, yb + h - 5, fw - 2, 1, C_WHITE, 26);
+ g_rect(fx + 1, yb + 1, 1, h - 5, C_WHITE, 26);
+ g_rect(fx + fw - 2, yb + 1, 1, h - 5, C_WHITE, 26);
+ }
+}
+
+void card_draw(int anim, int sel, bool full) {
+ float t = anim / 12.0f;
+ float s = 0.55f + 0.45f * ease_back(t);
+ float ang = cd.ang * (t >= 1 ? 1 : 0.3f + 0.7f * ease_back(t));
+ float cs = cosf(ang), sn = sinf(ang);
+ float cx = cd.cx, cy = cd.cy;
+ float hw = cd.w * 0.5f, hh = cd.h * 0.5f;
+ /* screen bbox of card and shadow */
+ float ex = (fabsf(cs) * hw + fabsf(sn) * hh) * s, ey = (fabsf(sn) * hw + fabsf(cs) * hh) * s;
+ int bx0 = (int)(cx - ex) - 1, bx1 = (int)(cx + ex) + 6, by0 = (int)(cy - ey) - 1, by1 = (int)(cy + ey) + 7;
+ if (bx0 < 0) bx0 = 0;
+ if (bx1 > SCREEN_W) bx1 = SCREEN_W;
+ if (by0 < 0) by0 = 0;
+ if (by1 > SCREEN_H) by1 = SCREEN_H;
+ /* photo camera: the photo shows the centre square of the game view */
+ float pu = (cd.photo.x0 + cd.photo.x1) * 0.5f, pv = (cd.photo.y0 + cd.photo.y1) * 0.5f;
+ float ph = (float)(cd.photo.y1 - cd.photo.y0);
+ float pcx = cx + s * (pu * cs - pv * sn), pcy = cy + s * (pu * sn + pv * cs);
+ float pex = (fabsf(cs) * (cd.photo.x1 - cd.photo.x0) + fabsf(sn) * ph) * 0.5f * s;
+ float pey = (fabsf(sn) * (cd.photo.x1 - cd.photo.x0) + fabsf(cs) * ph) * 0.5f * s;
+ int px0 = (int)(pcx - pex), px1 = (int)(pcx + pex) + 2, py0 = (int)(pcy - pey), py1 = (int)(pcy + pey) + 2;
+ if (px0 < 0) px0 = 0;
+ if (px1 > SCREEN_W) px1 = SCREEN_W;
+ Camera saved = cam;
+ cam_view(pcx, pcy, s * ph / 240.0f, -ang);
+ render_prepare(px0, px1);
+ int ybtn = 190;
+ int y_lo = full ? 0 : by0, y_hi = full ? SCREEN_H : by1;
+ int cx0 = full ? 0 : bx0, cx1 = full ? SCREEN_W : bx1;
+ for (int sy = y_lo - y_lo % STRIP_H; sy < y_hi; sy += STRIP_H) {
+ int n = SCREEN_H - sy < STRIP_H ? SCREEN_H - sy : STRIP_H;
+ uint16_t *buf = render_buffer();
+ bool photo_here = sy < py1 && sy + n > py0;
+ if (photo_here) render_strip(sy, n, px0, px1);
+ for (int r = 0; r < n; r++) {
+ int y = sy + r;
+ uint16_t *row = buf + r * SCREEN_W;
+ static uint16_t world[SCREEN_W];
+ bool in_rows = y >= by0 && y < by1;
+ if (photo_here && y >= py0 && y < py1) memcpy(world + px0, row + px0, (size_t)(px1 - px0) * 2);
+ bg_row(row, y, cx0, cx1);
+ if (!in_rows) continue;
+ float dy = y + 0.5f - cy;
+ for (int x = bx0; x < bx1; x++) {
+ float dx = x + 0.5f - cx;
+ float u = (dx * cs + dy * sn) / s, v = (-dx * sn + dy * cs) / s;
+ float e = fminf(hw - fabsf(u), hh - fabsf(v)) * s;
+ uint16_t bgc = row[x];
+ if (e < 0.5f) {
+ /* shadow */
+ float dx2 = dx - 3, dy2 = dy - 4;
+ float u2 = (dx2 * cs + dy2 * sn) / s, v2 = (-dx2 * sn + dy2 * cs) / s;
+ float e2 = fminf(hw - fabsf(u2), hh - fabsf(v2)) * s;
+ if (e2 > -0.5f) bgc = mix565(bgc, C_SHADOW, (int)(13 * fminf(1, e2 + 0.5f)));
+ if (e <= -0.5f) {
+ row[x] = bgc;
+ continue;
+ }
+ }
+ uint16_t c = C_WHITE;
+ if (u >= cd.photo.x0 && u < cd.photo.x1 && v >= cd.photo.y0 && v < cd.photo.y1 && photo_here && x >= px0 &&
+ x < px1) {
+ c = world[x];
+ } else {
+ for (int i = 0; i < cd.nbox; i++)
+ if (u >= cd.box[i].x0 && u < cd.box[i].x1 && v >= cd.box[i].y0 && v < cd.box[i].y1) c = cd.box[i].c;
+ for (int i = 0; i < cd.nrun; i++) {
+ const Run *rn = &cd.run[i];
+ if (v < rn->y - 1 || v > rn->y + rn->f->h + 1 || u < rn->x - 2 || u > rn->x + rn->w + 2) continue;
+ int a = run_alpha(rn, u, v);
+ if (a) c = mix565(c, rn->c, a > 32 ? 32 : a);
+ }
+ }
+ if (e < 0.5f) c = mix565(bgc, c, (int)((e + 0.5f) * 32));
+ row[x] = c;
+ }
+ }
+ g_begin(buf, sy, n);
+ if (full || (ybtn - 3 < sy + n && ybtn + 33 > sy)) card_btns(sel, ybtn);
+ if (full) {
+ g_icon(&ic_back, 34, 84, C_WHITE, 32);
+ g_icon(&ic_back, 35, 84, C_WHITE, 32);
+ }
+ if (full)
+ plat_push(0, sy, SCREEN_W, n, buf);
+ else {
+ int r0 = sy < by0 ? by0 - sy : 0, r1 = sy + n > by1 ? by1 - sy : n;
+ for (int r = r0; r < r1; r++) plat_push(bx0, sy + r, bx1 - bx0, 1, buf + r * SCREEN_W + bx0);
+ }
+ }
+ cam = saved;
+ cam_update();
+}
+
+/* ---------------------------------------------------------------- levels */
+#define TILE 28
+#define PITCH 34
+#define GX (160 - (5 * PITCH - (PITCH - TILE)) / 2)
+#define GY 46
+
+bool level_unlocked(int i) { return i == 0 || lvl_done(i) || lvl_done(i - 1); }
+
+void levels_draw(int sel, int scroll) {
+ for (int sy = 0; sy < SCREEN_H; sy += STRIP_H) {
+ int n = SCREEN_H - sy < STRIP_H ? SCREEN_H - sy : STRIP_H;
+ uint16_t *buf = render_buffer();
+ for (int r = 0; r < n; r++) bg_row(buf + r * SCREEN_W, sy + r, 0, SCREEN_W);
+ g_begin(buf, sy, n);
+ if (sy < 40) {
+ int ty = 22 - font_l.base;
+ for (int d = 0; d < 8; d++) {
+ static const int8_t o[8][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {-1, 1}, {1, -1}};
+ g_text_c(&font_l, 160 + o[d][0], ty + o[d][1] + 1, "Levels", C_TITLE_O, 32);
+ }
+ g_text_c(&font_l, 160, ty, "Levels", C_WHITE, 32);
+ }
+ for (int row = 0; row < 7; row++) {
+ int ly = GY + row * PITCH;
+ if (ly >= sy + n || ly + TILE + 3 <= sy) continue;
+ int fade = ly > 190 ? 32 - (ly - 190) * 32 / 40 : 32;
+ if (fade <= 0) continue;
+ for (int col = 0; col < 5; col++) {
+ int i = (scroll + row) * 5 + col;
+ if (i >= nlevels) break;
+ int lx = GX + col * PITCH;
+ uint16_t top, bot;
+ bool unl = level_unlocked(i);
+ if (lvl_done(i)) top = C_GREEN, bot = C_GREEN_D;
+ else if (unl) top = C_TILE_B, bot = C_TILE_BD;
+ else top = C_LOCK, bot = C_LOCK_D;
+ if (fade < 32 || !unl) {
+ /* translucent tiles over the background */
+ int a = unl ? fade : fade * 24 / 32;
+ g_rrect(lx - 1, ly - 1, TILE + 2, TILE + 2, 6, C_BLACK, a);
+ g_rrect(lx, ly, TILE, TILE, 5, bot, a);
+ g_rrect(lx, ly, TILE, TILE - 3, 5, top, a);
+ } else {
+ g_button(lx, ly, TILE, TILE, 5, top, bot, i == sel);
+ }
+ char num[4];
+ int k = 0, v = i + 1;
+ if (v >= 100) num[k++] = (char)('0' + v / 100);
+ if (v >= 10) num[k++] = (char)('0' + v / 10 % 10);
+ num[k++] = (char)('0' + v % 10);
+ num[k] = 0;
+ g_text_c(&font_m, lx + TILE / 2, ly + (TILE - 3) / 2 - (font_m.cap_top + font_m.base) / 2 + 1, num, C_WHITE,
+ unl ? fade : fade * 20 / 32);
+ }
+ }
+ if (sy < 110 && sy + n > 84) {
+ g_icon(&ic_back, 34, 84, C_WHITE, 32);
+ g_icon(&ic_back, 35, 84, C_WHITE, 32);
+ }
+ plat_push(0, sy, SCREEN_W, n, buf);
+ }
+}
diff --git a/games/numdrive/src/ui.h b/games/numdrive/src/ui.h
new file mode 100644
index 00000000..244cefcc
--- /dev/null
+++ b/games/numdrive/src/ui.h
@@ -0,0 +1,24 @@
+#ifndef UI_H
+#define UI_H
+#include <stdint.h>
+#include <stdbool.h>
+
+enum { CARD_PAUSE, CARD_WIN, CARD_LOSE };
+
+/* in-game overlay */
+void hud_reset(void);
+extern float hud_score, hud_coins; /* Set Score values, hidden when negative */
+void hud_tick(uint8_t buttons);
+void hud_draw(uint16_t *px, int y, int n);
+void viewfinder_draw(uint16_t *px, int y, int n, int t);
+
+/* menus: capture the blurred background from the current view */
+void ui_capture_background(void);
+/* card screen; anim counts frames since the card appeared; sel is the focused button */
+void card_setup(int kind, int level);
+void card_draw(int anim, int sel, bool full);
+int card_buttons(void); /* number of buttons (1 or 2) */
+/* level select */
+void levels_draw(int sel, int scroll);
+
+#endif
diff --git a/games/numdrive/src/vm.c b/games/numdrive/src/vm.c
new file mode 100644
index 00000000..5364357e
--- /dev/null
+++ b/games/numdrive/src/vm.c
@@ -0,0 +1,1090 @@
+/* Fancade script interpreter. */
+#include <string.h>
+#ifdef HOST
+#include <stdio.h>
+#include <stdlib.h>
+#endif
+#include "vm.h"
+#include "world.h"
+#include "physics.h"
+#include "ops.h"
+#include "platform.h"
+#include "ui.h"
+
+typedef struct {
+ uint8_t type;
+ uint8_t cap2; /* capacity: 0, or 1 << (cap2 - 1) elements */
+ uint16_t len;
+ uint8_t *data;
+} VarStore;
+#define VS_CAP(vs) ((vs)->cap2 ? 1 << ((vs)->cap2 - 1) : 0)
+
+typedef struct {
+ VarStore *vs;
+ int32_t idx;
+} Ptr;
+
+typedef struct {
+ uint8_t t;
+ uint8_t isptr;
+ union {
+ float f;
+ vec3 v;
+ quat q;
+ int32_t i;
+ Ptr p;
+ } u;
+} Val;
+
+struct Env {
+ Prog *prog;
+ uint16_t parent, pnode;
+ uint16_t nsub; /* environments in this subtree, itself included */
+ int16_t bx, by, bz;
+ int16_t anchor;
+ uint16_t tbase;
+ int16_t *selfobj;
+ VarStore *locals;
+ Val *slots;
+};
+
+static Env *envs;
+static int nenvs;
+static VarStore *globals;
+int vm_frame_count;
+uint32_t vm_buttons;
+static int button_counter;
+static uint32_t rng_state = 0x12345678u;
+
+#define MAXLATE 64
+static struct { uint16_t env, node; } lateq[MAXLATE];
+static int nlate;
+
+static const uint8_t esize[6] = {4, 12, 16, 1, 2, 2};
+
+static uint16_t rd16(const uint8_t *p) { return p[0] | p[1] << 8; }
+static float rdf(const uint8_t *p) {
+ uint32_t v = p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24;
+ float f;
+ memcpy(&f, &v, 4);
+ return f;
+}
+
+static float rnd01(void) {
+ rng_state ^= rng_state << 13;
+ rng_state ^= rng_state >> 17;
+ rng_state ^= rng_state << 5;
+ return (rng_state >> 8) * (1.0f / 16777216.0f);
+}
+
+/* ---------------------------------------------------------------- program */
+static inline const uint8_t *node_ptr(const Prog *p, int i) { return p->data + p->off[i]; }
+static inline uint16_t node_in(const uint8_t *nd, int k) { return rd16(nd + 1 + 2 * k); }
+/* exec list e (0..nexec-1), e == -1 for After. returns pointer to count byte */
+static const uint8_t *node_exec(const uint8_t *nd, int e) {
+ int op = nd[0];
+ const uint8_t *q = nd + 1 + 2 * op_shape[op][0];
+ int ne = op_shape[op][2];
+ if (e < 0) e = ne;
+ for (int i = 0; i < e; i++) q += 1 + 2 * q[0];
+ return q;
+}
+static const uint8_t *node_data(const uint8_t *nd) {
+ const uint8_t *q = node_exec(nd, -1);
+ return q + 1 + 2 * q[0];
+}
+
+/* -------------------------------------------------------------- variables */
+static VarStore *var_of(Env *e, const uint8_t *data) {
+ uint16_t v = rd16(data);
+ if (v & 0x8000) return &globals[v & 0x7fff];
+ return &e->locals[v];
+}
+
+static void val_default(Val *v, int t) {
+ memset(v, 0, sizeof *v);
+ v->t = t;
+ if (t == T_ROT) v->u.q = qident();
+ if (t == T_OBJ || t == T_CON) v->u.i = -1;
+}
+
+static void var_read(VarStore *vs, int idx, Val *out) {
+ val_default(out, vs->type);
+ if (idx < 0 || idx >= vs->len) return;
+ const uint8_t *d = vs->data + idx * esize[vs->type];
+ switch (vs->type) {
+ case T_NUM: memcpy(&out->u.f, d, 4); break;
+ case T_VEC: memcpy(&out->u.v, d, 12); break;
+ case T_ROT: memcpy(&out->u.q, d, 16); break;
+ case T_TRU: out->u.i = d[0]; break;
+ default: {
+ int16_t s;
+ memcpy(&s, d, 2);
+ out->u.i = s;
+ }
+ }
+}
+
+/* list storage given up when a list grows elsewhere, reused by later growth (the arena never frees) */
+#define NFREE 32
+static struct {
+ uint8_t *p;
+ uint32_t n;
+} freeblk[NFREE];
+static int nfree;
+
+static void give_back(uint8_t *p, uint32_t n) {
+ n = (n + 7) & ~7u;
+ if (!p || !n || arena_release_top(p, n)) return;
+ int k = nfree;
+ if (nfree == NFREE) { /* full: replace the smallest if this one is bigger */
+ k = 0;
+ for (int i = 1; i < NFREE; i++)
+ if (freeblk[i].n < freeblk[k].n) k = i;
+ if (freeblk[k].n >= n) return;
+ } else {
+ nfree++;
+ }
+ freeblk[k].p = p;
+ freeblk[k].n = n;
+}
+
+static uint8_t *list_alloc(uint32_t n) {
+ n = (n + 7) & ~7u;
+ int best = -1;
+ for (int i = 0; i < nfree; i++)
+ if (freeblk[i].n >= n && (best < 0 || freeblk[i].n < freeblk[best].n)) best = i;
+ if (best < 0) return arena_alloc(n);
+ uint8_t *p = freeblk[best].p;
+ uint32_t rest = freeblk[best].n - n;
+ if (rest >= 16) {
+ freeblk[best].p = p + n;
+ freeblk[best].n = rest;
+ } else {
+ freeblk[best] = freeblk[--nfree];
+ }
+ return p;
+}
+
+static void var_write(VarStore *vs, int idx, const Val *v) {
+ if (idx < 0 || idx >= 4096) return;
+ int es = esize[vs->type];
+ int cap = VS_CAP(vs);
+ if (idx >= cap) {
+ int c2 = vs->cap2 ? vs->cap2 : 1;
+ while ((1 << (c2 - 1)) <= idx) c2++;
+ int nc = 1 << (c2 - 1);
+ if (vs->data && arena_extend(vs->data, cap * es, nc * es)) {
+ vs->cap2 = (uint8_t)c2;
+ } else {
+ uint8_t *nd = list_alloc(nc * es);
+ if (!nd) return;
+ if (vs->len) memcpy(nd, vs->data, vs->len * es);
+ give_back(vs->data, cap * es);
+ vs->data = nd;
+ vs->cap2 = (uint8_t)c2;
+ }
+ }
+ while (vs->len <= idx) {
+ Val d;
+ val_default(&d, vs->type);
+ uint8_t *p = vs->data + vs->len * es;
+ switch (vs->type) {
+ case T_NUM: memcpy(p, &d.u.f, 4); break;
+ case T_VEC: memcpy(p, &d.u.v, 12); break;
+ case T_ROT: memcpy(p, &d.u.q, 16); break;
+ case T_TRU: p[0] = 0; break;
+ default: {
+ int16_t s = -1;
+ memcpy(p, &s, 2);
+ }
+ }
+ vs->len++;
+ }
+ uint8_t *p = vs->data + idx * es;
+ switch (vs->type) {
+ case T_NUM: memcpy(p, &v->u.f, 4); break;
+ case T_VEC: memcpy(p, &v->u.v, 12); break;
+ case T_ROT: memcpy(p, &v->u.q, 16); break;
+ case T_TRU: p[0] = v->u.i ? 1 : 0; break;
+ default: {
+ int16_t s = (int16_t)v->u.i;
+ memcpy(p, &s, 2);
+ }
+ }
+}
+
+/* ------------------------------------------------------------- evaluation */
+static void eval(Env *e, uint16_t ref, Val *out);
+static void run_chain(Env *e, uint16_t node);
+static void run_list(Env *e, const uint8_t *lst);
+
+static void deref(Val *v) {
+ if (v->isptr) {
+ Ptr p = v->u.p;
+ var_read(p.vs, p.idx, v);
+ }
+}
+
+static float in_num(Env *e, const uint8_t *nd, int k) {
+ Val v;
+ eval(e, node_in(nd, k), &v);
+ deref(&v);
+ return v.t == T_NUM ? v.u.f : 0;
+}
+static vec3 in_vec(Env *e, const uint8_t *nd, int k) {
+ Val v;
+ eval(e, node_in(nd, k), &v);
+ deref(&v);
+ return v.t == T_VEC ? v.u.v : v3(0, 0, 0);
+}
+static quat in_rot(Env *e, const uint8_t *nd, int k) {
+ Val v;
+ eval(e, node_in(nd, k), &v);
+ deref(&v);
+ return v.t == T_ROT ? v.u.q : qident();
+}
+static int in_tru(Env *e, const uint8_t *nd, int k) {
+ Val v;
+ eval(e, node_in(nd, k), &v);
+ deref(&v);
+ return v.t == T_TRU ? v.u.i != 0 : 0;
+}
+static int in_obj(Env *e, const uint8_t *nd, int k) {
+ Val v;
+ eval(e, node_in(nd, k), &v);
+ deref(&v);
+ if (v.t != T_OBJ && v.t != T_CON) return -1;
+ return v.u.i;
+}
+static bool connected(const uint8_t *nd, int k) { return node_in(nd, k) != NONE16; }
+
+static Env *child_env(Env *e, int node) {
+ int ei = (int)(e - envs);
+ for (int i = ei + 1; i < nenvs; i++)
+ if (envs[i].parent == ei && envs[i].pnode == node) return &envs[i];
+ return 0;
+}
+
+/* block position of this environment (for Get Position without object) */
+static void env_block_pose(Env *e, vec3 *pos, quat *rot) {
+ /* a script block's position is the centre of its model (a low plate for most); inside an object it is
+ that block's centre */
+ vec3 rest = v3(e->bx + 7 / 16.0f, e->by + e->prog->yc / 16.0f, e->bz + 7 / 16.0f);
+ if (e->anchor >= 0) {
+ /* the block's offset in its object is not turned with the object (scripts turn it themselves) */
+ Obj *o = &objs[e->anchor];
+ *pos = vadd(o->pos, vsub(shape_block_center(o->shape, e->bx, e->by, e->bz), o->shape->origin));
+ *rot = o->rot;
+ } else if (e->parent != NONE16 && !envs[e->parent].prog->is_level) {
+ /* not part of an object in its custom block: the enclosing block's position */
+ env_block_pose(&envs[e->parent], pos, rot);
+ } else {
+ *pos = rest;
+ *rot = qident();
+ }
+}
+
+static bool obj_valid(int o) { return o >= 0 && o < nobj && !(objs[o].flags & OF_DEAD); }
+
+static quat quat_lerp(quat a, quat b, float t) {
+ float d = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
+ float s = d < 0 ? -1.0f : 1.0f;
+ quat r = {a.x + (s * b.x - a.x) * t, a.y + (s * b.y - a.y) * t, a.z + (s * b.z - a.z) * t,
+ a.w + (s * b.w - a.w) * t};
+ return qnorm(r);
+}
+
+static quat look_rotation(vec3 fwd, vec3 up) {
+ if (fwd.x == 0 && fwd.y == 0 && fwd.z == 0) return qident();
+ fwd = vnorm(fwd);
+ up = vnorm(up);
+ vec3 right = vcross(up, fwd);
+ if (right.x == 0 && right.y == 0 && right.z == 0) right = v3(1, 0, 0);
+ else right = vnorm(right);
+ up = vcross(fwd, right);
+ /* matrix rows: right, up, fwd (System.Numerics row-vector convention) */
+ float m00 = right.x, m01 = right.y, m02 = right.z;
+ float m10 = up.x, m11 = up.y, m12 = up.z;
+ float m20 = fwd.x, m21 = fwd.y, m22 = fwd.z;
+ float tr = m00 + m11 + m22;
+ quat q;
+ if (tr > 0) {
+ float s = sqrtf(tr + 1.0f);
+ q.w = s * 0.5f;
+ s = 0.5f / s;
+ q.x = (m12 - m21) * s;
+ q.y = (m20 - m02) * s;
+ q.z = (m01 - m10) * s;
+ } else if (m00 >= m11 && m00 >= m22) {
+ float s = sqrtf(1.0f + m00 - m11 - m22);
+ float inv = 0.5f / s;
+ q.x = 0.5f * s;
+ q.y = (m01 + m10) * inv;
+ q.z = (m02 + m20) * inv;
+ q.w = (m12 - m21) * inv;
+ } else if (m11 > m22) {
+ float s = sqrtf(1.0f + m11 - m00 - m22);
+ float inv = 0.5f / s;
+ q.x = (m10 + m01) * inv;
+ q.y = 0.5f * s;
+ q.z = (m21 + m12) * inv;
+ q.w = (m20 - m02) * inv;
+ } else {
+ float s = sqrtf(1.0f + m22 - m00 - m11);
+ float inv = 0.5f / s;
+ q.x = (m20 + m02) * inv;
+ q.y = (m21 + m12) * inv;
+ q.z = 0.5f * s;
+ q.w = (m01 - m10) * inv;
+ }
+ return qnorm(q);
+}
+
+extern vec3 cam_world_to_screen(vec3 p);
+extern void cam_screen_to_world(float sx, float sy, vec3 *near, vec3 *far);
+
+#define RND_MEMO 8
+static struct {
+ const Env *e;
+ uint16_t node;
+ float v;
+} rnd_memo[RND_MEMO];
+static int nrnd;
+
+static void eval_node(Env *e, int ni, int out, Val *r) {
+ const Prog *p = e->prog;
+ const uint8_t *nd = node_ptr(p, ni);
+ int op = nd[0];
+ if (op == OP_CUSTOM) {
+ Env *c = child_env(e, ni);
+ if (!c || out >= c->prog->noutputs) {
+ val_default(r, T_NUM);
+ return;
+ }
+ eval(c, rd16(c->prog->outrefs + 2 * out), r);
+ return;
+ }
+ if (p->slot[ni] != NONE16) {
+ *r = e->slots[p->slot[ni] + out];
+ return;
+ }
+ memset(r, 0, sizeof *r);
+ switch (op) {
+ case OP_NUMBER: r->t = T_NUM; r->u.f = rdf(node_data(nd)); return;
+ case OP_VECTOR: {
+ const uint8_t *d = node_data(nd);
+ r->t = T_VEC;
+ r->u.v = v3(rdf(d), rdf(d + 4), rdf(d + 8));
+ return;
+ }
+ case OP_ROTATION: {
+ const uint8_t *d = node_data(nd);
+ r->t = T_ROT;
+ r->u.q = qeuler(rdf(d), rdf(d + 4), rdf(d + 8));
+ return;
+ }
+ case OP_TRUE: r->t = T_TRU; r->u.i = 1; return;
+ case OP_FALSE: r->t = T_TRU; r->u.i = 0; return;
+ case OP_GET_VAR_NUM: case OP_GET_VAR_VEC: case OP_GET_VAR_ROT: case OP_GET_VAR_TRU: case OP_GET_VAR_OBJ:
+ case OP_GET_VAR_CON: {
+ VarStore *vs = var_of(e, node_data(nd));
+ r->t = vs->type;
+ r->isptr = 1;
+ r->u.p.vs = vs;
+ r->u.p.idx = 0;
+ return;
+ }
+ case OP_LIST_NUM: case OP_LIST_OBJ: case OP_LIST_VEC: case OP_LIST_ROT: case OP_LIST_TRU: case OP_LIST_CON: {
+ Val v;
+ eval(e, node_in(nd, 0), &v);
+ float idx = in_num(e, nd, 1);
+ if (!v.isptr) {
+ val_default(r, T_NUM);
+ return;
+ }
+ *r = v;
+ r->u.p.idx += (int32_t)idx;
+ return;
+ }
+ case OP_NEGATE: r->t = T_NUM; r->u.f = -in_num(e, nd, 0); return;
+ case OP_ADD_NUMBERS: r->t = T_NUM; r->u.f = in_num(e, nd, 0) + in_num(e, nd, 1); return;
+ case OP_SUBTRACT_NUMBERS: r->t = T_NUM; r->u.f = in_num(e, nd, 0) - in_num(e, nd, 1); return;
+ case OP_MULTIPLY: r->t = T_NUM; r->u.f = in_num(e, nd, 0) * in_num(e, nd, 1); return;
+ case OP_DIVIDE: {
+ float a = in_num(e, nd, 0), b = in_num(e, nd, 1);
+ r->t = T_NUM;
+ r->u.f = b != 0 ? a / b : 0;
+ return;
+ }
+ case OP_ADD_VECTORS: r->t = T_VEC; r->u.v = vadd(in_vec(e, nd, 0), in_vec(e, nd, 1)); return;
+ case OP_SUBTRACT_VECTORS: r->t = T_VEC; r->u.v = vsub(in_vec(e, nd, 0), in_vec(e, nd, 1)); return;
+ case OP_SCALE: r->t = T_VEC; r->u.v = vscale(in_vec(e, nd, 0), in_num(e, nd, 1)); return;
+ case OP_ROTATE: r->t = T_VEC; r->u.v = qrot(in_rot(e, nd, 1), in_vec(e, nd, 0)); return;
+ case OP_COMBINE: r->t = T_ROT; r->u.q = qnorm(qmul(in_rot(e, nd, 0), in_rot(e, nd, 1))); return;
+ case OP_LESS_THAN: r->t = T_TRU; r->u.i = in_num(e, nd, 0) < in_num(e, nd, 1); return;
+ case OP_GREATER_THAN: r->t = T_TRU; r->u.i = in_num(e, nd, 0) > in_num(e, nd, 1); return;
+ case OP_EQUALS_NUMBERS: r->t = T_TRU; r->u.i = fabsf(in_num(e, nd, 0) - in_num(e, nd, 1)) < 0.001f; return;
+ case OP_EQUALS_VECTORS: {
+ vec3 d = vsub(in_vec(e, nd, 0), in_vec(e, nd, 1));
+ r->t = T_TRU;
+ r->u.i = vdot(d, d) < 1.0000001e-6f;
+ return;
+ }
+ case OP_EQUALS_OBJECTS: {
+ int a = in_obj(e, nd, 0), b = in_obj(e, nd, 1);
+ if (a >= 0 && !obj_valid(a)) a = -1;
+ if (b >= 0 && !obj_valid(b)) b = -1;
+ r->t = T_TRU;
+ r->u.i = a == b;
+ return;
+ }
+ case OP_EQUALS_TRUTHS: r->t = T_TRU; r->u.i = in_tru(e, nd, 0) == in_tru(e, nd, 1); return;
+ case OP_NOT: r->t = T_TRU; r->u.i = !in_tru(e, nd, 0); return;
+ case OP_AND: r->t = T_TRU; r->u.i = in_tru(e, nd, 0) && in_tru(e, nd, 1); return;
+ case OP_OR: r->t = T_TRU; r->u.i = in_tru(e, nd, 0) || in_tru(e, nd, 1); return;
+ case OP_MAKE_VECTOR: r->t = T_VEC; r->u.v = v3(in_num(e, nd, 0), in_num(e, nd, 1), in_num(e, nd, 2)); return;
+ case OP_BREAK_VECTOR: {
+ vec3 v = in_vec(e, nd, 0);
+ r->t = T_NUM;
+ r->u.f = out == 0 ? v.x : out == 1 ? v.y : v.z;
+ return;
+ }
+ case OP_MAKE_ROTATION: r->t = T_ROT; r->u.q = qeuler(in_num(e, nd, 0), in_num(e, nd, 1), in_num(e, nd, 2)); return;
+ case OP_BREAK_ROTATION: {
+ quat q = in_rot(e, nd, 0);
+ float v;
+ if (out == 0) {
+ float s = 2.0f * (q.w * q.x - q.y * q.z);
+ v = s >= 1 ? 90.0f : s <= -1 ? -90.0f : asinf(s) * RAD2DEG;
+ } else if (out == 1) {
+ v = atan2f(2.0f * (q.x * q.z + q.w * q.y), 1.0f - 2.0f * (q.x * q.x + q.y * q.y)) * RAD2DEG;
+ } else {
+ v = atan2f(2.0f * (q.x * q.y + q.w * q.z), 1.0f - 2.0f * (q.x * q.x + q.z * q.z)) * RAD2DEG;
+ }
+ r->t = T_NUM;
+ r->u.f = v;
+ return;
+ }
+ case OP_RANDOM: {
+ /* a value block is worked out once per statement: every use shares the same number */
+ for (int i = 0; i < nrnd; i++)
+ if (rnd_memo[i].e == e && rnd_memo[i].node == ni) {
+ r->t = T_NUM;
+ r->u.f = rnd_memo[i].v;
+ return;
+ }
+ float lo = in_num(e, nd, 0), hi = connected(nd, 1) ? in_num(e, nd, 1) : 1.0f;
+ r->t = T_NUM;
+ r->u.f = lo + (hi - lo) * rnd01();
+ if (nrnd < RND_MEMO) {
+ rnd_memo[nrnd].e = e;
+ rnd_memo[nrnd].node = (uint16_t)ni;
+ rnd_memo[nrnd++].v = r->u.f;
+ }
+ return;
+ }
+ case OP_MODULO: {
+ float a = in_num(e, nd, 0), b = in_num(e, nd, 1);
+ float m = b != 0 ? fmodf(a, b) : 0;
+ r->t = T_NUM;
+ r->u.f = m >= 0 ? m : b + m;
+ return;
+ }
+ case OP_MIN: { float a = in_num(e, nd, 0), b = in_num(e, nd, 1); r->t = T_NUM; r->u.f = a < b ? a : b; return; }
+ case OP_MAX: { float a = in_num(e, nd, 0), b = in_num(e, nd, 1); r->t = T_NUM; r->u.f = a > b ? a : b; return; }
+ case OP_ROUND: r->t = T_NUM; r->u.f = rintf(in_num(e, nd, 0)); return;
+ case OP_FLOOR: r->t = T_NUM; r->u.f = floorf(in_num(e, nd, 0)); return;
+ case OP_CEILING: r->t = T_NUM; r->u.f = ceilf(in_num(e, nd, 0)); return;
+ case OP_ABSOLUTE: r->t = T_NUM; r->u.f = fabsf(in_num(e, nd, 0)); return;
+ case OP_SIN: r->t = T_NUM; r->u.f = sinf(in_num(e, nd, 0) * DEG2RAD); return;
+ case OP_COS: r->t = T_NUM; r->u.f = cosf(in_num(e, nd, 0) * DEG2RAD); return;
+ case OP_POWER: r->t = T_NUM; r->u.f = powf(in_num(e, nd, 0), in_num(e, nd, 1)); return;
+ case OP_LOGARITHM: {
+ float a = in_num(e, nd, 0), b = in_num(e, nd, 1);
+ r->t = T_NUM;
+ r->u.f = logf(a) / logf(b);
+ return;
+ }
+ case OP_DISTANCE: r->t = T_NUM; r->u.f = vlen(vsub(in_vec(e, nd, 0), in_vec(e, nd, 1))); return;
+ case OP_DOT_PRODUCT: r->t = T_NUM; r->u.f = vdot(in_vec(e, nd, 0), in_vec(e, nd, 1)); return;
+ case OP_CROSS_PRODUCT: r->t = T_VEC; r->u.v = vcross(in_vec(e, nd, 0), in_vec(e, nd, 1)); return;
+ case OP_NORMALIZE: r->t = T_VEC; r->u.v = vnorm(in_vec(e, nd, 0)); return;
+ case OP_INVERSE: r->t = T_ROT; r->u.q = qconj(in_rot(e, nd, 0)); return;
+ case OP_LERP: r->t = T_ROT; r->u.q = quat_lerp(in_rot(e, nd, 0), in_rot(e, nd, 1), in_num(e, nd, 2)); return;
+ case OP_AXIS_ANGLE: r->t = T_ROT; r->u.q = qaxis(vnorm(in_vec(e, nd, 0)), in_num(e, nd, 1) * DEG2RAD); return;
+ case OP_LOOK_ROTATION: {
+ vec3 up = connected(nd, 1) ? in_vec(e, nd, 1) : v3(0, 1, 0);
+ r->t = T_ROT;
+ r->u.q = look_rotation(in_vec(e, nd, 0), up);
+ return;
+ }
+ case OP_LINE_VS_PLANE: {
+ vec3 a = in_vec(e, nd, 0), b = in_vec(e, nd, 1), pp = in_vec(e, nd, 2), pn = in_vec(e, nd, 3);
+ float den = vdot(vsub(b, a), pn);
+ float t = den != 0 ? vdot(vsub(pp, a), pn) / den : 0;
+ r->t = T_VEC;
+ r->u.v = vadd(a, vscale(vsub(b, a), t));
+ return;
+ }
+ case OP_SCREEN_SIZE: r->t = T_NUM; r->u.f = out == 0 ? SCREEN_W : SCREEN_H; return;
+ case OP_ACCELEROMETER: r->t = T_VEC; r->u.v = v3(0, -9.8f, 0); return;
+ case OP_CURRENT_FRAME: r->t = T_NUM; r->u.f = (float)vm_frame_count; return;
+ case OP_WORLD_TO_SCREEN: {
+ vec3 s = cam_world_to_screen(in_vec(e, nd, 0));
+ r->t = T_NUM;
+ r->u.f = out == 0 ? s.x : s.y;
+ return;
+ }
+ case OP_SCREEN_TO_WORLD: {
+ vec3 n, f;
+ cam_screen_to_world(in_num(e, nd, 0), in_num(e, nd, 1), &n, &f);
+ r->t = T_VEC;
+ r->u.v = out == 0 ? n : f;
+ return;
+ }
+ case OP_RAYCAST: {
+ vec3 from = in_vec(e, nd, 0), to = in_vec(e, nd, 1), hit;
+ int o = -1;
+ bool h = phys_raycast(from, to, &hit, &o);
+#ifdef HOST
+ if (getenv("ND_RDBG") && (vm_frame_count == atoi(getenv("ND_RDBG")) || atoi(getenv("ND_RDBG")) < 0))
+ {
+ fprintf(stderr, "ray (%.2f %.2f %.2f)->(%.2f %.2f %.2f) hit=%d obj=%d at (%.2f %.2f %.2f) f%d\n", from.x, from.y, from.z, to.x, to.y,
+ to.z, h, o, hit.x, hit.y, hit.z, vm_frame_count);
+ if (getenv("ND_RDBG2") && fabsf(from.x - atof(getenv("ND_RDBG2"))) < 0.01f)
+ for (int q = 0; q < nobj; q++) {
+ vec3 l = obj_local(&objs[q], from), l2 = obj_local(&objs[q], to);
+ const Shape *sh = objs[q].shape;
+ float ax = l.x < l2.x ? l.x : l2.x, bx = l.x < l2.x ? l2.x : l.x;
+ float ay = l.y < l2.y ? l.y : l2.y, by = l.y < l2.y ? l2.y : l.y;
+ float az = l.z < l2.z ? l.z : l2.z, bz = l.z < l2.z ? l2.z : l.z;
+ if (bx < sh->bmin.x || ax > sh->bmax.x || by < sh->bmin.y || ay > sh->bmax.y || bz < sh->bmin.z || az > sh->bmax.z) continue;
+ fprintf(stderr, " f%d cand obj %d flags %x local (%.3f %.3f %.3f)->(%.3f %.3f %.3f) bounds (%.2f %.2f %.2f)-(%.2f %.2f %.2f) np=%d\n", vm_frame_count, q, objs[q].flags, l.x, l.y, l.z, l2.x, l2.y, l2.z,
+ sh->bmin.x, sh->bmin.y, sh->bmin.z, sh->bmax.x, sh->bmax.y, sh->bmax.z, sh->np);
+ }
+ if (h) {
+ vec3 l = obj_local(&objs[o], from), l2 = obj_local(&objs[o], to);
+ fprintf(stderr, " local (%.3f %.3f %.3f)->(%.3f %.3f %.3f) np=%d env anchor=%d\n", l.x, l.y, l.z, l2.x, l2.y, l2.z, objs[o].shape->np, e->anchor);
+ }
+ }
+#endif
+ if (out == 0) {
+ r->t = T_TRU;
+ r->u.i = h;
+ } else if (out == 1) {
+ r->t = T_VEC;
+ r->u.v = h ? hit : to;
+ } else {
+ r->t = T_OBJ;
+ r->u.i = h ? o : -1;
+ }
+ return;
+ }
+ case OP_GET_POSITION: {
+ vec3 pos;
+ quat rot;
+ if (!connected(nd, 0)) {
+ env_block_pose(e, &pos, &rot);
+ } else {
+ int o = in_obj(e, nd, 0);
+ if (obj_valid(o)) {
+ pos = objs[o].pos;
+ rot = objs[o].rot;
+ } else {
+ pos = v3(0, 0, 0);
+ rot = qident();
+ }
+ }
+ if (out == 0) {
+ r->t = T_VEC;
+ r->u.v = pos;
+ } else {
+ r->t = T_ROT;
+ r->u.q = rot;
+ }
+ return;
+ }
+ case OP_GET_VELOCITY: {
+ int o = in_obj(e, nd, 0);
+ vec3 vel = v3(0, 0, 0), spin = v3(0, 0, 0);
+ if (obj_valid(o)) phys_get_velocity(o, &vel, &spin);
+ r->t = T_VEC;
+ r->u.v = out == 0 ? vel : spin;
+ return;
+ }
+ case OP_GET_SIZE: {
+ vec3 mn, mx;
+ if (!connected(nd, 0)) {
+ mn = v3(0, 0, 0);
+ mx = v3(level.sx, level.sy, level.sz);
+ } else {
+ int o = in_obj(e, nd, 0);
+ if (!obj_valid(o)) {
+ mn = mx = v3(0, 0, 0);
+ } else {
+ /* local bounds relative to the object's position, not rotated */
+ const Shape *s = objs[o].shape;
+ mn = vsub(s->bmin, s->origin);
+ mx = vsub(s->bmax, s->origin);
+ }
+ }
+ r->t = T_VEC;
+ r->u.v = out == 0 ? mn : mx;
+ return;
+ }
+ default: val_default(r, T_NUM); return;
+ }
+}
+
+static void eval(Env *e, uint16_t ref, Val *out) {
+ if (ref == NONE16) {
+ memset(out, 0, sizeof *out);
+ out->t = 0xff;
+ return;
+ }
+ int kind = ref >> 13;
+ switch (kind) {
+ case 0: eval_node(e, ref & 2047, (ref >> 11) & 3, out); return;
+ case 1: {
+ if (e->parent == NONE16) {
+ out->t = 0xff;
+ return;
+ }
+ Env *pe = &envs[e->parent];
+ const uint8_t *nd = node_ptr(pe->prog, e->pnode);
+ int k = ref & 8191;
+ if (k >= nd[9]) {
+ out->t = 0xff;
+ return;
+ }
+ eval(pe, rd16(nd + 10 + 2 * k), out);
+ return;
+ }
+ case 2: {
+ memset(out, 0, sizeof *out);
+ out->t = T_OBJ;
+ int k = ref & 8191;
+ out->u.i = k < e->prog->nself ? e->selfobj[k] : -1;
+ return;
+ }
+ default: {
+ memset(out, 0, sizeof *out);
+ out->t = T_OBJ;
+ out->u.i = e->tbase + (ref & 8191);
+ return;
+ }
+ }
+}
+
+/* ------------------------------------------------------------- statements */
+static void set_slot(Env *e, int ni, int k, const Val *v) {
+ uint16_t s = e->prog->slot[ni];
+ if (s != NONE16) e->slots[s + k] = *v;
+}
+
+static void exec_stmt(Env *e, int ni) {
+ nrnd = 0;
+ const Prog *p = e->prog;
+ const uint8_t *nd = node_ptr(p, ni);
+ int op = nd[0];
+ switch (op) {
+ case OP_SET_VAR_NUM: case OP_SET_VAR_VEC: case OP_SET_VAR_ROT: case OP_SET_VAR_TRU: case OP_SET_VAR_OBJ:
+ case OP_SET_VAR_CON: {
+ VarStore *vs = var_of(e, node_data(nd));
+ Val v;
+ eval(e, node_in(nd, 0), &v);
+ deref(&v);
+ /* a value wired from an input the outer script left unconnected changes nothing (scripts use
+ "set a default, then set the input" for optional inputs) */
+ if (v.t == 0xff && node_in(nd, 0) != NONE16) return;
+ if (v.t != vs->type && !(vs->type == T_CON && v.t == T_OBJ)) val_default(&v, vs->type);
+ var_write(vs, 0, &v);
+ return;
+ }
+ case OP_SET_PTR_NUM: case OP_SET_PTR_VEC: case OP_SET_PTR_ROT: case OP_SET_PTR_TRU: case OP_SET_PTR_OBJ:
+ case OP_SET_PTR_CON: {
+ Val ptr, v;
+ eval(e, node_in(nd, 0), &ptr);
+ if (!ptr.isptr) return;
+ eval(e, node_in(nd, 1), &v);
+ deref(&v);
+ if (v.t == 0xff && node_in(nd, 1) != NONE16) return;
+ if (v.t != ptr.u.p.vs->type && !(ptr.u.p.vs->type == T_CON && v.t == T_OBJ)) val_default(&v, ptr.u.p.vs->type);
+ var_write(ptr.u.p.vs, ptr.u.p.idx, &v);
+ return;
+ }
+ case OP_INCREASE_NUMBER: case OP_DECREASE_NUMBER: {
+ Val ptr, v;
+ eval(e, node_in(nd, 0), &ptr);
+ if (!ptr.isptr) return;
+ var_read(ptr.u.p.vs, ptr.u.p.idx, &v);
+ if (v.t != T_NUM) return;
+ v.u.f += op == OP_INCREASE_NUMBER ? 1 : -1;
+ var_write(ptr.u.p.vs, ptr.u.p.idx, &v);
+ return;
+ }
+ case OP_IF: {
+ int c = in_tru(e, nd, 0);
+ run_list(e, node_exec(nd, c ? 0 : 1));
+ return;
+ }
+ case OP_PLAY_SENSOR:
+ if (vm_frame_count == 0) run_list(e, node_exec(nd, 0));
+ return;
+ case OP_LATE_UPDATE: {
+ const uint8_t *l = node_exec(nd, 0);
+ for (int i = 0; i < l[0] && nlate < MAXLATE; i++) {
+ lateq[nlate].env = (uint16_t)(e - envs);
+ lateq[nlate].node = rd16(l + 1 + 2 * i);
+ nlate++;
+ }
+ return;
+ }
+ case OP_BUTTON: {
+ int b = button_counter++;
+ if (vm_buttons & (1u << b)) run_list(e, node_exec(nd, 0));
+ return;
+ }
+ case OP_BOX_ART_SENSOR: case OP_TOUCH_SENSOR: case OP_SWIPE_SENSOR: case OP_JOYSTICK: return;
+ case OP_COLLISION: {
+ int o = in_obj(e, nd, 0);
+ int other;
+ float imp;
+ vec3 n;
+ if (obj_valid(o) && phys_collision(o, &other, &imp, &n)) {
+ Val v;
+ memset(&v, 0, sizeof v);
+ v.t = T_OBJ;
+ v.u.i = other;
+ set_slot(e, ni, 0, &v);
+ v.t = T_NUM;
+ v.u.f = imp;
+ set_slot(e, ni, 1, &v);
+ v.t = T_VEC;
+ v.u.v = n;
+ set_slot(e, ni, 2, &v);
+ run_list(e, node_exec(nd, 0));
+ }
+ return;
+ }
+ case OP_LOOP: {
+ int start = (int)in_num(e, nd, 0);
+ int stop = (int)ceilf(in_num(e, nd, 1));
+ int step = stop > start ? 1 : stop < start ? -1 : 0;
+ int value = start - step;
+ Val v;
+ memset(&v, 0, sizeof v);
+ v.t = T_NUM;
+ v.u.f = (float)value;
+ set_slot(e, ni, 0, &v);
+ if (!step) return;
+ const uint8_t *body = node_exec(nd, 0);
+ for (int guard = 0; guard < 100000; guard++) {
+ stop = (int)ceilf(in_num(e, nd, 1));
+ int next = value + step;
+ if (step > 0 ? next >= stop : next <= stop) break;
+ value = next;
+ v.u.f = (float)value;
+ set_slot(e, ni, 0, &v);
+ run_list(e, body);
+ }
+ return;
+ }
+ case OP_WIN:
+#ifdef HOST
+ if (getenv("ND_WDBG")) fprintf(stderr, "win at frame %d env %d node %d\n", vm_frame_count, (int)(e - envs), ni);
+#endif
+ game_win(node_data(nd)[0]);
+ return;
+ case OP_LOSE: game_lose(node_data(nd)[0]); return;
+ case OP_SET_SCORE:
+ if (connected(nd, 0)) hud_score = in_num(e, nd, 0);
+#ifdef HOST
+ if (getenv("ND_SDBG")) fprintf(stderr, "score f%d %.2f\n", vm_frame_count, hud_score);
+#endif
+ if (connected(nd, 1)) hud_coins = in_num(e, nd, 1);
+ return;
+ case OP_SET_CAMERA: {
+ vec3 pos;
+ quat rot;
+ float range;
+ if (connected(nd, 0)) pos = in_vec(e, nd, 0);
+ if (connected(nd, 1)) rot = in_rot(e, nd, 1);
+ if (connected(nd, 2)) range = in_num(e, nd, 2);
+ cam_set(connected(nd, 0) ? &pos : 0, connected(nd, 1) ? &rot : 0, connected(nd, 2) ? &range : 0,
+ node_data(nd)[0]);
+ return;
+ }
+ case OP_SET_LIGHT: {
+ if (connected(nd, 1)) {
+ quat q = in_rot(e, nd, 1);
+ light_set(&q);
+ }
+ return;
+ }
+ case OP_SET_POSITION: {
+ int o = connected(nd, 0) ? in_obj(e, nd, 0) : e->anchor;
+ if (!obj_valid(o)) return;
+ if (connected(nd, 1)) objs[o].pos = in_vec(e, nd, 1);
+ if (connected(nd, 2)) objs[o].rot = qnorm(in_rot(e, nd, 2));
+#ifdef HOST
+ if (getenv("ND_PDBG")) fprintf(stderr, "f%d setpos obj%d (%.3f %.3f %.3f) rot(%.3f %.3f %.3f %.3f)%s\n", vm_frame_count, o, objs[o].pos.x, objs[o].pos.y, objs[o].pos.z, objs[o].rot.x, objs[o].rot.y, objs[o].rot.z, objs[o].rot.w, connected(nd, 2) ? " +rot" : "");
+#endif
+ objs[o].flags |= OF_MOVED;
+ phys_moved(o);
+ return;
+ }
+ case OP_SET_VELOCITY: {
+ int o = connected(nd, 0) ? in_obj(e, nd, 0) : e->anchor;
+ if (!obj_valid(o)) return;
+ vec3 vel, spin;
+ if (connected(nd, 1)) vel = in_vec(e, nd, 1);
+ if (connected(nd, 2)) spin = in_vec(e, nd, 2);
+ phys_set_velocity(o, connected(nd, 1) ? &vel : 0, connected(nd, 2) ? &spin : 0);
+ return;
+ }
+ case OP_ADD_FORCE: {
+ int o = connected(nd, 0) ? in_obj(e, nd, 0) : e->anchor;
+ if (!obj_valid(o)) return;
+ vec3 f, at, t;
+ if (connected(nd, 1)) f = in_vec(e, nd, 1);
+ if (connected(nd, 2)) at = in_vec(e, nd, 2);
+ if (connected(nd, 3)) t = in_vec(e, nd, 3);
+ phys_add_force(o, connected(nd, 1) ? &f : 0, connected(nd, 2) ? &at : 0, connected(nd, 3) ? &t : 0);
+ return;
+ }
+ case OP_SET_LOCKED: {
+ int o = connected(nd, 0) ? in_obj(e, nd, 0) : e->anchor;
+ if (!obj_valid(o)) return;
+ vec3 a, b;
+ if (connected(nd, 1)) a = in_vec(e, nd, 1);
+ if (connected(nd, 2)) b = in_vec(e, nd, 2);
+ phys_set_locked(o, connected(nd, 1) ? &a : 0, connected(nd, 2) ? &b : 0);
+ return;
+ }
+ case OP_SET_VISIBLE: {
+ int o = connected(nd, 0) ? in_obj(e, nd, 0) : e->anchor;
+ if (!obj_valid(o)) return;
+ if (in_tru(e, nd, 1)) objs[o].flags |= OF_VISIBLE;
+ else if (objs[o].flags & OF_VISIBLE) {
+ objs[o].flags &= ~OF_VISIBLE;
+ phys_hidden(o);
+ }
+ return;
+ }
+ case OP_CREATE_OBJECT: {
+ int o = in_obj(e, nd, 0);
+ Val v;
+ memset(&v, 0, sizeof v);
+ v.t = T_OBJ;
+ v.u.i = obj_valid(o) ? obj_clone(o) : -1;
+ if (v.u.i >= 0 && (objs[v.u.i].flags & OF_PHYSICS)) phys_make_dynamic(v.u.i);
+ set_slot(e, ni, 0, &v);
+ return;
+ }
+ case OP_DESTROY_OBJECT: {
+ int o = in_obj(e, nd, 0);
+ if (obj_valid(o)) {
+ phys_destroyed(o);
+ obj_destroy(o);
+ }
+ return;
+ }
+ case OP_SET_GRAVITY: phys_set_gravity(in_vec(e, nd, 0)); return;
+ case OP_SET_MASS: {
+ int o = connected(nd, 0) ? in_obj(e, nd, 0) : e->anchor;
+ if (obj_valid(o)) phys_set_mass(o, in_num(e, nd, 1));
+ return;
+ }
+ case OP_SET_FRICTION: {
+ int o = connected(nd, 0) ? in_obj(e, nd, 0) : e->anchor;
+ if (obj_valid(o)) phys_set_friction(o, in_num(e, nd, 1));
+ return;
+ }
+ case OP_SET_BOUNCINESS: {
+ int o = connected(nd, 0) ? in_obj(e, nd, 0) : e->anchor;
+ if (obj_valid(o)) phys_set_bounce(o, in_num(e, nd, 1));
+ return;
+ }
+ case OP_ADD_CONSTRAINT: {
+ int base = in_obj(e, nd, 0), part = in_obj(e, nd, 1);
+ vec3 pivot = connected(nd, 2) ? in_vec(e, nd, 2) : (obj_valid(part) ? objs[part].pos : v3(0, 0, 0));
+ Val v;
+ memset(&v, 0, sizeof v);
+ v.t = T_CON;
+ v.u.i = obj_valid(part) ? phys_add_constraint(obj_valid(base) ? base : -1, part, pivot) : -1;
+#ifdef HOST
+ if (getenv("ND_CDBG"))
+ fprintf(stderr, "constraint base=%d part=%d pivot=(%.2f %.2f %.2f) partpos=(%.2f %.2f %.2f)\n", base, part, pivot.x, pivot.y,
+ pivot.z, obj_valid(part) ? objs[part].pos.x : 0, obj_valid(part) ? objs[part].pos.y : 0,
+ obj_valid(part) ? objs[part].pos.z : 0);
+#endif
+ set_slot(e, ni, 0, &v);
+ return;
+ }
+ case OP_LINEAR_LIMITS: case OP_ANGULAR_LIMITS: {
+ int c = in_obj(e, nd, 0);
+ if (c >= 0) phys_con_limits(c, op == OP_ANGULAR_LIMITS, in_vec(e, nd, 1), in_vec(e, nd, 2));
+ return;
+ }
+ case OP_LINEAR_SPRING: case OP_ANGULAR_SPRING: {
+ int c = in_obj(e, nd, 0);
+ if (c >= 0) phys_con_spring(c, op == OP_ANGULAR_SPRING, in_vec(e, nd, 1), in_vec(e, nd, 2));
+ return;
+ }
+ case OP_LINEAR_MOTOR: case OP_ANGULAR_MOTOR: {
+ int c = in_obj(e, nd, 0);
+ if (c >= 0) phys_con_motor(c, op == OP_ANGULAR_MOTOR, in_vec(e, nd, 1), in_vec(e, nd, 2));
+ return;
+ }
+ case OP_PLAY_SOUND: {
+ static int channel;
+ Val v;
+ memset(&v, 0, sizeof v);
+ v.t = T_NUM;
+ v.u.f = (float)(channel++ & 7);
+ set_slot(e, ni, 0, &v);
+ return;
+ }
+ case OP_RANDOM_SEED: rng_state = (uint32_t)in_num(e, nd, 0) * 2654435761u + 1; return;
+ default: return; /* sound, inspect */
+ }
+}
+
+static void run_list(Env *e, const uint8_t *lst) {
+ int n = lst[0];
+ for (int i = 0; i < n; i++) run_chain(e, rd16(lst + 1 + 2 * i));
+}
+
+static void run_chain(Env *e, uint16_t node) {
+ while (node != NONE16 && node < e->prog->nnodes) {
+ exec_stmt(e, node);
+ const uint8_t *after = node_exec(node_ptr(e->prog, node), -1);
+ if (after[0] == 0) return;
+ /* several wires from one output run one after the other, in block order */
+ for (int i = 0; i + 1 < after[0]; i++) run_chain(e, rd16(after + 1 + 2 * i));
+ node = rd16(after + 1 + 2 * (after[0] - 1));
+ }
+}
+
+/* ------------------------------------------------------------------ setup */
+extern int world_add_template(Shape *s);
+
+static int count_envs(Prog *p) {
+ int n = 1;
+ for (int i = 0; i < p->nnodes; i++)
+ if (prog_child(p, i)) n += count_envs(prog_child(p, i));
+ return n;
+}
+
+static bool make_env(Prog *p, int parent, int pnode, int bx, int by, int bz) {
+ int idx = nenvs++;
+ Env *e = &envs[idx];
+ memset(e, 0, sizeof *e);
+ e->prog = p;
+ e->parent = parent < 0 ? NONE16 : parent;
+ e->pnode = pnode;
+ e->bx = bx;
+ e->by = by;
+ e->bz = bz;
+ e->anchor = -1;
+ if (parent >= 0) {
+ Env *pe = &envs[parent];
+ Prog *pp = pe->prog;
+ e->tbase = nobj;
+ for (int t = 0; t < p->ntmpl; t++)
+ if (world_add_template(p->tmpl[t]) < 0) return false;
+ /* anchor and self objects, resolved by the pack tool as indices in the parent grid */
+ const uint8_t *nd = node_ptr(pp, pnode);
+ const uint8_t *ob = nd + 10 + 2 * nd[9];
+ uint16_t a = rd16(ob);
+ e->anchor = a == NONE16 ? -1 : pe->tbase + a;
+ e->selfobj = arena_alloc(2 * (p->nself ? p->nself : 1));
+ if (!e->selfobj) return false;
+ for (int k = 0; k < p->nself; k++) {
+ uint16_t o = k < ob[2] ? rd16(ob + 3 + 2 * k) : NONE16;
+ e->selfobj[k] = o == NONE16 ? -1 : pe->tbase + o;
+ }
+ }
+ e->locals = arena_alloc(sizeof(VarStore) * (p->nlocals ? p->nlocals : 1));
+ if (!e->locals) return false;
+ for (int k = 0; k < p->nlocals; k++) {
+ e->locals[k].type = p->ltypes[k];
+ e->locals[k].len = e->locals[k].cap2 = 0;
+ e->locals[k].data = 0;
+ }
+ if (p->nslots) {
+ e->slots = arena_alloc(sizeof(Val) * p->nslots);
+ if (!e->slots) return false;
+ for (int k = 0; k < p->nslots; k++) val_default(&e->slots[k], T_NUM);
+ }
+ for (int i = 0; i < p->nnodes; i++) {
+ Prog *ch = prog_child(p, i);
+ if (!ch) continue;
+ const uint8_t *nd = node_ptr(p, i);
+ if (!make_env(ch, idx, i, rd16(nd + 3), rd16(nd + 5), rd16(nd + 7))) return false;
+ }
+ envs[idx].nsub = (uint16_t)(nenvs - idx);
+ return true;
+}
+
+bool vm_setup_envs(void) {
+ nfree = 0;
+ int n = count_envs(level.prog);
+ envs = arena_alloc(sizeof(Env) * n);
+ globals = arena_alloc(sizeof(VarStore) * (nglobals ? nglobals : 1));
+ if (!envs || !globals) return false;
+ for (int i = 0; i < nglobals; i++) {
+ globals[i].type = global_types[i];
+ globals[i].len = globals[i].cap2 = 0;
+ globals[i].data = 0;
+ }
+ nenvs = 0;
+ vm_frame_count = 0;
+ nlate = 0;
+ rng_state = 0x12345678u ^ plat_random();
+ return make_env(level.prog, -1, NONE16, 0, 0, 0);
+}
+
+/* Fancade runs the script chains of a program and the custom script blocks placed in it
+ * interleaved, in block order (nodes are sorted that way); child environments follow their
+ * parent in node order, each followed by its own subtree */
+static void run_env(int ei) {
+ Env *e = &envs[ei];
+ const Prog *p = e->prog;
+ int child = ei + 1, k = 0;
+ for (int i = 0; i < p->nnodes; i++) {
+ const uint8_t *nd = node_ptr(p, i);
+ if (nd[0] == OP_CUSTOM) {
+ if (child < nenvs && envs[child].parent == ei && envs[child].pnode == i) {
+ int n = envs[child].nsub;
+ run_env(child);
+ child += n;
+ }
+ continue;
+ }
+ for (int j = k; j < p->nentries; j++)
+ if (rd16(p->entries + 2 * j) == i) {
+ run_chain(e, (uint16_t)i);
+ if (j == k) k++;
+ break;
+ }
+ }
+}
+
+void vm_frame(void) {
+ button_counter = 0;
+ nlate = 0;
+ if (nenvs) run_env(0);
+}
+
+void vm_late(void) {
+ for (int i = 0; i < nlate; i++) run_chain(&envs[lateq[i].env], lateq[i].node);
+ nlate = 0;
+ vm_frame_count++;
+}
+
+/* --------------------------------------------------------- engine access */
+extern const char *vm_global_names[];
+int vm_global_count(void);
diff --git a/games/numdrive/src/vm.h b/games/numdrive/src/vm.h
new file mode 100644
index 00000000..9ca9bbc9
--- /dev/null
+++ b/games/numdrive/src/vm.h
@@ -0,0 +1,25 @@
+#ifndef VM_H
+#define VM_H
+#include <stdbool.h>
+#include "fmath.h"
+
+enum { T_NUM, T_VEC, T_ROT, T_TRU, T_OBJ, T_CON };
+
+bool vm_setup_envs(void);
+void vm_frame(void); /* run all scripts for one frame */
+void vm_late(void); /* run queued Late Update branches (after physics) */
+extern int vm_frame_count;
+extern uint32_t vm_buttons; /* bit0 = left (brake), bit1 = right (gas) */
+
+/* engine hooks implemented elsewhere */
+void game_win(int delay);
+void game_lose(int delay);
+void cam_set(const vec3 *pos, const quat *rot, const float *range, int perspective);
+void light_set(const quat *rot);
+
+/* global variable access by name index (for the engine) */
+int vm_global(const char *name, int type);
+float vm_global_num(int idx);
+int vm_global_tru(int idx);
+
+#endif
diff --git a/games/numdrive/src/world.c b/games/numdrive/src/world.c
new file mode 100644
index 00000000..66d6b4c4
--- /dev/null
+++ b/games/numdrive/src/world.c
@@ -0,0 +1,743 @@
+#include <stdlib.h>
+#include <string.h>
+#define ARENA_IMPL
+#include "world.h"
+#include "inflate.h"
+#include "ops.h"
+#ifdef HOST
+#include <stdio.h>
+#define FAIL(msg) do { fprintf(stderr, "world: %s (line %d)\n", msg, __LINE__); return false; } while (0)
+#else
+#define FAIL(msg) return false
+#endif
+
+extern const uint8_t pack_data[];
+
+/* ------------------------------------------------------------------ arena */
+#ifndef ARENA_SIZE
+#define ARENA_SIZE (122 * 1024)
+#endif
+static uint8_t arena[ARENA_SIZE] __attribute__((aligned(8)));
+/* persistent data grows up from the bottom; the object table sits at the very top (arena_hi) and
+ * setup-only data grows down below it */
+static uint32_t arena_pos, arena_tmp = ARENA_SIZE, arena_hi = ARENA_SIZE;
+uint32_t arena_peak;
+
+static inline void arena_track(void) {
+ uint32_t used = arena_pos + (ARENA_SIZE - arena_tmp);
+ if (used > arena_peak) arena_peak = used;
+}
+
+void *arena_alloc(uint32_t size) {
+ size = (size + 7) & ~7u;
+ if (arena_pos + size > arena_tmp) {
+ OOM("arena");
+ return 0;
+ }
+ void *p = arena + arena_pos;
+ arena_pos += size;
+ arena_track();
+ return p;
+}
+void *arena_tmp_alloc(uint32_t size) {
+ size = (size + 7) & ~7u;
+ if (arena_tmp < arena_pos + size) return 0;
+ arena_tmp -= size;
+ arena_track();
+ return arena + arena_tmp;
+}
+void arena_tmp_reset(void) { arena_tmp = arena_hi; }
+uint32_t arena_tmp_mark(void) { return arena_tmp; }
+void arena_tmp_release(uint32_t m) { arena_tmp = m; }
+static void *arena_high_alloc(uint32_t size) {
+ size = (size + 7) & ~7u;
+ if (arena_tmp < arena_pos + size || arena_tmp != arena_hi) return 0;
+ arena_hi -= size;
+ arena_tmp = arena_hi;
+ arena_track();
+ return arena + arena_hi;
+}
+/* long lived allocation from the top (below the object table) after setup; kept until level reset */
+void *arena_keep_alloc(uint32_t size) {
+ if (arena_tmp != arena_hi) return 0;
+ return arena_high_alloc(size);
+}
+int level_serial; /* incremented on every level load */
+
+void arena_reset(void) {
+ level_serial++;
+ arena_pos = 0;
+ arena_tmp = arena_hi = ARENA_SIZE;
+}
+#if defined(HOST) && defined(ARENA_PROFILE)
+#include <stdio.h>
+static struct { const char *f; int l; uint32_t n; } prof[64];
+static int nprof;
+/* live allocations (bump order) and a snapshot of them at the peak */
+static struct { uint32_t off, n; const char *f; int l; } live[8192];
+static int nlive;
+static char peak_snap[4096];
+static uint32_t snap_peak;
+static void prof_dump(void) {
+ for (int i = 0; i < nprof; i++) printf("PROF %s:%d %u\n", prof[i].f, prof[i].l, prof[i].n);
+ printf("PEAK %u\n%s", snap_peak, peak_snap);
+}
+static void prof_snapshot(void) {
+ uint32_t used = arena_pos + (ARENA_SIZE - arena_tmp);
+ if (used <= snap_peak) return;
+ snap_peak = used;
+ int n = snprintf(peak_snap, sizeof peak_snap, " pos %u tmp %u\n", arena_pos, ARENA_SIZE - arena_tmp);
+ for (int i = 0; i < nlive && n < (int)sizeof peak_snap - 64; i++) {
+ bool seen = false;
+ for (int k = 0; k < i && !seen; k++) seen = live[k].l == live[i].l && live[k].f == live[i].f;
+ if (seen) continue;
+ uint32_t tot = 0;
+ int cnt = 0;
+ for (int j = i; j < nlive; j++)
+ if (live[j].l == live[i].l && live[j].f == live[i].f) tot += live[j].n, cnt++;
+ n += snprintf(peak_snap + n, sizeof peak_snap - n, " %s:%d x%d %u\n", live[i].f, live[i].l, cnt, tot);
+ }
+}
+void *arena_alloc_dbg(uint32_t size, const char *f, int l) {
+ if (!nprof) atexit(prof_dump);
+ int i;
+ for (i = 0; i < nprof; i++)
+ if (prof[i].l == l && prof[i].f == f) break;
+ if (i == nprof && nprof < 64) prof[nprof++] = (typeof(prof[0])){f, l, 0};
+ if (i < 64) prof[i].n += (size + 7) & ~7u;
+ while (nlive && live[nlive - 1].off >= arena_pos) nlive--;
+ uint32_t off = arena_pos;
+ void *p = arena_alloc(size);
+ if (p && nlive < 8192) live[nlive++] = (typeof(live[0])){off, (size + 7) & ~7u, f, l};
+ prof_snapshot();
+ return p;
+}
+#define arena_alloc(n) arena_alloc_dbg((n), __FILE__, __LINE__)
+#endif
+uint32_t arena_used(void) { return arena_pos; }
+uint32_t arena_free(void) { return arena_tmp - arena_pos; }
+uint32_t arena_mark(void) { return arena_pos; }
+void arena_release(uint32_t m) { arena_pos = m; }
+bool arena_release_top(void *p, uint32_t size) {
+ size = (size + 7) & ~7u;
+ if ((uint8_t *)p + size != arena + arena_pos) return false;
+ arena_pos -= size;
+ return true;
+}
+bool arena_extend(void *p, uint32_t old_size, uint32_t new_size) {
+ old_size = (old_size + 7) & ~7u;
+ new_size = (new_size + 7) & ~7u;
+ if ((uint8_t *)p + old_size != arena + arena_pos) return false;
+ uint32_t start = (uint32_t)((uint8_t *)p - arena);
+ if (start + new_size > arena_tmp) return false;
+ arena_pos = start + new_size;
+ arena_track();
+ return true;
+}
+void *arena_top(uint32_t *avail) {
+ *avail = arena_tmp - arena_pos;
+ return arena + arena_pos;
+}
+
+/* ------------------------------------------------------------------- pack */
+static uint16_t rd16(const uint8_t *p) { return p[0] | p[1] << 8; }
+static uint32_t rd32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; }
+static float rdf(const uint8_t *p) {
+ uint32_t v = rd32(p);
+ float f;
+ memcpy(&f, &v, 4);
+ return f;
+}
+
+int pack_records(void) { return rd16(pack_data + 4); }
+static uint32_t pack_size_word(int rec) {
+ int n = pack_records();
+ return rd32(pack_data + 6 + 4 * (n + 1) + 4 * rec);
+}
+uint32_t pack_rawsize(int rec) { return pack_size_word(rec) & 0x7FFFFFFFu; }
+/* records stored uncompressed are used in place (no RAM copy) */
+static const uint8_t *pack_inplace(int rec) {
+ return (pack_size_word(rec) & 0x80000000u) ? pack_data + rd32(pack_data + 6 + 4 * rec) : 0;
+}
+int pack_load(int rec, uint8_t *dst, uint32_t cap) {
+ const uint8_t *o = pack_data + 6 + 4 * rec;
+ uint32_t a = rd32(o), b = rd32(o + 4), n = pack_rawsize(rec);
+ if (n > cap) return -1;
+ if (pack_inplace(rec)) {
+ memcpy(dst, pack_data + a, n);
+ return (int)n;
+ }
+ return inflate_raw(pack_data + a, b - a, dst, cap);
+}
+
+static const uint8_t *load_rec(int rec) {
+ const uint8_t *in = pack_inplace(rec);
+ if (in) return in;
+ uint32_t n = pack_rawsize(rec);
+ uint8_t *p = arena_alloc(n);
+ if (!p || pack_load(rec, p, n) != (int)n) return 0;
+ return p;
+}
+
+/* -------------------------------------------------------------- directory */
+uint16_t nglobals;
+const uint8_t *global_types;
+int nlevels;
+static const uint8_t *level_dir; /* per level: u16 record, name (u8 length + chars) */
+static uint16_t nblocklib, block_group, block_rec0;
+static const uint8_t *dir_buf; /* the directory record is stored uncompressed */
+
+bool world_init(void) {
+ dir_buf = pack_inplace(0);
+ if (!dir_buf) FAIL("world_init");
+ const uint8_t *p = dir_buf;
+ nblocklib = rd16(p);
+ block_group = p[2];
+ block_rec0 = rd16(p + 3);
+ p += 5;
+ nglobals = rd16(p);
+ p += 2;
+ global_types = p;
+ p += nglobals;
+ nlevels = rd16(p);
+ level_dir = p + 2;
+ return true;
+}
+
+static const uint8_t *level_entry(int i) {
+ const uint8_t *p = level_dir;
+ while (i-- > 0) p += 3 + p[2];
+ return p;
+}
+
+const char *level_name(int i) {
+ static char buf[24];
+ const uint8_t *q = level_entry(i) + 2;
+ int l = q[0] < 23 ? q[0] : 23;
+ memcpy(buf, q + 1, l);
+ buf[l] = 0;
+ return buf;
+}
+
+/* ----------------------------------------------------------------- blocks */
+Block *blocks[256];
+static uint8_t need_blk[256];
+
+/* block record: u8 flags, u8 ncomp, per component (u16 voxel count, f32 sums[3], u8 bounds[6]),
+ * then the part kept in RAM: u8 nbox, boxes (3 bytes each), u8 full faces, per face u8 count and quads (3 bytes) */
+#define COMP_STATS 6
+static uint32_t block_tail(const uint8_t *t) {
+ const uint8_t *p = t + 1 + 3 * t[0] + 1;
+ for (int f = 0; f < 6; f++) p += 1 + 3 * p[0];
+ return (uint32_t)(p - t);
+}
+
+static bool load_blocks(void) {
+ for (int g0 = 0; g0 < nblocklib; g0 += block_group) {
+ bool any = false;
+ for (int i = g0; i < g0 + block_group && i < nblocklib; i++)
+ if (need_blk[i] && !blocks[i]) any = true;
+ if (!any) continue;
+ int rec = block_rec0 + g0 / block_group;
+ uint32_t n = pack_rawsize(rec);
+ uint32_t tm = arena_tmp_mark();
+ uint8_t *base = arena_tmp_alloc(n);
+ if (!base || pack_load(rec, base, n) != (int)n) FAIL("load_blocks");
+ const uint8_t *p = base;
+ for (int i = g0; i < g0 + block_group && i < nblocklib; i++) {
+ int ncomp = p[1];
+ const uint8_t *st = p + 2, *t = st + COMP_STATS * ncomp;
+ uint32_t tl = block_tail(t);
+ if (need_blk[i] && !blocks[i]) {
+ Block *b = arena_alloc(sizeof(Block));
+ uint8_t *keep = arena_alloc(tl);
+ if (!b || !keep) FAIL("load_blocks");
+ memset(b, 0, sizeof *b);
+ b->flags = p[0];
+ b->ncomp = (uint8_t)ncomp;
+ b->bb = arena_alloc(6 * ncomp);
+ if (!b->bb) FAIL("load_blocks");
+ memcpy(b->bb, st, 6 * ncomp);
+ memcpy(keep, t, tl);
+ b->nbox = keep[0];
+ b->boxes = keep + 1;
+ const uint8_t *r = keep + 1 + 3 * b->nbox;
+ b->full = *r++;
+ for (int f = 0; f < 6; f++) {
+ b->nq[f] = r[0];
+ b->fq[f] = r + 1;
+ r += 1 + 3 * r[0];
+ }
+ blocks[i] = b;
+ }
+ p = t + tl;
+ }
+ arena_tmp_release(tm);
+ }
+ return true;
+}
+
+/* ---------------------------------------------------------------- objects */
+/* Grids are shipped as ready-made objects (grouped by the pack tool with Fancade's glue rules):
+ * u16 count, per object: varint parts, per part: u8 block, varint key delta. */
+static uint32_t rdvar(const uint8_t **pp) {
+ const uint8_t *p = *pp;
+ uint32_t v = 0;
+ int sh = 0;
+ while (*p & 0x80) {
+ v |= (uint32_t)(*p++ & 0x7F) << sh;
+ sh += 7;
+ }
+ v |= (uint32_t)(*p++) << sh;
+ *pp = p;
+ return v;
+}
+
+/* first pass: note the blocks used, return the end of the data */
+static const uint8_t *scan_objects(const uint8_t *p) {
+ uint16_t n = rd16(p);
+ p += 2;
+ uint32_t total = 0;
+ for (int o = 0; o < n; o++) total += rdvar(&p);
+ for (uint32_t i = 0; i < total; i++) need_blk[*p++] = 1;
+ for (uint32_t i = 0; i < total; i++) rdvar(&p);
+ return p;
+}
+
+int shape_find(const Shape *s, int x, int y, int z) {
+ if (x < 0 || y < 0 || z < 0 || x > 1023 || y > 127 || z > 1023) return -1;
+ uint32_t k = (uint32_t)x << 20 | (uint32_t)y << 13 | (uint32_t)z << 3;
+ int lo = 0, hi = s->np - 1, r = -1;
+ while (lo <= hi) {
+ int m = (lo + hi) >> 1;
+ if (s->key[m] < k) lo = m + 1;
+ else {
+ r = m;
+ hi = m - 1;
+ }
+ }
+ if (r >= 0 && (s->key[r] & ~7u) == k) return r;
+ return -1;
+}
+
+/* position of one block of an object: its cell for a stock block, the centre of its voxels for a
+ custom one */
+vec3 shape_block_center(const Shape *s, int x, int y, int z) {
+ int v0[3] = {8, 8, 8}, v1[3] = {-1, -1, -1};
+ for (int i = 0; i < s->np; i++) {
+ uint32_t k = s->key[i];
+ if (PK_X(k) != x || PK_Y(k) != y || PK_Z(k) != z) continue;
+ const Block *b = blocks[s->blk[i]];
+ if (b->flags & 8) return v3(x + 0.5f, y + 0.5f, z + 0.5f);
+ const uint8_t *bb = b->bb + PK_C(k) * 6;
+ for (int a = 0; a < 3; a++) {
+ if (bb[a] < v0[a]) v0[a] = bb[a];
+ if (bb[a + 3] > v1[a]) v1[a] = bb[a + 3];
+ }
+ }
+ if (v1[0] < v0[0]) return v3(x + 0.5f, y + 0.5f, z + 0.5f);
+ return v3(x + (v0[0] + v1[0] + 1) / 16.0f, y + (v0[1] + v1[1] + 1) / 16.0f, z + (v0[2] + v1[2] + 1) / 16.0f);
+}
+
+static void shape_finish(Shape *s) {
+ /* occlusion masks */
+ for (int i = 0; i < s->np; i++) {
+ uint32_t k = s->key[i];
+ int x = PK_X(k), y = PK_Y(k), z = PK_Z(k);
+ uint8_t m = 0;
+ static const int8_t D[6][3] = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}};
+ for (int f = 0; f < 6; f++) {
+ int j = shape_find(s, x + D[f][0], y + D[f][1], z + D[f][2]);
+ if (j >= 0 && (blocks[s->blk[j]]->full & (1 << (f ^ 1)))) m |= 1 << f;
+ }
+ s->occ[i] = m;
+ }
+ /* mass: the volume of the parts' voxel bounds (Fancade's colliders); com: the centre of the cells
+ holding colliders (a hinged plank balances over a pivot in its column, as in the original); bounds */
+ float v = 0;
+ float bx0 = 1e9f, by0 = 1e9f, bz0 = 1e9f, bx1 = -1e9f, by1 = -1e9f, bz1 = -1e9f;
+ int clo[2][3] = {{1 << 20, 1 << 20, 1 << 20}, {1 << 20, 1 << 20, 1 << 20}}, chi[2][3] = {{-1, -1, -1}, {-1, -1, -1}};
+ uint8_t coll = 0;
+ for (int i = 0; i < s->np; i++) {
+ Block *b = blocks[s->blk[i]];
+ uint32_t k = s->key[i];
+ int c = PK_C(k);
+ int cell[3] = {PK_X(k), PK_Y(k), PK_Z(k)};
+ for (int t = 0; t < 2; t++)
+ if (t == 0 || (b->flags & 3))
+ for (int a = 0; a < 3; a++) {
+ if (cell[a] < clo[t][a]) clo[t][a] = cell[a];
+ if (cell[a] > chi[t][a]) chi[t][a] = cell[a];
+ }
+ float cx = cell[0] * 8.0f, cy = cell[1] * 8.0f, cz = cell[2] * 8.0f;
+ const uint8_t *bb = b->bb + c * 6;
+ if (bb[0] <= bb[3]) v += (bb[3] - bb[0] + 1) * (bb[4] - bb[1] + 1) * (bb[5] - bb[2] + 1);
+ if (cx + bb[0] < bx0) bx0 = cx + bb[0];
+ if (cy + bb[1] < by0) by0 = cy + bb[1];
+ if (cz + bb[2] < bz0) bz0 = cz + bb[2];
+ if (cx + bb[3] + 1 > bx1) bx1 = cx + bb[3] + 1;
+ if (cy + bb[4] + 1 > by1) by1 = cy + bb[4] + 1;
+ if (cz + bb[5] + 1 > bz1) bz1 = cz + bb[5] + 1;
+ if (b->flags & 3) coll = 1;
+ }
+ s->mass = v / 512.0f;
+ {
+ int t = chi[1][0] >= 0 ? 1 : 0;
+ s->com = s->np ? v3((clo[t][0] + chi[t][0] + 1) * 0.5f, (clo[t][1] + chi[t][1] + 1) * 0.5f, (clo[t][2] + chi[t][2] + 1) * 0.5f)
+ : v3(0, 0, 0);
+ }
+ {
+ /* Fancade's object position: the centre of its bounds, where a stock block counts its whole cell
+ and a custom block its voxels */
+ float lo[3] = {1e9f, 1e9f, 1e9f}, hi[3] = {-1e9f, -1e9f, -1e9f};
+ for (int i = 0; i < s->np; i++) {
+ const Block *b = blocks[s->blk[i]];
+ uint32_t k = s->key[i];
+ const uint8_t *bb = b->bb + PK_C(k) * 6;
+ int c[3] = {PK_X(k), PK_Y(k), PK_Z(k)};
+ for (int a = 0; a < 3; a++) {
+ float l = (b->flags & 8) ? c[a] : c[a] + bb[a] / 8.0f, h = (b->flags & 8) ? c[a] + 1 : c[a] + (bb[a + 3] + 1) / 8.0f;
+ if (l < lo[a]) lo[a] = l;
+ if (h > hi[a]) hi[a] = h;
+ }
+ }
+ s->origin = s->np ? v3((lo[0] + hi[0]) * 0.5f, (lo[1] + hi[1]) * 0.5f, (lo[2] + hi[2]) * 0.5f) : s->com;
+ /* an object of one block sits at the centre of its cell */
+ bool one = true;
+ for (int i = 1; i < s->np && one; i++) one = (s->key[i] & ~7u) == (s->key[0] & ~7u);
+ if (s->np && one) s->origin = v3(PK_X(s->key[0]) + 0.5f, PK_Y(s->key[0]) + 0.5f, PK_Z(s->key[0]) + 0.5f);
+ }
+ s->bmin = v3(bx0 / 8, by0 / 8, bz0 / 8);
+ s->bmax = v3(bx1 / 8, by1 / 8, bz1 / 8);
+ s->coll = coll;
+ if (s->np == 1 && (blocks[s->blk[0]]->flags & 3) == 2) {
+ Block *b = blocks[s->blk[0]];
+ const uint8_t *bb = b->bb + PK_C(s->key[0]) * 6;
+ s->sphere = 1;
+ float ex = (bb[3] - bb[0] + 1) * 0.5f, ey = (bb[4] - bb[1] + 1) * 0.5f;
+ s->radius = (ex > ey ? ex : ey) / 8.0f;
+ }
+}
+
+/* second pass (blocks loaded): build the shapes; the list of shapes is setup-only data */
+static Shape **build_shapes(const uint8_t *p, uint16_t *nout) {
+ uint16_t n = rd16(p);
+ p += 2;
+ Shape **shapes = arena_tmp_alloc(sizeof(Shape *) * (n ? n : 1));
+ if (!shapes) return 0;
+ const uint8_t *cnt = p;
+ uint32_t total = 0;
+ for (int o = 0; o < n; o++) total += rdvar(&p);
+ const uint8_t *bp = p, *dp = p + total; /* block stream, key delta stream */
+ for (int o = 0; o < n; o++) {
+ uint32_t np = rdvar(&cnt);
+ Shape *s = arena_alloc(sizeof(Shape));
+ if (!s) return 0;
+ memset(s, 0, sizeof *s);
+ s->np = (uint16_t)np;
+ s->key = arena_alloc(4 * np);
+ s->blk = arena_alloc(np);
+ s->occ = arena_alloc(np);
+ if (!s->key || !s->blk || !s->occ) return 0;
+ uint32_t key = 0;
+ for (uint32_t i = 0; i < np; i++) {
+ s->blk[i] = *bp++;
+ key += rdvar(&dp);
+ s->key[i] = key;
+ }
+ shape_finish(s);
+ shapes[o] = s;
+ }
+ *nout = n;
+ return shapes;
+}
+
+/* --------------------------------------------------------------- programs */
+Obj *objs;
+int obj_cap;
+int nobj, nlevelobj;
+Level level;
+/* programs of the level (with their custom block children) */
+#define NPROG 48
+static Prog *progs[NPROG];
+static int nprogs;
+static Prog *prog_of(int rec) {
+ for (int i = 0; i < nprogs; i++)
+ if (progs[i]->rec == rec) return progs[i];
+ return 0;
+}
+
+int op_data_size(int op) {
+ switch (op) {
+ case OP_NUMBER: return 4;
+ case OP_VECTOR: case OP_ROTATION: return 12;
+ case OP_GET_VAR_NUM: case OP_GET_VAR_VEC: case OP_GET_VAR_ROT: case OP_GET_VAR_TRU: case OP_GET_VAR_OBJ:
+ case OP_GET_VAR_CON: case OP_SET_VAR_NUM: case OP_SET_VAR_VEC: case OP_SET_VAR_ROT: case OP_SET_VAR_TRU:
+ case OP_SET_VAR_OBJ: case OP_SET_VAR_CON: return 2;
+ case OP_WIN: case OP_LOSE: case OP_BUTTON: case OP_SET_CAMERA: case OP_JOYSTICK: case OP_PLAY_SOUND: return 1;
+ default: return 0;
+ }
+}
+
+
+static bool load_children(Prog *p);
+static Prog *load_prog(int rec) {
+ Prog *old = prog_of(rec);
+ if (old) return old;
+ if (nprogs == NPROG) return 0;
+ const uint8_t *d = load_rec(rec);
+ if (!d) return 0;
+ Prog *p = arena_alloc(sizeof(Prog));
+ memset(p, 0, sizeof *p);
+ progs[nprogs++] = p;
+ p->rec = rec;
+ const uint8_t *q = d;
+ p->is_level = q[0] & 1;
+ p->yc = (q[0] >> 1) & 15;
+ bool tables = q[0] & 0x80;
+ p->nnodes = rd16(q + 1);
+ p->nentries = rd16(q + 3);
+ p->entries = q + 5;
+ q += 5 + 2 * p->nentries;
+ p->nlocals = rd16(q);
+ p->ltypes = q + 2;
+ q += 2 + p->nlocals;
+ p->ninputs = q[0];
+ p->noutputs = q[1];
+ p->outrefs = q + 2;
+ q += 2 + 2 * p->noutputs;
+ p->nself = q[0];
+ p->selfvox = q + 1;
+ q += 1 + 3 * p->nself;
+ /* template objects */
+ p->objdata = q;
+ q = scan_objects(q);
+ if (tables) {
+ /* records read in place from flash carry their node offset and output slot tables */
+ p->nslots = rd16(q);
+ q += 2 + ((q + 2 - d) & 1);
+ p->off = (const uint16_t *)q;
+ p->slot = (const uint16_t *)(q + 2 * p->nnodes);
+ p->data = q + 4 * p->nnodes;
+ return load_children(p) ? p : 0;
+ }
+ p->data = q;
+ /* node offsets */
+ uint16_t *off = arena_alloc(2 * p->nnodes + 2), *slot = arena_alloc(2 * p->nnodes + 2);
+ if (!off || !slot) return 0;
+ p->off = off;
+ p->slot = slot;
+ uint16_t slots = 0;
+ const uint8_t *n = q;
+ for (int i = 0; i < p->nnodes; i++) {
+ off[i] = (uint16_t)(n - q);
+ int op = n[0];
+ slot[i] = NONE16;
+ if (op == OP_CUSTOM) {
+ n += 10 + 2 * n[9]; /* header, inputs */
+ n += 3 + 2 * n[2]; /* anchor object, self objects */
+ continue;
+ }
+ const unsigned char *sh = op_shape[op];
+ if (sh[3] && sh[1]) {
+ slot[i] = slots;
+ slots += sh[1];
+ }
+ n += 1 + 2 * sh[0];
+ for (int e = 0; e < sh[2]; e++) n += 1 + 2 * n[0];
+ n += 1 + 2 * n[0];
+ n += op_data_size(op);
+ }
+ p->nslots = slots;
+ return load_children(p) ? p : 0;
+}
+
+static bool load_children(Prog *p) {
+ for (int i = 0; i < p->nnodes; i++) {
+ const uint8_t *nd = p->data + p->off[i];
+ if (nd[0] == OP_CUSTOM && !load_prog(rd16(nd + 1))) return false;
+ }
+ return true;
+}
+
+Prog *prog_child(const Prog *p, int i) {
+ const uint8_t *nd = p->data + p->off[i];
+ return nd[0] == OP_CUSTOM ? prog_of(rd16(nd + 1)) : 0;
+}
+
+float mat_tab[NMAT][2];
+int nmat;
+uint8_t mat_find(float friction, float bounce) {
+ int best = 0;
+ float bd = 1e30f;
+ for (int i = 0; i < nmat; i++) {
+ float df = mat_tab[i][0] - friction, db = mat_tab[i][1] - bounce, d = df * df + db * db;
+ if (d == 0) return (uint8_t)i;
+ if (d < bd) bd = d, best = i;
+ }
+ if (nmat == NMAT) return (uint8_t)best; /* full: the closest pair */
+ mat_tab[nmat][0] = friction;
+ mat_tab[nmat][1] = bounce;
+ return (uint8_t)nmat++;
+}
+
+static void obj_init(Obj *o, Shape *s) {
+ memset(o, 0, sizeof *o);
+ o->shape = s;
+ o->pos = s->origin;
+ o->rot = qident();
+ o->flags = OF_VISIBLE | (s->coll ? OF_COLLIDE : 0);
+ for (int i = 0; i < s->np; i++)
+ if (blocks[s->blk[i]]->flags & 4) o->flags |= OF_PHYSICS;
+ o->mat = 0;
+ o->mass = s->mass > 0 ? s->mass : 1;
+#ifdef HOST
+ if (getenv("ND_DEFMASS")) o->mass *= atof(getenv("ND_DEFMASS"));
+#endif
+ o->lockp = 7;
+ o->lockr = 7;
+ o->body = -1;
+}
+
+int obj_clone(int src) {
+ if (src < 0) return -1;
+ if (nobj >= obj_cap) {
+ OOM("objects");
+ return -1;
+ }
+ Obj *o = &objs[nobj];
+ *o = objs[src];
+ o->flags &= ~(OF_TEMPLATE | OF_DEAD | OF_DYNAMIC);
+ o->flags |= OF_VISIBLE;
+ if (o->shape->coll) o->flags |= OF_COLLIDE;
+ o->body = -1;
+ o->src = objs[src].src;
+ return nobj++;
+}
+
+void obj_destroy(int id) {
+ if (id < 0 || id >= nobj) return;
+ objs[id].flags |= OF_DEAD;
+ objs[id].flags &= ~(OF_VISIBLE | OF_COLLIDE);
+}
+
+/* ------------------------------------------------------------------ level */
+extern bool vm_setup_envs(void); /* vm.c */
+
+int level_index;
+#ifdef HOST
+int st_obj_setup;
+uint32_t st_arena_setup;
+#endif
+
+bool world_load_level(int index) {
+ level_index = index;
+ arena_reset();
+ nmat = 0;
+ mat_find(0.5f, 0.0f); /* index 0: Fancade's defaults */
+#ifdef HOST
+ if (getenv("ND_OBJFRIC")) mat_tab[0][0] = atof(getenv("ND_OBJFRIC"));
+#endif
+ memset(blocks, 0, sizeof blocks);
+ memset(need_blk, 0, sizeof need_blk);
+ nobj = 0;
+ nprogs = 0;
+ /* the level record is only needed while loading: inflate it into free space, read the object
+ * capacity, reserve the object table at the top, then keep the record just below it */
+ uint32_t avail;
+ uint8_t *d = arena_top(&avail);
+ int lrec = rd16(level_entry(index));
+ uint32_t rn = pack_rawsize(lrec);
+ if (rn > avail || pack_load(lrec, d, rn) != (int)rn) FAIL("world_load_level");
+ const uint8_t *q = d;
+ int l = q[0];
+ memcpy(level.name, q + 1, l < 39 ? l : 39);
+ level.name[l < 39 ? l : 39] = 0;
+ q += 1 + l;
+ level.sx = rd16(q);
+ level.sy = rd16(q + 2);
+ level.sz = rd16(q + 4);
+ level.bg = q[6];
+ int prec = rd16(q + 7);
+ obj_cap = rd16(q + 9);
+ level.body_cap = rd16(q + 11);
+ level.joint_cap = rd16(q + 13);
+ q += 15;
+#ifdef HOST
+ if (getenv("ND_NOCAPS")) obj_cap = 3000, level.body_cap = 600, level.joint_cap = 800;
+#endif
+ uint32_t head = (uint32_t)(q - d);
+ objs = arena_high_alloc(sizeof(Obj) * obj_cap);
+ uint8_t *rec = arena_tmp_alloc(rn);
+ if (!objs || !rec) FAIL("world_load_level");
+ memmove(rec, d, rn);
+ const uint8_t *objdata = rec + head;
+ scan_objects(objdata);
+ level.prog = load_prog(prec);
+ if (!level.prog) FAIL("world_load_level");
+ level.index = index;
+ if (!load_blocks()) FAIL("world_load_level");
+ /* level objects first, then the template shapes of every program */
+ uint16_t n;
+ Shape **shapes = build_shapes(objdata, &n);
+ if (!shapes) FAIL("world_load_level");
+ for (int i = 0; i < n; i++) {
+ obj_init(&objs[nobj], shapes[i]);
+ objs[nobj].src = nobj;
+ nobj++;
+ }
+ nlevelobj = nobj;
+ for (int r = 0; r < nprogs; r++) {
+ Prog *p = progs[r];
+ p->tmpl = build_shapes(p->objdata, &p->ntmpl);
+ if (!p->tmpl) FAIL("world_load_level");
+ }
+#ifdef HOST
+ if (getenv("ND_SHDBG")) {
+ for (int r = -1; r < nprogs; r++) {
+ Shape **ss = r < 0 ? shapes : progs[r]->tmpl;
+ int ns = r < 0 ? n : progs[r]->ntmpl;
+ for (int i = 0; i < ns; i++) {
+ Shape *sh = ss[i];
+ uint32_t h = 2166136261u, k0 = sh->np ? sh->key[0] & ~7u : 0;
+ uint32_t x0 = k0 >> 20, y0 = (k0 >> 13) & 127, z0 = (k0 >> 3) & 1023;
+ for (int j = 0; j < sh->np; j++) {
+ uint32_t k = sh->key[j], d = ((k >> 20) - x0) << 20 | (((k >> 13) & 127) - y0) << 13 | (((k >> 3) & 1023) - z0) << 3 | (k & 7);
+ h = (h ^ d) * 16777619u;
+ h = (h ^ sh->blk[j]) * 16777619u;
+ }
+ fprintf(stderr, "SHAPE r%d i%d np %d hash %08x\n", r, i, sh->np, h);
+ if (r < 0 && getenv("ND_SHPARTS") && atoi(getenv("ND_SHPARTS")) == i)
+ for (int j = 0; j < sh->np; j++) {
+ const Block *b = blocks[sh->blk[j]];
+ int c = PK_C(sh->key[j]);
+ const uint8_t *bb = b->bb + c * 6;
+ fprintf(stderr, " part blk%d fl%x cell(%d,%d,%d) comp %d coll %d bb[%d-%d,%d-%d,%d-%d]\n", sh->blk[j], b->flags, PK_X(sh->key[j]), PK_Y(sh->key[j]), PK_Z(sh->key[j]), c,
+ b->flags & 3, bb[0], bb[3], bb[1], bb[4], bb[2], bb[5]);
+ }
+ }
+ }
+ }
+#endif
+ if (!vm_setup_envs()) FAIL("world_load_level");
+ arena_tmp_reset(); /* the level record and template lists are only needed while instantiating */
+#ifdef HOST
+ {
+ extern int st_obj_setup;
+ extern uint32_t st_arena_setup;
+ if (nobj > st_obj_setup) st_obj_setup = nobj;
+ if (arena_pos > st_arena_setup) st_arena_setup = arena_pos;
+ }
+#endif
+ return true;
+}
+
+/* template objects are created by the VM when environments are instantiated */
+int world_add_template(Shape *s) {
+ if (nobj >= obj_cap) return -1;
+ obj_init(&objs[nobj], s);
+ objs[nobj].flags &= ~(OF_VISIBLE | OF_COLLIDE);
+ objs[nobj].flags |= OF_TEMPLATE;
+ objs[nobj].src = nobj;
+ return nobj++;
+}
diff --git a/games/numdrive/src/world.h b/games/numdrive/src/world.h
new file mode 100644
index 00000000..84218072
--- /dev/null
+++ b/games/numdrive/src/world.h
@@ -0,0 +1,174 @@
+#ifndef WORLD_H
+#define WORLD_H
+#include <stdint.h>
+#include <stdbool.h>
+#include "fmath.h"
+
+#define NONE16 0xFFFF
+
+/* out-of-memory reporting on the host harness */
+#ifdef HOST
+#include <stdio.h>
+#define OOM(what) do { static int once; if (!once++) fprintf(stderr, "OOM %s\n", what); } while (0)
+#else
+#define OOM(what) do { } while (0)
+#endif
+
+/* ------------------------------------------------------------------ arena */
+void *arena_alloc(uint32_t size);
+#if defined(HOST) && defined(ARENA_PROFILE) && !defined(ARENA_IMPL)
+void *arena_alloc_dbg(uint32_t size, const char *f, int l);
+#define arena_alloc(n) arena_alloc_dbg((n), __FILE__, __LINE__)
+#endif
+void arena_reset(void);
+void *arena_tmp_alloc(uint32_t size); /* setup-only data, freed after the level is instantiated */
+void arena_tmp_reset(void);
+uint32_t arena_tmp_mark(void);
+void arena_tmp_release(uint32_t m);
+void *arena_keep_alloc(uint32_t size); /* after setup: allocation kept until the next level */
+extern int level_serial;
+uint32_t arena_used(void);
+uint32_t arena_mark(void);
+void arena_release(uint32_t mark);
+bool arena_release_top(void *p, uint32_t size); /* frees p if it is the last allocation */
+bool arena_extend(void *p, uint32_t old_size, uint32_t new_size); /* grow the last allocation in place */
+void *arena_top(uint32_t *avail); /* scratch space at the top of the arena */
+
+/* ------------------------------------------------------------------- pack */
+int pack_records(void);
+uint32_t pack_rawsize(int rec);
+int pack_load(int rec, uint8_t *dst, uint32_t cap);
+
+/* ----------------------------------------------------------------- blocks */
+typedef struct {
+ uint8_t flags; /* bits 0-1 collider (0 none, 1 box, 2 sphere), bit 2 physics prefab */
+ uint8_t ncomp;
+ uint8_t full; /* 6 bits: face fully covered */
+ uint8_t nbox;
+ const uint8_t *boxes; /* nbox * 3 */
+ const uint8_t *fq[6]; /* quads per face, 3 bytes each */
+ uint8_t nq[6];
+ /* per component stats (voxel units) */
+ uint8_t *bb; /* ncomp * 6: min xyz, max xyz (inclusive) */
+} Block;
+
+extern Block *blocks[256]; /* loaded blocks by library index (NULL if unused) */
+
+/* ----------------------------------------------------------------- shapes */
+/* A set of voxel-block parts forming one object shape (shared by clones). */
+typedef struct {
+ uint16_t np;
+ uint8_t coll; /* 1 if any part collides */
+ uint8_t sphere; /* shape is a single sphere */
+ uint32_t *key; /* x<<20 | y<<13 | z<<3 | comp (cell coords), sorted */
+ uint8_t *blk; /* library index per part */
+ uint8_t *occ; /* per part: faces hidden by a full neighbour face of the same shape */
+ float mass;
+ float radius; /* sphere radius */
+ vec3 com; /* rest-space centre of mass (world units) */
+ vec3 origin; /* rest-space reference point (centre of the block nearest the com) */
+ vec3 bmin, bmax; /* rest-space bounds (world units) */
+} Shape;
+
+#define PK_X(k) ((k) >> 20)
+#define PK_Y(k) (((k) >> 13) & 127)
+#define PK_Z(k) (((k) >> 3) & 1023)
+#define PK_C(k) ((k) & 7)
+
+/* ---------------------------------------------------------------- objects */
+enum {
+ OF_VISIBLE = 1, OF_COLLIDE = 2, OF_PHYSICS = 4, OF_DYNAMIC = 8, OF_TEMPLATE = 16, OF_DEAD = 32, OF_MOVED = 64
+};
+
+typedef struct {
+ Shape *shape;
+ vec3 pos; /* world position of the shape origin */
+ quat rot;
+ float mass;
+ uint8_t flags;
+ uint8_t mat; /* friction and bounciness (index into mat_tab) */
+ uint16_t src; /* object this was cloned from (or itself) */
+ int16_t body; /* physics body index or -1 */
+ uint8_t lockp, lockr; /* allowed axes bits (x=1,y=2,z=4) for position / rotation */
+} Obj;
+
+/* the distinct friction / bounciness pairs of the level's objects */
+#define NMAT 32
+extern float mat_tab[NMAT][2];
+extern int nmat;
+static inline float obj_friction(const Obj *o) { return mat_tab[o->mat][0]; }
+static inline float obj_bounce(const Obj *o) { return mat_tab[o->mat][1]; }
+uint8_t mat_find(float friction, float bounce);
+
+extern Obj *objs;
+extern int obj_cap;
+extern int nobj;
+extern int nlevelobj;
+
+/* world transform helpers: rest point -> world */
+static inline vec3 obj_world(const Obj *o, vec3 rest) {
+ return vadd(o->pos, qrot(o->rot, vsub(rest, o->shape->origin)));
+}
+static inline vec3 obj_local(const Obj *o, vec3 w) {
+ return vadd(o->shape->origin, qrot(qconj(o->rot), vsub(w, o->pos)));
+}
+
+/* --------------------------------------------------------------- programs */
+typedef struct Prog {
+ uint8_t is_level;
+ uint8_t yc; /* model centre height of a script block, in 1/16 */
+ uint16_t rec;
+ uint16_t nnodes;
+ const uint16_t *off; /* node offsets into data */
+ const uint8_t *data; /* node records */
+ uint16_t nentries;
+ const uint8_t *entries;
+ uint16_t nlocals;
+ const uint8_t *ltypes;
+ uint8_t ninputs, noutputs;
+ const uint8_t *outrefs;
+ uint8_t nself;
+ const uint8_t *selfvox;
+ uint16_t ntmpl; /* template shapes formed from the inner grid */
+ Shape **tmpl;
+ const uint16_t *slot; /* per node output slot (or NONE16) */
+ uint16_t nslots;
+ const uint8_t *objdata; /* template objects (see scan_objects) */
+} Prog;
+
+Prog *prog_child(const Prog *p, int node); /* child program of a CUSTOM node, else NULL */
+
+typedef struct Env Env;
+
+/* ------------------------------------------------------------------ level */
+typedef struct {
+ char name[40];
+ uint16_t sx, sy, sz;
+ uint16_t body_cap, joint_cap; /* physics capacities measured for this level */
+ uint8_t bg;
+ Prog *prog;
+ int index;
+} Level;
+
+extern Level level;
+extern int level_index;
+extern int nlevels;
+const char *level_name(int i);
+
+bool world_init(void);
+bool world_load_level(int index);
+
+
+/* global variables */
+extern uint16_t nglobals;
+extern const uint8_t *global_types;
+
+/* clone / destroy */
+int obj_clone(int src);
+void obj_destroy(int id);
+
+/* find part index of cell (x,y,z) in shape (first component), or -1 */
+int shape_find(const Shape *s, int x, int y, int z);
+vec3 shape_block_center(const Shape *s, int x, int y, int z);
+
+#endif
diff --git a/games/numdrive/tools/.gitignore b/games/numdrive/tools/.gitignore
new file mode 100644
index 00000000..f1d016e9
--- /dev/null
+++ b/games/numdrive/tools/.gitignore
@@ -0,0 +1,2 @@
+source/
+__pycache__/
diff --git a/games/numdrive/tools/blockdefs.py b/games/numdrive/tools/blockdefs.py
new file mode 100644
index 00000000..aa14fa67
--- /dev/null
+++ b/games/numdrive/tools/blockdefs.py
@@ -0,0 +1,135 @@
+"""Fancade stock script block definitions (name, kind, size, terminals).
+
+Terminal layout derived from BitcoderCZ.Fancade (MIT License, Copyright (c) BitcoderCZ).
+Each terminal: (signal type, direction, name, voxel position inside the block).
+"""
+
+DEFS = {
+ 16: ('Inspect Number', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Float', 'In', 'Number', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 20: ('Inspect Vector', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Vec3', 'In', 'Vector', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 24: ('Inspect Rotation', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Rot', 'In', 'Rotation', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 28: ('Inspect Truth', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Bool', 'In', 'Truth', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 32: ('Inspect Object', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Obj', 'In', 'Object', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 36: ('Number', 'Value', (2, 1, 1), [('Float', 'Out', 'Number', (14, 1, 3))]),
+ 38: ('Vector', 'Value', (2, 1, 2), [('Vec3', 'Out', 'Vector', (14, 1, 11))]),
+ 42: ('Rotation', 'Value', (2, 1, 2), [('Rot', 'Out', 'Rotation', (14, 1, 11))]),
+ 46: ('Variable', 'Pasive', (2, 1, 1), [('FloatPtr', 'Out', 'Number', (14, 1, 3))]),
+ 48: ('Variable', 'Pasive', (2, 1, 1), [('Vec3Ptr', 'Out', 'Vector', (14, 1, 3))]),
+ 50: ('Variable', 'Pasive', (2, 1, 1), [('RotPtr', 'Out', 'Rotation', (14, 1, 3))]),
+ 52: ('Variable', 'Pasive', (2, 1, 1), [('BoolPtr', 'Out', 'Truth', (14, 1, 3))]),
+ 54: ('Variable', 'Pasive', (2, 1, 1), [('ObjPtr', 'Out', 'Object', (14, 1, 3))]),
+ 56: ('Variable', 'Pasive', (2, 1, 1), [('ConPtr', 'Out', 'Constraint', (14, 1, 3))]),
+ 58: ('Set Number', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Float', 'In', 'Value', (0, 1, 3)), ('FloatPtr', 'In', 'Variable', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 62: ('Set Vector', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Vec3', 'In', 'Value', (0, 1, 3)), ('Vec3Ptr', 'In', 'Variable', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 66: ('Set Rotation', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Rot', 'In', 'Value', (0, 1, 3)), ('RotPtr', 'In', 'Variable', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 70: ('Set Truth', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Bool', 'In', 'Value', (0, 1, 3)), ('BoolPtr', 'In', 'Variable', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 74: ('Set Object', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Obj', 'In', 'Value', (0, 1, 3)), ('ObjPtr', 'In', 'Variable', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 78: ('Set Constraint', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Obj', 'In', 'Value', (0, 1, 3)), ('ConPtr', 'In', 'Variable', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 82: ('List Number', 'Pasive', (2, 1, 2), [('FloatPtr', 'Out', 'Element', (14, 1, 11)), ('Float', 'In', 'Index', (0, 1, 3)), ('FloatPtr', 'In', 'Variable', (0, 1, 11))]),
+ 86: ('List Object', 'Pasive', (2, 1, 2), [('ObjPtr', 'Out', 'Element', (14, 1, 11)), ('Float', 'In', 'Index', (0, 1, 3)), ('ObjPtr', 'In', 'Variable', (0, 1, 11))]),
+ 90: ('Negate', 'Pasive', (2, 1, 1), [('Float', 'Out', '-Num', (14, 1, 3)), ('Float', 'In', 'Num', (0, 1, 3))]),
+ 92: ('Add Numbers', 'Pasive', (2, 1, 2), [('Float', 'Out', 'Num1 + Num2', (14, 1, 11)), ('Float', 'In', 'Num2', (0, 1, 3)), ('Float', 'In', 'Num1', (0, 1, 11))]),
+ 96: ('Add Vectors', 'Pasive', (2, 1, 2), [('Vec3', 'Out', 'Vec1 + Vec2', (14, 1, 11)), ('Vec3', 'In', 'Vec2', (0, 1, 3)), ('Vec3', 'In', 'Vec1', (0, 1, 11))]),
+ 100: ('Subtract Numbers', 'Pasive', (2, 1, 2), [('Float', 'Out', 'Num1 - Num2', (14, 1, 11)), ('Float', 'In', 'Num2', (0, 1, 3)), ('Float', 'In', 'Num1', (0, 1, 11))]),
+ 104: ('Subtract Vectors', 'Pasive', (2, 1, 2), [('Vec3', 'Out', 'Vec1 - Vec2', (14, 1, 11)), ('Vec3', 'In', 'Vec2', (0, 1, 3)), ('Vec3', 'In', 'Vec1', (0, 1, 11))]),
+ 108: ('Multiply', 'Pasive', (2, 1, 2), [('Float', 'Out', 'Num1 * Num2', (14, 1, 11)), ('Float', 'In', 'Num2', (0, 1, 3)), ('Float', 'In', 'Num1', (0, 1, 11))]),
+ 112: ('Scale', 'Pasive', (2, 1, 2), [('Vec3', 'Out', 'Vec * Num', (14, 1, 11)), ('Float', 'In', 'Num', (0, 1, 3)), ('Vec3', 'In', 'Vec', (0, 1, 11))]),
+ 116: ('Rotate', 'Pasive', (2, 1, 2), [('Vec3', 'Out', 'Rot * Vec', (14, 1, 11)), ('Rot', 'In', 'Rot', (0, 1, 3)), ('Vec3', 'In', 'Vec', (0, 1, 11))]),
+ 120: ('Combine', 'Pasive', (2, 1, 2), [('Rot', 'Out', 'Rot1 * Rot2', (14, 1, 11)), ('Rot', 'In', 'Rot2', (0, 1, 3)), ('Rot', 'In', 'Rot1', (0, 1, 11))]),
+ 124: ('Divide', 'Pasive', (2, 1, 2), [('Float', 'Out', 'Num1 / Num2', (14, 1, 11)), ('Float', 'In', 'Num2', (0, 1, 3)), ('Float', 'In', 'Num1', (0, 1, 11))]),
+ 128: ('Less Than', 'Pasive', (2, 1, 2), [('Bool', 'Out', 'Num1 < Num2', (14, 1, 11)), ('Float', 'In', 'Num2', (0, 1, 3)), ('Float', 'In', 'Num1', (0, 1, 11))]),
+ 132: ('Equals Numbers', 'Pasive', (2, 1, 2), [('Bool', 'Out', 'Num1 = Num2', (14, 1, 11)), ('Float', 'In', 'Num2', (0, 1, 3)), ('Float', 'In', 'Num1', (0, 1, 11))]),
+ 136: ('Equals Vectors', 'Pasive', (2, 1, 2), [('Bool', 'Out', 'Vec1 = Vec2', (14, 1, 11)), ('Vec3', 'In', 'Vec2', (0, 1, 3)), ('Vec3', 'In', 'Vec1', (0, 1, 11))]),
+ 140: ('Equals Objects', 'Pasive', (2, 1, 2), [('Bool', 'Out', 'Obj1 = Obj2', (14, 1, 11)), ('Obj', 'In', 'Obj2', (0, 1, 3)), ('Obj', 'In', 'Obj1', (0, 1, 11))]),
+ 144: ('Not', 'Pasive', (2, 1, 1), [('Bool', 'Out', 'Not Tru', (14, 1, 3)), ('Bool', 'In', 'Tru', (0, 1, 3))]),
+ 146: ('AND', 'Pasive', (2, 1, 2), [('Bool', 'Out', 'Tru1 & Tru2', (14, 1, 11)), ('Bool', 'In', 'Tru2', (0, 1, 3)), ('Bool', 'In', 'Tru1', (0, 1, 11))]),
+ 150: ('Make Vector', 'Pasive', (2, 1, 3), [('Vec3', 'Out', 'Vector', (14, 1, 19)), ('Float', 'In', 'Z', (0, 1, 3)), ('Float', 'In', 'Y', (0, 1, 11)), ('Float', 'In', 'X', (0, 1, 19))]),
+ 156: ('Break Vector', 'Pasive', (2, 1, 3), [('Float', 'Out', 'Z', (14, 1, 3)), ('Float', 'Out', 'Y', (14, 1, 11)), ('Float', 'Out', 'X', (14, 1, 19)), ('Vec3', 'In', 'Vector', (0, 1, 19))]),
+ 162: ('Make Rotation', 'Pasive', (2, 1, 3), [('Rot', 'Out', 'Rotation', (14, 1, 19)), ('Float', 'In', 'Z angle', (0, 1, 3)), ('Float', 'In', 'Y angle', (0, 1, 11)), ('Float', 'In', 'X angle', (0, 1, 19))]),
+ 168: ('Random', 'Pasive', (2, 1, 2), [('Float', 'Out', 'Random', (14, 1, 11)), ('Float', 'In', 'Max', (0, 1, 3)), ('Float', 'In', 'Min', (0, 1, 11))]),
+ 172: ('Modulo', 'Pasive', (2, 1, 2), [('Float', 'Out', 'mod(a,b)', (14, 1, 11)), ('Float', 'In', 'b', (0, 1, 3)), ('Float', 'In', 'a', (0, 1, 11))]),
+ 176: ('Min', 'Pasive', (2, 1, 2), [('Float', 'Out', 'Smaller', (14, 1, 11)), ('Float', 'In', 'Num2', (0, 1, 3)), ('Float', 'In', 'Num1', (0, 1, 11))]),
+ 180: ('Max', 'Pasive', (2, 1, 2), [('Float', 'Out', 'Bigger', (14, 1, 11)), ('Float', 'In', 'Num2', (0, 1, 3)), ('Float', 'In', 'Num1', (0, 1, 11))]),
+ 184: ('Round', 'Pasive', (2, 1, 1), [('Float', 'Out', 'Rounded', (14, 1, 3)), ('Float', 'In', 'Number', (0, 1, 3))]),
+ 186: ('Floor', 'Pasive', (2, 1, 1), [('Float', 'Out', 'Floor', (14, 1, 3)), ('Float', 'In', 'Number', (0, 1, 3))]),
+ 188: ('Ceiling', 'Pasive', (2, 1, 1), [('Float', 'Out', 'Ceiling', (14, 1, 3)), ('Float', 'In', 'Number', (0, 1, 3))]),
+ 190: ('Distance', 'Pasive', (2, 1, 2), [('Float', 'Out', 'Distance', (14, 1, 11)), ('Vec3', 'In', 'Vector', (0, 1, 3)), ('Vec3', 'In', 'Vector', (0, 1, 11))]),
+ 194: ('LERP', 'Pasive', (2, 1, 3), [('Rot', 'Out', 'Rotation', (14, 1, 19)), ('Float', 'In', 'Amount', (0, 1, 3)), ('Rot', 'In', 'To', (0, 1, 11)), ('Rot', 'In', 'From', (0, 1, 19))]),
+ 200: ('Axis Angle', 'Pasive', (2, 1, 2), [('Rot', 'Out', 'Rotation', (14, 1, 11)), ('Float', 'In', 'Angle', (0, 1, 3)), ('Vec3', 'In', 'Axis', (0, 1, 11))]),
+ 204: ('Look Rotation', 'Pasive', (2, 1, 2), [('Rot', 'Out', 'Rotation', (14, 1, 11)), ('Vec3', 'In', 'Up', (0, 1, 3)), ('Vec3', 'In', 'Direction', (0, 1, 11))]),
+ 208: ('Line vs Plane', 'Pasive', (2, 1, 4), [('Vec3', 'Out', 'Intersection', (14, 1, 27)), ('Vec3', 'In', 'Plane Normal', (0, 1, 3)), ('Vec3', 'In', 'Plane Point', (0, 1, 11)), ('Vec3', 'In', 'Line To', (0, 1, 19)), ('Vec3', 'In', 'Line From', (0, 1, 27))]),
+ 216: ('Screen To World', 'Pasive', (2, 1, 2), [('Vec3', 'Out', 'World Far', (14, 1, 3)), ('Vec3', 'Out', 'World Near', (14, 1, 11)), ('Float', 'In', 'Screen Y', (0, 1, 3)), ('Float', 'In', 'Screen X', (0, 1, 11))]),
+ 220: ('Screen Size', 'Pasive', (2, 1, 2), [('Float', 'Out', 'Height', (14, 1, 3)), ('Float', 'Out', 'Width', (14, 1, 11))]),
+ 224: ('Accelerometer', 'Pasive', (2, 1, 2), [('Vec3', 'Out', 'Direction', (14, 1, 11))]),
+ 228: ('Raycast', 'Pasive', (2, 1, 3), [('Obj', 'Out', 'Hit Obj', (14, 1, 3)), ('Vec3', 'Out', 'Hit Pos', (14, 1, 11)), ('Bool', 'Out', 'Hit?', (14, 1, 19)), ('Vec3', 'In', 'To', (0, 1, 11)), ('Vec3', 'In', 'From', (0, 1, 19))]),
+ 234: ('If', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Void', 'Out', 'False', (14, 1, 3)), ('Void', 'Out', 'True', (14, 1, 11)), ('Bool', 'In', 'Condition', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 238: ('Play Sensor', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Void', 'Out', 'On Play', (14, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 242: ('Touch Sensor', 'Active', (2, 1, 3), [('Void', 'Out', 'After', (3, 1, 0)), ('Float', 'Out', 'Screen Y', (14, 1, 3)), ('Float', 'Out', 'Screen X', (14, 1, 11)), ('Void', 'Out', 'Touched', (14, 1, 19)), ('Void', 'In', 'Before', (3, 1, 22))]),
+ 248: ('Swipe Sensor', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Vec3', 'Out', 'Direction', (14, 1, 3)), ('Void', 'Out', 'Swiped', (14, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 252: ('Win', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 256: ('Lose', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 260: ('Set Score', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Float', 'In', 'Coins', (0, 1, 3)), ('Float', 'In', 'Score', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 264: ('Play Sound', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Float', 'Out', 'Channel', (14, 1, 11)), ('Float', 'In', 'Pitch', (0, 1, 3)), ('Float', 'In', 'Volume', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 268: ('Set Camera', 'Active', (2, 1, 3), [('Void', 'Out', 'After', (3, 1, 0)), ('Float', 'In', 'Range', (0, 1, 3)), ('Rot', 'In', 'Rotation', (0, 1, 11)), ('Vec3', 'In', 'Position', (0, 1, 19)), ('Void', 'In', 'Before', (3, 1, 22))]),
+ 274: ('Set Light', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Rot', 'In', 'Rotation', (0, 1, 3)), ('Vec3', 'In', 'Position', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 278: ('Get Position', 'Pasive', (2, 1, 2), [('Rot', 'Out', 'Rotation', (14, 1, 3)), ('Vec3', 'Out', 'Position', (14, 1, 11)), ('Obj', 'In', 'Object', (0, 1, 11))]),
+ 282: ('Set Position', 'Active', (2, 1, 3), [('Void', 'Out', 'After', (3, 1, 0)), ('Rot', 'In', 'Rotation', (0, 1, 3)), ('Vec3', 'In', 'Position', (0, 1, 11)), ('Obj', 'In', 'Object', (0, 1, 19)), ('Void', 'In', 'Before', (3, 1, 22))]),
+ 288: ('Get Velocity', 'Pasive', (2, 1, 2), [('Vec3', 'Out', 'Spin', (14, 1, 3)), ('Vec3', 'Out', 'Velocity', (14, 1, 11)), ('Obj', 'In', 'Object', (0, 1, 11))]),
+ 292: ('Set Velocity', 'Active', (2, 1, 3), [('Void', 'Out', 'After', (3, 1, 0)), ('Vec3', 'In', 'Spin', (0, 1, 3)), ('Vec3', 'In', 'Velocity', (0, 1, 11)), ('Obj', 'In', 'Object', (0, 1, 19)), ('Void', 'In', 'Before', (3, 1, 22))]),
+ 298: ('Add Force', 'Active', (2, 1, 4), [('Void', 'Out', 'After', (3, 1, 0)), ('Vec3', 'In', 'Torque', (0, 1, 3)), ('Vec3', 'In', 'Apply at', (0, 1, 11)), ('Vec3', 'In', 'Force', (0, 1, 19)), ('Obj', 'In', 'Object', (0, 1, 27)), ('Void', 'In', 'Before', (3, 1, 30))]),
+ 306: ('Set Visible', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Bool', 'In', 'Visible', (0, 1, 3)), ('Obj', 'In', 'Object', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 310: ('Set Locked', 'Active', (2, 1, 3), [('Void', 'Out', 'After', (3, 1, 0)), ('Vec3', 'In', 'Rotation', (0, 1, 3)), ('Vec3', 'In', 'Position', (0, 1, 11)), ('Obj', 'In', 'Object', (0, 1, 19)), ('Void', 'In', 'Before', (3, 1, 22))]),
+ 316: ('Create Object', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Obj', 'Out', 'Copy', (14, 1, 11)), ('Obj', 'In', 'Object', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 320: ('Destroy Object', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Obj', 'In', 'Object', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 324: ('Set Gravity', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Vec3', 'In', 'Gravity', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 328: ('Set Mass', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Float', 'In', 'Mass', (0, 1, 3)), ('Obj', 'In', 'Object', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 332: ('Set Friction', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Float', 'In', 'Friction', (0, 1, 3)), ('Obj', 'In', 'Object', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 336: ('Set Bounciness', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Float', 'In', 'Bounciness', (0, 1, 3)), ('Obj', 'In', 'Object', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 340: ('Add Constraint', 'Active', (2, 1, 3), [('Void', 'Out', 'After', (3, 1, 0)), ('Con', 'Out', 'Constraint', (14, 1, 19)), ('Vec3', 'In', 'Pivot', (0, 1, 3)), ('Obj', 'In', 'Part', (0, 1, 11)), ('Obj', 'In', 'Base', (0, 1, 19)), ('Void', 'In', 'Before', (3, 1, 22))]),
+ 346: ('Linear Limits', 'Active', (2, 1, 3), [('Void', 'Out', 'After', (3, 1, 0)), ('Vec3', 'In', 'Upper', (0, 1, 3)), ('Vec3', 'In', 'Lower', (0, 1, 11)), ('Con', 'In', 'Constraint', (0, 1, 19)), ('Void', 'In', 'Before', (3, 1, 22))]),
+ 352: ('Angular Limits', 'Active', (2, 1, 3), [('Void', 'Out', 'After', (3, 1, 0)), ('Vec3', 'In', 'Upper', (0, 1, 3)), ('Vec3', 'In', 'Lower', (0, 1, 11)), ('Con', 'In', 'Constraint', (0, 1, 19)), ('Void', 'In', 'Before', (3, 1, 22))]),
+ 358: ('Linear Spring', 'Active', (2, 1, 3), [('Void', 'Out', 'After', (3, 1, 0)), ('Vec3', 'In', 'Damping', (0, 1, 3)), ('Vec3', 'In', 'Stiffness', (0, 1, 11)), ('Con', 'In', 'Constraint', (0, 1, 19)), ('Void', 'In', 'Before', (3, 1, 22))]),
+ 364: ('Angular Spring', 'Active', (2, 1, 3), [('Void', 'Out', 'After', (3, 1, 0)), ('Vec3', 'In', 'Damping', (0, 1, 3)), ('Vec3', 'In', 'Stiffness', (0, 1, 11)), ('Con', 'In', 'Constraint', (0, 1, 19)), ('Void', 'In', 'Before', (3, 1, 22))]),
+ 370: ('Linear Motor', 'Active', (2, 1, 3), [('Void', 'Out', 'After', (3, 1, 0)), ('Vec3', 'In', 'Force', (0, 1, 3)), ('Vec3', 'In', 'Speed', (0, 1, 11)), ('Con', 'In', 'Constraint', (0, 1, 19)), ('Void', 'In', 'Before', (3, 1, 22))]),
+ 376: ('Angular Motor', 'Active', (2, 1, 3), [('Void', 'Out', 'After', (3, 1, 0)), ('Vec3', 'In', 'Force', (0, 1, 3)), ('Vec3', 'In', 'Speed', (0, 1, 11)), ('Con', 'In', 'Constraint', (0, 1, 19)), ('Void', 'In', 'Before', (3, 1, 22))]),
+ 391: ('Volume Pitch', 'Active', (2, 1, 3), [('Void', 'Out', 'After', (3, 1, 0)), ('Float', 'In', 'Pitch', (0, 1, 3)), ('Float', 'In', 'Volume', (0, 1, 11)), ('Float', 'In', 'Channel', (0, 1, 19)), ('Void', 'In', 'Before', (3, 1, 22))]),
+ 397: ('Stop Sound', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Float', 'In', 'Channel', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 401: ('Collision', 'Active', (2, 1, 4), [('Void', 'Out', 'After', (3, 1, 0)), ('Vec3', 'Out', 'Normal', (14, 1, 3)), ('Float', 'Out', 'Impulse', (14, 1, 11)), ('Obj', 'Out', '2nd Object', (14, 1, 19)), ('Void', 'Out', 'Collided', (14, 1, 27)), ('Obj', 'In', '1st Object', (0, 1, 27)), ('Void', 'In', 'Before', (3, 1, 30))]),
+ 409: ('Box Art Sensor', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Void', 'Out', 'On Screenshot', (14, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 413: ('Sin', 'Pasive', (2, 1, 1), [('Float', 'Out', 'Sin(Num)', (14, 1, 3)), ('Float', 'In', 'Num', (0, 1, 3))]),
+ 417: ('OR', 'Pasive', (2, 1, 2), [('Bool', 'Out', 'Tru1 | Tru2', (14, 1, 11)), ('Bool', 'In', 'Tru2', (0, 1, 3)), ('Bool', 'In', 'Tru1', (0, 1, 11))]),
+ 421: ('Equals Truths', 'Pasive', (2, 1, 2), [('Bool', 'Out', 'Tru1 = Tru2', (14, 1, 11)), ('Bool', 'In', 'Tru2', (0, 1, 3)), ('Bool', 'In', 'Tru1', (0, 1, 11))]),
+ 428: ('Set Variable', 'Active', (2, 1, 1), [('Void', 'Out', 'After', (3, 1, 0)), ('Float', 'In', 'Value', (0, 1, 3)), ('Void', 'In', 'Before', (3, 1, 6))]),
+ 430: ('Set Variable', 'Active', (2, 1, 1), [('Void', 'Out', 'After', (3, 1, 0)), ('Vec3', 'In', 'Value', (0, 1, 3)), ('Void', 'In', 'Before', (3, 1, 6))]),
+ 432: ('Set Variable', 'Active', (2, 1, 1), [('Void', 'Out', 'After', (3, 1, 0)), ('Rot', 'In', 'Value', (0, 1, 3)), ('Void', 'In', 'Before', (3, 1, 6))]),
+ 434: ('Set Variable', 'Active', (2, 1, 1), [('Void', 'Out', 'After', (3, 1, 0)), ('Bool', 'In', 'Value', (0, 1, 3)), ('Void', 'In', 'Before', (3, 1, 6))]),
+ 436: ('Set Variable', 'Active', (2, 1, 1), [('Void', 'Out', 'After', (3, 1, 0)), ('Obj', 'In', 'Value', (0, 1, 3)), ('Void', 'In', 'Before', (3, 1, 6))]),
+ 438: ('Set Variable', 'Active', (2, 1, 1), [('Void', 'Out', 'After', (3, 1, 0)), ('Con', 'In', 'Value', (0, 1, 3)), ('Void', 'In', 'Before', (3, 1, 6))]),
+ 440: ('Inverse', 'Pasive', (2, 1, 1), [('Rot', 'Out', 'Rot Inverse', (14, 1, 3)), ('Rot', 'In', 'Rot', (0, 1, 3))]),
+ 442: ('Break Rotation', 'Pasive', (2, 1, 3), [('Float', 'Out', 'Z angle', (14, 1, 3)), ('Float', 'Out', 'Y angle', (14, 1, 11)), ('Float', 'Out', 'X angle', (14, 1, 19)), ('Rot', 'In', 'Rotation', (0, 1, 19))]),
+ 449: ('True', 'Value', (2, 1, 1), [('Bool', 'Out', 'True', (14, 1, 3))]),
+ 451: ('False', 'Value', (2, 1, 1), [('Bool', 'Out', 'False', (14, 1, 3))]),
+ 453: ('Cos', 'Pasive', (2, 1, 1), [('Float', 'Out', 'Cos(Num)', (14, 1, 3)), ('Float', 'In', 'Num', (0, 1, 3))]),
+ 455: ('Absolute', 'Pasive', (2, 1, 1), [('Float', 'Out', '|Num|', (14, 1, 3)), ('Float', 'In', 'Num', (0, 1, 3))]),
+ 457: ('Power', 'Pasive', (2, 1, 2), [('Float', 'Out', 'Base ^ Exponent', (14, 1, 11)), ('Float', 'In', 'Exponent', (0, 1, 3)), ('Float', 'In', 'Base', (0, 1, 11))]),
+ 461: ('List Vector', 'Pasive', (2, 1, 2), [('Vec3Ptr', 'Out', 'Element', (14, 1, 11)), ('Float', 'In', 'Index', (0, 1, 3)), ('Vec3Ptr', 'In', 'Variable', (0, 1, 11))]),
+ 465: ('List Rotation', 'Pasive', (2, 1, 2), [('RotPtr', 'Out', 'Element', (14, 1, 11)), ('Float', 'In', 'Index', (0, 1, 3)), ('RotPtr', 'In', 'Variable', (0, 1, 11))]),
+ 469: ('List Truth', 'Pasive', (2, 1, 2), [('BoolPtr', 'Out', 'Element', (14, 1, 11)), ('Float', 'In', 'Index', (0, 1, 3)), ('BoolPtr', 'In', 'Variable', (0, 1, 11))]),
+ 473: ('List Constraint', 'Pasive', (2, 1, 2), [('ConPtr', 'Out', 'Element', (14, 1, 11)), ('Float', 'In', 'Index', (0, 1, 3)), ('ConPtr', 'In', 'Variable', (0, 1, 11))]),
+ 477: ('World To Screen', 'Pasive', (2, 1, 2), [('Float', 'Out', 'Screen Y', (14, 1, 3)), ('Float', 'Out', 'Screen X', (14, 1, 11)), ('Vec3', 'In', 'World Pos', (0, 1, 11))]),
+ 481: ('Greater Than', 'Pasive', (2, 1, 2), [('Bool', 'Out', 'Num1 > Num2', (14, 1, 11)), ('Float', 'In', 'Num2', (0, 1, 3)), ('Float', 'In', 'Num1', (0, 1, 11))]),
+ 485: ('Random Seed', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Float', 'In', 'Seed', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 489: ('Get Size', 'Pasive', (2, 1, 2), [('Vec3', 'Out', 'Max', (14, 1, 3)), ('Vec3', 'Out', 'Min', (14, 1, 11)), ('Obj', 'In', 'Object', (0, 1, 11))]),
+ 556: ('Increase Number', 'Active', (2, 1, 1), [('Void', 'Out', 'After', (3, 1, 0)), ('Float', 'In', 'Variable', (0, 1, 3)), ('Void', 'In', 'Before', (3, 1, 6))]),
+ 558: ('Decrease Number', 'Active', (2, 1, 1), [('Void', 'Out', 'After', (3, 1, 0)), ('Float', 'In', 'Variable', (0, 1, 3)), ('Void', 'In', 'Before', (3, 1, 6))]),
+ 560: ('Loop', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Float', 'Out', 'Counter', (14, 1, 3)), ('Void', 'Out', 'Do', (14, 1, 11)), ('Float', 'In', 'Stop', (0, 1, 3)), ('Float', 'In', 'Start', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 564: ('Current Frame', 'Value', (2, 1, 1), [('Float', 'Out', 'Counter', (14, 1, 3))]),
+ 566: ('Late Update', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Void', 'Out', 'After Physics', (14, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 570: ('Dot Product', 'Pasive', (2, 1, 2), [('Float', 'Out', 'Dot Product', (14, 1, 11)), ('Vec3', 'In', 'Vector', (0, 1, 3)), ('Vec3', 'In', 'Vector', (0, 1, 11))]),
+ 574: ('Cross Product', 'Pasive', (2, 1, 2), [('Vec3', 'Out', 'Cross Product', (14, 1, 11)), ('Vec3', 'In', 'Vector', (0, 1, 3)), ('Vec3', 'In', 'Vector', (0, 1, 11))]),
+ 578: ('Normalize', 'Pasive', (2, 1, 1), [('Vec3', 'Out', 'Normalized', (14, 1, 3)), ('Vec3', 'In', 'Vector', (0, 1, 3))]),
+ 580: ('Logarithm', 'Pasive', (2, 1, 2), [('Float', 'Out', 'Logarithm', (14, 1, 11)), ('Float', 'In', 'Base', (0, 1, 3)), ('Float', 'In', 'Number', (0, 1, 11))]),
+ 584: ('Menu Item', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Obj', 'In', 'Picture', (0, 1, 3)), ('FloatPtr', 'In', 'Variable', (0, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 588: ('Button', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Void', 'Out', 'Button', (14, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+ 592: ('Joystick', 'Active', (2, 1, 2), [('Void', 'Out', 'After', (3, 1, 0)), ('Vec3', 'Out', 'Joy Dir', (14, 1, 11)), ('Void', 'In', 'Before', (3, 1, 14))]),
+}
diff --git a/games/numdrive/tools/caps.txt b/games/numdrive/tools/caps.txt
new file mode 100644
index 00000000..ebd3c1d8
--- /dev/null
+++ b/games/numdrive/tools/caps.txt
@@ -0,0 +1,200 @@
+0 106 5 4
+1 108 5 4
+2 124 32 32
+3 117 5 4
+4 98 5 4
+5 94 6 4
+6 174 52 6
+7 107 5 4
+8 124 5 4
+9 99 8 7
+10 120 20 18
+11 105 5 4
+12 142 5 4
+13 129 5 4
+14 185 67 8
+15 166 83 203
+16 104 11 7
+17 102 5 4
+18 245 146 4
+19 94 6 4
+20 148 21 21
+21 194 23 22
+22 102 9 4
+23 184 37 37
+24 99 5 4
+25 157 23 23
+26 110 7 4
+27 156 19 19
+28 104 5 4
+29 227 5 4
+30 106 5 4
+31 118 18 18
+32 148 23 23
+33 131 5 4
+34 159 16 16
+35 117 55 5
+36 108 5 4
+37 123 14 14
+38 138 5 4
+39 99 7 6
+40 77 7 6
+41 162 42 4
+42 101 6 5
+43 125 5 4
+44 95 5 4
+45 135 9 8
+46 124 18 18
+47 98 5 4
+48 110 8 6
+49 94 6 4
+50 60 3 2
+51 96 6 5
+52 95 6 6
+53 158 6 4
+54 158 48 4
+55 122 22 22
+56 108 5 4
+57 101 5 4
+58 202 5 4
+59 106 11 10
+60 93 5 4
+61 100 7 6
+62 135 6 5
+63 64 2 1
+64 104 13 13
+65 121 25 44
+66 110 6 4
+67 126 32 7
+68 63 2 1
+69 276 5 4
+70 98 8 8
+71 123 13 13
+72 119 3 2
+73 121 6 5
+74 98 7 6
+75 123 33 4
+76 130 24 8
+77 124 18 18
+78 93 5 4
+79 182 25 44
+80 117 10 8
+81 95 5 4
+82 73 3 2
+83 93 5 4
+84 96 6 5
+85 281 5 4
+86 93 5 4
+87 96 5 4
+88 123 24 24
+89 55 2 1
+90 94 5 4
+91 93 5 4
+92 95 5 4
+93 98 5 4
+94 83 4 3
+95 126 19 18
+96 65 6 4
+97 55 1 0
+98 105 5 4
+99 134 10 8
+100 97 7 5
+101 100 7 8
+102 94 6 4
+103 104 7 6
+104 122 5 4
+105 110 6 4
+106 96 6 4
+107 99 11 4
+108 54 2 1
+109 177 12 10
+110 96 5 4
+111 110 20 20
+112 93 5 4
+113 113 5 4
+114 95 6 5
+115 206 14 14
+116 97 6 4
+117 101 5 4
+118 95 6 4
+119 93 5 4
+120 96 5 4
+121 259 66 4
+122 69 1 0
+123 126 5 4
+124 114 8 6
+125 106 18 18
+126 218 10 8
+127 129 21 21
+128 94 6 4
+129 113 7 6
+130 136 10 8
+131 94 6 4
+132 101 13 12
+133 101 6 4
+134 78 17 17
+135 96 5 4
+136 111 5 4
+137 97 4 3
+138 99 5 4
+139 95 6 6
+140 239 7 4
+141 37 2 1
+142 97 8 4
+143 110 5 4
+144 240 18 14
+145 95 5 4
+146 118 6 6
+147 94 6 4
+148 197 6 4
+149 99 8 8
+150 102 9 8
+151 94 6 5
+152 112 5 4
+153 78 5 4
+154 152 13 11
+155 367 26 25
+156 163 72 72
+157 115 18 16
+158 96 6 5
+159 104 14 14
+160 198 6 5
+161 98 6 4
+162 527 5 4
+163 134 10 8
+164 123 25 6
+165 115 13 4
+166 93 5 4
+167 95 35 64
+168 157 5 4
+169 186 6 5
+170 103 6 5
+171 98 7 6
+172 95 6 5
+173 96 6 5
+174 105 10 4
+175 96 6 5
+176 139 31 33
+177 96 6 5
+178 96 7 5
+179 113 7 6
+180 111 20 21
+181 111 5 4
+182 96 5 4
+183 140 10 8
+184 93 5 4
+185 97 5 4
+186 94 6 4
+187 193 13 12
+188 95 6 5
+189 147 5 4
+190 98 5 4
+191 184 5 4
+192 160 10 8
+193 104 5 4
+194 95 6 4
+195 105 5 4
+196 224 5 4
+197 94 5 4
+198 407 10 8
+199 93 5 4
diff --git a/games/numdrive/tools/deflate.py b/games/numdrive/tools/deflate.py
new file mode 100644
index 00000000..8b190bfc
--- /dev/null
+++ b/games/numdrive/tools/deflate.py
@@ -0,0 +1,11 @@
+import zlib
+import zopfli.zopfli as _z
+def raw_deflate(b):
+ c=zlib.compressobj(9, zlib.DEFLATED, -15); return c.compress(b)+c.flush()
+def zop(b, it=30):
+ z=_z.compress(bytes(b), numiterations=it)
+ return z[2:-4]
+def check(b):
+ d=zop(b)
+ assert zlib.decompress(d, -15)==bytes(b)
+ return d
diff --git a/games/numdrive/tools/fancade.py b/games/numdrive/tools/fancade.py
new file mode 100644
index 00000000..40ad4214
--- /dev/null
+++ b/games/numdrive/tools/fancade.py
@@ -0,0 +1,173 @@
+"""Reader for Fancade game files (format version 31) and the stock prefab list."""
+import os
+import struct
+import zlib
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+SOURCE = os.path.join(HERE, 'source')
+GAME_FILE = os.environ.get('FANCADE_GAME', os.path.join(SOURCE, '5F084A0BCE06B710'))
+STOCK_FILE = os.path.join(SOURCE, 'stockPrefabs.fcpl')
+
+# Fancade colour palette, index 0 = empty voxel
+PALETTE = [(0, 0, 0), (29, 29, 40), (63, 63, 80), (101, 103, 121), (144, 147, 164), (191, 194, 205),
+ (255, 255, 255), (148, 83, 94), (192, 109, 128), (225, 153, 152), (253, 181, 168),
+ (255, 219, 197), (255, 243, 242), (192, 54, 80), (255, 74, 104), (255, 154, 154),
+ (201, 80, 64), (255, 112, 83), (255, 168, 129), (232, 168, 0), (255, 213, 0),
+ (255, 255, 122), (0, 136, 76), (66, 195, 79), (181, 255, 110), (0, 108, 218),
+ (0, 142, 255), (0, 193, 255), (104, 83, 162), (140, 111, 217), (176, 138, 255),
+ (235, 112, 171), (255, 149, 206), (255, 185, 232)]
+
+NORMAL, PHYSICS, SCRIPT, LEVEL = 0, 1, 2, 3
+
+
+class Reader:
+ def __init__(self, b):
+ self.b = b
+ self.p = 0
+
+ def u8(self):
+ v = self.b[self.p]
+ self.p += 1
+ return v
+
+ def u16(self):
+ v = struct.unpack_from('<H', self.b, self.p)[0]
+ self.p += 2
+ return v
+
+ def u32(self):
+ v = struct.unpack_from('<I', self.b, self.p)[0]
+ self.p += 4
+ return v
+
+ def i32(self):
+ v = struct.unpack_from('<i', self.b, self.p)[0]
+ self.p += 4
+ return v
+
+ def f32(self):
+ v = struct.unpack_from('<f', self.b, self.p)[0]
+ self.p += 4
+ return v
+
+ def string(self):
+ n = self.u8()
+ v = self.b[self.p:self.p + n].decode('utf-8', 'replace')
+ self.p += n
+ return v
+
+ def raw(self, n):
+ v = self.b[self.p:self.p + n]
+ self.p += n
+ return v
+
+
+class Prefab:
+ """One raw prefab segment as stored in the file."""
+
+ def voxel(self, x, y, z, f):
+ return self.vox[f * 512 + x + y * 8 + z * 64]
+
+ def solid(self, x, y, z):
+ i = x + y * 8 + z * 64
+ v = self.vox
+ return any(v[f * 512 + i] & 0x7f for f in range(6))
+
+ def block(self, x, y, z):
+ sx, sy, sz = self.size
+ return self.blocks[x + y * sx + z * sx * sy]
+
+
+def read_prefab(r):
+ h0 = r.u8()
+ h1 = r.u8()
+ p = Prefab()
+ has_conn = h0 & 1
+ has_set = (h0 >> 1) & 1
+ has_blocks = (h0 >> 2) & 1
+ has_vox = (h0 >> 3) & 1
+ p.in_group = (h0 >> 4) & 1
+ has_coll = (h0 >> 5) & 1
+ has_bg = h1 & 1
+ has_d2 = (h1 >> 1) & 1
+ has_d1 = (h1 >> 2) & 1
+ has_name = (h1 >> 3) & 1
+ has_type = (h1 >> 4) & 1
+ p.type = r.u8() if has_type else NORMAL
+ p.name = r.string() if has_name else 'New Block'
+ p.data1 = r.u8() if has_d1 else 0
+ p.data2 = r.u32() if has_d2 else 0
+ p.bg = r.u8() if has_bg else 27
+ p.collider = r.u8() if has_coll else 1
+ p.group = None
+ p.gpos = (0, 0, 0)
+ if p.in_group:
+ p.group = r.u16()
+ p.gpos = (r.u8(), r.u8(), r.u8())
+ p.vox = r.raw(3072) if has_vox else None
+ p.size = (0, 0, 0)
+ p.blocks = []
+ if has_blocks:
+ p.size = (r.u16(), r.u16(), r.u16())
+ n = p.size[0] * p.size[1] * p.size[2]
+ p.blocks_off = r.p
+ p.blocks = list(struct.unpack_from('<%dH' % n, r.b, r.p))
+ r.p += 2 * n
+ p.settings = []
+ if has_set:
+ for _ in range(r.u16()):
+ idx = r.u8()
+ t = r.u8()
+ pos = (r.u16(), r.u16(), r.u16())
+ if t == 1:
+ v = r.u8()
+ elif t == 2:
+ v = r.u16()
+ elif t == 3:
+ v = r.i32()
+ elif t == 4:
+ v = r.f32()
+ elif t == 5:
+ v = (r.f32(), r.f32(), r.f32())
+ else:
+ v = r.string()
+ p.settings.append((idx, t, pos, v))
+ p.conns = []
+ p.conns_off = None
+ if has_conn:
+ p.conns_off = r.p + 2
+ for _ in range(r.u16()):
+ a = [r.u16() for _ in range(12)]
+ p.conns.append((tuple(a[0:3]), tuple(a[3:6]), tuple(a[6:9]), tuple(a[9:12])))
+ return p
+
+
+class Game:
+ def __init__(self, game_file=GAME_FILE, stock_file=STOCK_FILE):
+ d = zlib.decompress(open(game_file, 'rb').read())
+ r = Reader(d)
+ self.version = r.u16()
+ self.title = r.string()
+ self.author = r.string()
+ self.description = r.string()
+ self.id_offset = r.u16()
+ self.prefabs = [read_prefab(r) for _ in range(r.u16())]
+ assert r.p == len(d)
+ s = Reader(open(stock_file, 'rb').read())
+ n = s.u32()
+ off = s.u16()
+ assert off == 0
+ self.stock = [read_prefab(s) for _ in range(n)]
+ assert len(self.stock) == self.id_offset
+ for i, p in enumerate(self.stock):
+ p.id = i
+ for i, p in enumerate(self.prefabs):
+ p.id = i + self.id_offset
+
+ def seg(self, id):
+ if id < self.id_offset:
+ return self.stock[id]
+ return self.prefabs[id - self.id_offset]
+
+ def levels(self):
+ return [p for p in self.prefabs if p.type == LEVEL]
diff --git a/games/numdrive/tools/font.py b/games/numdrive/tools/font.py
new file mode 100644
index 00000000..705b441a
--- /dev/null
+++ b/games/numdrive/tools/font.py
@@ -0,0 +1,125 @@
+"""Generate anti-aliased 2 bpp bitmap fonts (Baloo 2 ExtraBold, the typeface used by Fancade)
+and a few UI icons as src/font.c.
+
+usage: font.py path/to/baloo2.woff ../src/font.c"""
+import sys
+from PIL import Image, ImageDraw, ImageFont
+
+SS = 4 # supersampling factor
+
+FONTS = [
+ # name, pixel size, characters
+ ('font_s', 11, ''.join(chr(c) for c in range(32, 127))),
+ ('font_m', 14, ''.join(chr(c) for c in range(32, 127))),
+ ('font_l', 20, ' .0123456789:DGLMTadegilmnorstv'),
+]
+
+
+def quant(im):
+ """downsample an L image by SS and quantise to 2 bits"""
+ w, h = im.size
+ im = im.resize((w // SS, h // SS), Image.BOX)
+ w, h = im.size
+ b = im.tobytes()
+ return [[(b[y * w + x] * 3 + 127) // 255 for x in range(w)] for y in range(h)]
+
+
+def glyph_record(rows):
+ """trim to the ink box; returns (xoff, y0, w, h, packed bytes)"""
+ H = len(rows)
+ W = len(rows[0]) if H else 0
+ ys = [y for y in range(H) if any(rows[y])]
+ xs = [x for x in range(W) if any(rows[y][x] for y in range(H))]
+ if not ys:
+ return 0, 0, 0, 0, b''
+ x0, x1, y0, y1 = xs[0], xs[-1] + 1, ys[0], ys[-1] + 1
+ bits = []
+ for y in range(y0, y1):
+ bits += rows[y][x0:x1]
+ out = bytearray()
+ for i in range(0, len(bits), 4):
+ q = bits[i:i + 4] + [0] * (4 - len(bits[i:i + 4]))
+ out.append(q[0] | q[1] << 2 | q[2] << 4 | q[3] << 6)
+ return x0, y0, x1 - x0, y1 - y0, bytes(out)
+
+
+def build_font(path, size, chars):
+ f = ImageFont.truetype(path, size * SS)
+ asc, desc = f.getmetrics()
+ H = (asc + desc) // SS + 1
+ recs = []
+ for ch in chars:
+ adv = round(f.getlength(ch) / SS)
+ W = adv + 4
+ im = Image.new('L', (W * SS, H * SS), 0)
+ ImageDraw.Draw(im).text((SS, 0), ch, font=f, fill=255)
+ x0, y0, w, h, data = glyph_record(quant(im))
+ recs.append((ch, adv, x0 - 1, y0, w, h, data))
+ # vertical metrics: baseline and cap height for layout
+ cap = f.getbbox('H')
+ return dict(h=H, base=asc // SS, cap_top=cap[1] // SS, recs=recs)
+
+
+def icon(draw_fn, w, h):
+ im = Image.new('L', (w * SS, h * SS), 0)
+ draw_fn(ImageDraw.Draw(im), SS)
+ rows = quant(im)
+ return glyph_record(rows)
+
+
+def rr(d, box, r, fill=255, outline=None, width=0):
+ d.rounded_rectangle(box, r, fill=fill, outline=outline, width=width)
+
+
+ICONS = {
+ # pause: two rounded pills with dark outline (drawn as two layers: outline + fill)
+ 'ic_pause_o': (lambda d, s: (rr(d, (0, 0, 7 * s, 16 * s), 3.5 * s), rr(d, (7 * s, 0, 14 * s, 16 * s), 3.5 * s)), 15, 17),
+ 'ic_pause_f': (lambda d, s: (rr(d, (1.2 * s, 1.2 * s, 5.8 * s, 14.8 * s), 2.3 * s),
+ rr(d, (8.2 * s, 1.2 * s, 12.8 * s, 14.8 * s), 2.3 * s)), 15, 17),
+ 'ic_play': (lambda d, s: d.polygon([(1 * s, 0), (13 * s, 7 * s), (1 * s, 14 * s)], fill=255), 14, 15),
+ 'ic_restart': (lambda d, s: (d.arc((1 * s, 1 * s, 13 * s, 13 * s), 300, 250, fill=255, width=int(2.4 * s)),
+ d.polygon([(5 * s, -0.5 * s), (10.5 * s, 2.2 * s), (5 * s, 6.0 * s)], fill=255)), 14, 14),
+ 'ic_back': (lambda d, s: d.line([(8 * s, 1 * s), (2 * s, 8 * s), (8 * s, 15 * s)], fill=255, width=int(2.6 * s), joint='curve'), 10, 17),
+ 'ic_next': (lambda d, s: d.line([(2 * s, 1 * s), (8 * s, 8 * s), (2 * s, 15 * s)], fill=255, width=int(2.6 * s), joint='curve'), 10, 17),
+ 'ic_left': (lambda d, s: d.polygon([(0.5 * s, 3 * s), (5.5 * s, 0), (5.5 * s, 6 * s)], fill=255), 6, 6),
+ 'ic_right': (lambda d, s: d.polygon([(5.5 * s, 3 * s), (0.5 * s, 0), (0.5 * s, 6 * s)], fill=255), 6, 6),
+ 'ic_lock': (lambda d, s: (d.arc((2 * s, 0, 8 * s, 8 * s), 180, 360, fill=255, width=int(1.6 * s)),
+ rr(d, (0.5 * s, 4 * s, 9.5 * s, 11 * s), 1.5 * s)), 10, 11),
+}
+
+
+def c_bytes(b):
+ return ','.join(str(x) for x in b)
+
+
+def main():
+ src, out = sys.argv[1], sys.argv[2]
+ lines = ['/* generated by tools/font.py from Baloo 2 ExtraBold (SIL Open Font License) */',
+ '#include "font.h"', '']
+ for name, size, chars in FONTS:
+ F = build_font(src, size, chars)
+ data = bytearray()
+ glyphs = []
+ for ch, adv, xo, y0, w, h, bits in F['recs']:
+ glyphs.append((ord(ch), adv, xo, y0, w, h, len(data)))
+ data += bits
+ lines.append('static const uint8_t %s_data[] = {%s};' % (name, c_bytes(data)))
+ lines.append('static const Glyph %s_glyphs[] = {' % name)
+ for c, adv, xo, y0, w, h, off in glyphs:
+ lines.append(' {%d, %d, %d, %d, %d, %d, %d},' % (c, adv, xo, y0, w, h, off))
+ lines.append('};')
+ lines.append('const Font %s = {%d, %d, %d, %d, %s_glyphs, %s_data};' % (
+ name, F['h'], F['base'], F['cap_top'], len(glyphs), name, name))
+ lines.append('')
+ print(name, 'glyph bytes', len(data), 'glyphs', len(glyphs), file=sys.stderr)
+ for name, (fn, w, h) in ICONS.items():
+ xo, y0, gw, gh, bits = icon(fn, w, h)
+ lines.append('static const uint8_t %s_data[] = {%s};' % (name, c_bytes(bits)))
+ lines.append('const Icon %s = {%d, %d, %d, %d, %d, %d, %s_data};' % (name, w, h, xo, y0, gw, gh, name))
+ open(out, 'w').write('\n'.join(lines) + '\n')
+ hdr = ['extern const Font %s;' % n for n, _, _ in FONTS] + ['extern const Icon %s;' % n for n in ICONS]
+ print('\n'.join(hdr))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/games/numdrive/tools/model.py b/games/numdrive/tools/model.py
new file mode 100644
index 00000000..2e9f3d9c
--- /dev/null
+++ b/games/numdrive/tools/model.py
@@ -0,0 +1,259 @@
+"""Voxel block analysis and object formation (Fancade rules)."""
+from fancade import NORMAL, PHYSICS, SCRIPT, LEVEL
+
+# voxel face order in Fancade files: +X -X +Y -Y +Z -Z
+DIRS = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]
+
+
+def vidx(x, y, z):
+ return x + y * 8 + z * 64
+
+
+class BlockInfo:
+ """Derived data for one voxel block (segment)."""
+
+ def __init__(self, seg):
+ self.seg = seg
+ v = seg.vox
+ self.solid = [any(v[f * 512 + i] & 0x7f for f in range(6)) for i in range(512)]
+ self._components()
+ self._full_faces()
+
+ def color(self, x, y, z, f):
+ return self.seg.vox[f * 512 + vidx(x, y, z)] & 0x7f
+
+ def sticky(self, x, y, z, f):
+ return not (self.seg.vox[f * 512 + vidx(x, y, z)] & 0x80)
+
+ def _components(self):
+ parent = list(range(512))
+
+ def find(a):
+ while parent[a] != a:
+ parent[a] = parent[parent[a]]
+ a = parent[a]
+ return a
+ for z in range(8):
+ for y in range(8):
+ for x in range(8):
+ i = vidx(x, y, z)
+ if not self.solid[i]:
+ continue
+ for axis in range(3):
+ q = [x, y, z]
+ q[axis] += 1
+ if q[axis] > 7:
+ continue
+ j = vidx(*q)
+ if self.solid[j] and self.sticky(x, y, z, axis * 2) and self.sticky(q[0], q[1], q[2], axis * 2 + 1):
+ parent[find(i)] = find(j)
+ roots = {}
+ self.comp = [-1] * 512
+ for i in range(512):
+ if self.solid[i]:
+ r = find(i)
+ if r not in roots:
+ roots[r] = len(roots)
+ self.comp[i] = roots[r]
+ self.ncomp = len(roots)
+ self.comp_count = [0] * self.ncomp
+ self.comp_sum = [[0.0, 0.0, 0.0] for _ in range(self.ncomp)]
+ self.comp_min = [[8, 8, 8] for _ in range(self.ncomp)]
+ self.comp_max = [[-1, -1, -1] for _ in range(self.ncomp)]
+ for i in range(512):
+ c = self.comp[i]
+ if c < 0:
+ continue
+ p = (i % 8, (i // 8) % 8, i // 64)
+ self.comp_count[c] += 1
+ for k in range(3):
+ self.comp_sum[c][k] += p[k] + 0.5
+ self.comp_min[c][k] = min(self.comp_min[c][k], p[k])
+ self.comp_max[c][k] = max(self.comp_max[c][k], p[k])
+
+ def _full_faces(self):
+ self.full = []
+ for f, d in enumerate(DIRS):
+ axis = [k for k in range(3) if d[k]][0]
+ layer = 7 if d[axis] > 0 else 0
+ ok = True
+ for u in range(8):
+ for w in range(8):
+ p = [0, 0, 0]
+ p[axis] = layer
+ a, b = [k for k in range(3) if k != axis]
+ p[a] = u
+ p[b] = w
+ if not self.solid[vidx(*p)]:
+ ok = False
+ self.full.append(ok)
+
+ def boxes(self):
+ """Greedy merge solid voxels of each component into boxes: list of (comp, x0,y0,z0,x1,y1,z1) (exclusive max)."""
+ used = [False] * 512
+ out = []
+ for z in range(8):
+ for y in range(8):
+ for x in range(8):
+ i = vidx(x, y, z)
+ if not self.solid[i] or used[i]:
+ continue
+ c = self.comp[i]
+
+ def ok(xx, yy, zz):
+ j = vidx(xx, yy, zz)
+ return self.solid[j] and not used[j] and self.comp[j] == c
+ x1 = x + 1
+ while x1 < 8 and ok(x1, y, z):
+ x1 += 1
+ y1 = y + 1
+ while y1 < 8 and all(ok(xx, y1, z) for xx in range(x, x1)):
+ y1 += 1
+ z1 = z + 1
+ while z1 < 8 and all(ok(xx, yy, z1) for xx in range(x, x1) for yy in range(y, y1)):
+ z1 += 1
+ for zz in range(z, z1):
+ for yy in range(y, y1):
+ for xx in range(x, x1):
+ used[vidx(xx, yy, zz)] = True
+ out.append((c, x, y, z, x1, y1, z1))
+ return out
+
+ def quads(self, f):
+ """Greedy mesh exposed faces for direction f within the block.
+ Returns list of (layer, u, v, du, dv, color, comp, boundary)."""
+ d = DIRS[f]
+ axis = [k for k in range(3) if d[k]][0]
+ ua, va = [k for k in range(3) if k != axis]
+ out = []
+ for layer in range(8):
+ grid = {}
+ for u in range(8):
+ for w in range(8):
+ p = [0, 0, 0]
+ p[axis] = layer
+ p[ua] = u
+ p[va] = w
+ i = vidx(*p)
+ if not self.solid[i]:
+ continue
+ col = self.color(p[0], p[1], p[2], f)
+ if not col:
+ continue
+ q = list(p)
+ q[axis] += d[axis]
+ if 0 <= q[axis] < 8 and self.solid[vidx(*q)]:
+ continue
+ grid[(u, w)] = (col, self.comp[i])
+ used = set()
+ for w in range(8):
+ for u in range(8):
+ if (u, w) not in grid or (u, w) in used:
+ continue
+ key = grid[(u, w)]
+ du = 1
+ while (u + du, w) in grid and grid[(u + du, w)] == key and (u + du, w) not in used:
+ du += 1
+ dv = 1
+ while all((u + k, w + dv) in grid and grid[(u + k, w + dv)] == key and (u + k, w + dv) not in used for k in range(du)):
+ dv += 1
+ for a in range(du):
+ for b in range(dv):
+ used.add((u + a, w + b))
+ boundary = (layer == 7 and d[axis] > 0) or (layer == 0 and d[axis] < 0)
+ out.append((layer, u, w, du, dv, key[0], key[1], boundary))
+ return out
+
+
+class BlockLib:
+ def __init__(self, game):
+ self.game = game
+ self.info = {}
+
+ def get(self, id):
+ if id not in self.info:
+ self.info[id] = BlockInfo(self.game.seg(id))
+ return self.info[id]
+
+
+def grid_cells(game, pf):
+ """Non-script voxel cells in a prefab grid: {cell: id}."""
+ sx, sy, sz = pf.size
+ out = {}
+ for z in range(sz):
+ for y in range(sy):
+ for x in range(sx):
+ id = pf.blocks[x + y * sx + z * sx * sy]
+ if not id:
+ continue
+ s = game.seg(id)
+ if s.type == SCRIPT or not s.vox:
+ continue
+ out[(x, y, z)] = id
+ return out
+
+
+class Obj:
+ def __init__(self):
+ self.parts = [] # (cell, id, comp)
+
+ def is_physics(self, game):
+ return any(game.seg(id).type == PHYSICS for (_, id, _) in self.parts)
+
+
+def build_objects(game, lib, pf):
+ """Group voxel components of a grid into Fancade objects.
+ Returns (objects, part_obj) where part_obj maps (cell, comp) -> object index."""
+ cells = grid_cells(game, pf)
+ nodes = []
+ for c, id in cells.items():
+ for k in range(lib.get(id).ncomp):
+ nodes.append((c, k))
+ parent = {n: n for n in nodes}
+
+ def find(a):
+ while parent[a] != a:
+ parent[a] = parent[parent[a]]
+ a = parent[a]
+ return a
+ for c, id in cells.items():
+ A = lib.get(id)
+ for axis in range(3):
+ n = list(c)
+ n[axis] += 1
+ n = tuple(n)
+ if n not in cells:
+ continue
+ B = lib.get(cells[n])
+ ua, va = [k for k in range(3) if k != axis]
+ for u in range(8):
+ for w in range(8):
+ pa = [0, 0, 0]
+ pa[axis] = 7
+ pa[ua] = u
+ pa[va] = w
+ pb = list(pa)
+ pb[axis] = 0
+ ia = vidx(*pa)
+ ib = vidx(*pb)
+ if A.solid[ia] and B.solid[ib] and A.sticky(pa[0], pa[1], pa[2], axis * 2) and B.sticky(pb[0], pb[1], pb[2], axis * 2 + 1):
+ ra = find((c, A.comp[ia]))
+ rb = find((n, B.comp[ib]))
+ if ra != rb:
+ parent[rb] = ra
+ groups = {}
+ for nd in nodes:
+ groups.setdefault(find(nd), []).append(nd)
+ # deterministic order: by first node in (z desc, y desc, x asc) parse order
+ def order_key(nd):
+ (x, y, z), k = nd
+ return (-z, -y, x, k)
+ objs = []
+ part_obj = {}
+ for root, members in sorted(groups.items(), key=lambda kv: min(order_key(m) for m in kv[1])):
+ o = Obj()
+ for (c, k) in sorted(members, key=lambda m: (m[0][0], m[0][1], m[0][2], m[1])):
+ o.parts.append((c, cells[c], k))
+ part_obj[(c, k)] = len(objs)
+ objs.append(o)
+ return objs, part_obj
diff --git a/games/numdrive/tools/ops.py b/games/numdrive/tools/ops.py
new file mode 100644
index 00000000..e9d9534f
--- /dev/null
+++ b/games/numdrive/tools/ops.py
@@ -0,0 +1,84 @@
+"""Script op table shared by the compiler and the C VM.
+
+Inputs and outputs are ordered top to bottom (highest terminal z first), which
+matches the operand order shown in the Fancade editor (Num1 above Num2, ...).
+"""
+from blockdefs import DEFS
+
+# stock ids that compile to VM ops (everything else is ignored or handled specially)
+SUPPORTED = [
+ 36, 38, 42, 449, 451, # literals
+ 46, 48, 50, 52, 54, 56, # get variable
+ 428, 430, 432, 434, 436, 438, # set variable
+ 58, 62, 66, 70, 74, 78, # set via pointer
+ 82, 86, 461, 465, 469, 473, # list element
+ 556, 558, # increase / decrease
+ 90, 92, 96, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144, 146,
+ 150, 156, 162, 168, 172, 176, 180, 184, 186, 188, 190, 194, 200, 204, 208,
+ 413, 417, 421, 440, 442, 453, 455, 457, 481, 570, 574, 578, 580,
+ 216, 220, 224, 477, 564, # screen / sensors values
+ 228, 278, 288, 489, # raycast, get position, get velocity, get size
+ 234, 238, 242, 248, 566, 409, 588, 592, 401, 560, # control / sensors
+ 252, 256, 260, 268, 274, # game
+ 282, 292, 298, 306, 310, 316, 320, 324, 328, 332, 336, # objects / physics
+ 340, 346, 352, 358, 364, 370, 376, # constraints
+ 264, 391, 397, 485, # sound, random seed
+ 16, 20, 24, 28, 32, # inspect (no-op)
+]
+
+EXTRA_OPS = ['CUSTOM'] # child environment (custom script / scripted object)
+
+
+def terminal_lists(id):
+ name, kind, size, terms = DEFS[id]
+ ins = [t for t in terms if t and t[1] == 'In' and t[0] != 'Void']
+ outs = [t for t in terms if t and t[1] == 'Out' and t[0] != 'Void']
+ execs = [t for t in terms if t and t[1] == 'Out' and t[0] == 'Void' and t[2] != 'After']
+ has_before = any(t and t[1] == 'In' and t[0] == 'Void' for t in terms)
+ key = lambda t: -t[3][2]
+ return name, kind, sorted(ins, key=key), sorted(outs, key=key), sorted(execs, key=key), has_before
+
+
+OPS = {}
+for i, id in enumerate(SUPPORTED):
+ name, kind, ins, outs, execs, has_before = terminal_lists(id)
+ OPS[id] = dict(index=i, name=name, kind=kind, ins=ins, outs=outs, execs=execs, active=kind == 'Active')
+
+OP_CUSTOM = len(SUPPORTED)
+
+
+def c_name(id):
+ n = OPS[id]['name'].upper().replace(' ', '_').replace('?', '')
+ if id in (46, 48, 50, 52, 54, 56):
+ n = 'GET_VAR_' + ['NUM', 'VEC', 'ROT', 'TRU', 'OBJ', 'CON'][(id - 46) // 2]
+ if id in (428, 430, 432, 434, 436, 438):
+ n = 'SET_VAR_' + ['NUM', 'VEC', 'ROT', 'TRU', 'OBJ', 'CON'][(id - 428) // 2]
+ if id in (16, 20, 24, 28, 32):
+ n = 'INSPECT_%d' % id
+ if id in (58, 62, 66, 70, 74, 78):
+ n = 'SET_PTR_' + ['NUM', 'VEC', 'ROT', 'TRU', 'OBJ', 'CON'][(id - 58) // 4]
+ if id in (82, 86, 461, 465, 469, 473):
+ n = 'LIST_' + {82: 'NUM', 86: 'OBJ', 461: 'VEC', 465: 'ROT', 469: 'TRU', 473: 'CON'}[id]
+ return 'OP_' + n
+
+
+def c_header():
+ lines = ['/* Generated by tools/ops.py. Do not edit. */', '#ifndef OPS_H', '#define OPS_H', '', 'enum {']
+ for id in SUPPORTED:
+ o = OPS[id]
+ lines.append(' %s, /* %d: ins %s outs %s execs %s */' % (
+ c_name(id), id, [t[2] for t in o['ins']], [t[2] for t in o['outs']], [t[2] for t in o['execs']]))
+ lines.append(' OP_CUSTOM,')
+ lines.append(' OP_COUNT')
+ lines.append('};')
+ lines.append('')
+ lines.append('/* per op: number of value inputs, value outputs, extra exec outputs, flags (1 = active) */')
+ lines.append('static const unsigned char op_shape[OP_COUNT][4] = {')
+ for id in SUPPORTED:
+ o = OPS[id]
+ lines.append(' {%d, %d, %d, %d}, /* %s */' % (len(o['ins']), len(o['outs']), len(o['execs']), 1 if o['active'] else 0, o['name']))
+ lines.append(' {0, 0, 0, 1}, /* custom */')
+ lines.append('};')
+ lines.append('')
+ lines.append('#endif')
+ return '\n'.join(lines) + '\n'
diff --git a/games/numdrive/tools/pack.py b/games/numdrive/tools/pack.py
new file mode 100644
index 00000000..ca27c79e
--- /dev/null
+++ b/games/numdrive/tools/pack.py
@@ -0,0 +1,464 @@
+import os
+"""Build the NumDrive data pack from the original Drive Mad game file.
+
+Usage: python3 pack.py [--fast] [out.c]
+"""
+import struct
+import sys
+import zlib
+
+import ops
+from deflate import raw_deflate, zop
+from fancade import Game, LEVEL, PHYSICS, SCRIPT
+
+# levels left out: parts turning out of the 2D plane (115, 144, 158, 173), too heavy to draw (128), or no
+# win found by the host win search
+SKIP = {115, 144, 158, 173, 128,
+ 16, 19, 25, 35, 42, 45, 48, 53, 56, 58, 59, 64, 66, 67, 69, 81, 85, 93, 97, 103, 104, 112, 122, 127,
+ 132, 137, 141, 146, 150, 154, 155, 169, 172, 180, 183, 190, 196, 198}
+from model import BlockLib, build_objects, grid_cells, DIRS, vidx
+from scriptc import Compiler, custom_terminals
+
+MAGIC = b'NDMP'
+REF_NONE = 0xFFFF
+
+
+class W:
+ def __init__(self):
+ self.b = bytearray()
+
+ def u8(self, v):
+ self.b += struct.pack('<B', v)
+
+ def u16(self, v):
+ self.b += struct.pack('<H', v)
+
+ def i16(self, v):
+ self.b += struct.pack('<h', v)
+
+ def u32(self, v):
+ self.b += struct.pack('<I', v)
+
+ def f32(self, v):
+ self.b += struct.pack('<f', v)
+
+ def s(self, text):
+ e = text.encode('utf-8')
+ self.u8(len(e))
+ self.b += e
+
+
+class Packer:
+ def __init__(self, fast=False):
+ self.fast = fast
+ self.g = Game()
+ self.lib = BlockLib(self.g)
+ self.comp = Compiler(self.g, self.lib, build_objects)
+ self.block_index = {} # segment id -> library index
+ self.records = [] # raw record bytes
+ self.prog_record = {} # prefab id -> record index
+ self.children = {} # program record -> child program records
+ self.node_tables = {} # program record -> (header length, node offsets, slots, slot count)
+
+ # ---------------------------------------------------------------- blocks
+ def blk(self, id):
+ if id not in self.block_index:
+ self.block_index[id] = len(self.block_index)
+ assert len(self.block_index) <= 255
+ return self.block_index[id]
+
+ GROUP = 16
+
+ def block_library(self):
+ ids = sorted(self.block_index, key=lambda i: self.block_index[i])
+ groups = []
+ for g0 in range(0, len(ids), self.GROUP):
+ w = W()
+ for id in ids[g0:g0 + self.GROUP]:
+ self.write_block(w, id)
+ groups.append(bytes(w.b))
+ return groups
+
+ def write_block(self, w, id):
+ if True:
+ info = self.lib.get(id)
+ s = self.g.seg(id)
+ # bit 3: stock block (its position counts its whole cell)
+ flags = min(s.collider, 2) | ((1 if s.type == PHYSICS else 0) << 2) | ((1 if id < self.g.id_offset else 0) << 3)
+ w.u8(flags)
+ w.u8(info.ncomp)
+ # per component voxel bounds (voxel units)
+ st = [[8, 8, 8, 0, 0, 0] for _ in range(info.ncomp)]
+ for i in range(512):
+ if not info.solid[i]:
+ continue
+ x, y, z = i & 7, (i >> 3) & 7, i >> 6
+ c = max(info.comp[i], 0) & 15 if info.ncomp > 1 else 0
+ b = st[c]
+ b[0] = min(b[0], x); b[1] = min(b[1], y); b[2] = min(b[2], z)
+ b[3] = max(b[3], x); b[4] = max(b[4], y); b[5] = max(b[5], z)
+ for bb in st:
+ w.b += bytes(bb)
+ boxes = info.boxes()
+ assert len(boxes) < 256
+ w.u8(len(boxes))
+ for (c, x0, y0, z0, x1, y1, z1) in boxes:
+ v = c | x0 << 3 | y0 << 6 | z0 << 9 | (x1 - 1) << 12 | (y1 - 1) << 15 | (z1 - 1) << 18
+ w.b += struct.pack('<I', v)[:3]
+ full = 0
+ for f in range(6):
+ if info.full[f]:
+ full |= 1 << f
+ w.u8(full)
+ for f in range(6):
+ q = info.quads(f)
+ assert len(q) < 256
+ w.u8(len(q))
+ for (layer, u, v_, du, dv, col, c, boundary) in q:
+ x = layer | u << 3 | v_ << 6 | (du - 1) << 9 | (dv - 1) << 12 | col << 15 | c << 21
+ w.b += struct.pack('<I', x)[:3]
+
+ # -------------------------------------------------------------- programs
+ def write_grid(self, w, pf):
+ """Sparse grid of object cells (non-script voxel blocks), RLE in z, y, x order.
+ The runtime rebuilds objects with the same glue rules and ordering as model.build_objects."""
+ cells = grid_cells(self.g, pf)
+ if not cells:
+ w.u16(0xFFFF)
+ return
+ xs = [c[0] for c in cells]; ys = [c[1] for c in cells]; zs = [c[2] for c in cells]
+ x0, x1, y0, y1, z0, z1 = min(xs), max(xs), min(ys), max(ys), min(zs), max(zs)
+ w.u16(x0); w.u16(y0); w.u16(z0)
+ w.u16(x1 - x0 + 1); w.u16(y1 - y0 + 1); w.u16(z1 - z0 + 1)
+ seq = []
+ for z in range(z0, z1 + 1):
+ for y in range(y0, y1 + 1):
+ for x in range(x0, x1 + 1):
+ id = cells.get((x, y, z))
+ seq.append(0 if id is None else self.blk(id) + 1)
+ i = 0
+ n = len(seq)
+ while i < n:
+ j = i
+ while j < n and seq[j] == 0 and j - i < 255:
+ j += 1
+ w.u8(j - i)
+ i = j
+ k = i
+ while k < n and seq[k] != 0 and k - i < 255:
+ k += 1
+ w.u8(k - i)
+ for t in range(i, k):
+ w.u8(seq[t] - 1)
+ i = k
+
+ def ref(self, r, selfmap):
+ if r is None:
+ return REF_NONE
+ kind = r[0]
+ if kind == 'node':
+ assert r[1] < 2048 and r[2] < 4
+ return r[1] | r[2] << 11
+ if kind == 'in':
+ return 1 << 13 | r[1]
+ if kind == 'self':
+ if r[1] not in selfmap:
+ selfmap[r[1]] = len(selfmap)
+ return 2 << 13 | selfmap[r[1]]
+ if kind == 'obj':
+ if r[1] is None:
+ return REF_NONE
+ return 3 << 13 | r[1]
+ raise ValueError(r)
+
+ @staticmethod
+ def varint(w, v):
+ while v >= 0x80:
+ w.u8((v & 0x7F) | 0x80)
+ v >>= 7
+ w.u8(v)
+
+ def write_objects(self, w, prog):
+ """Objects of a grid, already grouped (same glue rules and order as the original).
+ u16 count, varint part count per object, then all part blocks (u8), then all part key deltas
+ (varint, key = x<<20 | y<<13 | z<<3 | component, parts of an object sorted by key)."""
+ w.u16(len(prog.objects))
+ blocks, deltas = W(), W()
+ for o in prog.objects:
+ parts = sorted((c[0] << 20 | c[1] << 13 | c[2] << 3 | k, self.blk(id)) for (c, id, k) in o.parts)
+ self.varint(w, len(parts))
+ prev = 0
+ for key, b in parts:
+ blocks.u8(b)
+ self.varint(deltas, key - prev)
+ prev = key
+ w.b += blocks.b + deltas.b
+
+ def custom_objects(self, body, prog, n):
+ """object indices (in the parent grid) of a custom block's anchor and self references"""
+ child = self.comp.program(n.custom_prog)
+ bx, by, bz = n.pos
+ a = self.comp.object_at(prog, (bx, by, bz), (4, 4, 4))
+ body.u16(0xFFFF if a is None else a)
+ body.u8(len(child.selfmap))
+ for v, i in sorted(child.selfmap.items(), key=lambda kv: kv[1]):
+ cell = (bx + v[0] // 8, by + v[1] // 8, bz + v[2] // 8)
+ o = self.comp.object_at(prog, cell, (v[0] % 8, v[1] % 8, v[2] % 8))
+ body.u16(0xFFFF if o is None else o)
+
+ def program_record(self, pid):
+ if pid in self.prog_record:
+ return self.prog_record[pid]
+ prog = self.comp.program(pid)
+ # make sure children get records first
+ for n in prog.nodes:
+ if n.op == ops.OP_CUSTOM:
+ self.program_record(n.custom_prog)
+ idx = len(self.records)
+ self.records.append(None)
+ self.prog_record[pid] = idx
+ self.children[idx] = [self.prog_record[n.custom_prog] for n in prog.nodes if n.op == ops.OP_CUSTOM]
+ w = W()
+ selfmap = {}
+ body = W()
+ offs, slots, nslots = [], [], 0
+ for n in prog.nodes:
+ offs.append(len(body.b))
+ if n.op != ops.OP_CUSTOM:
+ o = ops.OPS[ops.SUPPORTED[n.op]]
+ if o['active'] and o['outs']:
+ slots.append(nslots)
+ nslots += len(o['outs'])
+ else:
+ slots.append(0xFFFF)
+ else:
+ slots.append(0xFFFF)
+ body.u8(n.op)
+ if n.op == ops.OP_CUSTOM:
+ body.u16(self.prog_record[n.custom_prog])
+ body.u16(n.pos[0]); body.u16(n.pos[1]); body.u16(n.pos[2])
+ body.u8(len(n.ins))
+ for r in n.ins:
+ body.u16(self.ref(r, selfmap))
+ self.custom_objects(body, prog, n)
+ continue
+ for r in n.ins:
+ body.u16(self.ref(r, selfmap))
+ # several wires from one output run in block order (node indices follow it)
+ for tg in n.execs:
+ body.u8(len(tg))
+ for t in sorted(tg):
+ body.u16(t)
+ body.u8(len(n.after))
+ for t in sorted(n.after):
+ body.u16(t)
+ d = n.data
+ if d:
+ if d[0] == 'num':
+ body.f32(d[1])
+ elif d[0] in ('vec', 'rot'):
+ for x in d[1]:
+ body.f32(x)
+ elif d[0] == 'var':
+ body.u16(d[2] | (0x8000 if d[1] else 0))
+ elif d[0] == 'byte':
+ body.u8(d[1])
+ elif n.block_id in (36,):
+ body.f32(0.0)
+ elif n.block_id in (38, 42):
+ body.f32(0.0); body.f32(0.0); body.f32(0.0)
+ elif n.block_id in (46, 48, 50, 52, 54, 56, 428, 430, 432, 434, 436, 438):
+ raise ValueError('variable without data')
+ elif n.block_id in (252, 256, 588, 268, 592, 264):
+ body.u8(0)
+ outs = W()
+ omap = dict(prog.outputs)
+ for k in range(len(prog.outputs_decl)):
+ outs.u16(self.ref(omap.get(k), selfmap))
+ is_level = prog.pf.type == LEVEL
+ # bits 1-4: height of the script block's model centre in 1/16 (its Get Position without object)
+ # (custom blocks with scripts use the standard script block model: 3/16)
+ yc = 3
+ if prog.pf.type == SCRIPT and prog.pf.vox is not None:
+ ys = [y for z in range(8) for y in range(8) for x in range(8) if prog.pf.solid(x, y, z)]
+ if ys:
+ yc = min(ys) + max(ys) + 1
+ w.u8((1 if is_level else 0) | yc << 1)
+ w.u16(len(prog.nodes))
+ w.u16(len(prog.entries))
+ for e in prog.entries:
+ w.u16(e)
+ locs = sorted(prog.locals.items(), key=lambda kv: kv[1])
+ w.u16(len(locs))
+ for (name, t), i in locs:
+ w.u8(t)
+ w.u8(len(prog.inputs))
+ w.u8(len(prog.outputs_decl))
+ w.b += outs.b
+ w.u8(len(selfmap))
+ for v, i in sorted(selfmap.items(), key=lambda kv: kv[1]):
+ w.u8(v[0]); w.u8(v[1]); w.u8(v[2])
+ if not is_level:
+ self.write_objects(w, prog)
+ else:
+ w.u16(0)
+ self.node_tables[idx] = (len(w.b), offs, slots, nslots)
+ w.b += body.b
+ prog.selfmap = selfmap
+ self.records[idx] = bytes(w.b)
+ return idx
+
+ # ----------------------------------------------------------------- levels
+ def level_record(self, L):
+ g = self.g
+ lv = g.prefabs[L]
+ prog = self.comp.program(lv.id)
+ self.program_record(lv.id)
+ w = W()
+ w.s(lv.name)
+ w.u16(lv.size[0]); w.u16(lv.size[1]); w.u16(lv.size[2])
+ w.u8(lv.bg)
+ w.u16(self.prog_record[lv.id])
+ # capacities measured by the host harness (objects, physics bodies, joints)
+ oc, bc, jc = self.caps.get(L, (600, 64, 64))
+ w.u16(oc); w.u16(bc); w.u16(jc)
+ self.write_objects(w, prog)
+ return bytes(w.b)
+
+ def reachable(self, rec):
+ """program records reachable from a program record (itself and custom block children)"""
+ out, todo = set(), [rec]
+ while todo:
+ r = todo.pop()
+ if r in out:
+ continue
+ out.add(r)
+ todo += self.children.get(r, [])
+ return out
+
+ def load_caps(self):
+ """caps.txt: 'level obj bodies joints' peak counts from host/caps.sh; add safety margins"""
+ self.caps = {}
+ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'caps.txt')
+ if not os.path.exists(path):
+ return
+ for line in open(path):
+ f = line.split()
+ if len(f) != 4:
+ continue
+ L, o, b, j = map(int, f)
+ self.caps[L] = (o + max(16, o // 8), b + max(4, b // 8), j + max(4, j // 8))
+
+ def build(self):
+ self.load_caps()
+ # record 0: directory (filled last)
+ self.records = [None]
+ levels = []
+ self.uses = {}
+ self.kept = [L for L in range(200) if L not in SKIP]
+ for L in self.kept:
+ before = set(self.prog_record.values())
+ rec = self.level_record(L)
+ levels.append(len(self.records))
+ self.records.append(rec)
+ lv = self.g.prefabs[L]
+ for r in self.reachable(self.prog_record[lv.id]):
+ self.uses[r] = self.uses.get(r, 0) + 1
+ groups = self.block_library()
+ first_block = len(self.records)
+ self.records += groups
+ d = W()
+ d.u16(len(self.block_index))
+ d.u8(self.GROUP)
+ d.u16(first_block)
+ d.u16(len(self.comp.globals))
+ for (name, t), i in sorted(self.comp.globals.items(), key=lambda kv: kv[1]):
+ d.u8(t)
+ d.u16(len(levels))
+ for L, r in zip(self.kept, levels):
+ d.u16(r)
+ d.s(self.g.prefabs[L].name)
+ # global variable names needed by the engine (index lookup)
+ wanted = ['$Win', '$Lose', '$You', '$Cam', '$Offset']
+ d.u8(len(wanted))
+ for name in wanted:
+ idx = [i for (n, t), i in self.comp.globals.items() if n == name]
+ d.s(name)
+ d.u8(len(idx))
+ for i in idx:
+ d.u16(i)
+ self.records[0] = bytes(d.b)
+ return self.records
+
+ def with_tables(self, i):
+ """a program record read in place gets its node offset and output slot tables (bit 7 of byte 0)"""
+ r = self.records[i]
+ hl, offs, slots, nslots = self.node_tables[i]
+ t = W()
+ t.u16(nslots)
+ if (hl + 2) & 1:
+ t.u8(0)
+ for o in offs:
+ t.u16(o)
+ for sl in slots:
+ t.u16(sl)
+ return bytes([r[0] | 0x80]) + r[1:hl] + bytes(t.b) + r[hl:]
+
+ def serialize(self):
+ # records read in place from flash (no RAM copy): the directory and programs used by most levels
+ self.raw = {0} | {r for r, n in self.uses.items() if n >= 100}
+ for i in self.raw:
+ if i in self.node_tables:
+ self.records[i] = self.with_tables(i)
+ comp = []
+ for i, r in enumerate(self.records):
+ if i in self.raw:
+ comp.append(r)
+ continue
+ c = raw_deflate(r) if self.fast else zop(r)
+ comp.append(c)
+ out = W()
+ out.b += MAGIC
+ out.u16(len(self.records))
+ hdr = 4 + 2 + 4 * (len(self.records) + 1) + 4 * len(self.records)
+ # every record starts 4-byte aligned (tables in records read in place are accessed directly)
+ comp = [c + bytes(-len(c) & 3) for c in comp]
+ start = (hdr + 3) & ~3
+ off = start
+ for c in comp:
+ out.u32(off)
+ off += len(c)
+ out.u32(off)
+ for i, r in enumerate(self.records):
+ out.u32(len(r) | (0x80000000 if i in self.raw else 0))
+ out.b += bytes(start - hdr)
+ for c in comp:
+ out.b += c
+ return bytes(out.b)
+
+
+def main():
+ fast = '--fast' in sys.argv
+ args = [a for a in sys.argv[1:] if not a.startswith('--')]
+ out = args[0] if args else '../src/pack.c'
+ p = Packer(fast)
+ p.build()
+ data = p.serialize()
+ raw = sum(len(r) for r in p.records)
+ print('records', len(p.records), 'raw', raw, 'packed', len(data), 'blocks', len(p.block_index))
+ with open(out.replace('.c', '.bin'), 'wb') as f:
+ f.write(data)
+ with open(out, 'w') as f:
+ f.write('/* Generated by tools/pack.py from the original Drive Mad game data. */\n')
+ f.write('#include <stdint.h>\n')
+ f.write('const uint32_t pack_size = %d;\n' % len(data))
+ f.write('const uint8_t pack_data[%d] __attribute__((aligned(4))) = {\n' % len(data))
+ for i in range(0, len(data), 24):
+ f.write(','.join(str(b) for b in data[i:i + 24]) + ',\n')
+ f.write('};\n')
+ with open(out.replace('pack.c', 'ops.h'), 'w') as f:
+ f.write(ops.c_header())
+
+
+if __name__ == '__main__':
+ main()
diff --git a/games/numdrive/tools/scriptc.py b/games/numdrive/tools/scriptc.py
new file mode 100644
index 00000000..cde4e6c8
--- /dev/null
+++ b/games/numdrive/tools/scriptc.py
@@ -0,0 +1,295 @@
+"""Compile Fancade script grids into a compact node program for the VM."""
+from blockdefs import DEFS
+from fancade import SCRIPT, LEVEL
+import ops
+
+OUTSIDE = 32769
+VAR_GET = {46: 0, 48: 1, 50: 2, 52: 3, 54: 4, 56: 5}
+VAR_SET = {428: 0, 430: 1, 432: 2, 434: 3, 436: 4, 438: 5}
+SIG = {'Float': 0, 'Vec3': 1, 'Rot': 2, 'Bool': 3, 'Obj': 4, 'Con': 5, 'Void': 6}
+TERM_SETTING = {7: ('Void', None), 8: ('Float', True), 9: ('Float', False), 10: ('Vec3', True), 11: ('Vec3', False),
+ 12: ('Rot', True), 13: ('Rot', False), 14: ('Bool', True), 15: ('Bool', False),
+ 16: ('Obj', True), 17: ('Obj', False), 18: ('Con', True), 19: ('Con', False)}
+IGNORED = {15} # Comment
+
+
+class CompileError(Exception):
+ pass
+
+
+def custom_terminals(pf):
+ """Declared terminals of a custom prefab: list of (voxel pos, signal, is_input), top-first order."""
+ out = []
+ for (idx, t, pos, v) in pf.settings:
+ if t >= 7 and max(pos) < 256 and t in TERM_SETTING:
+ sig, is_in = TERM_SETTING[t]
+ if is_in is None:
+ raise CompileError('void terminal on custom prefab %s' % pf.name)
+ out.append((pos, sig, is_in, v))
+ out.sort(key=lambda t: (-t[0][2], t[0][0], t[0][1]))
+ return out
+
+
+class Node:
+ def __init__(self, op, pos, block_id):
+ self.op = op
+ self.pos = pos
+ self.block_id = block_id
+ self.ins = [] # refs
+ self.execs = [] # branch targets (node indices or None), op order
+ self.after = None # next statement
+ self.data = None
+ self.has_before = False
+ self.custom_prog = None
+
+
+class Program:
+ def __init__(self, pf):
+ self.pf = pf
+ self.nodes = []
+ self.entries = []
+ self.locals = {} # (name, type) -> index
+ self.templates = [] # object indices in the prefab grid (for non-level prefabs)
+ self.outputs = [] # for custom prefabs: declared output terminals -> ref
+ self.inputs = [] # declared input terminals
+
+
+class Compiler:
+ def __init__(self, game, lib, build_objects):
+ self.game = game
+ self.lib = lib
+ self.build_objects = build_objects
+ self.programs = {} # prefab id -> Program
+ self.globals = {} # (name, type) -> index
+ self.warnings = set()
+
+ def gvar(self, name, t):
+ key = (name, t)
+ if key not in self.globals:
+ self.globals[key] = len(self.globals)
+ return self.globals[key]
+
+ def program(self, pid):
+ if pid not in self.programs:
+ self.programs[pid] = None # recursion guard
+ self.programs[pid] = self.compile(self.game.seg(pid))
+ return self.programs[pid]
+
+ def compile(self, pf):
+ g = self.game
+ prog = Program(pf)
+ sx, sy, sz = pf.size
+ settings = {}
+ for (idx, t, pos, v) in pf.settings:
+ settings.setdefault(tuple(pos), []).append((idx, t, v))
+ # block instances (origin cells)
+ inst = {}
+ for z in range(sz):
+ for y in range(sy):
+ for x in range(sx):
+ id = pf.blocks[x + y * sx + z * sx * sy]
+ if not id:
+ continue
+ s = g.seg(id)
+ if s.in_group and s.gpos != (0, 0, 0):
+ continue
+ inst[(x, y, z)] = id
+ # objects inside this grid (templates / level objects)
+ objs, part_obj = self.build_objects(g, self.lib, pf)
+ prog.objects = objs
+ prog.part_obj = part_obj
+ # terminal tables
+ tpos = {} # world voxel -> list of (block pos, term name, dir, sig)
+ node_of = {}
+ order = sorted(inst, key=lambda p: (-p[2], p[0], -p[1]))
+ for pos in order:
+ id = inst[pos]
+ s = g.seg(id)
+ if id in ops.OPS:
+ n = Node(ops.OPS[id]['index'], pos, id)
+ node_of[pos] = len(prog.nodes)
+ prog.nodes.append(n)
+ for t in DEFS[id][3]:
+ if not t:
+ continue
+ w = (pos[0] * 8 + t[3][0], pos[1] * 8 + t[3][1], pos[2] * 8 + t[3][2])
+ nm = t[2] if t[2] in ('After', 'Before') else ('V', tuple(t[3]))
+ tpos.setdefault(w, []).append((pos, nm, t[1], t[0]))
+ elif id < g.id_offset:
+ if s.type == SCRIPT and id not in IGNORED and id in DEFS:
+ self.warnings.add('unsupported block %s' % DEFS[id][0])
+ elif s.blocks and s.size != (0, 0, 0):
+ # custom prefab with inner grid: script block or scripted object
+ child = self.program(id)
+ if child is None:
+ raise CompileError('recursive prefab %s' % s.name)
+ n = Node(ops.OP_CUSTOM, pos, id)
+ n.custom_prog = id
+ node_of[pos] = len(prog.nodes)
+ prog.nodes.append(n)
+ for (tp, sig, is_in, name) in custom_terminals(s):
+ w = (pos[0] * 8 + tp[0], pos[1] * 8 + tp[1], pos[2] * 8 + tp[2])
+ tpos.setdefault(w, []).append((pos, ('T', tp), 'In' if is_in else 'Out', sig))
+ prog.inputs = [t for t in custom_terminals(pf) if t[2]]
+ prog.outputs_decl = [t for t in custom_terminals(pf) if not t[2]]
+
+ # connections: explicit + implicit adjacency
+ edges = [] # (src pos, src term, dst pos, dst term)
+
+ def term_at(pos, voxel):
+ w = (pos[0] * 8 + voxel[0], pos[1] * 8 + voxel[1], pos[2] * 8 + voxel[2])
+ for (p, nm, d, sig) in tpos.get(w, []):
+ if p == pos:
+ return nm, d, sig
+ return None
+ for (fp, tp, fo, to) in pf.conns:
+ src = ('outside', fo) if fp[0] == OUTSIDE else None
+ dst = ('outside', to) if tp[0] == OUTSIDE else None
+ if src is None:
+ tt = term_at(fp, fo) if fp in node_of else None
+ src = (fp, tt[0]) if tt else ('object', fp, fo)
+ if dst is None:
+ tt = term_at(tp, to) if tp in node_of else None
+ if tt is None:
+ self.warnings.add('connection into non-terminal in %s' % pf.name)
+ continue
+ dst = (tp, tt[0])
+ edges.append((src, dst))
+ for w, lst in tpos.items():
+ for (p, nm, d, sig) in lst:
+ if d != 'Out':
+ continue
+ if sig == 'Void' and nm == 'After':
+ for (p2, n2, d2, s2) in tpos.get((w[0], w[1], w[2] - 2), []):
+ if n2 == 'Before':
+ edges.append(((p, nm), (p2, n2)))
+ else:
+ for (p2, n2, d2, s2) in tpos.get((w[0] + 2, w[1], w[2]), []):
+ if d2 == 'In' and (s2 == 'Void') == (sig == 'Void') and n2 != 'Before':
+ edges.append(((p, nm), (p2, n2)))
+ edges = list(dict.fromkeys(edges))
+
+ # resolve refs
+ def src_ref(src):
+ if src[0] == 'outside':
+ voxel = src[1]
+ for k, t in enumerate(prog.inputs):
+ if tuple(t[0]) == tuple(voxel):
+ return ('in', k)
+ return ('self', tuple(voxel))
+ if src[0] == 'object':
+ cell, voxel = src[1], src[2]
+ # find the object component at that voxel
+ c = (cell[0] + voxel[0] // 8, cell[1] + voxel[1] // 8, cell[2] + voxel[2] // 8)
+ lv = (voxel[0] % 8, voxel[1] % 8, voxel[2] % 8)
+ return ('obj', self.object_at(prog, c, lv))
+ pos, term = src
+ ni = node_of[pos]
+ n = prog.nodes[ni]
+ if n.op == ops.OP_CUSTOM:
+ child = self.programs[n.custom_prog]
+ outs = [t for t in custom_terminals(g.seg(n.custom_prog)) if not t[2]]
+ for k, t in enumerate(outs):
+ if ('T', t[0]) == term:
+ return ('node', ni, k)
+ raise CompileError('bad custom output')
+ outs = ops.OPS[n.block_id]['outs']
+ for k, t in enumerate(outs):
+ if ('V', tuple(t[3])) == term:
+ return ('node', ni, k)
+ raise CompileError('output %s not found on %s' % (term, DEFS[n.block_id][0]))
+
+ in_edges = {}
+ exec_edges = {}
+ for (src, dst) in edges:
+ if dst[0] == 'outside':
+ # value output of this prefab
+ for k, t in enumerate(prog.outputs_decl):
+ if tuple(t[0]) == tuple(dst[1]):
+ prog.outputs.append((k, src_ref(src)))
+ continue
+ dpos, dterm = dst
+ dn = prog.nodes[node_of[dpos]]
+ if dterm == 'Before':
+ if src[0] == 'outside':
+ raise CompileError('void input from outside')
+ exec_edges.setdefault((src[0], src[1]), []).append(node_of[dpos])
+ dn.has_before = True
+ continue
+ in_edges.setdefault((dpos, dterm), []).append(src)
+ # fill node inputs / execs
+ for ni, n in enumerate(prog.nodes):
+ if n.op == ops.OP_CUSTOM:
+ for (tp, sig, is_in, name) in custom_terminals(g.seg(n.custom_prog)):
+ if is_in:
+ srcs = in_edges.get((n.pos, ('T', tp)), [])
+ n.ins.append(src_ref(srcs[0]) if srcs else None)
+ continue
+ o = ops.OPS[n.block_id]
+ for t in o['ins']:
+ srcs = in_edges.get((n.pos, ('V', tuple(t[3]))), [])
+ if len(srcs) > 1:
+ self.warnings.add('multiple sources into %s.%s' % (o['name'], t[2]))
+ n.ins.append(src_ref(srcs[0]) if srcs else None)
+ for t in o['execs']:
+ tg = exec_edges.get((n.pos, ('V', tuple(t[3]))), [])
+ n.execs.append(tg)
+ nx = exec_edges.get((n.pos, 'After'), [])
+ n.after = nx
+ n.data = self.node_data(prog, n, settings.get(n.pos, []))
+ # entries: active statements without Before connection, parse order
+ for ni, n in enumerate(prog.nodes):
+ if n.op != ops.OP_CUSTOM and ops.OPS[n.block_id]['active'] and not n.has_before:
+ prog.entries.append(ni)
+ # templates: every object inside a non-level prefab grid
+ prog.env_children = [ni for ni, n in enumerate(prog.nodes) if n.op == ops.OP_CUSTOM]
+ return prog
+
+ def object_at(self, prog, cell, voxel):
+ c = cell
+ cands = [(oi, pid, k) for (pc, k), oi in prog.part_obj.items() if pc == c for pid in [self.cell_id(prog, pc)]]
+ i = voxel[0] + voxel[1] * 8 + voxel[2] * 64
+ for (oi, pid, k) in cands:
+ if self.lib.get(pid).comp[i] == k:
+ return oi
+ if cands:
+ return min(cands)[0]
+ self.warnings.add('object reference to empty cell in %s' % prog.pf.name)
+ return None
+
+ def cell_id(self, prog, c):
+ sx, sy, sz = prog.pf.size
+ return prog.pf.blocks[c[0] + c[1] * sx + c[2] * sx * sy]
+
+ def node_data(self, prog, n, sets):
+ id = n.block_id
+ if id == 36:
+ return ('num', next((v for (i, t, v) in sets if t == 4), 0.0))
+ if id == 38:
+ return ('vec', next((v for (i, t, v) in sets if t == 5), (0.0, 0.0, 0.0)))
+ if id == 42:
+ return ('rot', next((v for (i, t, v) in sets if t == 5), (0.0, 0.0, 0.0)))
+ if id in VAR_GET or id in VAR_SET:
+ name = next((v for (i, t, v) in sets if t == 6), '')
+ vt = VAR_GET[id] if id in VAR_GET else VAR_SET[id]
+ if name.startswith('$') or name.startswith('!'):
+ return ('var', 1, self.gvar(name, vt), name)
+ key = (name, vt)
+ if key not in prog.locals:
+ prog.locals[key] = len(prog.locals)
+ return ('var', 0, prog.locals[key], name)
+ if id in (252, 256): # win / lose delay
+ return ('byte', next((v for (i, t, v) in sets if t == 1), 0))
+ if id == 588: # button type
+ return ('byte', next((v for (i, t, v) in sets if t == 1), 0))
+ if id == 268: # camera perspective flag
+ return ('byte', next((v for (i, t, v) in sets if t == 1), 0))
+ if id == 592:
+ return ('byte', next((v for (i, t, v) in sets if t == 1), 0))
+ if id == 264: # play sound: sound id
+ return ('byte', next((v for (i, t, v) in sets if t == 1), 0))
+ if sets and id not in (15,):
+ known = {t for (i, t, v) in sets}
+ if known - {6}:
+ self.warnings.add('settings ignored on %s: %s' % (DEFS[id][0], sets))
+ return None
diff --git a/games/tetris/UNLICENSE b/games/tetris/UNLICENSE
new file mode 100644
index 00000000..fdddb29a
--- /dev/null
+++ b/games/tetris/UNLICENSE
@@ -0,0 +1,24 @@
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+For more information, please refer to <https://unlicense.org>
diff --git a/games/tetris/docs/shot1.png b/games/tetris/docs/shot1.png
new file mode 100644
index 00000000..d39497f4
Binary files /dev/null and b/games/tetris/docs/shot1.png differ
diff --git a/games/tetris/docs/shot2.png b/games/tetris/docs/shot2.png
new file mode 100644
index 00000000..4ea9ed3f
Binary files /dev/null and b/games/tetris/docs/shot2.png differ
diff --git a/games/tetris/docs/shot3.png b/games/tetris/docs/shot3.png
new file mode 100644
index 00000000..dfa35d3b
Binary files /dev/null and b/games/tetris/docs/shot3.png differ
diff --git a/games/tetris/nppm_decoder/.gitignore b/games/tetris/nppm_decoder/.gitignore
new file mode 100644
index 00000000..52ad4bf6
--- /dev/null
+++ b/games/tetris/nppm_decoder/.gitignore
@@ -0,0 +1,3 @@
+target
+
+Cargo.lock
diff --git a/games/tetris/nppm_decoder/Cargo.toml b/games/tetris/nppm_decoder/Cargo.toml
new file mode 100644
index 00000000..5152dabc
--- /dev/null
+++ b/games/tetris/nppm_decoder/Cargo.toml
@@ -0,0 +1,9 @@
+[package]
+name = "nppm_decoder"
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+name = "nppm_decoder"
+
+[package.metadata]
diff --git a/games/tetris/nppm_decoder/src/decoder.rs b/games/tetris/nppm_decoder/src/decoder.rs
new file mode 100644
index 00000000..187e3d14
--- /dev/null
+++ b/games/tetris/nppm_decoder/src/decoder.rs
@@ -0,0 +1,151 @@
+use core::str;
+use std::{
+ fs,
+ io::{Read, Write},
+};
+
+/// This will take a ppm file (nothing else for now) and extract the pixel data from it.
+///
+/// To use with the build.rs files of the apps
+///
+/// TODO : read other things than ppm files (pngs)
+
+pub fn extract_data_from_file(input_file: &'static str, output_file: &'static str, tile_size: u16) {
+ if tile_size == 1 {
+ panic!("Tilesize can't be equal to 1.");
+ }
+ let mut file = fs::File::open(input_file).expect("Failed to read input image.");
+ let mut contents: Vec<u8> = Vec::new();
+ file.read_to_end(&mut contents)
+ .expect("Failed to read input image.");
+
+ let (width, height, pixel_data_start) =
+ find_pixel_data_start(&contents).expect("Failed to parse PPM File.");
+
+ let pixel_data = &contents[pixel_data_start..];
+ let rgb_data = get_rgb565_data(pixel_data);
+ let translated_data = translate_pixel_data(rgb_data, width, height, tile_size)
+ .expect("Width or height of image not a multiple of tilesize");
+ let final_data = to_u8_data(translated_data);
+
+ let mut output = fs::File::create(output_file).expect("Failed to create output file");
+ output
+ .write_all(&final_data)
+ .expect("Failed to write output file.");
+}
+
+/// Needs tile size to be able to translate !!
+/// -> how to do that ??
+fn translate_pixel_data(
+ rgb_data: Vec<u16>,
+ width: u16,
+ height: u16,
+ tilesize: u16,
+) -> Option<Vec<u16>> {
+ let mut new_data = Vec::new();
+
+ if width % tilesize != 0 || height % tilesize != 0 || tilesize == 1 {
+ eprintln!("Warning : Width of tileset not a multiple of tilesize, or tilesize == 1.");
+ return None;
+ }
+ /* let width_in_tiles: u16 = width / tilesize;
+ let height_in_tiles: u16 = height / tilesize; */
+
+ for y_tile in (0..height).step_by(tilesize as usize) {
+ for x_tile in (0..width).step_by(tilesize as usize) {
+ // all tiles, one after the other, line by line
+
+ for y in y_tile..(y_tile + tilesize) {
+ for x in x_tile..(x_tile + tilesize) {
+ // Every single pixel, line by line
+ new_data.push(*rgb_data.get((y * width + x) as usize).unwrap());
+ }
+ }
+ }
+ }
+
+ Some(new_data)
+}
+
+fn to_u8_data(data: Vec<u16>) -> Vec<u8> {
+ let mut new_vec = Vec::new();
+
+ for d in data {
+ new_vec.push(d as u8);
+ new_vec.push((d >> 8) as u8);
+ }
+
+ new_vec
+}
+
+/// Finds the start of the pixel data in a PPM file by parsing its header.
+fn find_pixel_data_start(data: &[u8]) -> Option<(u16, u16, usize)> {
+ // Parse the PPM header
+ let mut index = 0;
+ let mut size: [u16; 2] = [0, 0];
+ // Check for the magic number
+ if &data[index..index + 2] != b"P6" {
+ return None;
+ }
+ index += 2;
+
+ // Skip whitespace after the magic number
+ while index < data.len() && data[index].is_ascii_whitespace() {
+ index += 1;
+ }
+
+ // Some commentaries could be there (thanks Gimp)
+ if data[index] == b'#' {
+ while index < data.len() && data[index] != b'\n' {
+ index += 1;
+ }
+ }
+ while index < data.len() && data[index].is_ascii_whitespace() {
+ index += 1;
+ }
+
+ // Parse width and height
+ for h in 0..2 {
+ let mut word = Vec::new();
+ while index < data.len() && !data[index].is_ascii_whitespace() {
+ word.push(data[index]);
+ index += 1;
+ }
+ let s = match str::from_utf8(&word) {
+ Ok(v) => v,
+ Err(_) => return None,
+ };
+ size[h] = s.parse().unwrap();
+
+ // whitespace
+ while index < data.len() && data[index].is_ascii_whitespace() {
+ index += 1;
+ }
+ }
+
+ // Parse max color value (skip it)
+ while index < data.len() && !data[index].is_ascii_whitespace() {
+ index += 1;
+ }
+ while index < data.len() && data[index].is_ascii_whitespace() {
+ index += 1;
+ }
+
+ // The remaining bytes are pixel data
+ Some((size[0], size[1], index))
+}
+
+fn get_rgb565_data(data: &[u8]) -> Vec<u16> {
+ let mut res = Vec::new();
+ for (r, g, b) in data
+ .iter()
+ .enumerate()
+ .step_by(3)
+ .map(|(i, x)| (x, data.get(i + 1).unwrap(), data.get(i + 2).unwrap()))
+ {
+ let pixel: u16 =
+ ((*r as u16 & 0b1111_1000) << 8) | ((*g as u16 & 0b1111_1100) << 3) | (*b as u16 >> 3);
+ res.push(pixel);
+ }
+ res
+}
diff --git a/games/tetris/nppm_decoder/src/lib.rs b/games/tetris/nppm_decoder/src/lib.rs
new file mode 100644
index 00000000..56812db3
--- /dev/null
+++ b/games/tetris/nppm_decoder/src/lib.rs
@@ -0,0 +1 @@
+pub mod decoder;
diff --git a/games/tetris/nppm_decoder/src/main.rs b/games/tetris/nppm_decoder/src/main.rs
new file mode 100644
index 00000000..a0014c70
--- /dev/null
+++ b/games/tetris/nppm_decoder/src/main.rs
@@ -0,0 +1,5 @@
+use nppm_decoder::decoder::extract_data_from_file;
+
+fn main() {
+ extract_data_from_file("image.ppm", "image.nppm", 35);
+}
diff --git a/games/tetris/numworks_utils/.cargo/config.toml b/games/tetris/numworks_utils/.cargo/config.toml
new file mode 100644
index 00000000..c84c3e33
--- /dev/null
+++ b/games/tetris/numworks_utils/.cargo/config.toml
@@ -0,0 +1,12 @@
+[build]
+target = "thumbv7em-none-eabihf"
+
+[target.thumbv7em-none-eabihf]
+rustflags = [
+ "-C",
+ "link-arg=--relocatable",
+ "-C",
+ "link-arg=-no-gc-sections",
+ "-C",
+ "target-cpu=cortex-m7",
+]
diff --git a/games/tetris/numworks_utils/Cargo.lock b/games/tetris/numworks_utils/Cargo.lock
new file mode 100644
index 00000000..cce35261
--- /dev/null
+++ b/games/tetris/numworks_utils/Cargo.lock
@@ -0,0 +1,57 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "byteorder"
+version = "1.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
+
+[[package]]
+name = "cc"
+version = "1.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a012a0df96dd6d06ba9a1b29d6402d1a5d77c6befd2566afdc26e10603dc93d7"
+dependencies = [
+ "shlex",
+]
+
+[[package]]
+name = "hash32"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606"
+dependencies = [
+ "byteorder",
+]
+
+[[package]]
+name = "heapless"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad"
+dependencies = [
+ "hash32",
+ "stable_deref_trait",
+]
+
+[[package]]
+name = "numworks_utils"
+version = "0.3.0"
+dependencies = [
+ "cc",
+ "heapless",
+]
+
+[[package]]
+name = "shlex"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
diff --git a/games/tetris/numworks_utils/Cargo.toml b/games/tetris/numworks_utils/Cargo.toml
new file mode 100644
index 00000000..785c9ec4
--- /dev/null
+++ b/games/tetris/numworks_utils/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "numworks_utils"
+version = "0.3.0"
+edition = "2021"
+
+[lib]
+name = "numworks_utils"
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+heapless = "0.8.0"
+
+[build-dependencies]
+cc = "*"
diff --git a/games/tetris/numworks_utils/README.md b/games/tetris/numworks_utils/README.md
new file mode 100644
index 00000000..b293c5ce
--- /dev/null
+++ b/games/tetris/numworks_utils/README.md
@@ -0,0 +1,28 @@
+# NUMWORKS UTILS
+This lib contains a lot of code I use in all the Rust apps.
+
+### EADK
+Eadk.rs contains all the functions we can call on the Epsilon ecosystem, and some basic implementations.
+It is kindly given by the Numworks team, and I made minimal changes to it.
+
+### Menu
+Menu.rs contains all the code necessary to make a fully functional menu.
+It can take care of a very simple selection menu, or a fully complete menu with options and all.
+
+### Utils
+Utils.rs contains some useful functions which we don't have access to since we are coding in no_std.
+
+### Graphical
+Graphical.rs contains some functions useful for everything UI-related. It allows drawing images or do some fading.
+Tiling.rs allows working very efficiently with Tilemaps to draw stuff.
+
+### Tiling
+Tiling.rs is a more precise graphical lib. It allows using a simple Tileset and draw those tiles. Useful to make code simpler.
+
+### Storage
+Storage.rs contains functions allowing the use of the external data app. Most of the code is not from me
+See https://framagit.org/Yaya.Cout/numworks-extapp-storage
+copyright (c) 2021-2022 Numworks
+
+### Widgets
+Widgets.rs contains some little "widgets", a bit like html elements : an number input for exemple.
\ No newline at end of file
diff --git a/games/tetris/numworks_utils/build.rs b/games/tetris/numworks_utils/build.rs
new file mode 100644
index 00000000..66c7a9c4
--- /dev/null
+++ b/games/tetris/numworks_utils/build.rs
@@ -0,0 +1,39 @@
+use std::process::Command;
+
+fn main() {
+ // The C storage helpers read the calculator's memory directly: they are only
+ // built for the calculator. Other targets (the simulator build of NumPlay)
+ // provide the same functions.
+ if !std::env::var("TARGET").unwrap_or_default().starts_with("thumb") {
+ return;
+ }
+ // Exécuter la commande pour récupérer les CFLAGS
+ let output = Command::new("sh")
+ .arg("-c")
+ .arg("nwlink eadk-cflags-device") // Remplacez $(NWLINK) par la commande appropriée
+ .output()
+ .expect("Échec lors de l'exécution de la commande NWLINK");
+
+ if !output.status.success() {
+ panic!(
+ "La commande nwlink a échoué avec le statut : {}",
+ output.status
+ );
+ }
+ // Convertir la sortie en chaîne de caractères
+ let cflags = String::from_utf8(output.stdout)
+ .expect("Impossible de convertir la sortie de NWLINK en String");
+ let mut build = cc::Build::new();
+ for flag in cflags.split_whitespace() {
+ build.flag(flag.trim_matches('"'));
+ }
+ build
+ .file("src/storage/storage.c")
+ .file("src/storage/mystring.c")
+ // .flag("-Os")
+ .compiler("arm-none-eabi-gcc")
+ .compile("storage");
+
+ println!("cargo::rerun-if-changed=src/storage/mystring.c");
+ println!("cargo::rerun-if-changed=src/storage/storage.c");
+}
diff --git a/games/tetris/numworks_utils/src/eadk.rs b/games/tetris/numworks_utils/src/eadk.rs
new file mode 100644
index 00000000..4a231a56
--- /dev/null
+++ b/games/tetris/numworks_utils/src/eadk.rs
@@ -0,0 +1,370 @@
+use core::f32::consts::PI;
+
+// This file represents all the function we can call in the Epsilon ecosystem.
+// This is the like the libc or syscalls of the Numworks calculator.
+// There are also some quality of life functions directly linked to the structures defined here, kindly given by the Numworks team.
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct Color {
+ pub rgb565: u16,
+}
+
+impl Color {
+ pub const RED: Self = Self::from_rgb888(255, 0, 0);
+ pub const GREEN: Self = Self::from_rgb888(0, 255, 0);
+ pub const BLUE: Self = Self::from_rgb888(0, 0, 255);
+ pub const WHITE: Self = Self::from_rgb888(255, 255, 255);
+ pub const BLACK: Self = Self::from_rgb888(0, 0, 0);
+
+ #[must_use]
+ pub const fn new(rgb565: u16) -> Self {
+ Self { rgb565 }
+ }
+
+ #[must_use]
+ pub const fn from_rgb888(r: u8, g: u8, b: u8) -> Self {
+ Self {
+ rgb565: ((r as u16 & 0b1111_1000) << 8)
+ | ((g as u16 & 0b1111_1100) << 3)
+ | (b as u16 >> 3),
+ }
+ }
+
+ #[must_use]
+ pub fn from_hsv(hue: f32, saturation: f32, value: f32) -> Self {
+ let f = |n: f32| {
+ let k: f32 = (n + hue / PI * 3.) % 6.;
+ value * (1. - saturation * k.min(4. - k).clamp(0., 1.))
+ };
+ Color::from_rgb888(
+ (f(5.) * 255.) as u8,
+ (f(3.) * 255.) as u8,
+ (f(1.) * 255.) as u8,
+ )
+ }
+
+ #[must_use]
+ pub fn from_hv(hue: f32, value: f32) -> Self {
+ let f = |n: f32| {
+ let k: f32 = (n + hue / PI * 3.) % 6.;
+ value * (1. - k.min(4. - k).clamp(0., 1.))
+ };
+ Color::from_rgb888(
+ (f(5.) * 255.) as u8,
+ (f(3.) * 255.) as u8,
+ (f(1.) * 255.) as u8,
+ )
+ }
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct Rect {
+ pub x: u16,
+ pub y: u16,
+ pub width: u16,
+ pub height: u16,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct Point {
+ pub x: u16,
+ pub y: u16,
+}
+
+impl Point {
+ pub const ZERO: Point = Point::new(0, 0);
+
+ #[must_use]
+ pub const fn new(x: u16, y: u16) -> Self {
+ Self { x, y }
+ }
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct State(u64);
+
+impl State {
+ #[must_use]
+ pub fn new(state: u64) -> Self {
+ Self(state)
+ }
+
+ #[must_use]
+ pub fn key_down(&self, k: u32) -> bool {
+ self.0.wrapping_shr(k) & 1 != 0
+ }
+
+ #[must_use]
+ pub fn any_down(&self) -> bool {
+ self.0 != 0
+ }
+}
+
+pub mod key {
+ pub const LEFT: u32 = 0;
+ pub const UP: u32 = 1;
+ pub const DOWN: u32 = 2;
+ pub const RIGHT: u32 = 3;
+ pub const OK: u32 = 4;
+ pub const BACK: u32 = 5;
+ pub const HOME: u32 = 6;
+ pub const SHIFT: u32 = 12;
+ pub const ALPHA: u32 = 13;
+ pub const XNT: u32 = 14;
+ pub const VAR: u32 = 15;
+ pub const TOOLBOX: u32 = 16;
+ pub const BACKSPACE: u32 = 17;
+ pub const EXP: u32 = 18;
+ pub const LN: u32 = 19;
+ pub const LOG: u32 = 20;
+ pub const IMAGINARY: u32 = 21;
+ pub const COMMA: u32 = 22;
+ pub const POWER: u32 = 23;
+ pub const SINE: u32 = 24;
+ pub const COSINE: u32 = 25;
+ pub const TANGENT: u32 = 26;
+ pub const PI: u32 = 27;
+ pub const SQRT: u32 = 28;
+ pub const SQUARE: u32 = 29;
+ pub const SEVEN: u32 = 30;
+ pub const EIGHT: u32 = 31;
+ pub const NINE: u32 = 32;
+ pub const LEFTPARENTHESIS: u32 = 33;
+ pub const RIGHTPARENTHESIS: u32 = 34;
+ pub const FOUR: u32 = 36;
+ pub const FIVE: u32 = 37;
+ pub const SIX: u32 = 38;
+ pub const MULTIPLICATION: u32 = 39;
+ pub const DIVISION: u32 = 40;
+ pub const ONE: u32 = 42;
+ pub const TWO: u32 = 43;
+ pub const THREE: u32 = 44;
+ pub const PLUS: u32 = 45;
+ pub const MINUS: u32 = 46;
+ pub const ZERO: u32 = 48;
+ pub const DOT: u32 = 49;
+ pub const EE: u32 = 50;
+ pub const ANS: u32 = 51;
+ pub const EXE: u32 = 52;
+}
+
+pub mod backlight {
+ pub fn set_brightness(brightness: u8) {
+ unsafe {
+ eadk_backlight_set_brightness(brightness);
+ }
+ }
+
+ #[must_use]
+ pub fn brightness() -> u8 {
+ unsafe { eadk_backlight_brightness() } // 0 - 240, par pas de 16
+ }
+
+ extern "C" {
+ fn eadk_backlight_set_brightness(brightness: u8);
+ fn eadk_backlight_brightness() -> u8;
+ }
+}
+
+pub mod display {
+ use super::Color;
+ use super::Point;
+ use super::Rect;
+
+ pub const SCREEN_WIDTH: u16 = 320;
+ pub const SCREEN_HEIGHT: u16 = 240;
+
+ pub fn push_rect(rect: Rect, pixels: &[Color]) {
+ unsafe {
+ eadk_display_push_rect(rect, pixels.as_ptr());
+ }
+ }
+
+ /// Personnal addon : useful for some technical things.
+ /// # Safety
+ /// Just be smart
+ pub unsafe fn push_rect_ptr(rect: Rect, pixels: *const Color) {
+ unsafe {
+ eadk_display_push_rect(rect, pixels);
+ }
+ }
+
+ pub fn push_rect_uniform(rect: Rect, color: Color) {
+ unsafe {
+ eadk_display_push_rect_uniform(rect, color);
+ }
+ }
+
+ pub fn pull_rect(rect: Rect, pixels: &[Color]) {
+ unsafe {
+ eadk_display_pull_rect(rect, pixels.as_ptr());
+ }
+ }
+
+ pub fn draw_string(
+ string: &str,
+ pos: Point,
+ large: bool,
+ text_color: Color,
+ background_color: Color,
+ ) {
+ unsafe {
+ eadk_display_draw_string(string.as_ptr(), pos, large, text_color, background_color);
+ }
+ }
+
+ pub fn wait_for_vblank() {
+ unsafe {
+ eadk_display_wait_for_vblank();
+ }
+ }
+
+ extern "C" {
+ fn eadk_display_push_rect_uniform(rect: Rect, color: Color);
+ fn eadk_display_push_rect(rect: Rect, color: *const Color);
+ fn eadk_display_draw_string(
+ text: *const u8,
+ pos: Point,
+ large: bool,
+ text_color: Color,
+ background_color: Color,
+ );
+ fn eadk_display_wait_for_vblank();
+ fn eadk_display_pull_rect(rect: Rect, color: *const Color);
+ }
+}
+
+pub mod keyboard {
+ use super::State;
+
+ /// The keys held down. 8, 4, 6 and 2 on the number pad also count as the
+ /// up, left, right and down arrows.
+ #[must_use]
+ pub fn scan() -> State {
+ let raw = unsafe { eadk_keyboard_scan() };
+ let mut state = raw;
+ for (pad, arrow) in [
+ (super::key::EIGHT, super::key::UP),
+ (super::key::FOUR, super::key::LEFT),
+ (super::key::SIX, super::key::RIGHT),
+ (super::key::TWO, super::key::DOWN),
+ ] {
+ if raw >> pad & 1 != 0 {
+ state |= 1 << arrow;
+ }
+ }
+ State::new(state)
+ }
+
+ extern "C" {
+ fn eadk_keyboard_scan() -> u64;
+ }
+}
+
+pub mod timing {
+ pub fn usleep(us: u32) {
+ unsafe {
+ eadk_timing_usleep(us);
+ }
+ }
+
+ pub fn msleep(ms: u32) {
+ unsafe {
+ eadk_timing_msleep(ms);
+ }
+ }
+
+ #[must_use]
+ pub fn millis() -> u64 {
+ unsafe { eadk_timing_millis() }
+ }
+
+ extern "C" {
+ fn eadk_timing_usleep(us: u32);
+ fn eadk_timing_msleep(us: u32);
+ fn eadk_timing_millis() -> u64;
+ }
+}
+
+/// Does not seem to work for now, at least with API = 1.
+pub mod battery {
+ /// not working
+ pub fn battery_charging() -> bool {
+ unsafe { eadk_battery_is_charging() }
+ }
+ /// not working
+ #[must_use]
+ pub fn battery_voltage() -> f32 {
+ unsafe { eadk_battery_voltage() }
+ }
+ /// not working
+ #[must_use]
+ pub fn battery_level() -> u8 {
+ unsafe { eadk_battery_level() }
+ }
+
+ extern "C" {
+ fn eadk_battery_is_charging() -> bool;
+ fn eadk_battery_voltage() -> f32;
+ fn eadk_battery_level() -> u8;
+ }
+}
+
+#[must_use]
+pub fn random() -> u32 {
+ unsafe { eadk_random() }
+}
+
+extern "C" {
+ fn eadk_random() -> u32;
+}
+/// Doesn't seem to be working, at least with API = 1, if that changes anything.
+pub fn usb_is_plugged() -> bool {
+ unsafe { eadk_usb_is_plugged() }
+}
+
+extern "C" {
+ fn eadk_usb_is_plugged() -> bool;
+}
+
+use core::fmt::Write;
+use core::panic::PanicInfo;
+
+use heapless::String;
+
+#[panic_handler]
+fn panic(info: &PanicInfo<'_>) -> ! {
+ let mut panic_str: String<64> = String::new();
+ if let Some(location) = info.location() {
+ write!(
+ &mut panic_str,
+ "Error\nin {}\nline {}\0",
+ location.file(),
+ location.line()
+ )
+ .unwrap();
+ }
+
+ display::push_rect_uniform(
+ Rect {
+ x: 0,
+ y: 0,
+ width: display::SCREEN_WIDTH,
+ height: display::SCREEN_HEIGHT,
+ },
+ Color::RED,
+ );
+ display::draw_string(
+ &panic_str,
+ Point::new(0, 0),
+ true,
+ Color::BLACK,
+ Color::WHITE,
+ );
+
+ loop {}
+}
diff --git a/games/tetris/numworks_utils/src/graphical.rs b/games/tetris/numworks_utils/src/graphical.rs
new file mode 100644
index 00000000..d407209a
--- /dev/null
+++ b/games/tetris/numworks_utils/src/graphical.rs
@@ -0,0 +1,203 @@
+pub mod tiling;
+
+/// A structure that facilitates passing color configuration to functions.
+pub struct ColorConfig {
+ /// Color of the text
+ pub text: Color,
+ /// Color of the background
+ pub bckgrd: Color,
+ /// Other color, often used as a selection color.
+ pub alt: Color,
+}
+
+use crate::{
+ eadk::{
+ backlight::{brightness, set_brightness},
+ display::{
+ self, draw_string, push_rect, push_rect_uniform, wait_for_vblank, SCREEN_HEIGHT,
+ },
+ timing, Color, Point, Rect,
+ },
+ utils::get_centered_text_x_coordo,
+};
+
+/// Fills the screen with the given [Color]
+pub fn fill_screen(color: Color) {
+ display::push_rect_uniform(
+ Rect {
+ x: Point::ZERO.x,
+ y: Point::ZERO.y,
+ width: display::SCREEN_WIDTH,
+ height: display::SCREEN_HEIGHT,
+ },
+ color,
+ );
+}
+
+/// Make the screen fade to 0 [brightness], then back to original brightness
+pub fn fading(dur: u32) {
+ let start_brightness: u8 = if brightness() == 0 { 16 } else { brightness() };
+ let mut bs = start_brightness;
+ while bs != 0 {
+ bs -= 1;
+ timing::msleep(dur / start_brightness as u32);
+ set_brightness(bs);
+ }
+ wait_for_vblank();
+ fill_screen(Color::BLACK);
+ set_brightness(start_brightness);
+}
+
+#[inline(always)]
+/// Draws the given string centered in the x coordinate
+pub fn draw_centered_string(
+ string: &str,
+ posy: u16,
+ large: bool,
+ cfg: &ColorConfig,
+ // Use alt text color or not
+ alt: bool,
+) {
+ draw_string_cfg(
+ string,
+ Point::new(get_centered_text_x_coordo(string, large), posy),
+ large,
+ cfg,
+ alt,
+ )
+}
+
+#[inline(always)]
+/// Like [draw_string] but with a [ColorConfig] instead of two colors.
+pub fn draw_string_cfg(string: &str, pos: Point, large: bool, cfg: &ColorConfig, alt: bool) {
+ draw_string(
+ string,
+ pos,
+ large,
+ if alt { cfg.alt } else { cfg.text },
+ cfg.bckgrd,
+ )
+}
+
+/// A random and most likely never used [Color] to use as transparency. e700ff, or (231, 0, 255), which is 0xE01F in RGB565 format, the one used here.
+pub const TRANSPARENCY_COLOR: Color = Color::from_rgb888(231, 0, 255);
+
+/// Draws an image from its pixel data, given as an array of [Color].
+///
+/// Can be scaled and can take care of transparency, but no scaling and no transparency is incomparably faster. Use carefully.
+/// Using transparency on an image that doesn't have any will still use only one draw call, but use quite a bit more overhead.
+///
+/// Scaling is very VERY slow, don't use it for anything reactive.
+pub fn draw_image(image: &[Color], pos: Point, size: (u16, u16), scaling: u16, transparency: bool) {
+ if scaling > 1 {
+ // As I almost never use scaling > 1, this is not optimised at all and I don't care for now.
+ let max_x = pos.x + size.0 * scaling;
+ let max_y = pos.y + size.1 * scaling;
+ let mut x_pos = pos.x;
+ let mut y_pos = pos.y;
+ for c in image {
+ if !transparency || c.rgb565 != TRANSPARENCY_COLOR.rgb565 {
+ push_rect_uniform(
+ Rect {
+ x: x_pos,
+ y: y_pos,
+ width: scaling,
+ height: scaling,
+ },
+ *c,
+ );
+ }
+ x_pos += scaling;
+ if x_pos >= max_x {
+ x_pos = pos.x;
+ y_pos += scaling;
+ if y_pos >= max_y || y_pos >= SCREEN_HEIGHT {
+ break;
+ }
+ }
+ }
+ } else if transparency {
+ // This code here may be ugly, but it comes from an long optimisation work
+ // I'm trying to limit as much as possible the number of push_rect calls and give the work to
+ // the rust compiler, trying to limit as much as possible
+ let base_ptr = image.as_ptr();
+ let row_width = size.0 as usize;
+
+ // Limit how many pixels we process vertically to stay within screen bounds
+ let max_lines = u16::min(size.1, SCREEN_HEIGHT.saturating_sub(pos.y));
+ let visible_pixels = (max_lines * size.0) as usize;
+
+ // Process only the visible portion of the image buffer
+ for opaque_run in image[..visible_pixels]
+ .split(|c| c.rgb565 == TRANSPARENCY_COLOR.rgb565)
+ .filter(|chunk| !chunk.is_empty())
+ {
+ // Find the starting index of this opaque run relative to the whole image buffer
+ let chunk_start = unsafe { opaque_run.as_ptr().offset_from(base_ptr) as usize };
+
+ // If the run starts mid-line (not aligned), print the partial line first
+ let unaligned_offset = if chunk_start % row_width != 0 {
+ let align_to_end_of_line = row_width - (chunk_start % row_width);
+ let length = usize::min(opaque_run.len(), align_to_end_of_line);
+
+ push_rect(
+ Rect {
+ x: pos.x + (chunk_start % row_width) as u16,
+ y: pos.y + (chunk_start / row_width) as u16,
+ width: length as u16,
+ height: 1,
+ },
+ &opaque_run[..length],
+ );
+
+ length
+ } else {
+ 0
+ };
+
+ // If the entire run was drawn already (it was small and unaligned), continue
+ if unaligned_offset >= opaque_run.len() {
+ continue;
+ }
+
+ // Now we're aligned on the left edge of a line → draw full aligned blocks
+ let full_lines = (opaque_run.len() - unaligned_offset) / row_width;
+ if full_lines > 0 {
+ push_rect(
+ Rect {
+ x: pos.x,
+ y: pos.y + ((chunk_start + unaligned_offset) / row_width) as u16,
+ width: size.0,
+ height: full_lines as u16,
+ },
+ &opaque_run[unaligned_offset..unaligned_offset + full_lines * row_width],
+ );
+ }
+
+ // Handle any remaining trailing pixels (less than one line)
+ let processed = unaligned_offset + full_lines * row_width;
+ if processed < opaque_run.len() {
+ push_rect(
+ Rect {
+ x: pos.x,
+ y: pos.y + ((chunk_start + processed) / row_width) as u16,
+ width: (opaque_run.len() - processed) as u16,
+ height: 1,
+ },
+ &opaque_run[processed..],
+ );
+ }
+ }
+ } else {
+ // fastest option -> nothing to do but a syscall
+ push_rect(
+ Rect {
+ x: pos.x,
+ y: pos.y,
+ width: size.0,
+ height: size.1,
+ },
+ image,
+ );
+ }
+}
diff --git a/games/tetris/numworks_utils/src/graphical/tiling.rs b/games/tetris/numworks_utils/src/graphical/tiling.rs
new file mode 100644
index 00000000..b01bea77
--- /dev/null
+++ b/games/tetris/numworks_utils/src/graphical/tiling.rs
@@ -0,0 +1,130 @@
+use core::{mem, slice};
+
+use crate::{
+ eadk::{display::push_rect, Color, Point, Rect},
+ graphical::draw_image,
+};
+
+/// Transforms a &[u8] to &[Color]
+/// Good luck with it
+const fn as_color_slice(bytes: &'static [u8]) -> &'static [Color] {
+ unsafe {
+ slice::from_raw_parts(
+ bytes.as_ptr() as *const Color,
+ bytes.len() / mem::size_of::<Color>(),
+ )
+ }
+}
+
+/// A simple struct representing a Tileset.
+/// Is just a constant (the size of a tile) and a static reference to the pixels
+/// All tileset images should respect the following criterias :
+/// Be on "column" form : all tiles should be on top of each other.
+/// The column is as large as a single tile, not a pixel more, not a pixel less.
+/// A ppm image can be processed by the build.rs file given in every apps I make.
+///
+pub struct Tileset {
+ image: &'static [Color],
+ pub tile_size: u16,
+ width: u16,
+}
+
+impl Tileset {
+ /// Creates a new Tileset with the tile size, the width in tiles (necessary to calculate offsets and all) and the image bytes.
+ pub const fn new(tile_size: u16, width_in_tiles: u16, image: &'static [u8]) -> Self {
+ Self {
+ image: as_color_slice(image),
+ tile_size,
+ width: tile_size * width_in_tiles,
+ }
+ }
+
+ /// Returns the slice associated with the data of the image.
+ /// Because I don't care, the size associated with it is totally wrong. Use Tileset.tile_size instead.
+ pub fn get_tile(
+ &self,
+ pos_in_tileset: Point, // as tiles
+ ) -> &[Color] {
+ let offset = (self.tile_size
+ * (pos_in_tileset.y * self.width + pos_in_tileset.x * self.tile_size))
+ as usize;
+ &self.image[offset..]
+ }
+
+ #[inline(always)]
+ /// Draws the given tile.
+ /// Just a helper function, the logic being in draw_image anyway.
+ pub fn draw_tile(&self, pos: Point, tile: Point, scaling: u16, transparency: bool) {
+ draw_image(
+ self.get_tile(tile),
+ pos,
+ (self.tile_size, self.tile_size),
+ scaling,
+ transparency,
+ );
+ }
+
+ /// I needed this function to optimise a game, but put it here if I ever need it again.
+ ///
+ /// It allows tiling with only half of a tile, up or down, without scaling or transparency.
+ ///
+ /// Can be used to draw lines like some ground, and I reversed it because the rectangles on the right need to be drawn first (because of how the screen is refreshed)
+ ///
+ /// Will probably end up refactored with a draw_half_tile function.
+ pub fn reverse_half_tiling(
+ &self,
+ pos: Point,
+ dimensions: (u16, u16),
+ tile: Point,
+ bottom: bool,
+ ) {
+ let mut tile = self.get_tile(tile);
+ if bottom {
+ // offset the data by tile_size / 2 lines.
+ tile = &tile[((self.tile_size * (self.tile_size / 2)) as usize)..];
+ }
+ for x in 0..dimensions.0 {
+ let x_pos = x * self.tile_size + pos.x;
+ for y in
+ (pos.y..(dimensions.1 * self.tile_size + pos.y)).step_by(self.tile_size as usize)
+ {
+ push_rect(
+ Rect {
+ x: x_pos,
+ y,
+ width: self.tile_size,
+ height: self.tile_size / 2,
+ },
+ tile,
+ );
+ }
+ }
+ }
+
+ /// Helper function to draw a tiling of the given tile. Will simply call draw_image for all the necessary tiles.
+ /// WARNING : can go out of the screen !
+ pub fn tiling(
+ &self,
+ pos: Point,
+ dimensions: (u16, u16),
+ tile: Point,
+ transparency: bool,
+ scaling: u16,
+ ) {
+ // some optimisation by skipping the overhead necessary to calculate the offset...
+ // but really, it so small that it is not necessary.
+ let tile: &[Color] = self.get_tile(tile);
+ for x in 0..dimensions.0 {
+ let x_pos = x * self.tile_size + pos.x;
+ for y in 0..dimensions.1 {
+ draw_image(
+ tile,
+ Point::new(x_pos, y * self.tile_size + pos.y),
+ (self.tile_size, self.tile_size),
+ scaling,
+ transparency,
+ );
+ }
+ }
+ }
+}
diff --git a/games/tetris/numworks_utils/src/lib.rs b/games/tetris/numworks_utils/src/lib.rs
new file mode 100644
index 00000000..2e03ca7f
--- /dev/null
+++ b/games/tetris/numworks_utils/src/lib.rs
@@ -0,0 +1,13 @@
+#![no_std]
+#![no_main]
+
+pub mod eadk;
+pub mod graphical;
+pub mod menu;
+pub mod numbers;
+pub mod storage;
+pub mod utils;
+pub mod widgets;
+
+#[macro_use]
+pub mod macros;
diff --git a/games/tetris/numworks_utils/src/macros.rs b/games/tetris/numworks_utils/src/macros.rs
new file mode 100644
index 00000000..9683281c
--- /dev/null
+++ b/games/tetris/numworks_utils/src/macros.rs
@@ -0,0 +1,21 @@
+#[repr(C)] // guarantee 'bytes' comes after '_align'
+pub struct AlignedAs<Align, Bytes: ?Sized> {
+ pub _align: [Align; 0],
+ pub bytes: Bytes,
+}
+
+#[macro_export]
+macro_rules! include_bytes_align_as {
+ ($align_ty:ty, $path:literal) => {{
+ // const block expression to encapsulate the static
+ use $crate::macros::AlignedAs;
+
+ // this assignment is made possible by CoerceUnsized
+ static ALIGNED: &AlignedAs<$align_ty, [u8]> = &AlignedAs {
+ _align: [],
+ bytes: *include_bytes!($path),
+ };
+
+ &ALIGNED.bytes
+ }};
+}
diff --git a/games/tetris/numworks_utils/src/menu.rs b/games/tetris/numworks_utils/src/menu.rs
new file mode 100644
index 00000000..b48d8655
--- /dev/null
+++ b/games/tetris/numworks_utils/src/menu.rs
@@ -0,0 +1,510 @@
+pub mod settings;
+
+use settings::{set_values_from_file, Setting};
+
+use crate::eadk::display::{push_rect_uniform, wait_for_vblank, SCREEN_HEIGHT, SCREEN_WIDTH};
+use crate::eadk::{display, key, keyboard, timing, Point, Rect};
+use crate::graphical::{draw_centered_string, draw_string_cfg, fading, fill_screen, ColorConfig};
+use crate::storage::open_file;
+use crate::storage::save::{
+ delete_save, load_save, write_save, GameSave, SaveField, SaveSlotMode, MAX_SAVE_FIELDS,
+};
+use crate::storage::MAX_STORAGE_VALUES;
+use crate::utils::{
+ get_centered_text_x_coordo, get_string_pixel_size, wait_for_no_keydown, CENTER,
+ LARGE_CHAR_HEIGHT, SMALL_CHAR_HEIGHT,
+};
+
+const FADING_TIME: u32 = 500;
+const REPETITION_SPEED: u16 = 200;
+const SPACE_BETWEEN_LINES: u16 = LARGE_CHAR_HEIGHT;
+
+pub struct MenuConfig {
+ pub choices: &'static [&'static str],
+ pub rect_margins: (u16, u16),
+ pub dimensions: (u16, u16),
+ pub offset: (i16, i16),
+ pub back_key_return: u8,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum StartMenuAction<T> {
+ /// Slot index initialized (None for Single mode, Some(slot) for Multi mode).
+ NewGame(Option<u8>),
+ /// Active save state along with the slot it originated from.
+ Continue(T, Option<u8>),
+ Exit,
+}
+
+const CHOICES_NO_SAVE: &[&str] = &["Play\0", "Settings\0", "How to Play\0", "Exit\0"];
+const CHOICES_WITH_SAVE: &[&str] = &[
+ "Continue\0",
+ "New Game\0",
+ "Settings\0",
+ "How to Play\0",
+ "Exit\0",
+];
+
+fn confirm_dialog(prompt: &str, cfg: &ColorConfig) -> bool {
+ let dialog_w = 200u16;
+ let dialog_h = (LARGE_CHAR_HEIGHT * 3) + 16;
+ let dialog_x = (SCREEN_WIDTH - dialog_w) / 2;
+ let dialog_y = (SCREEN_HEIGHT - dialog_h) / 2;
+
+ display::wait_for_vblank();
+
+ // Outer border
+ push_rect_uniform(
+ Rect {
+ x: dialog_x,
+ y: dialog_y,
+ width: dialog_w,
+ height: dialog_h,
+ },
+ cfg.alt,
+ );
+ // Inner background
+ push_rect_uniform(
+ Rect {
+ x: dialog_x + 2,
+ y: dialog_y + 2,
+ width: dialog_w - 4,
+ height: dialog_h - 4,
+ },
+ cfg.bckgrd,
+ );
+
+ // Prompt text centered near the top of the box
+ draw_centered_string(prompt, dialog_y + 10, true, cfg, false);
+
+ // Button row Y offset relative to SCREEN_HEIGHT / 2
+ let btn_y_offset =
+ (dialog_y + dialog_h - LARGE_CHAR_HEIGHT - 12) as i16 - (SCREEN_HEIGHT / 2) as i16;
+
+ let choice = selection(
+ cfg,
+ &MenuConfig {
+ choices: &["No\0", "Yes\0"],
+ rect_margins: (35, 0), // 35px padding on left and right inside the 200px box
+ dimensions: (dialog_w - 4, LARGE_CHAR_HEIGHT + 4),
+ offset: (0, btn_y_offset),
+ back_key_return: 0,
+ },
+ true,
+ );
+
+ choice == 1
+}
+
+fn open_settings_with_save_editor<T: GameSave>(
+ opt: &mut [&mut Setting],
+ cfg: &ColorConfig,
+ filename: &str,
+ godmode: bool,
+) {
+ if !godmode {
+ settings::settings(opt, cfg, filename, false);
+ return;
+ }
+
+ if let Some(mut save_state) = load_save::<T>(filename, None) {
+ let fields = save_state.describe_fields();
+ let mut save_settings: heapless::Vec<Setting, MAX_SAVE_FIELDS> = heapless::Vec::new();
+
+ for f in fields.iter() {
+ let mut vals: heapless::Vec<u32, MAX_STORAGE_VALUES> = heapless::Vec::new();
+ let _ = vals.push(f.value);
+ let _ = vals.push(f.min);
+ let _ = vals.push(f.max);
+
+ let _ = save_settings.push(Setting {
+ name: f.name,
+ choice: 0,
+ values: vals,
+ texts: heapless::Vec::new(),
+ user_modifiable: false,
+ fixed_values: false,
+ });
+ }
+
+ let opt_len = opt.len();
+ let mut updated_values: heapless::Vec<u32, MAX_SAVE_FIELDS> = heapless::Vec::new();
+ {
+ let mut combined: heapless::Vec<&mut Setting, MAX_STORAGE_VALUES> =
+ heapless::Vec::new();
+ for s in opt.iter_mut() {
+ let _ = combined.push(&mut **s);
+ }
+ for s in save_settings.iter_mut() {
+ let _ = combined.push(s);
+ }
+
+ settings::settings(&mut combined, cfg, filename, true);
+
+ for s in combined[opt_len..].iter() {
+ let _ = updated_values.push(s.get_setting_value());
+ }
+ }
+
+ let mut updated_fields: heapless::Vec<SaveField, MAX_SAVE_FIELDS> = heapless::Vec::new();
+ for (i, f) in fields.iter().enumerate() {
+ let _ = updated_fields.push(SaveField {
+ name: f.name,
+ min: f.min,
+ max: f.max,
+ value: updated_values[i],
+ });
+ }
+
+ save_state.update_from_fields(&updated_fields);
+ write_save(filename, None, &save_state);
+ } else {
+ settings::settings(opt, cfg, filename, true);
+ }
+}
+
+fn start_menu_single_slot<T: GameSave>(
+ title: &str,
+ opt: &mut [&mut Setting],
+ cfg: &ColorConfig,
+ vis_addon: fn(),
+ controls_text: &str,
+ filename: &str,
+ check_save: bool,
+) -> StartMenuAction<T> {
+ open_file(filename);
+ set_values_from_file(opt, filename);
+
+ loop {
+ let maybe_save: Option<T> = if check_save {
+ load_save(filename, None)
+ } else {
+ None
+ };
+
+ wait_for_vblank();
+ fill_screen(cfg.bckgrd);
+ vis_addon();
+ draw_centered_string(title, 20, true, cfg, false);
+
+ let (choices, back_key, dims) = if maybe_save.is_some() {
+ (
+ CHOICES_WITH_SAVE,
+ 4u8,
+ (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 + 16),
+ )
+ } else {
+ (CHOICES_NO_SAVE, 3u8, (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2))
+ };
+
+ let action = selection(
+ cfg,
+ &MenuConfig {
+ choices,
+ rect_margins: (10, 10),
+ dimensions: dims,
+ offset: (0, (SCREEN_HEIGHT / 5) as i16),
+ back_key_return: back_key,
+ },
+ false,
+ );
+
+ if let Some(save) = maybe_save {
+ match action {
+ 0 => {
+ fading(FADING_TIME);
+ return StartMenuAction::Continue(save, None);
+ }
+ 1 => {
+ if confirm_dialog("Overwrite save?\0", cfg) {
+ delete_save(filename, None);
+ fading(FADING_TIME);
+ return StartMenuAction::NewGame(None);
+ }
+ }
+ 2 => {
+ let scan = keyboard::scan();
+ open_settings_with_save_editor::<T>(
+ opt,
+ cfg,
+ filename,
+ scan.key_down(key::SHIFT),
+ );
+ }
+ 3 => {
+ controls(controls_text, cfg);
+ }
+ _ => {
+ fading(FADING_TIME);
+ return StartMenuAction::Exit;
+ }
+ }
+ } else {
+ match action {
+ 0 => {
+ fading(FADING_TIME);
+ return StartMenuAction::NewGame(None);
+ }
+ 1 => {
+ let scan = keyboard::scan();
+ open_settings_with_save_editor::<T>(
+ opt,
+ cfg,
+ filename,
+ scan.key_down(key::SHIFT),
+ );
+ }
+ 2 => {
+ controls(controls_text, cfg);
+ }
+ _ => {
+ fading(FADING_TIME);
+ return StartMenuAction::Exit;
+ }
+ }
+ }
+ }
+}
+
+/// 100% backward-compatible start_menu for legacy games without saves.
+/// Returns 0 for Play, 3 for Exit.
+pub fn start_menu(
+ title: &str,
+ opt: &mut [&mut Setting],
+ cfg: &ColorConfig,
+ vis_addon: fn(),
+ controls_text: &str,
+ filename: &str,
+) -> u8 {
+ #[derive(Clone, Copy)]
+ struct NoSave;
+ impl GameSave for NoSave {
+ fn to_words(&self) -> heapless::Vec<u32, MAX_STORAGE_VALUES> {
+ heapless::Vec::new()
+ }
+ fn from_words(_: &[u32]) -> Option<Self> {
+ None
+ }
+ fn describe_fields(&self) -> heapless::Vec<SaveField, MAX_SAVE_FIELDS> {
+ heapless::Vec::new()
+ }
+ fn update_from_fields(&mut self, _: &[SaveField]) {}
+ }
+
+ match start_menu_single_slot::<NoSave>(
+ title,
+ opt,
+ cfg,
+ vis_addon,
+ controls_text,
+ filename,
+ false,
+ ) {
+ StartMenuAction::NewGame(_) => 0,
+ _ => 3,
+ }
+}
+
+/// Enhanced start menu with dynamic save detection and slot mode routing.
+pub fn start_menu_with_save<T: GameSave>(
+ title: &str,
+ opt: &mut [&mut Setting],
+ cfg: &ColorConfig,
+ vis_addon: fn(),
+ controls_text: &str,
+ filename: &str,
+ slot_mode: SaveSlotMode,
+) -> StartMenuAction<T> {
+ match slot_mode {
+ SaveSlotMode::Single => {
+ start_menu_single_slot(title, opt, cfg, vis_addon, controls_text, filename, true)
+ }
+ SaveSlotMode::Multiple(max_slots) => {
+ todo!(
+ "Multiple save slots picker not implemented yet! Requested slots: {}",
+ max_slots
+ );
+ }
+ }
+}
+
+pub fn pause_menu(cfg: &ColorConfig, y_offset: i16) -> u8 {
+ selection(
+ cfg,
+ &MenuConfig {
+ choices: &["Resume\0", "Menu\0", "Exit\0"],
+ rect_margins: (20, 10),
+ dimensions: (
+ SCREEN_WIDTH * 2 / 5,
+ LARGE_CHAR_HEIGHT * 3 + SPACE_BETWEEN_LINES * 4,
+ ),
+ offset: (0, y_offset),
+ back_key_return: 0,
+ },
+ false,
+ )
+}
+
+pub fn selection(color: &ColorConfig, config: &MenuConfig, horizontal: bool) -> u8 {
+ display::wait_for_vblank();
+ display::push_rect_uniform(
+ Rect {
+ x: (((SCREEN_WIDTH - config.dimensions.0) / 2) as i16 + config.offset.0) as u16,
+ y: (((SCREEN_HEIGHT - config.dimensions.1) / 2) as i16 + config.offset.1) as u16,
+ width: config.dimensions.0,
+ height: config.dimensions.1,
+ },
+ color.bckgrd,
+ );
+ for (i, _) in config.choices.iter().enumerate() {
+ draw_selection_string(i as u8, color, config, i == 0, horizontal);
+ }
+ wait_for_no_keydown();
+
+ let mut cursor_pos: u8 = 0;
+ let mut last_action: u64 = timing::millis();
+ let mut last_action_key: u32 = key::ALPHA;
+ loop {
+ let keyboard_state = keyboard::scan();
+ if (keyboard_state.key_down(key::DOWN)
+ || keyboard_state.key_down(key::UP)
+ || keyboard_state.key_down(key::LEFT)
+ || keyboard_state.key_down(key::RIGHT))
+ && (timing::millis() >= (last_action + REPETITION_SPEED as u64))
+ {
+ display::wait_for_vblank();
+ draw_selection_string(cursor_pos, color, config, false, horizontal);
+ if (!horizontal && keyboard_state.key_down(key::DOWN))
+ || (horizontal && keyboard_state.key_down(key::RIGHT))
+ {
+ cursor_pos += 1;
+ if cursor_pos >= config.choices.len() as u8 {
+ cursor_pos = 0;
+ }
+ last_action_key = if keyboard_state.key_down(key::DOWN) {
+ key::DOWN
+ } else {
+ key::RIGHT
+ };
+ } else if (!horizontal && keyboard_state.key_down(key::UP))
+ || (horizontal && keyboard_state.key_down(key::LEFT))
+ {
+ if cursor_pos == 0 {
+ cursor_pos = config.choices.len() as u8 - 1;
+ } else {
+ cursor_pos -= 1;
+ }
+ last_action_key = if keyboard_state.key_down(key::UP) {
+ key::UP
+ } else {
+ key::LEFT
+ };
+ }
+ draw_selection_string(cursor_pos, color, config, true, horizontal);
+ last_action = timing::millis();
+ } else if keyboard_state.key_down(key::OK) {
+ loop {
+ let keyboard_state_test = keyboard::scan();
+ if !keyboard_state_test.key_down(key::OK) {
+ return cursor_pos;
+ }
+ }
+ } else if keyboard_state.key_down(key::BACK) {
+ return config.back_key_return;
+ } else if !keyboard_state.key_down(last_action_key) {
+ last_action = 0;
+ }
+ }
+}
+
+fn draw_selection_string(
+ cursor_pos: u8,
+ color: &ColorConfig,
+ config: &MenuConfig,
+ selected: bool,
+ horizontal: bool,
+) {
+ let text: &str = config.choices[cursor_pos as usize];
+
+ let y_pos: u16 = if !horizontal {
+ (CENTER.y - config.dimensions.1 / 2
+ + config.rect_margins.1
+ + cursor_pos as u16
+ * (config.dimensions.1 - config.rect_margins.1 * 2 - LARGE_CHAR_HEIGHT)
+ / (config.choices.len() as u16 - 1)) as i16
+ + config.offset.1
+ } else {
+ (CENTER.y - LARGE_CHAR_HEIGHT / 2) as i16 + config.offset.1
+ } as u16;
+
+ let x_coordos: u16 = if horizontal {
+ let box_left = (((SCREEN_WIDTH - config.dimensions.0) / 2) as i16 + config.offset.0) as u16;
+ let box_right = box_left + config.dimensions.0;
+
+ if cursor_pos == 0 {
+ if config.rect_margins.0 != 0 {
+ box_left + config.rect_margins.0
+ } else {
+ box_left + 10
+ }
+ } else if cursor_pos == config.choices.len() as u8 - 1 {
+ box_right
+ - get_string_pixel_size(config.choices[cursor_pos as usize], true)
+ - config.rect_margins.0
+ } else {
+ // Original balanced calculation bounded strictly to the menu box
+ let start_x = box_left + get_string_pixel_size(config.choices[0], true);
+ let max_x = box_right
+ - get_string_pixel_size(config.choices.last().unwrap(), true)
+ - config.rect_margins.0;
+ start_x + cursor_pos as u16 * (max_x - start_x) / (config.choices.len() as u16 - 1)
+ - get_string_pixel_size(config.choices[cursor_pos as usize], true) / 2
+ }
+ } else {
+ (get_centered_text_x_coordo(text, true) as i16 + config.offset.0) as u16
+ };
+
+ draw_string_cfg(text, Point::new(x_coordos, y_pos), true, color, selected);
+ push_rect_uniform(
+ Rect {
+ x: if x_coordos > 15 { x_coordos - 15 } else { 0 },
+ y: y_pos + LARGE_CHAR_HEIGHT / 2,
+ width: if x_coordos > 15 { 10 } else { x_coordos - 2 },
+ height: 2,
+ },
+ if selected { color.alt } else { color.bckgrd },
+ );
+}
+
+fn controls(text: &str, cfg: &ColorConfig) -> u8 {
+ wait_for_vblank();
+ fill_screen(cfg.bckgrd);
+ let back_text = "Menu : <Back> \0";
+ draw_string_cfg(
+ back_text,
+ Point::new(
+ SCREEN_WIDTH - get_string_pixel_size(back_text, false) - 5,
+ SCREEN_HEIGHT - SMALL_CHAR_HEIGHT - 5,
+ ),
+ false,
+ cfg,
+ false,
+ );
+ wait_for_vblank();
+ for (i, line) in text.split('\n').enumerate() {
+ draw_string_cfg(
+ line,
+ Point::new(0, i as u16 * SMALL_CHAR_HEIGHT),
+ false,
+ cfg,
+ false,
+ );
+ }
+ loop {
+ let keyboard_state = keyboard::scan();
+ if keyboard_state.key_down(key::BACK) {
+ break;
+ }
+ }
+ 0
+}
diff --git a/games/tetris/numworks_utils/src/menu/settings.rs b/games/tetris/numworks_utils/src/menu/settings.rs
new file mode 100644
index 00000000..484662e1
--- /dev/null
+++ b/games/tetris/numworks_utils/src/menu/settings.rs
@@ -0,0 +1,450 @@
+use heapless::{String, Vec};
+
+use crate::{
+ eadk::{
+ display::{self, push_rect_uniform, SCREEN_HEIGHT, SCREEN_WIDTH},
+ key, keyboard, timing, Point, Rect,
+ },
+ graphical::{draw_centered_string, draw_string_cfg, fill_screen, ColorConfig},
+ storage::{read_file, write_data, MAX_STORAGE_VALUES},
+ utils::{
+ get_string_pixel_size, string_from_u32, wait_for_no_keydown, LARGE_CHAR_HEIGHT,
+ SMALL_CHAR_HEIGHT,
+ },
+ widgets::numberinput::numberinput,
+};
+
+use super::{REPETITION_SPEED, SPACE_BETWEEN_LINES};
+
+// The maximum number of different values an option can take.
+pub const MAX_SETTINGS_VALUES: usize = MAX_STORAGE_VALUES;
+
+/// Where in the x coordinate will the names of the [option][Setting] be placed
+const XPOS_NAMES: u16 = 30;
+/// Where in the x coordinate will the values ([option][Setting].value.1) be placed
+const XPOS_VALUES: u16 = 170;
+
+/// An Option of T type, with COUNT possible values
+/// Old values are represented as u32.
+#[derive(Debug)]
+pub struct Setting {
+ pub name: &'static str,
+ pub choice: usize, // the selected position in the arrays
+ pub values: Vec<u32, MAX_SETTINGS_VALUES>,
+ pub texts: Vec<&'static str, MAX_SETTINGS_VALUES>,
+ pub user_modifiable: bool,
+ pub fixed_values: bool,
+ // If true : will iterate through the values defined in the vec. If false : will use a number-choosing widget with values[1] and values[2] as the boundaries. (TODO)
+ // false will probably mostly be used to store data like high scores.
+}
+
+impl Setting {
+ /// Set the value to the next one, 0 if needed
+ fn increment_value(&mut self) {
+ if self.choice == self.values.len() - 1 {
+ self.choice = 0
+ } else {
+ self.choice += 1
+ }
+ }
+
+ fn decrement_value(&mut self) {
+ if self.choice == 0 {
+ self.choice = self.values.len() - 1
+ } else {
+ self.choice -= 1
+ }
+ }
+
+ pub fn set_value(&mut self, value: u32) {
+ self.values[if self.fixed_values { 0 } else { self.choice }] = value;
+ }
+
+ #[inline(always)]
+ fn get_text(&self) -> &'static str {
+ self.texts[self.choice]
+ }
+
+ pub fn get_setting_value(&self) -> u32 {
+ self.values[self.choice]
+ }
+}
+
+pub(super) fn set_values_from_file(list: &mut [&mut Setting], filename: &str) {
+ let v = read_file(filename);
+ if v.is_empty() {
+ return;
+ }
+ for (x, y) in list.iter_mut().zip(v.iter()) {
+ if x.fixed_values {
+ x.choice = *y as usize;
+ } else {
+ x.choice = 0;
+ x.set_value(*y);
+ }
+ }
+}
+
+pub fn write_values_to_file(list: &[&mut Setting], filename: &str) {
+ for (i, v) in list.iter().enumerate() {
+ if v.fixed_values {
+ write_data(filename, Some(i as u32), v.choice as u32);
+ } else {
+ write_data(filename, Some(i as u32), v.values[0]);
+ }
+ }
+}
+
+const MAX_ITEMS_PER_PAGE: u16 = 5;
+
+/// Formats current/total pages
+fn format_page_counter(current_page: u16, total_pages: u16) -> String<16> {
+ use core::fmt::Write;
+ let mut str = String::<16>::new();
+ let _ = write!(str, "{}/{}\0", current_page + 1, total_pages);
+ str
+}
+
+/// Computes the top Y coordinate for the settings list on the current page.
+#[inline]
+fn calculate_first_y(items_in_page: u16) -> u16 {
+ match (SCREEN_HEIGHT + LARGE_CHAR_HEIGHT)
+ .checked_sub((LARGE_CHAR_HEIGHT + SPACE_BETWEEN_LINES) * items_in_page)
+ {
+ None | Some(0) => 0,
+ x_ @ Some(1u16..=u16::MAX) => x_.unwrap() / 2,
+ }
+}
+
+/// Computes the Y coordinate of an item given its slot index within the page.
+#[inline]
+fn item_y(first_y: u16, slot: u16) -> u16 {
+ first_y + (LARGE_CHAR_HEIGHT + SPACE_BETWEEN_LINES) * slot
+}
+
+/// Returns the number of items displayed on a given page.
+#[inline]
+fn items_on_page(page: u16, total_items: u16) -> u16 {
+ let start = page * MAX_ITEMS_PER_PAGE;
+ if start >= total_items {
+ 0
+ } else {
+ (total_items - start).min(MAX_ITEMS_PER_PAGE)
+ }
+}
+
+/// Draws a full settings page and returns the calculated `first_y`.
+fn draw_settings_page(
+ visible: &[&mut Setting],
+ page: u16,
+ pages: u16,
+ cursor_pos: u16,
+ cfg: &ColorConfig,
+) -> u16 {
+ let count = items_on_page(page, visible.len() as u16);
+ let first_y = calculate_first_y(count);
+
+ // visual things
+ display::wait_for_vblank();
+ fill_screen(cfg.bckgrd);
+ draw_centered_string("SETTINGS\0", 5u16, true, cfg, false);
+ let back_text = "Menu : <Back> \0";
+ draw_string_cfg(
+ back_text,
+ Point::new(
+ SCREEN_WIDTH - get_string_pixel_size(back_text, false) - 5,
+ SCREEN_HEIGHT - SMALL_CHAR_HEIGHT - 5,
+ ),
+ false,
+ cfg,
+ false,
+ );
+
+ // Page counter: print "x/x" in the bottom-left corner only when there are multiple pages
+ if pages > 1 {
+ let page_str = format_page_counter(page, pages);
+ draw_string_cfg(
+ &page_str,
+ Point::new(10, SCREEN_HEIGHT - SMALL_CHAR_HEIGHT - 5),
+ false,
+ cfg,
+ false,
+ );
+ }
+
+ // Page indicator: show '^' if there is a previous page
+ if page > 0 {
+ draw_centered_string("^\0", first_y - LARGE_CHAR_HEIGHT, true, cfg, false);
+ }
+
+ // printing the options
+ let start = (page * MAX_ITEMS_PER_PAGE) as usize;
+ for (i, item) in visible[start..start + count as usize].iter().enumerate() {
+ let y_pos = item_y(first_y, i as u16);
+ let large: bool = get_string_pixel_size(item.name, true) + XPOS_NAMES
+ < XPOS_VALUES - LARGE_CHAR_HEIGHT * 2;
+ display::draw_string(
+ item.name,
+ Point::new(
+ XPOS_NAMES,
+ y_pos
+ + if !large {
+ (LARGE_CHAR_HEIGHT - SMALL_CHAR_HEIGHT) / 2
+ } else {
+ 0
+ },
+ ),
+ large,
+ cfg.text,
+ cfg.bckgrd,
+ );
+ draw_setting_selection(item, y_pos, i as u16 == cursor_pos, cfg);
+ }
+
+ // Page indicator: show 'v' if there is a next page
+ if page + 1 < pages {
+ let last_y = item_y(first_y, count - 1);
+ draw_centered_string("v\0", last_y + LARGE_CHAR_HEIGHT + 5, true, cfg, false);
+ }
+
+ first_y
+}
+
+/// Create a fully fonctional settings menu, which changes directly the [options][Setting] values. (no settings return)
+/// For now, only allows a limited number of settings because making multiple pages is too complicated and I don't have time for that
+pub(crate) fn settings(
+ list: &mut [&mut Setting],
+ cfg: &ColorConfig,
+ filename: &str,
+ godmode: bool,
+) {
+ // Collect active mutable references so we don't repeatedly filter in hot loops
+ {
+ let mut visible: heapless::Vec<&mut Setting, MAX_SETTINGS_VALUES> = list
+ .iter_mut()
+ .filter_map(|s| {
+ if godmode || s.user_modifiable {
+ Some(&mut **s)
+ } else {
+ None
+ }
+ })
+ .collect();
+
+ let items_number = visible.len() as u16;
+ if items_number == 0 {
+ return;
+ }
+ let pages: u16 = (items_number + MAX_ITEMS_PER_PAGE - 1) / MAX_ITEMS_PER_PAGE; // 1 -> 1 ; 5 -> 1 ; 6 -> 2 : good !
+
+ let mut current_page: u16 = 0;
+ let mut cursor_pos: u16 = 0;
+ let mut first_y = draw_settings_page(&visible, current_page, pages, cursor_pos, cfg);
+
+ setting_selection(
+ &mut visible,
+ cfg,
+ &mut first_y,
+ items_number,
+ pages,
+ &mut current_page,
+ &mut cursor_pos,
+ );
+ }
+
+ write_values_to_file(list, filename);
+}
+
+/// Takes care of all the difficult stuff, like moving the cursor and modifying the text.
+///
+/// Similar to [super::selection] but redone to account for more things (and not account for horizontal versions)
+fn setting_selection(
+ visible: &mut [&mut Setting],
+ cfg: &ColorConfig,
+ first_y: &mut u16,
+ items_number: u16,
+ pages: u16,
+ current_page: &mut u16,
+ cursor_pos: &mut u16,
+) {
+ wait_for_no_keydown();
+
+ let mut last_action: u64 = timing::millis();
+ let mut last_action_key: u32 = key::ALPHA;
+
+ loop {
+ let items_in_page = items_on_page(*current_page, items_number);
+ let keyboard_scan = keyboard::scan();
+
+ if keyboard_scan.key_down(key::BACK) {
+ break;
+ } else if (keyboard_scan.key_down(key::UP) || keyboard_scan.key_down(key::DOWN))
+ && (timing::millis() >= (last_action + REPETITION_SPEED as u64))
+ {
+ display::wait_for_vblank();
+
+ // moving cursor
+ if keyboard_scan.key_down(key::UP) {
+ if *cursor_pos > 0 {
+ // Un-highlight previous item
+ let old_global_idx =
+ (*current_page * MAX_ITEMS_PER_PAGE + *cursor_pos) as usize;
+ draw_setting_selection(
+ &visible[old_global_idx],
+ item_y(*first_y, *cursor_pos),
+ false,
+ cfg,
+ );
+
+ *cursor_pos -= 1;
+
+ // Highlight newly selected item
+ let new_global_idx =
+ (*current_page * MAX_ITEMS_PER_PAGE + *cursor_pos) as usize;
+ draw_setting_selection(
+ &visible[new_global_idx],
+ item_y(*first_y, *cursor_pos),
+ true,
+ cfg,
+ );
+ } else if *current_page > 0 {
+ *current_page -= 1;
+ *cursor_pos = items_on_page(*current_page, items_number) - 1;
+ *first_y = draw_settings_page(visible, *current_page, pages, *cursor_pos, cfg);
+ }
+ // If on page 0 and cursor_pos == 0, do nothing (no wrap around)
+ last_action_key = key::UP;
+ } else if keyboard_scan.key_down(key::DOWN) {
+ if *cursor_pos < items_in_page - 1 {
+ // Un-highlight previous item
+ let old_global_idx =
+ (*current_page * MAX_ITEMS_PER_PAGE + *cursor_pos) as usize;
+ draw_setting_selection(
+ &visible[old_global_idx],
+ item_y(*first_y, *cursor_pos),
+ false,
+ cfg,
+ );
+
+ *cursor_pos += 1;
+
+ // Highlight newly selected item
+ let new_global_idx =
+ (*current_page * MAX_ITEMS_PER_PAGE + *cursor_pos) as usize;
+ draw_setting_selection(
+ &visible[new_global_idx],
+ item_y(*first_y, *cursor_pos),
+ true,
+ cfg,
+ );
+ } else if *current_page + 1 < pages {
+ *current_page += 1;
+ *cursor_pos = 0;
+ *first_y = draw_settings_page(visible, *current_page, pages, *cursor_pos, cfg);
+ }
+ // If on the last page and on the last item, do nothing (no wrap around)
+ last_action_key = key::DOWN;
+ }
+
+ last_action = timing::millis();
+ } else if (keyboard_scan.key_down(key::OK)
+ || keyboard_scan.key_down(key::RIGHT)
+ || keyboard_scan.key_down(key::LEFT))
+ && (timing::millis() >= (last_action + REPETITION_SPEED as u64))
+ {
+ let current_y = item_y(*first_y, *cursor_pos);
+ display::wait_for_vblank();
+
+ push_rect_uniform(
+ // remove last text
+ Rect {
+ x: XPOS_VALUES,
+ y: current_y,
+ width: SCREEN_WIDTH - XPOS_VALUES,
+ height: LARGE_CHAR_HEIGHT + 2, // I got some problems with characters going under the line (like g)
+ },
+ cfg.bckgrd,
+ );
+
+ let global_idx = (*current_page * MAX_ITEMS_PER_PAGE + *cursor_pos) as usize;
+ let selection: &mut Setting = &mut visible[global_idx];
+
+ if !selection.fixed_values {
+ if keyboard_scan.key_down(key::OK) {
+ let v = numberinput(
+ selection.values[0],
+ selection.values[1],
+ selection.values[2],
+ true,
+ Point {
+ x: XPOS_VALUES,
+ y: current_y,
+ },
+ cfg,
+ );
+ selection.set_value(v);
+ last_action_key = key::OK;
+ } else if keyboard_scan.key_down(key::RIGHT) {
+ // increment one step
+ if selection.values[0] < selection.values[2] {
+ selection.set_value(selection.values[0] + 1);
+ }
+ last_action_key = key::RIGHT;
+ } else if keyboard_scan.key_down(key::LEFT) {
+ if selection.values[0] > selection.values[1] {
+ selection.set_value(selection.values[0] - 1);
+ }
+ last_action_key = key::LEFT;
+ }
+ } else if keyboard_scan.key_down(key::OK) {
+ selection.increment_value();
+ last_action_key = key::OK;
+ } else if keyboard_scan.key_down(key::RIGHT) {
+ selection.increment_value();
+ last_action_key = key::RIGHT;
+ } else {
+ selection.decrement_value();
+ last_action_key = key::LEFT;
+ }
+
+ draw_setting_selection(selection, current_y, true, cfg);
+ last_action = timing::millis();
+ } else if !keyboard_scan.key_down(last_action_key) {
+ // if we let go of the key, then we can use a key just after (even the same one)
+ last_action = 0;
+ }
+ }
+}
+
+/// Draws the line corresponding to the given setting value
+fn draw_setting_selection(set: &Setting, ypos: u16, selected: bool, cfg: &ColorConfig) {
+ let text = if set.fixed_values {
+ set.get_text()
+ } else {
+ &string_from_u32(set.get_setting_value())
+ };
+ let large: bool = get_string_pixel_size(text, true) < SCREEN_WIDTH - XPOS_VALUES;
+ draw_string_cfg(
+ text,
+ Point::new(
+ XPOS_VALUES,
+ ypos + if !large {
+ (LARGE_CHAR_HEIGHT - SMALL_CHAR_HEIGHT) / 2
+ } else {
+ 0
+ },
+ ),
+ large,
+ cfg,
+ selected,
+ );
+ push_rect_uniform(
+ Rect {
+ x: XPOS_VALUES - 15,
+ y: ypos + LARGE_CHAR_HEIGHT / 2,
+ width: 10,
+ height: 2,
+ },
+ if selected { cfg.alt } else { cfg.bckgrd },
+ );
+}
diff --git a/games/tetris/numworks_utils/src/numbers.rs b/games/tetris/numworks_utils/src/numbers.rs
new file mode 100644
index 00000000..9b69a93d
--- /dev/null
+++ b/games/tetris/numworks_utils/src/numbers.rs
@@ -0,0 +1,26 @@
+pub fn ceil(x: f32) -> f32 {
+ let int_part = x as i32 as f32; // Extract the integer part
+ if x > int_part {
+ int_part + 1.0
+ } else {
+ int_part
+ }
+}
+
+/// Returns the next biggest, in absolute value, integer number (ex : -3.0 from -2.7 and 3.0 from 2.7)
+pub fn floor(x: f32) -> f32 {
+ let int_part = x as i32 as f32; // Extract the integer part
+ if x < 0.0 {
+ int_part - 1.0
+ } else {
+ int_part
+ }
+}
+
+pub fn abs(x: i32) -> u32 {
+ if x < 0 {
+ (-x) as u32
+ } else {
+ x as u32
+ }
+}
diff --git a/games/tetris/numworks_utils/src/storage.rs b/games/tetris/numworks_utils/src/storage.rs
new file mode 100644
index 00000000..871481bf
--- /dev/null
+++ b/games/tetris/numworks_utils/src/storage.rs
@@ -0,0 +1,115 @@
+use heapless::Vec;
+use low_level_storage::{extapp_fileErase, extapp_fileExists, extapp_fileRead, extapp_fileWrite};
+
+pub mod save;
+
+pub const MAX_STORAGE_VALUES: usize = 32;
+// const MAX_FILE_SIZE: usize = MAX_VALUES * 4; // which represents 64 values (each represented by a u32)
+
+pub mod low_level_storage {
+ #[link(name = "storage")]
+ extern "C" {
+ #[allow(dead_code)]
+ fn reverse32(value: u32) -> u32;
+ #[allow(dead_code)]
+ fn strcmp(s1: *const u8, s2: *const u8);
+ pub fn extapp_fileExists(filename: *const u8) -> bool;
+ pub fn extapp_fileRead(filename: *const u8, len: *mut u32) -> *const u8;
+ pub fn extapp_fileWrite(filename: *const u8, content: *const u8, len: u32) -> bool;
+ pub fn extapp_fileErase(filename: *const u8) -> bool;
+ pub fn extapp_size() -> u32;
+ pub fn extapp_address() -> u32;
+ pub fn extapp_used() -> u32;
+ pub fn extapp_nextFree() -> *mut u32;
+ pub fn extapp_isValid(address: *mut u32) -> bool;
+ pub fn extapp_calculatorModel() -> u8;
+ pub fn extapp_userlandAddress() -> *mut u32;
+ }
+}
+
+// Here are some helpers functions to read and write a file as a &[u32].
+
+/// The record holding a game's settings: "<game>.set", NUL-terminated for the C
+/// storage functions (Epsilon record names need an extension).
+fn record_name(filename: &str) -> heapless::String<32> {
+ let mut s = heapless::String::<32>::new();
+ let base = filename.trim_end_matches('\0');
+ let _ = s.push_str(base);
+ if !base.contains('.') {
+ let _ = s.push_str(".set");
+ }
+ let _ = s.push('\0');
+ s
+}
+
+/// Takes the filename = name of the game, and opens the file associated : creates it if necessary, and returns True if it exists.
+pub fn open_file(filename: &str) -> bool {
+ let name = record_name(filename);
+ if unsafe { extapp_fileExists(name.as_ptr()) } {
+ true
+ } else {
+ unsafe { extapp_fileWrite(name.as_ptr(), core::ptr::null(), 0) }
+ }
+}
+
+/// Like "extapp_fileRead" but returns a Vec<u32, MAX_VALUES> instead of a *const u8.
+pub fn read_file(filename: &str) -> Vec<u32, MAX_STORAGE_VALUES> {
+ let name = record_name(filename);
+ if !unsafe { extapp_fileExists(name.as_ptr()) } {
+ Vec::new()
+ } else {
+ let mut len = 0;
+ let data = unsafe { extapp_fileRead(name.as_ptr(), &mut len) };
+ let mut data_read = Vec::new();
+ if data.is_null() {
+ return data_read;
+ }
+ for i in (0..len as usize).step_by(4) {
+ let v: u32 = unsafe { data.wrapping_add(i).cast::<u32>().read_unaligned() };
+ if data_read.push(v).is_err() {
+ break;
+ }
+ }
+
+ data_read
+ }
+}
+
+pub fn read_data(filename: &str, pos: usize) -> Option<u32> {
+ let values = read_file(filename);
+ values.get(pos).copied()
+}
+
+/// Write a given data value to the file. Will copy the entirety of the file before erasing it and rewriting it again.
+/// If a position is given, will replace this value. Else, writes it at the end of the file.
+/// Returns the position at which it was added.
+pub fn write_data(filename: &str, pos: Option<u32>, value: u32) -> usize {
+ let mut values = read_file(filename);
+ let res;
+ if let Some(x) = pos {
+ // if a position is given
+ let d = values.get_mut(x as usize);
+ if let Some(old_v) = d {
+ // if data was found there, replace it
+ *old_v = value;
+ res = x as usize;
+ } else {
+ let _ = values.push(value); // else add it
+ res = values.len() - 1;
+ }
+ } else {
+ let _ = values.push(value); // else add it
+ res = values.len() - 1;
+ }
+ let name = record_name(filename);
+ unsafe { extapp_fileErase(name.as_ptr()) };
+ // A full storage only means the settings are not remembered.
+ let _ = unsafe {
+ extapp_fileWrite(
+ name.as_ptr(),
+ values.as_ptr().cast(),
+ values.len() as u32 * 4,
+ )
+ };
+ res
+}
diff --git a/games/tetris/numworks_utils/src/storage/mystring.c b/games/tetris/numworks_utils/src/storage/mystring.c
new file mode 100644
index 00000000..1100b5f0
--- /dev/null
+++ b/games/tetris/numworks_utils/src/storage/mystring.c
@@ -0,0 +1,77 @@
+#include "mystring.h"
+
+// I couldn't make the libc work with Rust and all... so I just remade those 4 functions that storage.c uses. It is definitely not a good solution, and I may look at it again later.
+
+// from github.com/numworks/epsilon/liba/
+int strcmp(const char *s1, const char *s2)
+{
+ while (*s1 != '\0' && *s1 == *s2)
+ {
+ s1++;
+ s2++;
+ }
+ return (*(unsigned char *)s1) - (*(unsigned char *)s2);
+}
+
+// from github.com/numworks/epsilon/liba/
+void *mymemcpy(void *__restrict__ dest, const void *__restrict__ src, size_t n)
+{
+ char *destination = (char *)dest;
+ char *source = (char *)src;
+
+ while (n--)
+ {
+ *destination = *source;
+ destination++;
+ source++;
+ }
+
+ return dest;
+}
+
+// from github.com/numworks/epsilon/liba/
+void *mymemmove(void *dest, const void *src, size_t n)
+{
+ char *destination = (char *)dest;
+ char *source = (char *)src;
+
+ if (source < destination && destination < source + n)
+ {
+ /* Copy backwards to avoid overwrites */
+ source += n;
+ destination += n;
+ while (n--)
+ {
+ *--destination = *--source;
+ }
+ }
+ else
+ {
+ while (n--)
+ {
+ *destination++ = *source++;
+ }
+ }
+
+ return dest;
+}
+
+// from github.com/numworks/epsilon/liba/
+void *mymemset(void *s, int c, size_t n)
+{
+ char *destination = (char *)s;
+ while (n--)
+ {
+ *destination++ = (unsigned char)c;
+ }
+ return s;
+}
+
+// from github.com/numworks/epsilon/liba/
+unsigned int strlen(const char *s)
+{
+ const char *str = s;
+ while (*str)
+ str++;
+ return str - s;
+}
\ No newline at end of file
diff --git a/games/tetris/numworks_utils/src/storage/mystring.h b/games/tetris/numworks_utils/src/storage/mystring.h
new file mode 100644
index 00000000..cee96c83
--- /dev/null
+++ b/games/tetris/numworks_utils/src/storage/mystring.h
@@ -0,0 +1,15 @@
+#ifndef MYSTRING_H
+#define MYSTRING_H
+
+#include <stddef.h>
+
+#define CPY_DIR_LOWER_TO_HIGHER 0
+#define CPY_DIR_HIGHER_TO_LOWER 1
+
+int strcmp(const char *s1, const char *s2);
+void *mymemcpy(void *__restrict__ dest, const void *__restrict__ src, size_t n);
+void *mymemmove(void *dest, const void *src, size_t n);
+void *mymemset(void *s, int c, size_t n);
+unsigned int strlen(const char *s);
+
+#endif
\ No newline at end of file
diff --git a/games/tetris/numworks_utils/src/storage/save.rs b/games/tetris/numworks_utils/src/storage/save.rs
new file mode 100644
index 00000000..1d10a9e1
--- /dev/null
+++ b/games/tetris/numworks_utils/src/storage/save.rs
@@ -0,0 +1,103 @@
+use crate::storage::low_level_storage::{
+ extapp_fileErase, extapp_fileExists, extapp_fileRead, extapp_fileWrite,
+};
+use crate::storage::MAX_STORAGE_VALUES;
+use heapless::{String, Vec};
+
+pub const MAX_SAVE_FIELDS: usize = MAX_STORAGE_VALUES;
+
+/// Defines how many save slots a game supports.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum SaveSlotMode {
+ /// Exactly 1 save slot: uses `<app>.sav`. Overwriting or deleting targets this single file.
+ Single,
+ /// Up to `count` discrete slots: uses `<app>.s0`, `<app>.s1`, ...
+ Multiple(u8),
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct SaveField {
+ pub name: &'static str,
+ pub min: u32,
+ pub max: u32,
+ pub value: u32,
+}
+
+pub trait GameSave: Copy + Sized {
+ /// Serializes game state into raw u32 words.
+ fn to_words(&self) -> Vec<u32, MAX_STORAGE_VALUES>;
+
+ /// Deserializes a slice of u32 words back into Self.
+ fn from_words(words: &[u32]) -> Option<Self>;
+
+ /// Exposes named fields for God Mode inspection and editing.
+ fn describe_fields(&self) -> Vec<SaveField, MAX_SAVE_FIELDS>;
+
+ /// Updates Self from modified field values.
+ fn update_from_fields(&mut self, fields: &[SaveField]);
+}
+
+pub fn get_save_filename(app: &str, slot: Option<u8>) -> String<32> {
+ use core::fmt::Write;
+ let mut s = String::<32>::new();
+ if let Some(slot_num) = slot {
+ let _ = write!(s, "{}.s{}\0", app, slot_num);
+ } else {
+ let _ = write!(s, "{}.sav\0", app);
+ }
+ s
+}
+
+pub fn has_save(app: &str, slot: Option<u8>) -> bool {
+ let filename = get_save_filename(app, slot);
+ unsafe { extapp_fileExists(filename.as_ptr()) }
+}
+
+pub fn load_save<T: GameSave>(app: &str, slot: Option<u8>) -> Option<T> {
+ let filename = get_save_filename(app, slot);
+ if !unsafe { extapp_fileExists(filename.as_ptr()) } {
+ return None;
+ }
+
+ let mut len: u32 = 0;
+ let data_ptr = unsafe { extapp_fileRead(filename.as_ptr(), &mut len) };
+ if data_ptr.is_null() || len < 4 {
+ return None;
+ }
+
+ let mut words: Vec<u32, MAX_STORAGE_VALUES> = Vec::new();
+ let word_count = (len as usize / 4).min(MAX_STORAGE_VALUES);
+
+ for i in 0..word_count {
+ let val: u32 = unsafe { data_ptr.add(i * 4).cast::<u32>().read() };
+ words.push(val).ok()?;
+ }
+
+ T::from_words(&words)
+}
+
+pub fn write_save<T: GameSave>(app: &str, slot: Option<u8>, state: &T) -> bool {
+ let filename = get_save_filename(app, slot);
+ let words = state.to_words();
+
+ if unsafe { extapp_fileExists(filename.as_ptr()) } {
+ unsafe { extapp_fileErase(filename.as_ptr()) };
+ }
+
+ unsafe {
+ extapp_fileWrite(
+ filename.as_ptr(),
+ words.as_ptr().cast(),
+ words.len() as u32 * 4,
+ )
+ }
+}
+
+pub fn delete_save(app: &str, slot: Option<u8>) -> bool {
+ let filename = get_save_filename(app, slot);
+ if unsafe { extapp_fileExists(filename.as_ptr()) } {
+ unsafe { extapp_fileErase(filename.as_ptr()) }
+ } else {
+ true
+ }
+}
diff --git a/games/tetris/numworks_utils/src/storage/storage.c b/games/tetris/numworks_utils/src/storage/storage.c
new file mode 100644
index 00000000..f74c7bf0
--- /dev/null
+++ b/games/tetris/numworks_utils/src/storage/storage.c
@@ -0,0 +1,305 @@
+// https://framagit.org/Yaya.Cout/numworks-extapp-storage (thanks !)
+// copyright (c) 2021-2022 Numworks
+// Not the most optimised thing but pretty clean and working. Allows writing a lot of differents files to the storage.
+// In storage.rs, I made a wrapper to call those functions easily in a concrete environment : storing game data and options.
+
+#include <stdbool.h>
+#include "storage.h"
+#include <stdint.h>
+#include "mystring.h"
+
+// Taken from https://codereview.stackexchange.com/questions/151049/endianness-conversion-in-c/151070#151070
+// I could convert the endianness manually, but it's less readable.
+uint32_t reverse32(uint32_t value)
+{
+ return (((value & 0x000000FF) << 24) |
+ ((value & 0x0000FF00) << 8) |
+ ((value & 0x00FF0000) >> 8) |
+ ((value & 0xFF000000) >> 24));
+}
+
+bool extapp_fileExists(const char *filename)
+{
+ uint32_t storageAddress = extapp_address();
+ char *offset = (char *)storageAddress;
+ const char *endAddress = (char *)extapp_size() + storageAddress;
+
+ if (!extapp_isValid((const uint32_t *)offset))
+ {
+ // Storage is invalid
+ return false;
+ }
+
+ offset += 4;
+ int currentRecord = 0;
+
+ while (offset < endAddress)
+ {
+ uint16_t size = *(uint16_t *)offset;
+ if (size == 0)
+ {
+ break;
+ }
+ char *name = offset + 2;
+
+ if (strcmp(name, filename) == 0)
+ {
+ // File was found
+ return true;
+ }
+
+ offset += size;
+ currentRecord++;
+ }
+
+ return false;
+}
+
+char *extapp_fileRead(const char *filename, size_t *len)
+{
+ uint32_t storageAddress = extapp_address();
+ char *offset = (char *)storageAddress;
+ const char *endAddress = (char *)extapp_size() + storageAddress;
+
+ if (!extapp_isValid((const uint32_t *)offset))
+ {
+ // Storage is invalid
+ return NULL;
+ }
+
+ offset += 4;
+
+ while (offset < endAddress)
+ {
+ uint16_t size = *(uint16_t *)offset;
+ if (size == 0)
+ {
+ break;
+ }
+ char *name = offset + 2;
+
+ if (strcmp(name, filename) == 0)
+ {
+ // filename + \0
+ uint16_t nameSize = strlen(name) + 1;
+ // Size contains size + filename + real content. Here, we only want the
+ // content
+ *len = size - 2 - nameSize;
+ // offset + size + filename
+ return offset + 2 + nameSize;
+ }
+
+ offset += size;
+ }
+
+ // File not found
+ return NULL;
+}
+
+bool extapp_fileWrite(const char *filename, const char *content, size_t len)
+{
+ // Check if we have enough free space
+ const uint32_t *recordStartPointer = extapp_nextFree();
+ // Start Address + size + filename + \0 + content
+ const uint32_t *recordEndPointer = (uint32_t *)((char *)recordStartPointer + 2 + strlen(filename) + 1 + len);
+ const uint32_t *storageEndPointer = (uint32_t *)(extapp_address() + extapp_size());
+
+ // In case where we have overflown storage, we return an error
+ if (storageEndPointer <= recordEndPointer)
+ {
+ return false;
+ }
+
+ char *writableRecordStartPointer = (char *)extapp_nextFree();
+
+ // We have enough storage, so we can write the data
+ // Write size :
+ // size + filename + \0 + content
+ const uint16_t totalSize = 2 + strlen(filename) + 1 + len;
+
+ *(uint16_t *)writableRecordStartPointer = totalSize;
+
+ // Write filename:
+ mymemcpy(writableRecordStartPointer + 2, filename, strlen(filename) + 1); // COUPABLE DU CRASH !!!! ouuuiiiin (mon avis : résoudre ce problème = résoudre le problème de erase aussi)
+
+ // Write content:
+ mymemcpy(writableRecordStartPointer + 2 + strlen(filename) + 1, content, len);
+
+ // The record is now written, so we can return
+ return true;
+}
+
+bool extapp_fileErase(const char *filename)
+{
+ uint32_t storageAddress = extapp_address();
+ char *offset = (char *)storageAddress;
+ const char *endAddress = (char *)extapp_size() + storageAddress;
+
+ if (!extapp_isValid((const uint32_t *)offset))
+ {
+ // Storage is invalid
+ return false;
+ }
+
+ offset += 4;
+
+ // Locate the record address
+ char *recordAddress = NULL;
+ uint16_t file_size;
+ while (offset < endAddress)
+ {
+ uint16_t size = *(uint16_t *)offset;
+ if (size == 0)
+ {
+ file_size = 0;
+ break;
+ }
+ char *name = offset + 2;
+
+ if (strcmp(name, filename) == 0)
+ {
+ recordAddress = offset;
+ file_size = size;
+ break;
+ }
+
+ offset += size;
+ }
+
+ // File not found
+ if (recordAddress == NULL)
+ {
+ return false;
+ }
+
+ // Move the rest of the data
+ // Why not len + 2 ?
+ mymemmove(offset, offset + file_size, (char *)extapp_nextFree() - offset);
+
+ // Overwrite the rest of the storage with zeroes
+ // the + 1 in len + 1 is for the uint16_t used for file size
+ mymemset(offset + *(uint16_t *)offset + 1, 0, file_size + 1);
+
+ return true;
+}
+
+uint32_t extapp_address()
+{
+ return *(uint32_t *)((*extapp_userlandAddress()) + 0xC);
+}
+
+uint32_t extapp_size()
+{
+ return *(uint32_t *)((*extapp_userlandAddress()) + 0x10);
+}
+
+uint32_t *extapp_nextFree()
+{
+ uint32_t storageAddress = extapp_address();
+ char *offset = (char *)storageAddress;
+ const char *endAddress = (char *)extapp_size() + storageAddress;
+
+ if (!extapp_isValid((const uint32_t *)offset))
+ {
+ // Storage is invalid
+ return NULL;
+ }
+
+ offset += 4;
+
+ while (offset < endAddress)
+ {
+ uint16_t size = *(uint16_t *)offset;
+ if (size == 0)
+ {
+ // Here, we are at the place where new records should start
+ return (uint32_t *)offset;
+ }
+
+ offset += size;
+ }
+
+ // If we exited the loop, it mean that we have gone out of the storage
+ return NULL;
+ // return (uint32_t *)storageAddress + extapp_size();
+}
+
+uint32_t extapp_used()
+{
+ return (uint32_t)extapp_nextFree() - extapp_address();
+}
+
+bool extapp_isValid(const uint32_t *address)
+{
+ return *address == reverse32(0xBADD0BEE);
+}
+
+uint8_t extapp_calculatorModel()
+{
+ // To guess the storage size without reading forbidden addresses, we try to
+ // get the storage address from the userland header
+
+ uint32_t *userlandMagicSlotAN0110 = *(uint32_t **)0x90010000;
+ uint32_t *userlandMagicSlotBN0110 = *(uint32_t **)0x90410000;
+ uint32_t *userlandMagicSlotAN0120 = *(uint32_t **)0x90020000;
+ uint32_t *userlandMagicSlotBN0120 = *(uint32_t **)0x90420000;
+
+ // On N0110, RAM start is at 0x20000000 and end is 0x20040000
+ // On N0120, RAM start is at 0x20040000
+ bool userlandMagicSlotAN0110IsValid = reverse32(0xfeedc0de) == (uint32_t)userlandMagicSlotAN0110;
+ bool userlandMagicSlotBN0110IsValid = reverse32(0xfeedc0de) == (uint32_t)userlandMagicSlotBN0110;
+ // TODO: Check the end address on N0120 (should be working, but good to check anyway)
+ bool userlandMagicSlotAN0120IsValid = reverse32(0xfeedc0de) == (uint32_t)userlandMagicSlotAN0120;
+ bool userlandMagicSlotBN0120IsValid = reverse32(0xfeedc0de) == (uint32_t)userlandMagicSlotBN0120;
+
+ int N0110Counter = userlandMagicSlotAN0110IsValid + userlandMagicSlotBN0110IsValid;
+ int N0120Counter = userlandMagicSlotAN0120IsValid + userlandMagicSlotBN0120IsValid;
+
+ // At least one slot indicate N0110 and none N0120
+ if ((N0110Counter > 0) && (N0120Counter == 0))
+ {
+ return 1;
+ }
+
+ // At least one slot indicate N0120 and none N0110
+ if ((N0120Counter > 0) && (N0110Counter == 0))
+ {
+ return 2;
+ }
+
+ // In case where both matched, choose the one with most matches (for example,
+ // if slot data made a false positive (should not happen unless someone flash
+ // the wrong firmware on a calculator))
+ if (N0110Counter > N0120Counter)
+ {
+ return 1;
+ }
+ if (N0120Counter > N0110Counter)
+ {
+ return 2;
+ }
+
+ // The remaining cases is equality (no match or as much matches). In both
+ // cases, we cannot know
+ return 0;
+}
+
+uint32_t *extapp_userlandAddress()
+{
+ // Get the model
+ const uint8_t model = extapp_calculatorModel();
+
+ if (model == 1)
+ {
+ return (uint32_t *)0x20000008;
+ }
+ if (model == 2)
+ {
+ return (uint32_t *)0x24000008;
+ }
+
+ // We don't know for other cases, so we suppose (arbitrary) that it's an
+ // N0110/N0115 because N0120 is not the latest model and is much less used
+ // than N0110/N0115
+ return (uint32_t *)0x24000008;
+}
\ No newline at end of file
diff --git a/games/tetris/numworks_utils/src/storage/storage.h b/games/tetris/numworks_utils/src/storage/storage.h
new file mode 100644
index 00000000..149328e4
--- /dev/null
+++ b/games/tetris/numworks_utils/src/storage/storage.h
@@ -0,0 +1,25 @@
+// code from https://framagit.org/Yaya.Cout/numworks-extapp-storage (thanks !)
+// copyright (c) 2021-2022 Numworks
+
+#ifndef STORAGE_H
+#define STORAGE_H
+
+#include <stdint.h>
+#include <stddef.h>
+#include <stdbool.h>
+
+uint32_t reverse32(uint32_t value);
+bool extapp_fileExists(const char *filename);
+char *extapp_fileRead(const char *filename, size_t *len);
+bool extapp_fileWrite(const char *filename, const char *content, size_t len);
+bool extapp_fileErase(const char *filename);
+uint32_t extapp_size();
+uint32_t extapp_address();
+uint32_t extapp_used();
+uint32_t *extapp_nextFree();
+bool extapp_isValid(const uint32_t *address);
+// Return the calculator model : 0 is unknown, 1 is N0110/N0115, 2 is N0120
+uint8_t extapp_calculatorModel();
+uint32_t *extapp_userlandAddress();
+
+#endif
diff --git a/games/tetris/numworks_utils/src/utils.rs b/games/tetris/numworks_utils/src/utils.rs
new file mode 100644
index 00000000..e0f29cb9
--- /dev/null
+++ b/games/tetris/numworks_utils/src/utils.rs
@@ -0,0 +1,147 @@
+/// Here are some useful functions that should not have to be remade every time.
+/// There are also some useful constants, that some would argue should be in the graphical file.
+use heapless::String;
+
+use crate::eadk::display::{self, SCREEN_HEIGHT, SCREEN_WIDTH};
+use crate::eadk::{keyboard, random, Point};
+
+// Those constants have been found by hand and seem to not be perfect.
+
+/// Width in pixels of a large character
+pub const LARGE_CHAR_WIDTH: u16 = 10;
+/// Width in pixels of a small character
+pub const SMALL_CHAR_WIDTH: u16 = 7;
+/// Height in pixels of a large character
+pub const LARGE_CHAR_HEIGHT: u16 = 18;
+/// Height in pixels of a small character
+pub const SMALL_CHAR_HEIGHT: u16 = 14;
+
+/// This center is the upper left corner of the 4 pixels that make the center
+pub const CENTER: Point = Point::new(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2);
+
+/// Returns the left x coordinate that centers the given string
+pub fn get_centered_text_x_coordo(string: &str, large: bool) -> u16 {
+ match (display::SCREEN_WIDTH).checked_sub(get_string_pixel_size(string, large)) {
+ x @ Some(1_u16..=u16::MAX) => x.unwrap() / 2,
+ None | Some(0) => 0,
+ }
+}
+
+/// Returns the size IN PIXELS, on the screen, of the given string
+pub fn get_string_pixel_size(string: &str, large: bool) -> u16 {
+ string
+ .chars()
+ .filter(|p| p.is_ascii_alphanumeric() || *p == ' ' || p.is_ascii_punctuation())
+ .count() as u16
+ * (if large {
+ LARGE_CHAR_WIDTH
+ } else {
+ SMALL_CHAR_WIDTH
+ })
+}
+
+#[inline]
+/// Gives a [random] integer between a and b (excluded)
+pub fn randint(a: u32, b: u32) -> u32 {
+ if a == b {
+ 0
+ } else {
+ random() % (b - a) + a
+ }
+}
+
+/// Blocks the program until *nothing* is pressed.
+pub fn wait_for_no_keydown() {
+ loop {
+ let keyboard_state = keyboard::scan();
+ if !keyboard_state.any_down() {
+ break;
+ }
+ }
+}
+
+#[inline]
+/// Takes a decimal (from [include_bytes!]) and returns its value as a ascii number.
+/// Used to read images parameters.
+pub fn decimal_to_ascii_number(number: u8) -> Option<u8> {
+ if !((48..=57).contains(&number)) {
+ // not (48 <= number <= 57) == not an ascii number
+ None
+ } else {
+ Some(number - 48)
+ }
+}
+
+// Reads a text and returns the u32 associated with it. WARNING : does not care about overflow.
+// If the first character isn't a number, returns None. Else, stops at the first non-number character.
+pub fn text_to_u32(text: &str) -> Option<u32> {
+ let mut chars = text.chars().skip_while(|p| p.is_whitespace());
+ let c = chars.next()?;
+ let mut res = decimal_to_ascii_number(c as u8)? as u32;
+ let mut c2 = chars.next();
+ if c2.is_none() {
+ return Some(res);
+ }
+ while let Some(x) = decimal_to_ascii_number(c2.unwrap() as u8) {
+ res = res * 10 + x as u32;
+ c2 = chars.next();
+ if c2.is_none() {
+ return Some(res);
+ }
+ }
+ Some(res)
+}
+
+/// Returns the string corresponding to the decimal number given.
+pub fn string_from_u16(number: u16) -> String<6> {
+ let mut text: String<6> = String::new();
+ if number == 0 {
+ text.push('0').unwrap();
+ text.truncate(1);
+ text.push('\0').unwrap();
+ return text;
+ }
+ let mut n = number;
+ let mut cpt = 0;
+ while n != 0 {
+ text.push(((n % 10) as u8 + b'0') as char).unwrap();
+ n /= 10;
+ cpt += 1;
+ }
+ text.truncate(cpt);
+
+ let mut second_text: String<6> = String::new();
+ for i in (0..cpt).rev() {
+ second_text.push(text.chars().nth(i).unwrap()).unwrap();
+ }
+ second_text.truncate(cpt);
+ second_text.push('\0').unwrap();
+ second_text
+}
+
+/// Returns the string corresponding to the decimal number given.
+pub fn string_from_u32(number: u32) -> String<11> {
+ let mut text: String<11> = String::new();
+ if number == 0 {
+ text.push('0').unwrap();
+ text.truncate(1);
+ text.push('\0').unwrap();
+ return text;
+ }
+ let mut n = number;
+ let mut cpt = 0;
+ while n != 0 {
+ text.push(((n % 10) as u8 + b'0') as char).unwrap();
+ n /= 10;
+ cpt += 1;
+ }
+ text.truncate(cpt);
+
+ let mut second_text: String<11> = String::new();
+ for i in (0..cpt).rev() {
+ second_text.push(text.chars().nth(i).unwrap()).unwrap();
+ }
+ second_text.truncate(cpt);
+ second_text.push('\0').unwrap();
+ second_text
+}
diff --git a/games/tetris/numworks_utils/src/widgets.rs b/games/tetris/numworks_utils/src/widgets.rs
new file mode 100644
index 00000000..c6230262
--- /dev/null
+++ b/games/tetris/numworks_utils/src/widgets.rs
@@ -0,0 +1 @@
+pub mod numberinput;
diff --git a/games/tetris/numworks_utils/src/widgets/numberinput.rs b/games/tetris/numworks_utils/src/widgets/numberinput.rs
new file mode 100644
index 00000000..ebd7dd18
--- /dev/null
+++ b/games/tetris/numworks_utils/src/widgets/numberinput.rs
@@ -0,0 +1,180 @@
+use crate::{
+ eadk::{display::push_rect_uniform, key, keyboard, Point, Rect},
+ graphical::{draw_string_cfg, ColorConfig},
+ utils::{
+ string_from_u32, wait_for_no_keydown, LARGE_CHAR_HEIGHT, LARGE_CHAR_WIDTH,
+ SMALL_CHAR_HEIGHT, SMALL_CHAR_WIDTH,
+ },
+};
+
+/// Allows entering a number between min and max. Will block everything as long as it is not confirmed.
+/// Will print the input at the given position, and use the ColorConfig to choose the colors.
+pub fn numberinput(
+ default: u32,
+ min: u32,
+ max: u32,
+ large: bool,
+ pos: Point,
+ c: &ColorConfig,
+) -> u32 {
+ // Max digits : 10
+ push_rect_uniform(
+ Rect {
+ x: pos.x,
+ y: pos.y,
+ width: 10 * {
+ if large {
+ LARGE_CHAR_WIDTH
+ } else {
+ SMALL_CHAR_WIDTH
+ }
+ } + 6,
+ height: {
+ if large {
+ LARGE_CHAR_HEIGHT
+ } else {
+ SMALL_CHAR_HEIGHT
+ }
+ } + 6,
+ },
+ c.alt,
+ );
+ push_rect_uniform(
+ Rect {
+ x: pos.x + 3,
+ y: pos.y + 3,
+ width: 10 * {
+ if large {
+ LARGE_CHAR_WIDTH
+ } else {
+ SMALL_CHAR_WIDTH
+ }
+ },
+ height: {
+ if large {
+ LARGE_CHAR_HEIGHT
+ } else {
+ SMALL_CHAR_HEIGHT
+ }
+ },
+ },
+ c.bckgrd,
+ );
+ let mut current_value = default;
+ let mut current_string = string_from_u32(default);
+ draw_string_cfg(
+ &current_string,
+ Point {
+ x: pos.x + 3,
+ y: pos.y + 3,
+ },
+ large,
+ c,
+ false,
+ );
+ wait_for_no_keydown();
+ loop {
+ let scan = keyboard::scan();
+ if scan.key_down(key::OK) {
+ break;
+ }
+ let mut temp = current_value;
+
+ fn try_push_digit(temp: u32, digit: u32, max: u32) -> u32 {
+ temp.checked_mul(10)
+ .and_then(|v| v.checked_add(digit))
+ .filter(|&v| v <= max)
+ .unwrap_or(temp)
+ }
+
+ if scan.key_down(key::ZERO) {
+ temp = try_push_digit(temp, 0, max);
+ } else if scan.key_down(key::ONE) {
+ temp = try_push_digit(temp, 1, max);
+ } else if scan.key_down(key::TWO) {
+ temp = try_push_digit(temp, 2, max);
+ } else if scan.key_down(key::THREE) {
+ temp = try_push_digit(temp, 3, max);
+ } else if scan.key_down(key::FOUR) {
+ temp = try_push_digit(temp, 4, max);
+ } else if scan.key_down(key::FIVE) {
+ temp = try_push_digit(temp, 5, max);
+ } else if scan.key_down(key::SIX) {
+ temp = try_push_digit(temp, 6, max);
+ } else if scan.key_down(key::SEVEN) {
+ temp = try_push_digit(temp, 7, max);
+ } else if scan.key_down(key::EIGHT) {
+ temp = try_push_digit(temp, 8, max);
+ } else if scan.key_down(key::NINE) {
+ temp = try_push_digit(temp, 9, max);
+ } else if scan.key_down(key::UP) {
+ temp = temp.checked_add(1).filter(|&v| v <= max).unwrap_or(temp)
+ } else if scan.key_down(key::DOWN) {
+ temp = temp.checked_sub(1).filter(|&v| v >= min).unwrap_or(temp)
+ } else if scan.key_down(key::BACKSPACE) {
+ temp /= 10;
+ }
+
+ if temp != current_value {
+ current_value = temp;
+ current_string = string_from_u32(current_value);
+ push_rect_uniform(
+ Rect {
+ x: pos.x + 3,
+ y: pos.y + 3,
+ width: 10 * {
+ if large {
+ LARGE_CHAR_WIDTH
+ } else {
+ SMALL_CHAR_WIDTH
+ }
+ },
+ height: {
+ if large {
+ LARGE_CHAR_HEIGHT
+ } else {
+ SMALL_CHAR_HEIGHT
+ }
+ },
+ },
+ c.bckgrd,
+ );
+ draw_string_cfg(
+ &current_string,
+ Point {
+ x: pos.x + 3,
+ y: pos.y + 3,
+ },
+ large,
+ c,
+ false,
+ );
+ }
+
+ if scan.any_down() {
+ wait_for_no_keydown();
+ }
+ }
+ push_rect_uniform(
+ Rect {
+ x: pos.x,
+ y: pos.y,
+ width: 10 * {
+ if large {
+ LARGE_CHAR_WIDTH
+ } else {
+ SMALL_CHAR_WIDTH
+ }
+ } + 6,
+ height: {
+ if large {
+ LARGE_CHAR_HEIGHT
+ } else {
+ SMALL_CHAR_HEIGHT
+ }
+ } + 6,
+ },
+ c.bckgrd,
+ );
+ current_value
+}
diff --git a/games/tetris/tetris/.cargo/config.toml b/games/tetris/tetris/.cargo/config.toml
new file mode 100644
index 00000000..b3277d84
--- /dev/null
+++ b/games/tetris/tetris/.cargo/config.toml
@@ -0,0 +1,13 @@
+[target.thumbv7em-none-eabihf]
+runner = 'npx --yes -- nwlink install-nwa'
+rustflags = [
+ "-C",
+ "link-arg=--relocatable",
+ "-C",
+ "link-arg=-no-gc-sections",
+ "-C",
+ "target-cpu=cortex-m7",
+]
+
+[build]
+target = "thumbv7em-none-eabihf"
diff --git a/games/tetris/tetris/Cargo.lock b/games/tetris/tetris/Cargo.lock
new file mode 100644
index 00000000..0bb7690c
--- /dev/null
+++ b/games/tetris/tetris/Cargo.lock
@@ -0,0 +1,70 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "byteorder"
+version = "1.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
+
+[[package]]
+name = "cc"
+version = "1.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8293772165d9345bdaaa39b45b2109591e63fe5e6fbc23c6ff930a048aa310b"
+dependencies = [
+ "shlex",
+]
+
+[[package]]
+name = "hash32"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606"
+dependencies = [
+ "byteorder",
+]
+
+[[package]]
+name = "heapless"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad"
+dependencies = [
+ "hash32",
+ "stable_deref_trait",
+]
+
+[[package]]
+name = "nppm_decoder"
+version = "0.1.0"
+
+[[package]]
+name = "numworks_utils"
+version = "0.3.0"
+dependencies = [
+ "cc",
+ "heapless",
+]
+
+[[package]]
+name = "shlex"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
+
+[[package]]
+name = "tetris"
+version = "0.2.0"
+dependencies = [
+ "heapless",
+ "nppm_decoder",
+ "numworks_utils",
+]
diff --git a/games/tetris/tetris/Cargo.toml b/games/tetris/tetris/Cargo.toml
new file mode 100644
index 00000000..4c798e79
--- /dev/null
+++ b/games/tetris/tetris/Cargo.toml
@@ -0,0 +1,26 @@
+[package]
+name = "tetris"
+version = "0.2.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[lib]
+crate-type = ["rlib", "staticlib"]
+
+[profile.release]
+opt-level = "s"
+lto = true
+codegen-units = 1
+panic = "abort"
+debug = false
+
+[profile.dev]
+panic = "abort"
+
+[dependencies]
+heapless = "0.8.0"
+numworks_utils = { path = "../numworks_utils", version = "*" }
+
+[build-dependencies]
+nppm_decoder = { path = "../nppm_decoder", version = "*" }
diff --git a/games/tetris/tetris/build.rs b/games/tetris/tetris/build.rs
new file mode 100644
index 00000000..48d66e83
--- /dev/null
+++ b/games/tetris/tetris/build.rs
@@ -0,0 +1,24 @@
+use std::process::Command;
+
+const TILESIZE: u16 = 12;
+
+fn main() {
+ // Turn icon.png into icon.nwi
+ println!("cargo:rerun-if-changed=src/data/icon.png");
+ let output = Command::new("nwlink")
+ .args(["png-nwi", "src/data/icon.png", "target/icon.nwi"])
+ .output()
+ .expect("Failure to launch process");
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // Turn image.ppm into image.nppm
+ nppm_decoder::decoder::extract_data_from_file(
+ "src/data/image.ppm",
+ "src/data/image.nppm",
+ TILESIZE,
+ );
+}
diff --git a/games/tetris/tetris/src/data/icon.png b/games/tetris/tetris/src/data/icon.png
new file mode 100644
index 00000000..c330d48f
Binary files /dev/null and b/games/tetris/tetris/src/data/icon.png differ
diff --git a/games/tetris/tetris/src/data/image.ppm b/games/tetris/tetris/src/data/image.ppm
new file mode 100644
index 00000000..639f3d31
Binary files /dev/null and b/games/tetris/tetris/src/data/image.ppm differ
diff --git a/games/tetris/tetris/src/data/tetris_controls.txt b/games/tetris/tetris/src/data/tetris_controls.txt
new file mode 100644
index 00000000..7dd82b18
--- /dev/null
+++ b/games/tetris/tetris/src/data/tetris_controls.txt
@@ -0,0 +1,16 @@
+
+ HOW TO PLAY
+
+ - <LEFT> and <RIGHT> to move
+ - <DOWN> for soft drop
+ - <UP> for hard drop
+ - <OK> & <BACK> to rotate left and right
+ - <BACKSPACE> (<clear>) to hold the tetri
+ - <SHIFT> to pause
+
+ Every full line disappears
+ Get more points by clearing
+ multiple lines at once !
+ The level increases every 10 lines.
+ You lose when the stack reaches the top.
+ Hold the tetri to keep it for later !
\ No newline at end of file
diff --git a/games/tetris/tetris/src/data/tiles.png b/games/tetris/tetris/src/data/tiles.png
new file mode 100644
index 00000000..0399e1ed
Binary files /dev/null and b/games/tetris/tetris/src/data/tiles.png differ
diff --git a/games/tetris/tetris/src/game_tetris.rs b/games/tetris/tetris/src/game_tetris.rs
new file mode 100644
index 00000000..2f19872d
--- /dev/null
+++ b/games/tetris/tetris/src/game_tetris.rs
@@ -0,0 +1,662 @@
+use heapless::Vec;
+use numworks_utils::{
+ eadk::{
+ display::{self, wait_for_vblank},
+ key, keyboard, timing, Color,
+ },
+ graphical::{draw_centered_string, ColorConfig},
+ menu::{
+ pause_menu, selection,
+ settings::{write_values_to_file, Setting},
+ start_menu_with_save, MenuConfig, StartMenuAction,
+ },
+ storage::save::{delete_save, write_save, SaveSlotMode},
+ utils::{randint, LARGE_CHAR_HEIGHT},
+};
+
+use crate::{
+ tetriminos::{get_initial_tetri, get_random_bag, get_wall_kicks_data, SignedPoint, Tetrimino},
+ tetris_save::{TetrisSave, TetrisSaveState},
+ ui_tetris::{
+ draw_blank_line, draw_block, draw_held_tetrimino, draw_level, draw_lines_number,
+ draw_next_tetrimino, draw_score, draw_stable_ui, draw_tetrimino,
+ },
+};
+
+pub const COLOR_CONFIG: ColorConfig = ColorConfig {
+ text: Color::from_rgb888(251, 251, 219),
+ bckgrd: Color::from_rgb888(20, 20, 20),
+ alt: Color::RED,
+};
+
+pub const BACKGROUND_GRAY: Color = Color::from_rgb888(100, 100, 100);
+pub const BACKGROUND_DARK_GRAY: Color = Color::from_rgb888(70, 70, 70);
+
+fn vis_addon() {
+ let mut tetri = get_random_bag().swap_remove(0);
+ let rotation = randint(0, 3);
+ tetri.rotation = rotation as u8;
+ tetri.pos = SignedPoint { x: 4, y: 5 };
+ draw_tetrimino(&tetri, false);
+}
+
+pub fn start() {
+ let mut opt: [&mut Setting; 3] = [
+ &mut Setting {
+ name: "Ghost Piece\0",
+ choice: 0,
+ values: Vec::from_slice(&[1, 0]).unwrap(),
+ texts: Vec::from_slice(&["Yes\0", "No\0"]).unwrap(),
+ user_modifiable: true,
+ fixed_values: true,
+ },
+ &mut Setting {
+ name: "Starting Level\0",
+ choice: 0,
+ values: Vec::from_slice(&[1, 1, 9]).unwrap(),
+ texts: Vec::new(),
+ user_modifiable: true,
+ fixed_values: false,
+ },
+ &mut Setting {
+ name: "High Score\0",
+ choice: 0,
+ values: Vec::from_slice(&[0, 0, 999999]).unwrap(),
+ texts: Vec::new(),
+ user_modifiable: false,
+ fixed_values: false,
+ },
+ ];
+
+ loop {
+ let menu_action: StartMenuAction<TetrisSave> = start_menu_with_save(
+ "TETRIS \0",
+ &mut opt,
+ &COLOR_CONFIG,
+ vis_addon,
+ include_str!("./data/tetris_controls.txt"),
+ "tetris",
+ SaveSlotMode::Single,
+ );
+
+ match menu_action {
+ StartMenuAction::Continue(save, _) => {
+ let mut pending_save = Some(save);
+ loop {
+ let mut high_score = opt[2].get_setting_value();
+ let action = game(
+ opt[0].get_setting_value() != 0,
+ opt[1].get_setting_value() as u16,
+ &mut high_score,
+ pending_save.take(), // Consumes save on first run; None on replay
+ );
+ opt[2].set_value(high_score);
+ write_values_to_file(&mut opt, "tetris");
+ if action == 2 {
+ return;
+ } else if action == 1 {
+ break;
+ }
+ }
+ }
+ StartMenuAction::NewGame(_) => loop {
+ let mut high_score = opt[2].get_setting_value();
+ let action = game(
+ opt[0].get_setting_value() != 0,
+ opt[1].get_setting_value() as u16,
+ &mut high_score,
+ None,
+ );
+ opt[2].set_value(high_score);
+ write_values_to_file(&mut opt, "tetris");
+ if action == 2 {
+ return;
+ } else if action == 1 {
+ break;
+ }
+ },
+ StartMenuAction::Exit => return,
+ }
+ }
+}
+
+pub struct Grid {
+ pub grid: [[Option<u8>; PLAYFIELD_HEIGHT as usize]; PLAYFIELD_WIDTH as usize],
+}
+
+impl Grid {
+ pub fn new() -> Self {
+ Self {
+ grid: [[None; (PLAYFIELD_HEIGHT as usize)]; (PLAYFIELD_WIDTH as usize)],
+ }
+ }
+
+ pub fn get_color_at(&self, x: i16, y: i16) -> Option<u8> {
+ if (y < 0) || (x < 0) || (x as u16 >= PLAYFIELD_WIDTH) || (y as u16 >= PLAYFIELD_HEIGHT) {
+ None
+ } else {
+ self.grid[x as usize][y as usize]
+ }
+ }
+
+ pub fn set_color_at(&mut self, x: i16, y: i16, c: u8) {
+ if (y >= 0) && (x >= 0) && (x < PLAYFIELD_WIDTH as i16) && (y < PLAYFIELD_HEIGHT as i16) {
+ self.grid[x as usize][y as usize] = Some(c);
+ draw_block(x as u16, y as u16, c as u16);
+ }
+ }
+
+ pub fn remove_color_at(&mut self, x: i16, y: i16) {
+ if (y >= 0) && (x >= 0) && (x < PLAYFIELD_WIDTH as i16) && (y < PLAYFIELD_HEIGHT as i16) {
+ self.grid[x as usize][y as usize] = None;
+ }
+ }
+
+ pub fn remove_line(&mut self, y: i16) {
+ if (y >= 0) && (y < PLAYFIELD_HEIGHT as i16) {
+ for x in 0..PLAYFIELD_WIDTH {
+ self.remove_color_at(x as i16, y);
+ }
+ }
+ }
+}
+
+static FALL_SPEED_DATA: [f32; 19] = [
+ 0.01667, 0.021017, 0.026977, 0.035256, 0.04693, 0.06361, 0.0879, 0.1236, 0.1775, 0.2598, 0.388,
+ 0.59, 0.92, 1.46, 2.36, 3.91, 6.61, 11.43, 20.0,
+];
+
+/// Size of a block in pixels: 20 rows fill the whole height of the screen.
+pub const CASE_SIZE: u16 = 12;
+pub const PLAYFIELD_HEIGHT: u16 = 20;
+pub const PLAYFIELD_WIDTH: u16 = 10;
+
+const ROTATE_SPEED: u64 = 150;
+const DELAYED_AUTO_SHIFT: u64 = 167;
+const AUTO_MOVE_SPEED: u64 = 33;
+const SOFT_DROP_SPEED: u64 = 33;
+
+const LEFT_KEY: u32 = key::LEFT;
+const RIGHT_KEY: u32 = key::RIGHT;
+const SOFT_DROP_KEY: u32 = key::DOWN;
+const HARD_DROP_KEY: u32 = key::UP;
+const PAUSE_KEY: u32 = key::SHIFT;
+const RIGHT_ROTATION_KEY: u32 = key::BACK;
+const LEFT_ROTATION_KEY: u32 = key::OK;
+const HOLD_KEY: u32 = key::BACKSPACE;
+
+const DEATH_MENU: MenuConfig = MenuConfig {
+ choices: &["Replay\0", "Menu\0", "Exit\0"],
+ rect_margins: (20, 10),
+ dimensions: (CASE_SIZE * (PLAYFIELD_WIDTH + 2), CASE_SIZE * 10),
+ offset: (0, 60),
+ back_key_return: 2,
+};
+
+struct Timings {
+ pub fall: u64,
+ pub side_move: u64,
+ pub rotate: u64,
+}
+
+struct Buttons {
+ pub side_move: bool,
+ pub rotate: bool,
+ pub soft_drop: bool,
+}
+
+impl Buttons {
+ fn check_and_clear(&mut self) {
+ let keyboard_state = keyboard::scan();
+ if self.side_move
+ && !(keyboard_state.key_down(LEFT_KEY) || keyboard_state.key_down(RIGHT_KEY))
+ {
+ self.side_move = false;
+ }
+ if self.rotate
+ && !(keyboard_state.key_down(RIGHT_ROTATION_KEY)
+ || keyboard_state.key_down(LEFT_ROTATION_KEY))
+ {
+ self.rotate = false;
+ }
+ if self.soft_drop && !keyboard_state.key_down(SOFT_DROP_KEY) {
+ self.soft_drop = false;
+ }
+ }
+}
+
+struct Blockers {
+ pub hold: bool,
+ pub hard_drop: bool,
+ pub soft_drop: bool,
+}
+
+impl Blockers {
+ fn check_and_clear(&mut self, buttons: &Buttons) {
+ let keyboard_state = keyboard::scan();
+ if self.soft_drop && !buttons.soft_drop {
+ self.soft_drop = false;
+ }
+ if self.hard_drop && !keyboard_state.key_down(HARD_DROP_KEY) {
+ self.hard_drop = false;
+ }
+ }
+}
+
+pub fn game(
+ ghost_piece: bool,
+ starting_level: u16,
+ high_score: &mut u32,
+ initial_save: Option<TetrisSave>,
+) -> u8 {
+ let mut timings = Timings {
+ fall: timing::millis(),
+ side_move: timing::millis(),
+ rotate: timing::millis(),
+ };
+ let mut buttons = Buttons {
+ side_move: false,
+ rotate: false,
+ soft_drop: false,
+ };
+ let mut blockers = Blockers {
+ hold: false,
+ hard_drop: false,
+ soft_drop: false,
+ };
+
+ let mut grid: Grid;
+ let mut score: u32;
+ let mut level: u16;
+ let mut level_lines: u16;
+ let mut random_bag: Vec<Tetrimino, 7>;
+ let mut current_tetri: Tetrimino;
+ let mut next_tetri: Tetrimino;
+ let mut held_tetri: Option<Tetrimino>;
+
+ if let Some(save) = initial_save {
+ let state = save.unpack();
+ grid = state.grid;
+ score = state.score;
+ level = state.level;
+ level_lines = state.level_lines;
+ current_tetri = get_initial_tetri(state.current_piece);
+ next_tetri = get_initial_tetri(state.next_piece);
+ held_tetri = state.held_piece.map(get_initial_tetri);
+ random_bag = state.bag;
+ } else {
+ grid = Grid::new();
+ score = 0;
+ level = starting_level;
+ level_lines = 0;
+ random_bag = get_random_bag();
+ current_tetri = random_bag.swap_remove(0);
+ next_tetri = random_bag.swap_remove(0);
+ held_tetri = None;
+ }
+
+ let mut fall_speed: u64 =
+ (1000.0 / (FALL_SPEED_DATA[(level.max(1) as usize - 1).min(18)] * 60.0)) as u64;
+ let mut auto_repeat_move: bool = false;
+
+ // Draw restored board
+ draw_stable_ui(level, level_lines, score, *high_score);
+ for x in 0..PLAYFIELD_WIDTH {
+ for y in 0..PLAYFIELD_HEIGHT {
+ if let Some(c) = grid.get_color_at(x as i16, y as i16) {
+ draw_block(x, y, c as u16);
+ }
+ }
+ }
+ draw_tetrimino(&current_tetri, false);
+ draw_ghost_tetri(&current_tetri, &grid, false, ghost_piece);
+ draw_next_tetrimino(&next_tetri);
+ if let Some(h) = &held_tetri {
+ draw_held_tetrimino(h);
+ }
+
+ 'gameloop: loop {
+ let keyboard_state = keyboard::scan();
+ if (!buttons.side_move
+ || (auto_repeat_move && (timings.side_move + AUTO_MOVE_SPEED < timing::millis())))
+ && (keyboard_state.key_down(RIGHT_KEY) || keyboard_state.key_down(LEFT_KEY))
+ {
+ let direction: i16 = if keyboard_state.key_down(LEFT_KEY) {
+ -1
+ } else {
+ 1
+ };
+ if can_move(&current_tetri, (direction, 0), &grid) {
+ draw_tetrimino(&current_tetri, true);
+ draw_ghost_tetri(&current_tetri, &grid, true, ghost_piece);
+
+ current_tetri.pos.x += direction;
+
+ draw_ghost_tetri(&current_tetri, &grid, false, ghost_piece);
+ draw_tetrimino(&current_tetri, false);
+
+ timings.side_move = timing::millis();
+ buttons.side_move = true;
+ }
+ } else if (!buttons.rotate || (timings.rotate + ROTATE_SPEED < timing::millis()))
+ && (keyboard_state.key_down(RIGHT_ROTATION_KEY)
+ || keyboard_state.key_down(LEFT_ROTATION_KEY))
+ {
+ let new_tetri = can_rotate(
+ keyboard_state.key_down(RIGHT_ROTATION_KEY),
+ &current_tetri,
+ &grid,
+ );
+ if new_tetri.is_some() {
+ draw_tetrimino(&current_tetri, true);
+ draw_ghost_tetri(&current_tetri, &grid, true, ghost_piece);
+
+ current_tetri = new_tetri.unwrap();
+
+ draw_ghost_tetri(&current_tetri, &grid, false, ghost_piece);
+ draw_tetrimino(&current_tetri, false);
+
+ timings.rotate = timing::millis();
+ buttons.rotate = true;
+ }
+ } else if !blockers.hold && keyboard_state.key_down(HOLD_KEY) {
+ let temp = current_tetri.clone();
+ blockers.hold = true;
+
+ draw_tetrimino(&current_tetri, true);
+ draw_ghost_tetri(&current_tetri, &grid, true, ghost_piece);
+
+ if held_tetri.is_some() {
+ current_tetri = get_initial_tetri(held_tetri.unwrap().tetri);
+ held_tetri = Some(temp.clone());
+ } else {
+ if random_bag.is_empty() {
+ random_bag = get_random_bag();
+ }
+ current_tetri = next_tetri.clone();
+ next_tetri = random_bag.swap_remove(0);
+ draw_next_tetrimino(&next_tetri);
+ held_tetri = Some(temp.clone());
+ }
+ draw_ghost_tetri(&current_tetri, &grid, false, ghost_piece);
+ draw_tetrimino(&current_tetri, false);
+ draw_held_tetrimino(held_tetri.as_ref().unwrap());
+ }
+
+ if (timings.fall
+ + if (!buttons.soft_drop && keyboard_state.key_down(SOFT_DROP_KEY))
+ || (buttons.soft_drop && !blockers.soft_drop)
+ {
+ SOFT_DROP_SPEED
+ } else {
+ fall_speed
+ }
+ < timing::millis())
+ || (!blockers.hard_drop && keyboard_state.key_down(HARD_DROP_KEY))
+ {
+ if !blockers.hard_drop && keyboard_state.key_down(HARD_DROP_KEY) {
+ blockers.hard_drop = true;
+ draw_tetrimino(&current_tetri, true);
+ if can_move(&current_tetri, (0, 1), &grid) {
+ while can_move(&current_tetri, (0, 1), &grid) {
+ current_tetri.pos.y += 1;
+ }
+ }
+ } else if !buttons.soft_drop && keyboard_state.key_down(SOFT_DROP_KEY) {
+ buttons.soft_drop = true;
+ }
+
+ let need_to_fall = can_move(&current_tetri, (0, 1), &grid);
+ if need_to_fall {
+ draw_tetrimino(&current_tetri, true);
+ current_tetri.pos.y += 1;
+ draw_tetrimino(&current_tetri, false);
+ } else {
+ let mut death: bool = true;
+ for p in current_tetri.get_blocks_grid_pos() {
+ grid.set_color_at(p.x, p.y, current_tetri.color);
+ if death && p.y >= 0 {
+ death = false;
+ }
+ }
+ if death {
+ delete_save("tetris", None); // Deletes record immediately
+ draw_centered_string(" GAME OVER \0", 10, true, &COLOR_CONFIG, true);
+ if score > *high_score {
+ *high_score = score;
+ draw_centered_string(
+ " NEW HIGH SCORE! \0",
+ 10 + LARGE_CHAR_HEIGHT + 2,
+ true,
+ &COLOR_CONFIG,
+ true,
+ );
+ }
+ let action = selection(&COLOR_CONFIG, &DEATH_MENU, false);
+ // Ensure the save is deleted regardless of selection option chosen
+ delete_save("tetris", None);
+ break 'gameloop action;
+ }
+
+ let clear_lines_y = get_clear_lines(&current_tetri, &grid);
+ if !clear_lines_y.is_empty() {
+ score = add_points(&clear_lines_y, level, score);
+ let temp_level = level;
+ (level_lines, level) = add_lines(
+ clear_lines_y.len() as u16,
+ level,
+ level_lines,
+ starting_level,
+ );
+ if level != temp_level && level <= 19 {
+ fall_speed = (1000.0 / (FALL_SPEED_DATA[level as usize - 1] * 60.0)) as u64;
+ }
+ bring_lines_down(&clear_lines_y, &mut grid);
+ }
+
+ if random_bag.is_empty() {
+ random_bag = get_random_bag();
+ }
+ current_tetri = next_tetri.clone();
+ next_tetri = random_bag.swap_remove(0);
+
+ // Lock complete: save game state immediately
+ let save_state = TetrisSaveState {
+ grid,
+ score,
+ level,
+ level_lines,
+ current_piece: current_tetri.tetri,
+ next_piece: next_tetri.tetri,
+ held_piece: held_tetri.as_ref().map(|h| h.tetri),
+ bag: random_bag.clone(),
+ };
+ write_save("tetris", None, &TetrisSave::pack(&save_state));
+ grid = save_state.grid;
+
+ draw_ghost_tetri(&current_tetri, &grid, false, ghost_piece);
+ draw_tetrimino(&current_tetri, false);
+ draw_next_tetrimino(&next_tetri);
+
+ blockers.hold = false;
+ if buttons.soft_drop {
+ blockers.soft_drop = true;
+ }
+ }
+ timings.fall = timing::millis();
+ }
+
+ buttons.check_and_clear();
+ if auto_repeat_move && !buttons.side_move {
+ auto_repeat_move = false;
+ } else if buttons.side_move && (timings.side_move + DELAYED_AUTO_SHIFT < timing::millis()) {
+ auto_repeat_move = true;
+ }
+ blockers.check_and_clear(&buttons);
+
+ if keyboard_state.key_down(PAUSE_KEY) {
+ let action = pause_menu(&COLOR_CONFIG, 0);
+ if action != 0 {
+ return action;
+ } else {
+ wait_for_vblank();
+ draw_stable_ui(level, level_lines, score, *high_score);
+ wait_for_vblank();
+ for x in 0..PLAYFIELD_WIDTH {
+ for y in 0..PLAYFIELD_HEIGHT {
+ let c = grid.get_color_at(x as i16, y as i16);
+ if let Some(c_) = c {
+ draw_block(x, y, c_ as u16);
+ }
+ }
+ }
+ wait_for_vblank();
+ draw_tetrimino(&current_tetri, false);
+ draw_ghost_tetri(&current_tetri, &grid, false, ghost_piece);
+ if let Some(held_tetri_) = &held_tetri {
+ draw_held_tetrimino(held_tetri_);
+ }
+ draw_next_tetrimino(&next_tetri);
+ }
+ }
+ display::wait_for_vblank();
+ }
+}
+
+fn bring_lines_down(clear_lines_y: &Vec<i16, 4>, grid: &mut Grid) {
+ for i in clear_lines_y {
+ grid.remove_line(*i);
+ draw_blank_line(*i as u16);
+ }
+ for (i, e) in clear_lines_y.iter().enumerate() {
+ for j in (0..*e + i as i16).rev() {
+ for x in 0..PLAYFIELD_WIDTH {
+ let last_color = grid.get_color_at(x as i16, j);
+ if let Some(last_color_) = last_color {
+ grid.set_color_at(x as i16, j + 1, last_color_);
+ }
+ }
+ grid.remove_line(j);
+ draw_blank_line(j as u16);
+ }
+ }
+}
+
+fn draw_ghost_tetri(tetri: &Tetrimino, grid: &Grid, clear: bool, do_it: bool) {
+ if do_it && can_move(tetri, (0, 1), grid) {
+ let mut ghost_tetri = tetri.clone();
+ ghost_tetri.color = 8;
+ while can_move(&ghost_tetri, (0, 1), grid) {
+ ghost_tetri.pos.y += 1;
+ }
+ draw_tetrimino(&ghost_tetri, clear);
+ }
+}
+
+fn check_line(p: i16, grid: &Grid) -> bool {
+ for i in 0..PLAYFIELD_WIDTH {
+ if grid.get_color_at(i as i16, p).is_none() {
+ return false;
+ }
+ }
+ true
+}
+
+fn get_clear_lines(tetri: &Tetrimino, grid: &Grid) -> Vec<i16, 4> {
+ let mut clear_lines_y = Vec::<i16, 4>::new();
+ for pos in tetri.get_blocks_grid_pos() {
+ if check_line(pos.y, grid) && !clear_lines_y.contains(&(pos.y)) {
+ let mut new_index: usize = 0;
+ for e in clear_lines_y.iter() {
+ if (pos.y) < *e {
+ break;
+ }
+ new_index += 1;
+ }
+ clear_lines_y.insert(new_index, pos.y).unwrap();
+ }
+ }
+ clear_lines_y.reverse();
+ clear_lines_y
+}
+
+fn add_points(cleared_lines: &Vec<i16, 4>, level: u16, points: u32) -> u32 {
+ let mut sum: u32 = 0;
+
+ if cleared_lines.len() == 1 {
+ sum += 40
+ } else if cleared_lines.len() == 4 {
+ sum += 1200
+ } else if cleared_lines.len() == 2 {
+ if cleared_lines[0].abs_diff(cleared_lines[1]) == 1 {
+ sum += 100
+ } else {
+ sum += 80
+ }
+ } else {
+ if (cleared_lines[0].abs_diff(cleared_lines[1]) == 1)
+ && (cleared_lines[1].abs_diff(cleared_lines[2]) == 1)
+ {
+ sum += 300
+ } else {
+ sum += 140
+ }
+ }
+
+ draw_score((sum * (level as u32)) + points, false);
+ (sum * (level as u32)) + points
+}
+
+fn can_move(future_tetri: &Tetrimino, direction: (i16, i16), grid: &Grid) -> bool {
+ for pos in future_tetri.get_blocks_grid_pos() {
+ if (pos.x + direction.0 < 0)
+ || (pos.x + direction.0 > PLAYFIELD_WIDTH as i16 - 1)
+ || (pos.y + direction.1 > PLAYFIELD_HEIGHT as i16 - 1)
+ || grid
+ .get_color_at(pos.x + direction.0, pos.y + direction.1)
+ .is_some()
+ {
+ return false;
+ }
+ }
+ true
+}
+
+fn add_lines(number: u16, level: u16, current_lines: u16, starting_level: u16) -> (u16, u16) {
+ let max_lines: u16 = if level == starting_level {
+ starting_level * 10
+ } else {
+ 10
+ };
+
+ let new_number = (current_lines + number) % max_lines;
+ draw_lines_number(new_number);
+
+ if current_lines + number >= max_lines {
+ draw_level(level + 1);
+ return (new_number, level + 1);
+ }
+ (new_number, level)
+}
+
+fn can_rotate(right: bool, tetri: &Tetrimino, grid: &Grid) -> Option<Tetrimino> {
+ let mut rotated_tetri = tetri.clone();
+ if right {
+ rotated_tetri.rotate_right();
+ } else {
+ rotated_tetri.rotate_left();
+ }
+ if can_move(&rotated_tetri, (0, 0), grid) {
+ Some(rotated_tetri)
+ } else {
+ let kicks = get_wall_kicks_data(tetri, right);
+ for k in kicks {
+ if can_move(&rotated_tetri, *k, grid) {
+ rotated_tetri.pos.x += k.0;
+ rotated_tetri.pos.y += k.1;
+ return Some(rotated_tetri);
+ }
+ }
+ None
+ }
+}
diff --git a/games/tetris/tetris/src/lib.rs b/games/tetris/tetris/src/lib.rs
new file mode 100644
index 00000000..98095042
--- /dev/null
+++ b/games/tetris/tetris/src/lib.rs
@@ -0,0 +1,80 @@
+#![no_std]
+
+mod game_tetris;
+mod tetriminos;
+mod tetris_save;
+mod ui_tetris;
+
+use game_tetris::BACKGROUND_GRAY;
+use heapless::String;
+use numworks_utils::{
+ eadk::{display::push_rect_uniform, Color, Point, Rect},
+ utils::CENTER,
+};
+use tetriminos::{I_SHAPE, J_SHAPE, L_SHAPE, O_SHAPE, S_SHAPE, T_SHAPE, Z_SHAPE};
+use ui_tetris::draw_tetrimino;
+
+pub use game_tetris::start;
+
+/// Entry point when Tetris runs inside the NumPlay launcher.
+#[no_mangle]
+pub extern "C" fn np_tetris_main() -> i32 {
+ game_tetris::start();
+ 0
+}
+
+pub fn thumbnail(_: Point) {
+ push_rect_uniform(
+ Rect {
+ x: CENTER.x - 75,
+ y: 15,
+ width: 150,
+ height: 100,
+ },
+ Color::BLACK,
+ );
+ push_rect_uniform(
+ Rect {
+ x: CENTER.x - 72,
+ y: 18,
+ width: 144,
+ height: 94,
+ },
+ BACKGROUND_GRAY,
+ );
+ let mut tetri = T_SHAPE;
+ tetri.pos.y = 8;
+ tetri.pos.x = 6;
+ draw_tetrimino(&tetri, false);
+ let mut tetri2 = S_SHAPE;
+ tetri2.pos.y = 8;
+ tetri2.pos.x = 4;
+ draw_tetrimino(&tetri2, false);
+ let mut tetri3 = O_SHAPE;
+ tetri3.pos.y = 7;
+ tetri3.pos.x = 2;
+ draw_tetrimino(&tetri3, false);
+ let mut tetri4 = L_SHAPE;
+ tetri4.pos.y = 6;
+ tetri4.pos.x = 3;
+ draw_tetrimino(&tetri4, false);
+ let mut tetri5 = I_SHAPE;
+ tetri5.pos.y = 3;
+ tetri5.pos.x = 8;
+ tetri5.rotation = 1;
+ draw_tetrimino(&tetri5, false);
+ let mut tetri6 = Z_SHAPE;
+ tetri6.pos.y = 5;
+ tetri6.pos.x = 5;
+ tetri6.rotation = 1;
+ draw_tetrimino(&tetri6, false);
+ let mut tetri7 = J_SHAPE;
+ tetri7.pos.y = 4;
+ tetri7.pos.x = 3;
+ tetri7.rotation = 3;
+ draw_tetrimino(&tetri7, false);
+}
+
+pub fn get_name() -> String<15> {
+ String::try_from("Tetris\0").unwrap()
+}
diff --git a/games/tetris/tetris/src/main.rs b/games/tetris/tetris/src/main.rs
new file mode 100644
index 00000000..7499e9b2
--- /dev/null
+++ b/games/tetris/tetris/src/main.rs
@@ -0,0 +1,25 @@
+#![no_std]
+#![no_main]
+
+pub mod tetriminos;
+pub mod ui_tetris;
+
+pub mod game_tetris;
+pub mod tetris_save;
+
+#[used]
+#[link_section = ".rodata.eadk_app_name"]
+pub static EADK_APP_NAME: [u8; 7] = *b"TETRIS\0";
+
+#[used]
+#[link_section = ".rodata.eadk_api_level"]
+pub static EADK_APP_API_LEVEL: u32 = 0;
+
+#[used]
+#[link_section = ".rodata.eadk_app_icon"]
+pub static EADK_APP_ICON: [u8; 3030] = *include_bytes!("../target/icon.nwi");
+
+#[no_mangle]
+pub fn main() {
+ game_tetris::start();
+}
diff --git a/games/tetris/tetris/src/tetriminos.rs b/games/tetris/tetris/src/tetriminos.rs
new file mode 100644
index 00000000..d6534949
--- /dev/null
+++ b/games/tetris/tetris/src/tetriminos.rs
@@ -0,0 +1,300 @@
+use heapless::Vec;
+
+use numworks_utils::utils::randint;
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum TetriType {
+ T = 0,
+ J = 1,
+ Z = 2,
+ O = 3,
+ S = 4,
+ L = 5,
+ I = 6,
+}
+
+impl TetriType {
+ pub fn from_u8(v: u8) -> Option<Self> {
+ match v {
+ 0 => Some(Self::T),
+ 1 => Some(Self::J),
+ 2 => Some(Self::Z),
+ 3 => Some(Self::O),
+ 4 => Some(Self::S),
+ 5 => Some(Self::L),
+ 6 => Some(Self::I),
+ _ => None,
+ }
+ }
+}
+
+/// Exactly like a point, but signed
+#[derive(Clone, Copy, Debug)]
+pub struct SignedPoint {
+ pub x: i16,
+ pub y: i16,
+}
+
+impl SignedPoint {
+ /*
+ pub const fn from_unsigned_point(p : Point) -> SignedPoint{
+ return SignedPoint { x: p.x as i16, y: p.y as i16 }
+ }
+ */
+}
+
+/// Represents a shape, its type, rotation (0-3), color
+#[derive(Clone)]
+pub struct Tetrimino {
+ pub tetri: TetriType,
+ pub rotation: u8,
+ pub color: u8, // position in Tilemap
+ pub pos: SignedPoint,
+}
+
+impl Tetrimino {
+ /// Rotate the tetri to the right
+ pub fn rotate_right(&mut self) {
+ // needs tp check if can be rotated or not lol
+ if self.rotation < 3 {
+ self.rotation += 1
+ } else {
+ self.rotation = 0
+ }
+ }
+
+ /// Rotate the tetri to the left
+ pub fn rotate_left(&mut self) {
+ if self.rotation > 0 {
+ self.rotation -= 1
+ } else {
+ self.rotation = 3
+ }
+ }
+
+ /// Returns the position of all blocks of the tetri
+ /// The center of the tetri is (0, 0) every time, so need to call something like tetri.pos.x + x to get absolute pos
+ pub fn get_blocks(&self) -> [(i16, i16); 4] {
+ match self.tetri {
+ TetriType::T => match self.rotation {
+ 0 => [(0, 0), (-1, 0), (1, 0), (0, -1)],
+ 1 => [(0, 0), (1, 0), (0, 1), (0, -1)],
+ 2 => [(0, 0), (-1, 0), (1, 0), (0, 1)],
+ _ => [(0, 0), (-1, 0), (0, 1), (0, -1)],
+ },
+ TetriType::J => match self.rotation {
+ 0 => [(-1, 0), (-1, -1), (0, 0), (1, 0)],
+ 1 => [(0, 1), (0, 0), (0, -1), (1, -1)],
+ 2 => [(-1, 0), (0, 0), (1, 0), (1, 1)],
+ _ => [(-1, 1), (0, 1), (0, 0), (0, -1)],
+ },
+ TetriType::Z => match self.rotation {
+ 0 => [(-1, -1), (0, -1), (0, 0), (1, 0)],
+ 1 => [(0, 0), (0, 1), (1, 0), (1, -1)],
+ 2 => [(-1, 0), (0, 0), (0, 1), (1, 1)],
+ _ => [(-1, 1), (-1, 0), (0, 0), (0, -1)],
+ },
+ TetriType::O => [(0, 0), (-1, 0), (-1, 1), (0, 1)],
+ TetriType::S => match self.rotation {
+ 0 => [(-1, 0), (0, 0), (0, -1), (1, -1)],
+ 1 => [(0, 0), (1, 1), (1, 0), (0, -1)],
+ 2 => [(1, 0), (0, 0), (0, 1), (-1, 1)],
+ _ => [(-1, -1), (-1, 0), (0, 0), (0, 1)],
+ },
+ TetriType::L => match self.rotation {
+ 0 => [(-1, 0), (0, 0), (1, 0), (1, -1)],
+ 1 => [(1, 1), (0, 1), (0, 0), (0, -1)],
+ 2 => [(-1, 0), (-1, 1), (0, 0), (1, 0)],
+ _ => [(0, 1), (0, 0), (0, -1), (-1, -1)],
+ },
+ TetriType::I => match self.rotation {
+ 0 => [(0, 0), (1, 0), (-1, 0), (-2, 0)],
+ 1 => [(0, 0), (0, -1), (0, 1), (0, 2)],
+ 2 => [(0, 1), (1, 1), (-1, 1), (-2, 1)],
+ _ => [(-1, 0), (-1, -1), (-1, 1), (-1, 2)],
+ },
+ }
+ }
+
+ pub fn get_blocks_grid_pos(&self) -> [SignedPoint; 4] {
+ let mut res = Vec::<SignedPoint, 4>::new();
+ for e in self.get_blocks().iter() {
+ res.push(SignedPoint {
+ x: e.0 + self.pos.x,
+ y: e.1 + self.pos.y,
+ })
+ .unwrap();
+ }
+ res.into_array().unwrap()
+ }
+}
+
+pub const T_SHAPE: Tetrimino = Tetrimino {
+ tetri: TetriType::T,
+ rotation: 0,
+ color: 6,
+ pos: SignedPoint { x: 5, y: -1 },
+};
+pub const J_SHAPE: Tetrimino = Tetrimino {
+ tetri: TetriType::J,
+ rotation: 0,
+ color: 1,
+ pos: SignedPoint { x: 5, y: -1 },
+};
+pub const Z_SHAPE: Tetrimino = Tetrimino {
+ tetri: TetriType::Z,
+ rotation: 0,
+ color: 4,
+ pos: SignedPoint { x: 5, y: -1 },
+};
+pub const O_SHAPE: Tetrimino = Tetrimino {
+ tetri: TetriType::O,
+ rotation: 0,
+ color: 0,
+ pos: SignedPoint { x: 5, y: -2 },
+};
+pub const S_SHAPE: Tetrimino = Tetrimino {
+ tetri: TetriType::S,
+ rotation: 0,
+ color: 3,
+ pos: SignedPoint { x: 5, y: -1 },
+};
+pub const L_SHAPE: Tetrimino = Tetrimino {
+ tetri: TetriType::L,
+ rotation: 0,
+ color: 2,
+ pos: SignedPoint { x: 5, y: -1 },
+};
+pub const I_SHAPE: Tetrimino = Tetrimino {
+ tetri: TetriType::I,
+ rotation: 0,
+ color: 5,
+ pos: SignedPoint { x: 5, y: -1 },
+};
+
+pub fn get_initial_tetri(tetritype: TetriType) -> Tetrimino {
+ match tetritype {
+ TetriType::T => T_SHAPE,
+ TetriType::J => J_SHAPE,
+ TetriType::Z => Z_SHAPE,
+ TetriType::O => O_SHAPE,
+ TetriType::S => S_SHAPE,
+ TetriType::L => L_SHAPE,
+ TetriType::I => I_SHAPE,
+ }
+}
+
+pub fn get_random_bag() -> Vec<Tetrimino, 7> {
+ let mut res = Vec::<Tetrimino, 7>::new();
+ let mut tetri_list: Vec<Tetrimino, 7> = Vec::from_slice(&[
+ T_SHAPE, J_SHAPE, O_SHAPE, L_SHAPE, I_SHAPE, S_SHAPE, Z_SHAPE,
+ ])
+ .unwrap();
+
+ for _ in 0..6 {
+ unsafe {
+ res.push(tetri_list.swap_remove(randint(0, tetri_list.len() as u32 - 1) as usize))
+ .unwrap_unchecked();
+ }
+ }
+
+ unsafe {
+ res.push(tetri_list.swap_remove(0)).unwrap_unchecked();
+ }
+
+ res
+}
+
+/// Tetris.wiki uses an inversed y axis compared to me, so all y values are inversed.
+static WALL_KICK_TABLE: [(i16, i16); 32] = [
+ (-1, 0),
+ (-1, -1),
+ (0, 2),
+ (-1, 2),
+ (1, 0),
+ (1, 1),
+ (0, -2),
+ (1, -2),
+ (1, 0),
+ (1, 1),
+ (0, -2),
+ (1, -2),
+ (-1, 0),
+ (-1, -1),
+ (0, 2),
+ (-1, 2),
+ (1, 0),
+ (1, -1),
+ (0, 2),
+ (1, 2),
+ (-1, 0),
+ (-1, 1),
+ (0, -2),
+ (-1, -2),
+ (-1, 0),
+ (-1, 1),
+ (0, -2),
+ (-1, -2),
+ (1, 0),
+ (1, -1),
+ (0, 2),
+ (1, 2),
+];
+
+static I_WALL_KICKS_TABLE: [(i16, i16); 32] = [
+ (-2, 0),
+ (1, 0),
+ (1, -2),
+ (-2, 1),
+ (2, 0),
+ (-1, 0),
+ (2, -1),
+ (-1, 2),
+ (-1, 0),
+ (2, 0),
+ (-1, -2),
+ (2, 1),
+ (-2, 0),
+ (1, 0),
+ (-2, -1),
+ (1, 1),
+ (2, 0),
+ (-1, 0),
+ (2, -1),
+ (-1, 1),
+ (1, 0),
+ (-2, 0),
+ (1, -2),
+ (-2, 1),
+ (-2, 0),
+ (1, 0),
+ (-2, -1),
+ (1, 2),
+ (2, 0),
+ (-1, 0),
+ (-1, -2),
+ (2, 1),
+];
+
+pub fn get_wall_kicks_data(tetri: &Tetrimino, right: bool) -> &[(i16, i16)] {
+ let table: &[(i16, i16); 32] = match tetri.tetri {
+ TetriType::I => &I_WALL_KICKS_TABLE,
+ TetriType::O => return &[],
+ _ => &WALL_KICK_TABLE,
+ };
+ if right {
+ match tetri.rotation {
+ 0 => &table[0..4],
+ 1 => &table[8..12],
+ 2 => &table[16..20],
+ _ => &table[24..28],
+ }
+ } else {
+ match tetri.rotation {
+ 0 => &table[28..32],
+ 3 => &table[20..24],
+ 2 => &table[12..16],
+ _ => &table[4..8],
+ }
+ }
+}
diff --git a/games/tetris/tetris/src/tetris_save.rs b/games/tetris/tetris/src/tetris_save.rs
new file mode 100644
index 00000000..901fb495
--- /dev/null
+++ b/games/tetris/tetris/src/tetris_save.rs
@@ -0,0 +1,173 @@
+use heapless::Vec;
+use numworks_utils::storage::{
+ save::{GameSave, SaveField, MAX_SAVE_FIELDS},
+ MAX_STORAGE_VALUES,
+};
+
+use crate::{
+ game_tetris::{Grid, PLAYFIELD_HEIGHT, PLAYFIELD_WIDTH},
+ tetriminos::{get_initial_tetri, TetriType, Tetrimino},
+};
+
+pub const TETRIS_SAVE_WORDS: usize = 25;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct TetrisSave {
+ pub raw: [u32; TETRIS_SAVE_WORDS],
+}
+
+impl GameSave for TetrisSave {
+ fn to_words(&self) -> Vec<u32, MAX_STORAGE_VALUES> {
+ let mut v = Vec::new();
+ for &w in &self.raw {
+ let _ = v.push(w);
+ }
+ v
+ }
+
+ fn from_words(words: &[u32]) -> Option<Self> {
+ if words.len() >= TETRIS_SAVE_WORDS {
+ let mut raw = [0u32; TETRIS_SAVE_WORDS];
+ raw.copy_from_slice(&words[..TETRIS_SAVE_WORDS]);
+ Some(Self { raw })
+ } else {
+ None
+ }
+ }
+
+ fn describe_fields(&self) -> Vec<SaveField, MAX_SAVE_FIELDS> {
+ let mut fields = Vec::new();
+ let _ = fields.push(SaveField {
+ name: "Current Score\0",
+ min: 0,
+ max: 999999,
+ value: self.raw[20],
+ });
+ let _ = fields.push(SaveField {
+ name: "Current Level\0",
+ min: 1,
+ max: 20,
+ value: (self.raw[21] & 0xFFFF),
+ });
+ fields
+ }
+
+ fn update_from_fields(&mut self, fields: &[SaveField]) {
+ if fields.len() >= 2 {
+ self.raw[20] = fields[0].value;
+ self.raw[21] = (self.raw[21] & 0xFFFF_0000) | (fields[1].value & 0xFFFF);
+ }
+ }
+}
+
+pub struct TetrisSaveState {
+ pub grid: Grid,
+ pub score: u32,
+ pub level: u16,
+ pub level_lines: u16,
+ pub current_piece: TetriType,
+ pub next_piece: TetriType,
+ pub held_piece: Option<TetriType>,
+ pub bag: Vec<Tetrimino, 7>,
+}
+
+impl TetrisSave {
+ pub fn pack(state: &TetrisSaveState) -> Self {
+ let mut raw = [0u32; TETRIS_SAVE_WORDS];
+
+ // 1. Pack Grid: 200 cells into raw[0..20] (10 cells per word, 3 bits each)
+ // 0 = empty, 1..=7 = color + 1
+ let mut cell_idx = 0;
+ for y in 0..PLAYFIELD_HEIGHT as usize {
+ for x in 0..PLAYFIELD_WIDTH as usize {
+ let code = match state.grid.grid[x][y] {
+ None => 0u32,
+ Some(c) => (c as u32 + 1) & 0x07,
+ };
+ let word_idx = cell_idx / 10;
+ let shift = (cell_idx % 10) * 3;
+ raw[word_idx] |= code << shift;
+ cell_idx += 1;
+ }
+ }
+
+ // 2. Score
+ raw[20] = state.score;
+
+ // 3. Level & Lines
+ raw[21] = (state.level as u32) | ((state.level_lines as u32) << 16);
+
+ // 4. Current, Next, Held pieces (4 bits each in raw[22])
+ let cur = state.current_piece as u32 & 0x0F;
+ let nxt = state.next_piece as u32 & 0x0F;
+ let hld = match state.held_piece {
+ None => 0x0F,
+ Some(p) => p as u32 & 0x0F,
+ };
+ raw[22] = cur | (nxt << 4) | (hld << 8);
+
+ // 5. Bag contents in raw[23]
+ let mut bag_word = state.bag.len() as u32 & 0x0F;
+ for (i, t) in state.bag.iter().enumerate() {
+ let p_code = t.tetri as u32 & 0x07;
+ bag_word |= p_code << (4 + i * 3);
+ }
+ raw[23] = bag_word;
+
+ TetrisSave { raw }
+ }
+
+ pub fn unpack(&self) -> TetrisSaveState {
+ let mut grid = Grid::new();
+
+ // 1. Unpack Grid
+ let mut cell_idx = 0;
+ for y in 0..PLAYFIELD_HEIGHT as usize {
+ for x in 0..PLAYFIELD_WIDTH as usize {
+ let word_idx = cell_idx / 10;
+ let shift = (cell_idx % 10) * 3;
+ let code = (self.raw[word_idx] >> shift) & 0x07;
+ if code > 0 {
+ grid.grid[x][y] = Some((code - 1) as u8);
+ }
+ cell_idx += 1;
+ }
+ }
+
+ // 2. Score, Level, Lines
+ let score = self.raw[20];
+ let level = (self.raw[21] & 0xFFFF) as u16;
+ let level_lines = ((self.raw[21] >> 16) & 0xFFFF) as u16;
+
+ // 3. Current, Next, Held
+ let cur = TetriType::from_u8((self.raw[22] & 0x0F) as u8).unwrap_or(TetriType::T);
+ let nxt = TetriType::from_u8(((self.raw[22] >> 4) & 0x0F) as u8).unwrap_or(TetriType::J);
+ let hld_code = (self.raw[22] >> 8) & 0x0F;
+ let held_piece = if hld_code == 0x0F {
+ None
+ } else {
+ TetriType::from_u8(hld_code as u8)
+ };
+
+ // 4. Bag
+ let bag_len = (self.raw[23] & 0x0F) as usize;
+ let mut bag = Vec::<Tetrimino, 7>::new();
+ for i in 0..bag_len.min(7) {
+ let p_code = ((self.raw[23] >> (4 + i * 3)) & 0x07) as u8;
+ if let Some(t_type) = TetriType::from_u8(p_code) {
+ let _ = bag.push(get_initial_tetri(t_type));
+ }
+ }
+
+ TetrisSaveState {
+ grid,
+ score,
+ level,
+ level_lines,
+ current_piece: cur,
+ next_piece: nxt,
+ held_piece,
+ bag,
+ }
+ }
+}
diff --git a/games/tetris/tetris/src/ui_tetris.rs b/games/tetris/tetris/src/ui_tetris.rs
new file mode 100644
index 00000000..06d3b1ee
--- /dev/null
+++ b/games/tetris/tetris/src/ui_tetris.rs
@@ -0,0 +1,231 @@
+use heapless::String;
+use numworks_utils::{
+ eadk::{
+ display::{push_rect_uniform, wait_for_vblank, SCREEN_HEIGHT, SCREEN_WIDTH},
+ Color, Point, Rect,
+ },
+ graphical::{draw_string_cfg, tiling::Tileset},
+ include_bytes_align_as,
+ utils::{string_from_u32, LARGE_CHAR_WIDTH},
+};
+
+use crate::{
+ game_tetris::{
+ BACKGROUND_DARK_GRAY, BACKGROUND_GRAY, CASE_SIZE, COLOR_CONFIG, PLAYFIELD_HEIGHT,
+ PLAYFIELD_WIDTH,
+ },
+ tetriminos::Tetrimino,
+};
+
+const IMAGE_BYTES: &[u8] = include_bytes_align_as!(Color, "./data/image.nppm");
+
+static TILESET: Tileset = Tileset::new(CASE_SIZE, 10, IMAGE_BYTES);
+
+// Full screen layout: the playfield takes the whole height of the screen, the
+// panels fill the space on both sides.
+/// Left edge of the playfield, in pixels.
+pub const FIELD_X: u16 = (SCREEN_WIDTH - PLAYFIELD_WIDTH * CASE_SIZE) / 2;
+/// Top of the playfield, in pixels.
+pub const FIELD_Y: u16 = (SCREEN_HEIGHT - PLAYFIELD_HEIGHT * CASE_SIZE) / 2;
+const FRAME: u16 = 4;
+const PANEL_W: u16 = 88;
+const PANEL_H: u16 = 110;
+const LEFT_X: u16 = (FIELD_X - FRAME - PANEL_W) / 2;
+const RIGHT_X: u16 = SCREEN_WIDTH - LEFT_X - PANEL_W;
+const TOP_Y: u16 = 6;
+const BOTTOM_Y: u16 = SCREEN_HEIGHT - 6 - PANEL_H;
+const LINE: u16 = 20;
+
+/// Draws a framed panel (outer rectangle given) with its background.
+fn draw_panel(x: u16, y: u16) {
+ push_rect_uniform(
+ Rect {
+ x,
+ y,
+ width: PANEL_W,
+ height: PANEL_H,
+ },
+ BACKGROUND_DARK_GRAY,
+ );
+ push_rect_uniform(
+ Rect {
+ x: x + FRAME,
+ y: y + FRAME,
+ width: PANEL_W - 2 * FRAME,
+ height: PANEL_H - 2 * FRAME,
+ },
+ COLOR_CONFIG.bckgrd,
+ );
+}
+
+/// Draws a label centred in a panel, `row` lines below its top.
+fn draw_label(text: &str, panel_x: u16, panel_y: u16, row: u16) {
+ let chars = text.trim_end_matches('\0').chars().count() as u16;
+ let x = panel_x + (PANEL_W - chars * LARGE_CHAR_WIDTH) / 2;
+ draw_string_cfg(
+ text,
+ Point::new(x, panel_y + FRAME + 4 + row * LINE),
+ true,
+ &COLOR_CONFIG,
+ false,
+ );
+}
+
+/// This draws every UI elements that will never change (rects, titles...)
+pub fn draw_stable_ui(level: u16, level_lines: u16, score: u32, high_score: u32) {
+ wait_for_vblank();
+ push_rect_uniform(
+ Rect {
+ x: 0,
+ y: 0,
+ width: SCREEN_WIDTH,
+ height: SCREEN_HEIGHT,
+ },
+ BACKGROUND_GRAY,
+ );
+ push_rect_uniform(
+ Rect {
+ x: FIELD_X - FRAME,
+ y: 0,
+ width: PLAYFIELD_WIDTH * CASE_SIZE + 2 * FRAME,
+ height: SCREEN_HEIGHT,
+ },
+ BACKGROUND_DARK_GRAY,
+ );
+ TILESET.tiling(
+ Point::new(FIELD_X, FIELD_Y),
+ (PLAYFIELD_WIDTH, PLAYFIELD_HEIGHT),
+ Point::new(7, 0),
+ false,
+ 1,
+ );
+
+ wait_for_vblank();
+ draw_panel(LEFT_X, TOP_Y);
+ draw_panel(LEFT_X, BOTTOM_Y);
+ draw_panel(RIGHT_X, TOP_Y);
+ draw_panel(RIGHT_X, BOTTOM_Y);
+ draw_label("NEXT\0", LEFT_X, TOP_Y, 0);
+ draw_label("HOLD\0", LEFT_X, BOTTOM_Y, 0);
+ draw_label("BEST\0", RIGHT_X, TOP_Y, 0);
+ draw_label("SCORE\0", RIGHT_X, TOP_Y, 2);
+ draw_label("LEVEL\0", RIGHT_X, BOTTOM_Y, 0);
+ draw_label("LINES\0", RIGHT_X, BOTTOM_Y, 2);
+
+ wait_for_vblank();
+ draw_score(high_score, true);
+ draw_score(score, false);
+ draw_level(level);
+ draw_lines_number(level_lines);
+}
+
+/// A number right-padded to 6 characters: zeros for scores, spaces otherwise.
+fn padded(value: u32, zeros: bool) -> String<8> {
+ let mut txt: String<8> = String::new();
+ if value > 999_999 {
+ txt.push_str("999999\0").unwrap();
+ return txt;
+ }
+ let mut digits: String<11> = string_from_u32(value);
+ digits.pop();
+ for _ in 0..(6 - digits.chars().count()) {
+ txt.push(if zeros { '0' } else { ' ' }).unwrap();
+ }
+ txt.push_str(digits.as_str()).unwrap();
+ txt.push('\0').unwrap();
+ txt
+}
+
+pub fn draw_score(score: u32, high_score: bool) {
+ draw_label(
+ padded(score, true).as_str(),
+ RIGHT_X,
+ TOP_Y,
+ if high_score { 1 } else { 3 },
+ );
+}
+
+pub fn draw_level(level: u16) {
+ draw_label(padded(level as u32, false).as_str(), RIGHT_X, BOTTOM_Y, 1);
+}
+
+pub fn draw_lines_number(line: u16) {
+ draw_label(padded(line as u32, false).as_str(), RIGHT_X, BOTTOM_Y, 3);
+}
+
+/// Draws a given tetrimino.
+pub fn draw_tetrimino(tetri: &Tetrimino, clear: bool) {
+ for pos in tetri.get_blocks_grid_pos() {
+ if (pos.x >= 0) & (pos.y >= 0) {
+ draw_block_image(
+ FIELD_X + (pos.x as u16) * CASE_SIZE,
+ FIELD_Y + (pos.y as u16) * CASE_SIZE,
+ if clear { 7 } else { tetri.color as u16 },
+ );
+ }
+ }
+}
+
+/// Draws a piece centred in the preview area of a panel.
+fn draw_preview(tetri: &Tetrimino, panel_y: u16) {
+ let area_y = panel_y + FRAME + LINE + 4;
+ let area_h = PANEL_H - 2 * FRAME - LINE - 4;
+ push_rect_uniform(
+ Rect {
+ x: LEFT_X + FRAME,
+ y: area_y,
+ width: PANEL_W - 2 * FRAME,
+ height: area_h,
+ },
+ COLOR_CONFIG.bckgrd,
+ );
+ // centre the piece's bounding box in the area
+ let blocks = tetri.get_blocks();
+ let (mut x0, mut x1, mut y0, mut y1) = (i16::MAX, i16::MIN, i16::MAX, i16::MIN);
+ for (x, y) in blocks {
+ x0 = x0.min(x);
+ x1 = x1.max(x);
+ y0 = y0.min(y);
+ y1 = y1.max(y);
+ }
+ let case = CASE_SIZE as i16;
+ let origin_x = (LEFT_X + PANEL_W / 2) as i16 - (x1 - x0 + 1) * case / 2 - x0 * case;
+ let origin_y = (area_y + area_h / 2) as i16 - (y1 - y0 + 1) * case / 2 - y0 * case;
+ for (x, y) in blocks {
+ draw_block_image(
+ (origin_x + x * case) as u16,
+ (origin_y + y * case) as u16,
+ tetri.color as u16,
+ );
+ }
+}
+
+pub fn draw_next_tetrimino(tetri: &Tetrimino) {
+ draw_preview(tetri, TOP_Y);
+}
+
+pub fn draw_held_tetrimino(tetri: &Tetrimino) {
+ draw_preview(tetri, BOTTOM_Y);
+}
+
+pub fn draw_blank_line(y: u16) {
+ TILESET.tiling(
+ Point::new(FIELD_X, FIELD_Y + y * CASE_SIZE),
+ (PLAYFIELD_WIDTH, 1),
+ Point::new(7, 0),
+ false,
+ 1,
+ );
+}
+
+fn draw_block_image(abs_x: u16, abs_y: u16, x_map: u16) {
+ TILESET.draw_tile(Point::new(abs_x, abs_y), Point::new(x_map, 0), 1, false);
+}
+
+pub fn draw_block(x: u16, y: u16, color: u16) {
+ draw_block_image(
+ FIELD_X + x * CASE_SIZE,
+ FIELD_Y + y * CASE_SIZE,
+ color,
+ );
+}
diff --git a/launcher/assets/icon.png b/launcher/assets/icon.png
new file mode 100644
index 00000000..83dc929a
Binary files /dev/null and b/launcher/assets/icon.png differ
diff --git a/launcher/src/flash.c b/launcher/src/flash.c
new file mode 100644
index 00000000..178643cf
--- /dev/null
+++ b/launcher/src/flash.c
@@ -0,0 +1,132 @@
+/* Uninstalling a game for real: its block of flash is wiped, which frees the
+ * space it used, and its save files are deleted.
+ *
+ * External flash is erased in 64 KiB sectors. Sectors that lie entirely
+ * inside the game's block are erased; the ends of the block that share a
+ * sector with something else are overwritten with zeros instead (programming
+ * only clears bits, so nothing outside the block is touched and nothing
+ * needs to be buffered or rewritten). The first word is cleared first, so an
+ * interrupted uninstall still leaves the game marked as removed, and the
+ * launcher finishes the job the next time it starts. */
+#include <string.h>
+#include "np.h"
+#include "sys.h"
+
+#define SECTOR 0x10000u
+#define FLASH_BASE 0x90000000u
+
+#if NP_SIMULATOR
+extern bool np_sim_removed[];
+#endif
+
+bool np_uninstall_supported(void) {
+#if NP_SIMULATOR
+ return true;
+#else
+ /* The flash system calls have kept their numbers and arguments since
+ * Epsilon 20; older or unknown software is left alone. */
+ return np_userland() && np_software_major() >= 21;
+#endif
+}
+
+bool np_battery_ok(void) {
+#if NP_SIMULATOR
+ return true;
+#else
+ return np_battery_charging() || np_battery_level() >= 2;
+#endif
+}
+
+#if !NP_SIMULATOR
+/* Epsilon's Ion::Device::Flash::SectorAtAddress: 8 x 4K, 1 x 32K, then 64K. */
+static int sector_index(uint32_t address) { return 8 + (int)((address - FLASH_BASE) >> 16); }
+
+static bool zero_range(uint32_t a, uint32_t b) {
+ static const uint32_t chunk = 256;
+ uint8_t zeros[256]; /* the source must be in RAM, not in the flash being written */
+ memset(zeros, 0, sizeof zeros);
+ while (a < b) {
+ uint32_t n = NP_MIN(chunk - (a % chunk), b - a);
+ bool clean = true;
+ for (uint32_t i = 0; i < n; i++)
+ if (((const volatile uint8_t *)a)[i]) clean = false;
+ if (!clean && !np_flash_write((void *)a, zeros, n)) return false;
+ a += n;
+ }
+ return true;
+}
+
+static bool erased(uint32_t a, uint32_t b) {
+ for (const volatile uint32_t *p = (const volatile uint32_t *)a; (uint32_t)p < b; p++)
+ if (*p != 0xFFFFFFFFu) return false;
+ return true;
+}
+
+static bool zeroed(uint32_t a, uint32_t b) {
+ for (const volatile uint8_t *p = (const volatile uint8_t *)a; (uint32_t)p < b; p++)
+ if (*p) return false;
+ return true;
+}
+
+/* The block must be inside the app area, outside the code running now. */
+static bool range_ok(uint32_t a, uint32_t b) {
+ const np_userland_t *h = np_userland();
+ uint32_t self = (uint32_t)(uintptr_t)&range_ok;
+ return h && a < b && a % 4 == 0 && b % 4 == 0 && a >= h->apps_flash_start && b <= h->apps_flash_end &&
+ !(self >= a && self < b) && b - a < 0x400000;
+}
+
+static int wipe(uint32_t a, uint32_t b, void (*progress)(int, int)) {
+ uint32_t s0 = (a + SECTOR - 1) & ~(SECTOR - 1), s1 = b & ~(SECTOR - 1);
+ if (s1 < s0) s0 = s1 = b; /* the block sits inside one sector */
+ int total = 2 + (int)((s1 - s0) / SECTOR), done = 0;
+ if (progress) progress(done, total);
+ /* 1. the head marker, so the game is gone even if we stop here */
+ if (!zero_range(a, a + 4)) return NP_UNINSTALL_FAILED;
+ if (!zero_range(a + 4, s0)) return NP_UNINSTALL_FAILED;
+ if (progress) progress(++done, total);
+ for (uint32_t s = s0; s < s1; s += SECTOR) {
+ if (!erased(s, s + SECTOR) && !np_flash_erase_sector(sector_index(s))) return NP_UNINSTALL_FAILED;
+ if (progress) progress(++done, total);
+ }
+ if (!zero_range(s1, b)) return NP_UNINSTALL_FAILED;
+ if (progress) progress(++done, total);
+ bool ok = zeroed(a, s0) && erased(s0, s1) && zeroed(s1, b);
+ return ok ? NP_UNINSTALL_OK : NP_UNINSTALL_FAILED;
+}
+#endif
+
+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;
+ for (const char *const *r = g->records; r && *r; r++) np_storage_delete(*r);
+#if NP_SIMULATOR
+ for (int k = 0; k <= 4; k++) {
+ if (progress) progress(k, 4);
+ np_sleep(180);
+ }
+ np_sim_removed[i] = true;
+ return NP_UNINSTALL_OK;
+#else
+ uint32_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);
+#endif
+}
+
+void np_finish_pending_uninstalls(void) {
+#if !NP_SIMULATOR
+ if (!np_uninstall_supported() || !np_battery_ok()) return;
+ for (int i = 0; i < np_game_count; i++) {
+ if (np_game_installed(i)) continue;
+ const np_game_t *g = &np_games[i];
+ uint32_t a = (uint32_t)(uintptr_t)g->begin, b = (uint32_t)(uintptr_t)g->end;
+ if (!range_ok(a, b)) continue;
+ 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;
+ wipe(a, b, 0);
+ }
+#endif
+}
diff --git a/launcher/src/font.h b/launcher/src/font.h
new file mode 100644
index 00000000..1436d19c
--- /dev/null
+++ b/launcher/src/font.h
@@ -0,0 +1,19 @@
+#ifndef NP_FONT_H
+#define NP_FONT_H
+#include <stdint.h>
+
+typedef struct {
+ uint8_t w, h;
+ int8_t x, y; /* offset of the top left pixel from the pen (y from the baseline) */
+ uint8_t advance;
+ uint16_t offset; /* into data: 4-bit coverage, two pixels per byte, row major */
+} np_glyph_t;
+
+typedef struct {
+ uint8_t first, count, ascent, descent;
+ const np_glyph_t *glyphs;
+ const uint8_t *data;
+} np_font_t;
+
+extern const np_font_t np_font_title, np_font_body, np_font_small;
+#endif
diff --git a/launcher/src/font_data.c b/launcher/src/font_data.c
new file mode 100644
index 00000000..85fcfc47
--- /dev/null
+++ b/launcher/src/font_data.c
@@ -0,0 +1,814 @@
+/* Generated by tools/fontgen.py from Nunito (SIL Open Font License 1.1). */
+#include "font.h"
+
+static const uint8_t np_font_title_data[7603] = {
+ 128,222,36,255,207,242,255,29,255,191,224,255,9,252,127,160,255,6,248,79,112,255,2,226,
+ 11,0,0,0,233,61,243,255,58,255,175,144,223,3,231,61,64,238,245,255,10,252,223,255,
+ 159,192,255,220,255,7,250,175,251,95,128,255,136,255,3,246,111,162,8,16,153,1,0,96,
+ 143,48,206,0,0,252,9,248,13,0,241,111,176,175,32,203,255,188,255,93,247,255,255,255,
+ 255,27,199,223,168,255,40,0,252,10,248,13,0,224,127,176,175,0,48,255,4,254,7,128,
+ 252,207,252,223,26,254,255,255,255,255,67,254,140,252,142,6,224,127,176,191,0,32,255,4,
+ 253,8,0,242,30,208,63,0,0,17,0,17,0,0,0,0,64,73,0,0,0,0,0,254,
+ 14,0,0,0,0,240,255,0,0,0,0,182,255,223,57,0,16,252,255,255,255,95,0,250,
+ 255,255,255,255,7,241,255,61,16,131,25,48,255,143,0,0,0,0,242,255,142,20,0,0,
+ 0,252,255,255,223,40,0,32,253,255,255,255,111,0,16,182,254,255,255,47,0,0,0,98,
+ 253,255,6,17,0,0,80,255,127,226,175,70,100,252,255,101,255,255,255,255,255,13,226,255,
+ 255,255,255,45,0,113,235,255,191,6,0,0,0,240,255,0,0,0,0,0,252,12,0,0,
+ 0,0,16,19,0,0,0,0,216,223,8,0,0,228,12,0,0,160,255,255,175,0,0,253,
+ 47,0,0,243,223,213,255,3,112,255,10,0,0,246,143,144,255,6,225,239,2,0,0,247,
+ 143,128,255,7,249,143,0,0,0,246,143,144,255,54,255,29,0,0,0,242,223,213,255,194,
+ 255,69,186,74,0,144,255,255,159,245,191,247,255,255,6,0,216,223,24,253,79,255,142,254,
+ 31,0,0,0,128,255,105,255,9,249,111,0,0,0,242,239,113,255,8,248,127,0,0,0,
+ 250,127,112,255,8,248,127,0,0,64,255,13,64,255,28,252,79,0,0,192,255,4,0,252,
+ 255,255,12,0,0,192,175,0,0,194,255,191,2,0,0,16,21,0,0,0,66,2,0,0,
+ 96,236,223,7,0,0,0,249,255,255,159,0,0,64,255,191,249,255,2,0,112,255,31,192,
+ 255,4,0,96,255,63,225,255,2,0,32,255,207,253,175,32,3,0,248,255,255,28,242,143,
+ 48,253,255,239,1,247,159,227,255,255,255,28,251,111,251,255,115,255,223,255,31,254,207,0,
+ 247,255,255,10,254,239,1,112,255,255,4,250,255,141,216,255,255,62,226,255,255,255,255,255,
+ 223,32,233,255,239,41,228,207,0,0,50,3,0,16,19,231,61,255,175,255,159,253,127,251,
+ 95,248,63,162,8,0,195,27,0,252,95,96,255,63,208,255,13,243,255,9,248,255,6,251,
+ 255,3,253,255,1,255,255,0,255,255,0,254,255,0,253,255,1,251,255,3,248,255,6,244,
+ 255,9,208,255,13,96,255,63,0,252,95,0,195,28,214,8,0,253,95,0,250,223,0,245,
+ 255,6,241,255,11,208,255,31,176,255,63,144,255,111,128,255,127,128,255,127,128,255,127,144,
+ 255,111,176,255,79,208,255,31,241,255,11,245,255,6,250,223,0,253,95,0,214,8,0,0,
+ 134,48,25,0,224,111,253,7,0,248,254,46,48,220,255,239,156,246,255,255,255,14,131,255,
+ 239,36,0,254,233,111,0,176,29,232,4,0,0,49,0,0,0,0,208,111,0,0,0,0,
+ 255,8,0,0,0,240,143,0,0,65,68,255,73,52,208,255,255,255,255,159,253,255,255,255,
+ 255,25,68,244,159,68,3,0,0,255,8,0,0,0,240,143,0,0,0,0,253,6,0,0,
+ 0,16,3,0,0,128,222,52,255,223,243,255,15,232,223,0,248,9,243,46,48,93,0,48,
+ 68,68,1,248,255,255,30,251,255,255,63,179,187,187,8,144,222,51,255,175,243,255,10,249,
+ 61,0,0,16,187,2,0,0,247,111,0,0,192,255,3,0,32,255,13,0,0,246,143,0,
+ 0,176,255,3,0,16,255,13,0,0,246,159,0,0,176,255,4,0,16,255,14,0,0,245,
+ 159,0,0,160,255,5,0,16,254,14,0,0,245,175,0,0,160,255,5,0,0,254,31,0,
+ 0,241,175,0,0,0,115,1,0,0,0,64,235,223,41,0,0,247,255,255,239,4,48,255,
+ 255,255,255,29,160,255,95,145,255,111,224,255,12,16,255,175,242,255,9,0,253,223,243,255,
+ 8,0,252,255,244,255,8,0,251,255,243,255,8,0,252,239,242,255,9,0,253,223,224,255,
+ 13,16,255,175,144,255,111,145,255,95,32,255,255,255,255,13,0,246,255,255,239,3,0,64,
+ 235,223,41,0,0,0,215,159,0,0,0,212,255,255,0,0,144,255,255,255,0,0,245,255,
+ 255,255,0,0,243,191,253,255,0,0,48,4,251,255,0,0,0,0,251,255,0,0,0,0,
+ 251,255,0,0,0,0,251,255,0,0,0,0,251,255,0,0,0,0,251,255,0,0,16,68,
+ 252,255,68,1,226,255,255,255,255,46,243,255,255,255,255,63,128,187,187,187,187,8,64,218,
+ 255,157,3,144,255,255,255,255,4,255,255,255,255,223,128,191,70,230,255,63,0,0,0,248,
+ 255,4,0,0,144,255,47,0,0,32,255,207,0,0,16,253,255,5,0,16,252,255,9,0,
+ 16,252,255,10,0,16,252,255,10,0,0,251,255,10,0,0,247,255,255,255,255,153,255,255,
+ 255,255,255,228,255,255,255,255,9,0,165,253,223,41,0,176,255,255,255,255,4,240,255,255,
+ 255,255,13,128,174,69,230,255,63,0,0,0,128,255,63,0,0,0,176,255,30,0,64,187,
+ 254,255,7,0,208,255,255,175,0,0,160,255,255,255,11,0,0,67,164,255,127,0,0,0,
+ 16,255,191,128,107,2,113,255,191,243,255,255,255,255,127,242,255,255,255,255,28,48,234,255,
+ 255,142,1,0,0,50,35,0,0,0,0,0,178,191,0,0,0,0,192,255,63,0,0,0,
+ 112,255,255,4,0,0,48,255,255,79,0,0,0,252,255,255,4,0,0,247,239,255,79,0,
+ 0,243,207,248,255,4,0,192,255,131,255,79,0,128,255,8,248,255,4,32,255,143,184,255,
+ 159,6,247,255,255,255,255,255,86,255,255,255,255,255,111,80,135,136,251,255,105,0,0,0,
+ 112,255,63,0,0,0,0,194,175,0,0,145,187,187,187,171,1,247,255,255,255,255,7,248,
+ 255,255,255,255,4,248,255,71,68,36,0,248,255,4,0,0,0,248,255,169,171,5,0,248,
+ 255,255,255,191,1,248,255,255,255,255,9,246,223,70,248,255,31,64,4,0,144,255,63,0,
+ 0,0,128,255,63,196,74,1,228,255,31,251,255,255,255,255,10,249,255,255,255,223,2,112,
+ 252,255,239,25,0,0,16,67,3,0,0,0,0,165,254,190,22,0,177,255,255,255,191,0,
+ 251,255,255,255,239,80,255,239,71,149,109,176,255,47,0,0,0,241,255,43,184,90,0,243,
+ 255,234,255,255,10,244,255,255,255,255,111,243,255,207,116,255,207,242,255,47,0,250,239,224,
+ 255,15,0,248,255,160,255,95,16,253,207,48,255,255,236,255,127,0,247,255,255,255,12,0,
+ 80,253,255,159,1,0,0,32,51,1,0,128,187,187,187,187,91,48,255,255,255,255,255,31,
+ 242,255,255,255,255,255,1,116,136,136,251,255,11,0,0,0,209,255,63,0,0,0,112,255,
+ 175,0,0,0,16,254,255,2,0,0,0,249,255,8,0,0,0,242,255,30,0,0,0,176,
+ 255,127,0,0,0,64,255,223,0,0,0,0,252,255,6,0,0,0,245,255,12,0,0,0,
+ 192,255,79,0,0,0,0,250,159,0,0,0,0,0,51,0,0,0,0,0,129,236,239,107,
+ 0,32,254,255,255,255,28,176,255,223,235,255,127,224,255,11,16,254,191,224,255,8,0,252,
+ 175,160,255,110,132,255,111,16,252,255,255,255,9,32,252,255,255,255,6,208,255,207,236,255,
+ 95,245,255,5,16,252,207,247,255,0,0,248,255,246,255,5,16,252,239,242,255,223,236,255,
+ 159,80,255,255,255,255,28,0,146,236,239,107,0,0,145,253,190,5,0,48,254,255,255,175,
+ 0,192,255,255,255,255,8,244,255,25,211,255,31,247,255,1,128,255,111,247,255,1,128,255,
+ 159,245,255,25,227,255,191,225,255,255,255,255,191,96,255,255,191,255,191,0,197,239,57,255,
+ 159,0,0,0,112,255,95,128,56,16,230,255,30,245,255,255,255,255,6,245,255,255,255,143,
+ 0,96,253,255,207,5,0,0,32,51,1,0,0,32,87,16,254,143,243,255,27,254,127,32,
+ 87,0,0,0,0,0,0,233,61,243,255,58,255,175,144,223,3,32,103,17,254,191,243,255,
+ 31,254,191,32,103,1,0,0,0,0,0,232,77,243,255,61,255,255,128,254,13,128,159,48,
+ 239,2,211,5,0,0,0,48,233,7,0,16,199,255,207,0,164,255,255,191,67,253,255,223,
+ 39,0,254,239,74,0,0,224,255,158,3,0,0,212,255,255,124,1,0,64,250,255,255,58,
+ 0,0,113,253,255,11,0,0,0,148,126,116,136,136,136,120,226,255,255,255,255,191,251,255,
+ 255,255,255,7,0,0,0,0,0,65,68,68,68,68,208,255,255,255,255,159,253,255,255,255,
+ 255,26,68,68,68,68,4,193,108,1,0,0,0,243,255,175,4,0,0,112,253,255,223,23,
+ 0,0,64,234,255,255,26,0,0,16,198,255,111,0,0,16,182,255,111,0,48,233,255,255,
+ 26,96,253,255,223,39,0,243,255,175,4,0,0,193,124,1,0,0,0,32,200,254,157,2,
+ 245,255,255,255,62,251,255,255,255,191,247,108,84,254,255,16,0,0,252,239,0,0,80,255,
+ 143,0,0,227,255,28,0,0,251,159,0,0,0,255,11,0,0,0,254,4,0,0,0,50,
+ 0,0,0,48,186,5,0,0,208,255,47,0,0,224,255,63,0,0,128,255,12,0,0,0,
+ 50,0,0,0,0,48,200,254,222,90,0,0,0,0,178,255,255,255,255,223,4,0,0,228,
+ 255,74,1,33,214,255,5,0,227,223,3,0,0,0,144,239,2,192,239,2,113,171,21,87,
+ 192,159,64,255,6,210,255,255,252,15,245,14,249,14,176,255,140,253,223,32,255,210,175,48,
+ 255,11,48,255,10,240,79,254,8,246,95,0,242,143,16,255,243,143,112,255,4,80,255,5,
+ 243,31,254,9,246,127,16,252,79,128,207,192,191,32,255,207,254,255,156,255,5,247,47,96,
+ 255,255,104,255,255,8,16,254,10,48,119,3,48,119,3,0,112,255,7,0,0,0,0,0,
+ 0,0,144,255,75,0,0,64,187,0,0,0,112,255,239,188,252,255,13,0,0,0,32,216,
+ 255,255,223,24,0,0,0,0,0,16,67,19,0,0,0,0,0,0,0,230,110,0,0,0,
+ 0,0,32,255,255,3,0,0,0,0,144,255,255,10,0,0,0,0,242,255,255,47,0,0,
+ 0,0,248,223,253,159,0,0,0,16,254,127,247,239,1,0,0,112,255,30,225,255,8,0,
+ 0,225,255,9,144,255,30,0,0,246,255,3,48,255,127,0,0,253,255,255,255,255,223,0,
+ 80,255,255,255,255,255,255,6,192,255,255,255,255,255,255,12,244,255,7,0,0,112,255,79,
+ 249,239,1,0,0,16,254,175,245,127,0,0,0,0,246,111,16,1,0,0,0,0,16,1,
+ 146,187,187,187,122,2,144,255,255,255,255,255,6,251,255,255,255,255,255,179,255,15,0,161,
+ 255,127,251,255,0,0,244,255,183,255,15,0,161,255,47,251,255,255,255,255,94,176,255,255,
+ 255,255,191,2,251,255,187,203,255,239,178,255,15,0,64,255,159,251,255,0,0,241,255,187,
+ 255,15,0,113,255,175,251,255,255,255,255,255,148,255,255,255,255,255,7,145,187,187,187,138,
+ 2,0,0,16,183,254,206,57,0,80,254,255,255,255,95,80,255,255,255,255,255,25,254,255,
+ 125,68,215,62,247,255,28,0,0,0,192,255,95,0,0,0,0,254,255,1,0,0,0,240,
+ 255,15,0,0,0,0,254,255,1,0,0,0,192,255,95,0,0,0,0,247,255,29,0,0,
+ 0,16,254,255,125,68,216,62,80,255,255,255,255,255,10,80,254,255,255,255,111,0,16,183,
+ 254,206,57,0,146,187,187,171,89,1,0,144,255,255,255,255,239,7,0,251,255,255,255,255,
+ 255,11,176,255,79,68,182,255,255,7,251,255,0,0,96,255,239,177,255,15,0,0,192,255,
+ 79,251,255,0,0,0,249,255,183,255,15,0,0,128,255,127,251,255,0,0,0,249,255,183,
+ 255,15,0,0,192,255,79,251,255,0,0,112,255,239,176,255,79,68,182,255,255,7,251,255,
+ 255,255,255,255,10,144,255,255,255,255,239,7,0,146,187,187,187,89,1,0,0,146,187,187,
+ 187,187,149,255,255,255,255,223,251,255,255,255,255,186,255,79,68,68,3,251,255,0,0,0,
+ 176,255,15,0,0,0,251,255,255,255,223,178,255,255,255,255,95,251,255,255,255,223,178,255,
+ 15,0,0,0,251,255,0,0,0,176,255,15,0,0,0,251,255,255,255,255,168,255,255,255,
+ 255,223,211,255,255,255,255,8,145,187,187,187,187,148,255,255,255,255,191,251,255,255,255,255,
+ 184,255,79,68,68,3,251,255,0,0,0,176,255,15,0,0,0,251,255,187,187,139,176,255,
+ 255,255,255,63,251,255,255,255,239,178,255,79,68,68,2,251,255,0,0,0,176,255,15,0,
+ 0,0,251,255,0,0,0,176,255,15,0,0,0,246,175,0,0,0,0,50,0,0,0,0,
+ 0,0,166,253,239,123,1,0,211,255,255,255,255,46,64,255,255,255,255,255,95,209,255,239,
+ 72,100,233,28,246,255,29,0,0,0,0,251,255,6,0,0,0,0,254,255,2,16,119,119,
+ 6,255,255,0,144,255,255,111,254,255,1,128,255,255,143,252,255,4,0,67,252,143,248,255,
+ 11,0,0,251,143,242,255,191,20,32,252,143,128,255,255,255,255,255,127,0,248,255,255,255,
+ 255,111,0,48,234,255,255,207,7,0,0,0,50,35,0,0,212,126,0,0,0,212,126,250,
+ 239,0,0,0,251,239,251,255,0,0,0,251,255,251,255,0,0,0,251,255,251,255,0,0,
+ 0,251,255,251,255,68,68,68,252,255,251,255,255,255,255,255,255,251,255,255,255,255,255,255,
+ 251,255,255,255,255,255,255,251,255,0,0,0,251,255,251,255,0,0,0,251,255,251,255,0,
+ 0,0,251,255,251,255,0,0,0,251,255,250,239,0,0,0,250,239,212,126,0,0,0,212,
+ 126,212,126,250,239,251,255,251,255,251,255,251,255,251,255,251,255,251,255,251,255,251,255,251,
+ 255,251,255,250,239,212,126,0,0,231,77,0,0,254,191,0,0,255,191,0,0,255,191,0,
+ 0,255,191,0,0,255,191,0,0,255,191,0,0,255,191,0,0,255,191,0,0,255,191,0,
+ 0,255,191,0,80,255,175,194,255,255,111,245,255,255,12,193,255,141,1,212,126,0,0,80,
+ 237,181,255,14,0,96,255,191,251,255,0,80,255,255,181,255,15,64,255,255,6,251,255,48,
+ 254,255,6,176,255,47,254,255,7,0,251,255,253,255,7,0,176,255,255,255,63,0,0,251,
+ 255,251,255,46,0,176,255,31,252,255,29,0,251,255,16,253,255,28,176,255,15,32,253,255,
+ 11,251,255,0,32,254,255,169,255,14,0,48,254,255,212,126,0,0,64,253,8,162,75,0,
+ 0,0,160,255,14,0,0,0,251,255,0,0,0,176,255,15,0,0,0,251,255,0,0,0,
+ 176,255,15,0,0,0,251,255,0,0,0,176,255,15,0,0,0,251,255,0,0,0,176,255,
+ 15,0,0,0,251,255,0,0,0,176,255,79,68,68,3,251,255,255,255,255,169,255,255,255,
+ 255,223,211,255,255,255,239,7,194,175,0,0,0,0,177,191,112,255,127,0,0,0,144,255,
+ 63,248,255,30,0,0,48,255,255,132,255,255,9,0,0,251,255,79,248,255,255,2,0,245,
+ 255,255,132,255,255,191,0,208,255,255,79,248,255,255,79,96,255,255,255,132,255,175,255,28,
+ 254,175,255,79,248,255,242,255,252,207,244,255,132,255,15,248,255,255,68,255,79,248,255,16,
+ 253,255,10,244,255,132,255,15,80,255,46,64,255,79,248,255,0,128,92,0,244,255,116,255,
+ 15,0,0,0,48,255,63,210,143,0,0,0,0,176,191,0,228,94,0,0,0,248,45,251,
+ 255,3,0,0,255,127,251,255,46,0,0,255,143,251,255,207,1,0,255,143,251,255,255,10,
+ 0,255,143,251,255,255,127,0,255,143,251,223,254,255,5,255,143,251,191,245,255,46,255,143,
+ 251,191,128,255,223,255,143,251,191,0,250,255,255,143,251,191,0,209,255,255,143,251,191,0,
+ 32,254,255,143,251,191,0,0,244,255,143,251,191,0,0,112,255,127,228,94,0,0,0,231,
+ 45,0,16,199,254,206,23,0,0,80,254,255,255,255,78,0,80,255,255,255,255,255,79,16,
+ 254,255,109,100,252,255,30,247,255,28,0,16,253,255,183,255,95,0,0,80,255,191,254,255,
+ 1,0,0,241,255,254,255,15,0,0,0,255,255,254,255,1,0,0,241,255,206,255,79,0,
+ 0,64,255,207,248,255,11,0,0,251,255,40,255,255,41,32,250,255,47,112,255,255,255,255,
+ 255,127,0,128,255,255,255,255,143,0,0,64,251,255,255,75,0,0,0,0,49,52,1,0,
+ 0,146,187,187,187,122,2,144,255,255,255,255,239,5,251,255,255,255,255,239,178,255,79,68,
+ 197,255,143,251,255,0,0,242,255,187,255,15,0,16,255,191,251,255,0,32,249,255,185,255,
+ 255,255,255,255,63,251,255,255,255,255,143,176,255,255,255,239,75,0,251,255,0,0,0,0,
+ 176,255,15,0,0,0,0,251,255,0,0,0,0,176,255,15,0,0,0,0,246,175,0,0,
+ 0,0,0,50,0,0,0,0,0,0,16,199,254,206,23,0,0,80,254,255,255,255,78,0,
+ 80,255,255,255,255,255,79,16,254,255,109,100,252,255,30,247,255,28,0,16,253,255,183,255,
+ 95,0,0,80,255,191,254,255,1,0,0,241,255,254,255,15,0,0,0,255,255,254,255,1,
+ 0,0,241,255,206,255,79,0,0,64,255,207,248,255,11,0,0,251,255,40,255,255,41,32,
+ 250,255,47,112,255,255,255,255,255,127,0,128,255,255,255,255,143,0,0,64,251,255,255,223,
+ 2,0,0,0,49,116,255,223,1,0,0,0,0,144,255,159,0,0,0,0,0,225,255,31,
+ 0,0,0,0,0,245,223,0,0,0,0,0,0,83,1,146,187,187,187,122,2,144,255,255,
+ 255,255,255,6,251,255,255,255,255,255,179,255,79,68,197,255,159,251,255,0,0,242,255,187,
+ 255,15,0,16,255,191,251,255,68,84,252,255,183,255,255,255,255,255,30,251,255,255,255,255,
+ 60,176,255,143,216,255,78,0,251,255,0,242,255,63,176,255,15,0,249,255,11,251,255,0,
+ 16,254,255,180,255,15,0,112,255,175,246,175,0,0,176,255,8,50,0,0,0,48,3,0,
+ 113,236,239,140,2,0,228,255,255,255,239,3,226,255,255,255,255,127,128,255,191,69,133,221,
+ 2,251,255,1,0,0,0,160,255,143,2,0,0,0,246,255,255,173,39,0,0,250,255,255,
+ 255,175,1,0,181,255,255,255,175,0,0,0,99,250,255,47,0,0,0,0,249,255,99,190,
+ 38,0,211,255,47,254,255,255,255,255,207,176,255,255,255,255,239,2,96,251,255,255,158,1,
+ 0,0,32,68,2,0,0,181,187,187,187,187,187,59,254,255,255,255,255,255,175,253,255,255,
+ 255,255,255,159,114,136,248,255,141,136,23,0,0,240,255,11,0,0,0,0,240,255,11,0,
+ 0,0,0,240,255,11,0,0,0,0,240,255,11,0,0,0,0,240,255,11,0,0,0,0,
+ 240,255,11,0,0,0,0,240,255,11,0,0,0,0,240,255,11,0,0,0,0,240,255,11,
+ 0,0,0,0,240,255,11,0,0,0,0,160,255,6,0,0,0,0,0,35,0,0,0,212,
+ 126,0,0,0,250,28,250,239,0,0,48,255,127,251,255,0,0,64,255,143,251,255,0,0,
+ 64,255,143,251,255,0,0,64,255,143,251,255,0,0,64,255,143,251,255,0,0,64,255,143,
+ 251,255,0,0,64,255,143,251,255,0,0,64,255,127,251,255,1,0,80,255,127,249,255,5,
+ 0,144,255,95,245,255,94,17,247,255,31,208,255,255,255,255,255,10,48,254,255,255,255,207,
+ 1,0,146,254,255,239,24,0,0,0,32,52,2,0,0,211,126,0,0,0,0,251,11,249,
+ 255,3,0,0,112,255,63,246,255,9,0,0,208,255,30,225,255,31,0,0,245,255,8,128,
+ 255,127,0,0,251,255,2,16,254,223,0,48,255,175,0,0,249,255,5,144,255,63,0,0,
+ 242,255,12,225,255,11,0,0,160,255,63,247,255,4,0,0,48,255,175,253,207,0,0,0,
+ 0,252,255,255,95,0,0,0,0,245,255,255,13,0,0,0,0,208,255,255,7,0,0,0,
+ 0,96,255,239,1,0,0,0,0,0,251,111,0,0,0,0,0,0,16,1,0,0,0,160,
+ 223,2,0,0,228,78,0,0,48,237,38,255,159,0,0,208,255,12,0,0,250,223,224,255,
+ 14,0,64,255,255,2,0,241,255,9,248,255,4,0,249,255,127,0,80,255,79,48,255,159,
+ 0,224,255,255,12,0,251,223,0,208,255,14,80,255,255,255,2,241,255,8,0,247,255,4,
+ 250,191,254,127,96,255,63,0,32,255,159,241,255,149,255,12,251,207,0,0,176,255,110,255,
+ 30,244,255,244,255,7,0,0,246,255,254,159,0,253,223,255,47,0,0,16,255,255,255,4,
+ 128,255,255,191,0,0,0,160,255,255,13,0,243,255,255,5,0,0,0,245,255,143,0,0,
+ 252,255,30,0,0,0,0,254,255,2,0,112,255,175,0,0,0,0,96,255,8,0,0,193,
+ 239,2,0,0,0,0,16,1,0,0,0,32,0,0,0,112,222,3,0,0,231,61,224,255,
+ 29,0,80,255,159,160,255,191,0,226,255,79,16,253,255,7,252,255,8,0,227,255,191,255,
+ 207,0,0,96,255,255,255,46,0,0,0,249,255,255,4,0,0,0,242,255,191,0,0,0,
+ 0,251,255,255,5,0,0,112,255,255,255,46,0,0,244,255,158,255,223,1,32,254,255,5,
+ 251,255,10,176,255,159,0,209,255,111,241,255,29,0,64,255,191,144,207,2,0,0,230,78,
+ 211,142,0,0,48,253,153,255,95,0,16,253,255,245,255,30,0,249,255,10,250,255,10,244,
+ 255,29,16,254,255,214,255,79,0,64,255,255,255,159,0,0,144,255,255,223,1,0,0,209,
+ 255,255,3,0,0,0,245,255,9,0,0,0,64,255,143,0,0,0,0,244,255,8,0,0,
+ 0,64,255,143,0,0,0,0,244,255,8,0,0,0,48,255,127,0,0,0,0,192,239,2,
+ 0,0,0,0,32,0,0,0,128,187,187,187,187,139,49,255,255,255,255,255,127,242,255,255,
+ 255,255,255,6,116,136,136,250,255,30,0,0,0,209,255,79,0,0,0,176,255,111,0,0,
+ 0,128,255,159,0,0,0,96,255,207,0,0,0,48,255,239,2,0,0,16,253,255,3,0,
+ 0,0,251,255,6,0,0,0,248,255,76,68,68,3,242,255,255,255,255,255,75,255,255,255,
+ 255,255,255,160,255,255,255,255,255,8,163,187,155,177,255,255,95,251,255,223,178,255,15,0,
+ 251,255,0,176,255,15,0,251,255,0,176,255,15,0,251,255,0,176,255,15,0,251,255,0,
+ 176,255,15,0,251,255,0,176,255,15,0,251,255,0,176,255,15,0,251,255,223,162,255,255,
+ 95,163,187,155,1,144,76,0,0,16,255,12,0,0,208,255,2,0,0,248,127,0,0,48,
+ 255,12,0,0,208,255,2,0,0,248,111,0,0,64,255,11,0,0,224,255,1,0,0,249,
+ 111,0,0,64,255,11,0,0,224,255,1,0,0,250,95,0,0,80,255,10,0,0,225,239,
+ 0,0,0,250,95,0,0,80,255,6,0,0,80,6,180,187,139,208,255,255,63,231,255,255,
+ 4,128,255,79,0,248,255,4,128,255,79,0,248,255,4,128,255,79,0,248,255,4,128,255,
+ 79,0,248,255,4,128,255,79,0,248,255,4,128,255,79,0,248,255,4,128,255,79,247,255,
+ 255,212,255,255,63,180,187,123,0,0,0,83,1,0,0,0,244,223,0,0,0,176,255,95,
+ 0,0,32,255,255,11,0,0,248,175,255,2,0,208,191,242,143,0,80,255,6,252,13,0,
+ 251,30,96,255,5,242,159,0,225,175,112,255,3,0,249,31,248,12,0,48,255,2,19,0,
+ 0,32,2,248,255,255,255,239,130,255,255,255,255,46,81,2,176,207,0,251,95,32,254,13,
+ 80,255,3,96,8,0,48,118,87,2,0,211,255,255,255,8,128,255,255,255,255,6,195,106,
+ 84,253,207,0,0,0,128,255,14,129,236,255,255,255,208,255,207,219,255,63,255,111,0,249,
+ 255,243,255,74,247,255,15,252,255,255,254,255,16,251,255,75,255,10,0,65,3,32,3,231,
+ 77,0,0,0,0,254,191,0,0,0,0,255,191,0,0,0,0,255,191,0,0,0,0,255,
+ 191,64,103,2,0,255,207,251,255,143,0,255,255,255,255,255,6,255,255,74,248,255,13,255,
+ 239,0,176,255,47,255,191,0,128,255,79,255,191,0,128,255,63,255,239,1,192,255,31,255,
+ 255,141,251,255,12,255,239,255,255,255,4,250,111,248,255,93,0,48,2,16,51,0,0,0,
+ 16,116,87,1,0,230,255,255,111,112,255,255,255,175,225,255,143,100,58,245,255,8,0,0,
+ 247,255,4,0,0,247,255,5,0,0,244,255,10,0,0,208,255,191,152,109,64,254,255,255,
+ 191,0,179,255,255,77,0,0,49,36,0,0,0,0,0,231,77,0,0,0,0,254,191,0,
+ 0,0,0,255,191,0,0,0,0,255,191,0,64,119,3,255,191,16,251,255,143,255,191,160,
+ 255,255,255,255,191,242,255,110,197,255,191,246,255,7,48,255,191,247,255,4,0,255,191,247,
+ 255,5,16,255,191,245,255,9,80,255,191,225,255,159,232,255,191,112,255,255,239,255,191,0,
+ 231,255,78,250,111,0,16,51,0,48,2,0,16,117,71,0,0,96,254,255,223,3,96,255,
+ 255,255,239,18,254,191,18,249,159,245,255,2,16,255,125,255,255,255,255,255,247,255,188,187,
+ 187,73,255,111,0,0,0,208,255,175,136,252,7,227,255,255,255,175,0,162,254,255,191,2,
+ 0,0,67,19,0,0,0,113,186,9,0,80,254,255,63,0,243,255,239,11,0,248,255,6,
+ 0,48,252,255,52,0,249,255,255,255,7,250,255,255,255,8,114,253,255,120,1,0,251,255,
+ 0,0,0,251,255,0,0,0,251,255,0,0,0,251,255,0,0,0,251,255,0,0,0,251,
+ 255,0,0,0,246,175,0,0,0,32,3,0,0,0,48,119,4,96,39,16,250,255,191,248,
+ 207,160,255,255,255,255,255,242,255,110,164,255,255,246,255,7,0,253,255,247,255,4,0,251,
+ 255,247,255,6,0,252,255,243,255,61,112,255,255,192,255,255,255,255,255,32,253,255,239,252,
+ 255,0,113,186,23,250,239,32,22,0,48,254,191,192,255,189,252,255,111,176,255,255,255,255,
+ 9,16,183,254,239,90,0,231,78,0,0,0,224,255,11,0,0,0,255,191,0,0,0,240,
+ 255,11,0,0,0,255,191,129,187,23,240,255,237,255,255,11,255,255,255,255,255,243,255,95,
+ 128,255,111,255,207,0,244,255,247,255,11,64,255,143,255,191,0,244,255,248,255,11,64,255,
+ 143,255,191,0,244,255,232,255,11,48,255,127,231,78,0,160,207,2,97,55,192,255,47,254,
+ 255,115,254,10,0,0,0,118,1,248,207,176,255,15,251,255,176,255,15,251,255,176,255,15,
+ 251,255,176,255,15,251,255,96,255,9,32,3,0,0,16,118,3,0,192,255,46,0,224,255,
+ 63,0,112,254,10,0,0,0,0,0,16,118,2,0,144,255,12,0,176,255,15,0,176,255,
+ 15,0,176,255,15,0,176,255,15,0,176,255,15,0,176,255,15,0,176,255,15,0,176,255,
+ 15,0,176,255,15,0,208,255,14,128,253,255,11,242,255,255,3,160,239,59,0,231,78,0,
+ 0,0,224,255,11,0,0,0,255,191,0,0,0,240,255,11,0,0,0,255,191,0,128,123,
+ 240,255,11,160,255,31,255,191,112,255,207,240,255,91,255,239,2,255,223,254,255,4,240,255,
+ 255,255,11,0,255,239,255,255,6,240,255,107,255,255,4,255,191,144,255,239,225,255,11,176,
+ 255,127,231,78,0,161,223,2,231,77,0,224,255,11,0,255,191,0,240,255,11,0,255,191,
+ 0,240,255,11,0,255,191,0,240,255,11,0,255,191,0,240,255,11,0,255,191,0,240,255,
+ 13,0,252,255,205,113,255,255,79,144,255,239,1,16,51,1,32,3,0,51,0,0,50,2,
+ 96,255,89,254,239,36,251,255,27,251,239,255,255,239,253,255,255,184,255,223,216,255,255,154,
+ 255,223,251,255,3,245,255,10,192,255,191,255,15,64,255,143,0,251,255,251,255,0,244,255,
+ 8,176,255,191,255,15,64,255,143,0,251,255,251,255,0,244,255,8,176,255,191,255,15,64,
+ 255,127,0,251,255,246,175,0,209,255,3,112,255,10,50,0,0,49,1,0,32,3,48,2,
+ 16,51,0,160,255,117,254,239,5,255,239,255,255,239,241,255,207,216,255,95,255,239,1,245,
+ 255,247,255,11,64,255,143,255,191,0,244,255,248,255,11,64,255,143,255,191,0,244,255,248,
+ 255,11,64,255,127,250,127,0,209,255,3,35,0,0,49,1,0,0,116,103,2,0,0,230,
+ 255,255,191,1,96,255,255,255,255,29,225,255,110,180,255,143,245,255,7,16,254,223,247,255,
+ 4,0,252,255,247,255,5,0,252,239,244,255,9,32,255,207,208,255,175,216,255,111,64,254,
+ 255,255,255,11,0,179,255,255,126,0,0,0,49,36,0,0,114,6,64,119,2,0,252,143,
+ 251,255,143,0,255,255,255,255,255,6,255,255,74,248,255,13,255,239,0,176,255,47,255,191,
+ 0,128,255,79,255,191,0,128,255,63,255,239,1,192,255,31,255,255,141,251,255,12,255,255,
+ 255,255,255,4,255,207,248,255,93,0,255,191,16,51,0,0,255,191,0,0,0,0,254,191,
+ 0,0,0,0,231,78,0,0,0,0,0,64,119,3,114,22,16,251,255,143,252,159,160,255,
+ 255,255,255,191,242,255,110,197,255,191,246,255,7,48,255,191,247,255,4,0,255,191,247,255,
+ 5,16,255,191,245,255,9,80,255,191,225,255,159,232,255,191,112,255,255,255,255,191,0,231,
+ 255,94,255,191,0,16,51,0,255,191,0,0,0,0,255,191,0,0,0,0,254,191,0,0,
+ 0,0,231,78,114,6,80,55,252,127,251,207,255,239,255,207,255,255,223,75,255,255,4,0,
+ 255,207,0,0,255,191,0,0,255,191,0,0,255,191,0,0,255,191,0,0,250,111,0,0,
+ 48,2,0,0,0,48,118,71,1,32,252,255,255,78,208,255,255,255,127,243,255,3,98,25,
+ 243,255,105,19,0,192,255,255,255,26,16,216,255,255,191,0,0,48,249,255,194,123,69,249,
+ 239,245,255,255,255,127,128,254,255,223,6,0,32,51,2,0,0,32,53,0,0,0,225,255,
+ 4,0,0,244,255,7,0,32,247,255,73,3,242,255,255,255,159,243,255,255,255,175,80,249,
+ 255,123,39,0,244,255,8,0,0,244,255,8,0,0,244,255,8,0,0,243,255,10,0,0,
+ 241,255,223,188,0,144,255,255,255,0,0,233,255,175,0,0,16,67,2,114,22,0,48,87,
+ 192,255,9,16,255,95,255,191,0,244,255,248,255,11,64,255,143,255,191,0,244,255,248,255,
+ 11,64,255,143,255,191,0,244,255,232,255,12,112,255,143,252,255,153,255,255,120,255,255,255,
+ 255,127,144,255,223,196,255,3,16,51,0,48,2,64,21,0,0,82,114,255,11,0,226,239,
+ 248,255,3,128,255,62,255,143,0,254,159,176,255,14,245,255,2,245,255,181,255,11,0,253,
+ 223,255,79,0,112,255,255,207,0,0,225,255,255,5,0,0,248,255,13,0,0,16,253,95,
+ 0,0,0,16,35,0,0,64,21,0,0,83,0,0,48,21,246,175,0,48,255,9,0,244,
+ 175,247,255,2,144,255,30,0,250,191,242,255,8,225,255,111,16,255,95,176,255,13,245,255,
+ 207,112,255,14,64,255,79,251,255,255,194,255,8,0,253,207,255,205,255,251,255,2,0,247,
+ 255,255,88,255,255,175,0,0,241,255,255,2,254,255,79,0,0,144,255,191,0,248,255,13,
+ 0,0,32,254,62,0,209,255,5,0,0,0,49,1,0,16,19,0,0,113,6,0,96,23,
+ 250,191,0,251,175,249,255,136,255,159,209,255,255,255,29,32,254,255,239,2,0,245,255,95,
+ 0,0,251,255,191,0,128,255,255,255,8,245,255,204,255,95,254,239,34,254,239,252,78,0,
+ 244,207,49,1,0,16,19,64,21,0,0,82,2,246,207,0,16,254,30,247,255,4,112,255,
+ 31,242,255,10,208,255,11,160,255,31,244,255,4,48,255,127,250,207,0,0,252,223,255,111,
+ 0,0,245,255,255,13,0,0,208,255,255,7,0,0,112,255,239,1,0,0,64,255,159,0,
+ 0,0,144,255,47,0,0,0,242,255,10,0,0,0,245,255,3,0,0,0,193,143,0,0,
+ 0,32,68,68,68,2,242,255,255,255,95,243,255,255,255,143,80,119,215,255,46,0,0,246,
+ 255,4,0,80,255,95,0,0,227,255,6,0,32,254,143,0,0,208,255,191,187,107,243,255,
+ 255,255,255,192,255,255,255,175,0,0,166,187,7,0,128,255,255,31,0,224,255,255,11,0,
+ 240,255,13,0,0,240,255,11,0,0,240,255,11,0,0,240,255,11,0,0,244,255,10,0,
+ 226,255,239,3,0,245,255,143,0,0,161,253,255,5,0,0,242,255,11,0,0,240,255,11,
+ 0,0,240,255,11,0,0,240,255,11,0,0,240,255,13,0,0,208,255,255,12,0,112,255,
+ 255,31,0,0,166,187,7,194,175,112,255,63,248,255,132,255,79,248,255,132,255,79,248,255,
+ 132,255,79,248,255,132,255,79,248,255,132,255,79,248,255,132,255,79,248,255,132,255,79,248,
+ 255,116,255,63,194,175,0,180,187,24,0,208,255,255,12,0,248,255,255,3,0,144,255,79,
+ 0,0,248,255,4,0,128,255,79,0,0,247,255,4,0,96,255,143,0,0,209,255,255,5,
+ 0,244,255,159,0,226,255,190,3,112,255,111,0,0,248,255,4,0,128,255,79,0,0,248,
+ 255,4,0,144,255,79,0,248,255,255,2,208,255,255,11,0,180,187,23,0,0,112,238,58,
+ 0,100,96,255,255,191,248,63,248,74,249,255,207,0,4,0,146,139,1,
+};
+static const np_glyph_t np_font_title_glyphs[95] = {
+ {0, 0, 0, 0, 6, 0},
+ {5, 15, 0, -15, 6, 0},
+ {9, 7, 1, -15, 11, 38},
+ {11, 16, 1, -15, 13, 70},
+ {13, 21, 0, -18, 13, 158},
+ {20, 16, 0, -15, 20, 295},
+ {14, 16, 1, -15, 16, 455},
+ {4, 7, 1, -15, 6, 567},
+ {6, 19, 2, -15, 8, 581},
+ {6, 19, 1, -15, 8, 638},
+ {9, 8, 0, -15, 10, 695},
+ {11, 12, 1, -12, 13, 731},
+ {5, 7, 0, -4, 6, 797},
+ {8, 4, 1, -8, 9, 815},
+ {5, 4, 0, -4, 6, 831},
+ {9, 18, -1, -16, 7, 841},
+ {12, 15, 0, -15, 12, 922},
+ {12, 15, 1, -15, 12, 1012},
+ {11, 15, 1, -15, 12, 1102},
+ {12, 16, 0, -15, 12, 1185},
+ {13, 15, 0, -15, 12, 1281},
+ {12, 16, 1, -15, 12, 1379},
+ {12, 16, 0, -15, 12, 1475},
+ {13, 16, 0, -15, 12, 1571},
+ {12, 15, 0, -15, 12, 1675},
+ {12, 16, 0, -15, 12, 1765},
+ {5, 11, 0, -11, 6, 1861},
+ {5, 14, 0, -11, 6, 1889},
+ {11, 10, 1, -11, 13, 1924},
+ {11, 8, 1, -10, 13, 1979},
+ {12, 10, 0, -11, 12, 2023},
+ {10, 16, 0, -15, 10, 2083},
+ {19, 19, 1, -15, 20, 2163},
+ {16, 16, 0, -15, 16, 2344},
+ {13, 15, 1, -15, 14, 2472},
+ {13, 15, 1, -15, 14, 2570},
+ {15, 15, 1, -15, 16, 2668},
+ {11, 15, 1, -15, 13, 2781},
+ {11, 16, 1, -15, 12, 2864},
+ {14, 16, 1, -15, 16, 2952},
+ {14, 15, 1, -15, 16, 3064},
+ {4, 15, 1, -15, 6, 3169},
+ {8, 15, -1, -15, 8, 3199},
+ {13, 15, 1, -15, 15, 3259},
+ {11, 15, 1, -15, 12, 3357},
+ {17, 15, 1, -15, 19, 3440},
+ {14, 15, 1, -15, 16, 3568},
+ {15, 16, 1, -15, 17, 3673},
+ {13, 16, 1, -15, 14, 3793},
+ {15, 20, 1, -15, 17, 3897},
+ {13, 16, 1, -15, 15, 4047},
+ {13, 16, 1, -15, 14, 4151},
+ {14, 16, 0, -15, 14, 4255},
+ {14, 16, 1, -15, 16, 4367},
+ {16, 16, 0, -15, 16, 4479},
+ {23, 16, 0, -15, 24, 4607},
+ {14, 15, 0, -15, 15, 4791},
+ {13, 16, 0, -15, 14, 4896},
+ {13, 15, 0, -15, 13, 5000},
+ {7, 19, 2, -15, 8, 5098},
+ {9, 18, -1, -16, 7, 5165},
+ {7, 19, 0, -15, 8, 5246},
+ {11, 12, 1, -14, 12, 5313},
+ {11, 2, 0, 0, 10, 5379},
+ {5, 6, 2, -17, 8, 5390},
+ {11, 12, 0, -11, 12, 5405},
+ {12, 16, 1, -15, 13, 5471},
+ {10, 12, 0, -11, 10, 5567},
+ {12, 16, 0, -15, 13, 5627},
+ {11, 12, 0, -11, 12, 5723},
+ {10, 16, 0, -15, 9, 5789},
+ {12, 15, 0, -11, 13, 5869},
+ {11, 15, 1, -15, 12, 5959},
+ {5, 17, 1, -16, 6, 6042},
+ {8, 20, -2, -16, 6, 6085},
+ {11, 15, 1, -15, 12, 6165},
+ {7, 16, 1, -15, 8, 6248},
+ {17, 12, 1, -11, 19, 6304},
+ {11, 12, 1, -11, 12, 6406},
+ {12, 12, 0, -11, 13, 6472},
+ {12, 15, 1, -11, 13, 6544},
+ {12, 15, 0, -11, 13, 6634},
+ {8, 12, 1, -11, 9, 6724},
+ {10, 12, 0, -11, 10, 6772},
+ {10, 15, -1, -14, 9, 6832},
+ {11, 12, 1, -11, 12, 6907},
+ {11, 12, 0, -11, 12, 6973},
+ {18, 12, 0, -11, 18, 7039},
+ {10, 12, 1, -11, 12, 7147},
+ {12, 15, 0, -11, 11, 7207},
+ {10, 11, 0, -11, 10, 7297},
+ {10, 19, 0, -15, 9, 7352},
+ {5, 19, 1, -15, 7, 7447},
+ {9, 19, 0, -15, 9, 7495},
+ {11, 4, 1, -8, 12, 7581},
+};
+const np_font_t np_font_title = {32, 95, 18, 5, np_font_title_glyphs, np_font_title_data};
+
+static const uint8_t np_font_body_data[2788] = {
+ 113,98,143,245,71,111,243,20,63,96,80,94,229,5,113,49,6,245,167,47,244,149,31,242,
+ 115,14,48,0,2,0,66,96,1,144,25,47,113,189,249,21,248,201,93,48,31,138,0,214,
+ 208,5,246,255,255,6,108,228,0,224,99,11,0,1,16,0,0,208,6,0,80,191,4,193,
+ 255,255,103,159,17,53,247,25,0,32,253,223,25,16,149,253,11,0,0,253,231,137,250,43,
+ 234,239,25,0,240,7,0,0,20,0,32,87,0,96,4,32,222,159,48,111,0,247,145,14,
+ 203,0,112,15,248,245,4,0,243,218,219,122,222,4,181,137,62,159,219,0,16,142,244,132,
+ 15,0,217,33,127,219,0,241,5,128,255,5,0,2,0,16,1,0,114,39,0,0,243,238,
+ 30,0,112,95,245,3,0,243,220,28,5,32,253,46,245,2,237,247,171,14,243,9,247,159,
+ 32,223,84,254,27,96,254,175,247,6,0,18,0,1,113,81,127,244,37,63,48,0,32,6,
+ 219,243,120,79,250,178,31,251,145,63,246,38,175,144,13,33,113,0,244,5,224,12,176,31,
+ 144,63,128,95,128,79,144,63,192,14,241,10,244,3,32,0,80,97,0,186,30,233,239,28,
+ 218,29,144,162,1,0,48,0,0,0,79,0,0,240,4,96,255,255,111,81,245,88,2,0,
+ 79,0,0,160,2,0,229,84,127,192,19,6,194,221,24,135,72,229,85,94,0,16,0,245,
+ 0,202,16,126,80,47,160,12,224,7,244,3,217,0,142,0,42,0,0,116,22,0,249,255,
+ 29,242,28,247,103,111,16,191,247,5,240,124,95,0,207,245,8,243,26,238,198,79,64,253,
+ 127,0,0,18,0,0,85,0,195,207,0,223,207,0,19,207,0,0,207,0,0,207,0,0,
+ 207,0,134,239,72,253,255,159,32,118,22,64,255,255,29,114,18,251,4,0,144,79,0,48,
+ 222,0,32,237,3,16,237,4,0,252,139,72,225,255,255,9,32,118,21,64,255,255,29,98,
+ 18,250,4,0,177,47,16,254,143,0,64,182,79,0,0,244,104,124,198,111,195,255,158,0,
+ 16,2,0,0,0,54,0,0,246,11,0,226,191,0,192,253,11,112,79,191,48,127,241,11,
+ 250,221,239,75,135,248,109,0,0,174,0,0,16,0,96,136,120,1,255,255,79,240,12,0,
+ 0,223,84,1,240,255,239,3,106,81,191,0,0,241,60,141,166,143,161,255,175,1,0,18,
+ 0,0,98,87,0,229,255,159,225,61,64,83,127,117,3,247,237,255,116,207,48,191,245,9,
+ 241,28,237,133,143,48,252,175,1,0,17,0,114,136,120,100,255,255,191,0,0,249,6,0,
+ 242,13,0,160,95,0,48,207,0,0,251,5,0,244,12,0,128,79,0,0,16,0,0,16,
+ 117,38,16,253,237,95,244,10,242,43,191,65,159,112,255,223,49,206,134,175,247,5,208,95,
+ 191,100,223,128,254,207,3,0,18,0,16,118,5,16,252,253,11,246,8,248,117,111,96,175,
+ 244,109,253,11,231,126,175,0,0,245,71,123,231,30,211,255,60,0,16,1,0,229,85,94,
+ 0,0,0,229,85,94,229,85,94,0,0,0,229,84,127,192,19,6,0,0,32,2,0,181,
+ 143,113,253,74,112,191,1,0,145,222,40,0,16,198,127,0,0,64,3,115,136,120,83,221,
+ 221,93,32,34,34,112,255,255,127,65,68,68,1,33,0,0,112,191,5,0,48,233,142,1,
+ 0,161,159,16,215,175,98,223,23,0,66,0,0,0,64,119,2,250,255,79,85,97,143,0,
+ 144,95,0,245,7,0,155,0,0,19,0,32,142,0,32,142,0,0,16,117,87,0,0,96,
+ 190,136,219,4,112,78,0,0,227,18,94,177,191,108,136,229,160,45,245,69,123,12,142,48,
+ 47,180,199,224,9,247,128,72,30,248,188,206,29,192,8,50,16,19,0,227,57,16,165,0,
+ 0,129,253,206,6,0,0,16,23,0,0,0,250,10,0,0,242,253,2,0,128,63,159,0,
+ 16,174,160,31,0,247,71,247,8,224,255,255,239,97,127,34,98,127,234,1,0,208,11,1,
+ 0,0,17,112,136,103,2,244,222,253,46,244,9,112,127,244,9,128,95,244,255,255,10,244,
+ 91,165,111,244,9,32,191,244,91,165,143,226,255,239,25,0,81,103,2,64,254,255,95,225,
+ 143,84,74,245,9,0,0,247,5,0,0,247,6,0,0,244,28,0,1,176,223,186,127,16,
+ 233,255,43,0,0,18,0,112,136,87,1,48,255,255,239,4,244,9,81,238,66,159,0,112,
+ 111,244,9,0,244,72,159,0,80,143,244,9,0,251,68,207,136,252,11,226,255,223,7,0,
+ 112,136,120,51,239,221,125,244,9,0,64,159,0,0,244,255,255,68,191,85,21,244,9,0,
+ 64,191,85,37,226,255,255,8,112,136,120,50,239,221,93,244,9,0,64,159,0,0,244,222,
+ 205,66,207,136,23,244,9,0,64,159,0,0,242,7,0,0,1,0,0,0,81,119,4,48,
+ 254,255,191,225,94,17,85,245,8,0,0,247,5,146,121,247,6,179,253,243,11,0,248,176,
+ 191,102,251,16,232,255,158,0,0,18,0,112,2,0,114,65,143,0,112,95,244,9,0,248,
+ 69,159,0,128,95,244,255,255,255,69,207,136,184,95,244,9,0,248,69,159,0,128,95,242,
+ 7,0,246,3,1,0,0,1,112,66,143,244,73,159,244,73,159,244,73,159,242,7,1,0,
+ 112,2,64,143,0,244,9,64,159,0,244,9,64,159,0,244,9,181,127,243,191,1,17,0,
+ 112,2,0,54,244,8,160,127,244,9,250,9,244,153,159,0,244,254,11,0,244,235,95,0,
+ 244,57,254,4,244,9,227,78,242,7,64,174,16,0,0,1,112,2,0,64,143,0,0,244,
+ 9,0,64,159,0,0,244,9,0,64,159,0,0,244,9,0,64,207,136,55,226,255,255,8,
+ 112,2,0,0,39,244,12,0,112,143,244,95,0,225,159,244,223,1,248,159,244,251,39,191,
+ 159,244,153,190,77,159,244,25,254,69,159,244,9,166,64,159,243,7,0,48,127,16,0,0,
+ 0,1,112,1,0,99,64,207,0,176,31,244,159,0,251,65,223,111,176,31,244,169,63,251,
+ 65,159,209,221,31,244,9,227,255,65,159,0,246,31,243,7,0,234,1,1,0,0,1,0,
+ 81,103,2,0,227,255,255,7,225,94,32,252,84,143,0,48,175,247,5,0,240,124,111,0,
+ 16,207,243,11,0,246,8,250,106,248,30,16,233,255,43,0,0,32,1,0,112,136,103,1,
+ 244,222,253,45,244,9,112,127,244,9,64,143,244,91,198,95,244,255,223,7,244,9,0,0,
+ 244,9,0,0,242,7,0,0,16,0,0,0,0,81,103,2,0,227,255,255,7,225,94,32,
+ 252,84,143,0,48,175,247,5,0,240,124,111,0,16,207,243,11,0,246,8,250,106,248,30,
+ 16,233,255,62,0,0,32,247,10,0,0,0,251,3,0,0,16,6,112,136,103,1,244,222,
+ 253,46,244,9,112,127,244,9,80,143,244,156,233,63,244,189,255,5,244,9,245,10,244,9,
+ 192,79,242,7,48,143,16,0,0,1,0,115,87,1,128,255,255,13,242,44,64,6,243,44,
+ 0,0,192,255,157,3,0,149,253,46,0,0,144,79,229,105,215,47,162,254,223,4,0,32,
+ 1,0,134,136,136,72,253,255,255,159,0,241,11,0,0,241,11,0,0,241,11,0,0,241,
+ 11,0,0,241,11,0,0,241,11,0,0,224,10,0,0,16,0,0,112,2,0,99,64,143,
+ 0,176,31,244,9,0,251,65,159,0,176,31,244,9,0,251,65,159,0,176,31,242,11,0,
+ 237,0,252,105,251,10,32,251,255,26,0,0,33,1,0,84,0,0,96,178,63,0,80,127,
+ 245,9,0,252,2,237,1,244,9,112,127,160,63,0,225,45,191,0,0,248,252,4,0,32,
+ 255,12,0,0,144,95,0,0,0,16,0,0,114,1,0,54,0,48,118,111,0,243,11,0,
+ 221,242,11,144,255,2,243,9,252,2,222,127,128,63,96,111,244,213,12,221,0,241,172,30,
+ 248,245,7,0,250,159,48,239,47,0,80,255,4,192,207,0,0,209,13,0,246,6,0,0,
+ 17,0,0,1,0,114,1,16,39,246,9,144,111,176,95,245,11,16,238,238,2,0,245,95,
+ 0,0,249,159,0,96,191,251,6,227,30,225,62,248,4,64,143,16,0,0,1,84,0,32,
+ 23,251,4,192,47,243,29,248,8,112,207,207,0,0,251,46,0,0,244,9,0,0,244,9,
+ 0,0,244,9,0,0,242,7,0,0,16,0,0,114,136,136,5,246,255,255,14,0,0,248,
+ 7,0,80,175,0,0,226,29,0,0,252,3,0,128,111,0,0,244,142,136,23,245,255,255,
+ 47,132,39,251,93,251,1,251,1,251,1,251,1,251,1,251,1,251,1,251,2,251,111,65,
+ 20,16,0,16,95,0,192,10,0,231,0,32,79,0,208,9,0,232,0,48,79,0,208,9,
+ 0,216,0,48,10,133,23,234,95,128,95,128,95,128,95,128,95,128,95,128,95,128,95,129,
+ 95,252,79,66,3,0,113,2,0,112,175,0,0,173,31,0,244,193,7,160,10,215,32,79,
+ 16,78,97,0,80,2,249,255,223,34,160,12,226,4,36,144,254,77,16,122,230,14,48,118,
+ 253,81,207,216,31,247,89,254,17,252,189,14,0,1,16,0,112,2,0,64,143,0,0,244,
+ 9,0,64,191,252,43,244,127,249,74,175,0,237,244,9,208,79,239,117,191,243,234,223,2,
+ 1,32,0,80,252,93,242,109,88,247,6,0,247,6,0,243,77,70,96,254,111,0,32,0,
+ 0,0,96,3,0,16,191,0,0,241,11,230,158,191,243,109,251,123,111,32,191,247,6,242,
+ 75,207,164,191,128,255,233,10,16,1,1,64,252,60,32,223,182,13,247,139,250,115,191,136,
+ 23,242,77,132,2,213,255,44,0,16,1,0,0,81,5,227,191,160,63,192,255,143,211,111,
+ 2,251,1,176,31,0,251,1,160,14,0,16,0,96,238,216,58,223,166,207,247,6,241,124,
+ 111,32,207,242,142,252,12,196,108,207,112,35,247,25,253,255,44,0,66,2,0,112,2,0,
+ 64,143,0,0,244,9,0,64,191,252,28,244,110,250,71,159,64,159,244,9,244,73,159,64,
+ 159,243,7,242,7,1,0,1,179,83,94,0,48,94,245,88,143,245,88,143,243,6,1,48,
+ 59,80,94,0,0,48,94,80,143,80,143,80,143,80,143,80,127,128,127,250,29,49,0,112,
+ 2,0,64,143,0,0,244,9,0,64,159,128,30,244,121,175,64,223,207,0,244,253,29,64,
+ 159,247,11,243,7,248,4,1,0,1,112,2,244,8,244,9,244,9,244,9,244,9,244,9,
+ 243,60,160,239,0,17,226,200,175,230,110,64,239,198,207,230,14,244,9,248,5,251,65,159,
+ 128,95,176,31,244,9,248,5,251,49,127,96,63,160,14,16,0,16,0,16,0,226,200,207,
+ 65,239,166,127,244,9,244,73,159,64,159,244,9,244,57,127,32,127,16,0,16,0,64,252,
+ 125,32,223,182,111,247,6,242,122,111,32,191,243,76,250,6,230,255,9,0,32,1,0,226,
+ 200,191,66,255,151,175,244,10,208,78,159,0,253,244,94,247,75,191,254,45,244,9,2,48,
+ 143,0,0,48,1,0,0,96,238,216,57,223,182,191,247,6,242,123,111,32,191,244,76,250,
+ 11,248,175,191,0,17,241,11,0,16,175,0,0,32,1,226,199,78,255,123,244,10,64,159,
+ 0,244,9,48,127,0,16,0,0,161,238,27,246,103,42,245,105,2,64,184,79,133,84,127,
+ 229,255,27,0,17,0,112,9,0,252,0,254,255,74,253,53,192,15,0,252,0,176,111,4,
+ 227,239,0,32,0,226,6,227,69,159,80,143,244,9,245,72,159,80,143,242,76,251,8,250,
+ 175,111,0,17,16,0,217,0,229,130,95,192,14,242,59,143,0,250,251,1,48,255,9,0,
+ 176,63,0,0,16,0,0,216,0,215,0,215,247,5,253,5,205,241,74,239,74,111,160,191,
+ 140,175,30,64,255,39,255,9,0,236,1,251,3,0,16,0,16,0,226,6,218,192,159,143,
+ 32,254,11,32,254,11,209,158,127,246,5,235,16,0,16,217,1,229,114,111,176,30,241,44,
+ 143,0,249,251,2,48,255,10,0,192,63,0,16,206,0,0,245,5,0,0,3,0,0,246,
+ 255,111,81,229,63,0,248,6,80,159,0,227,110,53,246,255,175,0,116,6,242,191,64,159,
+ 0,244,9,64,143,96,237,3,196,79,0,244,9,64,159,0,244,26,16,254,14,16,36,69,
+ 207,207,207,207,207,207,207,207,207,206,18,117,5,160,254,3,128,95,0,248,5,112,95,0,
+ 226,110,48,207,4,247,5,128,95,16,249,5,252,46,32,20,0,48,55,32,33,207,207,94,
+ 48,32,87,0,
+};
+static const np_glyph_t np_font_body_glyphs[95] = {
+ {0, 0, 0, 0, 4, 0},
+ {3, 9, 0, -9, 3, 0},
+ {6, 5, 0, -9, 6, 14},
+ {7, 10, 0, -9, 8, 29},
+ {7, 12, 0, -10, 8, 64},
+ {11, 10, 0, -9, 12, 106},
+ {9, 10, 0, -9, 9, 161},
+ {3, 5, 0, -9, 3, 206},
+ {3, 12, 1, -9, 5, 214},
+ {4, 12, 0, -9, 5, 232},
+ {5, 5, 0, -9, 6, 256},
+ {7, 7, 0, -7, 7, 269},
+ {3, 4, 0, -2, 3, 294},
+ {5, 2, 0, -4, 6, 300},
+ {3, 2, 0, -2, 3, 305},
+ {4, 11, 0, -10, 4, 308},
+ {7, 10, 0, -9, 8, 330},
+ {6, 9, 1, -9, 8, 365},
+ {7, 9, 0, -9, 8, 392},
+ {7, 10, 0, -9, 8, 424},
+ {7, 10, 0, -9, 8, 459},
+ {7, 10, 0, -9, 8, 494},
+ {7, 10, 0, -9, 8, 529},
+ {7, 10, 0, -9, 8, 564},
+ {7, 10, 0, -9, 8, 599},
+ {7, 10, 0, -9, 8, 634},
+ {3, 6, 0, -6, 3, 669},
+ {3, 8, 0, -6, 3, 678},
+ {7, 7, 0, -7, 7, 690},
+ {7, 5, 0, -6, 7, 715},
+ {7, 7, 0, -7, 8, 733},
+ {6, 9, 0, -9, 6, 758},
+ {11, 11, 0, -9, 12, 785},
+ {9, 10, 0, -9, 9, 846},
+ {8, 9, 0, -9, 8, 891},
+ {8, 10, 0, -9, 8, 927},
+ {9, 9, 0, -9, 10, 967},
+ {7, 9, 0, -9, 8, 1008},
+ {7, 10, 0, -9, 7, 1040},
+ {8, 10, 0, -9, 9, 1075},
+ {9, 10, 0, -9, 10, 1115},
+ {3, 10, 0, -9, 4, 1160},
+ {5, 10, -1, -9, 5, 1175},
+ {8, 10, 0, -9, 8, 1200},
+ {7, 9, 0, -9, 7, 1240},
+ {10, 10, 0, -9, 11, 1272},
+ {9, 10, 0, -9, 9, 1322},
+ {9, 10, 0, -9, 10, 1367},
+ {8, 10, 0, -9, 8, 1412},
+ {9, 12, 0, -9, 10, 1452},
+ {8, 10, 0, -9, 8, 1506},
+ {8, 10, 0, -9, 8, 1546},
+ {8, 10, 0, -9, 8, 1586},
+ {9, 10, 0, -9, 9, 1626},
+ {9, 10, 0, -9, 9, 1671},
+ {13, 10, 0, -9, 14, 1716},
+ {8, 10, 0, -9, 8, 1781},
+ {8, 10, 0, -9, 8, 1821},
+ {8, 9, 0, -9, 8, 1861},
+ {4, 12, 1, -9, 5, 1897},
+ {5, 11, -1, -10, 4, 1921},
+ {4, 12, 0, -9, 5, 1949},
+ {7, 7, 0, -8, 8, 1973},
+ {6, 1, 0, 0, 6, 1998},
+ {3, 4, 1, -10, 5, 2001},
+ {7, 7, 0, -6, 7, 2007},
+ {7, 10, 0, -9, 8, 2032},
+ {6, 7, 0, -6, 6, 2067},
+ {7, 10, 0, -9, 8, 2088},
+ {7, 7, 0, -6, 7, 2123},
+ {5, 10, 0, -9, 5, 2148},
+ {7, 9, 0, -6, 8, 2173},
+ {7, 10, 0, -9, 8, 2205},
+ {3, 10, 0, -9, 3, 2240},
+ {4, 12, -1, -9, 3, 2255},
+ {7, 10, 0, -9, 7, 2279},
+ {4, 10, 0, -9, 4, 2314},
+ {11, 7, 0, -6, 11, 2334},
+ {7, 7, 0, -6, 8, 2373},
+ {7, 7, 0, -6, 8, 2398},
+ {7, 9, 0, -6, 8, 2423},
+ {7, 9, 0, -6, 8, 2455},
+ {5, 7, 0, -6, 6, 2487},
+ {6, 7, 0, -6, 6, 2505},
+ {5, 9, 0, -8, 5, 2526},
+ {7, 7, 0, -6, 8, 2549},
+ {7, 7, 0, -6, 7, 2574},
+ {10, 7, 0, -6, 10, 2599},
+ {6, 7, 0, -6, 7, 2634},
+ {7, 9, 0, -6, 7, 2655},
+ {6, 6, 0, -6, 6, 2687},
+ {5, 12, 0, -9, 6, 2705},
+ {2, 12, 1, -9, 4, 2735},
+ {5, 12, 0, -9, 5, 2747},
+ {7, 3, 0, -5, 8, 2777},
+};
+const np_font_t np_font_body = {32, 95, 10, 3, np_font_body_glyphs, np_font_body_data};
+
+static const uint8_t np_font_small_data[1791] = {
+ 230,113,31,246,64,13,178,48,26,229,2,214,226,99,63,63,212,241,2,2,2,0,44,59,
+ 129,143,110,161,157,94,112,104,10,213,221,93,209,197,22,208,208,1,0,50,0,0,183,0,
+ 128,254,76,245,37,54,247,39,0,193,255,61,0,99,190,101,51,173,197,255,27,0,183,0,
+ 0,16,0,0,0,0,2,48,237,6,227,1,154,229,176,8,160,89,94,46,3,211,110,141,
+ 222,9,0,199,199,228,0,225,100,93,14,128,10,193,110,0,17,0,0,0,64,253,11,0,
+ 219,243,3,112,207,60,5,234,95,168,246,130,239,102,95,211,79,145,238,138,13,214,246,212,
+ 32,16,16,46,232,192,10,142,240,8,158,176,11,246,17,43,16,96,12,243,4,142,192,11,
+ 187,192,10,142,244,83,9,16,0,0,157,6,232,207,18,220,6,96,51,0,0,17,0,0,
+ 119,0,98,170,38,181,221,91,0,136,0,0,85,0,163,81,63,193,1,2,32,18,246,175,
+ 163,81,46,0,37,0,78,64,14,144,9,224,5,228,0,168,0,93,0,26,0,144,238,6,
+ 246,116,63,218,16,127,203,0,143,218,16,127,246,116,47,144,238,6,129,62,208,255,4,84,
+ 79,0,244,4,64,79,16,245,21,253,255,10,179,239,8,132,148,63,0,80,63,0,210,11,
+ 16,221,1,209,78,2,244,255,111,195,239,8,132,148,63,16,148,30,80,237,27,0,32,111,
+ 133,116,111,196,239,9,0,176,10,0,248,12,48,222,12,209,182,12,233,216,109,150,233,142,
+ 0,144,10,243,255,79,244,37,2,244,120,4,244,187,111,48,0,188,147,85,158,178,238,26,
+ 48,252,93,225,75,86,246,149,6,247,156,127,246,4,188,242,57,158,80,253,27,246,255,175,
+ 32,82,127,0,176,30,0,244,6,0,220,0,80,95,0,160,11,0,161,238,26,247,84,127,
+ 244,102,79,210,238,45,218,0,173,234,51,174,178,238,43,177,223,5,233,131,47,219,80,111,
+ 245,204,127,48,53,111,101,180,30,213,207,3,229,50,26,0,48,26,229,2,229,50,26,0,
+ 48,26,245,19,28,32,0,0,0,33,0,147,126,195,141,2,245,58,0,16,215,76,0,0,
+ 68,98,102,38,181,187,91,98,102,38,181,187,91,18,0,0,231,57,0,32,216,60,0,163,
+ 95,196,125,1,68,0,0,213,223,115,71,189,0,227,7,208,7,0,10,0,163,1,80,46,
+ 0,0,197,254,92,0,215,20,65,93,226,146,191,77,109,89,46,199,240,135,199,128,41,109,
+ 58,207,203,123,225,34,3,34,0,229,71,149,7,0,147,171,23,0,0,209,8,0,0,232,
+ 31,0,16,94,141,0,112,14,230,1,225,190,252,7,246,102,166,30,154,0,32,78,226,255,
+ 158,64,95,130,63,244,37,248,66,255,255,11,244,4,243,70,95,82,127,242,255,174,1,48,
+ 235,190,18,206,85,41,246,3,0,112,31,0,0,246,3,0,16,206,85,41,48,235,190,2,
+ 226,255,157,1,244,37,229,11,244,4,96,47,244,4,64,79,244,4,96,47,244,37,229,11,
+ 242,255,157,1,226,255,143,244,37,18,244,37,2,244,255,111,244,4,0,244,37,18,242,255,
+ 143,226,255,143,244,37,18,244,37,2,244,255,79,244,4,0,244,4,0,226,3,0,32,234,
+ 207,20,221,69,88,246,3,0,112,31,224,175,246,3,129,27,221,69,186,32,234,223,6,226,
+ 3,96,77,79,0,248,244,71,148,79,255,255,255,244,4,128,79,79,0,248,226,3,96,13,
+ 226,67,79,244,68,79,244,68,79,226,3,0,214,0,248,0,248,0,248,0,248,32,234,225,
+ 93,226,3,227,68,79,227,10,244,231,10,64,255,47,0,244,214,29,64,79,226,28,226,3,
+ 210,6,226,3,0,244,4,0,244,4,0,244,4,0,244,4,0,244,71,20,242,255,143,227,
+ 4,0,215,244,12,16,254,244,111,144,255,244,234,227,250,244,196,142,248,244,68,29,248,227,
+ 3,0,214,227,4,96,77,239,3,248,244,221,129,79,79,204,248,244,36,238,79,79,64,255,
+ 227,3,112,14,32,234,190,2,209,92,197,29,246,3,48,111,247,1,16,127,246,3,48,111,
+ 209,92,213,29,32,235,174,2,242,255,158,64,95,98,111,244,4,242,71,207,235,46,244,104,
+ 21,64,79,0,0,226,3,0,0,32,234,190,2,209,92,197,29,246,3,48,111,247,1,16,
+ 127,246,3,48,111,209,92,213,29,32,235,239,3,0,0,226,10,0,0,80,13,242,255,174,
+ 64,95,82,111,244,4,242,71,239,253,29,244,103,127,64,79,144,47,226,3,210,6,128,254,
+ 93,245,71,103,247,21,0,177,255,76,0,65,236,150,69,220,180,254,60,253,255,255,22,146,
+ 47,2,0,248,0,0,128,15,0,0,248,0,0,128,15,0,0,214,0,0,226,3,160,74,
+ 79,0,203,244,4,176,76,79,0,203,243,5,192,27,206,116,127,64,252,158,0,155,0,64,
+ 30,248,2,192,12,225,8,243,5,144,30,218,0,32,159,111,0,0,250,14,0,0,227,6,
+ 0,215,0,225,5,128,91,79,96,191,0,142,224,9,220,31,245,2,233,243,227,166,12,48,
+ 207,12,201,110,0,208,127,64,255,1,0,230,1,192,9,0,214,1,228,35,190,209,11,64,
+ 239,30,0,176,127,0,80,223,46,32,174,209,28,200,1,227,4,200,0,228,50,159,225,11,
+ 112,207,30,0,176,79,0,0,248,0,0,128,15,0,0,214,0,0,250,255,159,66,132,95,
+ 0,226,9,0,204,0,144,46,0,245,72,52,249,255,223,254,248,25,143,240,8,143,240,8,
+ 143,240,25,254,8,6,0,78,0,154,0,213,0,225,3,160,8,80,13,16,63,0,56,252,
+ 26,204,176,12,203,176,12,203,176,28,204,252,10,0,18,0,0,204,0,64,221,4,160,119,
+ 10,226,17,30,115,0,55,250,255,13,42,153,97,195,239,38,37,234,213,220,191,61,251,212,
+ 158,13,214,0,0,248,0,0,248,250,28,248,70,158,248,1,188,248,70,158,214,250,44,161,
+ 238,133,78,36,203,0,128,78,36,161,239,5,0,0,110,0,0,143,193,175,143,233,100,143,
+ 203,16,143,233,100,143,194,175,109,161,223,132,78,216,235,187,139,78,99,145,254,11,0,48,
+ 0,228,62,160,13,160,255,14,193,28,0,203,0,176,12,0,170,0,193,175,109,233,100,143,
+ 203,16,143,233,116,143,194,175,127,83,98,95,196,239,8,214,0,0,248,0,0,248,250,11,
+ 248,117,63,248,64,79,248,64,79,230,32,62,114,97,46,0,96,13,248,128,15,248,96,13,
+ 16,3,112,63,16,3,96,13,128,15,128,15,128,15,128,15,161,14,233,7,214,0,0,248,
+ 0,0,248,128,13,248,247,5,248,191,0,248,246,7,230,112,30,214,0,248,0,248,0,248,
+ 0,248,0,247,4,210,63,214,250,185,143,248,165,95,234,248,128,15,248,248,128,15,248,230,
+ 96,13,214,214,250,11,248,117,63,248,64,79,248,64,79,230,32,62,161,238,8,232,100,95,
+ 203,16,127,232,100,79,161,239,8,214,250,28,248,70,158,248,1,188,248,70,158,248,250,44,
+ 248,0,0,214,0,0,193,175,109,233,100,143,203,16,143,233,100,143,194,175,143,0,0,143,
+ 0,0,109,214,234,248,57,248,1,248,1,230,0,194,223,116,45,37,178,189,68,37,186,213,
+ 223,4,96,2,0,143,0,254,239,16,159,1,240,8,0,174,2,96,238,1,214,48,62,248,
+ 64,79,248,64,79,247,148,79,194,175,62,154,48,30,247,145,12,225,232,6,144,239,0,32,
+ 110,0,154,64,30,208,116,31,250,86,31,225,248,187,171,0,249,60,255,3,48,94,176,11,
+ 0,214,114,13,209,253,6,80,223,0,209,252,9,214,81,46,139,48,30,232,161,12,242,247,
+ 6,160,239,0,80,143,0,112,31,0,160,9,0,250,255,18,162,11,96,29,64,94,2,249,
+ 255,6,48,238,1,247,2,128,15,0,249,0,248,9,16,234,0,128,15,0,247,2,64,238,
+ 1,226,67,79,244,68,79,244,68,79,244,68,79,226,3,252,7,193,11,176,12,176,13,80,
+ 207,160,29,176,12,193,11,252,7,145,74,37,147,216,45,
+};
+static const np_glyph_t np_font_small_glyphs[95] = {
+ {0, 0, 0, 0, 3, 0},
+ {3, 7, 0, -7, 3, 0},
+ {5, 4, 0, -7, 5, 11},
+ {6, 7, 0, -7, 7, 21},
+ {6, 11, 0, -9, 6, 42},
+ {9, 9, 0, -8, 10, 75},
+ {7, 7, 0, -7, 8, 116},
+ {2, 4, 0, -7, 3, 141},
+ {3, 10, 1, -8, 4, 145},
+ {3, 10, 0, -8, 4, 160},
+ {5, 5, 0, -8, 5, 175},
+ {6, 6, 0, -6, 6, 188},
+ {3, 4, 0, -2, 3, 206},
+ {4, 2, 0, -4, 5, 212},
+ {3, 2, 0, -2, 3, 216},
+ {4, 9, 0, -8, 4, 219},
+ {6, 7, 0, -7, 6, 237},
+ {5, 7, 1, -7, 6, 258},
+ {6, 7, 0, -7, 6, 276},
+ {6, 7, 0, -7, 6, 297},
+ {6, 7, 0, -7, 6, 318},
+ {6, 7, 0, -7, 6, 339},
+ {6, 7, 0, -7, 6, 360},
+ {6, 7, 0, -7, 6, 381},
+ {6, 7, 0, -7, 6, 402},
+ {6, 7, 0, -7, 6, 423},
+ {3, 5, 0, -5, 3, 444},
+ {3, 7, 0, -5, 3, 452},
+ {6, 6, 0, -6, 6, 463},
+ {6, 4, 0, -5, 6, 481},
+ {6, 6, 0, -6, 6, 493},
+ {5, 7, 0, -7, 6, 511},
+ {9, 9, 0, -7, 10, 529},
+ {8, 7, 0, -7, 8, 570},
+ {7, 7, 0, -7, 8, 598},
+ {7, 7, 0, -7, 7, 623},
+ {8, 7, 0, -7, 8, 648},
+ {6, 7, 0, -7, 6, 676},
+ {6, 7, 0, -7, 6, 697},
+ {7, 7, 0, -7, 8, 718},
+ {7, 7, 0, -7, 8, 743},
+ {3, 7, 0, -7, 4, 768},
+ {4, 7, -1, -7, 4, 779},
+ {7, 7, 0, -7, 7, 793},
+ {6, 7, 0, -7, 6, 818},
+ {8, 7, 0, -7, 9, 839},
+ {7, 7, 0, -7, 8, 867},
+ {8, 7, 0, -7, 8, 892},
+ {7, 7, 0, -7, 7, 920},
+ {8, 9, 0, -7, 8, 945},
+ {7, 7, 0, -7, 8, 981},
+ {6, 7, 0, -7, 7, 1006},
+ {7, 7, 0, -7, 7, 1027},
+ {7, 7, 0, -7, 8, 1052},
+ {8, 7, 0, -7, 8, 1077},
+ {11, 7, 0, -7, 12, 1105},
+ {7, 7, 0, -7, 7, 1144},
+ {7, 7, 0, -7, 7, 1169},
+ {6, 7, 0, -7, 7, 1194},
+ {3, 9, 1, -7, 4, 1215},
+ {4, 9, 0, -8, 4, 1229},
+ {3, 9, 0, -7, 4, 1247},
+ {6, 6, 0, -7, 6, 1261},
+ {5, 1, 0, 0, 6, 1279},
+ {2, 3, 1, -8, 4, 1282},
+ {5, 5, 0, -5, 6, 1285},
+ {6, 7, 0, -7, 6, 1298},
+ {5, 5, 0, -5, 5, 1319},
+ {6, 7, 0, -7, 6, 1332},
+ {5, 5, 0, -5, 6, 1353},
+ {5, 8, 0, -8, 5, 1366},
+ {6, 7, 0, -5, 6, 1386},
+ {6, 7, 0, -7, 6, 1407},
+ {3, 8, 0, -8, 3, 1428},
+ {4, 10, -1, -8, 3, 1440},
+ {6, 7, 0, -7, 6, 1460},
+ {4, 7, 0, -7, 4, 1481},
+ {8, 5, 0, -5, 9, 1495},
+ {6, 5, 0, -5, 6, 1515},
+ {6, 5, 0, -5, 6, 1530},
+ {6, 7, 0, -5, 6, 1545},
+ {6, 7, 0, -5, 6, 1566},
+ {4, 5, 0, -5, 5, 1587},
+ {5, 5, 0, -5, 6, 1597},
+ {5, 7, 0, -7, 4, 1610},
+ {6, 5, 0, -5, 6, 1628},
+ {6, 5, 0, -5, 6, 1643},
+ {9, 5, 0, -5, 9, 1658},
+ {6, 5, 0, -5, 6, 1681},
+ {6, 7, 0, -5, 6, 1696},
+ {5, 5, 0, -5, 5, 1717},
+ {5, 9, 0, -7, 5, 1730},
+ {3, 9, 0, -7, 4, 1753},
+ {4, 9, 0, -7, 5, 1767},
+ {6, 2, 0, -4, 6, 1785},
+};
+const np_font_t np_font_small = {32, 95, 9, 2, np_font_small_glyphs, np_font_small_data};
diff --git a/launcher/src/games.c b/launcher/src/games.c
new file mode 100644
index 00000000..3e051ff8
--- /dev/null
+++ b/launcher/src/games.c
@@ -0,0 +1,44 @@
+/* Installed games: each one is a block of flash between its head and tail
+ * markers (see tools/gen_games.py). Uninstalling wipes the block, so a game
+ * counts as installed only while both markers are intact. */
+#include <string.h>
+#include "np.h"
+#include "sys.h"
+
+#define HEAD_MAGIC 0x3147504Eu /* "NPG1" */
+#define TAIL_MAGIC 0x444E4550u /* "PEND" */
+
+#if NP_SIMULATOR
+bool np_sim_removed[16];
+#endif
+
+bool np_game_installed(int i) {
+ const np_game_t *g = &np_games[i];
+#if NP_SIMULATOR
+ (void)g;
+ return !np_sim_removed[i];
+#else
+ /* volatile: this flash changes under the compiler's feet when uninstalling */
+ const volatile uint32_t *head = g->begin, *tail = g->end - 1;
+ return head[0] == HEAD_MAGIC && tail[0] == TAIL_MAGIC;
+#endif
+}
+
+uint32_t np_game_size(int i) {
+ const np_game_t *g = &np_games[i];
+#if NP_SIMULATOR
+ uint32_t shots = 0;
+ for (int k = 0; k < g->nshots; k++) shots += g->shots[k].zsize + 2 * g->shots[k].ncolors;
+ return g->est_size + shots;
+#else
+ return (uint32_t)((const uint8_t *)g->end - (const uint8_t *)g->begin);
+#endif
+}
+
+void np_game_run(int i) {
+ const np_game_t *g = &np_games[i];
+ /* fresh RAM, as if the game had just been launched from the home screen */
+ if (g->data_size) memcpy(g->data, g->data_init, g->data_size);
+ if (g->bss_size) memset(g->bss, 0, g->bss_size);
+ g->main();
+}
diff --git a/launcher/src/gfx.c b/launcher/src/gfx.c
new file mode 100644
index 00000000..9f82b4af
--- /dev/null
+++ b/launcher/src/gfx.c
@@ -0,0 +1,327 @@
+#include "gfx.h"
+#include <string.h>
+
+color_t *gfx_buf;
+int gfx_y0, gfx_y1;
+int gfx_clip_x0 = 0, gfx_clip_x1 = SCREEN_W;
+
+void gfx_init(void) { gfx_buf = np_alloc(SCREEN_W * STRIP_H * sizeof(color_t)); }
+
+void gfx_render(gfx_scene_t scene, void *ctx, int y0, int y1) {
+ for (int y = y0; y < y1; y += STRIP_H) {
+ gfx_y0 = y;
+ gfx_y1 = NP_MIN(y + STRIP_H, y1);
+ scene(ctx);
+ np_push(0, y, SCREEN_W, gfx_y1 - y, gfx_buf);
+ }
+}
+
+static inline color_t *px_at(int x, int y) { return gfx_buf + (y - gfx_y0) * SCREEN_W + x; }
+
+color_t gfx_mix(color_t a, color_t b, int t) {
+ uint32_t A = (a | (uint32_t)a << 16) & 0x07E0F81F, B = (b | (uint32_t)b << 16) & 0x07E0F81F;
+ uint32_t M = ((A * (uint32_t)(32 - t) + B * (uint32_t)t) >> 5) & 0x07E0F81F;
+ return (color_t)(M | M >> 16);
+}
+
+color_t gfx_rgb(uint32_t c) { return RGB((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF); }
+
+uint32_t gfx_lerp888(uint32_t a, uint32_t b, int t) {
+ uint32_t out = 0;
+ for (int s = 0; s < 24; s += 8) {
+ int ca = (a >> s) & 0xFF, cb = (b >> s) & 0xFF;
+ out |= (uint32_t)((ca * (256 - t) + cb * t) >> 8) << s;
+ }
+ return out;
+}
+
+static bool clip(int *x, int *y, int *w, int *h) {
+ int x0 = NP_MAX(*x, 0), y0 = NP_MAX(*y, gfx_y0);
+ int x1 = NP_MIN(*x + *w, SCREEN_W), y1 = NP_MIN(*y + *h, gfx_y1);
+ if (x1 <= x0 || y1 <= y0) return false;
+ *x = x0, *y = y0, *w = x1 - x0, *h = y1 - y0;
+ return true;
+}
+
+static void span(color_t *p, int n, color_t c) {
+ if (n > 0 && ((uintptr_t)p & 2)) *p++ = c, n--;
+ uint32_t two = c | (uint32_t)c << 16, *q = (uint32_t *)p;
+ for (int i = 0; i < n / 2; i++) q[i] = two;
+ if (n & 1) p[n - 1] = c;
+}
+
+void gfx_fill(int x, int y, int w, int h, color_t c) {
+ if (!clip(&x, &y, &w, &h)) return;
+ for (int j = 0; j < h; j++) span(px_at(x, y + j), w, c);
+}
+
+static void span_alpha(color_t *p, int n, color_t c, int t) {
+ if (t >= 32) {
+ span(p, n, c);
+ return;
+ }
+ if (t <= 0) return;
+ uint32_t C = ((c | (uint32_t)c << 16) & 0x07E0F81F) * (uint32_t)t;
+ for (int i = 0; i < n; i++) {
+ uint32_t A = (p[i] | (uint32_t)p[i] << 16) & 0x07E0F81F;
+ uint32_t M = ((A * (uint32_t)(32 - t) + C) >> 5) & 0x07E0F81F;
+ p[i] = (color_t)(M | M >> 16);
+ }
+}
+
+void gfx_fill_alpha(int x, int y, int w, int h, color_t c, int a) {
+ if (!clip(&x, &y, &w, &h)) return;
+ int t = (a + 4) >> 3;
+ for (int j = 0; j < h; j++) span_alpha(px_at(x, y + j), w, c, t);
+}
+
+/* Ordered dithering hides the banding of 16-bit colour in soft gradients. */
+static const uint8_t bayer[4][4] = {{0, 8, 2, 10}, {12, 4, 14, 6}, {3, 11, 1, 9}, {15, 7, 13, 5}};
+
+void gfx_vgrad(int x, int y, int w, int h, uint32_t top, uint32_t bottom) {
+ int x0 = x, y0 = y, h0 = h;
+ if (!clip(&x, &y, &w, &h)) return;
+ (void)x0;
+ for (int j = 0; j < h; j++) {
+ int row = y + j;
+ int t = h0 > 1 ? (row - y0) * 256 / (h0 - 1) : 0;
+ uint32_t c = gfx_lerp888(top, bottom, t);
+ int r = (c >> 16) & 0xFF, g = (c >> 8) & 0xFF, b = c & 0xFF;
+ color_t pat[4];
+ for (int i = 0; i < 4; i++) {
+ int d = bayer[row & 3][i];
+ int r5 = NP_MIN(31, (r + (d >> 1)) >> 3), g6 = NP_MIN(63, (g + (d >> 2)) >> 2), b5 = NP_MIN(31, (b + (d >> 1)) >> 3);
+ pat[i] = (color_t)(r5 << 11 | g6 << 5 | b5);
+ }
+ color_t *p = px_at(x, row);
+ for (int i = 0; i < w; i++) p[i] = pat[(x + i) & 3];
+ }
+}
+
+static inline float clampf(float v) { return v < 0 ? 0 : v > 1 ? 1 : v; }
+
+/* Coverage of pixel column i (0 = leftmost) of a rounded corner of radius r,
+ * dy = vertical distance from the corner's centre row. */
+static int corner_cov(int i, int r, float dy) {
+ float dx = r - i - 0.5f;
+ float d = __builtin_sqrtf(dx * dx + dy * dy) - r;
+ return (int)(32 * clampf(0.5f - d) + 0.5f);
+}
+
+static float row_dy(int j, int h, int r) {
+ if (j < r) return r - j - 0.5f;
+ if (j >= h - r) return j + 0.5f - (h - r);
+ return 0;
+}
+
+void gfx_rrect(int x, int y, int w, int h, int r, color_t c, int a) {
+ if (w <= 0 || h <= 0) return;
+ if (2 * r > w) r = w / 2;
+ if (2 * r > h) r = h / 2;
+ int ya = NP_MAX(y, gfx_y0), yb = NP_MIN(y + h, gfx_y1);
+ int t = (a + 4) >> 3;
+ for (int row = ya; row < yb; row++) {
+ float dy = row_dy(row - y, h, r);
+ int solid0 = x, solid1 = x + w;
+ if (dy > 0) {
+ for (int i = 0; i < r; i++) {
+ int cov = corner_cov(i, r, dy);
+ if (cov >= 32) break;
+ int k = cov * t >> 5;
+ if (k > 0) {
+ if (x + i >= 0 && x + i < SCREEN_W) span_alpha(px_at(x + i, row), 1, c, k);
+ int xr = x + w - 1 - i;
+ if (xr >= 0 && xr < SCREEN_W) span_alpha(px_at(xr, row), 1, c, k);
+ }
+ solid0 = x + i + 1;
+ solid1 = x + w - i - 1;
+ }
+ }
+ int s0 = NP_MAX(solid0, 0), s1 = NP_MIN(solid1, SCREEN_W);
+ if (s1 > s0) span_alpha(px_at(s0, row), s1 - s0, c, t);
+ }
+}
+
+/* Signed distance from a pixel centre to a rounded box (negative inside). */
+static float box_dist(float px, float py, float hw, float hh, float r) {
+ float qx = __builtin_fabsf(px) - (hw - r), qy = __builtin_fabsf(py) - (hh - r);
+ float mx = qx > 0 ? qx : 0, my = qy > 0 ? qy : 0;
+ float in = qx > qy ? qx : qy;
+ return __builtin_sqrtf(mx * mx + my * my) + (in < 0 ? in : 0) - r;
+}
+
+void gfx_rrect_outline(int x, int y, int w, int h, int r, int th, color_t c, int a) {
+ if (w <= 0 || h <= 0) return;
+ int ya = NP_MAX(y, gfx_y0), yb = NP_MIN(y + h, gfx_y1);
+ int t = (a + 4) >> 3;
+ float hw = w * 0.5f, hh = h * 0.5f, ri = r > th ? r - th : 0;
+ for (int row = ya; row < yb; row++) {
+ float py = row + 0.5f - (y + hh);
+ for (int i = 0; i < w; i++) {
+ float px = i + 0.5f - hw;
+ float d_in = box_dist(px, py, hw - th, hh - th, ri);
+ if (d_in < -0.5f) {
+ if (i < w / 2) i = w - 1 - i - 1; /* the rest up to the mirror pixel is inside */
+ continue;
+ }
+ float cov = clampf(0.5f - box_dist(px, py, hw, hh, r)) - clampf(0.5f - d_in);
+ int k = (int)(cov * t + 0.5f);
+ int sx = x + i;
+ if (k > 0 && sx >= 0 && sx < SCREEN_W) span_alpha(px_at(sx, row), 1, c, k);
+ }
+ }
+}
+
+void gfx_shadow(int x, int y, int w, int h, int r, int blur, int a) {
+ int ya = NP_MAX(y - blur, gfx_y0), yb = NP_MIN(y + h + blur, gfx_y1);
+ float hw = w * 0.5f, hh = h * 0.5f, cx = x + hw, cy = y + hh;
+ int xa = x - blur, xb = x + w + blur;
+ for (int row = ya; row < yb; row++) {
+ float py = row + 0.5f - cy;
+ for (int sx = xa; sx < xb; sx++) {
+ float d = box_dist(sx + 0.5f - cx, py, hw, hh, r);
+ if (d <= 0) {
+ int mirror = (int)(2 * cx) - 1 - sx; /* inside: the card will cover it */
+ if (mirror > sx) sx = mirror - 1;
+ continue;
+ }
+ if (d >= blur || sx < 0 || sx >= SCREEN_W) continue;
+ float f = 1 - d / blur;
+ int k = (int)(f * f * a) >> 3;
+ if (k > 0) span_alpha(px_at(sx, row), 1, 0, k);
+ }
+ }
+}
+
+void gfx_circle(int cx, int cy, int r, color_t c, int a) {
+ gfx_rrect(cx - r, cy - r, 2 * r, 2 * r, r, c, a);
+}
+
+void gfx_image(const uint8_t *idx, const color_t *pal, int ncolors, int sw, int sh, int dx, int dy, int dw, int dh,
+ int radius, int dim) {
+ if (dw <= 0 || dh <= 0) return;
+ int ya = NP_MAX(dy, gfx_y0), yb = NP_MIN(dy + dh, gfx_y1);
+ if (ya >= yb || dx >= SCREEN_W || dx + dw <= 0) return;
+ color_t dimmed[256];
+ if (dim > 0) {
+ int t = (dim + 4) >> 3;
+ for (int i = 0; i < ncolors && i < 256; i++) dimmed[i] = gfx_mix(pal[i], 0, t);
+ pal = dimmed;
+ }
+ if (2 * radius > dw) radius = dw / 2;
+ if (2 * radius > dh) radius = dh / 2;
+ uint32_t step = ((uint32_t)sw << 16) / (uint32_t)dw;
+ int x0 = NP_MAX(dx, gfx_clip_x0), x1 = NP_MIN(dx + dw, gfx_clip_x1);
+ for (int row = ya; row < yb; row++) {
+ int j = row - dy;
+ const uint8_t *src = idx + (uint32_t)(j * sh / dh) * sw;
+ float fdy = row_dy(j, dh, radius);
+ int in0 = 0, in1 = dw; /* fully covered columns (relative) */
+ color_t *p = px_at(0, row);
+ if (fdy > 0) {
+ for (int i = 0; i < radius; i++) {
+ int cov = corner_cov(i, radius, fdy);
+ if (cov >= 32) break;
+ in0 = i + 1;
+ in1 = dw - i - 1;
+ if (cov <= 0) continue;
+ int xl = dx + i, xr = dx + dw - 1 - i;
+ if (xl >= x0 && xl < x1) p[xl] = gfx_mix(p[xl], pal[src[(uint32_t)i * step >> 16]], cov);
+ if (xr >= x0 && xr < x1) p[xr] = gfx_mix(p[xr], pal[src[(uint32_t)(dw - 1 - i) * step >> 16]], cov);
+ }
+ }
+ int a0 = NP_MAX(x0, dx + in0), a1 = NP_MIN(x1, dx + in1);
+ uint32_t fx = (uint32_t)(a0 - dx) * step;
+ for (int x = a0; x < a1; x++, fx += step) p[x] = pal[src[fx >> 16]];
+ }
+}
+
+void gfx_mask(const uint8_t *mask, int w, int h, int x, int y, color_t c, int a) {
+ int ya = NP_MAX(y, gfx_y0), yb = NP_MIN(y + h, gfx_y1);
+ for (int row = ya; row < yb; row++) {
+ int j = row - y;
+ for (int i = 0; i < w; i++) {
+ int px = x + i;
+ if (px < 0 || px >= SCREEN_W) continue;
+ int n = j * w + i;
+ int cov = (mask[n >> 1] >> ((n & 1) * 4)) & 15;
+ if (!cov) continue;
+ int k = (cov * a + 60) / 120; /* 0..32 */
+ color_t *p = px_at(px, row);
+ *p = gfx_mix(*p, c, NP_MIN(k, 32));
+ }
+ }
+}
+
+void gfx_corners(int x, int y, int w, int h, int r, color_t c) {
+ if (2 * r > w) r = w / 2;
+ if (2 * r > h) r = h / 2;
+ int ya = NP_MAX(y, gfx_y0), yb = NP_MIN(y + h, gfx_y1);
+ for (int row = ya; row < yb; row++) {
+ float dy = row_dy(row - y, h, r);
+ if (dy <= 0) continue;
+ for (int i = 0; i < r; i++) {
+ int cov = corner_cov(i, r, dy);
+ if (cov >= 32) break;
+ int xl = x + i, xr = x + w - 1 - i;
+ if (xl >= 0 && xl < SCREEN_W) span_alpha(px_at(xl, row), 1, c, 32 - cov);
+ if (xr >= 0 && xr < SCREEN_W) span_alpha(px_at(xr, row), 1, c, 32 - cov);
+ }
+ }
+}
+
+void gfx_icon(const np_icon_t *icon, int x, int y, color_t c, int a) { gfx_mask(icon->data, icon->w, icon->h, x, y, c, a); }
+
+static const np_glyph_t *glyph(const np_font_t *f, char ch) {
+ unsigned i = (unsigned char)ch - f->first;
+ return i < f->count ? &f->glyphs[i] : &f->glyphs['?' - f->first];
+}
+
+int gfx_text(const np_font_t *f, int x, int baseline, const char *s, color_t c, int a) {
+ int top = baseline - f->ascent, bottom = baseline + f->descent;
+ bool visible = bottom > gfx_y0 && top < gfx_y1;
+ for (; *s; s++) {
+ const np_glyph_t *g = glyph(f, *s);
+ if (visible && g->w) gfx_mask(f->data + g->offset, g->w, g->h, x + g->x, baseline + g->y, c, a);
+ x += g->advance;
+ }
+ return x;
+}
+
+int gfx_text_width(const np_font_t *f, const char *s) {
+ int w = 0;
+ for (; *s; s++) w += glyph(f, *s)->advance;
+ return w;
+}
+
+void gfx_text_center(const np_font_t *f, int cx, int baseline, const char *s, color_t c, int a) {
+ gfx_text(f, cx - gfx_text_width(f, s) / 2, baseline, s, c, a);
+}
+
+void gfx_text_right(const np_font_t *f, int rx, int baseline, const char *s, color_t c, int a) {
+ gfx_text(f, rx - gfx_text_width(f, s), baseline, s, c, a);
+}
+
+int gfx_paragraph(const np_font_t *f, int cx, int baseline, int width, int line, const char *s, color_t c, int a) {
+ char buf[96];
+ while (*s) {
+ /* take as many words as fit */
+ int n = 0, last_space = -1, wpx = 0;
+ while (s[n] && s[n] != '\n' && n < (int)sizeof(buf) - 1) {
+ wpx += glyph(f, s[n])->advance;
+ if (s[n] == ' ') last_space = n;
+ if (wpx > width && last_space > 0) {
+ n = last_space;
+ break;
+ }
+ n++;
+ }
+ memcpy(buf, s, (size_t)n);
+ buf[n] = 0;
+ gfx_text_center(f, cx, baseline, buf, c, a);
+ baseline += line;
+ s += n;
+ while (*s == ' ' || *s == '\n') s++;
+ }
+ return baseline;
+}
diff --git a/launcher/src/gfx.h b/launcher/src/gfx.h
new file mode 100644
index 00000000..b1dfd7a6
--- /dev/null
+++ b/launcher/src/gfx.h
@@ -0,0 +1,53 @@
+/* Frames are drawn in horizontal strips: a scene function is called once per
+ * strip and every primitive clips itself to the strip's rows. The whole screen
+ * never has to fit in RAM. */
+#ifndef NP_GFX_H
+#define NP_GFX_H
+#include "font.h"
+#include "np.h"
+
+#define STRIP_H 16
+extern color_t *gfx_buf; /* SCREEN_W x STRIP_H pixels */
+extern int gfx_y0, gfx_y1; /* rows of the strip being drawn */
+
+typedef void (*gfx_scene_t)(void *ctx);
+void gfx_init(void); /* takes the strip buffer from the arena */
+void gfx_render(gfx_scene_t scene, void *ctx, int y0, int y1);
+
+color_t gfx_mix(color_t a, color_t b, int t32); /* t32 = 0..32 */
+color_t gfx_rgb(uint32_t rgb888);
+uint32_t gfx_lerp888(uint32_t a, uint32_t b, int t256);
+
+void gfx_fill(int x, int y, int w, int h, color_t c);
+void gfx_fill_alpha(int x, int y, int w, int h, color_t c, int a256);
+void gfx_vgrad(int x, int y, int w, int h, uint32_t top, uint32_t bottom);
+void gfx_rrect(int x, int y, int w, int h, int r, color_t c, int a256);
+void gfx_rrect_outline(int x, int y, int w, int h, int r, int t, color_t c, int a256);
+void gfx_shadow(int x, int y, int w, int h, int r, int blur, int a256);
+void gfx_circle(int cx, int cy, int r, color_t c, int a256);
+/* Palette image scaled into (dx, dy, dw, dh), with rounded corners. `dim`
+ * darkens it (0..256). */
+void gfx_image(const uint8_t *idx, const color_t *pal, int ncolors, int sw, int sh, int dx, int dy, int dw, int dh,
+ int radius, int dim);
+void gfx_mask(const uint8_t *mask, int w, int h, int x, int y, color_t c, int a256);
+/* Paints the outside of the rounded corners of (x, y, w, h) with c. */
+void gfx_corners(int x, int y, int w, int h, int r, color_t c);
+/* Horizontal clip for gfx_image (defaults to the whole screen). */
+extern int gfx_clip_x0, gfx_clip_x1;
+
+int gfx_text(const np_font_t *f, int x, int baseline, const char *s, color_t c, int a256);
+int gfx_text_width(const np_font_t *f, const char *s);
+void gfx_text_center(const np_font_t *f, int cx, int baseline, const char *s, color_t c, int a256);
+void gfx_text_right(const np_font_t *f, int rx, int baseline, const char *s, color_t c, int a256);
+/* Word-wrapped paragraph, centred; returns the baseline after the last line. */
+int gfx_paragraph(const np_font_t *f, int cx, int baseline, int width, int line, const char *s, color_t c, int a256);
+
+/* Icons (icons.c, generated by tools/icongen.py): 4-bit masks. */
+typedef struct {
+ uint8_t w, h;
+ const uint8_t *data;
+} np_icon_t;
+extern const np_icon_t np_icon_gear, np_icon_warning, np_icon_trash, np_icon_play, np_icon_check, np_icon_back,
+ np_icon_left, np_icon_right, np_icon_logo;
+void gfx_icon(const np_icon_t *icon, int x, int y, color_t c, int a256);
+#endif
diff --git a/launcher/src/home.c b/launcher/src/home.c
new file mode 100644
index 00000000..43829cad
--- /dev/null
+++ b/launcher/src/home.c
@@ -0,0 +1,270 @@
+/* The home screen: a carousel of game cards. The selected card is large,
+ * its neighbours peek in from the sides, and the card cycles through the
+ * game's screenshots. The last card opens the settings. */
+#include "ui.h"
+
+#define CARD_W 200
+#define CARD_H 152
+#define CARD_CX 160
+#define CARD_CY 103
+#define SPACING 184
+#define FRAME 4
+#define SHOT_MS 2600
+#define SLIDE_MS 520
+
+#define SETTINGS_TOP 0x4A5163
+#define SETTINGS_BOTTOM 0x1C1F27
+#define SETTINGS_ACCENT 0x6C7A96
+
+typedef struct {
+ int n;
+ int8_t item[16]; /* game index, or -1 for the settings card */
+ int sel;
+ float pos; /* scroll position, in cards */
+ int shot; /* screenshot shown on the selected card */
+ float slide; /* 0..1 while sliding to the next screenshot */
+ uint32_t shot_time; /* ms spent on the current screenshot */
+ float badge; /* play badge, 0..1 */
+ float zoom; /* launch animation, 0..1 */
+ float intro;
+} home_t;
+
+static bool first_open = true;
+
+static uint32_t item_color(int game, int which) {
+ if (game < 0) return which == 0 ? SETTINGS_TOP : which == 1 ? SETTINGS_BOTTOM : SETTINGS_ACCENT;
+ const np_game_t *g = &np_games[game];
+ return which == 0 ? g->top : which == 1 ? g->bottom : g->accent;
+}
+
+static const char *item_title(int game) { return game < 0 ? "Settings" : np_games[game].title; }
+static const char *item_tagline(int game) { return game < 0 ? "Uninstall games to free up space" : np_games[game].tagline; }
+
+static float absf(float v) { return v < 0 ? -v : v; }
+
+/* ---- drawing */
+static void draw_settings_art(int x, int y, int w, int h, int dim) {
+ uint32_t top = gfx_lerp888(0x59627A, 0, dim), bottom = gfx_lerp888(0x2A2F3B, 0, dim);
+ gfx_vgrad(x, y, w, h, top, bottom);
+ const np_icon_t *gear = &np_icon_gear;
+ if (w > gear->w + 8) gfx_icon(gear, x + (w - gear->w) / 2, y + (h - gear->h) / 2 - 2, 0xFFFF, 200 - dim / 2);
+}
+
+static void draw_card(home_t *h, int k, float d) {
+ int game = h->item[k];
+ float ad = absf(d);
+ float s = 1 - 0.26f * NP_MIN(ad, 1.5f);
+ float z = h->zoom;
+ float cx = CARD_CX + d * SPACING, cy = CARD_CY;
+ float w = CARD_W * s, hh = CARD_H * s;
+ float frame = FRAME * s, radius = 12 * s;
+ int dim = (int)(130 * NP_MIN(ad, 1.f));
+ if (k == h->sel && z > 0) { /* launching: grow to the whole screen */
+ float e = ui_ease_in_out(z);
+ cx += (160 - cx) * e;
+ cy += (120 - cy) * e;
+ w += (SCREEN_W + 2 * frame - w) * e;
+ hh += (SCREEN_H + 2 * frame - hh) * e;
+ radius *= 1 - e;
+ }
+ int x = (int)(cx - w / 2), y = (int)(cy - hh / 2), iw = (int)w, ih = (int)hh;
+ if (x >= SCREEN_W || x + iw <= 0) return;
+ if (ad < 0.6f && z == 0) gfx_shadow(x, y + 5, iw, ih, (int)radius, 12, 120);
+ color_t frame_color = gfx_mix(0xFFFF, 0, dim >> 3);
+ gfx_rrect(x, y, iw, ih, (int)radius, frame_color, 256);
+ int fx = (int)frame, ir = NP_MAX((int)(radius - frame + 1), 0);
+ int ix = x + fx, iy = y + fx, iiw = iw - 2 * fx, iih = ih - 2 * fx;
+ if (game < 0) {
+ draw_settings_art(ix, iy, iiw, iih, dim);
+ } else {
+ const np_game_t *g = &np_games[game];
+ int shot = k == h->sel ? h->shot : 0;
+ gfx_clip_x0 = NP_MAX(ix, 0);
+ gfx_clip_x1 = NP_MIN(ix + iiw, SCREEN_W);
+ int off = k == h->sel ? (int)(ui_ease_in_out(h->slide) * iiw) : 0;
+ const uint8_t *px = ui_shot(game, shot);
+ const np_shot_t *sh = &g->shots[shot];
+ if (px) gfx_image(px, sh->palette, sh->ncolors, SHOT_W, SHOT_H, ix - off, iy, iiw, iih, 0, dim);
+ else gfx_fill(ix, iy, iiw, iih, gfx_rgb(gfx_lerp888(g->bottom, 0, dim)));
+ if (off) {
+ int next = (shot + 1) % g->nshots;
+ const uint8_t *px2 = ui_shot(game, next);
+ const np_shot_t *sh2 = &g->shots[next];
+ if (px2) gfx_image(px2, sh2->palette, sh2->ncolors, SHOT_W, SHOT_H, ix - off + iiw, iy, iiw, iih, 0, dim);
+ }
+ gfx_clip_x0 = 0;
+ gfx_clip_x1 = SCREEN_W;
+ }
+ gfx_corners(ix, iy, iiw, iih, ir, frame_color);
+ /* play badge on the selected game */
+ if (k == h->sel && game >= 0 && h->badge > 0 && z == 0) {
+ float b = ui_ease_out(h->badge);
+ int r = (int)(15 * b);
+ int bx = x + iw - 14, by = y + ih - 14;
+ gfx_circle(bx, by + 2, r + 2, 0, 60);
+ gfx_circle(bx, by, r + 2, 0xFFFF, 256);
+ gfx_circle(bx, by, r, gfx_rgb(item_color(game, 2)), 256);
+ if (b > 0.8f) gfx_icon(&np_icon_play, bx - 4, by - 6, 0xFFFF, (int)(256 * (b - 0.8f) * 5));
+ }
+}
+
+static void scene(void *ctx) {
+ home_t *h = ctx;
+ /* background: the theme of the card in front, blended while scrolling */
+ int a = (int)h->pos;
+ if (a < 0) a = 0;
+ if (a > h->n - 1) a = h->n - 1;
+ int b = NP_MIN(a + 1, h->n - 1);
+ int t = (int)((h->pos - a) * 256);
+ t = NP_CLAMP(t, 0, 256);
+ 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);
+
+ float z = ui_ease_in_out(h->zoom);
+ int ui_alpha = (int)(256 * (1 - z));
+ /* header */
+ if (gfx_y0 < 26 && ui_alpha > 0) {
+ gfx_icon(&np_icon_logo, 12, 6, 0xFFFF, ui_alpha);
+ gfx_text(&np_font_body, 40, 18, "NumPlay", 0xFFFF, ui_alpha);
+ /* where we are in the carousel */
+ int dots_w = h->n * 10 + 8;
+ int dx = SCREEN_W - 12 - dots_w;
+ for (int i = 0; i < h->n; i++) {
+ float near = 1 - NP_MIN(absf(i - h->pos), 1.f);
+ int w = 6 + (int)(10 * near);
+ gfx_rrect(dx, 11, w, 6, 3, 0xFFFF, (int)((90 + 166 * near) * ui_alpha / 256));
+ dx += w + 4;
+ }
+ }
+ /* cards, far ones first */
+ int lo = NP_MAX((int)h->pos - 2, 0), hi = NP_MIN((int)h->pos + 2, h->n - 1);
+ for (int pass = 3; pass >= 0; pass--)
+ for (int k = lo; k <= hi; k++) {
+ float d = k - h->pos;
+ int ring = absf(d) < 0.5f ? 0 : absf(d) < 1.5f ? 1 : absf(d) < 2.5f ? 2 : 3;
+ if (ring == pass && (k == h->sel || z < 1)) draw_card(h, k, d);
+ }
+ if (ui_alpha <= 0) return;
+ /* screenshot progress under the card */
+ int front = (int)(h->pos + 0.5f);
+ front = NP_CLAMP(front, 0, h->n - 1);
+ float away = absf(h->pos - front);
+ int text_alpha = (int)(ui_alpha * NP_CLAMP(1 - away * 2.2f, 0.f, 1.f));
+ int game = h->item[front];
+ if (gfx_y1 > 180 && text_alpha > 0) {
+ if (game >= 0 && np_games[game].nshots > 1) {
+ int n = np_games[game].nshots, seg = 22, gap = 5;
+ int x0 = CARD_CX - (n * seg + (n - 1) * gap) / 2;
+ float progress = front == h->sel ? (h->slide > 0 ? 1.f : NP_MIN(h->shot_time / (float)SHOT_MS, 1.f)) : 0;
+ for (int i = 0; i < n; i++) {
+ int x = x0 + i * (seg + gap);
+ gfx_rrect(x, 185, seg, 4, 2, 0xFFFF, text_alpha * 70 / 256);
+ int fill = i < h->shot ? seg : i == h->shot ? (int)(seg * progress) : 0;
+ if (fill >= 4) gfx_rrect(x, 185, fill, 4, 2, 0xFFFF, text_alpha * 230 / 256);
+ }
+ }
+ gfx_text_center(&np_font_title, CARD_CX, 213, item_title(game), 0xFFFF, text_alpha);
+ gfx_text_center(&np_font_body, CARD_CX, 231, item_tagline(game), 0xFFFF, text_alpha * 190 / 256);
+ }
+}
+
+/* ---- behaviour */
+static int build_items(home_t *h) {
+ h->n = 0;
+ for (int i = 0; i < np_game_count && h->n < 15; i++)
+ if (np_game_installed(i)) h->item[h->n++] = (int8_t)i;
+ h->item[h->n++] = -1;
+ return h->n;
+}
+
+int np_home(int *selected) {
+ ui_init();
+ home_t h = {0};
+ build_items(&h);
+ h.sel = h.n - 1;
+ for (int k = 0; k < h.n; k++)
+ if (h.item[k] == *selected) h.sel = k;
+ if (*selected == -1) h.sel = h.n - 1;
+ if (h.n == 1) h.sel = 0;
+ h.pos = h.sel;
+ if (first_open) {
+ h.pos = h.sel + 1.2f;
+ first_open = false;
+ }
+ ui_keys_t keys = {np_keys(), 0, 0}; /* ignore keys still held from before */
+ uint32_t last = np_millis();
+ bool dirty = true;
+ int result = -3;
+ for (;;) {
+ uint32_t now = np_millis();
+ float dt = NP_MIN((now - last) / 1000.f, 0.05f);
+ uint32_t elapsed = now - last;
+ last = now;
+ uint32_t pressed = ui_poll(&keys);
+ if (result == -3) {
+ int before = h.sel;
+ if (pressed & K_LEFT) h.sel = NP_MAX(h.sel - 1, 0);
+ if (pressed & K_RIGHT) h.sel = NP_MIN(h.sel + 1, h.n - 1);
+ if (h.sel != before) {
+ h.shot = 0;
+ h.slide = 0;
+ h.shot_time = 0;
+ h.badge = 0;
+ }
+ if (pressed & K_OK) result = h.item[h.sel];
+ if (pressed & K_HOME) return -2;
+ }
+ /* motion */
+ float pos = ui_approach(h.pos, (float)h.sel, dt, 0.075f);
+ bool moving = pos != h.pos;
+ if (moving) dirty = true;
+ h.pos = pos;
+ int game = h.item[h.sel];
+ bool settled = !moving;
+ if (settled && game >= 0 && result == -3) {
+ if (h.badge < 1) {
+ h.badge = NP_MIN(h.badge + dt / 0.22f, 1.f);
+ dirty = true;
+ }
+ if (np_games[game].nshots > 1) {
+ if (h.slide > 0) {
+ h.slide += elapsed / (float)SLIDE_MS;
+ if (h.slide >= 1) {
+ h.slide = 0;
+ h.shot = (h.shot + 1) % np_games[game].nshots;
+ h.shot_time = 0;
+ }
+ dirty = true;
+ } else {
+ uint32_t before = h.shot_time * 22 / SHOT_MS;
+ h.shot_time += elapsed;
+ if (h.shot_time >= SHOT_MS) h.slide = 0.0001f;
+ if (h.shot_time * 22 / SHOT_MS != before) dirty = true; /* the progress bar moves */
+ }
+ }
+ }
+ if (result != -3) {
+ if (result == -1 || !settled) {
+ if (result == -1) {
+ *selected = -1;
+ return -1;
+ }
+ } else {
+ h.zoom = NP_MIN(h.zoom + dt / 0.24f, 1.f);
+ dirty = true;
+ if (h.zoom >= 1) {
+ ui_frame(scene, &h);
+ *selected = result;
+ return result;
+ }
+ }
+ }
+ if (dirty) {
+ ui_frame(scene, &h);
+ dirty = false;
+ } else {
+ np_sleep(16);
+ }
+ }
+}
diff --git a/launcher/src/icons.c b/launcher/src/icons.c
new file mode 100644
index 00000000..d02d8e26
--- /dev/null
+++ b/launcher/src/icons.c
@@ -0,0 +1,158 @@
+/* Generated by tools/icongen.py. */
+#include "gfx.h"
+
+static const uint8_t gear_data[882] = {
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,166,21,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 132,0,0,0,0,48,255,255,9,0,0,0,0,0,0,0,0,0,0,0,179,255,27,0,
+ 0,0,225,255,255,13,0,0,0,0,0,0,0,0,0,0,48,255,255,223,3,0,0,252,
+ 255,255,15,0,0,0,0,0,0,0,0,0,0,32,255,255,255,94,0,160,255,255,255,47,
+ 0,0,0,0,0,0,0,0,0,0,16,255,255,255,255,237,255,255,255,255,79,0,0,0,
+ 0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,111,0,0,0,0,0,0,
+ 0,0,0,0,0,253,255,255,255,255,255,255,255,255,175,0,0,0,0,0,0,0,0,0,
+ 0,0,252,255,255,255,255,255,255,255,255,255,27,0,0,33,0,0,0,0,0,0,16,253,
+ 255,255,255,255,255,255,255,255,255,223,219,254,255,4,0,0,0,0,0,176,255,255,255,255,
+ 255,255,255,255,255,255,255,255,255,255,11,0,0,0,16,83,249,255,255,255,255,255,255,255,
+ 255,255,255,255,255,255,255,95,0,0,217,255,255,255,255,255,255,255,255,255,255,255,255,255,
+ 255,255,255,255,143,0,32,255,255,255,255,255,255,255,255,107,68,182,255,255,255,255,255,255,
+ 255,11,0,96,255,255,255,255,255,255,255,77,0,0,0,212,255,255,255,255,255,223,1,0,
+ 176,255,255,255,255,255,255,223,1,0,0,0,16,253,255,255,255,255,62,0,0,96,255,255,
+ 255,255,255,255,79,0,0,0,0,0,244,255,255,255,255,5,0,0,0,228,255,255,255,255,
+ 255,11,0,0,0,0,0,176,255,255,255,223,0,0,0,0,32,253,255,255,255,255,6,0,
+ 0,0,0,0,96,255,255,255,255,0,0,0,0,0,177,255,255,255,255,4,0,0,0,0,
+ 0,64,255,255,255,255,1,0,0,0,0,16,255,255,255,255,4,0,0,0,0,0,64,255,
+ 255,255,255,9,0,0,0,0,0,255,255,255,255,6,0,0,0,0,0,96,255,255,255,255,
+ 207,1,0,0,0,0,254,255,255,255,11,0,0,0,0,0,176,255,255,255,255,255,62,0,
+ 0,0,80,255,255,255,255,79,0,0,0,0,0,244,255,255,255,255,255,255,6,0,0,227,
+ 255,255,255,255,223,1,0,0,0,16,253,255,255,255,255,255,255,11,0,16,253,255,255,255,
+ 255,255,77,0,0,0,212,255,255,255,255,255,255,255,6,0,176,255,255,255,255,255,255,255,
+ 107,68,182,255,255,255,255,255,255,255,255,2,0,248,255,255,255,255,255,255,255,255,255,255,
+ 255,255,255,255,255,255,255,157,0,0,245,255,255,255,255,255,255,255,255,255,255,255,255,255,
+ 255,159,53,1,0,0,0,176,255,255,255,255,255,255,255,255,255,255,255,255,255,255,11,0,
+ 0,0,0,0,64,255,239,189,253,255,255,255,255,255,255,255,255,255,223,1,0,0,0,0,
+ 0,0,18,0,0,177,255,255,255,255,255,255,255,255,255,207,0,0,0,0,0,0,0,0,
+ 0,0,0,250,255,255,255,255,255,255,255,255,223,0,0,0,0,0,0,0,0,0,0,0,
+ 246,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,244,255,255,
+ 255,255,222,255,255,255,255,1,0,0,0,0,0,0,0,0,0,0,242,255,255,255,11,0,
+ 229,255,255,255,2,0,0,0,0,0,0,0,0,0,0,240,255,255,223,1,0,48,253,255,
+ 255,3,0,0,0,0,0,0,0,0,0,0,208,255,255,46,0,0,0,177,255,59,0,0,
+ 0,0,0,0,0,0,0,0,0,144,255,255,4,0,0,0,0,72,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,81,106,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+};
+const np_icon_t np_icon_gear = {42, 42, gear_data};
+
+static const uint8_t warning_data[920] = {
+ 0,0,0,0,0,0,0,0,0,0,32,237,3,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,160,255,11,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,244,255,95,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,252,255,223,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,96,255,255,255,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,225,255,255,255,47,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,248,255,255,255,175,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,32,255,255,255,255,255,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 176,255,255,255,255,255,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,244,
+ 255,255,255,255,255,111,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,255,
+ 255,255,255,255,239,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,112,255,255,255,
+ 255,255,255,255,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,225,255,255,255,255,
+ 255,255,255,63,0,0,0,0,0,0,0,0,0,0,0,0,0,0,249,255,255,159,68,232,
+ 255,255,191,0,0,0,0,0,0,0,0,0,0,0,0,0,48,255,255,239,3,0,32,253,
+ 255,255,5,0,0,0,0,0,0,0,0,0,0,0,0,192,255,255,111,0,0,0,244,255,
+ 255,13,0,0,0,0,0,0,0,0,0,0,0,0,245,255,255,15,0,0,0,208,255,255,
+ 127,0,0,0,0,0,0,0,0,0,0,0,16,254,255,255,13,0,0,0,176,255,255,255,
+ 2,0,0,0,0,0,0,0,0,0,0,128,255,255,255,13,0,0,0,176,255,255,255,10,
+ 0,0,0,0,0,0,0,0,0,0,242,255,255,255,13,0,0,0,176,255,255,255,79,0,
+ 0,0,0,0,0,0,0,0,0,250,255,255,255,13,0,0,0,176,255,255,255,207,0,0,
+ 0,0,0,0,0,0,0,64,255,255,255,255,13,0,0,0,176,255,255,255,255,6,0,0,
+ 0,0,0,0,0,0,208,255,255,255,255,13,0,0,0,176,255,255,255,255,30,0,0,0,
+ 0,0,0,0,0,246,255,255,255,255,13,0,0,0,176,255,255,255,255,143,0,0,0,0,
+ 0,0,0,16,254,255,255,255,255,47,0,0,0,224,255,255,255,255,255,2,0,0,0,0,
+ 0,0,144,255,255,255,255,255,159,0,0,0,247,255,255,255,255,255,11,0,0,0,0,0,
+ 0,243,255,255,255,255,255,255,8,0,112,255,255,255,255,255,255,79,0,0,0,0,0,0,
+ 251,255,255,255,255,255,255,239,170,253,255,255,255,255,255,255,223,0,0,0,0,0,80,255,
+ 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,7,0,0,0,0,208,255,255,
+ 255,255,255,255,255,191,136,251,255,255,255,255,255,255,255,30,0,0,0,0,248,255,255,255,
+ 255,255,255,239,4,0,64,254,255,255,255,255,255,255,159,0,0,0,32,255,255,255,255,255,
+ 255,255,79,0,0,0,244,255,255,255,255,255,255,255,3,0,0,160,255,255,255,255,255,255,
+ 255,10,0,0,0,160,255,255,255,255,255,255,255,12,0,0,244,255,255,255,255,255,255,255,
+ 6,0,0,0,96,255,255,255,255,255,255,255,95,0,0,252,255,255,255,255,255,255,255,6,
+ 0,0,0,96,255,255,255,255,255,255,255,239,1,96,255,255,255,255,255,255,255,255,9,0,
+ 0,0,144,255,255,255,255,255,255,255,255,8,225,255,255,255,255,255,255,255,255,46,0,0,
+ 0,226,255,255,255,255,255,255,255,255,47,249,255,255,255,255,255,255,255,255,207,1,0,16,
+ 252,255,255,255,255,255,255,255,255,191,255,255,255,255,255,255,255,255,255,255,142,68,232,255,
+ 255,255,255,255,255,255,255,255,255,249,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
+ 255,255,255,255,255,255,255,191,
+};
+const np_icon_t np_icon_warning = {46, 40, warning_data};
+
+static const uint8_t trash_data[112] = {
+ 0,0,48,153,4,0,0,0,0,224,255,31,0,0,64,136,248,255,143,136,5,208,255,255,
+ 255,255,255,15,64,152,187,187,187,137,5,0,228,255,255,255,95,0,0,219,68,68,68,203,
+ 0,0,187,246,0,111,217,0,0,187,246,0,111,217,0,0,187,246,0,111,217,0,0,187,
+ 246,0,111,217,0,0,187,246,0,111,217,0,0,187,246,0,111,217,0,0,187,131,0,56,
+ 217,0,0,248,187,187,187,174,0,0,129,187,187,187,25,0,
+};
+const np_icon_t np_icon_trash = {14, 16, trash_data};
+
+static const uint8_t play_data[66] = {
+ 129,3,0,0,0,64,255,25,0,0,0,244,255,126,0,0,64,255,255,223,4,0,244,255,
+ 255,255,43,64,255,255,255,255,143,244,255,255,255,255,73,255,255,255,207,3,244,255,255,93,
+ 0,64,255,239,7,0,0,244,159,1,0,0,32,58,0,0,0,0,
+};
+const np_icon_t np_icon_play = {11, 12, play_data};
+
+static const uint8_t check_data[450] = {
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,68,0,0,0,0,0,0,0,0,0,0,0,0,0,64,255,4,0,0,0,0,0,0,
+ 0,0,0,0,0,0,209,255,4,0,0,0,0,0,0,0,0,0,0,0,0,252,111,0,
+ 0,0,0,0,0,0,0,0,0,0,0,160,255,9,0,0,0,0,0,0,0,0,0,0,
+ 0,0,247,191,0,0,0,0,0,0,0,0,0,0,0,0,80,255,29,0,0,0,0,0,
+ 0,0,0,0,0,0,0,227,239,2,0,0,0,0,0,0,0,0,0,0,0,16,253,79,
+ 0,0,0,0,0,0,0,0,0,0,0,0,192,255,6,0,0,0,0,179,5,0,0,0,
+ 0,0,0,250,159,0,0,0,0,0,251,79,0,0,0,0,0,112,255,11,0,0,0,0,
+ 0,245,239,4,0,0,0,0,245,223,1,0,0,0,0,0,64,254,78,0,0,0,48,254,
+ 46,0,0,0,0,0,0,0,228,239,4,0,0,209,255,4,0,0,0,0,0,0,0,64,
+ 254,78,0,0,252,111,0,0,0,0,0,0,0,0,0,228,239,4,160,255,9,0,0,0,
+ 0,0,0,0,0,0,64,254,78,247,191,0,0,0,0,0,0,0,0,0,0,0,228,239,
+ 255,29,0,0,0,0,0,0,0,0,0,0,0,64,254,239,2,0,0,0,0,0,0,0,
+ 0,0,0,0,0,244,79,0,0,0,0,0,0,0,0,0,0,0,0,0,64,4,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+};
+const np_icon_t np_icon_check = {30, 30, check_data};
+
+static const uint8_t back_data[84] = {
+ 0,0,0,0,0,0,0,0,0,64,26,0,0,0,0,0,245,47,0,0,0,0,128,239,
+ 4,0,0,0,0,250,45,0,0,0,0,176,255,222,221,221,221,111,192,255,221,221,221,221,
+ 111,16,251,27,0,0,0,0,0,128,223,3,0,0,0,0,0,246,47,0,0,0,0,0,
+ 64,26,0,0,0,0,0,0,0,0,0,0,
+};
+const np_icon_t np_icon_back = {14, 12, back_data};
+
+static const uint8_t left_data[56] = {
+ 0,0,96,7,0,0,244,31,0,16,253,9,0,160,223,1,0,245,63,0,32,254,7,0,
+ 192,191,0,0,208,159,0,0,48,255,4,0,0,247,30,0,0,176,191,0,0,16,253,7,
+ 0,0,244,31,0,0,96,7,
+};
+const np_icon_t np_icon_left = {8, 14, left_data};
+
+static const uint8_t right_data[56] = {
+ 96,7,0,0,224,111,0,0,112,239,2,0,0,251,12,0,0,225,143,0,0,80,255,4,
+ 0,0,249,13,0,0,248,30,0,64,255,3,0,209,127,0,0,251,11,0,112,239,1,0,
+ 224,79,0,0,96,7,0,0,
+};
+const np_icon_t np_icon_right = {8, 14, right_data};
+
+static const uint8_t logo_data[165] = {
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,49,68,68,68,68,68,20,0,0,0,162,
+ 255,255,255,255,255,255,255,59,0,64,254,79,196,255,255,255,255,255,255,5,225,255,15,176,
+ 255,255,255,221,255,255,46,248,255,15,176,255,255,175,0,251,255,175,252,239,13,160,253,255,
+ 111,0,248,255,239,255,79,0,0,208,255,223,67,140,252,255,254,127,4,48,228,255,255,255,
+ 2,225,255,251,255,15,176,255,255,255,255,1,224,223,245,255,15,176,255,255,255,255,108,251,
+ 127,176,255,15,176,255,255,255,255,255,255,12,16,250,159,233,255,255,255,255,255,191,1,0,
+ 64,218,221,221,221,221,221,173,5,0,0,0,0,0,0,0,0,0,0,0,0,
+};
+const np_icon_t np_icon_logo = {22, 15, logo_data};
diff --git a/launcher/src/inflate.c b/launcher/src/inflate.c
new file mode 100644
index 00000000..2ee87321
--- /dev/null
+++ b/launcher/src/inflate.c
@@ -0,0 +1,193 @@
+/* Raw DEFLATE (RFC 1951) decoder for the screenshots. Huffman codes of up to
+ * 9 bits are decoded with one table lookup; longer ones bit by bit. The tables
+ * live in memory the caller provides (the arena), not in static RAM. */
+#include "inflate.h"
+#include <string.h>
+
+typedef struct {
+ uint16_t fast[512]; /* (length << 9) | symbol for codes of up to 9 bits, 0 otherwise */
+ uint16_t count[16];
+ uint16_t symbol[288];
+} huff_t;
+
+struct np_inflate_tables {
+ huff_t lit, dist;
+};
+
+typedef struct {
+ const uint8_t *in, *end;
+ uint32_t bits;
+ int nbits, overrun;
+ uint8_t *out;
+ uint32_t n, cap;
+} Z;
+
+static inline void need(Z *z, int k) {
+ while (z->nbits < k) {
+ uint32_t b = 0;
+ if (z->in < z->end) b = *z->in++;
+ else z->overrun++;
+ z->bits |= b << z->nbits;
+ z->nbits += 8;
+ }
+}
+
+static inline uint32_t take(Z *z, int k) {
+ if (!k) return 0;
+ need(z, k);
+ uint32_t v = z->bits & ((1u << k) - 1);
+ z->bits >>= k;
+ z->nbits -= k;
+ return v;
+}
+
+static bool build(huff_t *h, const uint8_t *len, int n) {
+ uint16_t offs[16], next[16];
+ memset(h->count, 0, sizeof h->count);
+ memset(h->fast, 0, sizeof h->fast);
+ for (int i = 0; i < n; i++) h->count[len[i]]++;
+ h->count[0] = 0;
+ int left = 1;
+ for (int l = 1; l < 16; l++) {
+ left = (left << 1) - h->count[l];
+ if (left < 0) return false;
+ }
+ offs[1] = 0;
+ for (int l = 1; l < 15; l++) offs[l + 1] = (uint16_t)(offs[l] + h->count[l]);
+ for (int i = 0; i < n; i++)
+ if (len[i]) h->symbol[offs[len[i]]++] = (uint16_t)i;
+ /* canonical codes, bit-reversed for the fast table */
+ int code = 0;
+ for (int l = 1; l < 16; l++) {
+ code = (code + (l > 1 ? h->count[l - 1] : 0)) << 1;
+ next[l] = (uint16_t)code;
+ }
+ for (int i = 0; i < n; i++) {
+ int l = len[i];
+ if (!l) continue;
+ int c = next[l]++;
+ if (l > 9) continue;
+ int rev = 0;
+ for (int b = 0; b < l; b++) rev |= ((c >> b) & 1) << (l - 1 - b);
+ for (int k = rev; k < 512; k += 1 << l) h->fast[k] = (uint16_t)(l << 9 | i);
+ }
+ return true;
+}
+
+static int decode(Z *z, const huff_t *h) {
+ need(z, 9);
+ uint16_t e = h->fast[z->bits & 511];
+ if (e) {
+ int l = e >> 9;
+ z->bits >>= l;
+ z->nbits -= l;
+ return e & 511;
+ }
+ int code = 0, first = 0, index = 0;
+ for (int l = 1; l < 16; l++) {
+ code |= (int)take(z, 1);
+ int count = h->count[l];
+ if (code - count < first) return h->symbol[index + (code - first)];
+ index += count;
+ first = (first + count) << 1;
+ code <<= 1;
+ }
+ return -1;
+}
+
+static const uint16_t len_base[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27,
+ 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
+static const uint8_t len_extra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
+static const uint16_t dist_base[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129,
+ 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
+static const uint8_t dist_extra[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
+
+static bool codes(Z *z, const huff_t *lit, const huff_t *dist) {
+ for (;;) {
+ int sym = decode(z, lit);
+ if (sym < 0 || z->overrun > 4) return false;
+ if (sym < 256) {
+ if (z->n >= z->cap) return false;
+ z->out[z->n++] = (uint8_t)sym;
+ } else if (sym == 256) {
+ return true;
+ } else {
+ sym -= 257;
+ if (sym >= 29) return false;
+ uint32_t len = len_base[sym] + take(z, len_extra[sym]);
+ int d = decode(z, dist);
+ if (d < 0 || d >= 30) return false;
+ uint32_t back = dist_base[d] + take(z, dist_extra[d]);
+ if (back > z->n || z->n + len > z->cap) return false;
+ uint8_t *o = z->out + z->n, *from = o - back;
+ for (uint32_t i = 0; i < len; i++) o[i] = from[i];
+ z->n += len;
+ }
+ }
+}
+
+uint32_t np_inflate_tables_size(void) { return sizeof(struct np_inflate_tables); }
+
+int np_inflate(uint8_t *out, uint32_t cap, const uint8_t *in, uint32_t len, np_inflate_tables_t *t) {
+ static const uint8_t order[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
+ Z z = {in, in + len, 0, 0, 0, out, 0, cap};
+ uint8_t lengths[320];
+ int last;
+ do {
+ last = (int)take(&z, 1);
+ int type = (int)take(&z, 2);
+ if (type == 0) {
+ z.bits = 0;
+ z.nbits = 0;
+ if (z.in + 4 > z.end) return -1;
+ unsigned n = z.in[0] | (unsigned)z.in[1] << 8, nn = z.in[2] | (unsigned)z.in[3] << 8;
+ z.in += 4;
+ if ((n ^ 0xFFFFu) != nn || z.in + n > z.end || z.n + n > z.cap) return -1;
+ memcpy(z.out + z.n, z.in, n);
+ z.in += n;
+ z.n += n;
+ } else if (type == 1) {
+ int i = 0;
+ for (; i < 144; i++) lengths[i] = 8;
+ for (; i < 256; i++) lengths[i] = 9;
+ for (; i < 280; i++) lengths[i] = 7;
+ for (; i < 288; i++) lengths[i] = 8;
+ build(&t->lit, lengths, 288);
+ for (i = 0; i < 30; i++) lengths[i] = 5;
+ build(&t->dist, lengths, 30);
+ if (!codes(&z, &t->lit, &t->dist)) return -1;
+ } else if (type == 2) {
+ int nlen = (int)take(&z, 5) + 257, ndist = (int)take(&z, 5) + 1, ncode = (int)take(&z, 4) + 4;
+ if (nlen > 286 || ndist > 30) return -1;
+ for (int i = 0; i < 19; i++) lengths[order[i]] = i < ncode ? (uint8_t)take(&z, 3) : 0;
+ if (!build(&t->lit, lengths, 19)) return -1;
+ int i = 0;
+ while (i < nlen + ndist) {
+ int sym = decode(&z, &t->lit);
+ if (sym < 0 || z.overrun > 4) return -1;
+ if (sym < 16) {
+ lengths[i++] = (uint8_t)sym;
+ continue;
+ }
+ int rep, val = 0;
+ if (sym == 16) {
+ if (!i) return -1;
+ val = lengths[i - 1];
+ rep = 3 + (int)take(&z, 2);
+ } else if (sym == 17) {
+ rep = 3 + (int)take(&z, 3);
+ } else {
+ rep = 11 + (int)take(&z, 7);
+ }
+ if (i + rep > nlen + ndist) return -1;
+ while (rep--) lengths[i++] = (uint8_t)val;
+ }
+ if (!lengths[256]) return -1;
+ if (!build(&t->lit, lengths, nlen) || !build(&t->dist, lengths + nlen, ndist)) return -1;
+ if (!codes(&z, &t->lit, &t->dist)) return -1;
+ } else {
+ return -1;
+ }
+ } while (!last);
+ return (int)z.n;
+}
diff --git a/launcher/src/inflate.h b/launcher/src/inflate.h
new file mode 100644
index 00000000..f33f3ef7
--- /dev/null
+++ b/launcher/src/inflate.h
@@ -0,0 +1,10 @@
+#ifndef NP_INFLATE_H
+#define NP_INFLATE_H
+#include <stdbool.h>
+#include <stdint.h>
+
+typedef struct np_inflate_tables np_inflate_tables_t;
+uint32_t np_inflate_tables_size(void);
+/* Returns the number of bytes written, or -1 if the data is invalid. */
+int np_inflate(uint8_t *out, uint32_t cap, const uint8_t *in, uint32_t len, np_inflate_tables_t *tables);
+#endif
diff --git a/launcher/src/main.c b/launcher/src/main.c
new file mode 100644
index 00000000..4dd495fa
--- /dev/null
+++ b/launcher/src/main.c
@@ -0,0 +1,24 @@
+/* NumPlay: one app for all the games. */
+#include "np.h"
+
+#if PLATFORM_DEVICE && !NP_SIMULATOR
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "NumPlay";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+#endif
+
+int main(void) {
+ np_finish_pending_uninstalls();
+ int selected = np_game_count ? 0 : -1;
+ for (;;) {
+ int r = np_home(&selected);
+ if (r == -2) break;
+ if (r == -1) {
+ np_settings();
+ continue;
+ }
+ np_game_run(r);
+ np_wait_release();
+ }
+ np_wait_release();
+ return 0;
+}
diff --git a/launcher/src/np.h b/launcher/src/np.h
new file mode 100644
index 00000000..234d3114
--- /dev/null
+++ b/launcher/src/np.h
@@ -0,0 +1,86 @@
+/* NumPlay launcher: shared definitions. */
+#ifndef NP_H
+#define NP_H
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+typedef uint16_t color_t;
+#define RGB(r, g, b) ((color_t)((((r) & 0xF8) << 8) | (((g) & 0xFC) << 3) | ((b) >> 3)))
+#define HEX(v) RGB(((v) >> 16) & 0xFF, ((v) >> 8) & 0xFF, (v) & 0xFF)
+#define SCREEN_W 320
+#define SCREEN_H 240
+#define NP_MIN(a, b) ((a) < (b) ? (a) : (b))
+#define NP_MAX(a, b) ((a) > (b) ? (a) : (b))
+#define NP_CLAMP(v, lo, hi) ((v) < (lo) ? (lo) : (v) > (hi) ? (hi) : (v))
+
+/* Keys, independent of the calculator's numbering. The number pad doubles
+ * as arrows (8 4 6 2) and 5 as OK. */
+enum {
+ K_LEFT = 1, K_RIGHT = 2, K_UP = 4, K_DOWN = 8, K_OK = 16, K_BACK = 32, K_HOME = 64, K_BACKSPACE = 128
+};
+
+/* ---- platform (platform.c) */
+uint32_t np_keys(void); /* keys held right now */
+uint32_t np_millis(void);
+void np_sleep(unsigned ms);
+void np_vblank(void);
+void np_push(int x, int y, int w, int h, const color_t *px);
+void np_fill_screen(int x, int y, int w, int h, color_t c);
+/* Waits until every key is released (after a game, or before quitting). */
+void np_wait_release(void);
+
+/* ---- one arena for everything big: the running game's RAM, or the
+ * launcher's buffers while no game runs */
+extern uint8_t np_arena[];
+extern const uint32_t np_arena_size;
+void *np_alloc(uint32_t size); /* bump allocator in the arena */
+void np_alloc_reset(void);
+
+/* ---- games (games.c, table generated by tools/gen_games.py) */
+typedef struct {
+ uint16_t w, h, ncolors;
+ uint32_t zsize;
+ const color_t *palette;
+ const uint8_t *z; /* raw DEFLATE of w*h palette indices */
+} np_shot_t;
+
+typedef struct {
+ const char *id, *title, *tagline, *credit;
+ uint32_t top, bottom, accent; /* 0xRRGGBB theme colours */
+ const uint32_t *begin, *end; /* the game's block of flash */
+ int (*main)(void);
+ uint8_t *data; /* the game's RAM inside the arena */
+ const uint8_t *data_init;
+ uint32_t data_size;
+ uint8_t *bss;
+ uint32_t bss_size;
+ const np_shot_t *shots;
+ uint8_t nshots;
+ const char *const *records; /* save files, deleted on uninstall */
+ uint32_t est_size; /* code and data, for the simulator */
+} np_game_t;
+
+extern const np_game_t np_games[];
+extern const int np_game_count;
+
+bool np_game_installed(int i);
+uint32_t np_game_size(int i); /* bytes of flash */
+void np_game_run(int i);
+
+/* ---- storage (storage.c): Epsilon's record file system */
+bool np_storage_delete(const char *name); /* true if gone (or never there) */
+uint32_t np_storage_record_size(const char *name);
+
+/* ---- uninstalling (flash.c) */
+enum { NP_UNINSTALL_OK, NP_UNINSTALL_UNSUPPORTED, NP_UNINSTALL_BATTERY, NP_UNINSTALL_FAILED };
+bool np_uninstall_supported(void);
+bool np_battery_ok(void);
+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 */
+void np_settings(void);
+
+#endif
diff --git a/launcher/src/platform.c b/launcher/src/platform.c
new file mode 100644
index 00000000..73bdd1e0
--- /dev/null
+++ b/launcher/src/platform.c
@@ -0,0 +1,44 @@
+#include <eadk.h>
+#include "np.h"
+
+uint32_t np_keys(void) {
+ eadk_keyboard_state_t k = eadk_keyboard_scan();
+#define DOWN(key) eadk_keyboard_key_down(k, key)
+ uint32_t out = 0;
+ if (DOWN(eadk_key_left) || DOWN(eadk_key_four)) out |= K_LEFT;
+ if (DOWN(eadk_key_right) || DOWN(eadk_key_six)) out |= K_RIGHT;
+ if (DOWN(eadk_key_up) || DOWN(eadk_key_eight)) out |= K_UP;
+ if (DOWN(eadk_key_down) || DOWN(eadk_key_two)) out |= K_DOWN;
+ if (DOWN(eadk_key_ok) || DOWN(eadk_key_exe) || DOWN(eadk_key_five)) out |= K_OK;
+ if (DOWN(eadk_key_back)) out |= K_BACK;
+ if (DOWN(eadk_key_home) || DOWN(eadk_key_on_off)) out |= K_HOME;
+ if (DOWN(eadk_key_backspace)) out |= K_BACKSPACE;
+#undef DOWN
+ return out;
+}
+
+uint32_t np_millis(void) { return (uint32_t)eadk_timing_millis(); }
+void np_sleep(unsigned ms) { eadk_timing_msleep(ms); }
+void np_vblank(void) { eadk_display_wait_for_vblank(); }
+
+void np_push(int x, int y, int w, int h, const color_t *px) {
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);
+}
+
+void np_fill_screen(int x, int y, int w, int h, color_t c) {
+ eadk_display_push_rect_uniform((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, c);
+}
+
+void np_wait_release(void) {
+ while (eadk_keyboard_scan()) eadk_timing_msleep(10);
+}
+
+static uint32_t alloc_pos;
+void *np_alloc(uint32_t size) {
+ size = (size + 7) & ~7u;
+ if (alloc_pos + size > np_arena_size) return 0;
+ void *p = np_arena + alloc_pos;
+ alloc_pos += size;
+ return p;
+}
+void np_alloc_reset(void) { alloc_pos = 0; }
diff --git a/launcher/src/settings.c b/launcher/src/settings.c
new file mode 100644
index 00000000..20a2209e
--- /dev/null
+++ b/launcher/src/settings.c
@@ -0,0 +1,288 @@
+/* Settings: the list of installed games, and uninstalling one of them behind
+ * a clear warning and a hold-to-confirm button. */
+#include <string.h>
+#include "sys.h"
+#include "ui.h"
+
+#define BG_TOP 0x3B4252
+#define BG_BOTTOM 0x171A21
+#define DANGER 0xE5484D
+#define DANGER_TOP 0x8C1D23
+#define DANGER_BOTTOM 0x2A080B
+#define OK_GREEN 0x2FB36B
+#define ROW_H 34
+#define ROWS_Y 50
+#define HOLD_MS 1400
+
+static char *fmt_kb(char *out, uint32_t bytes) {
+ uint32_t kb = (bytes + 1023) / 1024;
+ char t[8];
+ int n = 0;
+ do t[n++] = (char)('0' + kb % 10);
+ while (kb /= 10);
+ char *o = out;
+ while (n) *o++ = t[--n];
+ strcpy(o, " KB");
+ return out;
+}
+
+/* ---------------------------------------------------------------- list */
+typedef struct {
+ int n, sel, top;
+ int8_t games[16];
+ float cursor; /* animated selection */
+} list_t;
+
+static void draw_thumb(int game, int x, int y, int w, int h) {
+ const np_game_t *g = &np_games[game];
+ const uint8_t *px = ui_shot(game, 0);
+ if (px) gfx_image(px, g->shots[0].palette, g->shots[0].ncolors, SHOT_W, SHOT_H, x, y, w, h, 5, 0);
+ else gfx_rrect(x, y, w, h, 5, gfx_rgb(g->top), 256);
+}
+
+static void list_scene(void *ctx) {
+ list_t *l = ctx;
+ gfx_vgrad(0, 0, SCREEN_W, SCREEN_H, BG_TOP, BG_BOTTOM);
+ if (gfx_y0 < 44) {
+ gfx_icon(&np_icon_back, 14, 17, 0xFFFF, 200);
+ gfx_text(&np_font_title, 36, 30, "Settings", 0xFFFF, 256);
+ uint32_t total = 0;
+ for (int i = 0; i < l->n; i++) total += np_game_size(l->games[i]);
+ char kb[16];
+ if (l->n) {
+ gfx_text_right(&np_font_small, SCREEN_W - 14, 20, "INSTALLED GAMES", 0xFFFF, 150);
+ gfx_text_right(&np_font_body, SCREEN_W - 14, 34, fmt_kb(kb, total), 0xFFFF, 230);
+ }
+ }
+ if (!l->n) {
+ gfx_icon(&np_icon_check, 145, 92, 0xFFFF, 150);
+ gfx_text_center(&np_font_body, 160, 146, "No games left to uninstall", 0xFFFF, 220);
+ gfx_text_center(&np_font_small, 160, 164, "Reinstall NumPlay to get them back", 0xFFFF, 150);
+ return;
+ }
+ /* selection highlight slides between rows */
+ float cy = ROWS_Y + (l->cursor - l->top) * (ROW_H + 4);
+ gfx_rrect(10, (int)cy, SCREEN_W - 20, ROW_H, 10, 0xFFFF, 46);
+ for (int r = 0; r < 5 && l->top + r < l->n; r++) {
+ int i = l->top + r, game = l->games[i];
+ int y = ROWS_Y + r * (ROW_H + 4);
+ if (y >= gfx_y1 || y + ROW_H <= gfx_y0) continue;
+ const np_game_t *g = &np_games[game];
+ draw_thumb(game, 16, y + 4, 35, 26);
+ gfx_text(&np_font_body, 60, y + 15, g->title, 0xFFFF, 256);
+ char kb[16];
+ gfx_text(&np_font_small, 60, y + 28, fmt_kb(kb, np_game_size(game)), 0xFFFF, 150);
+ if (i == l->sel) {
+ gfx_rrect(SCREEN_W - 104, y + 7, 86, 20, 10, gfx_rgb(DANGER), 256);
+ gfx_icon(&np_icon_trash, SCREEN_W - 96, y + 9, 0xFFFF, 256);
+ gfx_text(&np_font_small, SCREEN_W - 78, y + 21, "Uninstall", 0xFFFF, 256);
+ }
+ }
+}
+
+/* ---------------------------------------------------------------- dialogs */
+typedef struct {
+ int game;
+ int choice; /* 0 cancel, 1 uninstall */
+ float hold; /* 0..1 while OK is held on "Uninstall" */
+ bool hinted;
+ int stage; /* 0 confirm, 1 working, 2 done, 3 error */
+ int error;
+ float progress;
+ uint32_t freed;
+} dialog_t;
+
+static const char *error_text(int e) {
+ switch (e) {
+ case NP_UNINSTALL_UNSUPPORTED:
+ return "Your calculator's software doesn't allow apps to uninstall parts of themselves. Update it to Epsilon 21 or "
+ "newer at my.numworks.com, then try again.";
+ case NP_UNINSTALL_BATTERY:
+ return "The battery is too low to safely erase flash memory. Plug in your calculator, then try again.";
+ default:
+ return "Something went wrong while erasing. To be safe, reinstall NumPlay from my.numworks.com/apps.";
+ }
+}
+
+static void dialog_scene(void *ctx) {
+ dialog_t *d = ctx;
+ const np_game_t *g = &np_games[d->game];
+ char line[64];
+ if (d->stage == 2) {
+ gfx_vgrad(0, 0, SCREEN_W, SCREEN_H, 0x1F5A3C, 0x0B1A12);
+ gfx_circle(160, 74, 34, gfx_rgb(OK_GREEN), 256);
+ gfx_icon(&np_icon_check, 145, 59, 0xFFFF, 256);
+ strcpy(line, g->title);
+ strcat(line, " was uninstalled");
+ gfx_text_center(&np_font_title, 160, 142, line, 0xFFFF, 256);
+ char kb[16];
+ strcpy(line, fmt_kb(kb, d->freed));
+ strcat(line, " of flash memory freed");
+ gfx_text_center(&np_font_body, 160, 166, line, 0xFFFF, 200);
+ ui_button(110, 192, 100, 28, "OK", true, OK_GREEN, 256);
+ return;
+ }
+ gfx_vgrad(0, 0, SCREEN_W, SCREEN_H, DANGER_TOP, DANGER_BOTTOM);
+ gfx_icon(&np_icon_warning, 137, 14, 0xFFFF, 256);
+ if (d->stage == 3) {
+ gfx_text_center(&np_font_title, 160, 84, "Couldn't uninstall", 0xFFFF, 256);
+ gfx_paragraph(&np_font_body, 160, 112, 280, 17, error_text(d->error), 0xFFFF, 220);
+ ui_button(110, 196, 100, 28, "OK", true, DANGER, 256);
+ return;
+ }
+ if (d->stage == 1) {
+ strcpy(line, "Uninstalling ");
+ strcat(line, g->title);
+ strcat(line, "...");
+ gfx_text_center(&np_font_title, 160, 96, line, 0xFFFF, 256);
+ gfx_rrect(40, 118, 240, 10, 5, 0xFFFF, 60);
+ int w = (int)(240 * d->progress);
+ if (w >= 10) gfx_rrect(40, 118, w, 10, 5, 0xFFFF, 256);
+ gfx_text_center(&np_font_body, 160, 152, "Don't turn off your calculator.", 0xFFFF, 200);
+ return;
+ }
+ strcpy(line, "Uninstall ");
+ strcat(line, g->title);
+ strcat(line, "?");
+ gfx_text_center(&np_font_title, 160, 80, line, 0xFFFF, 256);
+ strcpy(line, "This deletes ");
+ strcat(line, g->title);
+ int y = gfx_paragraph(&np_font_body, 160, 102, 290, 16, line, 0xFFFF, 240);
+ y = gfx_paragraph(&np_font_body, 160, y, 290, 16, "and all of its saved progress. You can't undo this.", 0xFFFF, 240);
+ gfx_paragraph(&np_font_small, 160, y + 4, 290, 13,
+ "To play it again, you'll have to reinstall all of NumPlay from my.numworks.com/apps, and "
+ "reinstalling may reset your progress in every game.",
+ 0xFFFF, 170);
+ ui_button(38, 198, 110, 28, "Cancel", d->choice == 0, 0x555D70, 256);
+ /* the uninstall button fills up while OK is held */
+ int bx = 172, by = 198, bw = 110, bh = 28;
+ if (d->choice == 1) {
+ gfx_rrect(bx, by + 2, bw, bh, bh / 2, 0, 64);
+ gfx_rrect(bx, by, bw, bh, bh / 2, gfx_rgb(DANGER), 256);
+ int fill = (int)(bw * d->hold);
+ if (fill > 0) {
+ gfx_rrect(bx, by, NP_MAX(fill, bh), bh, bh / 2, 0xFFFF, 110);
+ }
+ gfx_text_center(&np_font_body, bx + bw / 2, by + 18, d->hinted ? "Hold OK" : "Uninstall", 0xFFFF, 256);
+ } else {
+ gfx_rrect(bx, by, bw, bh, bh / 2, 0xFFFF, 40);
+ gfx_text_center(&np_font_body, bx + bw / 2, by + 18, "Uninstall", 0xFFFF, 200);
+ }
+}
+
+static dialog_t *active_dialog;
+static void on_progress(int done, int total) {
+ active_dialog->progress = total ? (float)done / total : 1;
+ ui_frame(dialog_scene, active_dialog);
+}
+
+static void wait_ok(dialog_t *d) {
+ ui_keys_t k = {np_keys(), 0, 0};
+ ui_frame(dialog_scene, d);
+ for (;;) {
+ uint32_t p = ui_poll(&k);
+ if (p & (K_OK | K_BACK | K_HOME)) return;
+ np_sleep(16);
+ }
+}
+
+/* Returns true if the game was uninstalled. */
+static bool uninstall_flow(int game) {
+ dialog_t d = {game, 0, 0, false, 0, 0, 0, 0};
+ active_dialog = &d;
+ if (!np_uninstall_supported() || !np_battery_ok()) {
+ d.stage = 3;
+ d.error = !np_uninstall_supported() ? NP_UNINSTALL_UNSUPPORTED : NP_UNINSTALL_BATTERY;
+ wait_ok(&d);
+ return false;
+ }
+ ui_keys_t k = {np_keys(), 0, 0};
+ uint32_t last = np_millis();
+ bool dirty = true;
+ for (;;) {
+ uint32_t now = np_millis(), dt = now - last;
+ last = now;
+ uint32_t p = ui_poll(&k);
+ if (p & (K_BACK | K_HOME)) return false;
+ if (p & K_LEFT) d.choice = 0, d.hold = 0, dirty = true;
+ if (p & K_RIGHT) d.choice = 1, dirty = true;
+ if (p & K_OK) {
+ if (d.choice == 0) return false;
+ d.hinted = true;
+ dirty = true;
+ }
+ if (d.choice == 1 && (k.held & K_OK)) {
+ d.hold += dt / (float)HOLD_MS;
+ dirty = true;
+ if (d.hold >= 1) break;
+ } else if (d.hold > 0) {
+ d.hold = NP_MAX(d.hold - dt / 300.f, 0.f);
+ dirty = true;
+ }
+ if (dirty) {
+ ui_frame(dialog_scene, &d);
+ dirty = false;
+ } else {
+ np_sleep(16);
+ }
+ }
+ d.stage = 1;
+ d.freed = np_game_size(game);
+ ui_frame(dialog_scene, &d);
+ int r = np_uninstall(game, on_progress);
+ np_wait_release();
+ if (r == NP_UNINSTALL_OK) {
+ d.stage = 2;
+ } else {
+ d.stage = 3;
+ d.error = r;
+ }
+ wait_ok(&d);
+ return r == NP_UNINSTALL_OK;
+}
+
+void np_settings(void) {
+ ui_init();
+ list_t l = {0};
+ for (int i = 0; i < np_game_count; i++)
+ if (np_game_installed(i)) l.games[l.n++] = (int8_t)i;
+ ui_keys_t k = {np_keys(), 0, 0};
+ uint32_t last = np_millis();
+ bool dirty = true;
+ for (;;) {
+ uint32_t now = np_millis();
+ float dt = NP_MIN((now - last) / 1000.f, 0.05f);
+ last = now;
+ uint32_t p = ui_poll(&k);
+ if (p & (K_BACK | K_HOME)) return;
+ if (l.n) {
+ if (p & K_UP) l.sel = NP_MAX(l.sel - 1, 0);
+ if (p & K_DOWN) l.sel = NP_MIN(l.sel + 1, l.n - 1);
+ if (l.sel < l.top) l.top = l.sel;
+ if (l.sel > l.top + 4) l.top = l.sel - 4;
+ if (p & (K_OK | K_BACKSPACE)) {
+ if (uninstall_flow(l.games[l.sel])) {
+ l.n = 0;
+ for (int i = 0; i < np_game_count; i++)
+ if (np_game_installed(i)) l.games[l.n++] = (int8_t)i;
+ l.sel = NP_MIN(l.sel, NP_MAX(l.n - 1, 0));
+ l.top = NP_MIN(l.top, l.sel);
+ l.cursor = l.sel;
+ }
+ k.held = np_keys();
+ last = np_millis();
+ dirty = true;
+ }
+ if (p) dirty = true;
+ }
+ float c = ui_approach(l.cursor, (float)l.sel, dt, 0.05f);
+ if (c != l.cursor) dirty = true;
+ l.cursor = c;
+ if (dirty) {
+ ui_frame(list_scene, &l);
+ dirty = false;
+ } else {
+ np_sleep(16);
+ }
+ }
+}
diff --git a/launcher/src/storage.c b/launcher/src/storage.c
new file mode 100644
index 00000000..6d89f396
--- /dev/null
+++ b/launcher/src/storage.c
@@ -0,0 +1,141 @@
+/* Deleting a game's save files from Epsilon's file system.
+ *
+ * The file system is a FileSystem object in RAM: a magic word, the record
+ * buffer, the magic word again, then private members. Records are packed:
+ * a 16-bit size, the NUL-terminated name, the content; a zero size ends the
+ * list. Removing a record slides the following ones down, exactly like
+ * Epsilon's own destroyRecord. Epsilon also caches the position of the last
+ * record it looked up (a name checksum and a pointer, stored after the
+ * buffer); that cache is located and verified, then cleared, so Epsilon does
+ * not use a stale position. If it cannot be verified, only a record that is
+ * last in the list (nothing moves) is removed. */
+#include <string.h>
+#include "np.h"
+#include "sys.h"
+
+#if PLATFORM_DEVICE && !NP_SIMULATOR
+#define FS_MAGIC 0xEE0BDDBAu
+
+typedef struct {
+ uint8_t *buf;
+ uint32_t size;
+ uint32_t *after; /* first word after the footer */
+} fs_t;
+
+static bool open_fs(fs_t *fs) {
+ const np_userland_t *h = np_userland();
+ if (!h) return false;
+ uint32_t ram = h->storage_ram, size = h->storage_size;
+ if (ram < 0x24000000 || ram % 4 || size < 1024 || size > 0x10000 || ram + size + 8 > 0x24040000) return false;
+ uint32_t *magic = (uint32_t *)ram;
+ uint32_t footer;
+ memcpy(&footer, (uint8_t *)ram + 4 + size, 4);
+ if (*magic != FS_MAGIC || footer != FS_MAGIC) return false;
+ fs->buf = (uint8_t *)ram + 4;
+ fs->size = size;
+ fs->after = (uint32_t *)(ram + 4 + size + 4);
+ return true;
+}
+
+static uint16_t rd16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); }
+
+/* End of the records (offset of the terminating zero size), or -1 if corrupt. */
+static int records_end(const fs_t *fs) {
+ uint32_t p = 0;
+ while (p + 2 <= fs->size) {
+ uint16_t n = rd16(fs->buf + p);
+ if (!n) return (int)p;
+ if (n < 4 || p + n > fs->size) return -1;
+ p += n;
+ }
+ return -1;
+}
+
+static int find(const fs_t *fs, const char *name, uint16_t *size) {
+ uint32_t p = 0;
+ size_t len = strlen(name) + 1;
+ while (p + 2 <= fs->size) {
+ uint16_t n = rd16(fs->buf + p);
+ if (n < 4 || p + n > fs->size) return -1;
+ if (n >= 2 + len && !memcmp(fs->buf + p + 2, name, len)) {
+ *size = n;
+ return (int)p;
+ }
+ p += n;
+ }
+ return -1;
+}
+
+static bool is_record_start(const fs_t *fs, uint32_t off, int end) {
+ uint32_t p = 0;
+ while ((int)p < end) {
+ if (p == off) return true;
+ p += rd16(fs->buf + p);
+ }
+ return false;
+}
+
+/* Epsilon's Record checksum: CRC of the CRCs of the base name and extension. */
+static uint32_t name_crc(const char *full) {
+ const char *dot = strchr(full, '.');
+ if (!dot) return 0;
+ uint32_t parts[2] = {np_crc32_bytes(full, (uint32_t)(dot - full)), np_crc32_bytes(dot + 1, (uint32_t)strlen(dot + 1))};
+ return np_crc32_words(parts, 2);
+}
+
+/* Finds Epsilon's (accessible size, cached record checksum, cached pointer)
+ * triple after the buffer. Exactly one candidate must pass every check. */
+static uint32_t *find_cache(const fs_t *fs, int end) {
+ uint32_t *found = 0;
+ for (int i = 1; i < 96; i++) {
+ uint32_t *w = fs->after + i;
+ uint32_t accessible = w[0], crc = w[1], ptr = w[2];
+ if (accessible > fs->size || (int)accessible < end + 2 || accessible < fs->size / 2) continue;
+ if (ptr == 0) {
+ if (crc != 0) continue;
+ } else {
+ uint32_t base = (uint32_t)(uintptr_t)fs->buf;
+ if (ptr < base || ptr >= base + (uint32_t)end || !is_record_start(fs, ptr - base, end)) continue;
+ if (crc == 0 || crc != name_crc((const char *)(uintptr_t)(ptr + 2))) continue;
+ }
+ if (found) return 0;
+ found = w;
+ }
+ return found;
+}
+
+bool np_storage_delete(const char *name) {
+ fs_t fs;
+ if (!open_fs(&fs)) return false;
+ int end = records_end(&fs);
+ if (end < 0) return false;
+ uint16_t size;
+ int at = find(&fs, name, &size);
+ if (at < 0) return true;
+ uint32_t *cache = find_cache(&fs, end);
+ bool last = at + size == end;
+ if (!cache && !last) return false;
+ /* slide what follows (and the terminating zero) down */
+ memmove(fs.buf + at, fs.buf + at + size, (size_t)(end + 2 - (at + size)));
+ memset(fs.buf + end + 2 - size, 0, size);
+ if (cache) cache[1] = cache[2] = 0;
+ return true;
+}
+
+uint32_t np_storage_record_size(const char *name) {
+ fs_t fs;
+ uint16_t size;
+ if (!open_fs(&fs) || find(&fs, name, &size) < 0) return 0;
+ return size;
+}
+
+#else
+bool np_storage_delete(const char *name) {
+ (void)name;
+ return true;
+}
+uint32_t np_storage_record_size(const char *name) {
+ (void)name;
+ return 0;
+}
+#endif
diff --git a/launcher/src/sys.c b/launcher/src/sys.c
new file mode 100644
index 00000000..9ca74b20
--- /dev/null
+++ b/launcher/src/sys.c
@@ -0,0 +1,96 @@
+#include "sys.h"
+
+#if PLATFORM_DEVICE && !NP_SIMULATOR
+#define USERLAND_MAGIC 0xDEC0EDFEu
+#define SLOT_MAGIC 0xEFEEDBBAu
+
+/* System calls, numbered as in Epsilon's svcall.h (stable since 2022). The
+ * kernel returns the result in r0 and may clobber r1-r3. */
+#define SVC2(n, a, b) \
+ ({ \
+ register uint32_t r0 __asm__("r0") = (uint32_t)(a); \
+ register uint32_t r1 __asm__("r1") = (uint32_t)(b); \
+ __asm__ volatile("svc %[imm]" : "+r"(r0), "+r"(r1) : [imm] "I"(n) : "r2", "r3", "r12", "memory"); \
+ r0; \
+ })
+#define SVC4(n, a, b, c, d) \
+ ({ \
+ register uint32_t r0 __asm__("r0") = (uint32_t)(a); \
+ register uint32_t r1 __asm__("r1") = (uint32_t)(b); \
+ register uint32_t r2 __asm__("r2") = (uint32_t)(c); \
+ register uint32_t r3 __asm__("r3") = (uint32_t)(d); \
+ __asm__ volatile("svc %[imm]" : "+r"(r0), "+r"(r1), "+r"(r2), "+r"(r3) : [imm] "I"(n) : "r12", "memory"); \
+ r0; \
+ })
+
+static bool valid_header(uint32_t address) {
+ /* the userland header sits at the start of the userland, after the kernel
+ * (and an optional extra data sector) of either firmware slot */
+ if (address != 0x90010000 && address != 0x90020000 && address != 0x90410000 && address != 0x90420000) return false;
+ const np_userland_t *h = (const np_userland_t *)address;
+ if (h->magic != USERLAND_MAGIC || h->footer != USERLAND_MAGIC) return false;
+ /* this app must run from the app area it describes */
+ uint32_t self = (uint32_t)(uintptr_t)&valid_header;
+ return h->apps_flash_start < h->apps_flash_end && self >= h->apps_flash_start && self < h->apps_flash_end &&
+ h->apps_flash_start % 0x10000 == 0;
+}
+
+const np_userland_t *np_userland(void) {
+ static const np_userland_t *cached;
+ static bool done;
+ if (done) return cached;
+ done = true;
+ const volatile uint32_t *slot = (const volatile uint32_t *)0x24000000;
+ if (slot[0] == SLOT_MAGIC && slot[3] == SLOT_MAGIC && valid_header(slot[2])) {
+ cached = (const np_userland_t *)slot[2];
+ return cached;
+ }
+ static const uint32_t candidates[] = {0x90010000, 0x90020000, 0x90410000, 0x90420000};
+ for (unsigned i = 0; i < 4; i++)
+ if (valid_header(candidates[i])) {
+ if (cached) { /* two matches: refuse to guess */
+ cached = 0;
+ return 0;
+ }
+ cached = (const np_userland_t *)candidates[i];
+ }
+ return cached;
+}
+
+uint32_t np_crc32_bytes(const void *data, uint32_t len) { return len ? SVC2(15, data, len) : 0; }
+uint32_t np_crc32_words(const uint32_t *data, uint32_t words) { return SVC2(16, data, words); }
+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; }
+
+#else /* simulator */
+
+const np_userland_t *np_userland(void) { return 0; }
+uint32_t np_crc32_bytes(const void *data, uint32_t len) {
+ (void)data, (void)len;
+ return 0;
+}
+uint32_t np_crc32_words(const uint32_t *data, uint32_t words) {
+ (void)data, (void)words;
+ return 0;
+}
+int np_battery_level(void) { return -1; }
+bool np_battery_charging(void) { return false; }
+bool np_flash_erase_sector(int sector) {
+ (void)sector;
+ return false;
+}
+bool np_flash_write(void *dst, const void *src, uint32_t len) {
+ (void)dst, (void)src, (void)len;
+ return false;
+}
+#endif
+
+int np_software_major(void) {
+ const np_userland_t *h = np_userland();
+ if (!h) return 0;
+ int major = 0, i = 0;
+ while (i < 3 && h->version[i] >= '0' && h->version[i] <= '9') major = major * 10 + (h->version[i++] - '0');
+ return i && h->version[i] == '.' ? major : 0;
+}
diff --git a/launcher/src/sys.h b/launcher/src/sys.h
new file mode 100644
index 00000000..824856ce
--- /dev/null
+++ b/launcher/src/sys.h
@@ -0,0 +1,29 @@
+/* What the launcher needs from the calculator's software beyond EADK: the
+ * userland header (where the file system and the app area are), and a few
+ * system calls. Everything here is validated before use and is a no-op in the
+ * simulator. */
+#ifndef NP_SYS_H
+#define NP_SYS_H
+#include "np.h"
+
+typedef struct {
+ uint32_t magic; /* 0xDEC0EDFE */
+ char version[8]; /* "25.2.2" */
+ uint32_t storage_ram, storage_size;
+ uint32_t apps_flash_start, apps_flash_end;
+ uint32_t apps_ram_start, apps_ram_end;
+ uint32_t name_flash_start, name_flash_end;
+ uint32_t footer; /* 0xDEC0EDFE */
+} np_userland_t;
+
+/* The header of the running software, or NULL if it cannot be identified. */
+const np_userland_t *np_userland(void);
+int np_software_major(void); /* 0 if unknown */
+
+uint32_t np_crc32_bytes(const void *data, uint32_t len);
+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);
+bool np_flash_write(void *dst, const void *src, uint32_t len);
+#endif
diff --git a/launcher/src/ui.c b/launcher/src/ui.c
new file mode 100644
index 00000000..9fafc276
--- /dev/null
+++ b/launcher/src/ui.c
@@ -0,0 +1,108 @@
+#include "ui.h"
+#include "inflate.h"
+
+/* ---- screenshots: decoded on demand into a few slots of the arena */
+#define MAX_SLOTS 6
+typedef struct {
+ int16_t game, shot;
+ uint32_t used;
+ uint8_t *px;
+} slot_t;
+static slot_t slots[MAX_SLOTS];
+static int nslots;
+static uint32_t lru_clock;
+static np_inflate_tables_t *tables;
+
+void ui_init(void) {
+ np_alloc_reset();
+ gfx_init();
+ tables = np_alloc(np_inflate_tables_size());
+ nslots = 0;
+ while (nslots < MAX_SLOTS) {
+ uint8_t *p = np_alloc(SHOT_W * SHOT_H);
+ if (!p) break;
+ slots[nslots++] = (slot_t){-1, -1, 0, p};
+ }
+}
+
+const uint8_t *ui_shot(int game, int shot) {
+ if (game < 0 || !np_game_installed(game) || !nslots) return 0;
+ const np_game_t *g = &np_games[game];
+ if (shot < 0 || shot >= g->nshots) return 0;
+ slot_t *best = &slots[0];
+ for (int i = 0; i < nslots; i++) {
+ if (slots[i].game == game && slots[i].shot == shot) {
+ slots[i].used = ++lru_clock;
+ return slots[i].px;
+ }
+ if (slots[i].used < best->used) best = &slots[i];
+ }
+ const np_shot_t *s = &g->shots[shot];
+ best->game = -1;
+ if (s->w != SHOT_W || s->h != SHOT_H) return 0;
+ if (np_inflate(best->px, SHOT_W * SHOT_H, s->z, s->zsize, tables) != SHOT_W * SHOT_H) return 0;
+ best->game = (int16_t)game;
+ best->shot = (int16_t)shot;
+ best->used = ++lru_clock;
+ return best->px;
+}
+
+/* ---- input */
+uint32_t ui_poll(ui_keys_t *k) {
+ uint32_t now = np_millis(), keys = np_keys();
+ uint32_t arrows = K_LEFT | K_RIGHT | K_UP | K_DOWN;
+ uint32_t pressed = keys & ~k->held;
+ if (pressed) {
+ k->since = now;
+ k->next = now + 380;
+ } else if ((keys & arrows) && (int32_t)(now - k->next) >= 0) {
+ pressed = keys & arrows;
+ k->next = now + 120;
+ }
+ k->held = keys;
+ return pressed;
+}
+
+/* ---- motion */
+float ui_ease_out(float t) {
+ t = NP_CLAMP(t, 0.f, 1.f);
+ float u = 1 - t;
+ return 1 - u * u * u;
+}
+
+float ui_ease_in_out(float t) {
+ t = NP_CLAMP(t, 0.f, 1.f);
+ return t < 0.5f ? 4 * t * t * t : 1 - (-2 * t + 2) * (-2 * t + 2) * (-2 * t + 2) / 2;
+}
+
+/* Exponential approach, independent of the frame rate. */
+float ui_approach(float v, float target, float dt, float tau) {
+ float k = dt / (tau + dt);
+ float out = v + (target - v) * k;
+ float d = out - target;
+ return (d < 0.001f && d > -0.001f) ? target : out;
+}
+
+void ui_frame(gfx_scene_t scene, void *ctx) {
+ np_vblank();
+ gfx_render(scene, ctx, 0, SCREEN_H);
+}
+
+/* ---- pieces */
+void ui_button(int x, int y, int w, int h, const char *label, bool selected, uint32_t accent, int a) {
+ if (selected) {
+ gfx_rrect(x, y + 2, w, h, h / 2, 0, a / 4);
+ gfx_rrect(x, y, w, h, h / 2, gfx_rgb(accent), a);
+ gfx_text_center(&np_font_body, x + w / 2, y + h / 2 + 4, label, 0xFFFF, a);
+ } else {
+ gfx_rrect(x, y, w, h, h / 2, 0xFFFF, a * 40 / 256);
+ gfx_text_center(&np_font_body, x + w / 2, y + h / 2 + 4, label, 0xFFFF, a * 200 / 256);
+ }
+}
+
+void ui_key_hint(int x, int baseline, const char *key, const char *label, color_t c) {
+ int kw = gfx_text_width(&np_font_small, key) + 8;
+ gfx_rrect(x, baseline - 10, kw, 13, 4, c, 70);
+ gfx_text(&np_font_small, x + 4, baseline, key, c, 256);
+ gfx_text(&np_font_small, x + kw + 4, baseline, label, c, 200);
+}
diff --git a/launcher/src/ui.h b/launcher/src/ui.h
new file mode 100644
index 00000000..43d6c984
--- /dev/null
+++ b/launcher/src/ui.h
@@ -0,0 +1,29 @@
+#ifndef NP_UI_H
+#define NP_UI_H
+#include "gfx.h"
+
+#define SHOT_W 192
+#define SHOT_H 144
+
+/* Sets up the launcher's buffers in the arena (again after each game). */
+void ui_init(void);
+/* Decoded screenshot (palette indices), or NULL if it cannot be decoded. */
+const uint8_t *ui_shot(int game, int shot);
+
+/* Key presses with auto-repeat for held arrows. */
+typedef struct {
+ uint32_t held, since, next;
+} ui_keys_t;
+uint32_t ui_poll(ui_keys_t *k);
+
+float ui_ease_out(float t);
+float ui_ease_in_out(float t);
+float ui_approach(float value, float target, float dt, float tau);
+
+/* A frame: renders the whole screen after the next vertical blank. */
+void ui_frame(gfx_scene_t scene, void *ctx);
+
+/* Common pieces */
+void ui_button(int x, int y, int w, int h, const char *label, bool selected, uint32_t accent, int a256);
+void ui_key_hint(int x, int baseline, const char *key, const char *label, color_t c);
+#endif
diff --git a/tests/test_uninstall.py b/tests/test_uninstall.py
new file mode 100644
index 00000000..036ab57b
--- /dev/null
+++ b/tests/test_uninstall.py
@@ -0,0 +1,162 @@
+#!/usr/bin/env python3
+"""Uninstalls a game from NumPlay.nwa running in the ARM emulator and checks
+what happened to the flash and to the calculator's files.
+
+- the game's block of flash is wiped: whole sectors erased, the shared ends
+ zeroed, and not one byte outside the block changed;
+- the other games are intact and still start;
+- the game's save file is gone, the other files are untouched, and Epsilon's
+ record lookup cache no longer points into moved data;
+- relaunching NumPlay shows the game gone and does not touch the flash again.
+
+Usage: test_uninstall.py build/NumPlay.nwa [--out DIR]
+"""
+import argparse
+import os
+import struct
+import sys
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools"))
+import emu # noqa: E402
+
+SECTOR = 0x10000
+
+
+def fail(msg):
+ print("FAIL:", msg)
+ sys.exit(1)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("nwa")
+ ap.add_argument("--out", default="build/test_uninstall")
+ ap.add_argument("--game", default="crossyroad")
+ a = ap.parse_args()
+ os.makedirs(a.out, exist_ok=True)
+ c = emu.Calculator(a.nwa)
+ games = [n[3:-6] for n in c.symbols if n.startswith("np_") and n.endswith("_begin")]
+ order = sorted(games, key=lambda g: c.symbols[f"np_{g}_begin"])
+ target = a.game
+ if target not in order:
+ fail(f"{target} not in {order}")
+ begin, end = c.symbols[f"np_{target}_begin"], c.symbols[f"np_{target}_end"]
+ flash_before = bytes(c.uc.mem_read(emu.FLASH, emu.FLASH_SIZE))
+
+ save = {"crossyroad": "crossyroad.sav", "numdrive": "drivemad.sav", "numdash": "numdash.nds",
+ "tetris": "tetris.sav", "chess": None}[target]
+ records = [("pi.py", b"\x01print(3.14)\n"), (save or "none.sav", bytes(range(40))),
+ ("script.py", b"\x01import math\nprint(math.e)\n"), ("tetris.set", struct.pack("<3I", 1, 1, 1234))]
+ c.set_records(records, cached="script.py")
+
+ # Home: the settings card is last. Settings: the games are listed in order.
+ installed = [g for g in order]
+ row = installed.index(target)
+ t = 1500
+ keys = []
+ for _ in range(len(installed)):
+ keys.append((t, t + 90, emu.KEYS["right"]))
+ t += 300
+ t += 800
+ keys.append((t, t + 90, emu.KEYS["ok"]))
+ t += 1000
+ for _ in range(row):
+ keys.append((t, t + 90, emu.KEYS["down"]))
+ t += 300
+ t += 500
+ keys.append((t, t + 90, emu.KEYS["ok"])) # open the warning
+ dialog = t + 600
+ t += 1000
+ keys.append((t, t + 90, emu.KEYS["right"])) # choose Uninstall
+ hold = t + 500
+ keys.append((hold, hold + 1800, emu.KEYS["ok"])) # hold OK to confirm
+ t = hold + 1800 + 5000
+ done = t - 200
+ keys.append((t, t + 90, emu.KEYS["ok"])) # dismiss "was uninstalled"
+ t += 1000
+ listing = t - 100
+ keys.append((t, t + 90, emu.KEYS["back"])) # back to the carousel
+ t += 1500
+ home = t
+ keys.append((t, t + 90, emu.KEYS["home"])) # quit NumPlay
+ c.keys = keys
+ shots = {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 not c.exited:
+ fail("NumPlay did not quit")
+
+ # ---- flash
+ flash = bytes(c.uc.mem_read(emu.FLASH, emu.FLASH_SIZE))
+ s0 = (begin + SECTOR - 1) & ~(SECTOR - 1)
+ s1 = end & ~(SECTOR - 1)
+ if s1 < s0:
+ s0 = s1 = end
+ off = lambda x: x - emu.FLASH # noqa: E731
+ if any(flash[off(begin):off(s0)]):
+ fail("the start of the block is not zeroed")
+ if any(b != 0xFF for b in flash[off(s0):off(s1)]):
+ fail("whole sectors of the block are not erased")
+ if any(flash[off(s1):off(end)]):
+ fail("the end of the block is not zeroed")
+ outside = [i for i in range(len(flash)) if flash[i] != flash_before[i] and not (off(begin) <= i < off(end))]
+ if outside:
+ fail(f"{len(outside)} bytes changed outside the block, first at {emu.FLASH + outside[0]:#x}")
+ for op in c.flash_log:
+ if not op[-1]:
+ fail(f"flash operation refused: {op}")
+ if op[0] == "erase" and not (begin <= op[2] and op[2] + op[3] <= end):
+ fail(f"erased a sector outside the block: {op}")
+ for g in order:
+ if g == target:
+ continue
+ 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")
+ 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")
+
+ # ---- files
+ names = [n for n, _ in c.records()]
+ if save and save in names:
+ fail(f"{save} is still there")
+ buf = c.storage_bytes()
+ for name, content in records:
+ if name == save:
+ continue
+ if name not in names:
+ fail(f"{name} disappeared")
+ p = 0
+ while True:
+ size, = struct.unpack_from("<H", buf, p)
+ if buf[p + 2:p + 2 + len(name) + 1] == name.encode() + b"\0":
+ if buf[p + 3 + len(name):p + size] != content:
+ fail(f"{name} changed")
+ break
+ p += size
+ crc, ptr = c.cache()
+ if save and (crc or ptr):
+ fail("Epsilon's record cache still points into the moved records")
+ print(f"files: {save or 'no save'} deleted, others intact ({names}), lookup cache cleared")
+
+ # ---- relaunch: the game is gone, nothing is written to flash
+ log = len(c.flash_log)
+ c.exited = False
+ 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 + 1500, start + 1590, emu.KEYS["home"])]
+ c.pending_shots = [(start + 1400, os.path.join(a.out, "6_relaunch.png"))]
+ c.run(start + 3000)
+ if len(c.flash_log) != log:
+ fail("the relaunch wrote to flash")
+ if not c.exited:
+ fail("NumPlay did not quit after the relaunch")
+ print("relaunch: ok, no flash writes")
+ print("PASS")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/emu.py b/tools/emu.py
new file mode 100644
index 00000000..13269a8b
--- /dev/null
+++ b/tools/emu.py
@@ -0,0 +1,476 @@
+#!/usr/bin/env python3
+"""Run a calculator build of an app (.nwa) in the Unicorn CPU emulator.
+
+The .nwa is linked by nwlink exactly as the calculator's installer does, at a
+realistic address, and the resulting Cortex-M7 code runs here with the
+calculator's system calls (SVC) serviced in Python:
+
+- display: a 320x240 RGB565 frame buffer, saved as PNG frames on request;
+- keyboard: keys held over scripted time ranges;
+- time: a virtual clock driven by executed instructions and msleep;
+- flash: sector erase and programming follow NOR rules (erase sets 0xFF,
+ programming can only clear bits), so NumPlay's uninstaller runs for real;
+- storage: an Epsilon record file system in RAM, found by apps through the
+ userland header, optionally loaded from and saved to a file.
+
+Usage:
+ emu.py app.nwa --ms 5000 --keys "500-600:ok,1000-1100:right" \
+ --shots 900,2000 --gif 0-5000 --out DIR
+"""
+import argparse
+import os
+import struct
+import subprocess
+import sys
+import tempfile
+
+from elftools.elf.elffile import ELFFile
+from unicorn import UC_ARCH_ARM, UC_HOOK_CODE, UC_HOOK_INTR, UC_HOOK_MEM_INVALID, UC_MODE_MCLASS, UC_MODE_THUMB, Uc, UcError
+from unicorn.arm_const import (UC_ARM_REG_LR, UC_ARM_REG_PC, UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2,
+ UC_ARM_REG_R3, UC_ARM_REG_SP)
+
+KEYS = {"left": 0, "up": 1, "down": 2, "right": 3, "ok": 4, "back": 5, "home": 6, "onoff": 8, "shift": 12,
+ "alpha": 13, "xnt": 14, "var": 15, "toolbox": 16, "backspace": 17, "exp": 18, "ln": 19, "log": 20,
+ "i": 21, "comma": 22, "power": 23, "sin": 24, "cos": 25, "tan": 26, "pi": 27, "sqrt": 28, "square": 29,
+ "7": 30, "8": 31, "9": 32, "lparen": 33, "rparen": 34, "4": 36, "5": 37, "6": 38, "mul": 39, "div": 40,
+ "1": 42, "2": 43, "3": 44, "plus": 45, "minus": 46, "0": 48, "dot": 49, "ee": 50, "ans": 51, "exe": 52}
+
+FLASH, FLASH_SIZE = 0x90000000, 0x800000
+SRAM, SRAM_SIZE = 0x24000000, 0x40000
+USERLAND_HEADER = 0x90020000 # N0120: kernel, extra data sector, then userland
+TRAMPOLINE = 0x90010400
+DRAW_STRING_HOOK = 0x90010800
+EXIT_HOOK = 0x90010900
+STORAGE = 0x24001000
+STORAGE_SIZE = 42 * 1024
+EXT_RAM_END = 0x24037000
+EXT_RAM_LEN = 153676
+EXT_RAM_START = EXT_RAM_END - EXT_RAM_LEN
+STACK_TOP = 0x2403F000
+EXT_FLASH_START = 0x90200000
+EXT_FLASH_END = 0x903F0000
+CPU_HZ = 216_000_000
+# Epsilon's SmallFont.ttf and LargeFont.ttf (from the epsilon repository), for text drawn by
+# the firmware. Without them, text shows as blank cells.
+FONT_DIR = os.environ.get("EPSILON_FONTS", "")
+
+
+def epsilon_crc32(data):
+ """Ion::crc32Byte as in Epsilon's simulator: CRC-32/MPEG-2 fed word by word
+ (little-endian words, most significant byte first), then the tail bytes."""
+ if not data:
+ return 0
+ crc = 0xFFFFFFFF
+
+ def eat(crc, b):
+ crc ^= b << 24
+ for _ in range(8):
+ crc = ((crc << 1) ^ 0x04C11DB7) if crc & 0x80000000 else crc << 1
+ crc &= 0xFFFFFFFF
+ return crc
+
+ n = len(data) // 4
+ for i in range(n):
+ for j in (3, 2, 1, 0):
+ crc = eat(crc, data[4 * i + j])
+ for b in data[4 * n:]:
+ crc = eat(crc, b)
+ return crc
+
+
+def record_crc(full_name):
+ base, _, ext = full_name.rpartition(".")
+ parts = struct.pack("<II", epsilon_crc32(base.encode()), epsilon_crc32(ext.encode()))
+ return epsilon_crc32(parts)
+
+
+def sector_of(addr):
+ """Epsilon's Ion::Device::Flash::SectorAtAddress (8x4K, 1x32K, then 64K sectors)."""
+ off = addr - FLASH
+ i = off >> 16
+ if i >= 1:
+ return 8 + 1 + i - 1
+ i = off >> 15
+ if i >= 1:
+ return 8 + i - 1
+ return off >> 12
+
+
+def sector_range(index):
+ if index < 8:
+ return FLASH + index * 0x1000, 0x1000
+ if index == 8:
+ return FLASH + 0x8000, 0x8000
+ return FLASH + (index - 8) * 0x10000, 0x10000
+
+
+class Font:
+ """Approximates Epsilon's fonts (4-bit anti-aliased, fixed cells) with PIL."""
+
+ def __init__(self):
+ from PIL import Image, ImageDraw, ImageFont
+ self.cells = {}
+ for large, (name, px, w, h) in ((False, ("SmallFont.ttf", 12, 7, 14)), (True, ("LargeFont.ttf", 16, 10, 18))):
+ path = os.path.join(FONT_DIR, name)
+ glyphs = {}
+ if os.path.exists(path):
+ f = ImageFont.truetype(path, px)
+ asc, _ = f.getmetrics()
+ for c in range(32, 127):
+ im = Image.new("L", (w, h), 0)
+ ImageDraw.Draw(im).text((0, h - 3 - asc + (1 if large else 0)), chr(c), font=f, fill=255)
+ glyphs[c] = im.tobytes()
+ self.cells[large] = (w, h, glyphs)
+
+ def draw(self, screen, text, x, y, large, fg, bg):
+ w, h, glyphs = self.cells[large]
+
+ def mix(t):
+ out = 0
+ for shift, mask in ((11, 31), (5, 63), (0, 31)):
+ a, b = (bg >> shift) & mask, (fg >> shift) & mask
+ out |= ((a * (255 - t) + b * t) // 255) << shift
+ return out
+
+ cx = x
+ for ch in text:
+ g = glyphs.get(ord(ch)) if ord(ch) < 128 else None
+ for j in range(h):
+ for i in range(w):
+ px, py = cx + i, y + j
+ if 0 <= px < 320 and 0 <= py < 240:
+ t = g[j * w + i] if g else 0
+ struct.pack_into("<H", screen, (py * 320 + px) * 2, mix(t))
+ cx += w
+ return cx
+
+
+class Calculator:
+ def __init__(self, nwa, flash_start=EXT_FLASH_START, storage_file=None, nwlink="nwlink", external_data=None):
+ self.flash_start = flash_start
+ self.storage_file = storage_file
+ with tempfile.TemporaryDirectory() as d:
+ elf = os.path.join(d, "app.elf")
+ cmd = [nwlink, "nwa-elf", nwa, elf, "--flash-start", hex(flash_start), "--flash-length",
+ hex(EXT_FLASH_END - flash_start), "--ram-start", hex(EXT_RAM_START), "--ram-length",
+ str(EXT_RAM_LEN), "--trampoline-start", hex(TRAMPOLINE)]
+ if external_data:
+ cmd += ["--external-data", external_data]
+ subprocess.run(cmd, check=True)
+ e = ELFFile(open(elf, "rb"))
+ self.segments = [(s["p_paddr"], s.data()) for s in e.iter_segments()
+ if s["p_type"] == "PT_LOAD" and s["p_filesz"]]
+ self.entry = e["e_entry"]
+ self.symbols = {}
+ st = e.get_section_by_name(".symtab")
+ if st:
+ for s in st.iter_symbols():
+ if s.name:
+ self.symbols[s.name] = s["st_value"]
+ uc = self.uc = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS)
+ uc.mem_map(FLASH, FLASH_SIZE)
+ uc.mem_map(SRAM, SRAM_SIZE)
+ uc.mem_write(FLASH, b"\xff" * FLASH_SIZE)
+ for addr, data in self.segments:
+ uc.mem_write(addr, data)
+ self.app_end = max(a + len(d) for a, d in self.segments if a >= FLASH)
+ # userland header (Ion::Device::UserlandHeader) and slot info, as apps find them
+ hdr = struct.pack("<I8sIIIIIIIII", 0xDEC0EDFE, b"25.2.2\0\0", STORAGE, STORAGE_SIZE, EXT_FLASH_START,
+ EXT_FLASH_END, EXT_RAM_START, EXT_RAM_END, 0x903F0000, 0x903F0400, 0xDEC0EDFE)
+ uc.mem_write(USERLAND_HEADER, hdr)
+ uc.mem_write(SRAM, struct.pack("<IIII", 0xEFEEDBBA, 0x90000000, USERLAND_HEADER, 0xEFEEDBBA))
+ # Epsilon's file system object: magic, buffer, magic, then private members
+ storage = bytearray(STORAGE_SIZE)
+ if storage_file and os.path.exists(storage_file):
+ saved = open(storage_file, "rb").read()[:STORAGE_SIZE]
+ storage[:len(saved)] = saved
+ uc.mem_write(STORAGE, struct.pack("<I", 0xEE0BDDBA) + bytes(storage) + struct.pack("<I", 0xEE0BDDBA))
+ # then, as in Epsilon's FileSystem: delegate, record name verifier (128 bytes),
+ # accessible size, and the cache of the last record looked up (checksum, pointer)
+ self.fs_private = STORAGE + 8 + STORAGE_SIZE
+ uc.mem_write(self.fs_private, struct.pack("<I", 0x24000F00) + bytes(128) +
+ struct.pack("<III", STORAGE_SIZE, 0, 0))
+ # trampoline: entry 0 is the firmware's draw string
+ uc.mem_write(TRAMPOLINE, struct.pack("<I", DRAW_STRING_HOOK | 1))
+ uc.mem_write(DRAW_STRING_HOOK, b"\x70\x47" * 8)
+ uc.mem_write(EXIT_HOOK, b"\x70\x47" * 8)
+ self.screen = bytearray(320 * 240 * 2)
+ self.font = Font()
+ self.keys = [] # (start_ms, end_ms, key index)
+ self.now_ms = 0.0
+ self.rng = 0x2545F491
+ self.events = []
+ self.flash_log = []
+ self.frames = []
+ self.frame_times = []
+ self.shots = {}
+ self.pending_shots = []
+ self.insns = 0
+ self.exited = False
+ self.svc_counts = {}
+ 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)
+ uc.reg_write(UC_ARM_REG_SP, STACK_TOP)
+ uc.reg_write(UC_ARM_REG_LR, EXIT_HOOK | 1)
+ self.pc = self.entry | 1
+
+ # ------------------------------------------------------------ helpers
+ def reg(self, r):
+ return self.uc.reg_read(r)
+
+ def keyboard_state(self):
+ s = 0
+ for a, b, k in self.keys:
+ if a <= self.now_ms < b:
+ s |= 1 << k
+ return s
+
+ def storage_bytes(self):
+ return bytes(self.uc.mem_read(STORAGE + 4, STORAGE_SIZE))
+
+ def set_records(self, records, cached=None):
+ """Fills the file system with (name, content) records; `cached` names the
+ record Epsilon's lookup cache points to."""
+ buf = bytearray(STORAGE_SIZE)
+ p = 0
+ where = {}
+ for name, content in records:
+ size = 2 + len(name) + 1 + len(content)
+ struct.pack_into("<H", buf, p, size)
+ buf[p + 2:p + size] = name.encode() + b"\0" + content
+ where[name] = p
+ p += size
+ self.uc.mem_write(STORAGE + 4, bytes(buf))
+ crc = ptr = 0
+ if cached:
+ crc, ptr = record_crc(cached), STORAGE + 4 + where[cached]
+ self.uc.mem_write(self.fs_private + 4 + 128 + 4, struct.pack("<II", crc, ptr))
+
+ def cache(self):
+ return struct.unpack("<II", self.uc.mem_read(self.fs_private + 4 + 128 + 4, 8))
+
+ def records(self):
+ buf = self.storage_bytes()
+ out, p = [], 0
+ while p + 2 <= len(buf):
+ size, = struct.unpack_from("<H", buf, p)
+ if size == 0:
+ break
+ name = buf[p + 2:buf.index(b"\0", p + 2)]
+ out.append((name.decode("latin1"), size))
+ p += size
+ return out
+
+ def save_png(self, path):
+ from PIL import Image
+ im = Image.new("RGB", (320, 240))
+ px = []
+ for i in range(0, len(self.screen), 2):
+ v = self.screen[i] | self.screen[i + 1] << 8
+ px.append((((v >> 11) & 31) * 255 // 31, ((v >> 5) & 63) * 255 // 63, (v & 31) * 255 // 31))
+ im.putdata(px)
+ im.save(path)
+
+ def frame_image(self):
+ from PIL import Image
+ import numpy as np
+ a = np.frombuffer(bytes(self.screen), dtype="<u2").reshape(240, 320)
+ rgb = np.stack([((a >> 11) & 31) * 255 // 31, ((a >> 5) & 63) * 255 // 63, (a & 31) * 255 // 31], -1)
+ return Image.fromarray(rgb.astype("uint8"), "RGB")
+
+ # ------------------------------------------------------------ hooks
+ def _invalid(self, uc, access, addr, size, value, data):
+ print(f"emu: invalid memory access at {addr:#x} (pc {uc.reg_read(UC_ARM_REG_PC):#x})", file=sys.stderr)
+ return False
+
+ def _exit(self, uc, addr, size, data):
+ self.exited = True
+ uc.emu_stop()
+
+ def _draw_string(self, uc, addr, size, data):
+ text_p, point, large, fg = (self.reg(r) for r in (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3))
+ sp = self.reg(UC_ARM_REG_SP)
+ bg, = struct.unpack("<H", uc.mem_read(sp, 2))
+ raw = bytes(uc.mem_read(text_p, 256))
+ text = raw[:raw.index(b"\0")].decode("utf-8", "replace")
+ self.font.draw(self.screen, text, point & 0xFFFF, point >> 16, bool(large & 0xFF), fg & 0xFFFF, bg)
+ uc.reg_write(UC_ARM_REG_PC, self.reg(UC_ARM_REG_LR))
+
+ def _intr(self, uc, intno, data):
+ if intno != 2: # EXCP_SWI
+ print(f"emu: exception {intno} at pc {self.reg(UC_ARM_REG_PC):#x}", file=sys.stderr)
+ uc.emu_stop()
+ self.exited = True
+ return
+ pc = self.reg(UC_ARM_REG_PC)
+ op, = struct.unpack("<H", uc.mem_read(pc - 2, 2))
+ n = op & 0xFF
+ self.svc_counts[n] = self.svc_counts.get(n, 0) + 1
+ r0, r1, r2, r3 = (self.reg(r) for r in (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3))
+ ret = None
+ ret1 = None
+ if n in (18, 19, 20): # pull, push, push uniform
+ x, y, w, h = r0 & 0xFFFF, r0 >> 16, r1 & 0xFFFF, r1 >> 16
+ if x + w > 320 or y + h > 240:
+ print(f"emu: rect out of screen {x},{y} {w}x{h}", file=sys.stderr)
+ w, h = max(0, min(w, 320 - x)), max(0, min(h, 240 - y))
+ if n == 20:
+ c = struct.pack("<H", r2 & 0xFFFF) * w
+ for j in range(h):
+ o = ((y + j) * 320 + x) * 2
+ self.screen[o:o + 2 * w] = c
+ elif n == 19:
+ src = bytes(uc.mem_read(r2, w * h * 2)) if w and h else b""
+ for j in range(h):
+ o = ((y + j) * 320 + x) * 2
+ self.screen[o:o + 2 * w] = src[j * w * 2:(j + 1) * w * 2]
+ else:
+ out = bytearray()
+ for j in range(h):
+ o = ((y + j) * 320 + x) * 2
+ out += self.screen[o:o + 2 * w]
+ if out:
+ uc.mem_write(r2, bytes(out))
+ self.insns += w * h // 4 # the bus is not free
+ elif n == 21:
+ ret = 1
+ elif n == 34 or n == 33:
+ s = self.keyboard_state()
+ ret, ret1 = s & 0xFFFFFFFF, s >> 32
+ elif n == 48:
+ ms = int(self.now_ms)
+ ret, ret1 = ms & 0xFFFFFFFF, ms >> 32
+ elif n == 49:
+ self.now_ms += r0
+ elif n == 50:
+ self.now_ms += r0 / 1000
+ elif n == 45:
+ self.rng ^= (self.rng << 13) & 0xFFFFFFFF
+ self.rng ^= self.rng >> 17
+ self.rng ^= (self.rng << 5) & 0xFFFFFFFF
+ ret = self.rng
+ elif n == 23: # event get
+ ret = 0xFFFF
+ s = self.keyboard_state()
+ for k in range(64):
+ if s >> k & 1:
+ ret = k
+ break
+ if ret == 0xFFFF:
+ self.now_ms += 10
+ elif n in (1,):
+ ret = 128
+ elif n == 2:
+ pass
+ elif n == 3:
+ ret = 0
+ elif n == 4:
+ ret = 3 # Ion::Battery::Charge::FULL
+ elif n == 52:
+ ret = 0
+ elif n == 30: # erase sector
+ base, size = sector_range(r0)
+ ok = EXT_FLASH_START <= base and base + size <= EXT_FLASH_END
+ self.flash_log.append(("erase", r0, base, size, ok))
+ if ok:
+ uc.mem_write(base, b"\xff" * size)
+ self.now_ms += 400
+ ret = 1 if ok else 0
+ elif n == 32: # write memory
+ dst, src, length = r0, r1, r2
+ ok = EXT_FLASH_START <= dst and dst + length <= EXT_FLASH_END
+ self.flash_log.append(("write", dst, length, ok))
+ if ok:
+ old = bytes(uc.mem_read(dst, length))
+ new = bytes(uc.mem_read(src, length))
+ uc.mem_write(dst, bytes(a & b for a, b in zip(old, new)))
+ self.now_ms += length / 1024
+ ret = 1 if ok else 0
+ elif n == 15: # Ion::crc32Byte(data, length)
+ ret = epsilon_crc32(bytes(uc.mem_read(r0, r1)))
+ elif n == 16: # Ion::crc32DoubleWord(data, words)
+ ret = epsilon_crc32(bytes(uc.mem_read(r0, 4 * r1)))
+ else:
+ print(f"emu: unhandled svc {n} at {pc - 2:#x}", file=sys.stderr)
+ if ret is not None:
+ uc.reg_write(UC_ARM_REG_R0, ret & 0xFFFFFFFF)
+ if ret1 is not None:
+ uc.reg_write(UC_ARM_REG_R1, ret1 & 0xFFFFFFFF)
+
+ # ------------------------------------------------------------ running
+ def run(self, until_ms, on_frame=None, frame_ms=None):
+ chunk = CPU_HZ // 1000 # about one millisecond of instructions
+ next_frame = self.now_ms if frame_ms else None
+ while not self.exited and self.now_ms < until_ms:
+ try:
+ self.uc.emu_start(self.pc, 0xFFFFFFFF, count=chunk)
+ except UcError as err:
+ pc = self.reg(UC_ARM_REG_PC)
+ raise RuntimeError(f"CPU fault {err} at pc {pc:#x}") from None
+ self.pc = self.reg(UC_ARM_REG_PC) | 1
+ self.insns += chunk
+ self.now_ms += 1
+ while self.pending_shots and self.pending_shots[0][0] <= self.now_ms:
+ t, path = self.pending_shots.pop(0)
+ self.save_png(path)
+ if frame_ms and self.now_ms >= next_frame:
+ if on_frame:
+ on_frame(self)
+ next_frame += frame_ms
+ if self.storage_file:
+ open(self.storage_file, "wb").write(self.storage_bytes())
+
+
+def parse_keys(spec):
+ out = []
+ for item in filter(None, spec.split(",")):
+ rng, k = item.split(":")
+ a, _, b = rng.partition("-")
+ a = int(a)
+ b = int(b) if b else a + 120
+ out.append((a, b, KEYS[k] if k in KEYS else int(k)))
+ return out
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("nwa")
+ ap.add_argument("--ms", type=int, default=3000)
+ ap.add_argument("--keys", default="")
+ ap.add_argument("--shots", default="", help="comma separated times (ms)")
+ ap.add_argument("--gif", default="", help="start-end (ms) of a GIF recording")
+ ap.add_argument("--fps", type=int, default=25)
+ ap.add_argument("--out", default=".")
+ ap.add_argument("--storage", help="file keeping the calculator's storage between runs")
+ ap.add_argument("--flash-start", type=lambda s: int(s, 0), default=EXT_FLASH_START)
+ ap.add_argument("--nwlink", default="nwlink")
+ ap.add_argument("--records", action="store_true", help="list storage records at the end")
+ a = ap.parse_args()
+ os.makedirs(a.out, exist_ok=True)
+ c = Calculator(a.nwa, a.flash_start, a.storage, a.nwlink)
+ c.keys = parse_keys(a.keys)
+ c.pending_shots = sorted((int(t), os.path.join(a.out, f"shot_{int(t):06d}.png"))
+ for t in filter(None, a.shots.split(",")))
+ frames = []
+ g0, g1 = (int(x) for x in a.gif.split("-")) if a.gif else (None, None)
+
+ def grab(calc):
+ if g0 is not None and g0 <= calc.now_ms <= g1:
+ frames.append(calc.frame_image())
+
+ c.run(a.ms, grab if a.gif else None, 1000 / a.fps if a.gif else None)
+ if frames:
+ frames[0].save(os.path.join(a.out, "anim.gif"), save_all=True, append_images=frames[1:],
+ duration=int(1000 / a.fps), loop=0)
+ c.save_png(os.path.join(a.out, "last.png"))
+ print(f"emu: {c.now_ms:.0f} ms, {c.insns / 1e6:.1f} M instructions, exited={c.exited}")
+ if c.flash_log:
+ print("emu: flash operations:", len(c.flash_log), "failed:", sum(1 for x in c.flash_log if not x[-1]))
+ if a.records:
+ print("emu: records:", c.records())
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/fontgen.py b/tools/fontgen.py
new file mode 100644
index 00000000..7ac39c0c
--- /dev/null
+++ b/tools/fontgen.py
@@ -0,0 +1,126 @@
+#!/usr/bin/env python3
+"""Rasterizes the launcher's fonts into launcher/src/font_data.c.
+
+Glyphs come from Nunito (SIL Open Font License, see LICENSES/), rendered 4x
+supersampled with the baseline on a pixel boundary and stored as 4-bit
+coverage. Run it again only to change sizes or weights; the output is
+committed.
+
+Usage: fontgen.py out.c
+"""
+import hashlib
+import sys
+import urllib.request
+from pathlib import Path
+
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+
+ROOT = Path(__file__).resolve().parent
+CACHE = ROOT / ".fonts"
+UP = 4
+SOURCE = ("Nunito.ttf", "https://raw.githubusercontent.com/google/fonts/main/ofl/nunito/Nunito%5Bwght%5D.ttf",
+ "bb55a5ca5c2042335b3991af27c4d0705d0ef41cac6164ac737fd8f2a1e85207")
+
+# name, cap height in pixels, weight, extra letter spacing (1/4 px)
+SPECS = [
+ ("np_font_title", 15, 900, 0),
+ ("np_font_body", 9, 800, 1),
+ ("np_font_small", 7, 800, 2),
+]
+FIRST, LAST = 32, 126
+
+
+def font_file():
+ name, url, digest = SOURCE
+ p = CACHE / name
+ if not p.exists():
+ CACHE.mkdir(exist_ok=True)
+ data = urllib.request.urlopen(url).read()
+ if hashlib.sha256(data).hexdigest() != digest:
+ raise SystemExit("unexpected font data")
+ p.write_bytes(data)
+ return str(p)
+
+
+def load(cap, weight):
+ for size in range(6, 200):
+ f = ImageFont.truetype(font_file(), size * UP)
+ f.set_variation_by_axes([weight])
+ bb = f.getbbox("H", anchor="ls")
+ if -bb[1] >= cap * UP - UP // 2:
+ return f
+ raise SystemExit("size")
+
+
+def glyph(f, ch, spacing):
+ adv = (f.getlength(ch) + spacing) / UP
+ bb = f.getbbox(ch, anchor="ls")
+ if bb[2] <= bb[0] or bb[3] <= bb[1]:
+ return None, round(adv)
+ pad = 2 * UP
+ x0 = pad - bb[0]
+ y0 = pad - bb[1]
+ x0 += (-x0) % UP
+ y0 += (-y0) % UP
+ w = x0 + bb[2] + pad
+ h = y0 + bb[3] + pad
+ w += (-w) % UP
+ h += (-h) % UP
+ im = Image.new("L", (w, h), 0)
+ ImageDraw.Draw(im).text((x0, y0), ch, font=f, fill=255, anchor="ls")
+ a = np.asarray(im).astype(np.float32) / 255
+ a = a.reshape(h // UP, UP, w // UP, UP).mean(axis=(1, 3))
+ q = np.clip(np.round(a * 15), 0, 15).astype(np.uint8)
+ ys, xs = np.nonzero(q)
+ if not len(ys):
+ return None, round(adv)
+ q = q[ys.min():ys.max() + 1, xs.min():xs.max() + 1]
+ ox = xs.min() - x0 // UP
+ oy = ys.min() - y0 // UP # top relative to the baseline
+ return (q, ox, oy), round(adv)
+
+
+def main(out):
+ lines = ["/* Generated by tools/fontgen.py from Nunito (SIL Open Font License 1.1). */",
+ '#include "font.h"', ""]
+ total = 0
+ for name, cap, weight, spacing in SPECS:
+ f = load(cap, weight)
+ data = bytearray()
+ glyphs = []
+ asc = desc = 0
+ for c in range(FIRST, LAST + 1):
+ g, adv = glyph(f, chr(c), spacing * UP / 4)
+ if g is None:
+ glyphs.append((0, 0, 0, 0, adv, len(data)))
+ continue
+ q, ox, oy = g
+ h, w = q.shape
+ asc = max(asc, -oy)
+ desc = max(desc, h + oy)
+ flat = q.flatten().tolist()
+ if len(flat) % 2:
+ flat.append(0)
+ off = len(data)
+ for i in range(0, len(flat), 2):
+ data.append(flat[i] | flat[i + 1] << 4)
+ glyphs.append((w, h, ox, oy, adv, off))
+ total += len(data) + 7 * len(glyphs)
+ lines.append(f"static const uint8_t {name}_data[{len(data)}] = {{")
+ for i in range(0, len(data), 24):
+ lines.append(" " + ",".join(str(b) for b in data[i:i + 24]) + ",")
+ lines.append("};")
+ lines.append(f"static const np_glyph_t {name}_glyphs[{len(glyphs)}] = {{")
+ for w, h, ox, oy, adv, off in glyphs:
+ lines.append(f" {{{w}, {h}, {ox}, {oy}, {adv}, {off}}},")
+ lines.append("};")
+ lines.append(f"const np_font_t {name} = {{{FIRST}, {LAST - FIRST + 1}, {asc}, {desc}, {name}_glyphs, {name}_data}};")
+ lines.append("")
+ print(f"{name}: cap {cap}px, ascent {asc}, descent {desc}, {len(data)} bytes of glyphs")
+ Path(out).write_text("\n".join(lines))
+ print(f"total {total} bytes")
+
+
+if __name__ == "__main__":
+ main(sys.argv[1])
diff --git a/tools/games_mk.py b/tools/games_mk.py
new file mode 100644
index 00000000..2d4690ed
--- /dev/null
+++ b/tools/games_mk.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python3
+"""Turns games/games.json into make variables (order, screenshots)."""
+import json
+import sys
+
+games = json.load(open(sys.argv[1]))
+print("# Generated by tools/games_mk.py from games/games.json")
+print("GAMES := " + " ".join(g["id"] for g in games))
+for n, g in enumerate(games, 1):
+ i = g["id"]
+ print(f"INDEX_{i} := {n}")
+ print(f"SHOTS_{i} := " + " ".join(f"games/{i}/{s}" for s in g["shots"]))
+ print(f"SHOTS_REL_{i} := " + " ".join(g["shots"]))
+ if g.get("colors"):
+ print(f"COLORS_{i} := --colors {g['colors']}")
diff --git a/tools/gen_games.py b/tools/gen_games.py
new file mode 100644
index 00000000..c0b0078b
--- /dev/null
+++ b/tools/gen_games.py
@@ -0,0 +1,145 @@
+#!/usr/bin/env python3
+"""Generates the glue between the launcher and the game modules.
+
+From games/games.json and the module sizes written by npmodule.py:
+- gametable.c: the table of games the launcher shows (np_games);
+- arena.s: the RAM arena, sized for the hungriest game, and the symbols that
+ place each game's .data and .bss inside it (games never run together);
+- marks.s: a head and a tail word around each game's block of flash;
+- numplay.ld: the script of the final `ld -r`, which keeps each game's code,
+ data image, screenshots and marks together as one block.
+
+Usage: gen_games.py games.json MODULE_DIR OUT_DIR [--simulator]
+"""
+import argparse
+import json
+import os
+
+LAUNCHER_RAM = 96 * 1024 # the launcher adapts its screenshot cache to the arena
+HEAD, TAIL = 0x3147504E, 0x444E4550
+
+
+def c_str(s):
+ return "NULL" if s is None else json.dumps(s)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("manifest")
+ ap.add_argument("modules")
+ ap.add_argument("out")
+ ap.add_argument("--simulator", action="store_true")
+ a = ap.parse_args()
+ games = json.load(open(a.manifest))
+ os.makedirs(a.out, exist_ok=True)
+ sizes = {}
+ for g in games:
+ p = os.path.join(a.modules, g["id"] + ".json")
+ sizes[g["id"]] = json.load(open(p)) if os.path.exists(p) else {"code": 0, "data": 0, "bss": 0, "ram_align": 8}
+
+ # ---- RAM layout
+ arena = LAUNCHER_RAM
+ layout = {}
+ for g in games:
+ s = sizes[g["id"]]
+ data = s["data"]
+ bss_off = (data + 7) & ~7
+ layout[g["id"]] = (0, bss_off)
+ arena = max(arena, bss_off + s["bss"])
+ arena = (arena + 7) & ~7
+
+ # ---- games.c
+ L = ["/* Generated by tools/gen_games.py from games/games.json. */", '#include "np.h"', ""]
+ for g in games:
+ i = g["id"]
+ L.append(f"extern const uint32_t np_{i}_begin[], np_{i}_end[];")
+ L.append(f"extern uint8_t np_{i}_data[], np_{i}_bss[];")
+ L.append(f"extern const uint8_t np_{i}_init[];")
+ L.append(f"extern const np_shot_t np_{i}_shots[];")
+ L.append(f"int np_{i}_main(void);")
+ recs = ", ".join(json.dumps(r) for r in g["records"])
+ L.append(f"static const char *const {i}_records[] = {{{recs + ', ' if recs else ''}NULL}};")
+ L.append("")
+ if a.simulator:
+ L.append("/* The simulator has no flash blocks and gives each game its own RAM. */")
+ for g in games:
+ i = g["id"]
+ L.append(f"const uint32_t np_{i}_begin[1], np_{i}_end[1];")
+ L.append("#define RAM(x) NULL")
+ L.append("#define INIT(x) NULL")
+ L.append("#define SIZE(x) 0")
+ L.append(f"uint8_t np_arena[{arena}] __attribute__((aligned(8)));")
+ else:
+ L.append("#define RAM(x) x")
+ L.append("#define INIT(x) x")
+ L.append("#define SIZE(x) x")
+ L.append(f"const uint32_t np_arena_size = {arena};")
+ L.append("")
+ L.append("const np_game_t np_games[] = {")
+ for g in games:
+ i = g["id"]
+ s = sizes[i]
+ est = s["code"] + s["data"]
+ L.append(f" {{{c_str(i)}, {c_str(g['title'])}, {c_str(g['tagline'])}, {c_str(g.get('credit'))},")
+ L.append(f" {g['top']}, {g['bottom']}, {g['accent']}, np_{i}_begin, np_{i}_end, np_{i}_main,")
+ L.append(f" RAM(np_{i}_data), INIT(np_{i}_init), SIZE({s['data']}), RAM(np_{i}_bss), SIZE({s['bss']}),")
+ L.append(f" np_{i}_shots, {len(g['shots'])}, {i}_records, {est}}},")
+ L.append("};")
+ L.append(f"const int np_game_count = {len(games)};")
+ open(os.path.join(a.out, "gametable.c"), "w").write("\n".join(L) + "\n")
+
+ if a.simulator:
+ print(f"games: {len(games)} (simulator)")
+ return
+
+ # ---- arena.s
+ S = ["@ Generated by tools/gen_games.py: one RAM arena shared by the launcher and the games.",
+ ' .section .bss.np_arena,"aw",%nobits', " .balign 8", " .global np_arena", "np_arena:",
+ f" .space {arena}"]
+ for g in games:
+ i = g["id"]
+ d, b = layout[i]
+ S += [f" .global np_{i}_data", f" .set np_{i}_data, np_arena + {d}",
+ f" .global np_{i}_bss", f" .set np_{i}_bss, np_arena + {b}"]
+ open(os.path.join(a.out, "arena.s"), "w").write("\n".join(S) + "\n")
+
+ # ---- marks.s
+ M = ["@ Generated by tools/gen_games.py: the first and last words of each game's block."]
+ for n, g in enumerate(games, 1):
+ i = g["id"]
+ M += [f' .section .rodata.np.{n}.{i}.0head,"a"', " .balign 4", f" .word {HEAD:#x}",
+ f' .section .rodata.np.{n}.{i}.zztail,"a"', " .balign 4", f" .word {TAIL:#x}"]
+ open(os.path.join(a.out, "marks.s"), "w").write("\n".join(M) + "\n")
+
+ # ---- numplay.ld
+ D = ["/* Generated by tools/gen_games.py. Script of the final `ld -r` that makes NumPlay.nwa:",
+ " each game becomes one section, so the calculator's installer keeps its code, data image,",
+ " screenshots and marks in one block of flash that uninstalling can wipe. */",
+ "SECTIONS {",
+ " .rodata.eadk_app_name : { KEEP(*(.rodata.eadk_app_name)) }",
+ " .rodata.eadk_api_level : { KEEP(*(.rodata.eadk_api_level)) }",
+ " .rodata.eadk_app_icon : { KEEP(*(.rodata.eadk_app_icon)) }"]
+ for n, g in enumerate(games, 1):
+ i = g["id"]
+ p = f".rodata.np.{n}.{i}"
+ D += [f" {p} : {{",
+ f" np_{i}_begin = .;",
+ f" KEEP(*({p}.0head))",
+ f" *({p})",
+ f" *({p}.init)",
+ f" KEEP(*({p}.shots))",
+ f" KEEP(*({p}.zztail))",
+ f" np_{i}_end = .;",
+ " }"]
+ D += [" .text : { *(.text .text.*) }",
+ " .rodata : { *(.rodata .rodata.*) }",
+ " .data : { *(.data .data.*) }",
+ " .bss : { *(.bss .bss.* COMMON) }",
+ " /DISCARD/ : { *(.comment) *(.note*) *(.ARM.exidx*) *(.ARM.extab*) }",
+ "}"]
+ open(os.path.join(a.out, "numplay.ld"), "w").write("\n".join(D) + "\n")
+ print(f"games: {len(games)}, arena {arena} bytes")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/icongen.py b/tools/icongen.py
new file mode 100644
index 00000000..71656ef5
--- /dev/null
+++ b/tools/icongen.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python3
+"""Draws the launcher's icons as 4-bit masks into launcher/src/icons.c.
+
+Shapes are drawn 8x supersampled with PIL and averaged down, so edges come
+out anti-aliased. Usage: icongen.py out.c [preview.png]
+"""
+import math
+import sys
+
+import numpy as np
+from PIL import Image, ImageDraw
+
+S = 8 # supersampling
+
+
+def canvas(w, h):
+ im = Image.new("L", (w * S, h * S), 0)
+ return im, ImageDraw.Draw(im)
+
+
+def finish(im, w, h):
+ a = np.asarray(im).astype(np.float32) / 255
+ a = a.reshape(h, S, w, S).mean(axis=(1, 3))
+ return np.clip(np.round(a * 15), 0, 15).astype(np.uint8)
+
+
+def gear(size, teeth=8):
+ im, d = canvas(size, size)
+ c = size * S / 2
+ r_out, r_in, r_hole = c * 0.96, c * 0.72, c * 0.32
+ pts = []
+ for k in range(teeth * 4):
+ ang = 2 * math.pi * (k / (teeth * 4)) - math.pi / 2
+ # tooth profile: two points on the outer radius, two on the inner one
+ r = r_out if (k % 4) in (1, 2) else r_in
+ pts.append((c + r * math.cos(ang), c + r * math.sin(ang)))
+ d.polygon(pts, fill=255)
+ d.ellipse([c - r_in * 0.98, c - r_in * 0.98, c + r_in * 0.98, c + r_in * 0.98], fill=255)
+ d.ellipse([c - r_hole, c - r_hole, c + r_hole, c + r_hole], fill=0)
+ return finish(im, size, size)
+
+
+def warning(w, h):
+ im, d = canvas(w, h)
+ W, H = w * S, h * S
+ m = S * 1.5
+ # rounded triangle: draw a triangle with a thick rounded outline
+ tri = [(W / 2, m), (W - m, H - m), (m, H - m)]
+ d.polygon(tri, fill=255)
+ d.line(tri + [tri[0]], fill=255, width=int(S * 3), joint="curve")
+ for x, y in tri:
+ rr = S * 1.5
+ d.ellipse([x - rr, y - rr, x + rr, y + rr], fill=255)
+ # exclamation mark cut out
+ bw = W * 0.09
+ d.rounded_rectangle([W / 2 - bw, H * 0.33, W / 2 + bw, H * 0.68], radius=bw, fill=0)
+ d.ellipse([W / 2 - bw * 1.1, H * 0.74, W / 2 + bw * 1.1, H * 0.74 + 2.2 * bw], fill=0)
+ return finish(im, w, h)
+
+
+def trash(w, h):
+ im, d = canvas(w, h)
+ W, H = w * S, h * S
+ lw = S * 1.6
+ d.rounded_rectangle([W * 0.08, H * 0.16, W * 0.92, H * 0.16 + lw * 1.1], radius=lw / 2, fill=255)
+ d.rounded_rectangle([W * 0.36, H * 0.02, W * 0.64, H * 0.2], radius=lw, outline=255, width=int(lw))
+ d.rounded_rectangle([W * 0.16, H * 0.3, W * 0.84, H * 0.98], radius=S * 2, outline=255, width=int(lw))
+ for fx in (0.38, 0.62):
+ d.line([(W * fx, H * 0.44), (W * fx, H * 0.84)], fill=255, width=int(lw * 0.9))
+ return finish(im, w, h)
+
+
+def play(w, h):
+ im, d = canvas(w, h)
+ W, H = w * S, h * S
+ tri = [(W * 0.12, H * 0.06), (W * 0.96, H * 0.5), (W * 0.12, H * 0.94)]
+ d.polygon(tri, fill=255)
+ d.line(tri + [tri[0]], fill=255, width=int(S * 1.2), joint="curve")
+ return finish(im, w, h)
+
+
+def check(w, h):
+ im, d = canvas(w, h)
+ W, H = w * S, h * S
+ d.line([(W * 0.12, H * 0.52), (W * 0.4, H * 0.8), (W * 0.9, H * 0.2)], fill=255, width=int(S * 2.6),
+ joint="curve")
+ for x, y in ((W * 0.12, H * 0.52), (W * 0.9, H * 0.2), (W * 0.4, H * 0.8)):
+ rr = S * 1.3
+ d.ellipse([x - rr, y - rr, x + rr, y + rr], fill=255)
+ return finish(im, w, h)
+
+
+def chevron(w, h, left):
+ im, d = canvas(w, h)
+ W, H = w * S, h * S
+ pts = [(W * 0.75, H * 0.1), (W * 0.25, H * 0.5), (W * 0.75, H * 0.9)]
+ if not left:
+ pts = [(W - x, y) for x, y in pts]
+ d.line(pts, fill=255, width=int(S * 2), joint="curve")
+ for x, y in pts:
+ rr = S
+ d.ellipse([x - rr, y - rr, x + rr, y + rr], fill=255)
+ return finish(im, w, h)
+
+
+def back(w, h):
+ im, d = canvas(w, h)
+ W, H = w * S, h * S
+ lw = S * 1.8
+ d.line([(W * 0.9, H * 0.5), (W * 0.15, H * 0.5)], fill=255, width=int(lw))
+ d.line([(W * 0.45, H * 0.18), (W * 0.13, H * 0.5), (W * 0.45, H * 0.82)], fill=255, width=int(lw), joint="curve")
+ for x, y in ((W * 0.45, H * 0.18), (W * 0.45, H * 0.82), (W * 0.9, H * 0.5)):
+ d.ellipse([x - lw / 2, y - lw / 2, x + lw / 2, y + lw / 2], fill=255)
+ return finish(im, w, h)
+
+
+def logo(w, h):
+ """A little game pad."""
+ im, d = canvas(w, h)
+ W, H = w * S, h * S
+ d.rounded_rectangle([0, H * 0.12, W, H * 0.92], radius=H * 0.4, fill=255)
+ cx, cy, a, b = W * 0.28, H * 0.52, W * 0.13, H * 0.1
+ d.rectangle([cx - a, cy - b * 0.55, cx + a, cy + b * 0.55], fill=0)
+ d.rectangle([cx - b * 0.55 * W / H * 0.9, cy - a * H / W * 2.3, cx + b * 0.55 * W / H * 0.9, cy + a * H / W * 2.3],
+ fill=0)
+ for fx, fy in ((0.68, 0.42), (0.8, 0.6)):
+ rr = H * 0.1
+ d.ellipse([W * fx - rr, H * fy - rr, W * fx + rr, H * fy + rr], fill=0)
+ return finish(im, w, h)
+
+
+ICONS = [
+ ("gear", lambda: gear(42)),
+ ("warning", lambda: warning(46, 40)),
+ ("trash", lambda: trash(14, 16)),
+ ("play", lambda: play(11, 12)),
+ ("check", lambda: check(30, 30)),
+ ("back", lambda: back(14, 12)),
+ ("left", lambda: chevron(8, 14, True)),
+ ("right", lambda: chevron(8, 14, False)),
+ ("logo", lambda: logo(22, 15)),
+]
+
+
+def main(out, preview=None):
+ lines = ["/* Generated by tools/icongen.py. */", '#include "gfx.h"', ""]
+ sheet = []
+ total = 0
+ for name, fn in ICONS:
+ q = fn()
+ h, w = q.shape
+ flat = q.flatten().tolist()
+ if len(flat) % 2:
+ flat.append(0)
+ data = bytes(flat[i] | flat[i + 1] << 4 for i in range(0, len(flat), 2))
+ total += len(data)
+ lines.append(f"static const uint8_t {name}_data[{len(data)}] = {{")
+ for i in range(0, len(data), 24):
+ lines.append(" " + ",".join(str(b) for b in data[i:i + 24]) + ",")
+ lines.append("};")
+ lines.append(f"const np_icon_t np_icon_{name} = {{{w}, {h}, {name}_data}};")
+ lines.append("")
+ sheet.append(q)
+ open(out, "w").write("\n".join(lines))
+ print(f"icons: {total} bytes")
+ if preview:
+ W = sum(q.shape[1] + 4 for q in sheet)
+ H = max(q.shape[0] for q in sheet)
+ im = Image.new("L", (W, H), 0)
+ x = 0
+ for q in sheet:
+ im.paste(Image.fromarray((q * 17).astype(np.uint8)), (x, 0))
+ x += q.shape[1] + 4
+ im.resize((W * 4, H * 4), Image.NEAREST).save(preview)
+
+
+if __name__ == "__main__":
+ main(*sys.argv[1:])
diff --git a/tools/make_icon.py b/tools/make_icon.py
new file mode 100644
index 00000000..5a8402d3
--- /dev/null
+++ b/tools/make_icon.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+"""Draws NumPlay's home screen icon (55x56, like the calculator's own apps):
+a white game pad on a warm-to-cool gradient. Usage: make_icon.py out.png [size]"""
+import sys
+
+from PIL import Image, ImageDraw
+
+S = 8
+
+
+def icon(w=55, h=56):
+ W, H = w * S, h * S
+ # diagonal gradient
+ top, bottom = (255, 94, 98), (123, 67, 255)
+ grad = Image.new("RGB", (W, H))
+ px = grad.load()
+ for y in range(H):
+ for x in range(W):
+ t = (x * 0.35 + y * 0.65) / (W * 0.35 + H * 0.65)
+ px[x, y] = tuple(int(a + (b - a) * t) for a, b in zip(top, bottom))
+ mask = Image.new("L", (W, H), 0)
+ ImageDraw.Draw(mask).rounded_rectangle([0, 0, W - 1, H - 1], radius=12 * S, fill=255)
+ out = Image.new("RGBA", (W, H), (0, 0, 0, 0))
+ out.paste(grad, (0, 0), mask)
+ d = ImageDraw.Draw(out)
+ # soft shadow, then the pad
+ cx, cy = W / 2, H / 2 + 2 * S
+ pw, ph = 40 * S, 24 * S
+
+ def pad(dx, dy, fill):
+ d.rounded_rectangle([cx - pw / 2 + dx, cy - ph / 2 + dy, cx + pw / 2 + dx, cy + ph / 2 + dy], radius=ph / 2,
+ fill=fill)
+
+ pad(0, 2 * S, (60, 20, 90, 90))
+ pad(0, 0, (255, 255, 255, 255))
+ ink = (120, 70, 220, 255)
+ # d-pad
+ dx, dy, a, b = cx - 10.5 * S, cy, 5.5 * S, 2 * S
+ d.rounded_rectangle([dx - a, dy - b, dx + a, dy + b], radius=S, fill=ink)
+ d.rounded_rectangle([dx - b, dy - a, dx + b, dy + a], radius=S, fill=ink)
+ # buttons
+ for bx, by, col in ((cx + 8 * S, cy + 2.5 * S, (255, 94, 98, 255)), (cx + 13 * S, cy - 2.5 * S, ink)):
+ r = 3 * S
+ d.ellipse([bx - r, by - r, bx + r, by + r], fill=col)
+ # a little sparkle above: this is a launcher of many games
+ for i, (sx, sy, r) in enumerate(((cx - 12 * S, 12 * S, 2.2 * S), (cx, 9 * S, 3 * S), (cx + 12 * S, 12 * S, 2.2 * S))):
+ d.ellipse([sx - r, sy - r, sx + r, sy + r], fill=(255, 255, 255, 230 if i == 1 else 170))
+ return out.resize((w, h), Image.LANCZOS)
+
+
+if __name__ == "__main__":
+ im = icon()
+ im.save(sys.argv[1])
+ if len(sys.argv) > 2:
+ im.resize((int(sys.argv[2]), int(int(sys.argv[2]) * 56 / 55)), Image.LANCZOS).save(sys.argv[1].replace(".png", "@big.png"))
diff --git a/tools/module.ld b/tools/module.ld
new file mode 100644
index 00000000..9983a8a4
--- /dev/null
+++ b/tools/module.ld
@@ -0,0 +1,14 @@
+/* First step of a NumPlay module: `ld -r -d -T tools/module.ld game.o`.
+ Merges a game into one code section, one .data and one .bss, and drops what
+ the launcher does not need (the game's own name, icon and unwind tables). */
+SECTIONS {
+ /DISCARD/ : {
+ *(.rodata.eadk_app_name) *(.rodata.eadk_app_icon) *(.rodata.eadk_api_level)
+ *(.ARM.exidx*) *(.ARM.extab*) *(.comment) *(.note*) *(.debug*)
+ }
+ .text : {
+ *(.text .text.* .rodata .rodata.* .glue_7 .glue_7t .vfp11_veneer .v4_bx)
+ }
+ .data : { *(.data .data.*) }
+ .bss : { *(.bss .bss.* COMMON) }
+}
diff --git a/tools/npmodule.py b/tools/npmodule.py
new file mode 100644
index 00000000..382adce3
--- /dev/null
+++ b/tools/npmodule.py
@@ -0,0 +1,306 @@
+#!/usr/bin/env python3
+"""Turn a game's partially linked object into a NumPlay module.
+
+The input is the game linked with `ld -r -T tools/module.ld`: one `.text`
+section (code and read-only data), one `.data` and one `.bss`. The output is
+a relocatable object where:
+
+- the code keeps its bytes and relocations, in a section named after the game
+ (`.rodata.np.<n>.<game>`), so the launcher link can keep each game in one
+ contiguous block of flash;
+- `.data` becomes a read-only copy (`...init`) that the launcher copies into
+ RAM before starting the game;
+- nothing is allocated in RAM any more: every reference to the game's
+ `.data` or `.bss` is redirected to the symbols `np_<game>_data` and
+ `np_<game>_bss`, which the launcher places inside one arena shared by all
+ games (only one game runs at a time);
+- `main` is renamed `np_<game>_main` and is the only global definition left.
+
+It also writes a small JSON file with the section sizes for the build.
+
+Usage: npmodule.py in.o out.o --game NAME --index N --json sizes.json
+"""
+import argparse
+import json
+import struct
+import sys
+
+SHT_NULL, SHT_PROGBITS, SHT_SYMTAB, SHT_STRTAB, SHT_REL, SHT_NOBITS = 0, 1, 2, 3, 9, 8
+SHT_ARM_ATTRIBUTES = 0x70000003
+SHF_WRITE, SHF_ALLOC, SHF_EXECINSTR, SHF_INFO_LINK = 1, 2, 4, 0x40
+STB_LOCAL, STB_GLOBAL, STB_WEAK = 0, 1, 2
+STT_NOTYPE, STT_OBJECT, STT_FUNC, STT_SECTION = 0, 1, 2, 3
+SHN_UNDEF, SHN_ABS = 0, 0xFFF1
+R_ARM_ABS32 = 2
+
+# Only these relocation types may point into the game's RAM.
+RAM_RELOCS = {R_ARM_ABS32}
+
+
+def fail(msg):
+ sys.exit("npmodule: " + msg)
+
+
+class Elf:
+ def __init__(self, data):
+ self.d = data
+ if data[:4] != b"\x7fELF" or data[4] != 1 or data[5] != 1:
+ fail("expected a 32-bit little-endian ELF")
+ (self.type, self.machine) = struct.unpack_from("<HH", data, 16)
+ if self.type != 1 or self.machine != 40:
+ fail("expected an ARM relocatable object")
+ self.flags, = struct.unpack_from("<I", data, 0x24)
+ shoff, = struct.unpack_from("<I", data, 0x20)
+ shentsize, shnum, shstrndx = struct.unpack_from("<HHH", data, 0x2E)
+ self.secs = []
+ for i in range(shnum):
+ f = struct.unpack_from("<10I", data, shoff + i * shentsize)
+ s = dict(zip("name type flags addr off size link info align entsize".split(), f))
+ s["data"] = b"" if s["type"] == SHT_NOBITS else bytes(data[s["off"]:s["off"] + s["size"]])
+ self.secs.append(s)
+ shstr = self.secs[shstrndx]["data"]
+ for s in self.secs:
+ s["sname"] = shstr[s["name"]:shstr.index(b"\0", s["name"])].decode()
+ symtabs = [i for i, s in enumerate(self.secs) if s["type"] == SHT_SYMTAB]
+ if len(symtabs) != 1:
+ fail("expected one symbol table")
+ self.symtab_i = symtabs[0]
+ st = self.secs[self.symtab_i]
+ strtab = self.secs[st["link"]]["data"]
+ self.syms = []
+ for k in range(st["size"] // 16):
+ name, value, size, info, other, shndx = struct.unpack_from("<IIIBBH", st["data"], 16 * k)
+ self.syms.append(dict(name=strtab[name:strtab.index(b"\0", name)].decode(), value=value,
+ size=size, bind=info >> 4, type=info & 15, other=other, shndx=shndx))
+
+ def rels_for(self, target):
+ out = []
+ for s in self.secs:
+ if s["type"] == SHT_REL and s["info"] == target:
+ for k in range(s["size"] // 8):
+ off, info = struct.unpack_from("<II", s["data"], 8 * k)
+ out.append([off, info & 255, info >> 8])
+ elif s["type"] == 4 and s["info"] == target: # SHT_RELA
+ fail("RELA relocations are not supported")
+ return out
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("inp")
+ ap.add_argument("out")
+ ap.add_argument("--game", required=True)
+ ap.add_argument("--index", type=int, required=True)
+ ap.add_argument("--entry", default="main")
+ ap.add_argument("--json")
+ a = ap.parse_args()
+ g = a.game
+ e = Elf(open(a.inp, "rb").read())
+
+ by_name = {}
+ for i, s in enumerate(e.secs):
+ if s["flags"] & SHF_ALLOC:
+ if s["sname"] not in (".text", ".data", ".bss"):
+ fail(f"unexpected allocated section {s['sname']} (update tools/module.ld)")
+ by_name[s["sname"]] = i
+ if ".text" not in by_name:
+ fail("no .text section")
+ text_i = by_name[".text"]
+ data_i = by_name.get(".data")
+ bss_i = by_name.get(".bss")
+ text = e.secs[text_i]
+ data = e.secs[data_i] if data_i is not None else None
+ bss = e.secs[bss_i] if bss_i is not None else None
+ data_size = data["size"] if data else 0
+ bss_size = bss["size"] if bss else 0
+ ram_align = max([8] + [s["align"] for s in (data, bss) if s])
+
+ # ---- symbols of the output
+ # index 0: null, 1: code section, 2: init section, then locals, then globals
+ out_syms = [dict(name="", value=0, size=0, bind=0, type=0, other=0, shndx=0)]
+ CODE, INIT = 1, 3 # section indexes (2 and 4 hold their relocations)
+ out_syms.append(dict(name="", value=0, size=0, bind=STB_LOCAL, type=STT_SECTION, other=0, shndx=CODE))
+ out_syms.append(dict(name="", value=0, size=0, bind=STB_LOCAL, type=STT_SECTION, other=0, shndx=INIT))
+ remap = {} # old symbol index -> new symbol index
+ ram_sym = {} # old symbol index -> (region, offset) for symbols defined in RAM
+ entry_found = False
+ globals_out = []
+ undefined = {}
+ for k, s in enumerate(e.syms):
+ if k == 0:
+ continue
+ sh = s["shndx"]
+ if s["type"] == STT_SECTION:
+ if sh == text_i:
+ remap[k] = 1 # the code section's symbol
+ elif sh == data_i:
+ ram_sym[k] = ("data", 0)
+ elif sh == bss_i:
+ ram_sym[k] = ("bss", 0)
+ continue
+ if s["type"] == 4: # STT_FILE
+ continue
+ if sh == data_i and data_i is not None:
+ ram_sym[k] = ("data", s["value"])
+ continue
+ if sh == bss_i and bss_i is not None:
+ ram_sym[k] = ("bss", s["value"])
+ continue
+ if sh == SHN_UNDEF:
+ if s["bind"] == STB_LOCAL:
+ continue
+ if s["name"] not in undefined:
+ undefined[s["name"]] = dict(name=s["name"], value=0, size=0, bind=s["bind"],
+ type=STT_NOTYPE, other=0, shndx=SHN_UNDEF)
+ continue
+ if sh == text_i:
+ n = dict(s, shndx=CODE)
+ if s["name"] == a.entry and s["bind"] != STB_LOCAL:
+ n["name"] = f"np_{g}_main"
+ n["bind"] = STB_GLOBAL
+ n["other"] = 0
+ entry_found = True
+ globals_out.append((k, n))
+ else:
+ # every other definition stays private to the module
+ n["bind"] = STB_LOCAL
+ n["other"] = 0
+ remap[k] = len(out_syms)
+ out_syms.append(n)
+ continue
+ if sh == SHN_ABS:
+ n = dict(s, bind=STB_LOCAL)
+ remap[k] = len(out_syms)
+ out_syms.append(n)
+ continue
+ fail(f"symbol {s['name']} defined in unexpected section {sh}")
+ if not entry_found:
+ fail(f"entry symbol {a.entry} not found")
+
+ first_global = len(out_syms)
+ for k, n in globals_out:
+ remap[k] = len(out_syms)
+ out_syms.append(n)
+ # start of the .data image the launcher copies into RAM
+ out_syms.append(dict(name=f"np_{g}_init", value=0, size=data_size, bind=STB_GLOBAL, type=STT_OBJECT,
+ other=0, shndx=INIT))
+ ram_index = {}
+ for region in ("data", "bss"):
+ ram_index[region] = len(out_syms)
+ out_syms.append(dict(name=f"np_{g}_{region}", value=0, size=0, bind=STB_GLOBAL,
+ type=STT_NOTYPE, other=0, shndx=SHN_UNDEF))
+ und_index = {}
+ for name, n in undefined.items():
+ und_index[name] = len(out_syms)
+ out_syms.append(n)
+ for k, s in enumerate(e.syms):
+ if k and s["shndx"] == SHN_UNDEF and s["bind"] != STB_LOCAL and s["type"] != STT_SECTION:
+ remap[k] = und_index[s["name"]]
+
+ # ---- relocations
+ def convert(target_i, blob):
+ blob = bytearray(blob)
+ out = []
+ for off, typ, si in e.rels_for(target_i):
+ if si in ram_sym:
+ region, value = ram_sym[si]
+ if typ not in RAM_RELOCS:
+ fail(f"relocation type {typ} at {off:#x} points into RAM; only ABS32 is handled")
+ if value:
+ addend, = struct.unpack_from("<I", blob, off)
+ struct.pack_into("<I", blob, off, (addend + value) & 0xFFFFFFFF)
+ out.append((off, typ, ram_index[region]))
+ elif si in remap:
+ out.append((off, typ, remap[si]))
+ else:
+ fail(f"relocation at {off:#x} uses unsupported symbol {e.syms[si]}")
+ return bytes(blob), out
+
+ code_bytes, code_rels = convert(text_i, text["data"])
+ init_bytes, init_rels = (b"", [])
+ if data:
+ init_bytes, init_rels = convert(data_i, data["data"])
+ for s in e.secs:
+ if s["type"] == SHT_REL and s["info"] not in (text_i, data_i):
+ if e.secs[s["info"]]["flags"] & SHF_ALLOC:
+ fail(f"relocations for unexpected section {e.secs[s['info']]['sname']}")
+
+ # ---- write the object
+ base = f".rodata.np.{a.index}.{g}"
+ names = ["", base, ".rel" + base, base + ".init", ".rel" + base + ".init", ".symtab", ".strtab",
+ ".shstrtab"]
+ attrs = [s for s in e.secs if s["type"] == SHT_ARM_ATTRIBUTES]
+ if attrs:
+ names.append(".ARM.attributes")
+ shstr = bytearray(b"\0")
+ name_off = []
+ for n in names:
+ if not n:
+ name_off.append(0)
+ continue
+ name_off.append(len(shstr))
+ shstr += n.encode() + b"\0"
+
+ strtab = bytearray(b"\0")
+ str_off = {}
+
+ def add_str(s):
+ if not s:
+ return 0
+ if s not in str_off:
+ str_off[s] = len(strtab)
+ strtab.extend(s.encode() + b"\0")
+ return str_off[s]
+
+ symtab = bytearray()
+ for s in out_syms:
+ symtab += struct.pack("<IIIBBH", add_str(s["name"]), s["value"], s["size"],
+ (s["bind"] << 4) | s["type"], s["other"], s["shndx"])
+
+ def rel_bytes(rels):
+ return b"".join(struct.pack("<II", off, (si << 8) | typ) for off, typ, si in rels)
+
+ code_align = max(4, text["align"])
+ bodies = [
+ None,
+ (SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR, code_bytes, 0, 0, code_align, 0),
+ (SHT_REL, SHF_INFO_LINK, rel_bytes(code_rels), 5, 1, 4, 8),
+ (SHT_PROGBITS, SHF_ALLOC, init_bytes, 0, 0, 4 if not data else max(4, data["align"]), 0),
+ (SHT_REL, SHF_INFO_LINK, rel_bytes(init_rels), 5, 3, 4, 8),
+ (SHT_SYMTAB, 0, bytes(symtab), 6, first_global, 4, 16),
+ (SHT_STRTAB, 0, bytes(strtab), 0, 0, 1, 0),
+ (SHT_STRTAB, 0, bytes(shstr), 0, 0, 1, 0),
+ ]
+ if attrs:
+ bodies.append((SHT_ARM_ATTRIBUTES, 0, attrs[0]["data"], 0, 0, 1, 0))
+
+ out = bytearray(52)
+ headers = [bytes(40)]
+ for i, b in enumerate(bodies):
+ if b is None:
+ continue
+ typ, flags, blob, link, info, align, entsize = b
+ while len(out) % max(align, 4):
+ out.append(0)
+ off = len(out)
+ out += blob
+ headers.append(struct.pack("<10I", name_off[i], typ, flags, 0, off, len(blob), link, info, align, entsize))
+ while len(out) % 4:
+ out.append(0)
+ shoff = len(out)
+ for h in headers:
+ out += h
+ ident = b"\x7fELF\x01\x01\x01" + bytes(9)
+ struct.pack_into("<16sHHIIIIIHHHHHH", out, 0, ident, 1, 40, 1, 0, 0, shoff, e.flags, 52, 0, 0, 40,
+ len(headers), 7)
+ open(a.out, "wb").write(out)
+
+ info = dict(game=g, index=a.index, code=len(code_bytes), data=data_size, bss=bss_size,
+ ram_align=ram_align, undefined=sorted(undefined))
+ if a.json:
+ json.dump(info, open(a.json, "w"), indent=1)
+ print(f"module {g}: code+rodata {len(code_bytes)} B, data {data_size} B, bss {bss_size} B")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/shots.py b/tools/shots.py
new file mode 100644
index 00000000..166c7067
--- /dev/null
+++ b/tools/shots.py
@@ -0,0 +1,98 @@
+#!/usr/bin/env python3
+"""Packs a game's screenshots for the launcher's carousel.
+
+Each screenshot is scaled to 192x144 (60 %), reduced to at most 256 colours
+and compressed with raw DEFLATE; the launcher inflates it when the card is on
+screen. On the calculator everything goes in the game's block of flash, so
+uninstalling the game frees its screenshots too.
+
+Usage: shots.py --id numdash --index 1 out.c shot1.png shot2.png ...
+"""
+import argparse
+import os
+import shutil
+import subprocess
+import tempfile
+import zlib
+
+from PIL import Image
+
+W, H = 192, 144
+
+
+def rgb565(r, g, b):
+ return (min(31, (r + 4) >> 3) << 11) | (min(63, (g + 2) >> 2) << 5) | min(31, (b + 4) >> 3)
+
+
+def deflate(data):
+ try:
+ import zopfli.zlib
+ return zopfli.zlib.compress(bytes(data), numiterations=60)[2:-4]
+ except ImportError:
+ c = zlib.compressobj(9, zlib.DEFLATED, -15, 9)
+ return c.compress(bytes(data)) + c.flush()
+
+
+def quantize(im, colors):
+ """pngquant keeps small palettes faithful; PIL's median cut is the fallback."""
+ if shutil.which("pngquant"):
+ with tempfile.TemporaryDirectory() as d:
+ src, dst = os.path.join(d, "in.png"), os.path.join(d, "out.png")
+ im.save(src)
+ subprocess.run(["pngquant", "--nofs", "--speed", "1", "--force", "--output", dst, str(colors), src],
+ check=True)
+ q = Image.open(dst)
+ q.load()
+ if q.mode == "P":
+ return q
+ return im.quantize(colors=colors, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE)
+
+
+def pack(path, colors):
+ im = Image.open(path).convert("RGB")
+ if im.size != (W, H):
+ im = im.resize((W, H), Image.LANCZOS)
+ q = quantize(im, colors)
+ idx = q.tobytes()
+ used = max(idx) + 1
+ pal = q.getpalette()[:3 * used]
+ pal565 = [rgb565(*pal[i:i + 3]) for i in range(0, len(pal), 3)]
+ return pal565, deflate(idx)
+
+
+def c_array(ctype, name, values, per_line, attr):
+ out = [f"static const {ctype} {name}[{len(values)}] {attr} = {{"]
+ for i in range(0, len(values), per_line):
+ out.append(" " + ",".join(str(v) for v in values[i:i + per_line]) + ",")
+ out.append("};")
+ return out
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--id", required=True)
+ ap.add_argument("--index", type=int, required=True)
+ ap.add_argument("--colors", type=int, default=64)
+ ap.add_argument("out")
+ ap.add_argument("shots", nargs="+")
+ a = ap.parse_args()
+ section = f".rodata.np.{a.index}.{a.id}.shots"
+ lines = [f"/* Generated by tools/shots.py for {a.id}. */", '#include "np.h"', "#ifdef __ELF__",
+ f'#define S __attribute__((section("{section}"), aligned(4)))', "#else", "#define S", "#endif", ""]
+ total = 0
+ entries = []
+ for k, path in enumerate(a.shots):
+ pal, z = pack(path, a.colors)
+ total += len(z) + 2 * len(pal) + 16
+ lines += c_array("color_t", f"pal{k}", pal, 16, "S")
+ lines += c_array("uint8_t", f"z{k}", list(z), 32, "S")
+ entries.append(f" {{{W}, {H}, {len(pal)}, {len(z)}, pal{k}, z{k}}},")
+ lines.append(f"const np_shot_t np_{a.id}_shots[{len(entries)}] S = {{")
+ lines += entries
+ lines.append("};")
+ open(a.out, "w").write("\n".join(lines) + "\n")
+ print(f"shots {a.id}: {len(a.shots)} screenshots, {total} bytes")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/sizes.py b/tools/sizes.py
new file mode 100644
index 00000000..c695f25f
--- /dev/null
+++ b/tools/sizes.py
@@ -0,0 +1,27 @@
+#!/usr/bin/env python3
+"""Prints how NumPlay.nwa's flash and RAM are shared between the games."""
+import json
+import os
+import subprocess
+import sys
+
+nwa, mods = sys.argv[1], sys.argv[2]
+out = subprocess.run(["arm-none-eabi-nm", "-S", nwa], capture_output=True, text=True).stdout
+sym = {}
+for line in out.splitlines():
+ parts = line.split()
+ if len(parts) >= 3:
+ sym[parts[-1]] = int(parts[0], 16)
+secs = subprocess.run(["arm-none-eabi-size", "-A", nwa], capture_output=True, text=True).stdout
+total = 0
+rows = []
+for line in secs.splitlines():
+ p = line.split()
+ if len(p) >= 2 and p[0].startswith(".rodata.np."):
+ rows.append((p[0].split(".")[-1], int(p[1])))
+ total += int(p[1])
+print("NumPlay.nwa games (flash, including screenshots):")
+for name, size in rows:
+ info = json.load(open(os.path.join(mods, name + ".json")))
+ print(f" {name:12s} {size / 1024:7.1f} KB RAM {(info['data'] + info['bss']) / 1024:6.1f} KB")
+print(f" {'all games':12s} {total / 1024:7.1f} KB")