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.

Undertale: the engine's start (rooms cut from the wiki's maps, Frisk walking, doors, text)

Mason Chen08c7ad08aafe
diff --git a/games/undertale/.gitignore b/games/undertale/.gitignore
new file mode 100644
index 00000000..342d9dda
--- /dev/null
+++ b/games/undertale/.gitignore
@@ -0,0 +1,2 @@
+output/
+build/
diff --git a/games/undertale/Makefile b/games/undertale/Makefile
new file mode 100644
index 00000000..9d85865a
--- /dev/null
+++ b/games/undertale/Makefile
@@ -0,0 +1,79 @@
+# Undertale on the NumWorks calculator.
+# make output/undertale.nwa
+# make check link it like the calculator does (output/undertale.bin)
+# make host build/play: the game on a computer, for tests and screenshots
+# make test the game played on a computer (tests/check.py, with the sanitizers)
+# make data src/data.bin and src/data.h from the public material tools/fetch.py gathers
+# (REF=its folder, Python + Pillow + NumPy)
+Q ?= @
+# the ARM toolchain on the PATH, or in TOOLCHAIN=<its bin folder>
+TOOLCHAIN ?=
+BIN = $(if $(TOOLCHAIN),$(TOOLCHAIN)/)
+CC = $(BIN)arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+STRIP ?= $(BIN)arm-none-eabi-strip --strip-unneeded
+SIZE = $(BIN)arm-none-eabi-size
+BUILD_DIR = output
+REF ?=
+
+# the drawing runs every frame at -O2; the rest is small at -Os
+HOT = src/gfx.c src/bullets.c
+COLD = $(filter-out $(HOT) src/plat_host.c src/plat_eadk.c,$(wildcard src/*.c)) src/lzma/LzmaDec.c
+COLD_OBJ = $(patsubst src/%.c,$(BUILD_DIR)/cold/%.o,$(COLD))
+HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h
+
+CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DDATA_BIN='"src/data.bin"'
+CFLAGS += -O2 -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+CFLAGS += -ffunction-sections -fdata-sections $(EXTRA)
+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 check clean host test data
+build: $(BUILD_DIR)/undertale.nwa
+
+# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones)
+check: $(BUILD_DIR)/undertale.nwa
+ $(Q) $(NWLINK) nwa-bin --ram-length 133652 $< $(BUILD_DIR)/undertale.bin
+ @echo "BIN $(BUILD_DIR)/undertale.bin: $$(wc -c < $(BUILD_DIR)/undertale.bin) bytes"
+
+$(BUILD_DIR)/data.o: src/data.S src/data.bin | $(BUILD_DIR)
+ $(Q) $(CC) -c -DDATA_BIN='"src/data.bin"' $< -o $@
+
+$(BUILD_DIR)/cold/%.o: src/%.c $(HEADERS)
+ @mkdir -p $(@D)
+ $(Q) $(CC) $(CFLAGS) -Os -c $< -o $@
+
+$(BUILD_DIR)/undertale.nwa: $(HOT) src/plat_eadk.c $(COLD_OBJ) $(HEADERS) $(BUILD_DIR)/icon.o $(BUILD_DIR)/data.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(HOT) src/plat_eadk.c $(COLD_OBJ) $(BUILD_DIR)/data.o $(BUILD_DIR)/icon.o -lm -o $@
+ $(Q) $(STRIP) $@
+ $(Q) $(SIZE) $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+# on a computer: tests/play.c plays it with scripted keys and saves screenshots
+HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -Isrc -DHOST -DDATA_BIN='"src/data.bin"'
+HOST_SAN = -fsanitize=address,undefined -fno-sanitize-recover=undefined
+HOST_SRC = $(filter-out src/plat_eadk.c src/main.c,$(wildcard src/*.c)) src/lzma/LzmaDec.c
+host: build/play
+build/play: $(HOST_SRC) tests/play.c src/data.S src/data.bin $(HEADERS)
+ $(Q) mkdir -p $(dir $@)
+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) $(HOST_SRC) tests/play.c src/data.S -lm -o $@
+ @echo "HOST $@"
+
+test: build/play
+ python3 tests/check.py build/play
+
+data:
+ @test -n "$(REF)" || { echo "make data REF=<the folder tools/fetch.py filled>"; exit 1; }
+ python3 -I tools/pack.py $(REF)
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR) build
diff --git a/games/undertale/src/battle.c b/games/undertale/src/battle.c
new file mode 100644
index 00000000..e5d1c077
--- /dev/null
+++ b/games/undertale/src/battle.c
@@ -0,0 +1,9 @@
+/* Battles (battle.h). */
+#include "battle.h"
+#include "game.h"
+static bool over = true;
+void battle_start(int id) { (void)id; over = true; }
+bool battle_over(void) { return over; }
+int battle_result(void) { return BR_SPARED; }
+void battle_update(uint32_t keys, uint32_t pressed) { (void)keys, (void)pressed; }
+void battle_draw(void) {}
diff --git a/games/undertale/src/battle.h b/games/undertale/src/battle.h
new file mode 100644
index 00000000..d64165ca
--- /dev/null
+++ b/games/undertale/src/battle.h
@@ -0,0 +1,13 @@
+/* Undertale: battles (encounters). */
+#ifndef UT_BATTLE_H
+#define UT_BATTLE_H
+#include <stdbool.h>
+#include <stdint.h>
+
+void battle_start(int id);
+bool battle_over(void);
+int battle_result(void); /* BR_*: how the last one ended */
+void battle_update(uint32_t keys, uint32_t pressed);
+void battle_draw(void);
+enum { BR_WON, BR_SPARED, BR_FLED, BR_DIED, BR_SCRIPTED };
+#endif
diff --git a/games/undertale/src/bullets.c b/games/undertale/src/bullets.c
new file mode 100644
index 00000000..60389322
--- /dev/null
+++ b/games/undertale/src/bullets.c
@@ -0,0 +1,2 @@
+/* The bullet board's bullets. */
+#include "game.h"
diff --git a/games/undertale/src/data.S b/games/undertale/src/data.S
new file mode 100644
index 00000000..ef216e88
--- /dev/null
+++ b/games/undertale/src/data.S
@@ -0,0 +1,19 @@
+/* data.bin (tools/pack.py) in the app's read-only data */
+#ifdef __APPLE__
+ .const_data
+ .p2align 2
+ .globl _ut_data
+_ut_data:
+ .incbin DATA_BIN
+ .p2align 2
+#else
+ .section .rodata.ut_data,"a"
+ .balign 4
+ .global ut_data
+ut_data:
+ .incbin DATA_BIN
+ .balign 4
+#endif
+#ifdef __ELF__
+ .section .note.GNU-stack,"",%progbits
+#endif
diff --git a/games/undertale/src/data.h b/games/undertale/src/data.h
new file mode 100644
index 00000000..e553aee7
--- /dev/null
+++ b/games/undertale/src/data.h
@@ -0,0 +1,112 @@
+/* made by tools/pack.py: the contents of data.bin */
+#ifndef UT_DATA_H
+#define UT_DATA_H
+#define SEC_SPRITES 0
+#define SEC_FRAMES 1
+#define SEC_TILES 2
+#define SEC_ROOMS 3
+#define SEC_GRID 4
+#define SEC_COLL 5
+#define SEC_FONTS 6
+#define SEC_STRINGS 7
+#define SEC_DOORS 8
+#define SPR_FRISK_D 0
+#define SPR_FRISK_U 1
+#define SPR_FRISK_L 2
+#define SPR_FRISK_R 3
+#define SPR_TORIEL_D 4
+#define SPR_TORIEL_U 5
+#define SPR_TORIEL_L 6
+#define SPR_TORIEL_R 7
+#define SPR_SAVEPOINT 8
+#define SPR_FLOWEY 9
+#define SPR_HEART 10
+#define SPR_FACE_TORIELTALK 11
+#define SPR_FACE_TORIELTALKSIDE 12
+#define SPR_FACE_TORIELHAPPYTALK 13
+#define SPR_FACE_TORIELWHAT 14
+#define SPR_FACE_TORIELWHATSIDE 15
+#define SPR_FACE_TORIELMAD 16
+#define SPR_FACE_TORIELCOLD 17
+#define SPR_FACE_TORIELSURPRISED 18
+#define SPR_FACE_TORIELEMBARRASSED 19
+#define SPR_FACE_TORIELGLASSES 20
+#define SPR_FACE_TORIELREVENGETALK 21
+#define SPR_FACE_TORIELSCARED 22
+#define SPR_FACE_TORIELBLINK 23
+#define SPR_FACE_TORIELHAPPYBLINK 24
+#define SPR_FACE_TORIELBODY 25
+#define SPR_FACE_SANS 26
+#define SPR_FACE_SANSCHUCKLE 27
+#define SPR_FACE_SANSWINK 28
+#define SPR_FACE_PAPYRUS 29
+#define SPR_FACE_PAPYRUSEVIL 30
+#define SPR_FACE_PAPYRUSLAUGH 31
+#define SPR_FACE_PAPYRUSMAD 32
+#define SPR_FACE_PAPYRUSSIDE 33
+#define SPR_FLOWEYNICE 34
+#define SPR_FLOWEYNICESIDE 35
+#define SPR_FLOWEYSASSY 36
+#define SPR_FLOWEYEVIL 37
+#define SPR_FLOWEYGRIN 38
+#define SPR_FLOWEYPLAIN 39
+#define SPR_FLOWEYPISSED 40
+#define SPR_FLOWEYWINK 41
+#define SPR_FLOWEYLAUGH 42
+#define SPR_FLOWEYHURT 43
+#define SPR_FLOWEYTORIEL 44
+#define SPR_FLOWEYTORIEL2 45
+#define SPR_FLOWEYSIDESHOCK 46
+#define AREA_RUINS 0
+#define ROOM_AREA1 0
+#define ROOM_AREA1_2 1
+#define ROOM_RUINS1 2
+#define ROOM_RUINS2 3
+#define ROOM_RUINS3 4
+#define ROOM_RUINS4 5
+#define ROOM_RUINS5 6
+#define ROOM_RUINS6 7
+#define ROOM_RUINS7 8
+#define ROOM_RUINS7A 9
+#define ROOM_RUINS8 10
+#define ROOM_RUINS8B 11
+#define ROOM_RUINS9 12
+#define ROOM_RUINS10 13
+#define ROOM_RUINS10B 14
+#define ROOM_RUINS11 15
+#define ROOM_RUINS12 16
+#define ROOM_RUINS13 17
+#define ROOM_RUINS14 18
+#define ROOM_RUINS15 19
+#define ROOM_RUINS16 20
+#define ROOM_RUINS16A 21
+#define ROOM_RUINS16B 22
+#define ROOM_RUINS16C 23
+#define ROOM_RUINS16D 24
+#define ROOM_RUINS16E 25
+#define ROOM_RUINS16F 26
+#define ROOM_RUINS17A 27
+#define ROOM_RUINS17B 28
+#define ROOM_RUINS17C 29
+#define ROOM_RUINS17D 30
+#define ROOM_RUINS17X 31
+#define ROOM_RUINS18 32
+#define ROOM_RUINS19 33
+#define ROOM_RUINS20 34
+#define ROOM_RUINS21 35
+#define ROOM_TORHOUSE1 36
+#define ROOM_TORHOUSE2 37
+#define ROOM_TORKITCHEN 38
+#define ROOM_TORHOUSE3 39
+#define ROOM_ASRIELROOM 40
+#define ROOM_TORIELROOM 41
+#define ROOM_BASEMENT1 42
+#define ROOM_BASEMENT2 43
+#define ROOM_BASEMENT3 44
+#define ROOM_RUINSEXIT 45
+#define FONT_MAIN 0
+#define FONT_SMALL 1
+#define NUM_SPRITES 47
+#define NUM_ROOMS 46
+#define NUM_FONTS 2
+#endif
diff --git a/games/undertale/src/event.c b/games/undertale/src/event.c
new file mode 100644
index 00000000..646a97e6
--- /dev/null
+++ b/games/undertale/src/event.c
@@ -0,0 +1,48 @@
+/* The event that runs now (event.h), and Frisk walking for a cutscene. */
+#include <string.h>
+#include "event.h"
+#include "game.h"
+
+static Ev cur;
+static bool running;
+
+void event_start(int id, Obj *self) {
+ if (running || !id) return;
+ memset(&cur, 0, sizeof cur);
+ cur.id = id, cur.self = self;
+ running = true;
+ event_update(); /* (it starts this frame: a talk opens at once) */
+}
+
+bool event_running(void) { return running; }
+
+void event_update(void) {
+ if (!running) return;
+ if (event_run(&cur)) running = false;
+}
+
+/* ---------------------------------------------------------------- Frisk walked */
+static struct {
+ int x, y, sp;
+ bool on;
+} walk;
+
+void pl_walk_to(int x, int y, int sp) { walk.x = x, walk.y = y, walk.sp = sp ? sp : 3, walk.on = true; }
+bool pl_walking(void) { return walk.on; }
+
+/* (world.c calls it each frame while a cutscene runs) */
+void pl_walk_step(void) {
+ if (!walk.on) {
+ pl.moving = 0;
+ return;
+ }
+ int dx = walk.x - pl.x, dy = walk.y - pl.y;
+ if (dx) pl.dir = dx < 0 ? DIR_LEFT : DIR_RIGHT;
+ if (abs_i(dy) > abs_i(dx)) pl.dir = dy < 0 ? DIR_UP : DIR_DOWN;
+ pl.x = (int16_t)(pl.x + clamp_i(dx, -walk.sp, walk.sp));
+ pl.y = (int16_t)(pl.y + clamp_i(dy, -walk.sp, walk.sp));
+ pl.anim++;
+ pl.frame = (uint8_t)((1 + pl.anim / 6) % (pl.dir < 2 ? 4 : 2));
+ pl.moving = 1;
+ if (pl.x == walk.x && pl.y == walk.y) walk.on = false, pl.frame = 0, pl.anim = 0, pl.moving = 0;
+}
diff --git a/games/undertale/src/event.h b/games/undertale/src/event.h
new file mode 100644
index 00000000..a850806b
--- /dev/null
+++ b/games/undertale/src/event.h
@@ -0,0 +1,43 @@
+/* Undertale: events, the game's cutscenes and talks.
+ *
+ * An event is a C function called once a frame until it says it is done;
+ * the macros below make it read like the game's scripts (each SAY waits for
+ * its text, each WAIT for its frames). Its locals don't last over a wait:
+ * what has to is kept in c->v. One event runs at a time; while it does,
+ * Frisk doesn't move unless it lets him. */
+#ifndef UT_EVENT_H
+#define UT_EVENT_H
+#include <stdbool.h>
+#include "text.h"
+#include "world.h"
+
+typedef struct Ev {
+ int id, line, t;
+ int v[6];
+ Obj *self;
+} Ev;
+
+#define EV_BEGIN switch (c->line) { case 0:
+#define EV_END } return 1
+#define EV_YIELD do { c->line = __LINE__; return 0; case __LINE__:; } while (0)
+#define WAIT_UNTIL(cond) do { c->line = __LINE__; case __LINE__: if (!(cond)) return 0; } while (0)
+#define WAIT(n) do { c->t = (n); c->line = __LINE__; case __LINE__: if (c->t-- > 0) return 0; } while (0)
+#define SAY(face, s) do { text_open(face, s); WAIT_UNTIL(!text_active()); } while (0)
+#define SAYF(face, ...) do { text_openf(face, __VA_ARGS__); WAIT_UNTIL(!text_active()); } while (0)
+#define NARRATE(s) SAY(FACE_NONE, s)
+#define CHOICE() text_choice()
+/* an object walks to (x, y) at sp pixels a frame; WALK waits for it */
+#define WALK_TO(o, X, Y, SP) do { (o)->tx = (int16_t)(X), (o)->ty = (int16_t)(Y), (o)->speed = (uint8_t)(SP), (o)->walking = 1; } while (0)
+#define WALK(o, X, Y, SP) do { WALK_TO(o, X, Y, SP); WAIT_UNTIL(!(o)->walking); } while (0)
+/* Frisk walks to (x, y), as a cutscene moves him */
+#define PL_WALK(X, Y, SP) do { pl_walk_to(X, Y, SP); WAIT_UNTIL(!pl_walking()); } while (0)
+#define BATTLE(id) do { battle_start(id); WAIT_UNTIL(battle_over()); } while (0)
+#define FADE_TO(r, X, Y, D) do { world_fade_to(r, X, Y, D); WAIT_UNTIL(!world_fading()); } while (0)
+
+void event_start(int id, Obj *self);
+bool event_running(void);
+void event_update(void);
+int event_run(Ev *c); /* events.c: the events, by id */
+void pl_walk_to(int x, int y, int sp);
+bool pl_walking(void);
+#endif
diff --git a/games/undertale/src/events.c b/games/undertale/src/events.c
new file mode 100644
index 00000000..8dadaf7a
--- /dev/null
+++ b/games/undertale/src/events.c
@@ -0,0 +1,10 @@
+/* The events (event.h). */
+#include "event.h"
+#include "events.h"
+#include "game.h"
+
+int event_run(Ev *c) {
+ switch (c->id) {
+ default: return 1;
+ }
+}
diff --git a/games/undertale/src/events.h b/games/undertale/src/events.h
new file mode 100644
index 00000000..f1ff3fbc
--- /dev/null
+++ b/games/undertale/src/events.h
@@ -0,0 +1,9 @@
+/* Undertale: the events, by id. */
+#ifndef UT_EVENTS_H
+#define UT_EVENTS_H
+enum {
+ EV_NONE,
+ EV_SIGN, /* a sign or anything that only says its text (self->arg: the text, in events.c) */
+ EV_COUNT
+};
+#endif
diff --git a/games/undertale/src/flags.h b/games/undertale/src/flags.h
new file mode 100644
index 00000000..46305f19
--- /dev/null
+++ b/games/undertale/src/flags.h
@@ -0,0 +1,55 @@
+/* Undertale: what the game remembers (the original's global.flag), named.
+ * Saved: new flags go at the end, before FLAG_COUNT. */
+#ifndef UT_FLAGS_H
+#define UT_FLAGS_H
+enum {
+ F_NONE,
+ /* the Ruins */
+ F_FLOWEY_MET, /* the first meeting is over */
+ F_TORIEL_MET,
+ F_RUINS1_DONE, /* Toriel waited at the entrance's stairs */
+ F_RUINS2_DONE, /* the middle road puzzle */
+ F_RUINS3_SW1, F_RUINS3_SW2, F_RUINS3_DONE,
+ F_DUMMY, /* 1 talked, 2 fought, 3 fled, 4 bored */
+ F_RUINS5_DONE, /* the spikes, hand in hand */
+ F_RUINS6_DONE, /* the independence test */
+ F_PHONE, /* Toriel's cell phone */
+ F_LEAFPILE_CALL,
+ F_CANDY_TAKEN, /* Monster Candy taken (to 4) */
+ F_CANDY_SPILT,
+ F_RUINS9_ROCK, /* the first rock pushed home */
+ F_FLAVOR_CALL, F_FLAVOR, /* 1 cinnamon, 2 butterscotch */
+ F_RUINS11_ROCK, /* the second rock puzzle: the reluctant rock moved */
+ F_RUINS11_ASK,
+ F_NAPSTA, /* 1 spared, 2 killed, 3 fled */
+ F_DONUT_BOUGHT, F_CIDER_BOUGHT,
+ F_ITEM_CALL,
+ F_FROGGIT_YELLOW, /* 0 yellow names, 1 white, 2 pink */
+ F_RIBBON, F_TOYKNIFE,
+ F_ONESWITCH, F_ROTATE1, F_ROTATE2, F_ROTATE3, F_ROTATE4,
+ F_ALLERGY_CALL,
+ F_TORIEL_HOME, /* Toriel found Frisk at her tree */
+ F_PIE, /* the pie slice taken */
+ F_TORIEL_TALKS, /* questions asked her by the fire */
+ F_TORIEL_BASEMENT, /* she went downstairs */
+ F_BASEMENT_TALK, /* 1..3: what she said along the way */
+ F_TORIEL_FIGHT, /* 1 spared, 2 killed */
+ F_FLOWEY_END,
+ F_RUINS_EXIT,
+ F_KILLS_RUINS,
+ F_SKIPS, /* text pages skipped with X (a Froggit notices) */
+ F_FROG_TIP,
+ F_SAVE_SEEN,
+ F_FALL_LEAVES,
+ F_SPIDER_CALL,
+ F_ASRIEL_ROOM,
+ F_MIRROR,
+ F_LIGHTS,
+ F_RUINS_SAVE_BED,
+ F_HARDMODE,
+ F_FIRST_FROGGIT,
+ F_TORIEL_SNAIL,
+ F_WHIMSUN_TALK,
+ FLAG_COUNT = 256
+};
+#endif
diff --git a/games/undertale/src/game.c b/games/undertale/src/game.c
new file mode 100644
index 00000000..748ffb39
--- /dev/null
+++ b/games/undertale/src/game.c
@@ -0,0 +1,136 @@
+/* The game's state, its modes and its frame (game.h). */
+#include <string.h>
+#include "battle.h"
+#include "event.h"
+#include "game.h"
+#include "gfx.h"
+#include "items.h"
+#include "menu.h"
+#include "res.h"
+#include "save.h"
+#include "text.h"
+#include "world.h"
+
+Save sv;
+int g_mode;
+uint32_t g_frame;
+bool g_running = true;
+static uint32_t prev_keys;
+
+static uint32_t seed = 0x2545F491u;
+uint32_t rnd(void) {
+ seed ^= seed << 13, seed ^= seed >> 17, seed ^= seed << 5;
+ return seed;
+}
+int rnd_n(int n) { return n > 0 ? (int)(rnd() % (uint32_t)n) : 0; }
+
+/* ---------------------------------------------------------------- stats (LOVE) */
+static const uint32_t exp_table[] = {0, 0, 10, 30, 70, 120, 200, 300, 500, 800, 1200, 1700, 2500, 3500, 5000, 7000,
+ 10000, 15000, 25000, 50000, 99999};
+int lv_exp_for(int lv) { return lv >= 1 && lv <= 20 ? (int)exp_table[lv] : 99999; }
+int lv_maxhp(int lv) { return lv >= 20 ? 99 : 16 + 4 * lv; }
+int lv_at(int lv) { return 8 + 2 * lv; }
+int lv_df(int lv) { return 10 + (lv - 1) / 4; }
+
+bool gain_exp(int exp) {
+ sv.exp = (uint32_t)min_i((int)sv.exp + exp, 99999);
+ bool up = false;
+ while (sv.lv < 20 && (int)sv.exp >= lv_exp_for(sv.lv + 1)) {
+ sv.lv++;
+ int old = sv.maxhp;
+ sv.maxhp = (int16_t)lv_maxhp(sv.lv);
+ sv.hp = (int16_t)(sv.hp + sv.maxhp - old);
+ sv.at = (uint8_t)lv_at(sv.lv), sv.df = (uint8_t)lv_df(sv.lv);
+ up = true;
+ }
+ return up;
+}
+int weapon_at(void) { return item_info(sv.weapon)->at; }
+int armor_df(void) { return item_info(sv.armor)->df; }
+
+bool item_add(int item) {
+ for (int i = 0; i < NUM_ITEMS; i++)
+ if (!sv.items[i]) {
+ sv.items[i] = (uint8_t)item;
+ return true;
+ }
+ return false;
+}
+void item_remove_at(int slot) {
+ for (int i = slot; i < NUM_ITEMS - 1; i++) sv.items[i] = sv.items[i + 1];
+ sv.items[NUM_ITEMS - 1] = 0;
+}
+int item_count(void) {
+ int n = 0;
+ while (n < NUM_ITEMS && sv.items[n]) n++;
+ return n;
+}
+
+/* ---------------------------------------------------------------- a new game */
+void game_new(const char *name) {
+ memset(&sv, 0, sizeof sv);
+ strncpy(sv.name, name, sizeof sv.name - 1);
+ memcpy(g_name, sv.name, sizeof g_name);
+ sv.lv = 1, sv.maxhp = sv.hp = 20, sv.at = (uint8_t)lv_at(1), sv.df = (uint8_t)lv_df(1);
+ sv.weapon = ITEM_STICK, sv.armor = ITEM_BANDAGE;
+ g_mode = MODE_WORLD;
+ world_enter(ROOM_AREA1, 120, 6010, DIR_DOWN);
+}
+
+void game_init(void) {
+ save_restore_copy();
+ menu_title_open();
+}
+
+void game_open_menu(void) { menu_open(); }
+
+void game_quit_save(void) { save_resume_write(); }
+
+/* ---------------------------------------------------------------- the frame */
+void game_frame(uint32_t keys) {
+ uint32_t pressed = keys & ~prev_keys;
+ prev_keys = keys;
+ g_frame++;
+ if (keys & K_HOME) {
+ if (g_mode == MODE_WORLD || g_mode == MODE_MENU || g_mode == MODE_BATTLE) game_quit_save();
+ g_running = false;
+ return;
+ }
+ if (g_mode == MODE_WORLD || g_mode == MODE_BATTLE || g_mode == MODE_MENU) sv.time++;
+ switch (g_mode) {
+ case MODE_WORLD:
+ world_update(keys, pressed);
+ event_update();
+ text_update(pressed);
+ break;
+ case MODE_BATTLE:
+ battle_update(keys, pressed);
+ event_update();
+ break;
+ default:
+ menu_update(keys, pressed);
+ if (g_mode == MODE_WORLD) event_update();
+ break;
+ }
+}
+
+void game_draw(void) {
+ gfx_begin();
+ switch (g_mode) {
+ case MODE_WORLD:
+ case MODE_MENU:
+ case MODE_SAVE:
+ world_draw();
+ if (g_fade) gfx_rect(0, 0, SCREEN_W, SCREEN_H, C_BLACK, g_fade);
+ text_draw();
+ if (g_mode != MODE_WORLD) menu_draw();
+ break;
+ case MODE_BATTLE:
+ battle_draw();
+ break;
+ default:
+ menu_draw();
+ break;
+ }
+ gfx_end();
+}
diff --git a/games/undertale/src/game.h b/games/undertale/src/game.h
new file mode 100644
index 00000000..d9cb1785
--- /dev/null
+++ b/games/undertale/src/game.h
@@ -0,0 +1,66 @@
+/* Undertale: the game's state and its modes (title, overworld, battle, menus).
+ *
+ * Inspired by Undertale by Toby Fox, not affiliated with him.
+ * Made by Mason Chen as part of NumPlay. */
+#ifndef UT_GAME_H
+#define UT_GAME_H
+#include <stdbool.h>
+#include <stdint.h>
+#include "flags.h"
+
+static inline int abs_i(int v) { return v < 0 ? -v : v; }
+static inline int clamp_i(int v, int a, int b) { return v < a ? a : v > b ? b : v; }
+static inline int min_i(int a, int b) { return a < b ? a : b; }
+static inline int max_i(int a, int b) { return a > b ? a : b; }
+
+enum { MODE_TITLE, MODE_NAME, MODE_WORLD, MODE_BATTLE, MODE_MENU, MODE_SAVE, MODE_GAMEOVER, MODE_INTRO, MODE_END };
+
+#define NUM_ITEMS 8
+typedef struct {
+ /* what a SAVE keeps */
+ char name[8];
+ uint8_t lv;
+ uint32_t exp;
+ uint16_t gold;
+ int16_t hp, maxhp;
+ uint8_t at, df; /* the game's own: 10 at LV 1, shown less 10 */
+ uint8_t weapon, armor; /* ITEM_* */
+ uint8_t items[NUM_ITEMS]; /* ITEM_*, 0 none */
+ uint8_t phone[8]; /* CELL: who can be called */
+ uint16_t kills;
+ uint32_t time; /* frames played */
+ int16_t room, x, y; /* where it was saved */
+ uint8_t flags[FLAG_COUNT];
+} Save;
+extern Save sv; /* the game now */
+extern int g_mode;
+extern uint32_t g_frame;
+extern bool g_running;
+
+static inline int flag(int f) { return sv.flags[f]; }
+static inline void set_flag(int f, int v) { sv.flags[f] = (uint8_t)v; }
+
+void game_init(void);
+void game_frame(uint32_t keys);
+void game_draw(void);
+void game_quit_save(void); /* Home: the moment is kept, to come back to */
+void game_open_menu(void);
+void room_setup(int room, int from); /* rooms.c: the room's objects */
+void encounter_step(void); /* rooms.c: a step towards a random encounter */
+uint32_t rnd(void);
+int rnd_n(int n); /* 0 .. n - 1 */
+
+/* stats */
+int lv_maxhp(int lv);
+int lv_at(int lv);
+int lv_df(int lv);
+int lv_exp_for(int lv); /* the EXP to reach LV lv */
+bool gain_exp(int exp); /* true if LOVE went up */
+int weapon_at(void);
+int armor_df(void);
+
+/* items: inventory */
+bool item_add(int item);
+void item_remove_at(int slot);
+int item_count(void);
+#endif
diff --git a/games/undertale/src/gfx.c b/games/undertale/src/gfx.c
new file mode 100644
index 00000000..10200547
--- /dev/null
+++ b/games/undertale/src/gfx.c
@@ -0,0 +1,475 @@
+/* The renderer: a draw list rasterised in bands of GFX_BAND rows.
+ *
+ * Each command keeps its screen bounds (clipped); a band walks the commands
+ * that cross it, in order. Sprites are row RLE (res.h): a row is runs of
+ * (skip, length, pixels), so a band only reads the rows it shows. Alpha has
+ * 33 steps (0..32), applied with the usual RGB565 trick. */
+#include <string.h>
+#include "gfx.h"
+#include "res.h"
+#include "world.h"
+
+enum { I_RECT, I_SPRITE, I_TILES, I_TEXT, I_LINE, I_CIRCLE, I_SPRITE_EX };
+
+typedef struct {
+ uint8_t kind, flags, alpha, font;
+ int16_t x0, y0, x1, y1; /* screen bounds, clipped: [x0, x1) x [y0, y1) */
+ int16_t cx0, cx1; /* the clip's columns */
+ int16_t x, y; /* sprite: its top-left; text: its top-left; line: start */
+ int16_t a, b; /* line: end; circle: radius; sprite_ex: scale x, scale y; text: shake, spacing */
+ uint16_t ref, sub; /* sprite, frame / text: pool offset, length */
+ uint16_t color; /* sprite: 0 its own colours, else 1 + RGB565 (in `extra`) */
+ uint16_t extra;
+ uint32_t seed;
+} Item;
+
+#ifdef HOST
+static uint16_t host_band[SCREEN_W * GFX_BAND];
+static uint16_t *band = host_band;
+#else
+static uint16_t *band;
+#endif
+void gfx_set_band_memory(uint16_t *px) {
+#ifdef HOST
+ band = px ? px : host_band;
+#else
+ band = px;
+#endif
+}
+
+static Item items[GFX_MAX_ITEMS];
+static int nitems;
+static char pool[GFX_TEXT_POOL];
+static int npool;
+static int clip_x0, clip_y0, clip_x1 = SCREEN_W, clip_y1 = SCREEN_H;
+int gfx_dropped;
+static int dropped_now;
+
+void gfx_begin(void) {
+ nitems = 0, npool = 0, dropped_now = 0;
+ gfx_clip_all();
+}
+
+void gfx_clip(int x, int y, int w, int h) {
+ clip_x0 = x < 0 ? 0 : x, clip_y0 = y < 0 ? 0 : y;
+ clip_x1 = x + w > SCREEN_W ? SCREEN_W : x + w, clip_y1 = y + h > SCREEN_H ? SCREEN_H : y + h;
+}
+void gfx_clip_all(void) { clip_x0 = 0, clip_y0 = 0, clip_x1 = SCREEN_W, clip_y1 = SCREEN_H; }
+
+/* a new command over [x0, x1) x [y0, y1), clipped; NULL if it shows nothing */
+static Item *add(int kind, int x0, int y0, int x1, int y1) {
+ if (x0 < clip_x0) x0 = clip_x0;
+ if (y0 < clip_y0) y0 = clip_y0;
+ if (x1 > clip_x1) x1 = clip_x1;
+ if (y1 > clip_y1) y1 = clip_y1;
+ if (x0 >= x1 || y0 >= y1) return NULL;
+ if (nitems >= GFX_MAX_ITEMS) {
+ dropped_now++;
+ return NULL;
+ }
+ Item *it = &items[nitems++];
+ memset(it, 0, sizeof *it);
+ it->kind = (uint8_t)kind;
+ it->x0 = (int16_t)x0, it->y0 = (int16_t)y0, it->x1 = (int16_t)x1, it->y1 = (int16_t)y1;
+ it->cx0 = (int16_t)clip_x0, it->cx1 = (int16_t)clip_x1;
+ it->alpha = 255;
+ return it;
+}
+
+void gfx_rect(int x, int y, int w, int h, uint16_t color, uint8_t alpha) {
+ if (!alpha) return;
+ Item *it = add(I_RECT, x, y, x + w, y + h);
+ if (it) it->color = color, it->alpha = alpha;
+}
+
+void gfx_frame_rect(int x, int y, int w, int h, int t, uint16_t color) {
+ gfx_rect(x, y, w, t, color, 255);
+ gfx_rect(x, y + h - t, w, t, color, 255);
+ gfx_rect(x, y + t, t, h - 2 * t, color, 255);
+ gfx_rect(x + w - t, y + t, t, h - 2 * t, color, 255);
+}
+
+static void sprite_item(uint16_t s, int i, int x, int y, uint8_t flags, uint16_t color, bool tint, uint8_t alpha) {
+ Frame f;
+ if (!alpha || !frame_get(s, i, &f)) return;
+ int tx = x - ((flags & GFX_FLIPX) ? f.w - 1 - f.ox : f.ox), ty = y - ((flags & GFX_FLIPY) ? f.h - 1 - f.oy : f.oy);
+ Item *it = add(I_SPRITE, tx, ty, tx + f.w, ty + f.h);
+ if (!it) return;
+ it->x = (int16_t)tx, it->y = (int16_t)ty;
+ it->ref = s, it->sub = (uint16_t)i, it->flags = flags, it->alpha = alpha;
+ it->color = tint, it->extra = color;
+}
+void gfx_sprite(uint16_t s, int i, int x, int y, uint8_t flags, uint8_t alpha) { sprite_item(s, i, x, y, flags, 0, false, alpha); }
+void gfx_sprite_color(uint16_t s, int i, int x, int y, uint8_t flags, uint16_t color, uint8_t alpha) {
+ sprite_item(s, i, x, y, flags, color, true, alpha);
+}
+
+/* scaled and turned: the bounds of the turned rectangle (sin and cos in 1/256 steps of a turn) */
+static const int16_t sin_q[65] = {
+ 0, 25, 50, 75, 100, 125, 150, 175, 200, 224, 249, 273, 297, 321, 345, 369, 392, 415, 438, 460, 483, 505, 526, 548,
+ 569, 590, 610, 630, 650, 669, 688, 706, 724, 742, 759, 775, 792, 807, 822, 837, 851, 865, 878, 891, 903, 915, 926,
+ 936, 946, 955, 964, 972, 980, 987, 993, 999, 1004, 1009, 1013, 1016, 1019, 1021, 1023, 1024, 1024};
+int gfx_sin(int a) { /* a in 1/256 turn, result in 1/1024 */
+ a &= 255;
+ if (a < 64) return sin_q[a];
+ if (a < 128) return sin_q[128 - a];
+ if (a < 192) return -sin_q[a - 128];
+ return -sin_q[256 - a];
+}
+int gfx_cos(int a) { return gfx_sin(a + 64); }
+
+void gfx_sprite_ex(uint16_t s, int i, int x, int y, int scale_x, int scale_y, int angle, uint16_t color, uint8_t alpha) {
+ Frame f;
+ if (!alpha || !frame_get(s, i, &f) || !scale_x || !scale_y) return;
+ if (!(angle & 255) && scale_x == 256 && scale_y == 256) {
+ sprite_item(s, i, x, y, 0, color, color != 0, alpha);
+ return;
+ }
+ /* the corners, relative to the origin, scaled then turned */
+ int c = gfx_cos(angle), sn = gfx_sin(angle);
+ int xs[4] = {-f.ox, f.w - f.ox, -f.ox, f.w - f.ox}, ys[4] = {-f.oy, -f.oy, f.h - f.oy, f.h - f.oy};
+ int minx = 1 << 30, maxx = -(1 << 30), miny = 1 << 30, maxy = -(1 << 30);
+ for (int k = 0; k < 4; k++) {
+ int px = xs[k] * scale_x / 256, py = ys[k] * scale_y / 256;
+ int rx = (px * c - py * sn) / 1024, ry = (px * sn + py * c) / 1024;
+ if (rx < minx) minx = rx;
+ if (rx > maxx) maxx = rx;
+ if (ry < miny) miny = ry;
+ if (ry > maxy) maxy = ry;
+ }
+ Item *it = add(I_SPRITE_EX, x + minx - 1, y + miny - 1, x + maxx + 2, y + maxy + 2);
+ if (!it) return;
+ it->x = (int16_t)x, it->y = (int16_t)y;
+ it->a = (int16_t)scale_x, it->b = (int16_t)scale_y;
+ it->ref = s, it->sub = (uint16_t)i, it->alpha = alpha;
+ it->color = color != 0, it->extra = color;
+ it->seed = (uint32_t)angle;
+}
+
+void gfx_tiles(int wx, int wy) {
+ Item *it = add(I_TILES, 0, 0, SCREEN_W, SCREEN_H);
+ if (it) it->x = (int16_t)wx, it->y = (int16_t)wy;
+}
+
+void gfx_line(int x0, int y0, int x1, int y1, uint16_t color) {
+ Item *it = add(I_LINE, (x0 < x1 ? x0 : x1), (y0 < y1 ? y0 : y1), (x0 > x1 ? x0 : x1) + 1, (y0 > y1 ? y0 : y1) + 1);
+ if (!it) return;
+ it->x = (int16_t)x0, it->y = (int16_t)y0, it->a = (int16_t)x1, it->b = (int16_t)y1, it->color = color;
+}
+
+void gfx_circle(int cx, int cy, int r, uint16_t color, uint8_t alpha) {
+ Item *it = add(I_CIRCLE, cx - r, cy - r, cx + r + 1, cy + r + 1);
+ if (!it) return;
+ it->x = (int16_t)cx, it->y = (int16_t)cy, it->a = (int16_t)r, it->color = color, it->alpha = alpha;
+}
+
+/* ---------------------------------------------------------------- fonts */
+typedef struct {
+ uint8_t height, first, count, flags;
+ const uint8_t *glyphs; /* 8 bytes each: advance, w, h, ox, oy, pad, bitmap offset (u16) */
+ const uint8_t *bits;
+} Font;
+static void font_get(int font, Font *f) {
+ const uint8_t *s = section(SEC_FONTS);
+ const uint8_t *p = s + rd32(s + 4 + 4 * font);
+ f->height = p[0], f->first = p[1], f->count = p[2], f->flags = p[3];
+ f->glyphs = p + 4;
+ f->bits = p + 4 + 8 * f->count;
+}
+static const uint8_t *glyph(const Font *f, uint8_t c) {
+ if (c < f->first || c >= f->first + f->count) c = '?';
+ if (c < f->first || c >= f->first + f->count) return NULL;
+ return f->glyphs + 8 * (c - f->first);
+}
+int font_height(int font) {
+ Font f;
+ font_get(font, &f);
+ return f.height;
+}
+int gfx_text_width(int font, const char *s, int n) {
+ Font f;
+ font_get(font, &f);
+ int w = 0, best = 0;
+ for (int i = 0; i < n && s[i]; i++) {
+ if (s[i] == '\n') {
+ if (w > best) best = w;
+ w = 0;
+ continue;
+ }
+ const uint8_t *g = glyph(&f, (uint8_t)s[i]);
+ if (g) w += g[0];
+ }
+ return w > best ? w : best;
+}
+
+int gfx_text_ex(int font, int x, int y, const char *s, int n, uint16_t color, int shake, uint32_t seed, int spacing) {
+ int len = 0;
+ while (len < n && s[len]) len++;
+ if (!len) return 0;
+ Font f;
+ font_get(font, &f);
+ int lines = 1;
+ for (int i = 0; i < len; i++) lines += s[i] == '\n';
+ int w = gfx_text_width(font, s, len) + len * spacing;
+ if (npool + len > GFX_TEXT_POOL) {
+ dropped_now++;
+ return w;
+ }
+ Item *it = add(I_TEXT, x - shake - 2, y - shake - 4, x + w + shake + 4, y + lines * (f.height + 2) + shake + 4);
+ if (!it) return w;
+ memcpy(pool + npool, s, (size_t)len);
+ it->ref = (uint16_t)npool, it->sub = (uint16_t)len;
+ npool += len;
+ it->x = (int16_t)x, it->y = (int16_t)y, it->font = (uint8_t)font, it->color = color;
+ it->a = (int16_t)shake, it->b = (int16_t)spacing, it->seed = seed;
+ return w;
+}
+int gfx_text(int font, int x, int y, const char *s, uint16_t color, uint8_t alpha) {
+ (void)alpha;
+ return gfx_text_ex(font, x, y, s, 0x7FFF, color, 0, 0, 0);
+}
+
+/* ---------------------------------------------------------------- rasterising */
+static inline uint16_t blend(uint16_t d, uint16_t s, uint32_t 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) * a) >> 5)) & 0x07E0F81Fu;
+ return (uint16_t)(r | r >> 16);
+}
+static inline uint32_t a32(uint8_t a) { return (a * 32u + 127) / 255; }
+
+static void rast_rect(const Item *it, int by0, int by1) {
+ int y0 = it->y0 > by0 ? it->y0 : by0, y1 = it->y1 < by1 ? it->y1 : by1;
+ uint32_t a = a32(it->alpha);
+ for (int y = y0; y < y1; y++) {
+ uint16_t *row = band + (y - by0) * SCREEN_W;
+ if (a >= 32)
+ for (int x = it->x0; x < it->x1; x++) row[x] = it->color;
+ else
+ for (int x = it->x0; x < it->x1; x++) row[x] = blend(row[x], it->color, a);
+ }
+}
+
+static inline uint32_t px_at(const uint8_t *p, int k, int bpp) {
+ switch (bpp) {
+ case 8: return p[k];
+ case 4: return (p[k >> 1] >> ((k & 1) * 4)) & 15;
+ case 2: return (p[k >> 2] >> ((k & 3) * 2)) & 3;
+ case 1: return (p[k >> 3] >> (k & 7)) & 1;
+ default: return 0;
+ }
+}
+
+static void rast_sprite(const Item *it, int by0, int by1) {
+ Frame f;
+ if (!frame_get(it->ref, it->sub, &f)) return;
+ int y0 = it->y0 > by0 ? it->y0 : by0, y1 = it->y1 < by1 ? it->y1 : by1;
+ uint32_t a = a32(it->alpha);
+ bool fx = it->flags & GFX_FLIPX, fy = it->flags & GFX_FLIPY;
+ uint16_t pal[256];
+ for (int k = 0; k < f.ncol; k++) pal[k] = it->color ? it->extra : rd16(f.pal + 2 * k);
+ int cx0 = it->x0, cx1 = it->x1;
+ for (int y = y0; y < y1; y++) {
+ int r = y - it->y;
+ if (fy) r = f.h - 1 - r;
+ const uint8_t *p = f.data + rd16(f.rows + 2 * r);
+ uint16_t *row = band + (y - by0) * SCREEN_W;
+ int x = 0;
+ while (x < f.w) {
+ int skip = p[0], len = p[1];
+ p += 2;
+ x += skip;
+ for (int k = 0; k < len; k++) {
+ int sx = x + k;
+ int dx = it->x + (fx ? f.w - 1 - sx : sx);
+ if (dx < cx0 || dx >= cx1) continue;
+ uint16_t c = pal[px_at(p, k, f.bpp)];
+ row[dx] = a >= 32 ? c : blend(row[dx], c, a);
+ }
+ p += (len * f.bpp + 7) >> 3;
+ x += len;
+ }
+ }
+}
+
+/* one row of a frame, unpacked: index + 1 for each pixel, 0 where clear */
+static void frame_row(const Frame *f, int r, uint8_t *out) {
+ memset(out, 0, f->w);
+ const uint8_t *p = f->data + rd16(f->rows + 2 * r);
+ int x = 0;
+ while (x < f->w) {
+ int skip = p[0], len = p[1];
+ p += 2;
+ x += skip;
+ for (int k = 0; k < len && x + k < f->w; k++) out[x + k] = (uint8_t)(px_at(p, k, f->bpp) + 1);
+ p += (len * f->bpp + 7) >> 3;
+ x += len;
+ }
+}
+
+static void rast_sprite_ex(const Item *it, int by0, int by1) {
+ Frame f;
+ if (!frame_get(it->ref, it->sub, &f) || f.w > 640) return;
+ int y0 = it->y0 > by0 ? it->y0 : by0, y1 = it->y1 < by1 ? it->y1 : by1;
+ uint32_t a = a32(it->alpha);
+ uint16_t pal[256];
+ for (int k = 0; k < f.ncol; k++) pal[k] = it->color ? it->extra : rd16(f.pal + 2 * k);
+ int c = gfx_cos((int)it->seed), s = gfx_sin((int)it->seed);
+ /* inverse: source = R(-angle) (screen - origin) / scale, in 1/1024 */
+ static uint8_t rowbuf[640];
+ int cached = -1;
+ for (int y = y0; y < y1; y++) {
+ uint16_t *row = band + (y - by0) * SCREEN_W;
+ int dy = y - it->y;
+ for (int x = it->x0; x < it->x1; x++) {
+ int dx = x - it->x;
+ int ux = (dx * c + dy * s), uy = (-dx * s + dy * c); /* x 1024 */
+ int sx = (int)((int64_t)ux * 256 / ((int64_t)it->a * 1024)) + f.ox;
+ int sy = (int)((int64_t)uy * 256 / ((int64_t)it->b * 1024)) + f.oy;
+ if (ux < 0 && (int64_t)ux * 256 % ((int64_t)it->a * 1024)) sx--;
+ if (uy < 0 && (int64_t)uy * 256 % ((int64_t)it->b * 1024)) sy--;
+ if (sx < 0 || sy < 0 || sx >= f.w || sy >= f.h) continue;
+ if (sy != cached) frame_row(&f, sy, rowbuf), cached = sy;
+ uint8_t v = rowbuf[sx];
+ if (!v) continue;
+ uint16_t col = pal[v - 1];
+ row[x] = a >= 32 ? col : blend(row[x], col, a);
+ }
+ }
+}
+
+static void rast_tiles(const Item *it, int by0, int by1) {
+ const RoomInfo *r = world_room_info();
+ if (!r) return;
+ int y0 = it->y0 > by0 ? it->y0 : by0, y1 = it->y1 < by1 ? it->y1 : by1;
+ /* only inside the room's rectangle: outside it stays black */
+ int rx0 = r->x - it->x, rx1 = r->x + r->w - it->x;
+ if (rx0 < it->x0) rx0 = it->x0;
+ if (rx1 > it->x1) rx1 = it->x1;
+ for (int y = y0; y < y1; y++) {
+ int wy = it->y + y;
+ if (wy < r->y || wy >= r->y + r->h) continue;
+ int gy = wy - r->gy;
+ if (gy < 0 || gy >= r->grows * 20) continue;
+ int trow = gy / 20, ty = gy % 20;
+ uint16_t *row = band + (y - by0) * SCREEN_W;
+ int x = rx0;
+ while (x < rx1) {
+ int wx = it->x + x, gx = wx - r->gx;
+ int tcol = gx >= 0 ? gx / 20 : -1, tx = gx >= 0 ? gx % 20 : 0;
+ int n = 20 - tx;
+ if (x + n > rx1) n = rx1 - x;
+ uint16_t id = tcol >= 0 && tcol < r->gcols ? rd16(r->grid + 2 * (trow * r->gcols + tcol)) : 0xFFFF;
+ if (id != 0xFFFF) {
+ Tile t;
+ tile_get(id, &t);
+ if (t.bpp == 0) {
+ uint16_t c = rd16(t.pal);
+ for (int k = 0; k < n; k++) row[x + k] = c;
+ } else {
+ uint16_t pal[16];
+ int nc = t.ncol > 16 ? 16 : t.ncol;
+ for (int k = 0; k < nc; k++) pal[k] = rd16(t.pal + 2 * k);
+ int base = ty * 20 + tx;
+ if (t.bpp == 8)
+ for (int k = 0; k < n; k++) row[x + k] = rd16(t.pal + 2 * t.bits[base + k]);
+ else
+ for (int k = 0; k < n; k++) row[x + k] = pal[px_at(t.bits, base + k, t.bpp)];
+ }
+ }
+ x += n;
+ }
+ }
+}
+
+/* a pseudo-random shake for letter i of a text */
+static int shake_of(uint32_t seed, int i, int axis, int amount) {
+ uint32_t h = seed * 2654435761u ^ (uint32_t)(i * 2 + axis) * 40503u;
+ h ^= h >> 13, h *= 0x5bd1e995u, h ^= h >> 15;
+ return (int)(h % (uint32_t)(2 * amount + 1)) - amount;
+}
+
+static void rast_text(const Item *it, int by0, int by1) {
+ Font f;
+ font_get(it->font, &f);
+ const char *s = pool + it->ref;
+ int x = it->x, y = it->y;
+ for (int i = 0; i < it->sub; i++) {
+ uint8_t ch = (uint8_t)s[i];
+ if (ch == '\n') {
+ x = it->x, y += f.height + 2;
+ continue;
+ }
+ const uint8_t *g = glyph(&f, ch);
+ if (!g) continue;
+ int gw = g[1], gh = g[2], gx = x + (int8_t)g[3], gy = y + (int8_t)g[4];
+ if (it->a) gx += shake_of(it->seed, i, 0, it->a), gy += shake_of(it->seed, i, 1, it->a);
+ x += g[0] + it->b;
+ if (gy >= by1 || gy + gh <= by0) continue;
+ const uint8_t *bits = f.bits + rd16(g + 6);
+ int stride = (gw + 7) >> 3;
+ for (int r = 0; r < gh; r++) {
+ int yy = gy + r;
+ if (yy < by0 || yy >= by1 || yy < it->y0 || yy >= it->y1) continue;
+ uint16_t *row = band + (yy - by0) * SCREEN_W;
+ const uint8_t *b = bits + r * stride;
+ for (int c = 0; c < gw; c++)
+ if (b[c >> 3] & (0x80 >> (c & 7))) {
+ int xx = gx + c;
+ if (xx >= it->cx0 && xx < it->cx1 && xx >= 0 && xx < SCREEN_W) row[xx] = it->color;
+ }
+ }
+ }
+}
+
+static void rast_line(const Item *it, int by0, int by1) {
+ int x0 = it->x, y0 = it->y, x1 = it->a, y1 = it->b;
+ int dx = x1 > x0 ? x1 - x0 : x0 - x1, dy = y1 > y0 ? y0 - y1 : y1 - y0;
+ int sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1, err = dx + dy;
+ for (;;) {
+ if (y0 >= by0 && y0 < by1 && x0 >= it->x0 && x0 < it->x1 && y0 >= it->y0 && y0 < it->y1) band[(y0 - by0) * SCREEN_W + x0] = it->color;
+ if (x0 == x1 && y0 == y1) break;
+ int e2 = 2 * err;
+ if (e2 >= dy) err += dy, x0 += sx;
+ if (e2 <= dx) err += dx, y0 += sy;
+ }
+}
+
+static void rast_circle(const Item *it, int by0, int by1) {
+ int y0 = it->y0 > by0 ? it->y0 : by0, y1 = it->y1 < by1 ? it->y1 : by1;
+ int r = it->a;
+ uint32_t a = a32(it->alpha);
+ for (int y = y0; y < y1; y++) {
+ int dy = y - it->y, w = 0;
+ while ((w + 1) * (w + 1) + dy * dy <= r * r + r) w++;
+ if (dy * dy > r * r + r) continue;
+ int xa = it->x - w, xb = it->x + w + 1;
+ if (xa < it->x0) xa = it->x0;
+ if (xb > it->x1) xb = it->x1;
+ uint16_t *row = band + (y - by0) * SCREEN_W;
+ for (int x = xa; x < xb; x++) row[x] = a >= 32 ? it->color : blend(row[x], it->color, a);
+ }
+}
+
+void gfx_end(void) {
+ gfx_dropped = dropped_now;
+ if (!band) return;
+ for (int by0 = 0; by0 < SCREEN_H; by0 += GFX_BAND) {
+ int by1 = by0 + GFX_BAND;
+ memset(band, 0, sizeof(uint16_t) * SCREEN_W * GFX_BAND);
+ for (int i = 0; i < nitems; i++) {
+ const Item *it = &items[i];
+ if (it->y1 <= by0 || it->y0 >= by1) continue;
+ switch (it->kind) {
+ case I_RECT: rast_rect(it, by0, by1); break;
+ case I_SPRITE: rast_sprite(it, by0, by1); break;
+ case I_SPRITE_EX: rast_sprite_ex(it, by0, by1); break;
+ case I_TILES: rast_tiles(it, by0, by1); break;
+ case I_TEXT: rast_text(it, by0, by1); break;
+ case I_LINE: rast_line(it, by0, by1); break;
+ case I_CIRCLE: rast_circle(it, by0, by1); break;
+ }
+ }
+ plat_push(0, by0, SCREEN_W, GFX_BAND, band);
+ }
+}
diff --git a/games/undertale/src/gfx.h b/games/undertale/src/gfx.h
new file mode 100644
index 00000000..6ab55d10
--- /dev/null
+++ b/games/undertale/src/gfx.h
@@ -0,0 +1,61 @@
+/* Undertale: drawing.
+ *
+ * A frame is a draw list, rasterised band by band (the calculator has no
+ * frame buffer) and pushed to the screen. Commands are in screen pixels and
+ * painted in the order given. The game draws at the original's 320 x 240,
+ * the calculator's own size: one of the game's pixels is one of the screen's. */
+#ifndef UT_GFX_H
+#define UT_GFX_H
+#include <stdbool.h>
+#include <stdint.h>
+#include "plat.h"
+
+static inline uint16_t rgb565(uint32_t rgb) { /* 0xRRGGBB */
+ return (uint16_t)(((rgb >> 8) & 0xF800) | ((rgb >> 5) & 0x07E0) | ((rgb >> 3) & 0x001F));
+}
+#define C_BLACK 0x0000
+#define C_WHITE 0xFFFF
+#define C_RED 0xF800
+#define C_YELLOW 0xFFE0
+
+enum { GFX_FLIPX = 1, GFX_FLIPY = 2 };
+
+#define GFX_BAND 16 /* screen rows rasterised at a time */
+#define GFX_MAX_ITEMS 400 /* commands in a frame (more are dropped) */
+#define GFX_TEXT_POOL 1536 /* bytes of text in a frame */
+
+/* the band: SCREEN_W * GFX_BAND pixels, the caller's (main's stack on the calculator) */
+void gfx_set_band_memory(uint16_t *px);
+void gfx_begin(void);
+void gfx_end(void);
+/* later commands draw only inside this screen rectangle (gfx_clip_all(): all of it) */
+void gfx_clip(int x, int y, int w, int h);
+void gfx_clip_all(void);
+
+void gfx_rect(int x, int y, int w, int h, uint16_t color, uint8_t alpha); /* alpha 0 (none) to 255 */
+void gfx_frame_rect(int x, int y, int w, int h, int t, uint16_t color); /* an outline t pixels thick */
+/* frame i of sprite s (SPR_* in data.h), its origin at (x, y); alpha 255 opaque */
+void gfx_sprite(uint16_t s, int i, int x, int y, uint8_t flags, uint8_t alpha);
+/* the same, every opaque pixel in one colour (a flash, a silhouette) */
+void gfx_sprite_color(uint16_t s, int i, int x, int y, uint8_t flags, uint16_t color, uint8_t alpha);
+/* the same, scaled (fixed point 8.8, 256 = 1) around its origin, and turned by angle (0-255 for a turn) */
+void gfx_sprite_ex(uint16_t s, int i, int x, int y, int scale_x, int scale_y, int angle, uint16_t color, uint8_t alpha);
+/* the room's tiles (world.c gives them), its world point (wx, wy) at the screen's top-left */
+void gfx_tiles(int wx, int wy);
+/* text in a font (FONT_* in data.h), its top-left at (x, y); returns its width. '\n' starts a line */
+int gfx_text(int font, int x, int y, const char *s, uint16_t color, uint8_t alpha);
+/* the same, each letter shaken by up to `shake` pixels (the game's shaking text), seeded */
+int gfx_text_ex(int font, int x, int y, const char *s, int n, uint16_t color, int shake, uint32_t seed, int spacing);
+int gfx_text_width(int font, const char *s, int n);
+int font_height(int font);
+/* a line one pixel wide */
+void gfx_line(int x0, int y0, int x1, int y1, uint16_t color);
+/* sine and cosine of a in 1/256 turns, in 1/1024 */
+int gfx_sin(int a);
+int gfx_cos(int a);
+/* a solid circle */
+void gfx_circle(int cx, int cy, int r, uint16_t color, uint8_t alpha);
+
+/* how many commands the last frame dropped */
+extern int gfx_dropped;
+#endif
diff --git a/games/undertale/src/items.c b/games/undertale/src/items.c
new file mode 100644
index 00000000..d04be764
--- /dev/null
+++ b/games/undertale/src/items.c
@@ -0,0 +1,98 @@
+/* Items: what they are and what using one does (items.h). Their texts are the game's. */
+#include <stdio.h>
+#include <string.h>
+#include "game.h"
+#include "items.h"
+
+static const ItemInfo items[ITEM_COUNT] = {
+ [ITEM_NONE] = {"", "", IT_SPECIAL, 0, 0, 0, "", "", 0},
+ [ITEM_MONSTER_CANDY] = {"Monster Candy", "MnstrCndy", IT_FOOD, 10, 0, 0, "Has a distinct,\n non-licorice flavor.",
+ "* You ate the Monster Candy.\n* Very un-licorice-like.", 25},
+ [ITEM_STICK] = {"Stick", "Stick", IT_WEAPON, 0, 0, 0, "Its bark is worse than\n its bite.",
+ "* You threw the stick away.\n* Then picked it back up.", 150},
+ [ITEM_BANDAGE] = {"Bandage", "Bandage", IT_ARMOR, 10, 0, 0, "It has already been used\n several times.",
+ "* You re-applied the bandage.\n* Still kind of gooey.", 150},
+ [ITEM_SPIDER_DONUT] = {"Spider Donut", "SpidrDont", IT_FOOD, 12, 0, 0, "A donut made with Spider\n Cider in the batter.",
+ "* You ate the Spider Donut.", 30},
+ [ITEM_SPIDER_CIDER] = {"Spider Cider", "SpidrCidr", IT_FOOD, 24, 0, 0, "Made with whole spiders,\n not just the juice.",
+ "* You drank the Spider Cider.", 60},
+ [ITEM_BUTTERSCOTCH_PIE] = {"Butterscotch Pie", "ButtsPie", IT_FOOD, 999, 0, 0, "Butterscotch-cinnamon\n pie, one slice.",
+ "* You ate the Butterscotch\n Pie.", 180},
+ [ITEM_SNAIL_PIE] = {"Snail Pie", "SnailPie", IT_FOOD, 998, 0, 0, "An acquired taste.",
+ "* You ate the Snail Pie.\n* Your HP was maxed. Almost.", 350},
+ [ITEM_FADED_RIBBON] = {"Faded Ribbon", "Ribbon", IT_ARMOR, 0, 0, 3, "If you're cuter, monsters\n won't hit you as hard.", "", 0},
+ [ITEM_TOY_KNIFE] = {"Toy Knife", "Toy Knife", IT_WEAPON, 0, 3, 0, "Made of plastic.\n* A rarity nowadays.", "", 100},
+};
+
+const ItemInfo *item_info(int id) { return &items[id >= 0 && id < ITEM_COUNT ? id : 0]; }
+
+void item_info_text(int id, char *out, int cap) {
+ const ItemInfo *it = item_info(id);
+ switch (it->type) {
+ case IT_WEAPON: snprintf(out, (size_t)cap, "* \"%s\" - Weapon AT %d\n* %s", it->name, it->at, it->info); break;
+ case IT_ARMOR:
+ if (id == ITEM_BANDAGE) snprintf(out, (size_t)cap, "* \"%s\" - Heals %d HP\n* %s", it->name, it->heal, it->info);
+ else snprintf(out, (size_t)cap, "* \"%s\" - Armor DF %d\n* %s", it->name, it->df, it->info);
+ break;
+ default:
+ if (it->heal >= 998) snprintf(out, (size_t)cap, "* \"%s\" - Heals ALL HP\n* %s", it->name, it->info);
+ else snprintf(out, (size_t)cap, "* \"%s\" - Heals %d HP\n* %s", it->name, it->heal, it->info);
+ break;
+ }
+}
+
+/* heals and says so: "You recovered N HP!" or "Your HP was maxed out." */
+static int heal(int n, char *out, int cap) {
+ int before = sv.hp;
+ sv.hp = (int16_t)min_i(sv.maxhp, sv.hp + n);
+ if (sv.hp >= sv.maxhp) return snprintf(out, (size_t)cap, "\n* Your HP was maxed out.");
+ return snprintf(out, (size_t)cap, "\n* You recovered %d HP!", sv.hp - before);
+}
+
+void item_use(int slot, char *out, int cap, int in_battle) {
+ int id = sv.items[slot];
+ const ItemInfo *it = item_info(id);
+ out[0] = 0;
+ switch (it->type) {
+ case IT_WEAPON: {
+ if (id == ITEM_STICK) {
+ snprintf(out, (size_t)cap, "%s", it->use);
+ return;
+ }
+ int old = sv.weapon;
+ sv.weapon = (uint8_t)id;
+ sv.items[slot] = (uint8_t)(old == ITEM_STICK ? 0 : old);
+ if (!sv.items[slot]) item_remove_at(slot);
+ snprintf(out, (size_t)cap, "* You equipped the %s.", it->name);
+ return;
+ }
+ case IT_ARMOR:
+ if (id == ITEM_BANDAGE && sv.armor != ITEM_BANDAGE) {
+ int n = snprintf(out, (size_t)cap, "%s", it->use);
+ item_remove_at(slot);
+ heal(it->heal, out + n, cap - n);
+ return;
+ } else {
+ int old = sv.armor;
+ sv.armor = (uint8_t)id;
+ sv.items[slot] = (uint8_t)old;
+ if (!old) item_remove_at(slot);
+ snprintf(out, (size_t)cap, "* You equipped the %s.", it->name);
+ return;
+ }
+ default: {
+ int n = snprintf(out, (size_t)cap, "%s", it->use);
+ item_remove_at(slot);
+ if (it->heal >= 999) {
+ sv.hp = sv.maxhp;
+ snprintf(out + n, (size_t)(cap - n), "\n* Your HP was maxed out.");
+ } else if (it->heal == 998) {
+ if (sv.hp < sv.maxhp - 1) sv.hp = (int16_t)(sv.maxhp - 1);
+ } else {
+ heal(it->heal, out + n, cap - n);
+ }
+ (void)in_battle;
+ return;
+ }
+ }
+}
diff --git a/games/undertale/src/items.h b/games/undertale/src/items.h
new file mode 100644
index 00000000..701691da
--- /dev/null
+++ b/games/undertale/src/items.h
@@ -0,0 +1,35 @@
+/* Undertale: items (the game's ids are kept where it has them, for the record). */
+#ifndef UT_ITEMS_H
+#define UT_ITEMS_H
+#include <stdint.h>
+
+enum {
+ ITEM_NONE,
+ ITEM_MONSTER_CANDY,
+ ITEM_STICK,
+ ITEM_BANDAGE,
+ ITEM_SPIDER_DONUT,
+ ITEM_SPIDER_CIDER,
+ ITEM_BUTTERSCOTCH_PIE,
+ ITEM_SNAIL_PIE,
+ ITEM_FADED_RIBBON,
+ ITEM_TOY_KNIFE,
+ ITEM_COUNT
+};
+enum { IT_FOOD, IT_WEAPON, IT_ARMOR, IT_SPECIAL };
+
+typedef struct {
+ const char *name; /* in the menu */
+ const char *short_name; /* in battle, 9 letters at most */
+ uint8_t type;
+ int16_t heal; /* HP, 999 all of it */
+ uint8_t at, df;
+ const char *info; /* what Info says after its name */
+ const char *use; /* what eating it says (before the HP) */
+ uint16_t sell;
+} ItemInfo;
+const ItemInfo *item_info(int id);
+/* uses the item in slot (the inventory's): fills `out` with what to say; in battle or not */
+void item_use(int slot, char *out, int cap, int in_battle);
+void item_info_text(int id, char *out, int cap);
+#endif
diff --git a/games/undertale/src/lzma/7zTypes.h b/games/undertale/src/lzma/7zTypes.h
new file mode 100644
index 00000000..4977cdaa
--- /dev/null
+++ b/games/undertale/src/lzma/7zTypes.h
@@ -0,0 +1,374 @@
+/* 7zTypes.h -- Basic types
+2017-07-17 : Igor Pavlov : Public domain */
+
+#ifndef __7Z_TYPES_H
+#define __7Z_TYPES_H
+
+#ifdef _WIN32
+/* #include <windows.h> */
+#endif
+
+#include <stddef.h>
+
+#ifndef EXTERN_C_BEGIN
+#ifdef __cplusplus
+#define EXTERN_C_BEGIN extern "C" {
+#define EXTERN_C_END }
+#else
+#define EXTERN_C_BEGIN
+#define EXTERN_C_END
+#endif
+#endif
+
+EXTERN_C_BEGIN
+
+#define SZ_OK 0
+
+#define SZ_ERROR_DATA 1
+#define SZ_ERROR_MEM 2
+#define SZ_ERROR_CRC 3
+#define SZ_ERROR_UNSUPPORTED 4
+#define SZ_ERROR_PARAM 5
+#define SZ_ERROR_INPUT_EOF 6
+#define SZ_ERROR_OUTPUT_EOF 7
+#define SZ_ERROR_READ 8
+#define SZ_ERROR_WRITE 9
+#define SZ_ERROR_PROGRESS 10
+#define SZ_ERROR_FAIL 11
+#define SZ_ERROR_THREAD 12
+
+#define SZ_ERROR_ARCHIVE 16
+#define SZ_ERROR_NO_ARCHIVE 17
+
+typedef int SRes;
+
+
+#ifdef _WIN32
+
+/* typedef DWORD WRes; */
+typedef unsigned WRes;
+#define MY_SRes_HRESULT_FROM_WRes(x) HRESULT_FROM_WIN32(x)
+
+#else
+
+typedef int WRes;
+#define MY__FACILITY_WIN32 7
+#define MY__FACILITY__WRes MY__FACILITY_WIN32
+#define MY_SRes_HRESULT_FROM_WRes(x) ((HRESULT)(x) <= 0 ? ((HRESULT)(x)) : ((HRESULT) (((x) & 0x0000FFFF) | (MY__FACILITY__WRes << 16) | 0x80000000)))
+
+#endif
+
+
+#ifndef RINOK
+#define RINOK(x) { int __result__ = (x); if (__result__ != 0) return __result__; }
+#endif
+
+typedef unsigned char Byte;
+typedef short Int16;
+typedef unsigned short UInt16;
+
+#ifdef _LZMA_UINT32_IS_ULONG
+typedef long Int32;
+typedef unsigned long UInt32;
+#else
+typedef int Int32;
+typedef unsigned int UInt32;
+#endif
+
+#ifdef _SZ_NO_INT_64
+
+/* define _SZ_NO_INT_64, if your compiler doesn't support 64-bit integers.
+ NOTES: Some code will work incorrectly in that case! */
+
+typedef long Int64;
+typedef unsigned long UInt64;
+
+#else
+
+#if defined(_MSC_VER) || defined(__BORLANDC__)
+typedef __int64 Int64;
+typedef unsigned __int64 UInt64;
+#define UINT64_CONST(n) n
+#else
+typedef long long int Int64;
+typedef unsigned long long int UInt64;
+#define UINT64_CONST(n) n ## ULL
+#endif
+
+#endif
+
+#ifdef _LZMA_NO_SYSTEM_SIZE_T
+typedef UInt32 SizeT;
+#else
+typedef size_t SizeT;
+#endif
+
+typedef int Bool;
+#define True 1
+#define False 0
+
+
+#ifdef _WIN32
+#define MY_STD_CALL __stdcall
+#else
+#define MY_STD_CALL
+#endif
+
+#ifdef _MSC_VER
+
+#if _MSC_VER >= 1300
+#define MY_NO_INLINE __declspec(noinline)
+#else
+#define MY_NO_INLINE
+#endif
+
+#define MY_FORCE_INLINE __forceinline
+
+#define MY_CDECL __cdecl
+#define MY_FAST_CALL __fastcall
+
+#else
+
+#define MY_NO_INLINE
+#define MY_FORCE_INLINE
+#define MY_CDECL
+#define MY_FAST_CALL
+
+/* inline keyword : for C++ / C99 */
+
+/* GCC, clang: */
+/*
+#if defined (__GNUC__) && (__GNUC__ >= 4)
+#define MY_FORCE_INLINE __attribute__((always_inline))
+#define MY_NO_INLINE __attribute__((noinline))
+#endif
+*/
+
+#endif
+
+
+/* The following interfaces use first parameter as pointer to structure */
+
+typedef struct IByteIn IByteIn;
+struct IByteIn
+{
+ Byte (*Read)(const IByteIn *p); /* reads one byte, returns 0 in case of EOF or error */
+};
+#define IByteIn_Read(p) (p)->Read(p)
+
+
+typedef struct IByteOut IByteOut;
+struct IByteOut
+{
+ void (*Write)(const IByteOut *p, Byte b);
+};
+#define IByteOut_Write(p, b) (p)->Write(p, b)
+
+
+typedef struct ISeqInStream ISeqInStream;
+struct ISeqInStream
+{
+ SRes (*Read)(const ISeqInStream *p, void *buf, size_t *size);
+ /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream.
+ (output(*size) < input(*size)) is allowed */
+};
+#define ISeqInStream_Read(p, buf, size) (p)->Read(p, buf, size)
+
+/* it can return SZ_ERROR_INPUT_EOF */
+SRes SeqInStream_Read(const ISeqInStream *stream, void *buf, size_t size);
+SRes SeqInStream_Read2(const ISeqInStream *stream, void *buf, size_t size, SRes errorType);
+SRes SeqInStream_ReadByte(const ISeqInStream *stream, Byte *buf);
+
+
+typedef struct ISeqOutStream ISeqOutStream;
+struct ISeqOutStream
+{
+ size_t (*Write)(const ISeqOutStream *p, const void *buf, size_t size);
+ /* Returns: result - the number of actually written bytes.
+ (result < size) means error */
+};
+#define ISeqOutStream_Write(p, buf, size) (p)->Write(p, buf, size)
+
+typedef enum
+{
+ SZ_SEEK_SET = 0,
+ SZ_SEEK_CUR = 1,
+ SZ_SEEK_END = 2
+} ESzSeek;
+
+
+typedef struct ISeekInStream ISeekInStream;
+struct ISeekInStream
+{
+ SRes (*Read)(const ISeekInStream *p, void *buf, size_t *size); /* same as ISeqInStream::Read */
+ SRes (*Seek)(const ISeekInStream *p, Int64 *pos, ESzSeek origin);
+};
+#define ISeekInStream_Read(p, buf, size) (p)->Read(p, buf, size)
+#define ISeekInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin)
+
+
+typedef struct ILookInStream ILookInStream;
+struct ILookInStream
+{
+ SRes (*Look)(const ILookInStream *p, const void **buf, size_t *size);
+ /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream.
+ (output(*size) > input(*size)) is not allowed
+ (output(*size) < input(*size)) is allowed */
+ SRes (*Skip)(const ILookInStream *p, size_t offset);
+ /* offset must be <= output(*size) of Look */
+
+ SRes (*Read)(const ILookInStream *p, void *buf, size_t *size);
+ /* reads directly (without buffer). It's same as ISeqInStream::Read */
+ SRes (*Seek)(const ILookInStream *p, Int64 *pos, ESzSeek origin);
+};
+
+#define ILookInStream_Look(p, buf, size) (p)->Look(p, buf, size)
+#define ILookInStream_Skip(p, offset) (p)->Skip(p, offset)
+#define ILookInStream_Read(p, buf, size) (p)->Read(p, buf, size)
+#define ILookInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin)
+
+
+SRes LookInStream_LookRead(const ILookInStream *stream, void *buf, size_t *size);
+SRes LookInStream_SeekTo(const ILookInStream *stream, UInt64 offset);
+
+/* reads via ILookInStream::Read */
+SRes LookInStream_Read2(const ILookInStream *stream, void *buf, size_t size, SRes errorType);
+SRes LookInStream_Read(const ILookInStream *stream, void *buf, size_t size);
+
+
+
+typedef struct
+{
+ ILookInStream vt;
+ const ISeekInStream *realStream;
+
+ size_t pos;
+ size_t size; /* it's data size */
+
+ /* the following variables must be set outside */
+ Byte *buf;
+ size_t bufSize;
+} CLookToRead2;
+
+void LookToRead2_CreateVTable(CLookToRead2 *p, int lookahead);
+
+#define LookToRead2_Init(p) { (p)->pos = (p)->size = 0; }
+
+
+typedef struct
+{
+ ISeqInStream vt;
+ const ILookInStream *realStream;
+} CSecToLook;
+
+void SecToLook_CreateVTable(CSecToLook *p);
+
+
+
+typedef struct
+{
+ ISeqInStream vt;
+ const ILookInStream *realStream;
+} CSecToRead;
+
+void SecToRead_CreateVTable(CSecToRead *p);
+
+
+typedef struct ICompressProgress ICompressProgress;
+
+struct ICompressProgress
+{
+ SRes (*Progress)(const ICompressProgress *p, UInt64 inSize, UInt64 outSize);
+ /* Returns: result. (result != SZ_OK) means break.
+ Value (UInt64)(Int64)-1 for size means unknown value. */
+};
+#define ICompressProgress_Progress(p, inSize, outSize) (p)->Progress(p, inSize, outSize)
+
+
+
+typedef struct ISzAlloc ISzAlloc;
+typedef const ISzAlloc * ISzAllocPtr;
+
+struct ISzAlloc
+{
+ void *(*Alloc)(ISzAllocPtr p, size_t size);
+ void (*Free)(ISzAllocPtr p, void *address); /* address can be 0 */
+};
+
+#define ISzAlloc_Alloc(p, size) (p)->Alloc(p, size)
+#define ISzAlloc_Free(p, a) (p)->Free(p, a)
+
+/* deprecated */
+#define IAlloc_Alloc(p, size) ISzAlloc_Alloc(p, size)
+#define IAlloc_Free(p, a) ISzAlloc_Free(p, a)
+
+
+
+
+
+#ifndef MY_offsetof
+ #ifdef offsetof
+ #define MY_offsetof(type, m) offsetof(type, m)
+ /*
+ #define MY_offsetof(type, m) FIELD_OFFSET(type, m)
+ */
+ #else
+ #define MY_offsetof(type, m) ((size_t)&(((type *)0)->m))
+ #endif
+#endif
+
+
+
+#ifndef MY_container_of
+
+/*
+#define MY_container_of(ptr, type, m) container_of(ptr, type, m)
+#define MY_container_of(ptr, type, m) CONTAINING_RECORD(ptr, type, m)
+#define MY_container_of(ptr, type, m) ((type *)((char *)(ptr) - offsetof(type, m)))
+#define MY_container_of(ptr, type, m) (&((type *)0)->m == (ptr), ((type *)(((char *)(ptr)) - MY_offsetof(type, m))))
+*/
+
+/*
+ GCC shows warning: "perhaps the 'offsetof' macro was used incorrectly"
+ GCC 3.4.4 : classes with constructor
+ GCC 4.8.1 : classes with non-public variable members"
+*/
+
+#define MY_container_of(ptr, type, m) ((type *)((char *)(1 ? (ptr) : &((type *)0)->m) - MY_offsetof(type, m)))
+
+
+#endif
+
+#define CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ((type *)(ptr))
+
+/*
+#define CONTAINER_FROM_VTBL(ptr, type, m) CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m)
+*/
+#define CONTAINER_FROM_VTBL(ptr, type, m) MY_container_of(ptr, type, m)
+
+#define CONTAINER_FROM_VTBL_CLS(ptr, type, m) CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m)
+/*
+#define CONTAINER_FROM_VTBL_CLS(ptr, type, m) CONTAINER_FROM_VTBL(ptr, type, m)
+*/
+
+
+
+#ifdef _WIN32
+
+#define CHAR_PATH_SEPARATOR '\\'
+#define WCHAR_PATH_SEPARATOR L'\\'
+#define STRING_PATH_SEPARATOR "\\"
+#define WSTRING_PATH_SEPARATOR L"\\"
+
+#else
+
+#define CHAR_PATH_SEPARATOR '/'
+#define WCHAR_PATH_SEPARATOR L'/'
+#define STRING_PATH_SEPARATOR "/"
+#define WSTRING_PATH_SEPARATOR L"/"
+
+#endif
+
+EXTERN_C_END
+
+#endif
diff --git a/games/undertale/src/lzma/LzmaDec.c b/games/undertale/src/lzma/LzmaDec.c
new file mode 100644
index 00000000..962b94bb
--- /dev/null
+++ b/games/undertale/src/lzma/LzmaDec.c
@@ -0,0 +1,1185 @@
+/* LzmaDec.c -- LZMA Decoder
+2018-02-28 : Igor Pavlov : Public domain */
+
+#include "Precomp.h"
+
+/* #include "CpuArch.h" */
+#include "LzmaDec.h"
+
+#include <string.h>
+
+#define kNumTopBits 24
+#define kTopValue ((UInt32)1 << kNumTopBits)
+
+#define kNumBitModelTotalBits 11
+#define kBitModelTotal (1 << kNumBitModelTotalBits)
+#define kNumMoveBits 5
+
+#define RC_INIT_SIZE 5
+
+#define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); }
+
+#define IF_BIT_0(p) ttt = *(p); NORMALIZE; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound)
+#define UPDATE_0(p) range = bound; *(p) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits));
+#define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits));
+#define GET_BIT2(p, i, A0, A1) IF_BIT_0(p) \
+ { UPDATE_0(p); i = (i + i); A0; } else \
+ { UPDATE_1(p); i = (i + i) + 1; A1; }
+
+#define TREE_GET_BIT(probs, i) { GET_BIT2(probs + i, i, ;, ;); }
+
+#define REV_BIT(p, i, A0, A1) IF_BIT_0(p + i) \
+ { UPDATE_0(p + i); A0; } else \
+ { UPDATE_1(p + i); A1; }
+#define REV_BIT_VAR( p, i, m) REV_BIT(p, i, i += m; m += m, m += m; i += m; )
+#define REV_BIT_CONST(p, i, m) REV_BIT(p, i, i += m; , i += m * 2; )
+#define REV_BIT_LAST( p, i, m) REV_BIT(p, i, i -= m , ; )
+
+#define TREE_DECODE(probs, limit, i) \
+ { i = 1; do { TREE_GET_BIT(probs, i); } while (i < limit); i -= limit; }
+
+/* #define _LZMA_SIZE_OPT */
+
+#ifdef _LZMA_SIZE_OPT
+#define TREE_6_DECODE(probs, i) TREE_DECODE(probs, (1 << 6), i)
+#else
+#define TREE_6_DECODE(probs, i) \
+ { i = 1; \
+ TREE_GET_BIT(probs, i); \
+ TREE_GET_BIT(probs, i); \
+ TREE_GET_BIT(probs, i); \
+ TREE_GET_BIT(probs, i); \
+ TREE_GET_BIT(probs, i); \
+ TREE_GET_BIT(probs, i); \
+ i -= 0x40; }
+#endif
+
+#define NORMAL_LITER_DEC TREE_GET_BIT(prob, symbol)
+#define MATCHED_LITER_DEC \
+ matchByte += matchByte; \
+ bit = offs; \
+ offs &= matchByte; \
+ probLit = prob + (offs + bit + symbol); \
+ GET_BIT2(probLit, symbol, offs ^= bit; , ;)
+
+
+
+#define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_ERROR; range <<= 8; code = (code << 8) | (*buf++); }
+
+#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound)
+#define UPDATE_0_CHECK range = bound;
+#define UPDATE_1_CHECK range -= bound; code -= bound;
+#define GET_BIT2_CHECK(p, i, A0, A1) IF_BIT_0_CHECK(p) \
+ { UPDATE_0_CHECK; i = (i + i); A0; } else \
+ { UPDATE_1_CHECK; i = (i + i) + 1; A1; }
+#define GET_BIT_CHECK(p, i) GET_BIT2_CHECK(p, i, ; , ;)
+#define TREE_DECODE_CHECK(probs, limit, i) \
+ { i = 1; do { GET_BIT_CHECK(probs + i, i) } while (i < limit); i -= limit; }
+
+
+#define REV_BIT_CHECK(p, i, m) IF_BIT_0_CHECK(p + i) \
+ { UPDATE_0_CHECK; i += m; m += m; } else \
+ { UPDATE_1_CHECK; m += m; i += m; }
+
+
+#define kNumPosBitsMax 4
+#define kNumPosStatesMax (1 << kNumPosBitsMax)
+
+#define kLenNumLowBits 3
+#define kLenNumLowSymbols (1 << kLenNumLowBits)
+#define kLenNumHighBits 8
+#define kLenNumHighSymbols (1 << kLenNumHighBits)
+
+#define LenLow 0
+#define LenHigh (LenLow + 2 * (kNumPosStatesMax << kLenNumLowBits))
+#define kNumLenProbs (LenHigh + kLenNumHighSymbols)
+
+#define LenChoice LenLow
+#define LenChoice2 (LenLow + (1 << kLenNumLowBits))
+
+#define kNumStates 12
+#define kNumStates2 16
+#define kNumLitStates 7
+
+#define kStartPosModelIndex 4
+#define kEndPosModelIndex 14
+#define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
+
+#define kNumPosSlotBits 6
+#define kNumLenToPosStates 4
+
+#define kNumAlignBits 4
+#define kAlignTableSize (1 << kNumAlignBits)
+
+#define kMatchMinLen 2
+#define kMatchSpecLenStart (kMatchMinLen + kLenNumLowSymbols * 2 + kLenNumHighSymbols)
+
+/* External ASM code needs same CLzmaProb array layout. So don't change it. */
+
+/* (probs_1664) is faster and better for code size at some platforms */
+/*
+#ifdef MY_CPU_X86_OR_AMD64
+*/
+#define kStartOffset 1664
+#define GET_PROBS p->probs_1664
+/*
+#define GET_PROBS p->probs + kStartOffset
+#else
+#define kStartOffset 0
+#define GET_PROBS p->probs
+#endif
+*/
+
+#define SpecPos (-kStartOffset)
+#define IsRep0Long (SpecPos + kNumFullDistances)
+#define RepLenCoder (IsRep0Long + (kNumStates2 << kNumPosBitsMax))
+#define LenCoder (RepLenCoder + kNumLenProbs)
+#define IsMatch (LenCoder + kNumLenProbs)
+#define Align (IsMatch + (kNumStates2 << kNumPosBitsMax))
+#define IsRep (Align + kAlignTableSize)
+#define IsRepG0 (IsRep + kNumStates)
+#define IsRepG1 (IsRepG0 + kNumStates)
+#define IsRepG2 (IsRepG1 + kNumStates)
+#define PosSlot (IsRepG2 + kNumStates)
+#define Literal (PosSlot + (kNumLenToPosStates << kNumPosSlotBits))
+#define NUM_BASE_PROBS (Literal + kStartOffset)
+
+#if Align != 0 && kStartOffset != 0
+ #error Stop_Compiling_Bad_LZMA_kAlign
+#endif
+
+#if NUM_BASE_PROBS != 1984
+ #error Stop_Compiling_Bad_LZMA_PROBS
+#endif
+
+
+#define LZMA_LIT_SIZE 0x300
+
+#define LzmaProps_GetNumProbs(p) (NUM_BASE_PROBS + ((UInt32)LZMA_LIT_SIZE << ((p)->lc + (p)->lp)))
+
+
+#define CALC_POS_STATE(processedPos, pbMask) (((processedPos) & (pbMask)) << 4)
+#define COMBINED_PS_STATE (posState + state)
+#define GET_LEN_STATE (posState)
+
+#define LZMA_DIC_MIN (1 << 12)
+
+/*
+p->remainLen : shows status of LZMA decoder:
+ < kMatchSpecLenStart : normal remain
+ = kMatchSpecLenStart : finished
+ = kMatchSpecLenStart + 1 : need init range coder
+ = kMatchSpecLenStart + 2 : need init range coder and state
+*/
+
+/* ---------- LZMA_DECODE_REAL ---------- */
+/*
+LzmaDec_DecodeReal_3() can be implemented in external ASM file.
+3 - is the code compatibility version of that function for check at link time.
+*/
+
+#define LZMA_DECODE_REAL LzmaDec_DecodeReal_3
+
+/*
+LZMA_DECODE_REAL()
+In:
+ RangeCoder is normalized
+ if (p->dicPos == limit)
+ {
+ LzmaDec_TryDummy() was called before to exclude LITERAL and MATCH-REP cases.
+ So first symbol can be only MATCH-NON-REP. And if that MATCH-NON-REP symbol
+ is not END_OF_PAYALOAD_MARKER, then function returns error code.
+ }
+
+Processing:
+ first LZMA symbol will be decoded in any case
+ All checks for limits are at the end of main loop,
+ It will decode new LZMA-symbols while (p->buf < bufLimit && dicPos < limit),
+ RangeCoder is still without last normalization when (p->buf < bufLimit) is being checked.
+
+Out:
+ RangeCoder is normalized
+ Result:
+ SZ_OK - OK
+ SZ_ERROR_DATA - Error
+ p->remainLen:
+ < kMatchSpecLenStart : normal remain
+ = kMatchSpecLenStart : finished
+*/
+
+
+#ifdef _LZMA_DEC_OPT
+
+int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit);
+
+#else
+
+static
+int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit)
+{
+ CLzmaProb *probs = GET_PROBS;
+ unsigned state = (unsigned)p->state;
+ UInt32 rep0 = p->reps[0], rep1 = p->reps[1], rep2 = p->reps[2], rep3 = p->reps[3];
+ unsigned pbMask = ((unsigned)1 << (p->prop.pb)) - 1;
+ unsigned lc = p->prop.lc;
+ unsigned lpMask = ((unsigned)0x100 << p->prop.lp) - ((unsigned)0x100 >> lc);
+
+ Byte *dic = p->dic;
+ SizeT dicBufSize = p->dicBufSize;
+ SizeT dicPos = p->dicPos;
+
+ UInt32 processedPos = p->processedPos;
+ UInt32 checkDicSize = p->checkDicSize;
+ unsigned len = 0;
+
+ const Byte *buf = p->buf;
+ UInt32 range = p->range;
+ UInt32 code = p->code;
+
+ do
+ {
+ CLzmaProb *prob;
+ UInt32 bound;
+ unsigned ttt;
+ unsigned posState = CALC_POS_STATE(processedPos, pbMask);
+
+ prob = probs + IsMatch + COMBINED_PS_STATE;
+ IF_BIT_0(prob)
+ {
+ unsigned symbol;
+ UPDATE_0(prob);
+ prob = probs + Literal;
+ if (processedPos != 0 || checkDicSize != 0)
+ prob += (UInt32)3 * ((((processedPos << 8) + dic[(dicPos == 0 ? dicBufSize : dicPos) - 1]) & lpMask) << lc);
+ processedPos++;
+
+ if (state < kNumLitStates)
+ {
+ state -= (state < 4) ? state : 3;
+ symbol = 1;
+ #ifdef _LZMA_SIZE_OPT
+ do { NORMAL_LITER_DEC } while (symbol < 0x100);
+ #else
+ NORMAL_LITER_DEC
+ NORMAL_LITER_DEC
+ NORMAL_LITER_DEC
+ NORMAL_LITER_DEC
+ NORMAL_LITER_DEC
+ NORMAL_LITER_DEC
+ NORMAL_LITER_DEC
+ NORMAL_LITER_DEC
+ #endif
+ }
+ else
+ {
+ unsigned matchByte = dic[dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0)];
+ unsigned offs = 0x100;
+ state -= (state < 10) ? 3 : 6;
+ symbol = 1;
+ #ifdef _LZMA_SIZE_OPT
+ do
+ {
+ unsigned bit;
+ CLzmaProb *probLit;
+ MATCHED_LITER_DEC
+ }
+ while (symbol < 0x100);
+ #else
+ {
+ unsigned bit;
+ CLzmaProb *probLit;
+ MATCHED_LITER_DEC
+ MATCHED_LITER_DEC
+ MATCHED_LITER_DEC
+ MATCHED_LITER_DEC
+ MATCHED_LITER_DEC
+ MATCHED_LITER_DEC
+ MATCHED_LITER_DEC
+ MATCHED_LITER_DEC
+ }
+ #endif
+ }
+
+ dic[dicPos++] = (Byte)symbol;
+ continue;
+ }
+
+ {
+ UPDATE_1(prob);
+ prob = probs + IsRep + state;
+ IF_BIT_0(prob)
+ {
+ UPDATE_0(prob);
+ state += kNumStates;
+ prob = probs + LenCoder;
+ }
+ else
+ {
+ UPDATE_1(prob);
+ /*
+ // that case was checked before with kBadRepCode
+ if (checkDicSize == 0 && processedPos == 0)
+ return SZ_ERROR_DATA;
+ */
+ prob = probs + IsRepG0 + state;
+ IF_BIT_0(prob)
+ {
+ UPDATE_0(prob);
+ prob = probs + IsRep0Long + COMBINED_PS_STATE;
+ IF_BIT_0(prob)
+ {
+ UPDATE_0(prob);
+ dic[dicPos] = dic[dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0)];
+ dicPos++;
+ processedPos++;
+ state = state < kNumLitStates ? 9 : 11;
+ continue;
+ }
+ UPDATE_1(prob);
+ }
+ else
+ {
+ UInt32 distance;
+ UPDATE_1(prob);
+ prob = probs + IsRepG1 + state;
+ IF_BIT_0(prob)
+ {
+ UPDATE_0(prob);
+ distance = rep1;
+ }
+ else
+ {
+ UPDATE_1(prob);
+ prob = probs + IsRepG2 + state;
+ IF_BIT_0(prob)
+ {
+ UPDATE_0(prob);
+ distance = rep2;
+ }
+ else
+ {
+ UPDATE_1(prob);
+ distance = rep3;
+ rep3 = rep2;
+ }
+ rep2 = rep1;
+ }
+ rep1 = rep0;
+ rep0 = distance;
+ }
+ state = state < kNumLitStates ? 8 : 11;
+ prob = probs + RepLenCoder;
+ }
+
+ #ifdef _LZMA_SIZE_OPT
+ {
+ unsigned lim, offset;
+ CLzmaProb *probLen = prob + LenChoice;
+ IF_BIT_0(probLen)
+ {
+ UPDATE_0(probLen);
+ probLen = prob + LenLow + GET_LEN_STATE;
+ offset = 0;
+ lim = (1 << kLenNumLowBits);
+ }
+ else
+ {
+ UPDATE_1(probLen);
+ probLen = prob + LenChoice2;
+ IF_BIT_0(probLen)
+ {
+ UPDATE_0(probLen);
+ probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits);
+ offset = kLenNumLowSymbols;
+ lim = (1 << kLenNumLowBits);
+ }
+ else
+ {
+ UPDATE_1(probLen);
+ probLen = prob + LenHigh;
+ offset = kLenNumLowSymbols * 2;
+ lim = (1 << kLenNumHighBits);
+ }
+ }
+ TREE_DECODE(probLen, lim, len);
+ len += offset;
+ }
+ #else
+ {
+ CLzmaProb *probLen = prob + LenChoice;
+ IF_BIT_0(probLen)
+ {
+ UPDATE_0(probLen);
+ probLen = prob + LenLow + GET_LEN_STATE;
+ len = 1;
+ TREE_GET_BIT(probLen, len);
+ TREE_GET_BIT(probLen, len);
+ TREE_GET_BIT(probLen, len);
+ len -= 8;
+ }
+ else
+ {
+ UPDATE_1(probLen);
+ probLen = prob + LenChoice2;
+ IF_BIT_0(probLen)
+ {
+ UPDATE_0(probLen);
+ probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits);
+ len = 1;
+ TREE_GET_BIT(probLen, len);
+ TREE_GET_BIT(probLen, len);
+ TREE_GET_BIT(probLen, len);
+ }
+ else
+ {
+ UPDATE_1(probLen);
+ probLen = prob + LenHigh;
+ TREE_DECODE(probLen, (1 << kLenNumHighBits), len);
+ len += kLenNumLowSymbols * 2;
+ }
+ }
+ }
+ #endif
+
+ if (state >= kNumStates)
+ {
+ UInt32 distance;
+ prob = probs + PosSlot +
+ ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits);
+ TREE_6_DECODE(prob, distance);
+ if (distance >= kStartPosModelIndex)
+ {
+ unsigned posSlot = (unsigned)distance;
+ unsigned numDirectBits = (unsigned)(((distance >> 1) - 1));
+ distance = (2 | (distance & 1));
+ if (posSlot < kEndPosModelIndex)
+ {
+ distance <<= numDirectBits;
+ prob = probs + SpecPos;
+ {
+ UInt32 m = 1;
+ distance++;
+ do
+ {
+ REV_BIT_VAR(prob, distance, m);
+ }
+ while (--numDirectBits);
+ distance -= m;
+ }
+ }
+ else
+ {
+ numDirectBits -= kNumAlignBits;
+ do
+ {
+ NORMALIZE
+ range >>= 1;
+
+ {
+ UInt32 t;
+ code -= range;
+ t = (0 - ((UInt32)code >> 31)); /* (UInt32)((Int32)code >> 31) */
+ distance = (distance << 1) + (t + 1);
+ code += range & t;
+ }
+ /*
+ distance <<= 1;
+ if (code >= range)
+ {
+ code -= range;
+ distance |= 1;
+ }
+ */
+ }
+ while (--numDirectBits);
+ prob = probs + Align;
+ distance <<= kNumAlignBits;
+ {
+ unsigned i = 1;
+ REV_BIT_CONST(prob, i, 1);
+ REV_BIT_CONST(prob, i, 2);
+ REV_BIT_CONST(prob, i, 4);
+ REV_BIT_LAST (prob, i, 8);
+ distance |= i;
+ }
+ if (distance == (UInt32)0xFFFFFFFF)
+ {
+ len = kMatchSpecLenStart;
+ state -= kNumStates;
+ break;
+ }
+ }
+ }
+
+ rep3 = rep2;
+ rep2 = rep1;
+ rep1 = rep0;
+ rep0 = distance + 1;
+ state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3;
+ if (distance >= (checkDicSize == 0 ? processedPos: checkDicSize))
+ {
+ p->dicPos = dicPos;
+ return SZ_ERROR_DATA;
+ }
+ }
+
+ len += kMatchMinLen;
+
+ {
+ SizeT rem;
+ unsigned curLen;
+ SizeT pos;
+
+ if ((rem = limit - dicPos) == 0)
+ {
+ p->dicPos = dicPos;
+ return SZ_ERROR_DATA;
+ }
+
+ curLen = ((rem < len) ? (unsigned)rem : len);
+ pos = dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0);
+
+ processedPos += curLen;
+
+ len -= curLen;
+ if (curLen <= dicBufSize - pos)
+ {
+ Byte *dest = dic + dicPos;
+ ptrdiff_t src = (ptrdiff_t)pos - (ptrdiff_t)dicPos;
+ const Byte *lim = dest + curLen;
+ dicPos += curLen;
+ do
+ *(dest) = (Byte)*(dest + src);
+ while (++dest != lim);
+ }
+ else
+ {
+ do
+ {
+ dic[dicPos++] = dic[pos];
+ if (++pos == dicBufSize)
+ pos = 0;
+ }
+ while (--curLen != 0);
+ }
+ }
+ }
+ }
+ while (dicPos < limit && buf < bufLimit);
+
+ NORMALIZE;
+
+ p->buf = buf;
+ p->range = range;
+ p->code = code;
+ p->remainLen = len;
+ p->dicPos = dicPos;
+ p->processedPos = processedPos;
+ p->reps[0] = rep0;
+ p->reps[1] = rep1;
+ p->reps[2] = rep2;
+ p->reps[3] = rep3;
+ p->state = state;
+
+ return SZ_OK;
+}
+#endif
+
+static void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit)
+{
+ if (p->remainLen != 0 && p->remainLen < kMatchSpecLenStart)
+ {
+ Byte *dic = p->dic;
+ SizeT dicPos = p->dicPos;
+ SizeT dicBufSize = p->dicBufSize;
+ unsigned len = (unsigned)p->remainLen;
+ SizeT rep0 = p->reps[0]; /* we use SizeT to avoid the BUG of VC14 for AMD64 */
+ SizeT rem = limit - dicPos;
+ if (rem < len)
+ len = (unsigned)(rem);
+
+ if (p->checkDicSize == 0 && p->prop.dicSize - p->processedPos <= len)
+ p->checkDicSize = p->prop.dicSize;
+
+ p->processedPos += len;
+ p->remainLen -= len;
+ while (len != 0)
+ {
+ len--;
+ dic[dicPos] = dic[dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0)];
+ dicPos++;
+ }
+ p->dicPos = dicPos;
+ }
+}
+
+
+#define kRange0 0xFFFFFFFF
+#define kBound0 ((kRange0 >> kNumBitModelTotalBits) << (kNumBitModelTotalBits - 1))
+#define kBadRepCode (kBound0 + (((kRange0 - kBound0) >> kNumBitModelTotalBits) << (kNumBitModelTotalBits - 1)))
+#if kBadRepCode != (0xC0000000 - 0x400)
+ #error Stop_Compiling_Bad_LZMA_Check
+#endif
+
+static int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit)
+{
+ do
+ {
+ SizeT limit2 = limit;
+ if (p->checkDicSize == 0)
+ {
+ UInt32 rem = p->prop.dicSize - p->processedPos;
+ if (limit - p->dicPos > rem)
+ limit2 = p->dicPos + rem;
+
+ if (p->processedPos == 0)
+ if (p->code >= kBadRepCode)
+ return SZ_ERROR_DATA;
+ }
+
+ RINOK(LZMA_DECODE_REAL(p, limit2, bufLimit));
+
+ if (p->checkDicSize == 0 && p->processedPos >= p->prop.dicSize)
+ p->checkDicSize = p->prop.dicSize;
+
+ LzmaDec_WriteRem(p, limit);
+ }
+ while (p->dicPos < limit && p->buf < bufLimit && p->remainLen < kMatchSpecLenStart);
+
+ return 0;
+}
+
+typedef enum
+{
+ DUMMY_ERROR, /* unexpected end of input stream */
+ DUMMY_LIT,
+ DUMMY_MATCH,
+ DUMMY_REP
+} ELzmaDummy;
+
+static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, SizeT inSize)
+{
+ UInt32 range = p->range;
+ UInt32 code = p->code;
+ const Byte *bufLimit = buf + inSize;
+ const CLzmaProb *probs = GET_PROBS;
+ unsigned state = (unsigned)p->state;
+ ELzmaDummy res;
+
+ {
+ const CLzmaProb *prob;
+ UInt32 bound;
+ unsigned ttt;
+ unsigned posState = CALC_POS_STATE(p->processedPos, (1 << p->prop.pb) - 1);
+
+ prob = probs + IsMatch + COMBINED_PS_STATE;
+ IF_BIT_0_CHECK(prob)
+ {
+ UPDATE_0_CHECK
+
+ /* if (bufLimit - buf >= 7) return DUMMY_LIT; */
+
+ prob = probs + Literal;
+ if (p->checkDicSize != 0 || p->processedPos != 0)
+ prob += ((UInt32)LZMA_LIT_SIZE *
+ ((((p->processedPos) & ((1 << (p->prop.lp)) - 1)) << p->prop.lc) +
+ (p->dic[(p->dicPos == 0 ? p->dicBufSize : p->dicPos) - 1] >> (8 - p->prop.lc))));
+
+ if (state < kNumLitStates)
+ {
+ unsigned symbol = 1;
+ do { GET_BIT_CHECK(prob + symbol, symbol) } while (symbol < 0x100);
+ }
+ else
+ {
+ unsigned matchByte = p->dic[p->dicPos - p->reps[0] +
+ (p->dicPos < p->reps[0] ? p->dicBufSize : 0)];
+ unsigned offs = 0x100;
+ unsigned symbol = 1;
+ do
+ {
+ unsigned bit;
+ const CLzmaProb *probLit;
+ matchByte += matchByte;
+ bit = offs;
+ offs &= matchByte;
+ probLit = prob + (offs + bit + symbol);
+ GET_BIT2_CHECK(probLit, symbol, offs ^= bit; , ; )
+ }
+ while (symbol < 0x100);
+ }
+ res = DUMMY_LIT;
+ }
+ else
+ {
+ unsigned len;
+ UPDATE_1_CHECK;
+
+ prob = probs + IsRep + state;
+ IF_BIT_0_CHECK(prob)
+ {
+ UPDATE_0_CHECK;
+ state = 0;
+ prob = probs + LenCoder;
+ res = DUMMY_MATCH;
+ }
+ else
+ {
+ UPDATE_1_CHECK;
+ res = DUMMY_REP;
+ prob = probs + IsRepG0 + state;
+ IF_BIT_0_CHECK(prob)
+ {
+ UPDATE_0_CHECK;
+ prob = probs + IsRep0Long + COMBINED_PS_STATE;
+ IF_BIT_0_CHECK(prob)
+ {
+ UPDATE_0_CHECK;
+ NORMALIZE_CHECK;
+ return DUMMY_REP;
+ }
+ else
+ {
+ UPDATE_1_CHECK;
+ }
+ }
+ else
+ {
+ UPDATE_1_CHECK;
+ prob = probs + IsRepG1 + state;
+ IF_BIT_0_CHECK(prob)
+ {
+ UPDATE_0_CHECK;
+ }
+ else
+ {
+ UPDATE_1_CHECK;
+ prob = probs + IsRepG2 + state;
+ IF_BIT_0_CHECK(prob)
+ {
+ UPDATE_0_CHECK;
+ }
+ else
+ {
+ UPDATE_1_CHECK;
+ }
+ }
+ }
+ state = kNumStates;
+ prob = probs + RepLenCoder;
+ }
+ {
+ unsigned limit, offset;
+ const CLzmaProb *probLen = prob + LenChoice;
+ IF_BIT_0_CHECK(probLen)
+ {
+ UPDATE_0_CHECK;
+ probLen = prob + LenLow + GET_LEN_STATE;
+ offset = 0;
+ limit = 1 << kLenNumLowBits;
+ }
+ else
+ {
+ UPDATE_1_CHECK;
+ probLen = prob + LenChoice2;
+ IF_BIT_0_CHECK(probLen)
+ {
+ UPDATE_0_CHECK;
+ probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits);
+ offset = kLenNumLowSymbols;
+ limit = 1 << kLenNumLowBits;
+ }
+ else
+ {
+ UPDATE_1_CHECK;
+ probLen = prob + LenHigh;
+ offset = kLenNumLowSymbols * 2;
+ limit = 1 << kLenNumHighBits;
+ }
+ }
+ TREE_DECODE_CHECK(probLen, limit, len);
+ len += offset;
+ }
+
+ if (state < 4)
+ {
+ unsigned posSlot;
+ prob = probs + PosSlot +
+ ((len < kNumLenToPosStates - 1 ? len : kNumLenToPosStates - 1) <<
+ kNumPosSlotBits);
+ TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot);
+ if (posSlot >= kStartPosModelIndex)
+ {
+ unsigned numDirectBits = ((posSlot >> 1) - 1);
+
+ /* if (bufLimit - buf >= 8) return DUMMY_MATCH; */
+
+ if (posSlot < kEndPosModelIndex)
+ {
+ prob = probs + SpecPos + ((2 | (posSlot & 1)) << numDirectBits);
+ }
+ else
+ {
+ numDirectBits -= kNumAlignBits;
+ do
+ {
+ NORMALIZE_CHECK
+ range >>= 1;
+ code -= range & (((code - range) >> 31) - 1);
+ /* if (code >= range) code -= range; */
+ }
+ while (--numDirectBits);
+ prob = probs + Align;
+ numDirectBits = kNumAlignBits;
+ }
+ {
+ unsigned i = 1;
+ unsigned m = 1;
+ do
+ {
+ REV_BIT_CHECK(prob, i, m);
+ }
+ while (--numDirectBits);
+ }
+ }
+ }
+ }
+ }
+ NORMALIZE_CHECK;
+ return res;
+}
+
+
+void LzmaDec_InitDicAndState(CLzmaDec *p, Bool initDic, Bool initState)
+{
+ p->remainLen = kMatchSpecLenStart + 1;
+ p->tempBufSize = 0;
+
+ if (initDic)
+ {
+ p->processedPos = 0;
+ p->checkDicSize = 0;
+ p->remainLen = kMatchSpecLenStart + 2;
+ }
+ if (initState)
+ p->remainLen = kMatchSpecLenStart + 2;
+}
+
+void LzmaDec_Init(CLzmaDec *p)
+{
+ p->dicPos = 0;
+ LzmaDec_InitDicAndState(p, True, True);
+}
+
+
+SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *srcLen,
+ ELzmaFinishMode finishMode, ELzmaStatus *status)
+{
+ SizeT inSize = *srcLen;
+ (*srcLen) = 0;
+
+ *status = LZMA_STATUS_NOT_SPECIFIED;
+
+ if (p->remainLen > kMatchSpecLenStart)
+ {
+ for (; inSize > 0 && p->tempBufSize < RC_INIT_SIZE; (*srcLen)++, inSize--)
+ p->tempBuf[p->tempBufSize++] = *src++;
+ if (p->tempBufSize != 0 && p->tempBuf[0] != 0)
+ return SZ_ERROR_DATA;
+ if (p->tempBufSize < RC_INIT_SIZE)
+ {
+ *status = LZMA_STATUS_NEEDS_MORE_INPUT;
+ return SZ_OK;
+ }
+ p->code =
+ ((UInt32)p->tempBuf[1] << 24)
+ | ((UInt32)p->tempBuf[2] << 16)
+ | ((UInt32)p->tempBuf[3] << 8)
+ | ((UInt32)p->tempBuf[4]);
+ p->range = 0xFFFFFFFF;
+ p->tempBufSize = 0;
+
+ if (p->remainLen > kMatchSpecLenStart + 1)
+ {
+ SizeT numProbs = LzmaProps_GetNumProbs(&p->prop);
+ SizeT i;
+ CLzmaProb *probs = p->probs;
+ for (i = 0; i < numProbs; i++)
+ probs[i] = kBitModelTotal >> 1;
+ p->reps[0] = p->reps[1] = p->reps[2] = p->reps[3] = 1;
+ p->state = 0;
+ }
+
+ p->remainLen = 0;
+ }
+
+ LzmaDec_WriteRem(p, dicLimit);
+
+ while (p->remainLen != kMatchSpecLenStart)
+ {
+ int checkEndMarkNow = 0;
+
+ if (p->dicPos >= dicLimit)
+ {
+ if (p->remainLen == 0 && p->code == 0)
+ {
+ *status = LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK;
+ return SZ_OK;
+ }
+ if (finishMode == LZMA_FINISH_ANY)
+ {
+ *status = LZMA_STATUS_NOT_FINISHED;
+ return SZ_OK;
+ }
+ if (p->remainLen != 0)
+ {
+ *status = LZMA_STATUS_NOT_FINISHED;
+ return SZ_ERROR_DATA;
+ }
+ checkEndMarkNow = 1;
+ }
+
+ if (p->tempBufSize == 0)
+ {
+ SizeT processed;
+ const Byte *bufLimit;
+ if (inSize < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow)
+ {
+ int dummyRes = LzmaDec_TryDummy(p, src, inSize);
+ if (dummyRes == DUMMY_ERROR)
+ {
+ memcpy(p->tempBuf, src, inSize);
+ p->tempBufSize = (unsigned)inSize;
+ (*srcLen) += inSize;
+ *status = LZMA_STATUS_NEEDS_MORE_INPUT;
+ return SZ_OK;
+ }
+ if (checkEndMarkNow && dummyRes != DUMMY_MATCH)
+ {
+ *status = LZMA_STATUS_NOT_FINISHED;
+ return SZ_ERROR_DATA;
+ }
+ bufLimit = src;
+ }
+ else
+ bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX;
+ p->buf = src;
+ if (LzmaDec_DecodeReal2(p, dicLimit, bufLimit) != 0)
+ return SZ_ERROR_DATA;
+ processed = (SizeT)(p->buf - src);
+ (*srcLen) += processed;
+ src += processed;
+ inSize -= processed;
+ }
+ else
+ {
+ unsigned rem = p->tempBufSize, lookAhead = 0;
+ while (rem < LZMA_REQUIRED_INPUT_MAX && lookAhead < inSize)
+ p->tempBuf[rem++] = src[lookAhead++];
+ p->tempBufSize = rem;
+ if (rem < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow)
+ {
+ int dummyRes = LzmaDec_TryDummy(p, p->tempBuf, rem);
+ if (dummyRes == DUMMY_ERROR)
+ {
+ (*srcLen) += lookAhead;
+ *status = LZMA_STATUS_NEEDS_MORE_INPUT;
+ return SZ_OK;
+ }
+ if (checkEndMarkNow && dummyRes != DUMMY_MATCH)
+ {
+ *status = LZMA_STATUS_NOT_FINISHED;
+ return SZ_ERROR_DATA;
+ }
+ }
+ p->buf = p->tempBuf;
+ if (LzmaDec_DecodeReal2(p, dicLimit, p->buf) != 0)
+ return SZ_ERROR_DATA;
+
+ {
+ unsigned kkk = (unsigned)(p->buf - p->tempBuf);
+ if (rem < kkk)
+ return SZ_ERROR_FAIL; /* some internal error */
+ rem -= kkk;
+ if (lookAhead < rem)
+ return SZ_ERROR_FAIL; /* some internal error */
+ lookAhead -= rem;
+ }
+ (*srcLen) += lookAhead;
+ src += lookAhead;
+ inSize -= lookAhead;
+ p->tempBufSize = 0;
+ }
+ }
+
+ if (p->code != 0)
+ return SZ_ERROR_DATA;
+ *status = LZMA_STATUS_FINISHED_WITH_MARK;
+ return SZ_OK;
+}
+
+
+SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status)
+{
+ SizeT outSize = *destLen;
+ SizeT inSize = *srcLen;
+ *srcLen = *destLen = 0;
+ for (;;)
+ {
+ SizeT inSizeCur = inSize, outSizeCur, dicPos;
+ ELzmaFinishMode curFinishMode;
+ SRes res;
+ if (p->dicPos == p->dicBufSize)
+ p->dicPos = 0;
+ dicPos = p->dicPos;
+ if (outSize > p->dicBufSize - dicPos)
+ {
+ outSizeCur = p->dicBufSize;
+ curFinishMode = LZMA_FINISH_ANY;
+ }
+ else
+ {
+ outSizeCur = dicPos + outSize;
+ curFinishMode = finishMode;
+ }
+
+ res = LzmaDec_DecodeToDic(p, outSizeCur, src, &inSizeCur, curFinishMode, status);
+ src += inSizeCur;
+ inSize -= inSizeCur;
+ *srcLen += inSizeCur;
+ outSizeCur = p->dicPos - dicPos;
+ memcpy(dest, p->dic + dicPos, outSizeCur);
+ dest += outSizeCur;
+ outSize -= outSizeCur;
+ *destLen += outSizeCur;
+ if (res != 0)
+ return res;
+ if (outSizeCur == 0 || outSize == 0)
+ return SZ_OK;
+ }
+}
+
+void LzmaDec_FreeProbs(CLzmaDec *p, ISzAllocPtr alloc)
+{
+ ISzAlloc_Free(alloc, p->probs);
+ p->probs = NULL;
+}
+
+static void LzmaDec_FreeDict(CLzmaDec *p, ISzAllocPtr alloc)
+{
+ ISzAlloc_Free(alloc, p->dic);
+ p->dic = NULL;
+}
+
+void LzmaDec_Free(CLzmaDec *p, ISzAllocPtr alloc)
+{
+ LzmaDec_FreeProbs(p, alloc);
+ LzmaDec_FreeDict(p, alloc);
+}
+
+SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size)
+{
+ UInt32 dicSize;
+ Byte d;
+
+ if (size < LZMA_PROPS_SIZE)
+ return SZ_ERROR_UNSUPPORTED;
+ else
+ dicSize = data[1] | ((UInt32)data[2] << 8) | ((UInt32)data[3] << 16) | ((UInt32)data[4] << 24);
+
+ if (dicSize < LZMA_DIC_MIN)
+ dicSize = LZMA_DIC_MIN;
+ p->dicSize = dicSize;
+
+ d = data[0];
+ if (d >= (9 * 5 * 5))
+ return SZ_ERROR_UNSUPPORTED;
+
+ p->lc = (Byte)(d % 9);
+ d /= 9;
+ p->pb = (Byte)(d / 5);
+ p->lp = (Byte)(d % 5);
+
+ return SZ_OK;
+}
+
+static SRes LzmaDec_AllocateProbs2(CLzmaDec *p, const CLzmaProps *propNew, ISzAllocPtr alloc)
+{
+ UInt32 numProbs = LzmaProps_GetNumProbs(propNew);
+ if (!p->probs || numProbs != p->numProbs)
+ {
+ LzmaDec_FreeProbs(p, alloc);
+ p->probs = (CLzmaProb *)ISzAlloc_Alloc(alloc, numProbs * sizeof(CLzmaProb));
+ if (!p->probs)
+ return SZ_ERROR_MEM;
+ p->probs_1664 = p->probs + 1664;
+ p->numProbs = numProbs;
+ }
+ return SZ_OK;
+}
+
+SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc)
+{
+ CLzmaProps propNew;
+ RINOK(LzmaProps_Decode(&propNew, props, propsSize));
+ RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc));
+ p->prop = propNew;
+ return SZ_OK;
+}
+
+SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc)
+{
+ CLzmaProps propNew;
+ SizeT dicBufSize;
+ RINOK(LzmaProps_Decode(&propNew, props, propsSize));
+ RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc));
+
+ {
+ UInt32 dictSize = propNew.dicSize;
+ SizeT mask = ((UInt32)1 << 12) - 1;
+ if (dictSize >= ((UInt32)1 << 30)) mask = ((UInt32)1 << 22) - 1;
+ else if (dictSize >= ((UInt32)1 << 22)) mask = ((UInt32)1 << 20) - 1;;
+ dicBufSize = ((SizeT)dictSize + mask) & ~mask;
+ if (dicBufSize < dictSize)
+ dicBufSize = dictSize;
+ }
+
+ if (!p->dic || dicBufSize != p->dicBufSize)
+ {
+ LzmaDec_FreeDict(p, alloc);
+ p->dic = (Byte *)ISzAlloc_Alloc(alloc, dicBufSize);
+ if (!p->dic)
+ {
+ LzmaDec_FreeProbs(p, alloc);
+ return SZ_ERROR_MEM;
+ }
+ }
+ p->dicBufSize = dicBufSize;
+ p->prop = propNew;
+ return SZ_OK;
+}
+
+SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
+ const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode,
+ ELzmaStatus *status, ISzAllocPtr alloc)
+{
+ CLzmaDec p;
+ SRes res;
+ SizeT outSize = *destLen, inSize = *srcLen;
+ *destLen = *srcLen = 0;
+ *status = LZMA_STATUS_NOT_SPECIFIED;
+ if (inSize < RC_INIT_SIZE)
+ return SZ_ERROR_INPUT_EOF;
+ LzmaDec_Construct(&p);
+ RINOK(LzmaDec_AllocateProbs(&p, propData, propSize, alloc));
+ p.dic = dest;
+ p.dicBufSize = outSize;
+ LzmaDec_Init(&p);
+ *srcLen = inSize;
+ res = LzmaDec_DecodeToDic(&p, outSize, src, srcLen, finishMode, status);
+ *destLen = p.dicPos;
+ if (res == SZ_OK && *status == LZMA_STATUS_NEEDS_MORE_INPUT)
+ res = SZ_ERROR_INPUT_EOF;
+ LzmaDec_FreeProbs(&p, alloc);
+ return res;
+}
diff --git a/games/undertale/src/lzma/LzmaDec.h b/games/undertale/src/lzma/LzmaDec.h
new file mode 100644
index 00000000..28ce60c3
--- /dev/null
+++ b/games/undertale/src/lzma/LzmaDec.h
@@ -0,0 +1,234 @@
+/* LzmaDec.h -- LZMA Decoder
+2018-04-21 : Igor Pavlov : Public domain */
+
+#ifndef __LZMA_DEC_H
+#define __LZMA_DEC_H
+
+#include "7zTypes.h"
+
+EXTERN_C_BEGIN
+
+/* #define _LZMA_PROB32 */
+/* _LZMA_PROB32 can increase the speed on some CPUs,
+ but memory usage for CLzmaDec::probs will be doubled in that case */
+
+typedef
+#ifdef _LZMA_PROB32
+ UInt32
+#else
+ UInt16
+#endif
+ CLzmaProb;
+
+
+/* ---------- LZMA Properties ---------- */
+
+#define LZMA_PROPS_SIZE 5
+
+typedef struct _CLzmaProps
+{
+ Byte lc;
+ Byte lp;
+ Byte pb;
+ Byte _pad_;
+ UInt32 dicSize;
+} CLzmaProps;
+
+/* LzmaProps_Decode - decodes properties
+Returns:
+ SZ_OK
+ SZ_ERROR_UNSUPPORTED - Unsupported properties
+*/
+
+SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size);
+
+
+/* ---------- LZMA Decoder state ---------- */
+
+/* LZMA_REQUIRED_INPUT_MAX = number of required input bytes for worst case.
+ Num bits = log2((2^11 / 31) ^ 22) + 26 < 134 + 26 = 160; */
+
+#define LZMA_REQUIRED_INPUT_MAX 20
+
+typedef struct
+{
+ /* Don't change this structure. ASM code can use it. */
+ CLzmaProps prop;
+ CLzmaProb *probs;
+ CLzmaProb *probs_1664;
+ Byte *dic;
+ SizeT dicBufSize;
+ SizeT dicPos;
+ const Byte *buf;
+ UInt32 range;
+ UInt32 code;
+ UInt32 processedPos;
+ UInt32 checkDicSize;
+ UInt32 reps[4];
+ UInt32 state;
+ UInt32 remainLen;
+
+ UInt32 numProbs;
+ unsigned tempBufSize;
+ Byte tempBuf[LZMA_REQUIRED_INPUT_MAX];
+} CLzmaDec;
+
+#define LzmaDec_Construct(p) { (p)->dic = NULL; (p)->probs = NULL; }
+
+void LzmaDec_Init(CLzmaDec *p);
+
+/* There are two types of LZMA streams:
+ - Stream with end mark. That end mark adds about 6 bytes to compressed size.
+ - Stream without end mark. You must know exact uncompressed size to decompress such stream. */
+
+typedef enum
+{
+ LZMA_FINISH_ANY, /* finish at any point */
+ LZMA_FINISH_END /* block must be finished at the end */
+} ELzmaFinishMode;
+
+/* ELzmaFinishMode has meaning only if the decoding reaches output limit !!!
+
+ You must use LZMA_FINISH_END, when you know that current output buffer
+ covers last bytes of block. In other cases you must use LZMA_FINISH_ANY.
+
+ If LZMA decoder sees end marker before reaching output limit, it returns SZ_OK,
+ and output value of destLen will be less than output buffer size limit.
+ You can check status result also.
+
+ You can use multiple checks to test data integrity after full decompression:
+ 1) Check Result and "status" variable.
+ 2) Check that output(destLen) = uncompressedSize, if you know real uncompressedSize.
+ 3) Check that output(srcLen) = compressedSize, if you know real compressedSize.
+ You must use correct finish mode in that case. */
+
+typedef enum
+{
+ LZMA_STATUS_NOT_SPECIFIED, /* use main error code instead */
+ LZMA_STATUS_FINISHED_WITH_MARK, /* stream was finished with end mark. */
+ LZMA_STATUS_NOT_FINISHED, /* stream was not finished */
+ LZMA_STATUS_NEEDS_MORE_INPUT, /* you must provide more input bytes */
+ LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK /* there is probability that stream was finished without end mark */
+} ELzmaStatus;
+
+/* ELzmaStatus is used only as output value for function call */
+
+
+/* ---------- Interfaces ---------- */
+
+/* There are 3 levels of interfaces:
+ 1) Dictionary Interface
+ 2) Buffer Interface
+ 3) One Call Interface
+ You can select any of these interfaces, but don't mix functions from different
+ groups for same object. */
+
+
+/* There are two variants to allocate state for Dictionary Interface:
+ 1) LzmaDec_Allocate / LzmaDec_Free
+ 2) LzmaDec_AllocateProbs / LzmaDec_FreeProbs
+ You can use variant 2, if you set dictionary buffer manually.
+ For Buffer Interface you must always use variant 1.
+
+LzmaDec_Allocate* can return:
+ SZ_OK
+ SZ_ERROR_MEM - Memory allocation error
+ SZ_ERROR_UNSUPPORTED - Unsupported properties
+*/
+
+SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc);
+void LzmaDec_FreeProbs(CLzmaDec *p, ISzAllocPtr alloc);
+
+SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc);
+void LzmaDec_Free(CLzmaDec *p, ISzAllocPtr alloc);
+
+/* ---------- Dictionary Interface ---------- */
+
+/* You can use it, if you want to eliminate the overhead for data copying from
+ dictionary to some other external buffer.
+ You must work with CLzmaDec variables directly in this interface.
+
+ STEPS:
+ LzmaDec_Construct()
+ LzmaDec_Allocate()
+ for (each new stream)
+ {
+ LzmaDec_Init()
+ while (it needs more decompression)
+ {
+ LzmaDec_DecodeToDic()
+ use data from CLzmaDec::dic and update CLzmaDec::dicPos
+ }
+ }
+ LzmaDec_Free()
+*/
+
+/* LzmaDec_DecodeToDic
+
+ The decoding to internal dictionary buffer (CLzmaDec::dic).
+ You must manually update CLzmaDec::dicPos, if it reaches CLzmaDec::dicBufSize !!!
+
+finishMode:
+ It has meaning only if the decoding reaches output limit (dicLimit).
+ LZMA_FINISH_ANY - Decode just dicLimit bytes.
+ LZMA_FINISH_END - Stream must be finished after dicLimit.
+
+Returns:
+ SZ_OK
+ status:
+ LZMA_STATUS_FINISHED_WITH_MARK
+ LZMA_STATUS_NOT_FINISHED
+ LZMA_STATUS_NEEDS_MORE_INPUT
+ LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
+ SZ_ERROR_DATA - Data error
+*/
+
+SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit,
+ const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
+
+
+/* ---------- Buffer Interface ---------- */
+
+/* It's zlib-like interface.
+ See LzmaDec_DecodeToDic description for information about STEPS and return results,
+ but you must use LzmaDec_DecodeToBuf instead of LzmaDec_DecodeToDic and you don't need
+ to work with CLzmaDec variables manually.
+
+finishMode:
+ It has meaning only if the decoding reaches output limit (*destLen).
+ LZMA_FINISH_ANY - Decode just destLen bytes.
+ LZMA_FINISH_END - Stream must be finished after (*destLen).
+*/
+
+SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen,
+ const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
+
+
+/* ---------- One Call Interface ---------- */
+
+/* LzmaDecode
+
+finishMode:
+ It has meaning only if the decoding reaches output limit (*destLen).
+ LZMA_FINISH_ANY - Decode just destLen bytes.
+ LZMA_FINISH_END - Stream must be finished after (*destLen).
+
+Returns:
+ SZ_OK
+ status:
+ LZMA_STATUS_FINISHED_WITH_MARK
+ LZMA_STATUS_NOT_FINISHED
+ LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
+ SZ_ERROR_DATA - Data error
+ SZ_ERROR_MEM - Memory allocation error
+ SZ_ERROR_UNSUPPORTED - Unsupported properties
+ SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src).
+*/
+
+SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
+ const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode,
+ ELzmaStatus *status, ISzAllocPtr alloc);
+
+EXTERN_C_END
+
+#endif
diff --git a/games/undertale/src/lzma/Precomp.h b/games/undertale/src/lzma/Precomp.h
new file mode 100644
index 00000000..fdaa2452
--- /dev/null
+++ b/games/undertale/src/lzma/Precomp.h
@@ -0,0 +1,5 @@
+/* Precomp.h -- StdAfx
+2013-11-12 : Igor Pavlov : Public domain */
+#ifndef __7Z_PRECOMP_H
+#define __7Z_PRECOMP_H
+#endif
diff --git a/games/undertale/src/main.c b/games/undertale/src/main.c
new file mode 100644
index 00000000..05da21a5
--- /dev/null
+++ b/games/undertale/src/main.c
@@ -0,0 +1,48 @@
+#if defined(__GNUC__) && !defined(__clang__)
+#pragma GCC optimize("Os") /* not drawn every frame: smaller over faster */
+#endif
+/* Undertale for the NumWorks calculator.
+ *
+ * Inspired by Undertale by Toby Fox, not affiliated with him.
+ * Made by Mason Chen as part of NumPlay. */
+#include "game.h"
+#include "gfx.h"
+#include "plat.h"
+#include "res.h"
+
+#ifndef HOST
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Undertale";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+extern const uint8_t ut_data[];
+
+uint32_t perf_frames __attribute__((used)); /* read by tools/emu.py */
+uint32_t perf_updates __attribute__((used));
+
+int main(void) {
+ uint16_t band[SCREEN_W * GFX_BAND]; /* (here: on the stack, out of the RAM apps get) */
+ gfx_set_band_memory(band);
+ plat_begin();
+ ut_bin = ut_data;
+ game_init();
+ uint32_t next = plat_millis() * 3; /* in thirds of a millisecond: 100 per frame, as the game's 30 a second */
+ while (g_running) {
+ /* the game's frames: drawn when caught up (at most 2 updates per drawing) */
+ int n = 0;
+ uint32_t now = plat_millis() * 3;
+ while ((int32_t)(now - next) >= 0 && n < 2 && g_running) {
+ game_frame(plat_keys());
+ perf_updates++;
+ next += 100;
+ n++;
+ }
+ if (!g_running) break;
+ if ((int32_t)(now - next) > 600) next = now; /* far behind: do not rush */
+ if (n) {
+ game_draw();
+ perf_frames++;
+ } else
+ plat_sleep(1);
+ }
+ return plat_end();
+}
+#endif
diff --git a/games/undertale/src/menu.c b/games/undertale/src/menu.c
new file mode 100644
index 00000000..9a1bc484
--- /dev/null
+++ b/games/undertale/src/menu.c
@@ -0,0 +1,8 @@
+/* The menus (menu.h). */
+#include "game.h"
+#include "menu.h"
+void menu_title_open(void) { game_new("Frisk"); }
+void menu_open(void) {}
+void menu_save_open(void) {}
+void menu_update(uint32_t keys, uint32_t pressed) { (void)keys, (void)pressed; }
+void menu_draw(void) {}
diff --git a/games/undertale/src/menu.h b/games/undertale/src/menu.h
new file mode 100644
index 00000000..18fcaa16
--- /dev/null
+++ b/games/undertale/src/menu.h
@@ -0,0 +1,11 @@
+/* Undertale: the menus (title, naming, the C menu, SAVE). */
+#ifndef UT_MENU_H
+#define UT_MENU_H
+#include <stdint.h>
+void menu_title_open(void);
+void menu_open(void);
+void menu_save_open(void);
+void menu_update(uint32_t keys, uint32_t pressed);
+void menu_draw(void);
+void game_new(const char *name);
+#endif
diff --git a/games/undertale/src/plat.h b/games/undertale/src/plat.h
new file mode 100644
index 00000000..615facbf
--- /dev/null
+++ b/games/undertale/src/plat.h
@@ -0,0 +1,40 @@
+/* Undertale: the platform (the calculator, or a computer for tests).
+ *
+ * plat_eadk.c: the calculator's EADK display, keyboard, time and files.
+ * plat_host.c: a frame buffer that tests save as images, scripted keys and
+ * simulated time (tests/play.c). */
+#ifndef UT_PLAT_H
+#define UT_PLAT_H
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#define SCREEN_W 320
+#define SCREEN_H 240
+
+/* keys held now, as bits: the game's Z, X and C are OK, Back and toolbox */
+enum {
+ K_LEFT = 1 << 0, K_RIGHT = 1 << 1, K_UP = 1 << 2, K_DOWN = 1 << 3,
+ K_Z = 1 << 4, /* OK, EXE: confirm */
+ K_X = 1 << 5, /* Back: cancel */
+ K_C = 1 << 6, /* toolbox, shift: the menu */
+ K_HOME = 1 << 7, /* Home, On/Off: save the moment and quit */
+ K_ANY = 1 << 8
+};
+uint32_t plat_keys(void);
+uint32_t plat_millis(void);
+void plat_sleep(uint32_t ms);
+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);
+bool plat_save(const char *name, const void *data, uint32_t len);
+const uint8_t *plat_load(const char *name, uint32_t *len); /* NULL if absent */
+/* a file of len bytes to write in place (the calculator's storage is RAM): plat_reserve gives its
+ * bytes, plat_reserved says they are written; NULL if there is no room */
+uint8_t *plat_reserve(const char *name, uint32_t len);
+void plat_reserved(const char *name, uint32_t len);
+bool plat_remove(const char *name);
+void plat_begin(void);
+int plat_end(void);
+/* an N0110 or N0115 (216 MHz, the N0120 has 550) */
+bool plat_slow(void);
+#endif
diff --git a/games/undertale/src/plat_eadk.c b/games/undertale/src/plat_eadk.c
new file mode 100644
index 00000000..4d67782a
--- /dev/null
+++ b/games/undertale/src/plat_eadk.c
@@ -0,0 +1,42 @@
+/* The calculator: EADK display, keyboard, time and files. */
+#include <eadk.h>
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+#include "plat.h"
+
+#define KEY(k) ((uint64_t)1 << (k))
+
+uint32_t plat_keys(void) {
+ uint64_t k = eadk_keyboard_scan();
+ uint32_t r = 0;
+ if (k & (KEY(eadk_key_left) | KEY(eadk_key_four))) r |= K_LEFT;
+ if (k & (KEY(eadk_key_right) | KEY(eadk_key_six))) r |= K_RIGHT;
+ if (k & (KEY(eadk_key_up) | KEY(eadk_key_eight))) r |= K_UP;
+ if (k & (KEY(eadk_key_down) | KEY(eadk_key_two))) r |= K_DOWN;
+ if (k & (KEY(eadk_key_ok) | KEY(eadk_key_exe) | KEY(eadk_key_five))) r |= K_Z;
+ if (k & (KEY(eadk_key_back) | KEY(eadk_key_backspace))) r |= K_X;
+ if (k & (KEY(eadk_key_toolbox) | KEY(eadk_key_shift) | KEY(eadk_key_var))) r |= K_C;
+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) r |= K_HOME;
+ if (k) r |= K_ANY;
+ return r;
+}
+
+uint32_t plat_millis(void) { return (uint32_t)eadk_timing_millis(); }
+void plat_sleep(uint32_t ms) { eadk_timing_msleep(ms); }
+void plat_push(int x, int y, int w, int h, const uint16_t *px) {
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);
+}
+void plat_fill(int x, int y, int w, int h, uint16_t c) {
+ if (w > 0 && h > 0) eadk_display_push_rect_uniform((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, c);
+}
+bool plat_save(const char *name, const void *data, uint32_t len) { return ef_write(name, data, len); }
+const uint8_t *plat_load(const char *name, uint32_t *len) { return ef_read(name, len); }
+uint8_t *plat_reserve(const char *name, uint32_t len) {
+ uint32_t n;
+ return ef_write(name, NULL, len) ? (uint8_t *)(uintptr_t)ef_read(name, &n) : NULL; /* (the storage is RAM) */
+}
+void plat_reserved(const char *name, uint32_t len) { (void)name, (void)len; }
+bool plat_remove(const char *name) { return ef_remove(name); }
+void plat_begin(void) { np_app_begin(); }
+int plat_end(void) { return np_app_end(); }
+bool plat_slow(void) { return epsilon_slow_model(); }
diff --git a/games/undertale/src/plat_host.c b/games/undertale/src/plat_host.c
new file mode 100644
index 00000000..047ec744
--- /dev/null
+++ b/games/undertale/src/plat_host.c
@@ -0,0 +1,76 @@
+/* A computer: the screen goes to a frame buffer that tests save as images,
+ * keys come from a script, time is simulated. */
+#include <stdio.h>
+#include <stdlib.h>
+#include "plat.h"
+
+uint16_t host_fb[SCREEN_W * SCREEN_H];
+uint32_t host_time; /* ms */
+uint32_t host_keys;
+
+uint32_t plat_keys(void) { return host_keys; }
+uint32_t plat_millis(void) { return host_time; }
+void plat_sleep(uint32_t ms) { host_time += ms; }
+void plat_push(int x, int y, int w, int h, const uint16_t *px) {
+ for (int r = 0; r < h; r++)
+ for (int c = 0; c < w; c++)
+ if ((unsigned)(x + c) < SCREEN_W && (unsigned)(y + r) < SCREEN_H) host_fb[(y + r) * SCREEN_W + x + c] = px[r * w + c];
+}
+void plat_fill(int x, int y, int w, int h, uint16_t c) {
+ for (int r = 0; r < h; r++)
+ for (int k = 0; k < w; k++)
+ if ((unsigned)(x + k) < SCREEN_W && (unsigned)(y + r) < SCREEN_H) host_fb[(y + r) * SCREEN_W + x + k] = c;
+}
+
+static char save_dir[256] = "build/host-saves";
+void host_save_dir(const char *d) { snprintf(save_dir, sizeof save_dir, "%s", d); }
+bool plat_save(const char *name, const void *data, uint32_t len) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s", save_dir, name);
+ FILE *f = fopen(p, "wb");
+ if (!f) return false;
+ bool ok = fwrite(data, 1, len, f) == len;
+ fclose(f);
+ return ok;
+}
+/* (each file read gets its own buffer: callers may hold two at once) */
+static uint8_t loaded[4][1 << 16];
+static int next_load;
+const uint8_t *plat_load(const char *name, uint32_t *len) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s", save_dir, name);
+ FILE *f = fopen(p, "rb");
+ if (!f) return NULL;
+ uint8_t *b = loaded[next_load++ & 3];
+ *len = (uint32_t)fread(b, 1, sizeof loaded[0], f);
+ fclose(f);
+ return b;
+}
+static uint8_t reserved[1 << 16];
+bool host_storage_full; /* tests: no room for any file */
+uint8_t *plat_reserve(const char *name, uint32_t len) {
+ (void)name;
+ return len <= sizeof reserved && !host_storage_full ? reserved : NULL;
+}
+void plat_reserved(const char *name, uint32_t len) { plat_save(name, reserved, len); }
+bool plat_remove(const char *name) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s", save_dir, name);
+ return remove(p) == 0;
+}
+void plat_begin(void) {}
+int plat_end(void) { return 0; }
+bool plat_slow(void) { return false; }
+
+/* writes the screen as a PPM image */
+void host_shot(const char *path) {
+ 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 = host_fb[i];
+ uint8_t rgb[3] = {(uint8_t)((c >> 11) * 255 / 31), (uint8_t)(((c >> 5) & 63) * 255 / 63), (uint8_t)((c & 31) * 255 / 31)};
+ fwrite(rgb, 1, 3, f);
+ }
+ fclose(f);
+}
diff --git a/games/undertale/src/res.c b/games/undertale/src/res.c
new file mode 100644
index 00000000..575c3a44
--- /dev/null
+++ b/games/undertale/src/res.c
@@ -0,0 +1,77 @@
+/* data.bin: sections, sprites, tiles, rooms and strings (see res.h). */
+#include "res.h"
+
+const uint8_t *ut_bin;
+
+int spr_frames(uint16_t spr) {
+ const uint8_t *s = section(SEC_SPRITES);
+ if (spr >= rd32(s)) return 0;
+ return rd16(s + 4 + 4 * spr + 2);
+}
+
+bool frame_get(uint16_t spr, int i, Frame *f) {
+ const uint8_t *s = section(SEC_SPRITES);
+ if (spr >= rd32(s)) return false;
+ int first = rd16(s + 4 + 4 * spr), n = rd16(s + 4 + 4 * spr + 2);
+ if (n <= 0) return false;
+ i %= n;
+ if (i < 0) i += n;
+ const uint8_t *fs = section(SEC_FRAMES);
+ const uint8_t *p = fs + rd32(fs + 4 + 4 * (first + i));
+ f->w = rd16(p), f->h = rd16(p + 2);
+ f->ox = rds16(p + 4), f->oy = rds16(p + 6);
+ f->bpp = p[8], f->ncol = p[9];
+ f->pal = p + 10;
+ uint32_t o = 10 + 2u * f->ncol;
+ f->rows = p + o;
+ f->data = p + o + 2u * f->h;
+ return true;
+}
+
+int spr_w(uint16_t spr) {
+ Frame f;
+ return frame_get(spr, 0, &f) ? f.w : 0;
+}
+int spr_h(uint16_t spr) {
+ Frame f;
+ return frame_get(spr, 0, &f) ? f.h : 0;
+}
+
+void tile_get(uint16_t id, Tile *t) {
+ const uint8_t *s = section(SEC_TILES);
+ const uint8_t *p = s + rd32(s + 4 + 4 * id);
+ t->bpp = p[0], t->ncol = p[1];
+ t->pal = p + 2;
+ t->bits = p + 2 + 2 * t->ncol;
+}
+
+void room_info(int room, RoomInfo *r) {
+ const uint8_t *s = section(SEC_ROOMS);
+ const uint8_t *p = s + 4 + 32 * room;
+ r->x = rds16(p), r->y = rds16(p + 2), r->w = rds16(p + 4), r->h = rds16(p + 6);
+ r->gx = rds16(p + 8), r->gy = rds16(p + 10);
+ r->gcols = rd16(p + 12), r->grows = rd16(p + 14);
+ r->grid = section(SEC_GRID) + rd32(p + 16);
+ r->coll = section(SEC_COLL) + rd32(p + 20);
+ r->cw = rd16(p + 24), r->ch = rd16(p + 26);
+ r->area = p[28], r->flags = p[29];
+ r->name = rd16(p + 30);
+}
+
+const char *str(uint16_t id) {
+ const uint8_t *s = section(SEC_STRINGS);
+ if (id >= rd32(s)) return "";
+ return (const char *)s + rd32(s + 4 + 4 * id);
+}
+
+int room_doors(int room, Door *out, int max) {
+ const uint8_t *s = section(SEC_DOORS);
+ int first = rd16(s + 4 * room), n = rd16(s + 4 * room + 2);
+ const uint8_t *d = s + 4 * NUM_ROOMS + 16 * first;
+ if (n > max) n = max;
+ for (int i = 0; i < n; i++, d += 16) {
+ out[i].x = rds16(d), out[i].y = rds16(d + 2), out[i].w = rds16(d + 4), out[i].h = rds16(d + 6);
+ out[i].room = rd16(d + 8), out[i].tx = rds16(d + 10), out[i].ty = rds16(d + 12), out[i].dir = rd16(d + 14);
+ }
+ return n;
+}
diff --git a/games/undertale/src/res.h b/games/undertale/src/res.h
new file mode 100644
index 00000000..8fa4a1e6
--- /dev/null
+++ b/games/undertale/src/res.h
@@ -0,0 +1,62 @@
+/* Undertale: data.bin (tools/pack.py), read where it lies in flash.
+ *
+ * Its sections (SEC_* in data.h): sprites and their frames, the areas' tiles,
+ * rooms (a tile grid and a collision map each), fonts and strings. */
+#ifndef UT_RES_H
+#define UT_RES_H
+#include <stdbool.h>
+#include <stdint.h>
+#include "data.h"
+
+extern const uint8_t *ut_bin;
+static inline uint16_t rd16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); }
+static inline int16_t rds16(const uint8_t *p) { return (int16_t)rd16(p); }
+static inline uint32_t rd32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; }
+static inline const uint8_t *section(int s) { return ut_bin + rd32(ut_bin + 8 + 4 * s); }
+
+/* a sprite's frame: its size and origin, palette and rows */
+typedef struct {
+ uint16_t w, h;
+ int16_t ox, oy;
+ uint8_t bpp, ncol;
+ const uint8_t *pal; /* ncol RGB565 colours (unaligned: read with rd16) */
+ const uint8_t *rows; /* u16 offsets of each row, from `data` */
+ const uint8_t *data;
+} Frame;
+bool frame_get(uint16_t spr, int i, Frame *f);
+int spr_frames(uint16_t spr);
+int spr_w(uint16_t spr);
+int spr_h(uint16_t spr);
+
+/* a 20 x 20 tile: bpp 0 (one colour), 1, 2, 4 or 8 */
+typedef struct {
+ uint8_t bpp, ncol;
+ const uint8_t *pal; /* ncol RGB565 colours */
+ const uint8_t *bits; /* 400 pixels, bpp bits each, lowest bits first */
+} Tile;
+void tile_get(uint16_t id, Tile *t);
+
+/* a room's facts */
+typedef struct {
+ int16_t x, y, w, h; /* its rectangle on the area's map */
+ int16_t gx, gy; /* the tile grid's top-left on the map */
+ uint16_t gcols, grows;
+ const uint8_t *grid; /* gcols * grows tile ids (u16), 0xFFFF none */
+ const uint8_t *coll; /* cw * ch bits, row by row ((cw + 7) / 8 bytes a row): 1 walkable */
+ uint16_t cw, ch; /* 4-pixel cells over the rectangle */
+ uint8_t area, flags;
+ uint16_t name; /* string: what SAVE shows */
+} RoomInfo;
+void room_info(int room, RoomInfo *r);
+
+/* a door of a room: walking into its rectangle takes Frisk to another room */
+typedef struct {
+ int16_t x, y, w, h;
+ uint16_t room;
+ int16_t tx, ty;
+ uint16_t dir;
+} Door;
+int room_doors(int room, Door *out, int max);
+
+const char *str(uint16_t id);
+#endif
diff --git a/games/undertale/src/rooms.c b/games/undertale/src/rooms.c
new file mode 100644
index 00000000..20063886
--- /dev/null
+++ b/games/undertale/src/rooms.c
@@ -0,0 +1,14 @@
+/* The rooms' objects and their random encounters. */
+#include "event.h"
+#include "events.h"
+#include "game.h"
+#include "world.h"
+
+void room_setup(int room, int from) {
+ (void)from;
+ switch (room) {
+ default: break;
+ }
+}
+
+void encounter_step(void) {}
diff --git a/games/undertale/src/save.c b/games/undertale/src/save.c
new file mode 100644
index 00000000..9355a6cc
--- /dev/null
+++ b/games/undertale/src/save.c
@@ -0,0 +1,8 @@
+/* Saves (save.h). */
+#include "save.h"
+void save_restore_copy(void) {}
+bool save_write(void) { return false; }
+bool save_exists(void) { return false; }
+bool save_load(void) { return false; }
+void save_resume_write(void) {}
+bool save_resume_load(void) { return false; }
diff --git a/games/undertale/src/save.h b/games/undertale/src/save.h
new file mode 100644
index 00000000..0458f15e
--- /dev/null
+++ b/games/undertale/src/save.h
@@ -0,0 +1,11 @@
+/* Undertale: saves (the game's SAVE, the moment kept on Home), and their copy in a Python script. */
+#ifndef UT_SAVE_H
+#define UT_SAVE_H
+#include <stdbool.h>
+void save_restore_copy(void);
+bool save_write(void);
+bool save_exists(void);
+bool save_load(void);
+void save_resume_write(void);
+bool save_resume_load(void);
+#endif
diff --git a/games/undertale/src/text.c b/games/undertale/src/text.c
new file mode 100644
index 00000000..1117eca6
--- /dev/null
+++ b/games/undertale/src/text.c
@@ -0,0 +1,301 @@
+/* Text typed a letter at a time, and the dialogue box (see text.h). */
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+#include "gfx.h"
+#include "res.h"
+#include "text.h"
+#include "world.h"
+
+char g_name[8] = "Frisk";
+
+/* ---------------------------------------------------------------- faces */
+/* each expression: its sprite (2 frames: the second one talks), drawn at (x, y) in the box; Toriel's
+ * heads sit on her shoulders */
+typedef struct {
+ uint16_t spr;
+ int8_t x, y;
+} Expr;
+static const Expr toriel_faces[] = {
+ {SPR_FACE_TORIELTALK, 9, 0}, {SPR_FACE_TORIELTALKSIDE, 9, 0}, {SPR_FACE_TORIELHAPPYTALK, 9, 0},
+ {SPR_FACE_TORIELWHAT, 9, 0}, {SPR_FACE_TORIELWHATSIDE, 9, 0}, {SPR_FACE_TORIELMAD, 9, 0},
+ {SPR_FACE_TORIELCOLD, 9, 0}, {SPR_FACE_TORIELSURPRISED, 9, 0}, {SPR_FACE_TORIELEMBARRASSED, 9, 0},
+ {SPR_FACE_TORIELGLASSES, 9, 0}, {SPR_FACE_TORIELREVENGETALK, 9, 0}, {SPR_FACE_TORIELSCARED, 9, 0},
+ {SPR_FACE_TORIELBLINK, 9, 0}, {SPR_FACE_TORIELHAPPYBLINK, 9, 0},
+};
+static const Expr flowey_faces[] = {
+ {SPR_FLOWEYNICE, 4, -2}, {SPR_FLOWEYNICESIDE, 4, -2}, {SPR_FLOWEYSASSY, 4, -2}, {SPR_FLOWEYEVIL, 4, -2},
+ {SPR_FLOWEYGRIN, 4, -2}, {SPR_FLOWEYPLAIN, 4, -2}, {SPR_FLOWEYPISSED, 4, -2}, {SPR_FLOWEYWINK, 4, -2},
+ {SPR_FLOWEYLAUGH, 4, -2}, {SPR_FLOWEYHURT, 4, -2}, {SPR_FLOWEYTORIEL, 4, -2}, {SPR_FLOWEYTORIEL2, 4, -2},
+ {SPR_FLOWEYSIDESHOCK, 4, -2},
+};
+static const Expr sans_faces[] = {{SPR_FACE_SANS, 4, 0}, {SPR_FACE_SANSCHUCKLE, 4, 0}, {SPR_FACE_SANSWINK, 4, 0}};
+static const Expr papyrus_faces[] = {
+ {SPR_FACE_PAPYRUS, 4, -4}, {SPR_FACE_PAPYRUSEVIL, 4, -4}, {SPR_FACE_PAPYRUSLAUGH, 4, -4},
+ {SPR_FACE_PAPYRUSMAD, 4, -4}, {SPR_FACE_PAPYRUSSIDE, 4, -4},
+};
+static const struct {
+ const Expr *e;
+ int n;
+} faces[FACE_MAX] = {
+ [FACE_TORIEL] = {toriel_faces, sizeof toriel_faces / sizeof toriel_faces[0]},
+ [FACE_FLOWEY] = {flowey_faces, sizeof flowey_faces / sizeof flowey_faces[0]},
+ [FACE_SANS] = {sans_faces, sizeof sans_faces / sizeof sans_faces[0]},
+ [FACE_PAPYRUS] = {papyrus_faces, sizeof papyrus_faces / sizeof papyrus_faces[0]},
+};
+
+/* ---------------------------------------------------------------- the writer */
+#define MAX_LINES 8
+static uint16_t breaks[MAX_LINES]; /* where the page's lines wrap (src offsets), the line after indented */
+static int nbreaks;
+static int wrap_width = 270;
+
+static int page_len(const char *s) {
+ int n = 0;
+ while (s[n] && s[n] != '|') n++;
+ return n;
+}
+
+/* the width of a letter, 0 for the marks */
+static int code_len(const char *s) {
+ switch (s[0]) {
+ case '^': case '`': case '#': return s[1] ? 2 : 1;
+ case '~': return 1;
+ default: return 0;
+ }
+}
+
+/* where the page's lines wrap: at the last space before the box's edge */
+static void layout(Writer *w) {
+ nbreaks = 0;
+ const char *s = w->src + w->page;
+ int x = 0, last_space = -1, start = 0;
+ for (int i = 0; i < w->len; i++) {
+ int c = code_len(s + i);
+ if (c) {
+ i += c - 1;
+ continue;
+ }
+ if (s[i] == '@') break;
+ if (s[i] == '\n') {
+ x = 0, last_space = -1, start = i + 1;
+ continue;
+ }
+ if (s[i] == ' ') last_space = i;
+ int adv = s[i] == '$' ? 8 * (int)strlen(g_name) : 8;
+ x += adv;
+ if (x > wrap_width && last_space > start && nbreaks < MAX_LINES) {
+ breaks[nbreaks++] = (uint16_t)(w->page + last_space);
+ /* the line after: indented under the first's words when the page starts with "* " */
+ x = (s[0] == '*' ? 16 : 0);
+ for (int k = last_space + 1; k <= i; k++)
+ if (!code_len(s + k)) x += 8;
+ start = last_space + 1;
+ last_space = -1;
+ }
+ }
+}
+
+static uint8_t expr_of(char c) { return (uint8_t)(c >= 'a' ? 10 + c - 'a' : c - '0'); }
+
+static void page_begin(Writer *w) {
+ w->len = page_len(w->src + w->page);
+ w->shown = 0, w->pause = 0, w->t = 0, w->done = false, w->auto_close = false;
+ w->choices = 0, w->choice = 0;
+ for (int i = 0; i < w->len; i++)
+ if (w->src[w->page + i] == '@') {
+ w->choice_at = w->page + i;
+ w->choices = 2;
+ break;
+ }
+ layout(w);
+}
+
+void writer_start(Writer *w, const char *s, int x, int y, int font) {
+ memset(w, 0, sizeof *w);
+ w->src = s, w->x = x, w->y = y, w->font = font;
+ w->line_h = 18, w->speed = 1;
+ page_begin(w);
+}
+
+static void show_all(Writer *w) {
+ const char *s = w->src + w->page;
+ while (w->shown < w->len && s[w->shown] != '@') {
+ int c = code_len(s + w->shown);
+ if (c && s[w->shown] == '`') w->face_expr = expr_of(s[w->shown + 1]);
+ if (c && s[w->shown] == '~') w->auto_close = true;
+ w->shown += c ? c : 1;
+ }
+ w->done = true;
+}
+
+bool writer_update(Writer *w, uint32_t pressed) {
+ if (w->finished) return false;
+ const char *s = w->src + w->page;
+ if (!w->done) {
+ if (pressed & K_X) {
+ show_all(w);
+ } else if (w->pause > 0) {
+ w->pause--;
+ } else if (++w->t >= w->speed) {
+ w->t = 0;
+ /* the marks take no time; the next letter shows */
+ for (;;) {
+ if (w->shown >= w->len || s[w->shown] == '@') {
+ w->done = true;
+ break;
+ }
+ int c = code_len(s + w->shown);
+ if (!c) {
+ w->shown++;
+ break;
+ }
+ if (s[w->shown] == '^') w->pause = (s[w->shown + 1] - '0') * 5;
+ if (s[w->shown] == '`') w->face_expr = expr_of(s[w->shown + 1]);
+ if (s[w->shown] == '~') w->auto_close = true;
+ w->shown += c;
+ if (w->pause) break;
+ }
+ if (w->shown >= w->len) w->done = true;
+ }
+ return true;
+ }
+ if (w->choices) {
+ if (pressed & K_LEFT) w->choice = 0;
+ if (pressed & K_RIGHT) w->choice = 1;
+ }
+ if ((pressed & K_Z) || w->auto_close) {
+ const char *next = s + w->len;
+ if (*next == '|') {
+ w->page += w->len + 1;
+ page_begin(w);
+ } else {
+ w->finished = true;
+ return false;
+ }
+ }
+ return true;
+}
+
+int writer_talking(const Writer *w) { return !w->done && !w->pause; }
+
+static uint16_t color_of(char c) {
+ switch (c) {
+ case 'Y': return rgb565(0xFFFF00);
+ case 'R': return rgb565(0xFF0000);
+ case 'B': return rgb565(0x0000FF);
+ case 'O': return rgb565(0xFFA040);
+ case 'G': return rgb565(0x00C000);
+ case 'P': return rgb565(0xD535D9);
+ case 'L': return rgb565(0x0EC0FD);
+ default: return C_WHITE;
+ }
+}
+
+void writer_draw(const Writer *w, uint16_t color) {
+ if (w->finished) return;
+ char seg[80];
+ int n = 0, x = w->x, y = w->y, sx = x;
+ uint16_t col = color, segcol = color;
+ const char *s = w->src + w->page;
+ int b = 0;
+#define FLUSH() do { if (n) { seg[n] = 0; gfx_text_ex(w->font, sx, y, seg, n, segcol, w->shake, (uint32_t)(y * 31 + sx), 0); n = 0; } } while (0)
+ for (int i = 0; i < w->shown && i < w->len; i++) {
+ if (s[i] == '@') break;
+ int c = code_len(s + i);
+ if (c) {
+ if (s[i] == '#') {
+ FLUSH();
+ col = s[i + 1] == 'X' || s[i + 1] == 'W' ? color : color_of(s[i + 1]);
+ }
+ i += c - 1;
+ continue;
+ }
+ if (s[i] == '\n' || (b < nbreaks && w->page + i == breaks[b])) {
+ FLUSH();
+ if (s[i] != '\n') b++;
+ y += w->line_h;
+ x = w->x + (s[i] != '\n' && s[0] == '*' ? 16 : 0);
+ continue;
+ }
+ if (n == 0) sx = x, segcol = col;
+ if (col != segcol) {
+ FLUSH();
+ sx = x, segcol = col;
+ }
+ if (s[i] == '$') {
+ for (const char *p = g_name; *p && n < 70; p++) seg[n++] = *p, x += 8;
+ continue;
+ }
+ seg[n++] = s[i];
+ x += 8;
+ if (n >= 70) FLUSH();
+ }
+ FLUSH();
+#undef FLUSH
+ if (w->choices && w->done) {
+ /* the two options on the next line, the heart by the one selected */
+ const char *a = w->src + w->choice_at + 1, *bb = strchr(a, '@');
+ int la = bb ? (int)(bb - a) : 0, lb = bb ? page_len(bb + 1) : 0;
+ int cy = y + w->line_h + 4;
+ int ax = w->x + 56, bx = w->x + 168;
+ gfx_text_ex(w->font, ax, cy, a, la, C_WHITE, 0, 0, 0);
+ if (bb) gfx_text_ex(w->font, bx, cy, bb + 1, lb, C_WHITE, 0, 0, 0);
+ gfx_sprite(SPR_HEART, 0, (w->choice ? bx : ax) - 12, cy + 6, 0, 255);
+ }
+}
+
+/* ---------------------------------------------------------------- the dialogue box */
+static Writer box;
+static bool box_open;
+static int box_face;
+static int box_top = -1, box_at_top;
+static int last_choice;
+static char fmt_buf[512];
+
+void text_set_top(int top) { box_top = top; }
+
+void text_open(int face, const char *s) {
+ box_face = face;
+ int tx = face ? 76 : 22;
+ wrap_width = face ? 300 - tx - 6 : 300 - tx - 8;
+ box_at_top = box_top >= 0 ? box_top : (pl.y + 15 - cam_y > 130);
+ writer_start(&box, s, tx, (box_at_top ? 5 : 160) + 11, FONT_MAIN);
+ box_open = true;
+}
+
+void text_openf(int face, const char *fmt, ...) {
+ va_list ap;
+ va_start(ap, fmt);
+ vsnprintf(fmt_buf, sizeof fmt_buf, fmt, ap);
+ va_end(ap);
+ text_open(face, fmt_buf);
+}
+
+bool text_active(void) { return box_open; }
+int text_choice(void) { return last_choice; }
+
+void text_update(uint32_t pressed) {
+ if (!box_open) return;
+ int ch = box.choice;
+ bool had = box.choices && box.done;
+ if (!writer_update(&box, pressed)) {
+ box_open = false;
+ if (had) last_choice = ch;
+ }
+}
+
+void text_draw(void) {
+ if (!box_open) return;
+ int y = box_at_top ? 5 : 160;
+ gfx_rect(16, y, 288, 76, C_WHITE, 255);
+ gfx_rect(19, y + 3, 282, 70, C_BLACK, 255);
+ if (box_face && faces[box_face].e) {
+ int e = box.face_expr < faces[box_face].n ? box.face_expr : 0;
+ const Expr *x = &faces[box_face].e[e];
+ int fr = writer_talking(&box) ? (box.shown / 2) & 1 : 0;
+ if (box_face == FACE_TORIEL) gfx_sprite(SPR_FACE_TORIELBODY, 0, 26, y + 13 + 32, 0, 255);
+ gfx_sprite(x->spr, fr, 26 + x->x, y + 13 + x->y, 0, 255);
+ }
+ writer_draw(&box, C_WHITE);
+}
diff --git a/games/undertale/src/text.h b/games/undertale/src/text.h
new file mode 100644
index 00000000..6a1cf139
--- /dev/null
+++ b/games/undertale/src/text.h
@@ -0,0 +1,56 @@
+/* Undertale: text, typed a letter at a time.
+ *
+ * The game's texts are written with a few marks:
+ * \n a new line
+ * | a new page (after Z)
+ * ^N a pause of N times 5 frames (^1 .. ^9)
+ * `N the face's expression N (FACE_* in face.c)
+ * #Y #R #B #O #G #P #L #X yellow, red, blue, orange, green, purple, light blue, white again
+ * $ the fallen human's name
+ * @A@B at the end of a page: a choice between A and B (text_choice() says which)
+ * ~ the page closes itself once typed (no Z)
+ *
+ * A Writer types into a rectangle; the dialogue box is one, with a face or not, at the top or the bottom of
+ * the screen. */
+#ifndef UT_TEXT_H
+#define UT_TEXT_H
+#include <stdbool.h>
+#include <stdint.h>
+
+enum { FACE_NONE, FACE_TORIEL, FACE_FLOWEY, FACE_SANS, FACE_PAPYRUS, FACE_UNDYNE, FACE_ALPHYS, FACE_ASGORE, FACE_MAX };
+
+typedef struct {
+ const char *src; /* the whole text */
+ int page; /* where the page being typed starts in src */
+ int shown; /* letters of the page shown */
+ int len; /* the page's length (up to | or the end) */
+ int pause; /* frames left before the next letter */
+ int x, y, line_h;
+ int font;
+ int speed; /* frames between letters */
+ int t;
+ uint8_t face_expr;
+ bool done; /* the page is all typed */
+ bool finished; /* every page read */
+ bool auto_close;
+ int shake; /* letters shaking (pixels) */
+ int choice, choices; /* the page's choice: selected, how many (0: none) */
+ int choice_at; /* where the choice's options start in src */
+} Writer;
+
+void writer_start(Writer *w, const char *s, int x, int y, int font);
+/* one frame: Z goes on, X shows the page at once; returns true while it isn't finished */
+bool writer_update(Writer *w, uint32_t pressed);
+void writer_draw(const Writer *w, uint16_t color);
+int writer_talking(const Writer *w); /* letters are being typed (a face moves its mouth) */
+
+/* the dialogue box */
+void text_open(int face, const char *s);
+void text_openf(int face, const char *fmt, ...);
+bool text_active(void);
+void text_update(uint32_t pressed);
+void text_draw(void);
+int text_choice(void); /* 0 or 1: the last choice made */
+void text_set_top(int top); /* -1: by where Frisk is (the game's way), 0 bottom, 1 top */
+extern char g_name[8]; /* the fallen human's name */
+#endif
diff --git a/games/undertale/src/world.c b/games/undertale/src/world.c
new file mode 100644
index 00000000..3edcf3d9
--- /dev/null
+++ b/games/undertale/src/world.c
@@ -0,0 +1,335 @@
+/* The overworld: rooms, the camera, Frisk and the room's objects (world.h). */
+#include <string.h>
+#include "event.h"
+#include "game.h"
+#include "gfx.h"
+#include "res.h"
+#include "text.h"
+#include "world.h"
+
+void pl_walk_step(void); /* event.c */
+
+Obj objs[MAX_OBJS];
+Player pl;
+int g_room = -1;
+static RoomInfo room;
+static Door doors[16];
+static int ndoors;
+int cam_x, cam_y;
+bool cam_locked;
+uint8_t g_fade;
+
+/* Frisk's box: his feet (from his sprite's top-left), as the game's mask */
+#define PBX 3
+#define PBY 20
+#define PBW 14
+#define PBH 9
+#define SPEED 3
+
+const RoomInfo *world_room_info(void) { return g_room >= 0 ? &room : NULL; }
+
+/* the room of the same area whose rectangle holds (x, y), -1 none */
+static int room_at(int x, int y) {
+ if (x >= room.x && x < room.x + room.w && y >= room.y && y < room.y + room.h) return g_room;
+ for (int r = 0; r < NUM_ROOMS; r++) {
+ RoomInfo o;
+ room_info(r, &o);
+ if (o.area == room.area && x >= o.x && x < o.x + o.w && y >= o.y && y < o.y + o.h) return r;
+ }
+ return -1;
+}
+
+/* the 4-pixel cell at (x, y) walkable? (in whichever room of the area holds it) */
+static bool cell_walkable(int x, int y) {
+ const RoomInfo *ri = &room;
+ RoomInfo o;
+ if (!(x >= room.x && x < room.x + room.w && y >= room.y && y < room.y + room.h)) {
+ int r = room_at(x, y);
+ if (r < 0) return false;
+ room_info(r, &o);
+ ri = &o;
+ }
+ int cx = (x - ri->x) >> 2, cy = (y - ri->y) >> 2;
+ if (cx < 0 || cy < 0 || cx >= ri->cw || cy >= ri->ch) return false;
+ return ri->coll[cy * ((ri->cw + 7) >> 3) + (cx >> 3)] >> (cx & 7) & 1;
+}
+
+static bool boxes_meet(int ax, int ay, int aw, int ah, int bx, int by, int bw, int bh) {
+ return ax < bx + bw && bx < ax + aw && ay < by + bh && by < ay + ah;
+}
+
+bool world_walkable(int x, int y, int w, int h, int ignore) {
+ /* every cell the box covers (its corners and every 4 pixels between) */
+ for (int yy = y;; yy += 4) {
+ if (yy > y + h - 1) yy = y + h - 1;
+ for (int xx = x;; xx += 4) {
+ if (xx > x + w - 1) xx = x + w - 1;
+ if (!cell_walkable(xx, yy)) return false;
+ if (xx == x + w - 1) break;
+ }
+ if (yy == y + h - 1) break;
+ }
+ for (int i = 0; i < MAX_OBJS; i++) {
+ const Obj *o = &objs[i];
+ if (i == ignore || o->kind == OBJ_NONE || !(o->flags & OF_SOLID)) continue;
+ if (boxes_meet(x, y, w, h, o->x + o->bx, o->y + o->by, o->bw, o->bh)) return false;
+ }
+ return true;
+}
+
+static bool player_free(int x, int y) { return world_walkable(x + PBX, y + PBY, PBW, PBH, -1); }
+
+Obj *obj_new(int kind, int x, int y) {
+ for (int i = 0; i < MAX_OBJS; i++)
+ if (objs[i].kind == OBJ_NONE) {
+ Obj *o = &objs[i];
+ memset(o, 0, sizeof *o);
+ o->kind = (uint8_t)kind, o->x = (int16_t)x, o->y = (int16_t)y, o->alpha = 255;
+ return o;
+ }
+ return NULL;
+}
+Obj *obj_find(int name) {
+ for (int i = 0; i < MAX_OBJS; i++)
+ if (objs[i].kind != OBJ_NONE && objs[i].name == name) return &objs[i];
+ return NULL;
+}
+void obj_clear_all(void) { memset(objs, 0, sizeof objs); }
+
+void world_camera(void) {
+ if (cam_locked) return;
+ int cx = pl.x + 10 - SCREEN_W / 2, cy = pl.y + 15 - SCREEN_H / 2;
+ if (room.w <= SCREEN_W) cx = room.x + (room.w - SCREEN_W) / 2;
+ else if (cx < room.x) cx = room.x;
+ else if (cx > room.x + room.w - SCREEN_W) cx = room.x + room.w - SCREEN_W;
+ if (room.h <= SCREEN_H) cy = room.y + (room.h - SCREEN_H) / 2;
+ else if (cy < room.y) cy = room.y;
+ else if (cy > room.y + room.h - SCREEN_H) cy = room.y + room.h - SCREEN_H;
+ cam_x = cx, cam_y = cy;
+}
+
+void world_enter(int r, int x, int y, int dir) {
+ int from = g_room;
+ g_room = r;
+ room_info(r, &room);
+ pl.x = (int16_t)x, pl.y = (int16_t)y, pl.dir = (uint8_t)dir;
+ pl.frame = 0, pl.anim = 0;
+ obj_clear_all();
+ ndoors = room_doors(r, doors, 16);
+ cam_locked = false;
+ room_setup(r, from);
+ world_camera();
+}
+
+/* ---------------------------------------------------------------- fades */
+static struct {
+ int room, x, y, dir;
+ int phase, t; /* 1: going black, 2: coming back */
+} fade;
+#define FADE_FRAMES 4
+
+void world_fade_to(int r, int x, int y, int dir) {
+ fade.room = r, fade.x = x, fade.y = y, fade.dir = dir;
+ fade.phase = 1, fade.t = 0;
+}
+bool world_fading(void) { return fade.phase != 0; }
+
+static void fade_step(void) {
+ if (fade.phase == 1) {
+ if (++fade.t >= FADE_FRAMES) {
+ world_enter(fade.room, fade.x, fade.y, fade.dir);
+ fade.phase = 2, fade.t = 0;
+ }
+ g_fade = (uint8_t)(255 * fade.t / FADE_FRAMES);
+ } else if (fade.phase == 2) {
+ if (++fade.t >= FADE_FRAMES) fade.phase = 0;
+ g_fade = (uint8_t)(255 - 255 * fade.t / FADE_FRAMES);
+ } else {
+ g_fade = 0;
+ }
+}
+
+/* ---------------------------------------------------------------- Frisk */
+static const uint8_t frames_of[4] = {4, 4, 2, 2};
+
+static void face_from_keys(uint32_t keys, uint32_t pressed) {
+ static const uint32_t bit[4] = {K_DOWN, K_UP, K_LEFT, K_RIGHT};
+ /* a direction just pressed turns him; letting go of the one he faces turns him to one still held */
+ for (int d = 0; d < 4; d++)
+ if (pressed & bit[d]) pl.dir = (uint8_t)d;
+ if (!(keys & bit[pl.dir]))
+ for (int d = 0; d < 4; d++)
+ if (keys & bit[d]) {
+ pl.dir = (uint8_t)d;
+ break;
+ }
+}
+
+/* one pixel along an axis, sliding past a corner (diagonal walls are steps of cells) */
+static bool step(int sx, int sy, bool slide) {
+ if (player_free(pl.x + sx, pl.y + sy)) {
+ pl.x = (int16_t)(pl.x + sx), pl.y = (int16_t)(pl.y + sy);
+ return true;
+ }
+ if (!slide) return false;
+ for (int k = 1; k <= 2; k++) {
+ bool a = sx ? player_free(pl.x + sx, pl.y - k) : player_free(pl.x - k, pl.y + sy);
+ bool b = sx ? player_free(pl.x + sx, pl.y + k) : player_free(pl.x + k, pl.y + sy);
+ if (a != b) {
+ int o = a ? -1 : 1;
+ if (sx) pl.y = (int16_t)(pl.y + o), pl.x = (int16_t)(pl.x + sx);
+ else pl.x = (int16_t)(pl.x + o), pl.y = (int16_t)(pl.y + sy);
+ return true;
+ }
+ if (a && b) break;
+ }
+ return false;
+}
+
+static void player_move(uint32_t keys, uint32_t pressed) {
+ int dx = ((keys & K_RIGHT) != 0) - ((keys & K_LEFT) != 0);
+ int dy = ((keys & K_DOWN) != 0) - ((keys & K_UP) != 0);
+ face_from_keys(keys, pressed);
+ bool moved = false;
+ for (int i = 0; i < SPEED; i++) {
+ if (dx) moved |= step(dx, 0, !dy);
+ if (dy) moved |= step(0, dy, !dx);
+ }
+ if (dx || dy) {
+ pl.anim++;
+ pl.frame = (uint8_t)((1 + pl.anim / 6) % frames_of[pl.dir]);
+ if (moved) pl.steps++;
+ } else {
+ pl.anim = 0, pl.frame = 0;
+ }
+ pl.moving = moved;
+}
+
+/* the box in front of Frisk, where Z looks */
+static void front_box(int *x, int *y, int *w, int *h) {
+ int fx = pl.x + PBX, fy = pl.y + PBY, fw = PBW, fh = PBH;
+ switch (pl.dir) {
+ case DIR_DOWN: fy += fh, fh = 12; break;
+ case DIR_UP: fy -= 14, fh = 14; break;
+ case DIR_LEFT: fx -= 12, fw = 12; break;
+ default: fx += fw, fw = 12; break;
+ }
+ *x = fx, *y = fy, *w = fw, *h = fh;
+}
+
+static void interact(void) {
+ int x, y, w, h;
+ front_box(&x, &y, &w, &h);
+ for (int i = 0; i < MAX_OBJS; i++) {
+ Obj *o = &objs[i];
+ if (o->kind == OBJ_NONE || !(o->flags & OF_TALK)) continue;
+ if (boxes_meet(x, y, w, h, o->x + o->bx, o->y + o->by, o->bw, o->bh)) {
+ event_start(o->event, o);
+ return;
+ }
+ }
+}
+
+static void touches(void) {
+ int x = pl.x + PBX, y = pl.y + PBY;
+ for (int i = 0; i < MAX_OBJS; i++) {
+ Obj *o = &objs[i];
+ if (o->kind == OBJ_NONE || !(o->flags & OF_TOUCH)) continue;
+ if (boxes_meet(x, y, PBW, PBH, o->x + o->bx, o->y + o->by, o->bw, o->bh)) {
+ event_start(o->event, o);
+ return;
+ }
+ }
+}
+
+/* ---------------------------------------------------------------- objects walking */
+static void objs_update(void) {
+ for (int i = 0; i < MAX_OBJS; i++) {
+ Obj *o = &objs[i];
+ if (o->kind == OBJ_NONE) continue;
+ if (o->walking) {
+ int dx = o->tx - o->x, dy = o->ty - o->y;
+ int sp = o->speed ? o->speed : 2;
+ if (dx) o->dir = dx < 0 ? DIR_LEFT : DIR_RIGHT;
+ if (abs_i(dy) > abs_i(dx)) o->dir = dy < 0 ? DIR_UP : DIR_DOWN;
+ o->x = (int16_t)(o->x + clamp_i(dx, -sp, sp));
+ o->y = (int16_t)(o->y + clamp_i(dy, -sp, sp));
+ if (o->x == o->tx && o->y == o->ty) o->walking = 0;
+ if (o->flags & OF_WALKANIM) {
+ o->anim_t++;
+ o->frame = (uint8_t)(1 + o->anim_t / (o->anim_speed ? o->anim_speed : 6));
+ }
+ if (!o->walking && (o->flags & OF_WALKANIM)) o->frame = 0, o->anim_t = 0;
+ } else if (o->flags & OF_ANIM) {
+ if (++o->anim_t >= (o->anim_speed ? o->anim_speed : 6)) o->anim_t = 0, o->frame++;
+ }
+ }
+}
+
+void world_update(uint32_t keys, uint32_t pressed) {
+ fade_step();
+ if (fade.phase == 1) return;
+ objs_update();
+ bool busy = event_running() || text_active() || fade.phase;
+ if (!busy && !pl.frozen) {
+ player_move(keys, pressed);
+ /* out of the room's rectangle: into the room that holds his feet */
+ int fx = pl.x + PBX + PBW / 2, fy = pl.y + PBY + PBH / 2;
+ int r = room_at(fx, fy);
+ if (r >= 0 && r != g_room) {
+ world_fade_to(r, pl.x, pl.y, pl.dir);
+ return;
+ }
+ /* a door */
+ for (int i = 0; i < ndoors; i++)
+ if (boxes_meet(pl.x + PBX, pl.y + PBY, PBW, PBH, doors[i].x, doors[i].y, doors[i].w, doors[i].h)) {
+ world_fade_to(doors[i].room, doors[i].tx, doors[i].ty, doors[i].dir);
+ return;
+ }
+ if (pressed & K_Z) interact();
+ else touches();
+ if (!event_running() && (pressed & K_C)) game_open_menu();
+ if (!event_running()) encounter_step();
+ } else {
+ pl_walk_step();
+ }
+ world_camera();
+}
+
+/* ---------------------------------------------------------------- drawing */
+typedef struct {
+ int16_t depth;
+ int8_t who; /* object index, -1 Frisk */
+} DrawRef;
+
+static uint16_t obj_sprite(const Obj *o) { return o->spr[o->spr[o->dir] ? o->dir : 0]; }
+
+void world_draw(void) {
+ gfx_tiles(cam_x, cam_y);
+ /* the room's objects and Frisk, the lower ones in front */
+ DrawRef order[MAX_OBJS + 1];
+ int n = 0;
+ for (int i = 0; i < MAX_OBJS; i++) {
+ const Obj *o = &objs[i];
+ if (o->kind == OBJ_NONE || (o->flags & OF_HIDDEN) || !o->spr[0]) continue;
+ int d = o->y + o->by + o->bh + o->depth_bias;
+ if (o->flags & OF_BACK) d = -30000;
+ if (o->flags & OF_FRONT) d = 30000;
+ order[n++] = (DrawRef){(int16_t)d, (int8_t)i};
+ }
+ if (!pl.hidden) order[n++] = (DrawRef){(int16_t)(pl.y + PBY + PBH), -1};
+ for (int i = 1; i < n; i++)
+ for (int j = i; j > 0 && order[j - 1].depth > order[j].depth; j--) {
+ DrawRef t = order[j];
+ order[j] = order[j - 1], order[j - 1] = t;
+ }
+ static const uint16_t frisk[4] = {SPR_FRISK_D, SPR_FRISK_U, SPR_FRISK_L, SPR_FRISK_R};
+ for (int i = 0; i < n; i++) {
+ if (order[i].who < 0) {
+ gfx_sprite(frisk[pl.dir], pl.frame, pl.x - cam_x, pl.y - cam_y, 0, 255);
+ } else {
+ const Obj *o = &objs[order[i].who];
+ gfx_sprite(obj_sprite(o), o->frame, o->x - cam_x, o->y - cam_y, 0, o->alpha);
+ }
+ }
+}
diff --git a/games/undertale/src/world.h b/games/undertale/src/world.h
new file mode 100644
index 00000000..c8a5f137
--- /dev/null
+++ b/games/undertale/src/world.h
@@ -0,0 +1,74 @@
+/* Undertale: the overworld. Rooms, the camera, Frisk, the room's objects.
+ *
+ * Positions are the area map's pixels (tools/rooms.py): the rooms of an area
+ * keep their places on it, so walking out of a room's rectangle walks into the
+ * next room, after a fade, as in the game. */
+#ifndef UT_WORLD_H
+#define UT_WORLD_H
+#include <stdbool.h>
+#include <stdint.h>
+#include "res.h"
+
+enum { DIR_DOWN, DIR_UP, DIR_LEFT, DIR_RIGHT };
+
+/* an object of the room: a character, a SAVE Point, a sign, a trigger... */
+enum {
+ OBJ_NONE, OBJ_NPC, OBJ_SAVE, OBJ_SIGN, OBJ_TRIGGER, OBJ_DECO, OBJ_ROCK, OBJ_SPIKES, OBJ_SWITCH, OBJ_ITEM,
+ OBJ_MARK
+};
+enum {
+ OF_SOLID = 1, /* Frisk can't walk through its box */
+ OF_TALK = 2, /* pressing Z facing it runs its event */
+ OF_TOUCH = 4, /* walking into its box runs its event */
+ OF_HIDDEN = 8, /* not drawn */
+ OF_ANIM = 16, /* its frames cycle (anim_speed) even standing */
+ OF_WALKANIM = 32, /* its frames cycle while it walks */
+ OF_FRONT = 64, /* drawn over everything else */
+ OF_BACK = 128 /* drawn under everything else */
+};
+#define MAX_OBJS 48
+typedef struct {
+ uint8_t kind, dir;
+ uint16_t flags;
+ int16_t x, y; /* its sprite's origin (the frame's top-left for the game's sprites) */
+ int16_t bx, by, bw, bh; /* its box, from (x, y) */
+ uint16_t spr[4]; /* its sprite for each direction (spr[0] if it has one) */
+ uint8_t frame, anim_speed, anim_t, depth_bias;
+ uint16_t event; /* EV_* run when talked to or touched */
+ int16_t arg, arg2; /* the kind's own (a sign's text, a flag...) */
+ /* walking somewhere: (tx, ty) at speed pixels a frame */
+ int16_t tx, ty;
+ uint8_t speed, walking;
+ uint8_t alpha;
+ uint8_t name; /* an ACTOR_* (scripts find it by it) */
+ int16_t fx, fy; /* fractions (1/16 pixel) for slow walks */
+} Obj;
+extern Obj objs[MAX_OBJS];
+
+typedef struct {
+ int16_t x, y; /* Frisk's sprite's top-left */
+ uint8_t dir, frame, anim, moving;
+ bool frozen; /* a cutscene has control */
+ bool hidden;
+ uint16_t steps; /* towards an encounter */
+} Player;
+extern Player pl;
+
+extern int g_room; /* ROOM_* */
+extern int cam_x, cam_y; /* the screen's top-left on the map */
+extern bool cam_locked; /* a cutscene moves the camera */
+
+const RoomInfo *world_room_info(void);
+void world_enter(int room, int x, int y, int dir); /* (x, y) Frisk's top-left; no fade */
+void world_update(uint32_t keys, uint32_t pressed);
+void world_draw(void);
+bool world_walkable(int x, int y, int w, int h, int ignore); /* a box on the map, objects too (not `ignore`) */
+void world_camera(void); /* follows Frisk, inside the room */
+Obj *obj_new(int kind, int x, int y);
+Obj *obj_find(int name);
+void obj_clear_all(void);
+/* the room fades out, then in: room changes in the middle */
+void world_fade_to(int room, int x, int y, int dir);
+bool world_fading(void);
+extern uint8_t g_fade; /* 0 clear, 255 black: drawn over the room */
+#endif
diff --git a/games/undertale/tests/play.c b/games/undertale/tests/play.c
new file mode 100644
index 00000000..2e339f4f
--- /dev/null
+++ b/games/undertale/tests/play.c
@@ -0,0 +1,215 @@
+/* Plays Undertale on a computer, with scripted keys, and saves frames.
+ *
+ * play [--frames N] [--keys "10-40:right,50:z,..."] [--shots 30,60|all] [--out DIR] [--saves DIR]
+ * [--room N --at X,Y] [--name NAME] [--flag F=V]... [--battle ID] [--trace]
+ *
+ * --path "x,y;x,y;z;w30;..." steers Frisk to each point in turn (holding arrows), presses Z ("z"), X ("x"),
+ * waits ("wN": N frames) or mashes Z through talks ("talk": until no text or event is left), when the scripted
+ * keys don't hold anything.
+ * Keys: left right up down z x c home. "a-b:key" holds the key from frame a to b, "a:key" for one frame.
+ * --room starts a new game in room N (its ROOM_* number) with Frisk's top-left at (X, Y), past the title.
+ * Screenshots are DIR/shot_<frame>.ppm. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include "../src/battle.h"
+#include "../src/game.h"
+#include "../src/gfx.h"
+#include "../src/menu.h"
+#include "../src/res.h"
+#include "../src/world.h"
+
+extern uint32_t host_keys, host_time;
+extern uint16_t host_fb[SCREEN_W * SCREEN_H];
+void host_shot(const char *path);
+void host_save_dir(const char *d);
+extern const uint8_t ut_data[];
+
+typedef struct { int a, b; uint32_t k; } Hold;
+static Hold holds[4096];
+static int nholds;
+
+#include "../src/event.h"
+#include "../src/text.h"
+static char path_buf[65536];
+static char *path_at;
+static int path_wait, path_stuck, path_last_x, path_last_y, path_room = -1;
+
+/* the keys the path holds this frame (0: it's done or waiting) */
+static uint32_t path_keys(int f) {
+ if (!path_at || !*path_at) return 0;
+ if (path_wait > 0) {
+ path_wait--;
+ return 0;
+ }
+ char *end = strchr(path_at, ';');
+ char tok[64];
+ int n = end ? (int)(end - path_at) : (int)strlen(path_at);
+ snprintf(tok, sizeof tok, "%.*s", n, path_at);
+ char *next = end ? end + 1 : path_at + n;
+ if (!strcmp(tok, "z") || !strcmp(tok, "x") || !strcmp(tok, "c")) {
+ path_at = next;
+ path_wait = 1;
+ return tok[0] == 'z' ? K_Z : tok[0] == 'x' ? K_X : K_C;
+ }
+ if (tok[0] == 'w') {
+ path_wait = atoi(tok + 1);
+ path_at = next;
+ return 0;
+ }
+ if (!strcmp(tok, "talk")) {
+ if (!text_active() && !event_running() && g_mode == MODE_WORLD && !world_fading()) {
+ path_at = next;
+ return 0;
+ }
+ return (f & 1) ? K_Z : 0;
+ }
+ int x, y;
+ if (sscanf(tok, "%d,%d", &x, &y) != 2) {
+ path_at = next;
+ return 0;
+ }
+ if (g_mode != MODE_WORLD || text_active() || event_running() || world_fading()) return 0;
+ /* a door took him to another room: that point is reached */
+ if (path_room >= 0 && g_room != path_room) {
+ path_room = g_room;
+ path_at = next;
+ return 0;
+ }
+ path_room = g_room;
+ int dx = x - pl.x, dy = y - pl.y;
+ if (abs(dx) <= 1 && abs(dy) <= 1) {
+ path_at = next;
+ path_stuck = 0;
+ return 0;
+ }
+ if (pl.x == path_last_x && pl.y == path_last_y) {
+ if (++path_stuck > 60) {
+ fprintf(stderr, "path: stuck at %d,%d on the way to %d,%d (room %d)\n", pl.x, pl.y, x, y, g_room);
+ path_at = next, path_stuck = 0;
+ }
+ } else
+ path_stuck = 0;
+ path_last_x = pl.x, path_last_y = pl.y;
+ uint32_t k = 0;
+ if (dx > 1) k |= K_RIGHT;
+ if (dx < -1) k |= K_LEFT;
+ if (dy > 1) k |= K_DOWN;
+ if (dy < -1) k |= K_UP;
+ return k;
+}
+
+static uint32_t key_bit(const char *s) {
+ static const struct { const char *n; uint32_t k; } keys[] = {
+ {"left", K_LEFT}, {"right", K_RIGHT}, {"up", K_UP}, {"down", K_DOWN}, {"z", K_Z}, {"x", K_X}, {"c", K_C},
+ {"home", K_HOME}};
+ for (size_t i = 0; i < sizeof keys / sizeof keys[0]; i++)
+ if (!strcmp(s, keys[i].n)) return keys[i].k;
+ fprintf(stderr, "unknown key %s\n", s);
+ exit(2);
+}
+
+static void parse_keys(const char *spec) {
+ char buf[65536];
+ snprintf(buf, sizeof buf, "%s", spec);
+ for (char *t = strtok(buf, ","); t; t = strtok(NULL, ",")) {
+ int a, b;
+ char k[32];
+ if (sscanf(t, "%d-%d:%31s", &a, &b, k) == 3) holds[nholds++] = (Hold){a, b, key_bit(k)};
+ else if (sscanf(t, "%d:%31s", &a, k) == 2) holds[nholds++] = (Hold){a, a, key_bit(k)};
+ else fprintf(stderr, "bad key %s\n", t), exit(2);
+ }
+}
+
+int main(int argc, char **argv) {
+ const char *out = "build/play", *saves = NULL, *shots = "";
+ int frames = 120, room = -1, ax = 0, ay = 0, battle = -1;
+ const char *name = NULL;
+ int nflags = 0, fl[64][2];
+ bool trace = false, coll = false;
+ for (int i = 1; i < argc; i++) {
+ if (!strcmp(argv[i], "--frames") && i + 1 < argc) frames = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--keys") && i + 1 < argc) parse_keys(argv[++i]);
+ else if (!strcmp(argv[i], "--path") && i + 1 < argc) snprintf(path_buf, sizeof path_buf, "%s", argv[++i]), path_at = path_buf;
+ else if (!strcmp(argv[i], "--shots") && i + 1 < argc) shots = argv[++i];
+ else if (!strcmp(argv[i], "--out") && i + 1 < argc) out = argv[++i];
+ else if (!strcmp(argv[i], "--saves") && i + 1 < argc) saves = argv[++i];
+ else if (!strcmp(argv[i], "--room") && i + 1 < argc) room = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--at") && i + 1 < argc) sscanf(argv[++i], "%d,%d", &ax, &ay);
+ else if (!strcmp(argv[i], "--name") && i + 1 < argc) name = argv[++i];
+ else if (!strcmp(argv[i], "--battle") && i + 1 < argc) battle = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--flag") && i + 1 < argc && nflags < 64) {
+ sscanf(argv[++i], "%d=%d", &fl[nflags][0], &fl[nflags][1]);
+ nflags++;
+ } else if (!strcmp(argv[i], "--trace")) trace = true;
+ else if (!strcmp(argv[i], "--coll")) coll = true;
+ else fprintf(stderr, "unknown option %s\n", argv[i]), exit(2);
+ }
+ mkdir(out, 0755);
+ char sd[512];
+ snprintf(sd, sizeof sd, "%s/saves", out);
+ if (!saves) saves = sd;
+ mkdir(saves, 0755);
+ host_save_dir(saves);
+ ut_bin = ut_data;
+ game_init();
+ if (room >= 0 || name) {
+ game_new(name ? name : "Frisk");
+ if (room >= 0) {
+ if (!ax && !ay) {
+ RoomInfo ri;
+ room_info(room, &ri);
+ ax = ri.x + ri.w / 2 - 10, ay = ri.y + ri.h / 2 - 15;
+ }
+ world_enter(room, ax, ay, DIR_DOWN);
+ }
+ }
+ for (int i = 0; i < nflags; i++) set_flag(fl[i][0], fl[i][1]);
+ if (battle >= 0) battle_start(battle);
+ bool all = !strcmp(shots, "all");
+ for (int f = 0; f < frames && g_running; f++) {
+ uint32_t k = 0;
+ for (int i = 0; i < nholds; i++)
+ if (f >= holds[i].a && f <= holds[i].b) k |= holds[i].k;
+ if (!k) k = path_keys(f);
+ host_keys = k;
+ host_time += 33;
+ game_frame(k);
+ game_draw();
+ if (trace) printf("%d mode %d room %d frisk %d,%d cam %d,%d hp %d\n", f, g_mode, g_room, pl.x, pl.y, cam_x, cam_y, sv.hp);
+ char want[16];
+ snprintf(want, sizeof want, "%d", f);
+ bool shoot = all;
+ if (!shoot) {
+ const char *p = shots;
+ size_t n = strlen(want);
+ while ((p = strstr(p, want))) {
+ if ((p == shots || p[-1] == ',') && (p[n] == ',' || !p[n])) {
+ shoot = true;
+ break;
+ }
+ p += n;
+ }
+ }
+ if (shoot && coll && world_room_info()) {
+ /* the walkable cells tinted green, the others red */
+ const RoomInfo *r = world_room_info();
+ for (int y = 0; y < SCREEN_H; y++)
+ for (int x = 0; x < SCREEN_W; x++) {
+ int wx = x + cam_x, wy = y + cam_y, cx = (wx - r->x) >> 2, cy = (wy - r->y) >> 2;
+ if (wx < r->x || wy < r->y || cx >= r->cw || cy >= r->ch) continue;
+ bool w = r->coll[cy * ((r->cw + 7) >> 3) + (cx >> 3)] >> (cx & 7) & 1;
+ uint16_t c = host_fb[y * SCREEN_W + x];
+ host_fb[y * SCREEN_W + x] = w ? (uint16_t)((c >> 1 & 0x7BEF) | 0x0400) : (uint16_t)((c >> 1 & 0x7BEF) | 0x8000);
+ }
+ }
+ if (shoot) {
+ char path[600];
+ snprintf(path, sizeof path, "%s/shot_%d.ppm", out, f);
+ host_shot(path);
+ }
+ }
+ if (gfx_dropped) printf("dropped %d draw commands\n", gfx_dropped);
+ return 0;
+}
diff --git a/games/undertale/tools/fetch.py b/games/undertale/tools/fetch.py
new file mode 100644
index 00000000..708a6fba
--- /dev/null
+++ b/games/undertale/tools/fetch.py
@@ -0,0 +1,134 @@
+#!/usr/bin/env python3
+"""Gathers the public material the pack is made from, into REF (not committed):
+
+ python3 -I tools/fetch.py REF
+
+- REF/wiki/maps/*.png: the Undertale Wiki's maps of each area (undertale.wiki, Category:Maps): every room,
+ one pixel for one, laid out as in the game
+- REF/wiki/sprites/*: the wiki's sprite files (Category:Overworld sprites, Battle sprites, Face sprites,
+ Sprites, Item files), as their own names
+- REF/wiki/pages/*.txt: the wiki's pages (their wikitext) that the game's texts are checked against
+- REF/demo/: the free demo from undertale.com (its Mac build keeps its sprites and backgrounds as PNG files)
+- REF/fonts/: Pixel Operator (CC0), by Jayvee Enaguas, once called 8-bit Operator: the font the game credits
+
+Files already there are kept: run it again to fetch only what is missing."""
+import json
+import os
+import sys
+import time
+import urllib.parse
+import urllib.request
+import zipfile
+
+API = "https://undertale.wiki/api.php"
+UA = {"User-Agent": "NumPlay-Undertale/1.0 (fan port for the NumWorks calculator; one-time asset fetch)"}
+CATEGORIES = {
+ "maps": ["Maps"],
+ "sprites": ["Overworld_sprites", "Battle_sprites", "Face_sprites", "Sprites", "Item_files", "Location_files"],
+}
+PAGES = ["Ruins", "Ruins/Puzzles", "Toriel", "Toriel/In_battle", "Toriel's_Home", "Flowey", "Napstablook",
+ "Cell_Phone/Toriel", "SAVE_Point", "Froggit", "Whimsun", "Moldsmal", "Loox", "Vegetoid", "Migosp",
+ "Dummy", "Froggit_NPC", "Spider_Bake_Sale", "Items", "Monster_Candy", "Spider_Donut", "Spider_Cider",
+ "Butterscotch_Pie", "Snail_Pie", "Toy_Knife", "Faded_Ribbon", "Bandage", "Stick", "LOVE", "EXP",
+ "HP", "AT", "DF", "Stats", "FIGHT", "ACT", "MERCY", "ITEM", "Flowey/In_battle", "Napstablook/In_battle",
+ "Encounter", "Home", "Annoying_Dog", "Rock", "Mouse", "Golden_flower", "Chara", "Frisk", "Name",
+ "Item", "Consumables", "Weapons", "Armor", "Cell_Phone", "Intro", "Game_Over", "Damage", "Monster_Candy",
+ "Toriel's_Home", "Blue_SOUL", "Bullet_board", "Spare", "Flee", "Gold", "Save"]
+DEMO = {
+ "MacUnderTale.zip": "https://thisisatestofthevideogamedeliverysystem.sfo2.digitaloceanspaces.com/game/MacUnderTale.zip",
+}
+FONT = ("pixel_operator.zip", "https://dl.dafont.com/dl/?f=pixel_operator")
+
+
+def get(url, tries=4):
+ for t in range(tries):
+ try:
+ with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=60) as r:
+ return r.read()
+ except Exception as e: # network hiccups: wait and try again
+ if t == tries - 1:
+ raise
+ print(" retry", url, e)
+ time.sleep(2 ** (t + 1))
+
+
+def api(**q):
+ q["format"] = "json"
+ return json.loads(get(API + "?" + urllib.parse.urlencode(q)))
+
+
+def category_files(cat):
+ out, cont = [], {}
+ while True:
+ d = api(action="query", list="categorymembers", cmtitle="Category:" + cat, cmlimit=500, cmtype="file", **cont)
+ out += [m["title"] for m in d["query"]["categorymembers"]]
+ if "continue" not in d:
+ return out
+ cont = {"cmcontinue": d["continue"]["cmcontinue"]}
+
+
+def file_url(title):
+ d = api(action="query", prop="imageinfo", iiprop="url", titles=title)
+ for p in d["query"]["pages"].values():
+ if "imageinfo" in p:
+ return p["imageinfo"][0]["url"].split("?")[0]
+ return None
+
+
+def save(path, data):
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path + ".part", "wb") as f:
+ f.write(data)
+ os.replace(path + ".part", path)
+
+
+def main():
+ if len(sys.argv) != 2:
+ sys.exit(__doc__)
+ ref = sys.argv[1]
+ for kind, cats in CATEGORIES.items():
+ for cat in cats:
+ for title in category_files(cat):
+ name = title.split(":", 1)[1].replace(" ", "_")
+ path = os.path.join(ref, "wiki", kind, name)
+ if os.path.exists(path):
+ continue
+ url = file_url(title)
+ if url:
+ print(kind, name)
+ save(path, get(url))
+ for page in PAGES:
+ path = os.path.join(ref, "wiki", "pages", page.replace("/", "__") + ".txt")
+ if os.path.exists(path):
+ continue
+ d = api(action="parse", page=page.replace("_", " "), prop="wikitext", redirects=1)
+ if "parse" in d:
+ print("page", page)
+ save(path, d["parse"]["wikitext"]["*"].encode())
+ for name, url in DEMO.items():
+ path = os.path.join(ref, "demo", name)
+ if not os.path.exists(path):
+ print("demo", name)
+ save(path, get(url))
+ out = os.path.join(ref, "demo", "mac")
+ if not os.path.exists(out):
+ with zipfile.ZipFile(path) as z:
+ for m in z.namelist():
+ if "/MacOS/sprites/" in m or "/MacOS/bgs/" in m or m.endswith("_manifest.txt"):
+ if m.startswith("__MACOSX") or m.endswith("/"):
+ continue
+ save(os.path.join(out, *m.split("/MacOS/")[1].split("/")), z.read(m))
+ path = os.path.join(ref, "fonts", FONT[0])
+ if not os.path.exists(path):
+ print("font", FONT[0])
+ save(path, get(FONT[1]))
+ with zipfile.ZipFile(path) as z:
+ for m in z.namelist():
+ if m.endswith(".ttf") or m.endswith(".txt"):
+ dst = os.path.join(ref, "fonts", os.path.basename(m))
+ if not os.path.exists(dst):
+ save(dst, z.read(m))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/games/undertale/tools/pack.py b/games/undertale/tools/pack.py
new file mode 100644
index 00000000..0b03f50f
--- /dev/null
+++ b/games/undertale/tools/pack.py
@@ -0,0 +1,468 @@
+#!/usr/bin/env python3
+"""Undertale's pictures, rooms and fonts -> src/data.bin + src/data.h.
+
+ python3 -I tools/pack.py REF (REF: the folder tools/fetch.py filled)
+
+data.bin: "UTD1", the number of sections, their offsets, then the sections (SEC_* in data.h):
+- SPRITES: for each sprite (SPR_*) its first frame and its number of frames (u16, u16)
+- FRAMES: each frame: w, h, origin x, y (u16, u16, s16, s16), bpp, colours (u8, u8), the colours (RGB565),
+ each row's offset (u16) from the rows' data, then the rows: runs of (skip, length, length pixels of bpp bits,
+ lowest first, the run padded to a byte), until the row's width
+- TILES: the areas' 20 x 20 tiles: bpp (0: one colour), colours, the colours (RGB565), 400 pixels of bpp bits
+- ROOMS: 32 bytes each (res.c room_info): the room's rectangle on its area's map, its tile grid and
+ collision map (4-pixel cells, 1 walkable), its area, flags and name
+- GRID, COLL: the rooms' tile ids (u16, 0xFFFF none) and collision bits
+- FONTS: height, first character, count, flags, then 8 bytes a glyph (advance, w, h, ox, oy, 0,
+ bitmap offset u16) and the bitmaps (rows of whole bytes, highest bit first)
+- STRINGS: the room names and other texts the data refers to
+- DOORS: for each room its first door and how many (u16, u16), then the doors: 16 bytes each (x, y, w, h on
+ the map, the room it leads to, where Frisk's top-left lands, the way he faces)"""
+import os
+import struct
+import sys
+
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont, ImageSequence
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, HERE)
+import rooms as R # noqa: E402
+import sprites as S # noqa: E402
+
+OUT_BIN = os.path.join(HERE, "..", "src", "data.bin")
+OUT_H = os.path.join(HERE, "..", "src", "data.h")
+SECTIONS = ["SPRITES", "FRAMES", "TILES", "ROOMS", "GRID", "COLL", "FONTS", "STRINGS", "DOORS"]
+
+
+def rgb565(r, g, b):
+ r, g, b = int(r), int(g), int(b)
+ return ((r * 31 + 127) // 255) << 11 | ((g * 63 + 127) // 255) << 5 | ((b * 31 + 127) // 255)
+
+
+class Strings:
+ def __init__(self):
+ self.list, self.ids = [], {}
+
+ def add(self, s):
+ if s not in self.ids:
+ self.ids[s] = len(self.list)
+ self.list.append(s)
+ return self.ids[s]
+
+ def blob(self):
+ out, offs = bytearray(), []
+ base = 4 + 4 * len(self.list)
+ for s in self.list:
+ offs.append(base + len(out))
+ out += s.encode("latin-1") + b"\0"
+ return struct.pack("<I", len(self.list)) + b"".join(struct.pack("<I", o) for o in offs) + bytes(out)
+
+
+def table(entries):
+ """u32 count, u32 offsets (from the section's start), then the entries"""
+ out, offs = bytearray(), []
+ base = 4 + 4 * len(entries)
+ for e in entries:
+ while (base + len(out)) % 2:
+ out.append(0)
+ offs.append(base + len(out))
+ out += e
+ return struct.pack("<I", len(entries)) + b"".join(struct.pack("<I", o) for o in offs) + bytes(out)
+
+
+def bits_pack(values, bpp):
+ """values (ints < 2**bpp), lowest bits first"""
+ out = bytearray((len(values) * bpp + 7) // 8)
+ for k, v in enumerate(values):
+ b = k * bpp
+ out[b >> 3] |= v << (b & 7)
+ return out
+
+
+def bpp_for(n):
+ return 1 if n <= 2 else 2 if n <= 4 else 4 if n <= 16 else 8
+
+
+# ------------------------------------------------------------------ frames
+def encode_frame(img, ox, oy):
+ """an RGBA image -> the frame's bytes (row RLE)"""
+ a = np.array(img.convert("RGBA"))
+ h, w = a.shape[:2]
+ opaque = a[:, :, 3] >= 128
+ cols = {}
+ for c in map(tuple, a[opaque][:, :3]):
+ k = rgb565(*c)
+ cols[k] = cols.get(k, 0) + 1
+ pal = sorted(cols, key=lambda k: -cols[k])
+ if len(pal) > 255:
+ raise ValueError("a frame with more than 255 colours")
+ index = {k: i for i, k in enumerate(pal)}
+ bpp = bpp_for(max(len(pal), 1))
+ rows, data = [], bytearray()
+ for y in range(h):
+ rows.append(len(data))
+ x = 0
+ while x < w:
+ skip = 0
+ while x < w and not opaque[y, x] and skip < 255:
+ x += 1
+ skip += 1
+ run = []
+ while x < w and opaque[y, x] and len(run) < 255:
+ run.append(index[rgb565(*a[y, x, :3])])
+ x += 1
+ data += bytes([skip, len(run)]) + bits_pack(run, bpp)
+ if len(data) > 0xFFFF:
+ raise ValueError("a frame too big")
+ head = struct.pack("<HHhhBB", w, h, ox, oy, bpp, len(pal)) + b"".join(struct.pack("<H", k) for k in pal)
+ return head + b"".join(struct.pack("<H", r) for r in rows) + bytes(data)
+
+
+def halve(img):
+ """a sprite the wiki shows at twice the game's size -> the game's size (the phase where 2 x 2 blocks agree)"""
+ a = np.array(img.convert("RGBA")).astype(np.int32)
+ h, w = a.shape[:2]
+ best = None
+ for py in (0, 1):
+ for px in (0, 1):
+ b = a[py:py + (h - py) // 2 * 2, px:px + (w - px) // 2 * 2]
+ if not b.size:
+ continue
+ q = b.reshape(b.shape[0] // 2, 2, b.shape[1] // 2, 2, 4)
+ err = np.abs(q - q[:, :1, :, :1]).sum()
+ if best is None or err < best[0]:
+ best = (err, py, px)
+ _, py, px = best
+ b = a[py::2, px::2]
+ return Image.fromarray(b.astype(np.uint8), "RGBA")
+
+
+def load_frames(ref, src):
+ """'demo:spr_name' (all its numbered frames), 'wiki:File.png' or .gif (all frames, halved), 'png:path'"""
+ kind, name = src.split(":", 1)
+ if kind == "demo":
+ d = os.path.join(ref, "demo", "mac", "sprites")
+ out, k = [], 0
+ while os.path.exists(os.path.join(d, "%s %d.png" % (name, k))):
+ out.append(Image.open(os.path.join(d, "%s %d.png" % (name, k))).convert("RGBA"))
+ k += 1
+ if not out:
+ raise FileNotFoundError(src)
+ return out
+ if kind == "demobg":
+ return [Image.open(os.path.join(ref, "demo", "mac", "bgs", name + ".png")).convert("RGBA")]
+ if kind in ("wiki", "wiki1"):
+ im = Image.open(os.path.join(ref, "wiki", "sprites", name))
+ frames = []
+ for fr in ImageSequence.Iterator(im):
+ f = fr.convert("RGBA")
+ frames.append(halve(f) if kind == "wiki" else f)
+ return frames
+ if kind == "png":
+ return [Image.open(os.path.join(HERE, name)).convert("RGBA")]
+ raise ValueError(src)
+
+
+def crop_frames(frames):
+ """all frames cropped to the union of their opaque pixels; returns the frames and the crop's top-left"""
+ box = None
+ for f in frames:
+ b = f.getchannel("A").point(lambda v: 255 if v >= 128 else 0).getbbox()
+ if b:
+ box = b if box is None else (min(box[0], b[0]), min(box[1], b[1]), max(box[2], b[2]), max(box[3], b[3]))
+ if box is None:
+ return frames, 0, 0
+ return [f.crop(box) for f in frames], box[0], box[1]
+
+
+# ------------------------------------------------------------------ fonts
+def make_font(ref, spec):
+ path = os.path.join(ref, "fonts", spec["ttf"]) if not spec["ttf"].startswith("/") else spec["ttf"]
+ font = ImageFont.truetype(path, spec["size"])
+ first, last = 32, 127
+ glyphs, bits = bytearray(), bytearray()
+ asc = spec.get("ascent", spec["size"])
+ for c in range(first, last):
+ ch = chr(c) if c < 127 else "♥"
+ if c == 127 and "heart" not in spec:
+ ch = "?"
+ im = Image.new("L", (spec["size"] * 3, spec["size"] * 3), 0)
+ d = ImageDraw.Draw(im)
+ d.fontmode = "1"
+ d.text((spec["size"], spec["size"]), ch, font=font, fill=255)
+ adv = int(round(font.getlength(ch))) if "advance" not in spec else spec["advance"]
+ bb = im.getbbox()
+ if bb is None:
+ glyphs += struct.pack("<BBBbbBH", adv, 0, 0, 0, 0, 0, len(bits))
+ continue
+ g = np.array(im.crop(bb)) >= 128
+ gh, gw = g.shape
+ ox, oy = bb[0] - spec["size"], bb[1] - spec["size"] - (spec["size"] - asc)
+ off = len(bits)
+ for row in g:
+ rb = bytearray((gw + 7) // 8)
+ for x, v in enumerate(row):
+ if v:
+ rb[x >> 3] |= 0x80 >> (x & 7)
+ bits += rb
+ glyphs += struct.pack("<BBBbbBH", adv, gw, gh, ox, oy, 0, off)
+ return struct.pack("<BBBB", spec["height"], first, last - first, 0) + bytes(glyphs) + bytes(bits)
+
+
+# ------------------------------------------------------------------ areas and rooms
+class Area:
+ """an area's map: its colours, as indices into a palette, and its tiles"""
+
+ def __init__(self, ref, spec):
+ im = Image.open(os.path.join(ref, "wiki", "maps", spec["map"]))
+ if im.mode != "P":
+ im = im.convert("RGB").quantize(256, method=Image.Quantize.MAXCOVERAGE)
+ self.idx = np.array(im)
+ p = im.getpalette()
+ self.rgb = [tuple(p[3 * i:3 * i + 3]) for i in range(len(p) // 3)]
+ self.transparent = im.info.get("transparency", None)
+ if isinstance(self.transparent, bytes):
+ self.transparent = None
+ self.spec = spec
+ for patch in spec.get("patches", []):
+ self.patch(patch)
+
+ def black_index(self):
+ for i, c in enumerate(self.rgb):
+ if c == (0, 0, 0):
+ return i
+ return None
+
+ def patch(self, p):
+ """changes to the map, before rooms are cut from it: ('fill', x, y, w, h, (r, g, b)),
+ ('copy', sx, sy, w, h, dx, dy) or ('mirror', ...) the same, flipped left to right"""
+ if p[0] == "fill":
+ _, x, y, w, h, c = p
+ self.idx[y:y + h, x:x + w] = self.color_index(c)
+ elif p[0] == "copy":
+ _, sx, sy, w, h, dx, dy = p
+ self.idx[dy:dy + h, dx:dx + w] = self.idx[sy:sy + h, sx:sx + w].copy()
+ elif p[0] == "mirror":
+ _, sx, sy, w, h, dx, dy = p
+ self.idx[dy:dy + h, dx:dx + w] = self.idx[sy:sy + h, sx:sx + w][:, ::-1].copy()
+ else:
+ raise ValueError(p)
+
+ def color_index(self, c):
+ for i, k in enumerate(self.rgb):
+ if k == tuple(c) and i != self.transparent:
+ return i
+ raise ValueError("colour %s not in the map" % (c,))
+
+
+def room_pixels(area, r):
+ """the room's rectangle of the map, as RGB565 per pixel; outside the map and its clear pixels black"""
+ x, y, w, h = r["rect"]
+ H, W = area.idx.shape
+ out = np.zeros((h, w), np.int32)
+ xs0, ys0, xs1, ys1 = max(x, 0), max(y, 0), min(x + w, W), min(y + h, H)
+ sub = area.idx[ys0:ys1, xs0:xs1]
+ lut = np.array([rgb565(*c) for c in area.rgb] + [0] * (256 - len(area.rgb)), np.int32)
+ if area.transparent is not None:
+ lut[area.transparent] = 0
+ out[ys0 - y:ys1 - y, xs0 - x:xs1 - x] = lut[sub]
+ return out, sub, (xs0 - x, ys0 - y)
+
+
+def collision(area, r):
+ """4-pixel cells over the room: walkable where the floor's colours fill at least half the cell and
+ inside one of its floor rectangles (all of it if it has none), then its own fixes"""
+ x, y, w, h = r["rect"]
+ cw, ch = (w + 3) // 4, (h + 3) // 4
+ H, W = area.idx.shape
+ walk_idx = set()
+ for c in area.spec["floor"] + r.get("floor_colors", []):
+ for i, k in enumerate(area.rgb):
+ if k == tuple(c) and i != area.transparent:
+ walk_idx.add(i)
+ sub = np.zeros((ch * 4, cw * 4), bool)
+ xs0, ys0, xs1, ys1 = max(x, 0), max(y, 0), min(x + w, W), min(y + h, H)
+ m = np.isin(area.idx[ys0:ys1, xs0:xs1], list(walk_idx))
+ sub[ys0 - y:ys1 - y, xs0 - x:xs1 - x] = m
+ cells = sub.reshape(ch, 4, cw, 4).mean(axis=(1, 3)) >= 0.5
+ # walls drawn in the floor's colours give themselves away by their lines: a cell is floor only with no
+ # other colour within `margin` pixels of it
+ margin = r.get("margin", area.spec.get("margin", 0))
+ if margin:
+ other = ~sub
+ pad = np.pad(other, margin, constant_values=False)
+ near = np.zeros_like(other)
+ for dy in range(2 * margin + 1):
+ for dx in range(2 * margin + 1):
+ near |= pad[dy:dy + other.shape[0], dx:dx + other.shape[1]]
+ cells &= ~near.reshape(ch, 4, cw, 4).any(axis=(1, 3))
+ if r.get("floor_rects"):
+ keep = np.zeros_like(cells)
+ for fx, fy, fw, fh in r["floor_rects"]:
+ keep[max(0, (fy - y) // 4):max(0, (fy + fh - y + 3) // 4), max(0, (fx - x) // 4):max(0, (fx + fw - x + 3) // 4)] = True
+ cells &= keep
+ for kind, fx, fy, fw, fh in r.get("fix", []):
+ cells[max(0, (fy - y) // 4):max(0, (fy + fh - y + 3) // 4), max(0, (fx - x) // 4):max(0, (fx + fw - x + 3) // 4)] = kind == "walk"
+ out = bytearray()
+ for row in cells:
+ rb = bytearray((cw + 7) // 8)
+ for i, v in enumerate(row):
+ if v:
+ rb[i >> 3] |= 1 << (i & 7)
+ out += rb
+ return out, cw, ch
+
+
+class TileSet:
+ def __init__(self):
+ self.ids, self.blobs = {}, []
+ self.blobs_size = 0
+
+ def add(self, block):
+ """a 20 x 20 block of RGB565 values -> its tile id"""
+ key = block.tobytes()
+ if key in self.ids:
+ return self.ids[key]
+ flat = block.reshape(-1)
+ cols, counts = np.unique(flat, return_counts=True)
+ order = [int(c) for c, _ in sorted(zip(cols, counts), key=lambda t: -t[1])]
+ if len(order) == 1:
+ blob = struct.pack("<BBH", 0, 1, order[0])
+ else:
+ index = {c: i for i, c in enumerate(order)}
+ bpp = bpp_for(len(order))
+ blob = struct.pack("<BB", bpp, len(order)) + b"".join(struct.pack("<H", c) for c in order)
+ blob += bits_pack([index[int(v)] for v in flat], bpp)
+ self.ids[key] = len(self.blobs)
+ self.blobs.append(blob)
+ return self.ids[key]
+
+
+def pack_room(area, r, tiles, strings):
+ x, y, w, h = r["rect"]
+ px, _, _ = room_pixels(area, r)
+ # the grid: 20-pixel tiles aligned on the map's own 20-pixel grid
+ gx, gy = x // 20 * 20, y // 20 * 20
+ gx1, gy1 = (x + w + 19) // 20 * 20, (y + h + 19) // 20 * 20
+ cols, rows = (gx1 - gx) // 20, (gy1 - gy) // 20
+ big = np.zeros((rows * 20, cols * 20), np.int32)
+ big[y - gy:y - gy + h, x - gx:x - gx + w] = px
+ grid = bytearray()
+ for ty in range(rows):
+ for tx in range(cols):
+ block = big[ty * 20:ty * 20 + 20, tx * 20:tx * 20 + 20]
+ grid += struct.pack("<H", 0xFFFF if not block.any() else tiles.add(block.astype(np.uint16)))
+ coll, cw, ch = collision(area, r)
+ return dict(rect=(x, y, w, h), g=(gx, gy, cols, rows), grid=bytes(grid), coll=bytes(coll), cw=cw, ch=ch,
+ area=r["area_id"], flags=r.get("flags", 0), name=strings.add(r.get("title", "")))
+
+
+# ------------------------------------------------------------------ main
+def main():
+ if len(sys.argv) < 2:
+ sys.exit(__doc__)
+ ref = sys.argv[1]
+ strings = Strings()
+ strings.add("")
+ defines = []
+
+ # sprites
+ spr_entries, frames = [], []
+ for k, spec in enumerate(S.SPRITES):
+ name, src = spec[0], spec[1]
+ opts = spec[2] if len(spec) > 2 else {}
+ imgs = []
+ for s in (src if isinstance(src, list) else [src]):
+ imgs += load_frames(ref, s)
+ if "frames" in opts:
+ imgs = [imgs[i] for i in opts["frames"]]
+ if "scale" in opts:
+ imgs = [im.resize((im.width * opts["scale"], im.height * opts["scale"]), Image.NEAREST) for im in imgs]
+ w0, h0 = imgs[0].size
+ ox, oy = opts.get("origin", (0, 0))
+ if opts.get("center"):
+ ox, oy = w0 // 2, h0 // 2
+ if opts.get("feet"):
+ ox, oy = w0 // 2, h0
+ if not opts.get("keep"):
+ imgs, cx, cy = crop_frames(imgs)
+ ox, oy = ox - cx, oy - cy
+ spr_entries.append((len(frames), len(imgs)))
+ for im in imgs:
+ frames.append(encode_frame(im, ox, oy))
+ defines.append(("SPR_" + name.upper(), k))
+ sec_sprites = struct.pack("<I", len(spr_entries)) + b"".join(struct.pack("<HH", a, b) for a, b in spr_entries)
+ sec_frames = table(frames)
+
+ # areas and rooms
+ tiles = TileSet()
+ packed = []
+ for ai, aspec in enumerate(R.AREAS):
+ area = Area(ref, aspec)
+ defines.append(("AREA_" + aspec["name"].upper(), ai))
+ for r in R.ROOMS:
+ if r["area"] != aspec["name"]:
+ continue
+ r["area_id"] = ai
+ packed.append((r, pack_room(area, r, tiles, strings)))
+ room_tab, grid_blob, coll_blob = bytearray(), bytearray(), bytearray()
+ for k, (r, p) in enumerate(packed):
+ defines.append(("ROOM_" + r["name"].upper(), k))
+ x, y, w, h = p["rect"]
+ gx, gy, cols, rows = p["g"]
+ room_tab += struct.pack("<hhhhhhHHIIHHBBH", x, y, w, h, gx, gy, cols, rows, len(grid_blob), len(coll_blob),
+ p["cw"], p["ch"], p["area"], p["flags"], p["name"])
+ grid_blob += p["grid"]
+ coll_blob += p["coll"]
+ while len(coll_blob) % 2:
+ coll_blob.append(0)
+ sec_rooms = struct.pack("<I", len(packed)) + bytes(room_tab)
+ names = {r["name"]: k for k, (r, _) in enumerate(packed)}
+ dirs = {"down": 0, "up": 1, "left": 2, "right": 3}
+ door_index, doors = bytearray(), bytearray()
+ ndoors = 0
+ for r, _ in packed:
+ ds = r.get("doors", [])
+ door_index += struct.pack("<HH", ndoors, len(ds))
+ for (dx, dy, dw, dh), to, (tx, ty), d in ds:
+ doors += struct.pack("<hhhhHhhH", dx, dy, dw, dh, names[to], tx, ty, dirs[d])
+ ndoors += 1
+ sec_doors = bytes(door_index) + bytes(doors)
+ sec_tiles = table(tiles.blobs)
+
+ # fonts
+ fonts = []
+ for k, spec in enumerate(S.FONTS):
+ fonts.append(make_font(ref, spec))
+ defines.append(("FONT_" + spec["name"].upper(), k))
+ sec_fonts = table(fonts)
+
+ sections = [sec_sprites, sec_frames, sec_tiles, sec_rooms, bytes(grid_blob), bytes(coll_blob), sec_fonts,
+ strings.blob(), sec_doors]
+ head = b"UTD1" + struct.pack("<I", len(sections))
+ offs, body = [], bytearray()
+ base = len(head) + 4 * len(sections)
+ for s in sections:
+ while (base + len(body)) % 4:
+ body.append(0)
+ offs.append(base + len(body))
+ body += s
+ blob = head + b"".join(struct.pack("<I", o) for o in offs) + bytes(body)
+ with open(OUT_BIN, "wb") as f:
+ f.write(blob)
+
+ with open(OUT_H, "w") as f:
+ f.write("/* made by tools/pack.py: the contents of data.bin */\n#ifndef UT_DATA_H\n#define UT_DATA_H\n")
+ for i, s in enumerate(SECTIONS):
+ f.write("#define SEC_%s %d\n" % (s, i))
+ for n, v in defines:
+ f.write("#define %s %d\n" % (n, v))
+ f.write("#define NUM_SPRITES %d\n#define NUM_ROOMS %d\n#define NUM_FONTS %d\n" % (len(spr_entries), len(packed), len(fonts)))
+ f.write("#endif\n")
+ sizes = dict(zip(SECTIONS, map(len, sections)))
+ print("data.bin: %d bytes (%s); %d tiles, %d frames, %d rooms" % (
+ len(blob), ", ".join("%s %d" % kv for kv in sizes.items()), len(tiles.blobs), len(frames), len(packed)))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/games/undertale/tools/rooms.py b/games/undertale/tools/rooms.py
new file mode 100644
index 00000000..69eaf4a1
--- /dev/null
+++ b/games/undertale/tools/rooms.py
@@ -0,0 +1,102 @@
+"""The game's areas and rooms, cut from the wiki's maps (tools/fetch.py).
+
+An area is one map: every room of the area, one pixel for one, laid out as in the game. A room is a
+rectangle of it (rect: x, y, w, h on the map); its rooms touch where their doors are, so walking out of one
+walks into the next (world.c). Walkable: the area's floor colours (and the room's floor_colors), inside the
+room's floor_rects if it has some (walls of the floor's colour are left out that way), then its fixes
+("walk" or "wall" rectangles). Patches change the map first (objects drawn into it, like the rocks, are
+taken out: the game draws them).
+
+Rooms are named as the game names them (room_ruins1 is ruins1)."""
+
+RUINS_FLOOR = [
+ (163, 73, 164), (185, 98, 185), # the floor and its paths
+ (128, 17, 17), (232, 35, 19), (233, 77, 42), (123, 24, 19), (121, 18, 0), (64, 0, 0), (157, 32, 0), # red leaves
+ (58, 57, 72), (95, 94, 119), (200, 194, 226), (34, 177, 76), # the landing: stone, its rings, grass
+ (249, 240, 0), (219, 177, 0), (124, 106, 0), # golden flowers
+ (167, 112, 82), (112, 66, 56), (169, 85, 38), (105, 58, 27), # bridges
+]
+
+AREAS = [
+ dict(name="ruins", map="Ruins_map.png", floor=RUINS_FLOOR, margin=3, patches=[
+ ("mirror", 95, 5988, 27, 60, 178, 5988), # Toriel tending the flowers (the game's last pages)
+ ("fill", 509, 5768, 23, 12, (0, 0, 0)), ("fill", 509, 5780, 23, 11, (34, 177, 76)), # Flowey
+ ]),
+]
+
+ROOMS = [
+ # the landing: the bed of golden flowers, a hallway, the Delta Rune arch
+ dict(name="area1", area="ruins", rect=(0, 5900, 680, 260), title="Ruins", margin=0,
+ fix=[("walk", 600, 6040, 36, 22)],
+ doors=[((602, 6040, 32, 8), "area1_2", (510, 5858), "up")]),
+ # Flowey's patch of grass in the dark (the floor is black: all of it is walked on), the purple arch north
+ dict(name="area1_2", area="ruins", rect=(360, 5560, 320, 340), title="Ruins", margin=0,
+ floor_colors=[(0, 0, 0)], floor_rects=[(420, 5640, 200, 260), (500, 5560, 40, 80)],
+ doors=[((420, 5894, 200, 6), "area1", (608, 6030), "down")]),
+ # the entrance: two staircases, the red leaves, the first SAVE Point
+ dict(name="ruins1", area="ruins", rect=(360, 5080, 320, 480), title="Ruins - Entrance"),
+ # the middle road puzzle: six switches on the floor and a lever
+ dict(name="ruins2", area="ruins", rect=(360, 4840, 320, 240), title="Ruins"),
+ # the switch room, with Toriel's labels; spikes at its end
+ dict(name="ruins3", area="ruins", rect=(360, 4600, 720, 240), title="Ruins"),
+ # the training dummy
+ dict(name="ruins4", area="ruins", rect=(1080, 4600, 320, 240), title="Ruins"),
+ # the blueprint and the spikes over the water
+ dict(name="ruins5", area="ruins", rect=(1100, 4340, 1180, 260), title="Ruins"),
+ # the long hallway: the independence test
+ dict(name="ruins6", area="ruins", rect=(2280, 4340, 2560, 240), title="Ruins"),
+ # the leaf pile, its SAVE Point, the first Froggit to talk
+ dict(name="ruins7", area="ruins", rect=(4840, 4360, 240, 440), title="Ruins - Leaf Pile"),
+ # the Monster Candy
+ dict(name="ruins7a", area="ruins", rect=(4860, 4100, 200, 260), title="Ruins"),
+ # the cracked floor and the room under it
+ dict(name="ruins8", area="ruins", rect=(5080, 4600, 410, 220), title="Ruins"),
+ dict(name="ruins8b", area="ruins", rect=(5140, 5020, 280, 200), title="Ruins"),
+ # the first rock puzzle
+ dict(name="ruins9", area="ruins", rect=(5490, 4600, 420, 220), title="Ruins"),
+ # the leaf puzzle: cracked floor above, the way through in leaves below
+ dict(name="ruins10", area="ruins", rect=(5910, 4600, 580, 320), title="Ruins"),
+ dict(name="ruins10b", area="ruins", rect=(5940, 5020, 540, 300), title="Ruins"),
+ # the second rock puzzle: the rock that won't move
+ dict(name="ruins11", area="ruins", rect=(6490, 4680, 560, 260), title="Ruins"),
+ # the mouse hole, its SAVE Point, the cheese
+ dict(name="ruins12", area="ruins", rect=(7050, 4720, 380, 200), title="Ruins - Mouse Hole"),
+ # Napstablook, pretending to sleep
+ dict(name="ruins13", area="ruins", rect=(7430, 4700, 260, 220), title="Ruins"),
+ # the Spider Bake Sale
+ dict(name="ruins14", area="ruins", rect=(7690, 4700, 340, 220), title="Ruins"),
+ # the Froggits' hall
+ dict(name="ruins15", area="ruins", rect=(7520, 4400, 540, 300), title="Ruins"),
+ # the one switch puzzle, and its six rooms under it
+ dict(name="ruins16", area="ruins", rect=(8060, 4480, 640, 280), title="Ruins"),
+ dict(name="ruins16a", area="ruins", rect=(8230, 4915, 160, 125), title="Ruins"),
+ dict(name="ruins16b", area="ruins", rect=(8410, 4915, 140, 125), title="Ruins"),
+ dict(name="ruins16c", area="ruins", rect=(8550, 4915, 140, 125), title="Ruins"),
+ dict(name="ruins16d", area="ruins", rect=(8230, 5040, 160, 120), title="Ruins"),
+ dict(name="ruins16e", area="ruins", rect=(8410, 5040, 140, 120), title="Ruins"),
+ dict(name="ruins16f", area="ruins", rect=(8550, 5040, 140, 120), title="Ruins"),
+ # the rotating rooms: the same room, turned; and the one a wrong switch drops Frisk in
+ dict(name="ruins17a", area="ruins", rect=(8700, 4500, 360, 400), title="Ruins"),
+ dict(name="ruins17b", area="ruins", rect=(8720, 4060, 340, 380), title="Ruins"),
+ dict(name="ruins17c", area="ruins", rect=(8380, 4000, 340, 440), title="Ruins"),
+ dict(name="ruins17d", area="ruins", rect=(8380, 3610, 320, 390), title="Ruins"),
+ dict(name="ruins17x", area="ruins", rect=(9140, 4540, 280, 160), title="Ruins"),
+ # the crossroads, the Froggit who saw Toriel, the balcony over Home
+ dict(name="ruins18", area="ruins", rect=(8700, 3460, 590, 370), title="Ruins"),
+ dict(name="ruins19", area="ruins", rect=(9290, 3620, 250, 200), title="Ruins"),
+ dict(name="ruins20", area="ruins", rect=(9300, 3360, 360, 260), title="Ruins"),
+ # Toriel's tree and her door
+ dict(name="ruins21", area="ruins", rect=(8860, 2920, 320, 540), title="Ruins - Home"),
+ # Toriel's home
+ dict(name="torhouse1", area="ruins", rect=(8860, 2660, 320, 260), title="Home"),
+ dict(name="torhouse2", area="ruins", rect=(8540, 2670, 320, 250), title="Home"),
+ dict(name="torkitchen", area="ruins", rect=(8540, 2500, 200, 170), title="Home"),
+ dict(name="torhouse3", area="ruins", rect=(9180, 2700, 760, 220), title="Home"),
+ dict(name="asrielroom", area="ruins", rect=(9200, 2460, 260, 230), title="Home"),
+ dict(name="torielroom", area="ruins", rect=(9510, 2430, 280, 260), title="Home"),
+ # the basement, to the end of the Ruins
+ dict(name="basement1", area="ruins", rect=(8860, 2220, 1260, 180), title="Ruins"),
+ dict(name="basement2", area="ruins", rect=(9930, 1960, 220, 260), title="Ruins"),
+ dict(name="basement3", area="ruins", rect=(9940, 300, 180, 1660), title="Ruins"),
+ dict(name="ruinsexit", area="ruins", rect=(9940, 0, 200, 300), title="Ruins - Exit"),
+]
diff --git a/games/undertale/tools/sprites.py b/games/undertale/tools/sprites.py
new file mode 100644
index 00000000..1891747b
--- /dev/null
+++ b/games/undertale/tools/sprites.py
@@ -0,0 +1,43 @@
+"""The sprites and fonts the pack holds.
+
+A sprite: (name, source or [sources], options). Sources (tools/pack.py load_frames):
+ demo:spr_x the free demo's sprite spr_x, all its frames (the game's size)
+ demobg:bg_x one of the demo's backgrounds
+ wiki:File.png a file of the Undertale Wiki, every frame of a GIF; the wiki shows sprites at twice the size,
+ halved here (wiki1: as it is)
+Options: origin (x, y) in the source's pixels, center (its middle), feet (the middle of its bottom),
+frames (which of them), keep (no crop to the opaque pixels)."""
+
+SPRITES = [
+ # Frisk walking: down and up 4 frames, left and right 2 (the game's own frames, from the demo)
+ ("frisk_d", "demo:spr_maincharad", {"origin": (0, 0), "keep": True}),
+ ("frisk_u", "demo:spr_maincharau", {"origin": (0, 0), "keep": True}),
+ ("frisk_l", "demo:spr_maincharal", {"origin": (0, 0), "keep": True}),
+ ("frisk_r", "demo:spr_maincharar", {"origin": (0, 0), "keep": True}),
+ ("toriel_d", "demo:spr_toriel_d", {"origin": (0, 0), "keep": True}),
+ ("toriel_u", "demo:spr_toriel_u", {"origin": (0, 0), "keep": True}),
+ ("toriel_l", "demo:spr_toriel_l", {"origin": (0, 0), "keep": True}),
+ ("toriel_r", "demo:spr_toriel_r", {"origin": (0, 0), "keep": True}),
+ ("savepoint", "demo:spr_savepoint", {"origin": (0, 0), "keep": True}),
+ ("flowey", "demo:spr_flowey", {"origin": (0, 0), "keep": True}),
+ ("heart", "demo:spr_heart", {"center": True, "keep": True}),
+] + [
+ # faces in the dialogue box (the demo's: a head, and Toriel's shoulders under it); 2 frames: talking
+ ("face_" + n, "demo:spr_face_" + n, {"keep": True}) for n in [
+ "torieltalk", "torieltalkside", "torielhappytalk", "torielwhat", "torielwhatside", "torielmad", "torielcold",
+ "torielsurprised", "torielembarrassed", "torielglasses", "torielrevengetalk", "torielscared", "torielblink",
+ "torielhappyblink", "torielbody", "sans", "sanschuckle", "sanswink", "papyrus", "papyrusevil",
+ "papyruslaugh", "papyrusmad", "papyrusside"]
+] + [
+ # Flowey's faces (his talks and his battle)
+ (n, "demo:spr_" + n, {"keep": True}) for n in [
+ "floweynice", "floweyniceside", "floweysassy", "floweyevil", "floweygrin", "floweyplain", "floweypissed",
+ "floweywink", "floweylaugh", "floweyhurt", "floweytoriel", "floweytoriel2", "floweysideshock"]
+]
+
+FONTS = [
+ # the dialogue's font: Pixel Operator Mono Bold, 8 pixels a letter
+ dict(name="main", ttf="PixelOperatorMono-Bold.ttf", size=16, height=12, advance=8, ascent=13),
+ # small text (the menu's numbers)
+ dict(name="small", ttf="PixelOperator8.ttf", size=8, height=8, ascent=8),
+]