Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
Hollow Knight: scenery renderer, room data tools, and the Knight running, jumping and attacking in King's Pass
Mason Chenbb775bfd17c3
diff --git a/games/hollowknight/.gitignore b/games/hollowknight/.gitignorenew file mode 100644index 00000000..2915254f--- /dev/null+++ b/games/hollowknight/.gitignore@@ -0,0 +1,5 @@+output/+build/+__pycache__/+tools/cache/+out_*/diff --git a/games/hollowknight/Makefile b/games/hollowknight/Makefilenew file mode 100644index 00000000..ee783404--- /dev/null+++ b/games/hollowknight/Makefile@@ -0,0 +1,62 @@+# Hollow Knight for the NumWorks calculator.+# make output/hollowknight.nwa+# make check link it like the calculator does (output/hollowknight.bin)+# make host build/play: the game on a computer, for tests and screenshots+# make test checks of the host build (tests/check.py)+# make data regenerate src/data.bin from the game (HOLLOWKNIGHT=<its Data folder>)+Q ?= @+CC = arm-none-eabi-gcc+NWLINK ?= npx --yes -- [email protected]+STRIP ?= arm-none-eabi-strip --strip-unneeded+BUILD_DIR = output+GAME = src/res.c src/tex.c src/room.c src/gfx.c src/phys.c src/anim.c src/hero.c src/camera.c src/game.c src/lzma/LzmaDec.c+SRC = $(GAME) src/plat_eadk.c src/main.c+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 data test+build: $(BUILD_DIR)/hollowknight.nwa++check: $(BUILD_DIR)/hollowknight.nwa+ $(Q) $(NWLINK) nwa-bin --ram-length 153676 $< $(BUILD_DIR)/hollowknight.bin+ @echo "BIN $(BUILD_DIR)/hollowknight.bin: $$(wc -c < $(BUILD_DIR)/hollowknight.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)/hollowknight.nwa: $(SRC) $(HEADERS) $(BUILD_DIR)/icon.o $(BUILD_DIR)/data.o+ @echo "LD $@"+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(SRC) $(BUILD_DIR)/data.o $(BUILD_DIR)/icon.o -lm -o $@+ $(Q) $(STRIP) $@+ $(Q) arm-none-eabi-size $@++$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)+ @echo "ICON $<"+ $(Q) $(NWLINK) png-icon-o $< $@++$(BUILD_DIR):+ $(Q) mkdir -p $@++HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -Isrc -DHOST+HOST_OUT ?= build/play+host: $(HOST_OUT)+$(HOST_OUT): $(GAME) src/plat_host.c tests/play.c $(HEADERS)+ $(Q) mkdir -p $(dir $@) build/host-saves+ $(Q) cc $(HOST_FLAGS) -fsanitize=address,undefined $(GAME) src/plat_host.c tests/play.c -lm -o $@+ @echo "HOST $@"++test: $(HOST_OUT)+ python3 tests/check.py $(HOST_OUT) src/data.bin++data:+ cd tools && python3 pack.py++clean:+ $(Q) rm -rf $(BUILD_DIR) builddiff --git a/games/hollowknight/src/anim.c b/games/hollowknight/src/anim.cnew file mode 100644index 00000000..f89f3828--- /dev/null+++ b/games/hollowknight/src/anim.c@@ -0,0 +1,166 @@+/* Sprite animations as 2D Toolkit plays them (tk2dSpriteAnimator), and sprite frames placed in the world. */+#include <math.h>+#include "hk.h"++enum { WRAP_LOOP, WRAP_LOOP_SECTION, WRAP_ONCE, WRAP_PING_PONG, WRAP_RANDOM_FRAME, WRAP_RANDOM_LOOP, WRAP_SINGLE };++typedef struct {+ uint16_t first, n;+ float fps;+ uint8_t wrap, loop;+ uint16_t pad;+} ClipRec;++static const ClipRec *clip_rec(int clip) { return (const ClipRec *)(const void *)(section(SEC_CLIP) + 4) + clip; }+static const uint16_t *clip_frames(const ClipRec *c) {+ return (const uint16_t *)(const void *)(section(SEC_CLIP) + 4 + sizeof(ClipRec) * rd32(section(SEC_CLIP))) + c->first;+}++const SpriteRec *sprite_rec(int id) { return (const SpriteRec *)(const void *)section(SEC_SPR) + id; }++float clip_duration(int clip) {+ const ClipRec *c = clip_rec(clip);+ return c->n / c->fps;+}+int clip_frames_count(int clip) { return clip_rec(clip)->n; }++static uint32_t rng = 0x9E3779B9u;+static int rand_below(int n) {+ rng ^= rng << 13, rng ^= rng >> 17, rng ^= rng << 5;+ return (int)(rng % (uint32_t)n);+}++/* shows frame f (and its event, as WarpClipToLocalTime does) */+static void warp(Anim *a, const ClipRec *c, float t) {+ a->time = t;+ int f = (int)t % c->n;+ a->frame = (int16_t)f;+ a->sprite = (int16_t)(clip_frames(c)[f] & 0x7FFF);+ if (clip_frames(c)[f] & 0x8000) a->events |= ANIM_TRIGGER;+}++void anim_play_from(Anim *a, int clip, float start) {+ const ClipRec *c = clip_rec(clip);+ if (!c->n) {+ a->events |= ANIM_DONE, a->playing = false;+ return;+ }+ if (start == 0 && a->playing && a->clip == clip) return; /* (already playing: goes on) */+ a->playing = true;+ a->clip = (int16_t)clip;+ a->fps = c->fps;+ if (c->wrap == WRAP_SINGLE) {+ warp(a, c, 0);+ a->playing = false;+ } else if (c->wrap == WRAP_RANDOM_FRAME || c->wrap == WRAP_RANDOM_LOOP) {+ warp(a, c, (float)rand_below(c->n));+ if (c->wrap == WRAP_RANDOM_FRAME) a->frame = -1, a->playing = false;+ } else {+ float t = start * a->fps;+ if (c->wrap == WRAP_ONCE && t >= a->fps * c->n) {+ warp(a, c, (float)(c->n - 1));+ a->playing = false;+ } else+ warp(a, c, t);+ }+}++void anim_play(Anim *a, int clip) { anim_play_from(a, clip, 0); }+void anim_play_from_frame(Anim *a, int clip, int frame) { anim_play_from(a, clip, (frame + 0.001f) / clip_rec(clip)->fps); }+bool anim_is_playing(const Anim *a, int clip) { return a->playing && a->clip == clip; }++/* the frames from prev (exclusive) to f (inclusive), their events */+static void events(Anim *a, const ClipRec *c, int prev, int f, int dir) {+ const uint16_t *fr = clip_frames(c);+ for (int i = prev + dir; dir > 0 ? i <= f : i >= f; i += dir)+ if (i >= 0 && i < c->n && (fr[i] & 0x8000)) a->events |= ANIM_TRIGGER;+}++static void set_frame(Anim *a, const ClipRec *c, int f) {+ a->frame = (int16_t)f;+ a->sprite = (int16_t)(clip_frames(c)[f] & 0x7FFF);+}++void anim_update(Anim *a, float dt) {+ if (!a->playing || a->paused) return;+ const ClipRec *c = clip_rec(a->clip);+ a->time += dt * a->fps;+ int prev = a->frame, n = c->n, t = (int)a->time;+ switch (c->wrap) {+ case WRAP_LOOP:+ case WRAP_RANDOM_LOOP: {+ int f = t % n;+ set_frame(a, c, f);+ if (f < prev) events(a, c, prev, n - 1, 1), events(a, c, -1, f, 1);+ else events(a, c, prev, f, 1);+ break;+ }+ case WRAP_LOOP_SECTION: {+ int ls = c->loop;+ if (t >= ls) {+ int f = ls + (t - ls) % (n - ls);+ set_frame(a, c, f);+ if (prev < ls) events(a, c, prev, ls - 1, 1), events(a, c, ls - 1, f, 1);+ else if (f < prev) events(a, c, prev, n - 1, 1), events(a, c, ls - 1, f, 1);+ else events(a, c, prev, f, 1);+ } else {+ set_frame(a, c, t);+ events(a, c, prev, t, 1);+ }+ break;+ }+ case WRAP_PING_PONG: {+ int f = n > 1 ? t % (2 * n - 2) : 0, dir = 1;+ if (f >= n) f = 2 * n - 2 - f, dir = -1;+ if (f < prev) dir = -1;+ set_frame(a, c, f);+ events(a, c, prev, f, dir);+ break;+ }+ default: /* once */+ if (t >= n) {+ set_frame(a, c, n - 1);+ a->playing = false;+ events(a, c, prev, n - 1, 1);+ a->events |= ANIM_DONE;+ } else {+ set_frame(a, c, t);+ events(a, c, prev, t, 1);+ }+ break;+ }+}++/* ---------------------------------------------------------------- half floats */+uint16_t to_f16(float f) {+ uint32_t x;+ memcpy(&x, &f, 4);+ uint32_t s = x >> 16 & 0x8000, e = x >> 23 & 255, m = x & 0x7FFFFF;+ if (e == 255) return (uint16_t)(s | 0x7C00 | (m ? 0x200 : 0));+ int ne = (int)e - 127 + 15;+ if (ne >= 31) return (uint16_t)(s | 0x7C00);+ if (ne <= 0) {+ if (ne < -10) return (uint16_t)s;+ m |= 0x800000;+ uint32_t sh = (uint32_t)(14 - ne), hm = m >> sh;+ if ((m >> (sh - 1)) & 1) hm++; /* (round half up) */+ return (uint16_t)(s | hm);+ }+ uint32_t h = s | (uint32_t)ne << 10 | m >> 13;+ if (m & 0x1000) h++; /* round */+ return (uint16_t)h;+}++/* the sprite drawn at (x, y, z), scaled (sx < 0: mirrored), tinted */+void sprite_inst(int sprite, float x, float y, float z, float sx, float sy, uint8_t tint, Inst *out) {+ const SpriteRec *s = sprite_rec(sprite);+ out->ax = (int16_t)lrintf((x + sx * s->lx) * 64);+ out->ay = (int16_t)lrintf((y + sy * s->ty) * 64);+ out->z = (int16_t)lrintf(z * 128);+ out->tex = s->tex;+ out->tint = tint;+ out->flags = 0;+ out->a = to_f16(sx * s->tu);+ out->b = to_f16(-sy * s->tv);+ out->rot = 0;+}diff --git a/games/hollowknight/src/camera.c b/games/hollowknight/src/camera.cnew file mode 100644index 00000000..c48694dc--- /dev/null+++ b/games/hollowknight/src/camera.c@@ -0,0 +1,289 @@+/* The camera: CameraTarget follows the Knight (looking ahead, catching falls), CameraController follows the target+ * (looking up and down), both inside the scene and the room's lock areas. */+#include <math.h>+#include "game.h"++#define DT 0.02f+#define X_MIN 14.6f+#define Y_MIN 8.3f+/* CameraTarget */+#define DAMP_NORMAL 0.075f+#define DAMP_SLOW 0.5f+#define SLOW_TIME 0.5f+#define X_LOOK_AHEAD 1.0f+#define DASH_LOOK_AHEAD 1.5f+#define SNAP 0.15f+/* CameraController */+#define DAMP_TIME 0.15f++enum { TM_FOLLOW_HERO, TM_LOCK_ZONE, TM_BOSS, TM_FREE };+enum { CM_FROZEN, CM_FOLLOWING, CM_LOCKED, CM_PANNING, CM_FADEOUT, CM_FADEIN, CM_PREVIOUS };++static struct {+ /* the target */+ int tmode;+ float tx, ty, vx_x, vy_y, x_offset, dash_offset, damp_x, damp_y, slow_timer, fall_catcher, prev_hx, prev_hy;+ float lock_x0, lock_x1, lock_y0, lock_y1;+ bool stick_x, stick_y, fall_stick;+ bool entered_left, entered_right, entered_top, entered_bot, exited_left, exited_right, exited_top, exited_bot;+ /* the camera */+ int mode;+ float cx, cy, cvx, cvy, cdamp_x, cdamp_y, look_offset, x_limit, y_limit, start_locked_timer;+ float x_lock0, x_lock1, y_lock0, y_lock1;+ int8_t locks[8], nlocks, cur_lock; /* lockZoneList, currentLockArea (entities) */+} c;++/* Mathf.SmoothDamp */+static float smooth_damp(float cur, float target, float *vel, float t, float dt) {+ if (t < 0.0001f) t = 0.0001f;+ float omega = 2 / t, x = omega * dt, e = 1 / (1 + x + 0.48f * x * x + 0.235f * x * x * x);+ float change = cur - target, orig = target;+ target = cur - change;+ float temp = (*vel + omega * change) * dt;+ *vel = (*vel - omega * temp) * e;+ float out = target + (change + temp) * e;+ if ((orig - cur > 0) == (out > orig)) out = orig, *vel = (out - orig) / dt;+ return out;+}++static void set_damp_time(void) {+ if (c.slow_timer > 0) {+ c.slow_timer -= DT;+ return;+ }+ if (c.damp_x > DAMP_NORMAL) c.damp_x -= 0.007f;+ else if (c.damp_x < DAMP_NORMAL) c.damp_x = DAMP_NORMAL;+ if (c.damp_y > DAMP_NORMAL) c.damp_y -= 0.007f;+ else if (c.damp_y < DAMP_NORMAL) c.damp_y = DAMP_NORMAL;+}++static void keep_in_scene(float *x, float *y) {+ if (*x < X_MIN) *x = X_MIN;+ if (*x > c.x_limit) *x = c.x_limit;+ if (*y < Y_MIN) *y = Y_MIN;+ if (*y > c.y_limit) *y = c.y_limit;+}++void cam_init(void) {+ const Hero *h = &g_hero;+ memset(&c, 0, sizeof c);+ c.x_limit = g_room.h->w - X_MIN, c.y_limit = g_room.h->h - Y_MIN;+ if (c.x_limit < X_MIN) c.x_limit = X_MIN;+ if (c.y_limit < Y_MIN) c.y_limit = Y_MIN;+ c.tmode = TM_FOLLOW_HERO;+ c.stick_x = c.stick_y = true;+ c.lock_x0 = 0, c.lock_x1 = c.x_limit, c.lock_y0 = 0, c.lock_y1 = c.y_limit;+ c.damp_x = c.damp_y = DAMP_NORMAL;+ c.mode = CM_FOLLOWING;+ c.cdamp_x = c.cdamp_y = DAMP_TIME;+ c.start_locked_timer = 0.5f;+ c.cur_lock = -1;+ c.x_lock0 = 0, c.x_lock1 = c.x_limit, c.y_lock0 = 0, c.y_lock1 = c.y_limit;+ /* PositionToStart */+ c.x_offset = h->cs.facing_right ? 1.0f : -1.0f;+ c.tx = h->body.x, c.ty = h->body.y;+ keep_in_scene(&c.tx, &c.ty);+ c.cx = c.tx + c.x_offset, c.cy = c.ty;+ keep_in_scene(&c.cx, &c.cy);+ c.prev_hx = h->body.x, c.prev_hy = h->body.y;+ g_cam_x = c.cx, g_cam_y = c.cy;+}++/* ---------------------------------------------------------------- lock areas */+static void lock_bounds(const Ent *e, float *x0, float *y0, float *x1, float *y1) {+ /* (CameraLockArea.ValidateBounds) */+ *x0 = e->p0 == -1 ? X_MIN : e->p0, *y0 = e->p1 == -1 ? Y_MIN : e->p1;+ *x1 = e->p2 == -1 ? c.x_limit : e->p2, *y1 = e->p3 == -1 ? c.y_limit : e->p3;+}++static void target_enter_lock_zone(float x0, float x1, float y0, float y1) {+ const Hero *h = &g_hero;+ c.lock_x0 = x0, c.lock_x1 = x1, c.lock_y0 = y0, c.lock_y1 = y1;+ c.tmode = TM_LOCK_ZONE;+ if ((!c.entered_left || x0 != 14.6f) && (!c.entered_right || x1 != c.x_limit)) c.damp_x = DAMP_SLOW;+ if ((!c.entered_bot || y0 != 8.3f) && (!c.entered_top || y1 != c.y_limit)) c.damp_y = DAMP_SLOW;+ c.slow_timer = SLOW_TIME;+ c.stick_x = c.tx >= h->body.x - SNAP && c.tx <= h->body.x + SNAP;+ c.stick_y = c.ty >= h->body.y - SNAP && c.ty <= h->body.y + SNAP;+}++static void target_enter_lock_zone_instant(float x0, float x1, float y0, float y1) {+ c.lock_x0 = x0, c.lock_x1 = x1, c.lock_y0 = y0, c.lock_y1 = y1;+ c.tmode = TM_LOCK_ZONE;+ if (c.tx < x0) c.tx = x0;+ if (c.tx > x1) c.tx = x1;+ if (c.ty < y0) c.ty = y0;+ if (c.ty > y1) c.ty = y1;+ c.stick_x = c.stick_y = true;+}++static void target_exit_lock_zone(void) {+ const Hero *h = &g_hero;+ if (c.tmode == TM_FREE) return;+ c.tmode = h->cs.hazard_death || h->cs.dead ||+ (h->transition_state != TS_WAITING_TO_TRANSITION && h->transition_state != TS_WAITING_TO_ENTER_LEVEL)+ ? TM_FREE+ : TM_FOLLOW_HERO;+ if ((!c.exited_left || c.lock_x0 != 14.6f) && (!c.exited_right || c.lock_x1 != c.x_limit)) c.damp_x = DAMP_SLOW;+ if ((!c.exited_bot || c.lock_y0 != 8.3f) && (!c.exited_top || c.lock_y1 != c.y_limit)) c.damp_y = DAMP_SLOW;+ c.slow_timer = SLOW_TIME;+ c.fall_stick = false;+ c.lock_x0 = 0, c.lock_x1 = c.x_limit, c.lock_y0 = 0, c.lock_y1 = c.y_limit;+ c.stick_x = c.tx >= h->body.x - SNAP && c.tx <= h->body.x + SNAP;+ c.stick_y = c.ty >= h->body.y - SNAP && c.ty <= h->body.y + SNAP;+}++static float clampf(float v, float a, float b) { return v < a ? a : v > b ? b : v; }++void cam_lock(int ent) {+ int n;+ const Ent *es = room_ents(&n), *e = &es[ent];+ for (int i = 0; i < c.nlocks; i++)+ if (c.locks[i] == ent) return; /* (already in the list: Stay) */+ /* (OnTriggerEnter2D: which side the Knight came in by) */+ const Hero *h = &g_hero;+ float hx = h->body.x, hy = h->body.y;+ c.entered_left = hx > e->x0 - 1 && hx < e->x0 + 1;+ c.entered_right = hx > e->x1 - 1 && hx < e->x1 + 1;+ c.entered_top = hy > e->y1 - 2 && hy < e->y1 + 2;+ c.entered_bot = hy > e->y0 - 1 && hy < e->y0 + 1;+ if (c.nlocks < 8) c.locks[c.nlocks++] = (int8_t)ent;+ if (c.cur_lock >= 0 && (es[c.cur_lock].flags & CL_MAX_PRIORITY) && !(e->flags & CL_MAX_PRIORITY)) return;+ c.cur_lock = (int8_t)ent;+ c.mode = CM_LOCKED;+ lock_bounds(e, &c.x_lock0, &c.y_lock0, &c.x_lock1, &c.y_lock1);+ if (c.start_locked_timer > 0) {+ c.tx = clampf(hx, c.x_lock0, c.x_lock1), c.ty = clampf(hy, c.y_lock0, c.y_lock1);+ target_enter_lock_zone_instant(c.x_lock0, c.x_lock1, c.y_lock0, c.y_lock1);+ c.cx = c.tx, c.cy = c.ty;+ } else+ target_enter_lock_zone(c.x_lock0, c.x_lock1, c.y_lock0, c.y_lock1);+}++void cam_release(int ent) {+ int n;+ const Ent *es = room_ents(&n), *e = &es[ent];+ int j = 0;+ for (int i = 0; i < c.nlocks; i++)+ if (c.locks[i] != ent) c.locks[j++] = c.locks[i];+ bool was_listed = j != c.nlocks;+ c.nlocks = (int8_t)j;+ if (!was_listed) return;+ const Hero *h = &g_hero;+ float hx = h->body.x, hy = h->body.y;+ c.exited_left = hx > e->x0 - 1 && hx < e->x0 + 1;+ c.exited_right = hx > e->x1 - 1 && hx < e->x1 + 1;+ c.exited_top = hy > e->y1 - 2 && hy < e->y1 + 2;+ c.exited_bot = hy > e->y0 - 1 && hy < e->y0 + 1;+ if (ent != c.cur_lock) return;+ if (c.nlocks > 0) {+ c.cur_lock = c.locks[c.nlocks - 1];+ const Ent *l = &es[c.cur_lock];+ /* (as the game: the raw values) */+ c.x_lock0 = l->p0, c.y_lock0 = l->p1, c.x_lock1 = l->p2, c.y_lock1 = l->p3;+ target_enter_lock_zone(c.x_lock0, c.x_lock1, c.y_lock0, c.y_lock1);+ return;+ }+ target_exit_lock_zone();+ c.cur_lock = -1;+ if (!h->cs.hazard_death && !h->cs.dead) c.mode = CM_FOLLOWING;+}++/* CameraTarget.Update */+static void target_update(void) {+ const Hero *h = &g_hero;+ float hx = h->body.x, hy = h->body.y;+ if (c.tmode == TM_FOLLOW_HERO || c.tmode == TM_LOCK_ZONE) {+ set_damp_time();+ float dx = hx, dy = hy;+ bool lock = c.tmode == TM_LOCK_ZONE;+ if (lock) {+ if (dx < c.lock_x0) dx = c.lock_x0;+ if (dx > c.lock_x1) dx = c.lock_x1;+ if (dy < c.lock_y0) dy = c.lock_y0;+ if (dy > c.lock_y1) dy = c.lock_y1;+ }+ float nx = smooth_damp(c.tx, dx, &c.vx_x, c.damp_x, DT);+ if (!c.fall_stick && c.fall_catcher <= 0) c.ty = smooth_damp(c.ty, dy, &c.vy_y, c.damp_y, DT);+ c.tx = nx;+ float x = c.tx, y = c.ty;+ if ((c.prev_hx < x && hx > x) || (c.prev_hx > x && hx < x) || (x >= hx - SNAP && x <= hx + SNAP)) c.stick_x = true;+ if ((c.prev_hy < y && hy > y) || (c.prev_hy > y && hy < y) || (y >= hy - SNAP && y <= hy + SNAP)) c.stick_y = true;+ if (c.stick_x && (!lock || (hx >= c.lock_x0 && hx <= c.lock_x1) || (hx <= c.lock_x1 && hx >= x) || (hx >= c.lock_x0 && hx <= x)))+ c.tx = hx;+ if (c.stick_y && (!lock || (hy >= c.lock_y0 && hy <= c.lock_y1) || (hy <= c.lock_y1 && hy >= y) || (hy >= c.lock_y0 && hy <= y)))+ c.ty = hy;+ }+ /* looking ahead */+ if (h->cs.facing_right) {+ if (c.x_offset < X_LOOK_AHEAD) c.x_offset += DT * 6;+ } else if (c.x_offset > -X_LOOK_AHEAD)+ c.x_offset -= DT * 6;+ if (c.x_offset < -X_LOOK_AHEAD) c.x_offset = -X_LOOK_AHEAD;+ if (c.x_offset > X_LOOK_AHEAD) c.x_offset = X_LOOK_AHEAD;+ if (c.tmode == TM_LOCK_ZONE) {+ if (hx < c.lock_x0 && h->cs.facing_right) c.x_offset = hx - c.tx + 1;+ if (hx > c.lock_x1 && !h->cs.facing_right) c.x_offset = hx - c.tx - 1;+ if (c.tx + c.x_offset > c.lock_x1) c.x_offset = c.lock_x1 - c.tx;+ if (c.tx + c.x_offset < c.lock_x0) c.x_offset = c.lock_x0 - c.tx;+ }+ if (c.x_offset < -X_LOOK_AHEAD) c.x_offset = -X_LOOK_AHEAD;+ if (c.x_offset > X_LOOK_AHEAD) c.x_offset = X_LOOK_AHEAD;+ if (h->cs.dashing && fabsf(h->body.vx) > 5) {+ c.dash_offset = h->cs.facing_right ? DASH_LOOK_AHEAD : -DASH_LOOK_AHEAD;+ if (c.tmode == TM_LOCK_ZONE &&+ (c.tx + c.dash_offset > c.lock_x1 || c.tx + c.dash_offset < c.lock_x0 || hx > c.lock_x1 || hx < c.lock_x0))+ c.dash_offset = 0;+ } else+ c.dash_offset = 0;+ c.prev_hx = hx, c.prev_hy = hy;+ if (!h->cs.falling) c.fall_catcher = 0, c.fall_stick = false;+ /* catching up with a fall */+ if (c.tmode == TM_FOLLOW_HERO || c.tmode == TM_LOCK_ZONE) {+ if (h->cs.falling && c.cy > hy + 0.1f && !c.fall_stick && !h->cs.transitioning &&+ (c.cy - 0.1f >= c.lock_y0 || c.tmode != TM_LOCK_ZONE)) {+ c.cy -= c.fall_catcher * DT;+ if (c.tmode == TM_LOCK_ZONE && c.cy < c.lock_y0) c.cy = c.lock_y0;+ if (c.cy < Y_MIN) c.cy = Y_MIN;+ if (c.fall_catcher < 25) c.fall_catcher += 80 * DT;+ if (c.cy < hy + 0.1f) c.fall_stick = true;+ c.ty = c.cy;+ }+ if (c.fall_stick) {+ c.fall_catcher = 0;+ if (hy + 0.1f >= c.lock_y0 || c.tmode != TM_LOCK_ZONE) c.cy = hy + 0.1f, c.ty = c.cy;+ if (c.tmode == TM_LOCK_ZONE && c.cy < c.lock_y0) c.cy = c.lock_y0;+ if (c.cy < Y_MIN) c.cy = Y_MIN;+ }+ }+}++/* CameraController.LateUpdate */+static void controller_late_update(void) {+ const Hero *h = &g_hero;+ if (c.mode != CM_FROZEN) {+ if (h->cs.looking_up) c.look_offset = h->body.y - c.ty + 6;+ else if (h->cs.looking_down) c.look_offset = h->body.y - c.ty - 6;+ else c.look_offset = 0;+ float dx = c.tx + c.x_offset + c.dash_offset, dy = c.ty + c.look_offset;+ if (c.mode == CM_LOCKED && c.cur_lock >= 0) {+ int n;+ const Ent *l = &room_ents(&n)[c.cur_lock];+ float x0, y0, x1, y1;+ lock_bounds(l, &x0, &y0, &x1, &y1);+ if (c.look_offset > 0 && (l->flags & CL_PREVENT_UP) && dy > y1) dy = c.cy > y1 ? dy - c.look_offset : y1;+ if (c.look_offset < 0 && (l->flags & CL_PREVENT_DOWN) && dy < y0) dy = c.cy < y0 ? dy - c.look_offset : y0;+ }+ if (c.mode == CM_FOLLOWING || c.mode == CM_LOCKED) keep_in_scene(&dx, &dy);+ float nx = smooth_damp(c.cx, dx, &c.cvx, c.cdamp_x, DT);+ float ny = smooth_damp(c.cy, dy, &c.cvy, c.cdamp_y, DT);+ c.cx = nx, c.cy = ny;+ }+ keep_in_scene(&c.cx, &c.cy);+}++void cam_tick(void) {+ target_update();+ controller_late_update();+ g_cam_x = c.cx, g_cam_y = c.cy;+}diff --git a/games/hollowknight/src/data.S b/games/hollowknight/src/data.Snew file mode 100644index 00000000..5a8e9965--- /dev/null+++ b/games/hollowknight/src/data.S@@ -0,0 +1,10 @@+/* data.bin (tools/pack.py) in the app's read-only data */+ .section .rodata.hk_data,"a"+ .balign 4+ .global hk_data+hk_data:+ .incbin DATA_BIN+ .balign 4+#ifdef __ELF__+ .section .note.GNU-stack,"",%progbits+#endifdiff --git a/games/hollowknight/src/data.bin b/games/hollowknight/src/data.binnew file mode 100644index 00000000..88d4049cBinary files /dev/null and b/games/hollowknight/src/data.bin differdiff --git a/games/hollowknight/src/data.h b/games/hollowknight/src/data.hnew file mode 100644index 00000000..71f32c4b--- /dev/null+++ b/games/hollowknight/src/data.h@@ -0,0 +1,136 @@+/* made by tools/pack.py */+#pragma once+#define SEC_TEX 0+#define SEC_TMAP 1+#define SEC_PAL 2+#define SEC_BIDX 3+#define SEC_BLK 4+#define SEC_ROOMS 5+#define SEC_RBLOB 6+#define SEC_PRIOR 7+#define SEC_SOFT 8+#define SEC_SPR 9+#define SEC_CLIP 10+#define SEC_STR 11+#define NUM_ROOMS 41+#define ROOM_TUTORIAL_01 0+#define ROOM_TOWN 1+#define ROOM_ROOM_SHOP 2+#define ROOM_ROOM_MAPPER 3+#define ROOM_ROOM_TOWN_STAG_STATION 4+#define ROOM_CROSSROADS_01 5+#define ROOM_CROSSROADS_02 6+#define ROOM_ROOM_TEMPLE 7+#define ROOM_CROSSROADS_07 8+#define ROOM_CROSSROADS_38 9+#define ROOM_CROSSROADS_33 10+#define ROOM_CROSSROADS_06 11+#define ROOM_CROSSROADS_SHAMANTEMPLE 12+#define ROOM_CROSSROADS_10 13+#define ROOM_CROSSROADS_10_BOSS 14+#define ROOM_CROSSROADS_10_BOSS_DEFEATED 15+#define ROOM_CROSSROADS_21 16+#define ROOM_CROSSROADS_39 17+#define ROOM_CROSSROADS_14 18+#define ROOM_CROSSROADS_16 19+#define ROOM_CROSSROADS_03 20+#define ROOM_CROSSROADS_47 21+#define ROOM_CROSSROADS_19 22+#define ROOM_CROSSROADS_04 23+#define ROOM_ROOM_RUINHOUSE 24+#define ROOM_ROOM_CHARM_SHOP 25+#define ROOM_CROSSROADS_08 26+#define ROOM_CROSSROADS_30 27+#define ROOM_CROSSROADS_11_ALT 28+#define ROOM_FUNGUS1_01 29+#define ROOM_FUNGUS1_01B 30+#define ROOM_FUNGUS1_02 31+#define ROOM_FUNGUS1_17 32+#define ROOM_FUNGUS1_03 33+#define ROOM_FUNGUS1_31 34+#define ROOM_FUNGUS1_32 35+#define ROOM_FUNGUS1_21 36+#define ROOM_FUNGUS1_22 37+#define ROOM_FUNGUS1_16_ALT 38+#define ROOM_FUNGUS1_04 39+#define ROOM_FUNGUS1_04_BOSS 40+#define CLIP_KNIGHT_IDLE 0+#define CLIP_KNIGHT_IDLE_HURT 1+#define CLIP_KNIGHT_IDLE_WIND 2+#define CLIP_KNIGHT_RUN 3+#define CLIP_KNIGHT_RUN_TO_IDLE 4+#define CLIP_KNIGHT_WALK 5+#define CLIP_KNIGHT_TURN 6+#define CLIP_KNIGHT_TURNTOIDLE 7+#define CLIP_KNIGHT_AIRBORNE 8+#define CLIP_KNIGHT_FALL 9+#define CLIP_KNIGHT_LAND 10+#define CLIP_KNIGHT_HARDLAND 11+#define CLIP_KNIGHT_DASH 12+#define CLIP_KNIGHT_DASH_TO_IDLE 13+#define CLIP_KNIGHT_DASH_EFFECT 14+#define CLIP_KNIGHT_SLASH 15+#define CLIP_KNIGHT_SLASHALT 16+#define CLIP_KNIGHT_UPSLASH 17+#define CLIP_KNIGHT_DOWNSLASH 18+#define CLIP_KNIGHT_SLASHEFFECT 19+#define CLIP_KNIGHT_SLASHEFFECTALT 20+#define CLIP_KNIGHT_UPSLASHEFFECT 21+#define CLIP_KNIGHT_DOWNSLASHEFFECT 22+#define CLIP_KNIGHT_LOOKUP 23+#define CLIP_KNIGHT_LOOKUPEND 24+#define CLIP_KNIGHT_LOOKUPTOIDLE 25+#define CLIP_KNIGHT_LOOKDOWN 26+#define CLIP_KNIGHT_LOOKDOWNEND 27+#define CLIP_KNIGHT_LOOKDOWNTOIDLE 28+#define CLIP_KNIGHT_RECOIL 29+#define CLIP_KNIGHT_STUN 30+#define CLIP_KNIGHT_DEATH 31+#define CLIP_KNIGHT_DEATH_HEAD_NORMAL 32+#define CLIP_KNIGHT_SPIKE_DEATH 33+#define CLIP_KNIGHT_SPIKE_DEATH_ANTIC 34+#define CLIP_KNIGHT_HAZARD_RESPAWN 35+#define CLIP_KNIGHT_RESPAWN_WAKE 36+#define CLIP_KNIGHT_FOCUS 37+#define CLIP_KNIGHT_FOCUS_GET 38+#define CLIP_KNIGHT_FOCUS_GET_ONCE 39+#define CLIP_KNIGHT_FOCUS_END 40+#define CLIP_KNIGHT_FIREBALL_ANTIC 41+#define CLIP_KNIGHT_FIREBALL1_CAST 42+#define CLIP_KNIGHT_SIT 43+#define CLIP_KNIGHT_SIT_LEAN 44+#define CLIP_KNIGHT_SIT_IDLE 45+#define CLIP_KNIGHT_SITTING_ASLEEP 46+#define CLIP_KNIGHT_SIT_FALL_ASLEEP 47+#define CLIP_KNIGHT_WAKE 48+#define CLIP_KNIGHT_WAKE_TO_SIT 49+#define CLIP_KNIGHT_GET_OFF 50+#define CLIP_KNIGHT_SIT_MAP_OPEN 51+#define CLIP_KNIGHT_SIT_MAP_CLOSE 52+#define CLIP_KNIGHT_MAP_OPEN 53+#define CLIP_KNIGHT_MAP_IDLE 54+#define CLIP_KNIGHT_MAP_WALK 55+#define CLIP_KNIGHT_MAP_TURN 56+#define CLIP_KNIGHT_MAP_AWAY 57+#define CLIP_KNIGHT_MAP_UPDATE 58+#define CLIP_KNIGHT_ENTER 59+#define CLIP_KNIGHT_EXIT 60+#define CLIP_KNIGHT_EXIT_DOOR_TO_IDLE 61+#define CLIP_KNIGHT_TURNTOBG 62+#define CLIP_KNIGHT_TURNFROMBG 63+#define CLIP_KNIGHT_ROAR_LOCK 64+#define CLIP_KNIGHT_PROSTRATE 65+#define CLIP_KNIGHT_PROSTRATE_RISE 66+#define CLIP_KNIGHT_WAKE_UP_GROUND 67+#define CLIP_KNIGHT_COLLECT_NORMAL_1 68+#define CLIP_KNIGHT_COLLECT_NORMAL_2 69+#define CLIP_KNIGHT_COLLECT_NORMAL_3 70+#define CLIP_KNIGHT_COLLECT_MAGICAL_1 71+#define CLIP_KNIGHT_COLLECT_MAGICAL_2 72+#define CLIP_KNIGHT_COLLECT_MAGICAL_3 73+#define CLIP_KNIGHT_COLLECT_MAGICAL_FALL 74+#define CLIP_KNIGHT_COLLECT_MAGICAL_LAND 75+#define CLIP_KNIGHT_COLLECT_HEART_PIECE 76+#define CLIP_KNIGHT_COLLECT_HEART_PIECE_END 77+#define CLIP_KNIGHT_COLLECT_STANDTOIDLE 78+#define CLIP_KNIGHT_GETUPTOIDLE 79diff --git a/games/hollowknight/src/game.c b/games/hollowknight/src/game.cnew file mode 100644index 00000000..0839f324--- /dev/null+++ b/games/hollowknight/src/game.c@@ -0,0 +1,78 @@+/* The game: a scene, the Knight in it, the camera; ticks of 1/50 s. */+#include "game.h"++PlayerData g_pd;+Game g_game;+static uint8_t inside[MAX_ENTS / 8]; /* the triggers the Knight is in */++void game_new(void) {+ memset(&g_pd, 0, sizeof g_pd);+ g_pd.health = g_pd.max_health = 5;+ g_pd.max_mp = 99;+ g_pd.can_dash = false;+}++bool game_enter(int room, float x, float y, bool facing_right) {+ if (!room_load(room)) return false;+ memset(inside, 0, sizeof inside);+ hero_init(x, y, facing_right);+ cam_init();+ return true;+}++const Ent *room_ents(int *n) {+ *n = g_room.h->nent;+ return (const Ent *)(const void *)(section(SEC_RBLOB) + g_room.h->ents);+}++/* ---------------------------------------------------------------- triggers: the Knight's box in the objects' */++static void trigger_event(int i, const Ent *e, int kind) {+ Hero *h = &g_hero;+ switch (e->type) {+ case ENT_CAMLOCK:+ if (kind == EV_EXIT) cam_release(i);+ else cam_lock(i); /* (Enter and Stay) */+ break;+ case ENT_HAZARD_TRIGGER:+ if (kind == EV_ENTER) {+ int n;+ const Ent *m = &room_ents(&n)[e->a];+ g_game.hazard_x = m->x0, g_game.hazard_y = m->y0, g_game.hazard_facing_right = m->flags & FACING_RIGHT;+ }+ break;+ default:+ break;+ }+ (void)h;+}++static void triggers_tick(void) {+ const Body *b = &g_hero.body;+ float x0 = b->x + b->ox - b->hx, x1 = b->x + b->ox + b->hx, y0 = b->y + b->oy - b->hy, y1 = b->y + b->oy + b->hy;+ int n;+ const Ent *es = room_ents(&n);+ if (n > MAX_ENTS) n = MAX_ENTS;+ for (int i = 0; i < n; i++) {+ const Ent *e = &es[i];+ if (e->type != ENT_CAMLOCK && e->type != ENT_GATE && e->type != ENT_HAZARD_TRIGGER) continue;+ bool in = x1 > e->x0 && x0 < e->x1 && y1 > e->y0 && y0 < e->y1;+ bool was = inside[i >> 3] >> (i & 7) & 1;+ if (in) inside[i >> 3] |= (uint8_t)(1 << (i & 7));+ else inside[i >> 3] &= (uint8_t)~(1 << (i & 7));+ if (in || was) trigger_event(i, e, in && was ? EV_STAY : in ? EV_ENTER : EV_EXIT);+ }+}++void game_tick(uint32_t keys) {+ g_game.time += 0.02f;+ hero_fixed(keys);+ triggers_tick();+ hero_update();+ cam_tick();+}++void game_draw(void) {+ hero_draw();+ gfx_frame();+}diff --git a/games/hollowknight/src/game.h b/games/hollowknight/src/game.hnew file mode 100644index 00000000..104b6e1f--- /dev/null+++ b/games/hollowknight/src/game.h@@ -0,0 +1,113 @@+/* The game: the Knight, what the player has, the camera, the scene. */+#pragma once+#include "hk.h"++/* ---------------------------------------------------------------- PlayerData (what a save keeps) */+typedef struct {+ int8_t health, max_health, health_blue;+ int16_t mp, mp_reserve, max_mp;+ int32_t geo;+ bool can_dash, has_spell, has_dash;+ uint8_t fireball_level;+ bool disable_pause;+} PlayerData;+extern PlayerData g_pd;++/* ---------------------------------------------------------------- the room's game objects (tools/ents.py) */+enum { ENT_CAMLOCK = 1, ENT_GATE, ENT_HAZARD_MARKER, ENT_RESPAWN, ENT_HAZARD_TRIGGER };+enum { CL_PREVENT_UP = 1, CL_PREVENT_DOWN = 2, CL_MAX_PRIORITY = 4 };+enum { G_DOOR = 1, G_ENTER_RIGHT = 2, G_ENTER_LEFT = 4, G_DONT_WALK_OUT = 8, G_NON_HAZARD = 16 };+#define FACING_RIGHT 1+typedef struct {+ uint8_t type, flags;+ uint16_t a; /* gate: the room it leads to; hazard trigger: its marker */+ float x0, y0, x1, y1; /* its trigger (or its place) */+ float p0, p1, p2, p3; /* camera lock: x min, y min, x max, y max (-1: none); gate: entry delay */+ uint16_t s0, s1; /* names (str_at): a gate's own and its entry point's */+} Ent;+const Ent *room_ents(int *n);+#define MAX_ENTS 160++/* ---------------------------------------------------------------- the game */+typedef struct {+ bool paused;+ float time;+ float hazard_x, hazard_y; /* where a hazard sends the Knight back to */+ bool hazard_facing_right;+} Game;+extern Game g_game;++/* ---------------------------------------------------------------- the Knight (hero.c) */+enum { HS_INACTIVE, HS_IDLE, HS_RUNNING, HS_AIRBORNE, HS_WALL_SLIDING, HS_HARD_LANDING, HS_DASH_LANDING, HS_NO_INPUT,+ HS_PREVIOUS, HS_GROUNDED }; /* ActorStates (grounded and previous only as SetState's arguments) */+enum { TS_WAITING_TO_TRANSITION, TS_EXITING_SCENE, TS_WAITING_TO_ENTER_LEVEL, TS_ENTERING_SCENE, TS_DROPPING_DOWN };+enum { GATE_TOP, GATE_RIGHT, GATE_LEFT, GATE_BOTTOM, GATE_DOOR, GATE_UNKNOWN };+enum { SIDE_TOP, SIDE_LEFT, SIDE_RIGHT, SIDE_BOTTOM };+enum { ATK_NORMAL, ATK_UP, ATK_DOWN };+enum { SLASH_NORMAL, SLASH_ALT, SLASH_UP, SLASH_DOWN };+enum { DAMAGE_FULL, DAMAGE_HAZARD_ONLY, DAMAGE_NONE };+#define RECOIL_DURATION 0.2f++typedef struct { /* HeroControllerStates */+ bool facing_right, on_ground, jumping, dashing, falling, attacking, up_attacking, down_attacking, alt_attack;+ bool looking_up, looking_down, looking_up_anim, looking_down_anim, bouncing, recoiling_left, recoiling_right;+ bool recoiling, recoil_frozen, dead, hazard_death, hazard_respawning, will_hard_land, casting, cast_recoiling;+ bool prevent_dash, dash_cooldown, in_walk_zone, touching_wall, touching_non_slider, was_on_ground, transitioning;+ bool invulnerable, focusing;+} CState;++typedef struct {+ Body body;+ uint32_t keys, prev_keys;+ uint8_t state, prev_state, anim_state, transition_state, gate_position, damage_mode;+ float move_input, vertical_input;+ CState cs;+ int jump_steps, jumped_steps, jump_queue_steps, dash_queue_steps, attack_queue_steps, recoil_steps;+ int landing_buffer_steps, ledge_buffer_steps, head_bump_steps;+ bool jump_queuing, dash_queuing, attack_queuing, recoil_large, hard_landed, air_dashed;+ float dash_timer, dash_cooldown_timer, attack_time, attack_duration, attack_cooldown, alt_attack_time;+ float time_since_level, bounce_timer, recoil_timer, recoil_vx, recoil_vy, fall_timer, hard_landing_timer;+ float dash_landing_timer, hard_land_fail_safe_timer, floating_buffer_timer, look_delay_timer, prev_gravity;+ float transition_vx, transition_vy;+ bool accepting_input, control_relinquished, doing_hazard_respawn, landed_event;+ bool touching_wall_l, touching_wall_r;+ int8_t thunk_dir;+ bool thunk_hit;+ float thunk_timer;+ /* HeroAnimationController */+ Anim anim;+ bool anim_control, play_landing, play_run_to_idle, play_dash_to_idle, complete_delegate, set_entry_anim;+ bool was_facing_right, was_attacking;+} Hero;+extern Hero g_hero;++void hero_init(float x, float y, bool facing_right);+void hero_fixed(uint32_t keys); /* a 1/50 s step: FixedUpdate, the physics and its collisions */+void hero_update(void); /* then Update and the animations */+void hero_draw(void);+bool hero_touching_ground(void);+void hero_recoil_left(void);+void hero_recoil_right(void);+void hero_recoil_down(void);+void hero_bounce(void);+void hero_finished_entering_scene(void);++/* the nail's slashes (NailSlash), children of the Knight */+void slash_start(int kind);+void slash_cancel(void);+void slash_tick(void);+void slash_draw(void);++/* effects */+void fx_dash_burst(float x, float y, bool facing_right, bool on_ground);++void game_new(void);+bool game_enter(int room, float x, float y, bool facing_right);+void game_tick(uint32_t keys); /* 1/50 s */+void game_draw(void);++/* ---------------------------------------------------------------- the camera (camera.c) */+void cam_init(void);+void cam_tick(void);+void cam_lock(int ent); /* CameraController.LockToArea, the hero entering the area's trigger */+void cam_release(int ent); /* ReleaseLock */diff --git a/games/hollowknight/src/gfx.c b/games/hollowknight/src/gfx.cnew file mode 100644index 00000000..c6a7c800--- /dev/null+++ b/games/hollowknight/src/gfx.c@@ -0,0 +1,1098 @@+/* Drawing a room: its sprites front to back, a strip of rows at a time. Each pixel keeps the light gathered so far+ * and how much still gets through from behind, so what is hidden is never fetched nor drawn. What is behind the+ * blur plane is drawn small beforehand (as the game's background camera does) and shows through at the end.+ * Then the strip is dithered to the screen's 16 bits. */+#include <math.h>+#include <stdint.h>+#include "hk.h"+#ifdef HOST+#include <stdio.h>+#include <stdlib.h>+#endif++#define STRIP_H 4+#ifndef MAX_ITEMS+#define MAX_ITEMS 512+#endif+#ifndef NPAL+#define NPAL 104+#endif+#define NPX (STRIP_H * VIEW_W)++float g_cam_x, g_cam_y;+uint32_t g_gfx_items, g_gfx_pixels, g_gfx_dropped;+#ifdef HOST+uint32_t g_peak_pals, g_peak_arena, g_peak_soft;+#endif++/* the strip: light gathered (x 128, room above for lights that add): red << 16 | blue, green; and the light still+ * getting through (255 .. 0) */+static uint32_t arb[NPX];+static uint16_t ag[NPX];+static uint8_t trans[NPX] __attribute__((aligned(4)));+static uint32_t cov[STRIP_H][VIEW_W / 32]; /* pixels with no light left from behind */+static bool strip_ready; /* the strip buffers are clear (finish_strip leaves them so) */++/* an instance in front of the blur plane, seen this frame */+typedef struct {+ Inst in;+ uint16_t x0, x1; /* on screen, clipped */+ uint8_t y0, y1;+ uint8_t pal;+ int8_t cty; /* the tile row whose slots the arena holds */+ uint16_t ar; /* its tiles (a row of them, or all if turned), in the arena */+} Item;+#ifndef ARENA+#define ARENA 2048+#endif+#define UNRES_SLOT 0xFFFE+#define EMPTY_SLOT 0xFFFF+static uint16_t arena[ARENA];+static int arena_top;+static Item items[MAX_ITEMS];+static int nitems;++/* ---------------------------------------------------------------- palettes: a texture's colors for a tint, graded */+typedef struct {+ uint32_t key;+ uint16_t frame;+ uint8_t solid; /* the tint is opaque: a tile of opaque texels hides what is behind */+ uint32_t c[16]; /* premultiplied 0xAARRGGBB; [0] transparent */+} Pal;+static Pal pals[NPAL];+static uint16_t pal_frame = 1;+static int pal_hand;++static void soft_reset(void);+static uint8_t lut3[3][256]; /* the room's curves */+static float room_sat;+static int lut_room = -1;++static void make_luts(void) {+ RoomHdr *h = g_room.h;+ for (int c = 0; c < 3; c++)+ for (int i = 0; i < 256; i++) {+ float x = i * 63.0f / 255.0f;+ int a = (int)x;+ if (a > 62) a = 62;+ float t = x - a;+ lut3[c][i] = (uint8_t)(h->lut[c][a] + (h->lut[c][a + 1] - h->lut[c][a]) * t + 0.5f);+ }+ room_sat = h->saturation;+ lut_room = g_room.id;+ soft_reset();+ for (int i = 0; i < NPAL; i++) pals[i].key = 0xFFFFFFFF;+}++static uint32_t grade(float r, float g, float b, float a) {+ /* r g b a: 0..1 straight */+ int ri = (int)(r * 255 + 0.5f), gi = (int)(g * 255 + 0.5f), bi = (int)(b * 255 + 0.5f);+ if (ri > 255) ri = 255;+ if (gi > 255) gi = 255;+ if (bi > 255) bi = 255;+ float R = lut3[0][ri], G = lut3[1][gi], B = lut3[2][bi];+ float L = 0.2126f * R + 0.7152f * G + 0.0722f * B;+ R = L + (R - L) * room_sat, G = L + (G - L) * room_sat, B = L + (B - L) * room_sat;+ R = R < 0 ? 0 : R > 255 ? 255 : R;+ G = G < 0 ? 0 : G > 255 ? 255 : G;+ B = B < 0 ? 0 : B > 255 ? 255 : B;+ int A = (int)(a * 255 + 0.5f);+ if (A > 255) A = 255;+ return (uint32_t)A << 24 | (uint32_t)(R * a + 0.5f) << 16 | (uint32_t)(G * a + 0.5f) << 8 | (uint32_t)(B * a + 0.5f);+}++static int pal_get(uint16_t tex, uint8_t tint, uint8_t flags) {+ uint32_t key = (uint32_t)tex << 16 | (uint32_t)tint << 1 | ((flags & F_LIT) ? 1 : 0);+ if (tex != TEX_NONE) {+ const TexRec *r = tex_rec(tex);+ if (r->fmt >= FMT_SOFT) return 0; /* (no colors: soft_get) */+ if (r->fmt == FMT_ALPHA2) key = 0xFFFE0000u | g_room.tints[4 * tint + 3]; /* black: only the alpha matters */+ }+ for (int i = 0; i < NPAL; i++)+ if (pals[i].key == key) {+ pals[i].frame = pal_frame;+ return i;+ }+ int s = -1;+ for (int n = 0; n < NPAL; n++) {+ int i = (pal_hand + n) % NPAL;+ if (pals[i].frame != pal_frame) {+ s = i;+ break;+ }+ }+ if (s < 0) s = pal_hand;+ pal_hand = (s + 1) % NPAL;+ Pal *p = &pals[s];+ p->key = key, p->frame = pal_frame;+ const uint8_t *t = g_room.tints + 4 * tint;+ p->solid = t[3] == 255;+ float tr = t[0] / 255.0f, tg = t[1] / 255.0f, tb = t[2] / 255.0f, ta = t[3] / 255.0f;+ if (flags & F_LIT) {+ const float *am = g_room.h->ambient;+ tr *= am[0], tg *= am[1], tb *= am[2];+ }+ p->c[0] = 0;+ if (tex == TEX_NONE) {+ p->c[1] = grade(tr, tg, tb, ta);+ return s;+ }+ const TexRec *r = tex_rec(tex);+ if (r->fmt >= FMT_SOFT) return s;+ if (r->fmt == FMT_ALPHA2) { /* (drawn black whatever the tint) */+ for (int i = 1; i < 4; i++) p->c[i] = (uint32_t)(ta * i / 3.0f * 255 + 0.5f) << 24;+ } else {+ const uint8_t *pc = section(SEC_PAL) + r->pal_off;+ for (int i = 0; i < 15; i++)+ p->c[i + 1] = grade(pc[4 * i] / 255.0f * tr, pc[4 * i + 1] / 255.0f * tg, pc[4 * i + 2] / 255.0f * tb,+ pc[4 * i + 3] / 255.0f * ta);+ }+ return s;+}++/* ---------------------------------------------------------------- smooth textures: a few texels, graded for a tint (those of+ * one color are alpha only, read in place) */+#ifndef SOFT_POOL+#define SOFT_POOL 768+#endif+#ifndef NSOFT+#define NSOFT 16+#endif+static uint32_t soft_pool[SOFT_POOL];+typedef struct {+ uint32_t key;+ uint16_t frame, off, n;+} SoftEnt;+static SoftEnt soft_ent[NSOFT];+static int nsoft, soft_top;++static void soft_reset(void) { nsoft = 0, soft_top = 0; }++uint32_t g_soft_misses;+static const uint32_t *soft_get(uint16_t tex, uint8_t tint, uint8_t flags) {+ const TexRec *rr = tex_rec(tex);+ if (rr->fmt == FMT_SOFTA) return (const uint32_t *)(const void *)(section(SEC_SOFT) + rr->pal_off); /* (alpha, in place) */+ uint32_t key = (uint32_t)tex << 16 | (uint32_t)tint << 1 | ((flags & F_LIT) ? 1 : 0);+ for (int i = 0; i < nsoft; i++)+ if (soft_ent[i].key == key) {+ soft_ent[i].frame = pal_frame;+ return soft_pool + soft_ent[i].off;+ }+ const TexRec *r = rr;+ int n = r->w * r->h; /* (in words) */+ g_soft_misses++;+ if (n > SOFT_POOL) return NULL;+ if (soft_top + n > SOFT_POOL || nsoft == NSOFT) {+ /* keep this frame's, packed */+ int k = 0, top = 0;+ for (int i = 0; i < nsoft; i++) {+ if (soft_ent[i].frame != pal_frame) continue;+ memmove(soft_pool + top, soft_pool + soft_ent[i].off, soft_ent[i].n * 4u);+ soft_ent[k] = soft_ent[i];+ soft_ent[k].off = (uint16_t)top;+ top += soft_ent[k].n, k++;+ }+ nsoft = k, soft_top = top;+ if (soft_top + n > SOFT_POOL || nsoft == NSOFT) return NULL;+ }+ uint32_t *px = soft_pool + soft_top;+ const uint8_t *src = section(SEC_SOFT) + r->pal_off;+ lz_decode(src + 4, rd32(src), (uint8_t *)px, (uint32_t)n * 4);+ const uint8_t *t = g_room.tints + 4 * tint;+ float tr = t[0] / 255.0f, tg = t[1] / 255.0f, tb = t[2] / 255.0f, ta = t[3] / 255.0f;+ if (flags & F_LIT) {+ const float *am = g_room.h->ambient;+ tr *= am[0], tg *= am[1], tb *= am[2];+ }+ for (int i = 0; i < n; i++) {+ const uint8_t *c = (const uint8_t *)&px[i]; /* premultiplied r g b a bytes */+ int a = c[3];+ if (!a) {+ px[i] = 0;+ continue;+ }+ float ia = 1.0f / a;+ px[i] = grade(c[0] * ia * tr, c[1] * ia * tg, c[2] * ia * tb, a / 255.0f * ta);+ }+ soft_ent[nsoft++] = (SoftEnt){key, pal_frame, (uint16_t)soft_top, (uint16_t)n};+ soft_top += n;+ return px;+}++/* ---------------------------------------------------------------- an item's mapping from screen to texels */+typedef struct {+ float ox, oy; /* screen position of texel (0, 0) */+ float iux, iuy, ivx, ivy; /* u = iux*(x-ox) + iuy*(y-oy), v = ivx*(x-ox) + ivy*(y-oy) */+ float pu, pv; /* (axis aligned) screen pixels a texel along u and v, signed */+ bool rot;+} Map;++static float inst_k(const Inst *in) { return FOCAL / (in->z * (1.0f / 128) - CAM_Z); }++/* the instance's u and v steps on screen (pixels a texel) */+static void inst_axes(const Inst *in, float k, float *ux, float *uy, float *vx, float *vy) {+ float a = f16(in->a) * k, b = f16(in->b) * k;+ if (in->flags & F_ROT) {+ float t = in->rot * (6.2831853f / 65536.0f), c = cosf(t), s = sinf(t);+ /* world u = a (c, s), v = b (-s, c); screen y is down */+ *ux = a * c, *uy = -a * s, *vx = -b * s, *vy = -b * c;+ } else+ *ux = a, *uy = 0, *vx = 0, *vy = -b;+}++static void inst_map(const Inst *in, Map *m) {+ float k = inst_k(in);+ m->ox = VIEW_W / 2 + (in->ax * (1.0f / 64) - g_cam_x) * k;+ m->oy = VIEW_H / 2 - (in->ay * (1.0f / 64) - g_cam_y) * k;+ float ax, ay, bx, by;+ inst_axes(in, k, &ax, &ay, &bx, &by);+ if (in->flags & F_ROT) {+ /* screen = o + u (ax, ay) + v (bx, by): the inverse */+ float det = ax * by - bx * ay;+ if (det == 0) det = 1e-6f;+ m->iux = by / det, m->iuy = -bx / det, m->ivx = -ay / det, m->ivy = ax / det;+ m->pu = ax, m->pv = by;+ m->rot = true;+ } else {+ m->pu = ax, m->pv = by;+ m->iux = 1 / ax, m->iuy = 0, m->ivx = 0, m->ivy = 1 / by;+ m->rot = false;+ }+}++__attribute__((noinline)) static bool item_box(const Inst *in, Item *it) {+ float k = inst_k(in);+ if (!(k > 0) || k > 400) return false;+ float bx0, by0, bx1, by1;+ if (in->flags & F_SOLID) {+ float ox = VIEW_W / 2 + (in->ax * (1.0f / 64) - g_cam_x) * k, oy = VIEW_H / 2 - (in->ay * (1.0f / 64) - g_cam_y) * k;+ bx0 = ox, by0 = oy, bx1 = ox + f16(in->a) * k, by1 = oy - f16(in->b) * k;+ } else {+ const TexRec *r = tex_rec(in->tex);+ Map m;+ inst_map(in, &m);+ if (in->flags & F_ROT) {+ float ux, uy, vx, vy;+ inst_axes(in, k, &ux, &uy, &vx, &vy);+ ux *= r->w, uy *= r->w, vx *= r->h, vy *= r->h;+ float xs[4] = {m.ox, m.ox + ux, m.ox + vx, m.ox + ux + vx}, ys[4] = {m.oy, m.oy + uy, m.oy + vy, m.oy + uy + vy};+ bx0 = bx1 = xs[0], by0 = by1 = ys[0];+ for (int i = 1; i < 4; i++) {+ if (xs[i] < bx0) bx0 = xs[i];+ if (xs[i] > bx1) bx1 = xs[i];+ if (ys[i] < by0) by0 = ys[i];+ if (ys[i] > by1) by1 = ys[i];+ }+ } else {+ float ex = m.ox + m.pu * r->w, ey = m.oy + m.pv * r->h;+ bx0 = m.ox < ex ? m.ox : ex, bx1 = m.ox < ex ? ex : m.ox;+ by0 = m.oy < ey ? m.oy : ey, by1 = m.oy < ey ? ey : m.oy;+ }+ }+ if (bx1 <= 0 || by1 <= 0 || bx0 >= VIEW_W || by0 >= VIEW_H) return false;+ int a = (int)(bx0 + 0.5f), b = (int)(by0 + 0.5f), c = (int)(bx1 + 0.5f), d = (int)(by1 + 0.5f);+ if (a < 0) a = 0;+ if (b < 0) b = 0;+ if (c > VIEW_W) c = VIEW_W;+ if (d > VIEW_H) d = VIEW_H;+ if (a >= c || b >= d) return false;+ it->x0 = (uint16_t)a, it->y0 = (uint8_t)b, it->x1 = (uint16_t)c, it->y1 = (uint8_t)d;+ return true;+}++/* ---------------------------------------------------------------- back to front blending (the small background) */+static inline uint32_t blend_over(uint32_t d, uint32_t s) {+ uint32_t ia = 256 - (s >> 24);+ uint32_t rb = ((d & 0xFF00FF) * ia >> 8) & 0xFF00FF, g = ((d & 0xFF00) * ia >> 8) & 0xFF00;+ return (s & 0xFFFFFF) + rb + g;+}+static inline uint32_t blend_mode(uint32_t d, uint32_t s, int mode) {+ int dr = d >> 16 & 255, dg = d >> 8 & 255, db = d & 255;+ int sr = s >> 16 & 255, sg = s >> 8 & 255, sb = s & 255, sa = s >> 24;+ int r, g, b;+ switch (mode) {+ case BL_ADD: r = dr + sr, g = dg + sg, b = db + sb; break;+ case BL_SCREEN: r = dr + sr - ((dr * sr * 257 + 257) >> 16), g = dg + sg - ((dg * sg * 257 + 257) >> 16), b = db + sb - ((db * sb * 257 + 257) >> 16); break;+ case BL_LINEARLIGHT: r = dr + 2 * sr - sa, g = dg + 2 * sg - sa, b = db + 2 * sb - sa; break;+ case BL_MULTIPLY: r = dr * (256 - sa + sr) >> 8, g = dg * (256 - sa + sg) >> 8, b = db * (256 - sa + sb) >> 8; break;+ default: return blend_over(d, s);+ }+ r = r < 0 ? 0 : r > 255 ? 255 : r;+ g = g < 0 ? 0 : g > 255 ? 255 : g;+ b = b < 0 ? 0 : b > 255 ? 255 : b;+ return (uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b;+}++/* ---------------------------------------------------------------- front to back: a pixel takes a source's light */+static inline void cover(int row, int x) { cov[row][x >> 5] |= 1u << (x & 31); }+/* [a, b) */+static void cover_run(int row, int a, int b) {+ uint32_t *cv = cov[row];+ while (a < b) {+ int w = a >> 5, n = 32 - (a & 31);+ if (n > b - a) n = b - a;+ cv[w] |= (n == 32 ? 0xFFFFFFFFu : ((1u << n) - 1)) << (a & 31);+ a += n;+ }+}+static inline int code_of(const uint8_t *codes, int tx) { return codes[tx >> 2] >> ((tx & 3) * 2) & 3; }++/* s: premultiplied 0xAARRGGBB; p: the pixel's index in the strip */+#ifdef HOST+uint32_t g_kind_px[6];+#define COUNT_PX(k, n) (g_kind_px[k] += (uint32_t)(n))+#else+#define COUNT_PX(k, n) ((void)0)+#endif+static inline void take_over(int row, int x, int p, uint32_t s) {+ uint32_t t = trans[p], tt = (t + 1) >> 1;+ arb[p] += (s & 0xFF00FF) * tt;+ ag[p] = (uint16_t)(ag[p] + ((s >> 8) & 255) * tt);+ t = (t * (255 - (s >> 24)) * 257) >> 16;+ if (t < 2) t = 0, cover(row, x);+ trans[p] = (uint8_t)t;+}++#define ACC_TOP (65535 - 255 * 128 - 1024) /* lights that add stop here: what is behind, and the dither, still fit */+static void take_mode(int row, int x, int p, uint32_t s, int mode) {+ int32_t t = trans[p], tt = (t + 1) >> 1;+ int32_t sr = s >> 16 & 255, sg = s >> 8 & 255, sb = s & 255, sa = s >> 24;+ int32_t r = arb[p] >> 16, g = ag[p], b = arb[p] & 0xFFFF;+ switch (mode) {+ case BL_ADD: r += sr * tt, g += sg * tt, b += sb * tt; break;+ case BL_SCREEN: {+ r += sr * tt, g += sg * tt, b += sb * tt;+ int32_t m = sr > sg ? sr : sg;+ m = m > sb ? m : sb;+ t = (t * (255 - m) * 257) >> 16;+ break;+ }+ case BL_LINEARLIGHT: r += (2 * sr - sa) * tt, g += (2 * sg - sa) * tt, b += (2 * sb - sa) * tt; break;+ case BL_MULTIPLY: t = (t * (255 - sa + (sr + sg + sb) / 3) * 257) >> 16; break;+ default:+ r += sr * tt, g += sg * tt, b += sb * tt;+ t = (t * (255 - sa) * 257) >> 16;+ break;+ }+ r = r < 0 ? 0 : r > ACC_TOP ? ACC_TOP : r;+ g = g < 0 ? 0 : g > ACC_TOP ? ACC_TOP : g;+ b = b < 0 ? 0 : b > ACC_TOP ? ACC_TOP : b;+ arb[p] = (uint32_t)r << 16 | (uint32_t)b;+ ag[p] = (uint16_t)g;+ if (t < 2) t = 0, cover(row, x);+ trans[p] = (uint8_t)t;+}++#define TAKE(row, x, p, s) (mode ? take_mode(row, x, p, s, mode) : take_over(row, x, p, s))++/* the first pixel in [x, b) with light left (b if none), and the first after it with none */+static inline int open_from(const uint32_t *cv, int x, int b) {+ while (x < b) {+ uint32_t w = ~cv[x >> 5] >> (x & 31);+ if (w) {+ x += __builtin_ctz(w);+ return x < b ? x : b;+ }+ x = (x | 31) + 1;+ }+ return b;+}+static inline int closed_from(const uint32_t *cv, int x, int b) {+ while (x < b) {+ uint32_t w = cv[x >> 5] >> (x & 31);+ if (w) {+ x += __builtin_ctz(w);+ return x < b ? x : b;+ }+ x = (x | 31) + 1;+ }+ return b;+}++/* the pixels i in [0, n) where 0 <= u0 + du i < U and 0 <= v0 + dv i < V (16.16): [*i0, *i1) */+static void clip_lin(int32_t u0, int32_t du, int32_t U, int n, int *i0, int *i1) {+ int a = *i0, b = *i1;+ if (du == 0) {+ if (u0 < 0 || u0 >= U) a = b;+ } else if (du > 0) {+ if (u0 < 0) {+ int k = (-u0 + du - 1) / du;+ if (k > a) a = k;+ }+ int k = u0 >= U ? 0 : (U - 1 - u0) / du + 1; /* first i with u >= U */+ if (k < b) b = k;+ } else {+ if (u0 >= U) {+ int k = (u0 - U) / -du + 1;+ if (k > a) a = k;+ }+ int k = u0 < 0 ? 0 : u0 / -du + 1; /* first i with u < 0 */+ if (k < b) b = k;+ }+ (void)n;+ *i0 = a, *i1 = b > a ? b : a;+}++static inline uint32_t rgb_of565(uint32_t c) { return (c >> 11) << 19 | (c >> 5 & 63) << 10 | (c & 31) << 3; }++static inline uint32_t lerp4(uint32_t a, uint32_t b, uint32_t w) { /* w: 0..256 */+ uint32_t iw = 256 - w;+ uint32_t rb = ((a & 0xFF00FF) * iw + (b & 0xFF00FF) * w) >> 8 & 0xFF00FF;+ uint32_t ag = (((a >> 8) & 0xFF00FF) * iw + ((b >> 8) & 0xFF00FF) * w) & 0xFF00FF00;+ return rb | ag;+}++typedef struct {+ uint16_t tex, tw;+ const TexRec *r;+ uint16_t *slots; /* tw * th, or NULL */+ const uint32_t *pal;+} BiTex;++static inline const uint8_t *bi_tile(const BiTex *b, int tx, int ty) {+ if (b->slots && !g_tex_overload) {+ uint16_t *e = b->slots + ty * b->tw + tx;+ if (*e == UNRES_SLOT) {+ int q = tex_slot(b->tex, tx, ty);+ *e = q < 0 ? EMPTY_SLOT : (uint16_t)q;+ }+ return *e == EMPTY_SLOT ? NULL : tex_slot_px(*e);+ }+ return tex_tile(b->tex, tx, ty);+}++static inline uint32_t bi_texel(const BiTex *b, int u, int v) {+ if ((unsigned)u >= b->r->w || (unsigned)v >= b->r->h) return 0;+ const uint8_t *t = bi_tile(b, u >> 4, v >> 4);+ if (!t) return 0;+ int ur = u & 15, vr = v & 15;+ return b->pal[t[vr * 8 + (ur >> 1)] >> ((ur & 1) * 4) & 15];+}++/* the four texels around (u, v) (16.16), mixed */+static inline uint32_t bi_sample(const BiTex *b, int32_t u, int32_t v) {+ int c = u >> 16, rr = v >> 16;+ uint32_t fu = (uint32_t)(u >> 8) & 255, fv = (uint32_t)(v >> 8) & 255;+ uint32_t t00, t10, t01, t11;+ if ((c & 15) != 15 && (rr & 15) != 15 && (unsigned)c < (unsigned)(b->r->w - 1) && (unsigned)rr < (unsigned)(b->r->h - 1)) {+ const uint8_t *t = bi_tile(b, c >> 4, rr >> 4);+ if (!t) return 0;+ int ur = c & 15, vr = rr & 15;+ const uint8_t *row = t + vr * 8;+ int i0 = row[ur >> 1] >> ((ur & 1) * 4) & 15, i1 = row[(ur + 1) >> 1] >> (((ur + 1) & 1) * 4) & 15;+ row += 8;+ int i2 = row[ur >> 1] >> ((ur & 1) * 4) & 15, i3 = row[(ur + 1) >> 1] >> (((ur + 1) & 1) * 4) & 15;+ t00 = b->pal[i0], t10 = b->pal[i1], t01 = b->pal[i2], t11 = b->pal[i3];+ } else {+ t00 = bi_texel(b, c, rr), t10 = bi_texel(b, c + 1, rr), t01 = bi_texel(b, c, rr + 1), t11 = bi_texel(b, c + 1, rr + 1);+ }+ return lerp4(lerp4(t00, t10, fu), lerp4(t01, t11, fu), fv);+}++/* ---------------------------------------------------------------- one item in a strip, on the pixels with light left */+typedef struct {+ int idx, mode, row, sy0;+ const Inst *in;+ const TexRec *r;+ const Map *m;+ const uint32_t *pal;+ Item *it;+} Ctx;++/* a run [a, b) of row y (all pixels with light left), by kind */+static void run_solid(const Ctx *c, int y, int a, int b) {+ int mode = c->mode;+ uint32_t s = c->pal[1];+ for (int x = a; x < b; x++) TAKE(c->row, x, c->row * VIEW_W + x, s);+}++static void run_axis(const Ctx *c, int y, int a, int b, uint16_t *tp, int ty, int vr) {+ const Map *m = c->m;+ const TexRec *r = c->r;+ int mode = c->mode, row = c->row, W = r->w;+ bool a2 = r->fmt == FMT_ALPHA2, solid = pals[c->it->pal].solid;+ const uint8_t *codes = tex_row_codes(c->in->tex, ty);+ int sh = TILE_SHIFT(r->fmt), um = (1 << sh) - 1;+ int32_t du = (int32_t)(65536.0f / m->pu);+ int32_t u = (int32_t)((a + 0.5f - m->ox) * m->iux * 65536.0f);+ int x = a, p = row * VIEW_W + a;+ while (x < b) {+ int ui = u >> 16;+ if ((unsigned)ui >= (unsigned)W) {+ x++, p++, u += du;+ continue;+ }+ int tx = ui >> sh;+ int32_t edge = du > 0 ? ((tx + 1) << (16 + sh)) : ((tx << (16 + sh)) - 1);+ int n = (int)((edge - u) / du) + 1;+ if (n > b - x) n = b - x;+ if (n < 1) n = 1;+ uint16_t sl = tp[tx];+ if (sl == UNRES_SLOT) {+ int q = tex_slot(c->in->tex, tx, ty);+ sl = tp[tx] = q < 0 ? EMPTY_SLOT : (uint16_t)q;+ }+ if (sl == EMPTY_SLOT) {+ x += n, p += n, u += du * n;+ continue;+ }+ const uint8_t *t = tex_slot_px(sl);+ int e = x + n;+ if (solid && !mode && code_of(codes, tx) == 3) {+ /* a tile of opaque texels over everything behind it: nothing is left from behind */+ int x0 = x;+ if (a2) {+ uint32_t s = c->pal[3];+ for (; x < e; x++, p++) {+ uint32_t tt = (trans[p] + 1u) >> 1;+ arb[p] += (s & 0xFF00FF) * tt, ag[p] = (uint16_t)(ag[p] + ((s >> 8) & 255) * tt), trans[p] = 0;+ }+ u += du * (e - x0);+ } else {+ const uint8_t *rw = t + vr * 8;+ for (; x < e; x++, p++, u += du) {+ int ur = (u >> 16) & 15;+ uint32_t s = c->pal[rw[ur >> 1] >> ((ur & 1) << 2) & 15], tt = (trans[p] + 1u) >> 1;+ arb[p] += (s & 0xFF00FF) * tt, ag[p] = (uint16_t)(ag[p] + ((s >> 8) & 255) * tt), trans[p] = 0;+ }+ }+ cover_run(row, x0, e);+ continue;+ }+ if (a2) {+ const uint8_t *rw = t + vr * 8;+ for (; x < e; x++, p++, u += du) {+ int ur = (u >> 16) & um, ci = rw[ur >> 2] >> ((ur & 3) * 2) & 3;+ if (ci) TAKE(row, x, p, c->pal[ci]);+ }+ } else if (!mode) {+ const uint8_t *rw = t + vr * 8;+ for (; x < e; x++, p++, u += du) {+ int ur = (u >> 16) & 15, ci = rw[ur >> 1] >> ((ur & 1) << 2) & 15;+ if (ci) take_over(row, x, p, c->pal[ci]);+ }+ } else {+ const uint8_t *rw = t + vr * 8;+ for (; x < e; x++, p++, u += du) {+ int ur = (u >> 16) & 15, ci = rw[ur >> 1] >> ((ur & 1) << 2) & 15;+ if (ci) take_mode(row, x, p, c->pal[ci], mode);+ }+ }+ }+}++static inline const uint8_t *turned_tile(uint16_t *rtp, uint16_t tex, int tw, int tx, int ty) {+ if (rtp && !g_tex_overload) {+ uint16_t *e = rtp + ty * tw + tx;+ if (*e == UNRES_SLOT) {+ int q = tex_slot(tex, tx, ty);+ *e = q < 0 ? EMPTY_SLOT : (uint16_t)q;+ }+ return *e == EMPTY_SLOT ? NULL : tex_slot_px(*e);+ }+ return tex_tile(tex, tx, ty);+}++static void run_turned(const Ctx *c, int y, int a, int b, int *last_key, const uint8_t **last_t) {+ const Map *m = c->m;+ const TexRec *r = c->r;+ int mode = c->mode, row = c->row;+ int sh = TILE_SHIFT(r->fmt), um = (1 << sh) - 1, tw = r->tw;+ uint16_t tex = c->in->tex;+ const uint32_t *pal = c->pal;+ uint16_t *rtp = c->it->ar != 0xFFFF ? arena + c->it->ar : NULL;+ int32_t dux = (int32_t)(m->iux * 65536), dvx = (int32_t)(m->ivx * 65536);+ int32_t W16 = (int32_t)r->w << 16, H16 = (int32_t)r->h << 16;+ float fx = a + 0.5f - m->ox, fy = y + 0.5f - m->oy;+ int32_t u = (int32_t)((m->iux * fx + m->iuy * fy) * 65536), v = (int32_t)((m->ivx * fx + m->ivy * fy) * 65536);+ int i0 = 0, i1 = b - a;+ clip_lin(u, dux, W16, b - a, &i0, &i1);+ clip_lin(v, dvx, H16, b - a, &i0, &i1);+ u += dux * i0, v += dvx * i0;+ int lk = *last_key;+ const uint8_t *lt = *last_t;+#define TURNED(TEXEL, PUT) \+ for (int x = a + i0, e = a + i1, p = row * VIEW_W + a + i0; x < e; x++, p++, u += dux, v += dvx) { \+ int ui = u >> 16, vi = v >> 16, tkey = (vi >> 4) << 8 | (ui >> sh); \+ if (tkey != lk) lk = tkey, lt = turned_tile(rtp, tex, tw, ui >> sh, vi >> 4); \+ if (!lt) continue; \+ int ur = ui & um, vr = vi & 15, ci = TEXEL; \+ if (ci) PUT; \+ }+ if (r->fmt == FMT_ALPHA2) {+ if (!mode) TURNED(lt[vr * 8 + (ur >> 2)] >> ((ur & 3) * 2) & 3, take_over(row, x, p, pal[ci]))+ else TURNED(lt[vr * 8 + (ur >> 2)] >> ((ur & 3) * 2) & 3, take_mode(row, x, p, pal[ci], mode))+ } else {+ if (!mode) TURNED(lt[vr * 8 + (ur >> 1)] >> ((ur & 1) * 4) & 15, take_over(row, x, p, pal[ci]))+ else TURNED(lt[vr * 8 + (ur >> 1)] >> ((ur & 1) * 4) & 15, take_mode(row, x, p, pal[ci], mode))+ }+#undef TURNED+ *last_key = lk, *last_t = lt;+}++/* smooth textures: a few texels, interpolated */+static void run_soft(const Ctx *c, int y, int a, int b, const uint32_t *tx, uint32_t crb, uint32_t cg, uint32_t ta) {+ const Map *m = c->m;+ const TexRec *r = c->r;+ int mode = c->mode, row = c->row, W = r->w, H = r->h;+ bool mono = r->fmt == FMT_SOFTA;+ const uint8_t *al = (const uint8_t *)tx;+ float fx = a + 0.5f - m->ox, fy = y + 0.5f - m->oy;+ int32_t u0 = (int32_t)((m->iux * fx + m->iuy * fy - 0.5f) * 65536), v0 = (int32_t)((m->ivx * fx + m->ivy * fy - 0.5f) * 65536);+ int32_t dux = (int32_t)(m->iux * 65536), dvx = (int32_t)(m->ivx * 65536);+ /* where all four texels are inside (the edges of these textures are clear) */+ int i0 = 0, i1 = b - a;+ clip_lin(u0, dux, (W - 1) << 16, b - a, &i0, &i1);+ clip_lin(v0, dvx, (H - 1) << 16, b - a, &i0, &i1);+ if (i0 >= i1) return;+ u0 += dux * i0, v0 += dvx * i0;+ int x = a + i0, e = a + i1, p = row * VIEW_W + a + i0;+ if (mono && dvx == 0) {+ /* upright, one color: the row's two texel rows mixed once per texel column */+ int rr = v0 >> 16;+ uint32_t fv = (uint32_t)(v0 >> 8) & 255;+ const uint8_t *r0 = al + rr * W, *r1 = r0 + W;+ int lc = -1;+ uint32_t c0 = 0, c1 = 0;+ for (; x < e; x++, p++, u0 += dux) {+ int cx = u0 >> 16;+ if (cx != lc) {+ lc = cx;+ c0 = (r0[cx] * (256 - fv) + r1[cx] * fv) * ta >> 8, c1 = (r0[cx + 1] * (256 - fv) + r1[cx + 1] * fv) * ta >> 8;+ }+ uint32_t fu = (uint32_t)(u0 >> 8) & 255, aa = (c0 * (256 - fu) + c1 * fu) >> 16;+ if (!aa) continue;+ uint32_t s = aa << 24 | ((crb * aa >> 8) & 0xFF00FF) | ((cg * aa >> 8) & 0xFF00);+ TAKE(row, x, p, s);+ }+ return;+ }+ for (; x < e; x++, p++, u0 += dux, v0 += dvx) {+ int cx = u0 >> 16, rr = v0 >> 16;+ uint32_t fu = (uint32_t)(u0 >> 8) & 255, fv = (uint32_t)(v0 >> 8) & 255, s;+ if (mono) {+ const uint8_t *p0 = al + rr * W + cx, *p1 = p0 + W;+ uint32_t top = p0[0] * (256 - fu) + p0[1] * fu, bot = p1[0] * (256 - fu) + p1[1] * fu;+ uint32_t aa = ((top * (256 - fv) + bot * fv) >> 16) * ta >> 8;+ if (!aa) continue;+ s = aa << 24 | ((crb * aa >> 8) & 0xFF00FF) | ((cg * aa >> 8) & 0xFF00);+ } else {+ const uint32_t *p0 = tx + rr * W + cx, *p1 = p0 + W;+ s = lerp4(lerp4(p0[0], p0[1], fu), lerp4(p1[0], p1[1], fu), fv);+ if (!(s >> 24)) continue;+ }+ TAKE(row, x, p, s);+ }+}++/* the blurred background's own textures, if drawn in front of the blur plane: interpolated tiles */+static void run_bilinear(const Ctx *c, int y, int a, int b, BiTex *bt) {+ const Map *m = c->m;+ int mode = c->mode, row = c->row;+ float fx = a + 0.5f - m->ox, fy = y + 0.5f - m->oy;+ int32_t u = (int32_t)((m->iux * fx + m->iuy * fy - 0.5f) * 65536) + 65536, v = (int32_t)((m->ivx * fx + m->ivy * fy - 0.5f) * 65536) + 65536;+ int32_t dux = (int32_t)(m->iux * 65536), dvx = (int32_t)(m->ivx * 65536);+ int i0 = 0, i1 = b - a;+ clip_lin(u, dux, (int32_t)(c->r->w + 1) << 16, b - a, &i0, &i1);+ clip_lin(v, dvx, (int32_t)(c->r->h + 1) << 16, b - a, &i0, &i1);+ u += dux * i0 - 65536, v += dvx * i0 - 65536;+ for (int x = a + i0, e = a + i1, p = row * VIEW_W + a + i0; x < e; x++, p++, u += dux, v += dvx) {+ uint32_t s = bi_sample(bt, u, v);+ if (s >> 24) TAKE(row, x, p, s);+ }+}++__attribute__((noinline)) static void draw_item(int idx, Item *it, int sy0, int sy1) {+ const Inst *in = &it->in;+ int ya = it->y0 > sy0 ? it->y0 : sy0, yb = it->y1 < sy1 ? it->y1 : sy1;+ if (ya >= yb) return;+ Ctx c = {idx, in->flags & F_BLEND, 0, sy0, in, NULL, NULL, pals[it->pal].c, it};+ Map m;+ int kind = 0; /* 0 solid, 1 axis, 2 turned, 3 soft, 4 bilinear */+ const uint32_t *soft = NULL;+ uint32_t crb = 0, cg = 0, ta = 256;+ BiTex bt;+ if (!(in->flags & F_SOLID)) {+ c.r = tex_rec(in->tex);+ inst_map(in, &m);+ c.m = &m;+ if (c.r->fmt >= FMT_SOFT) {+ kind = 3;+ soft = soft_get(in->tex, in->tint, in->flags);+ if (!soft) return;+ if (c.r->fmt == FMT_SOFTA) {+ const uint8_t *t = g_room.tints + 4 * in->tint;+ float tr = t[0] / 255.0f, tg = t[1] / 255.0f, tb = t[2] / 255.0f;+ if (in->flags & F_LIT) tr *= g_room.h->ambient[0], tg *= g_room.h->ambient[1], tb *= g_room.h->ambient[2];+ uint32_t base = c.r->map_off;+ uint32_t col = grade((base & 255) / 255.0f * tr, (base >> 8 & 255) / 255.0f * tg, (base >> 16 & 255) / 255.0f * tb, 1);+ crb = col & 0xFF00FF, cg = col & 0xFF00, ta = t[3] + 1u;+ }+ } else if ((c.r->flags & TEX_SMOOTH) && c.r->fmt == FMT_PAL4) {+ kind = 4;+ bt = (BiTex){in->tex, c.r->tw, c.r, NULL, c.pal};+ if (it->ar != 0xFFFF && (in->flags & F_ROT)) bt.slots = arena + it->ar;+ } else+ kind = m.rot ? 2 : 1;+ }+#ifdef HOST+ if (getenv("PROBE")) {+ int px, py;+ sscanf(getenv("PROBE"), "%d,%d", &px, &py);+ if (py >= ya && py < yb && px >= it->x0 && px < it->x1)+ fprintf(stderr, "item %d kind %d tex %u fmt %d blend %d z %.2f trans-before %u\n", idx, kind, in->tex,+ c.r ? c.r->fmt : -1, c.mode, in->z / 128.0, trans[(py - sy0) * VIEW_W + px]);+ }+#endif+ uint16_t local[64], *tp = NULL;+ if (kind == 1) {+ tp = it->ar != 0xFFFF ? arena + it->ar : local;+ if (tp == local) it->cty = -1;+ }+ int last_key = -1;+ const uint8_t *last_t = NULL;+ for (int y = ya; y < yb; y++) {+ c.row = y - sy0;+ const uint32_t *cv = cov[c.row];+ int x = open_from(cv, it->x0, it->x1);+ if (x >= it->x1) continue;+ int ty = 0, vr = 0;+ if (kind == 1) {+ int v = (int)((y + 0.5f - m.oy) * m.ivy);+ if (v < 0 || v >= c.r->h) continue;+ ty = v / TILE, vr = v & (TILE - 1);+ if (ty != it->cty || g_tex_overload) {+ it->cty = (int16_t)ty;+ for (int i = 0; i < c.r->tw; i++) tp[i] = UNRES_SLOT;+ }+ }+ while (x < it->x1) {+ int e = closed_from(cv, x, it->x1);+ COUNT_PX(kind, e - x);+#ifdef HOST+ if (kind == 3) COUNT_PX(5, (e - x) * (c.r->fmt == FMT_SOFTA ? 1 : 0) * (m.rot ? 1 : 0));+#endif+ switch (kind) {+ case 0: run_solid(&c, y, x, e); break;+ case 1: run_axis(&c, y, x, e, tp, ty, vr); break;+ case 2: run_turned(&c, y, x, e, &last_key, &last_t); break;+ case 3: run_soft(&c, y, x, e, soft, crb, cg, ta); break;+ default: run_bilinear(&c, y, x, e, &bt); break;+ }+ x = open_from(cv, e, it->x1);+ }+ }+}++/* ---------------------------------------------------------------- the background: what is behind the blur plane,+ * drawn small, blurred and stretched behind the rest (as LightBlurredBackground does) */+#define BG_S 4+#define BG_W (VIEW_W / BG_S)+#define BG_H (VIEW_H / BG_S)+static uint16_t bgbuf[BG_W * BG_H]; /* RGB565 */+static bool bg_on;++static inline void bg_put(uint16_t *d, uint32_t s, int mode) {+ uint32_t dd = rgb_of565(*d);+ dd = mode ? blend_mode(dd, s, mode) : blend_over(dd, s);+ *d = (uint16_t)((dd >> 8 & 0xF800) | (dd >> 5 & 0x07E0) | (dd >> 3 & 0x001F));+}++/* an item behind the blur plane, into the small background (back to front), sampled at the centers of its pixels */+static void draw_bg_item(Item *it) {+ const Inst *in = &it->in;+ int mode = in->flags & F_BLEND;+ const uint32_t *pal = pals[it->pal].c;+ int bx0 = it->x0 / BG_S, by0 = it->y0 / BG_S, bx1 = (it->x1 + BG_S - 1) / BG_S, by1 = (it->y1 + BG_S - 1) / BG_S;+ if (in->flags & F_SOLID) {+ /* the pixels whose centers are in the box */+ int a = (it->x0 + BG_S / 2) / BG_S, b = (it->x1 + BG_S / 2) / BG_S, c = (it->y0 + BG_S / 2) / BG_S, d = (it->y1 + BG_S / 2) / BG_S;+ for (int by = c; by < d; by++)+ for (int bx = a; bx < b; bx++) bg_put(bgbuf + by * BG_W + bx, pal[1], mode);+ return;+ }+ const TexRec *r = tex_rec(in->tex);+ Map m;+ inst_map(in, &m);+ const uint32_t *soft = NULL;+ uint32_t crb = 0, cg = 0, ta = 256;+ if (r->fmt >= FMT_SOFT) {+ soft = soft_get(in->tex, in->tint, in->flags);+ if (!soft) return;+ if (r->fmt == FMT_SOFTA) {+ const uint8_t *t = g_room.tints + 4 * in->tint;+ float tr = t[0] / 255.0f, tg = t[1] / 255.0f, tb = t[2] / 255.0f;+ if (in->flags & F_LIT) tr *= g_room.h->ambient[0], tg *= g_room.h->ambient[1], tb *= g_room.h->ambient[2];+ uint32_t base = r->map_off;+ uint32_t c = grade((base & 255) / 255.0f * tr, (base >> 8 & 255) / 255.0f * tg, (base >> 16 & 255) / 255.0f * tb, 1);+ crb = c & 0xFF00FF, cg = c & 0xFF00, ta = t[3] + 1u;+ }+ }+ BiTex bt = {in->tex, r->tw, r, NULL, pal};+ if (it->ar != 0xFFFF && (in->flags & F_ROT)) bt.slots = arena + it->ar;+ int W = r->w, H = r->h;+ /* texel coordinates (16.16) less half a texel: where bilinear samples are centered */+ int32_t du = (int32_t)(m.iux * BG_S * 65536), dv = (int32_t)(m.ivx * BG_S * 65536);+ for (int by = by0; by < by1; by++) {+ uint16_t *d16 = bgbuf + by * BG_W;+ float fx = bx0 * BG_S + BG_S * 0.5f - m.ox, fy = by * BG_S + BG_S * 0.5f - m.oy;+ int32_t u = (int32_t)((m.iux * fx + m.iuy * fy - 0.5f) * 65536), v = (int32_t)((m.ivx * fx + m.ivy * fy - 0.5f) * 65536);+ int i0 = 0, i1 = bx1 - bx0;+ if (r->fmt == FMT_ALPHA2) {+ /* nearest */+ u += 32768, v += 32768;+ clip_lin(u, du, W << 16, i1, &i0, &i1);+ clip_lin(v, dv, H << 16, i1, &i0, &i1);+ u += du * i0, v += dv * i0;+ for (int bx = bx0 + i0; bx < bx0 + i1; bx++, u += du, v += dv) {+ int ui = u >> 16, vi = v >> 16;+ const uint8_t *t = bi_tile(&bt, ui >> 5, vi >> 4);+ if (!t) continue;+ int ur = ui & 31, vr = vi & 15, ci = t[vr * 8 + (ur >> 2)] >> ((ur & 3) * 2) & 3;+ if (ci) bg_put(d16 + bx, pal[ci], mode);+ }+ } else if (r->fmt == FMT_PAL4) {+ /* bilinear: where any of the four texels is inside */+ clip_lin(u + 65536, du, (W + 1) << 16, i1, &i0, &i1);+ clip_lin(v + 65536, dv, (H + 1) << 16, i1, &i0, &i1);+ u += du * i0, v += dv * i0;+ for (int bx = bx0 + i0; bx < bx0 + i1; bx++, u += du, v += dv) {+ uint32_t s = bi_sample(&bt, u, v);+ if (s >> 24) bg_put(d16 + bx, s, mode);+ }+ } else {+ /* smooth: bilinear, the edges repeated */+ u += du * i0, v += dv * i0;+ for (int bx = bx0 + i0; bx < bx0 + i1; bx++, u += du, v += dv) {+ int c = u >> 16, rr = v >> 16;+ uint32_t wu = (uint32_t)(u >> 8) & 255, wv = (uint32_t)(v >> 8) & 255;+ int c0 = c < 0 ? 0 : c >= W ? W - 1 : c, c1 = c + 1 < 0 ? 0 : c + 1 >= W ? W - 1 : c + 1;+ int r0 = rr < 0 ? 0 : rr >= H ? H - 1 : rr, r1 = rr + 1 < 0 ? 0 : rr + 1 >= H ? H - 1 : rr + 1;+ uint32_t s;+ if (r->fmt == FMT_SOFT)+ s = lerp4(lerp4(soft[r0 * W + c0], soft[r0 * W + c1], wu), lerp4(soft[r1 * W + c0], soft[r1 * W + c1], wu), wv);+ else {+ const uint8_t *al = (const uint8_t *)soft;+ uint32_t top = al[r0 * W + c0] * (256 - wu) + al[r0 * W + c1] * wu, bot = al[r1 * W + c0] * (256 - wu) + al[r1 * W + c1] * wu;+ uint32_t aa = ((top * (256 - wv) + bot * wv) >> 16) * ta >> 8;+ s = aa << 24 | ((crb * aa >> 8) & 0xFF00FF) | ((cg * aa >> 8) & 0xFF00);+ }+ if (s >> 24) bg_put(d16 + bx, s, mode);+ }+ }+ }+}++/* the background shows where light is left; then the strip goes to the screen, dithered. The strip's buffers are+ * left cleared for the next one. */+static const uint8_t bayer[4][4] = {{0, 8, 2, 10}, {12, 4, 14, 6}, {3, 11, 1, 9}, {15, 7, 13, 5}};+static uint32_t bgline[BG_W + 2]; /* a row of the background (0xRRGGBB), its edges repeated */+++/* light (x 128) to 5 or 6 bits (dithering added before): one instruction on the calculator */+#if defined(__arm__)+static inline uint32_t to5(uint32_t v) {+ uint32_t r;+ __asm__("usat %0, #5, %1, asr #10" : "=r"(r) : "r"(v));+ return r;+}+static inline uint32_t to6(uint32_t v) {+ uint32_t r;+ __asm__("usat %0, #6, %1, asr #9" : "=r"(r) : "r"(v));+ return r;+}+#else+static inline uint32_t to5(uint32_t v) { return v >= (32u << 10) ? 31u : v >> 10; }+static inline uint32_t to6(uint32_t v) { return v >= (64u << 9) ? 63u : v >> 9; }+#endif++__attribute__((noinline)) static void finish_strip(int sy0, int rows) {+#ifdef HOST+ if (getenv("PROBE")) {+ int px, py;+ sscanf(getenv("PROBE"), "%d,%d", &px, &py);+ if (py >= sy0 && py < sy0 + rows) {+ int p = (py - sy0) * VIEW_W + px;+ fprintf(stderr, "probe %d,%d: trans %u acc r %u g %u b %u bg_on %d bg565 %04x\n", px, py, trans[p], arb[p] >> 16, ag[p], arb[p] & 0xFFFF, bg_on,+ bgbuf[(py / BG_S) * BG_W + px / BG_S]);+ }+ }+#endif+ uint16_t *out = (uint16_t *)(void *)arb; /* in place: each 16-bit pixel goes where its 32-bit one was read */+ for (int y = 0; y < rows; y++) {+ int sy = sy0 + y;+ if (bg_on) {+ /* the background's row, between two of its own rows */+ float fy = (sy + 0.5f) / BG_S - 0.5f;+ int r0 = (int)(fy + 4096.0f) - 4096;+ uint32_t wv = (uint32_t)((fy - r0) * 256);+ const uint16_t *a16 = bgbuf + (r0 < 0 ? 0 : r0 >= BG_H ? BG_H - 1 : r0) * BG_W;+ const uint16_t *b16 = bgbuf + (r0 + 1 < 0 ? 0 : r0 + 1 >= BG_H ? BG_H - 1 : r0 + 1) * BG_W;+ for (int i = 0; i < BG_W; i++) bgline[i + 1] = lerp4(rgb_of565(a16[i]), rgb_of565(b16[i]), wv);+ bgline[0] = bgline[1], bgline[BG_W + 1] = bgline[BG_W];+ }+ /* the dither of each of 4 columns: red and blue in the high and low halves (both lanes of arb), green */+ const uint8_t *by = bayer[sy & 3];+ uint32_t drb[4], dg[4];+ for (int i = 0; i < 4; i++) drb[i] = (uint32_t)(by[i] >> 1) * 0x800080u, dg[i] = (uint32_t)(by[i] >> 2) << 7;+ int p = y * VIEW_W;+ uint32_t *A = arb + p;+ uint16_t *G16 = ag + p, *O = out + p;+ uint8_t *T = trans + p;+ if (!bg_on) {+ for (int x = 0; x < VIEW_W; x += 4, A += 4, G16 += 4, O += 4, T += 4) {+ for (int j = 0; j < 4; j++) {+ uint32_t rb = A[j] + drb[j], g = G16[j] + dg[j];+ O[j] = (uint16_t)(to5(rb >> 16) << 11 | to6(g) << 5 | to5(rb & 0xFFFF));+ }+ G16[0] = G16[1] = G16[2] = G16[3] = 0;+ *(uint32_t *)(void *)T = 0xFFFFFFFFu;+ }+ continue;+ }+ /* screen pixel 4i + j samples the background at i - 0.375 + j / 4: between texels i - 1 and i, then i and i + 1+ * (bgline is one texel ahead) */+ const uint32_t *bl = bgline;+ for (int x = 0; x < VIEW_W; x += 4, A += 4, G16 += 4, O += 4, T += 4, bl++) {+ uint32_t t4 = *(const uint32_t *)(const void *)T;+ if (!t4) {+ for (int j = 0; j < 4; j++) {+ uint32_t rb = A[j] + drb[j], g = G16[j] + dg[j];+ O[j] = (uint16_t)(to5(rb >> 16) << 11 | to6(g) << 5 | to5(rb & 0xFFFF));+ }+ } else {+ uint32_t bgs[4] = {lerp4(bl[0], bl[1], 160), lerp4(bl[0], bl[1], 224), lerp4(bl[1], bl[2], 32), lerp4(bl[1], bl[2], 96)};+ for (int j = 0; j < 4; j++) {+ uint32_t t = (T[j] + 1u) >> 1, bg = bgs[j];+ /* red and blue in their lanes together */+ uint32_t rb = A[j] + (bg & 0xFF00FF) * t + drb[j], g = G16[j] + (bg >> 8 & 255) * t + dg[j];+ O[j] = (uint16_t)(to5(rb >> 16) << 11 | to6(g) << 5 | to5(rb & 0xFFFF));+ }+ }+ G16[0] = G16[1] = G16[2] = G16[3] = 0;+ *(uint32_t *)(void *)T = 0xFFFFFFFFu;+ }+ }+ plat_push(0, VIEW_Y + sy0, VIEW_W, rows, out);+ /* (arb held the strip's 16-bit pixels) */+ uint32_t *w = arb;+ for (int i = 0; i < NPX; i += 4) w[i] = w[i + 1] = w[i + 2] = w[i + 3] = 0;+}++/* a rotated item's slots (all its tiles) or an upright one's (a row), in the arena: false if it is full */+static bool arena_take(Item *it, bool keep) {+ const Inst *in = &it->in;+ it->ar = 0xFFFF, it->cty = -1;+ if (in->flags & F_SOLID) return true;+ const TexRec *tr = tex_rec(in->tex);+ int n = (in->flags & F_ROT) ? tr->tw * tr->th : tr->tw;+ if (!n || n > 256 || arena_top + n > ARENA) return true;+ it->ar = (uint16_t)arena_top;+ if (keep) arena_top += n;+ if (in->flags & F_ROT)+ for (int q = 0; q < n; q++) arena[it->ar + q] = UNRES_SLOT;+ return true;+}++/* ---------------------------------------------------------------- the frame */+typedef struct {+ Inst in;+ uint32_t group;+} Actor;+#define MAX_ACTORS 64+static Actor actors[MAX_ACTORS];+static int nactors;++bool gfx_actor(const Inst *in, uint32_t group) {+ if (nactors >= MAX_ACTORS) return false;+ /* kept in draw order: sorting layer and order, then far first */+ int i = nactors++;+ while (i > 0 && (actors[i - 1].group > group || (actors[i - 1].group == group && actors[i - 1].in.z < in->z)))+ actors[i] = actors[i - 1], i--;+ actors[i].in = *in, actors[i].group = group;+ return true;+}++static void add_item(const Inst *in, float blur_z) {+ Item cur;+ cur.in = *in;+ if (!item_box(&cur.in, &cur)) return;+ cur.pal = (uint8_t)pal_get(cur.in.flags & F_SOLID ? TEX_NONE : cur.in.tex, cur.in.tint, cur.in.flags);+ if (cur.in.z * (1.0f / 128) > blur_z) {+ arena_take(&cur, false);+ if (!bg_on) memset(bgbuf, 0, sizeof bgbuf), bg_on = true;+ draw_bg_item(&cur);+ return;+ }+ if (nitems >= MAX_ITEMS) {+ g_gfx_dropped++; /* (never in the game's rooms: checked by tests) */+ return;+ }+ arena_take(&cur, true);+ items[nitems++] = cur;+}++void gfx_frame(void) {+ if (lut_room != g_room.id) make_luts();+ tex_frame();+ pal_frame++;+ if (!pal_frame) pal_frame = 1;+ nitems = 0;+ arena_top = 0;+ bg_on = false;+ g_gfx_dropped = 0;+ float blur_z = g_room.h->blur_z;+ /* the instances near the camera, back to front, and the actors among them: what is behind the blur plane is drawn+ * now (small), the rest kept */+ room_near(g_cam_x, g_cam_y);+ room_first();+ Item cur;+ uint32_t group;+ int na = 0;+ while (room_next(&cur.in, &group)) {+ while (na < nactors && (actors[na].group < group || (actors[na].group == group && actors[na].in.z > cur.in.z)))+ add_item(&actors[na++].in, blur_z);+ add_item(&cur.in, blur_z);+ }+ while (na < nactors) add_item(&actors[na++].in, blur_z);+ nactors = 0;+ g_gfx_items = (uint32_t)nitems;+ if (!strip_ready) {+ memset(arb, 0, sizeof arb), memset(ag, 0, sizeof ag), memset(trans, 255, sizeof trans);+ strip_ready = true;+ }+#ifdef HOST+ {+ extern uint32_t g_peak_pals, g_peak_arena, g_peak_soft;+ uint32_t n = 0;+ for (int i = 0; i < NPAL; i++) {+ bool used = false;+ for (int j = 0; j < nitems && !used; j++) used = items[j].pal == i;+ n += used;+ }+ if (n > g_peak_pals) g_peak_pals = n;+ if ((uint32_t)arena_top > g_peak_arena) g_peak_arena = (uint32_t)arena_top;+ }+#endif+ for (int sy0 = 0; sy0 < VIEW_H; sy0 += STRIP_H) {+ int sy1 = sy0 + STRIP_H;+ memset(cov, 0, sizeof cov);+ for (int i = nitems - 1; i >= 0; i--)+ if (items[i].y0 < sy1 && items[i].y1 > sy0) draw_item(i, &items[i], sy0, sy1);+ finish_strip(sy0, STRIP_H);+ }+#ifdef HOST+ {+ extern uint32_t g_peak_soft;+ uint32_t sn = 0;+ for (int i = 0; i < nsoft; i++)+ if (soft_ent[i].frame == pal_frame) sn += soft_ent[i].n;+ if (sn > g_peak_soft) g_peak_soft = sn;+ if (getenv("SOFTDUMP"))+ for (int i = 0; i < nsoft; i++)+ if (soft_ent[i].frame == pal_frame)+ fprintf(stderr, "soft tex %u key %08x words %u (%dx%d fmt %d)\n", soft_ent[i].key >> 16, soft_ent[i].key, soft_ent[i].n,+ tex_rec((uint16_t)(soft_ent[i].key >> 16))->w, tex_rec((uint16_t)(soft_ent[i].key >> 16))->h, tex_rec((uint16_t)(soft_ent[i].key >> 16))->fmt);+ }+#endif+}diff --git a/games/hollowknight/src/hero.c b/games/hollowknight/src/hero.cnew file mode 100644index 00000000..589589bc--- /dev/null+++ b/games/hollowknight/src/hero.c@@ -0,0 +1,872 @@+/* The Knight: HeroController and HeroAnimationController, run 50 times a second (Unity's FixedUpdate rate), each tick+ * as a Unity frame: FixedUpdate, the physics step and its collision callbacks, Update, then the animation. */+#include <math.h>+#include "game.h"++/* HeroController's values (the Knight prefab) and constants */+#define RUN_SPEED 8.3f+#define WALK_SPEED 6.0f+#define JUMP_SPEED 16.65f+#define JUMP_STEPS 9+#define JUMP_STEPS_MIN 4+#define DASH_SPEED 20.0f+#define DASH_TIME 0.25f+#define DASH_QUEUE_STEPS 10+#define DASH_COOLDOWN 0.6f+#define DEFAULT_GRAVITY 0.79f+#define ATTACK_DURATION 0.35f+#define ALT_ATTACK_RESET 0.5f+#define ATTACK_RECOVERY_TIME 0.1f+#define ATTACK_COOLDOWN_TIME 0.41f+#define BOUNCE_TIME 0.25f+#define BOUNCE_VELOCITY 12.0f+#define RECOIL_HOR_VELOCITY 3.75f+#define RECOIL_HOR_VELOCITY_LONG 16.0f+#define RECOIL_HOR_STEPS 8+#define BIG_FALL_TIME 1.1f+#define HARD_LANDING_TIME 0.8f+#define DOWN_DASH_TIME 0.0f+#define MAX_FALL_VELOCITY 20.0f+#define JUMP_QUEUE_STEPS 2+#define ATTACK_QUEUE_STEPS 5+#define LOOK_DELAY 0.85f+#define LOOK_ANIM_DELAY 0.25f+#define FLOATING_CHECK_TIME 0.18f+#define NAIL_TERRAIN_CHECK_TIME 0.12f+#define BUMP_VELOCITY 4.0f+#define BUMP_VELOCITY_DASH 5.0f+#define LANDING_BUFFER_STEPS 5+#define LEDGE_BUFFER_STEPS 2+#define HEAD_BUMP_STEPS 3+#define DT 0.02f++Hero g_hero;++/* ---------------------------------------------------------------- input */+static bool held(uint32_t k) { return (g_hero.keys & k) != 0; }+static bool pressed(uint32_t k) { return (g_hero.keys & k) && !(g_hero.prev_keys & k); }++/* ---------------------------------------------------------------- the collider's bounds */+static float bmin_x(void) { return g_hero.body.x + g_hero.body.ox - g_hero.body.hx; }+static float bmax_x(void) { return g_hero.body.x + g_hero.body.ox + g_hero.body.hx; }+static float bmin_y(void) { return g_hero.body.y + g_hero.body.oy - g_hero.body.hy; }+static float bmax_y(void) { return g_hero.body.y + g_hero.body.oy + g_hero.body.hy; }+static float bcx(void) { return g_hero.body.x + g_hero.body.ox; }+static float bcy(void) { return g_hero.body.y + g_hero.body.oy; }++static bool ray(float x, float y, float dx, float dy, float d) { return phys_ray(x, y, dx, dy, d, CF_TERRAIN, NULL); }++bool hero_touching_ground(void) {+ float d = g_hero.body.hy + 0.16f;+ return ray(bmin_x(), bcy(), 0, -1, d) || ray(bcx(), bcy(), 0, -1, d) || ray(bmax_x(), bcy(), 0, -1, d);+}++static bool check_near_roof(void) {+ float l = 1.1180340f; /* |(0.5, 1)| */+ return phys_ray(bmin_x(), bmax_y(), -0.5f / l, 1 / l, 2, CF_TERRAIN, NULL) ||+ phys_ray(bmax_x(), bmax_y(), 0.5f / l, 1 / l, 2, CF_TERRAIN, NULL) ||+ ray(bcx() + g_hero.body.hx / 2, bmax_y(), 0, 1, 1) || ray(bcx() - g_hero.body.hx / 2, bmax_y(), 0, 1, 1);+}++static bool wall_hit(float x, float y, float dx) {+ PhysHit h;+ if (!phys_ray(x, y, dx, 0, 0.1f, CF_TERRAIN, &h)) return false;+ return !(phys_col_flags(h.col) & (CF_STEEP | CF_NONSLIDER));+}+static bool check_still_touching_wall(int left, bool check_top) {+ float x = left ? bmin_x() : bmax_x(), dx = left ? -1.0f : 1.0f;+ if (wall_hit(x, bcy(), dx) || wall_hit(x, bmin_y(), dx)) return true;+ return check_top && wall_hit(x, bmax_y(), dx);+}++static bool check_for_bump(int left) {+ float n = 0.025f, m = 0.2f, dist = 0.32f + m, dx = left ? -1.0f : 1.0f;+ float x = left ? bmin_x() + m : bmax_x() - m;+ PhysHit low;+ bool hit_low = phys_ray(x, bmin_y() - n, dx, 0, dist, CF_TERRAIN, &low);+ bool hit_high = phys_ray(x, bmin_y() + 0.2f, dx, 0, dist, CF_TERRAIN, NULL);+ if (!hit_low || hit_high) return false;+ PhysHit a, b;+ if (!phys_ray(low.x + (left ? -0.1f : 0.1f), low.y + 1, 0, -1, 1.5f, CF_TERRAIN, &a)) return false;+ if (!phys_ray(low.x + (left ? 0.1f : -0.1f), low.y + 1, 0, -1, 1.5f, CF_TERRAIN, &b)) return true;+ return a.y - b.y > 0;+}++/* ---------------------------------------------------------------- state */+static void anim_update_state(int s);++static bool can_exit_no_input(void) { return !g_hero.doing_hazard_respawn && !g_hero.cs.dead; }++static void set_state(int s) {+ Hero *h = &g_hero;+ if (h->state == HS_NO_INPUT && !can_exit_no_input()) return;+ if (s == HS_GROUNDED) s = fabsf(h->move_input) > 1e-6f ? HS_RUNNING : HS_IDLE;+ else if (s == HS_PREVIOUS) s = h->prev_state;+ if (s != h->state) {+ h->prev_state = h->state;+ h->state = (uint8_t)s;+ anim_update_state(s);+ }+}++static void face_right(void) { g_hero.cs.facing_right = true; }+static void face_left(void) { g_hero.cs.facing_right = false; }+static void flip_sprite(void) { g_hero.cs.facing_right = !g_hero.cs.facing_right; }++static void affected_by_gravity(bool on) {+ Hero *h = &g_hero;+ if (h->body.gravity_scale > 1e-6f && !on) {+ h->prev_gravity = h->body.gravity_scale;+ h->body.gravity_scale = 0;+ } else if (h->body.gravity_scale <= 1e-6f && on)+ h->body.gravity_scale = h->prev_gravity;+}++static void cancel_jump(void) { g_hero.cs.jumping = false, g_hero.jump_steps = 0; }+static void cancel_dash(void) {+ g_hero.cs.dashing = false, g_hero.dash_timer = 0;+ affected_by_gravity(true);+}+static void cancel_bounce(void) { g_hero.cs.bouncing = false, g_hero.bounce_timer = 0; }+static void cancel_recoil_horizontal(void) { g_hero.cs.recoiling_left = g_hero.cs.recoiling_right = false, g_hero.recoil_steps = 0; }+static void reset_attacks(void) {+ Hero *h = &g_hero;+ h->cs.attacking = h->cs.up_attacking = h->cs.down_attacking = false;+ h->attack_time = 0;+}+static void cancel_attack(void) {+ if (g_hero.cs.attacking) slash_cancel(), reset_attacks();+}+static void cancel_down_attack(void) {+ if (g_hero.cs.down_attacking) slash_cancel(), reset_attacks();+}+static void reset_motion(void) {+ Hero *h = &g_hero;+ cancel_jump(), cancel_dash(), cancel_bounce(), cancel_recoil_horizontal();+ h->body.vx = h->body.vy = 0;+}+static void reset_look(void) {+ Hero *h = &g_hero;+ h->cs.looking_up = h->cs.looking_down = h->cs.looking_up_anim = h->cs.looking_down_anim = false;+ h->look_delay_timer = 0;+}+static void reset_input(void) { g_hero.move_input = g_hero.vertical_input = 0; }++static void back_on_ground(void) {+ Hero *h = &g_hero;+ if (h->landing_buffer_steps <= 0) h->landing_buffer_steps = LANDING_BUFFER_STEPS;+ h->cs.falling = false;+ h->fall_timer = 0;+ h->dash_landing_timer = 0;+ h->cs.will_hard_land = false;+ h->hard_landing_timer = 0;+ h->hard_landed = false;+ h->jump_steps = 0;+ set_state(HS_GROUNDED);+ h->cs.on_ground = true;+ h->air_dashed = false;+}++static void jump_released(void) {+ Hero *h = &g_hero;+ if (h->body.vy > 0 && h->jumped_steps >= JUMP_STEPS_MIN) {+ h->body.vy = 0;+ cancel_jump();+ }+ h->jump_queuing = false;+}++static void finished_dashing(void) {+ cancel_dash();+ affected_by_gravity(true);+ g_hero.play_dash_to_idle = true;+}++static void do_hard_landing(void) {+ Hero *h = &g_hero;+ affected_by_gravity(true);+ reset_input();+ set_state(HS_HARD_LANDING);+ cancel_attack();+ h->hard_landed = true;+}++/* ---------------------------------------------------------------- abilities */+static bool can_jump(void) {+ Hero *h = &g_hero;+ if (h->state == HS_NO_INPUT || h->state == HS_HARD_LANDING || h->state == HS_DASH_LANDING || h->cs.dashing ||+ h->cs.jumping || h->cs.bouncing)+ return false;+ if (h->cs.on_ground) return true;+ if (h->ledge_buffer_steps > 0 && !h->cs.dead && !h->control_relinquished && h->head_bump_steps <= 0 && !check_near_roof()) {+ h->ledge_buffer_steps = 0;+ return true;+ }+ return false;+}++static bool can_dash(void) {+ Hero *h = &g_hero;+ return h->state != HS_NO_INPUT && h->state != HS_HARD_LANDING && h->state != HS_DASH_LANDING && h->dash_cooldown_timer <= 0 &&+ !h->cs.dashing && !(h->cs.attacking && h->attack_time < ATTACK_RECOVERY_TIME) && !h->cs.prevent_dash &&+ (h->cs.on_ground || !h->air_dashed) && !h->cs.hazard_death && g_pd.can_dash;+}++static bool can_attack(void) {+ Hero *h = &g_hero;+ return h->attack_cooldown <= 0 && !h->cs.attacking && !h->cs.dashing && !h->cs.dead && !h->cs.hazard_death &&+ !h->cs.hazard_respawning && !h->control_relinquished && h->state != HS_NO_INPUT && h->state != HS_HARD_LANDING &&+ h->state != HS_DASH_LANDING;+}++static void hero_jump(void) {+ Hero *h = &g_hero;+ reset_look();+ h->cs.recoiling = false;+ h->cs.jumping = true;+ h->jump_queue_steps = 0;+ h->jumped_steps = 0;+}++static void hero_dash(void) {+ Hero *h = &g_hero;+ if (!h->cs.on_ground) h->air_dashed = true;+ h->cs.attacking = h->cs.up_attacking = h->cs.down_attacking = false, h->attack_time = 0;+ cancel_bounce();+ reset_look();+ h->cs.recoiling = false;+ if (held(K_RIGHT)) face_right();+ else if (held(K_LEFT)) face_left();+ h->cs.dashing = true;+ h->dash_queue_steps = 0;+ h->dash_cooldown_timer = DASH_COOLDOWN;+ fx_dash_burst(h->body.x, h->body.y, h->cs.facing_right, h->cs.on_ground);+}++static void attack(int dir) {+ Hero *h = &g_hero;+ if (h->time_since_level - h->alt_attack_time > ALT_ATTACK_RESET) h->cs.alt_attack = false;+ h->cs.attacking = true;+ h->attack_duration = ATTACK_DURATION;+ int kind;+ if (dir == ATK_NORMAL) {+ kind = h->cs.alt_attack ? SLASH_ALT : SLASH_NORMAL;+ h->cs.alt_attack = !h->cs.alt_attack;+ } else if (dir == ATK_UP) {+ kind = SLASH_UP;+ h->cs.up_attacking = true;+ } else {+ kind = SLASH_DOWN;+ h->cs.down_attacking = true;+ }+ h->alt_attack_time = h->time_since_level;+ slash_start(kind);+}++static void do_attack(void) {+ Hero *h = &g_hero;+ reset_look();+ h->cs.recoiling = false;+ h->attack_cooldown = ATTACK_COOLDOWN_TIME;+ int dir = ATK_NORMAL;+ if (h->vertical_input > 1e-6f) dir = ATK_UP;+ else if (h->vertical_input < -1e-6f && h->state != HS_IDLE && h->state != HS_RUNNING) dir = ATK_DOWN;+ attack(dir);+ /* CheckForTerrainThunk */+ h->thunk_dir = (int8_t)dir;+ h->thunk_timer = NAIL_TERRAIN_CHECK_TIME;+ h->thunk_hit = false;+}++void hero_recoil_left(void) {+ Hero *h = &g_hero;+ if (!h->cs.recoiling_left && !h->cs.recoiling_right && !h->control_relinquished) {+ cancel_dash();+ h->recoil_steps = 0;+ h->cs.recoiling_left = true, h->cs.recoiling_right = false;+ h->recoil_large = false;+ h->body.vx = -RECOIL_HOR_VELOCITY;+ }+}+void hero_recoil_right(void) {+ Hero *h = &g_hero;+ if (!h->cs.recoiling_left && !h->cs.recoiling_right && !h->control_relinquished) {+ cancel_dash();+ h->recoil_steps = 0;+ h->cs.recoiling_right = true, h->cs.recoiling_left = false;+ h->recoil_large = false;+ h->body.vx = RECOIL_HOR_VELOCITY;+ }+}+void hero_recoil_down(void) {+ Hero *h = &g_hero;+ cancel_jump();+ if (h->body.vy > 0) h->body.vy = 0; /* (RECOIL_DOWN_VELOCITY) */+}+void hero_bounce(void) {+ Hero *h = &g_hero;+ if (!h->cs.bouncing && !h->control_relinquished) {+ cancel_jump();+ cancel_dash();+ h->bounce_timer = 0;+ h->cs.bouncing = true;+ h->air_dashed = false;+ }+}++/* the nail meeting the ground: the Knight is pushed back (CheckForTerrainThunk) */+static void terrain_thunk(void) {+ Hero *h = &g_hero;+ if (h->thunk_timer <= 0) return;+ if (!h->thunk_hit) {+ float len = h->thunk_dir == ATK_NORMAL ? 2.0f : 1.5f;+ float hs = 0.225f; /* the 0.45 box cast */+ float ox = bcx(), oy = bcy() + 0.25f, dx = 0, dy = 0;+ if (h->thunk_dir == ATK_NORMAL) dx = h->cs.facing_right ? 1 : -1;+ else if (h->thunk_dir == ATK_UP) oy = bmax_y(), dy = 1;+ else oy = bmin_y(), dy = -1;+ /* (a box cast, as three rays across the box) */+ bool hit = false;+ for (int i = -1; i <= 1 && !hit; i++)+ hit = phys_ray(ox + (dy ? i * hs : 0), oy + (dx ? i * hs : 0), dx, dy, len + hs, CF_TERRAIN, NULL);+ if (hit) {+ h->thunk_hit = true;+ if (h->thunk_dir == ATK_NORMAL) {+ if (h->cs.facing_right) hero_recoil_left();+ else hero_recoil_right();+ } else if (h->thunk_dir == ATK_UP)+ hero_recoil_down();+ }+ }+ h->thunk_timer -= DT;+}++/* ---------------------------------------------------------------- FixedUpdate */+static void move(float dir) {+ Hero *h = &g_hero;+ if (h->cs.on_ground) set_state(HS_GROUNDED);+ if (h->accepting_input) h->body.vx = dir * (h->cs.in_walk_zone ? WALK_SPEED : RUN_SPEED);+}++static void jump(void) {+ Hero *h = &g_hero;+ if (h->jump_steps <= JUMP_STEPS) {+ h->body.vy = JUMP_SPEED;+ h->jump_steps++, h->jumped_steps++;+ h->ledge_buffer_steps = 0;+ } else+ cancel_jump();+}++static void dash(void) {+ Hero *h = &g_hero;+ affected_by_gravity(false);+ h->hard_landing_timer = 0;+ if (h->dash_timer > DASH_TIME) {+ finished_dashing();+ return;+ }+ float s = DASH_SPEED;+ if (h->cs.facing_right) {+ if (check_for_bump(0)) h->body.vx = s, h->body.vy = h->cs.on_ground ? BUMP_VELOCITY : BUMP_VELOCITY_DASH;+ else h->body.vx = s, h->body.vy = 0;+ } else if (check_for_bump(1))+ h->body.vx = -s, h->body.vy = h->cs.on_ground ? BUMP_VELOCITY : BUMP_VELOCITY_DASH;+ else+ h->body.vx = -s, h->body.vy = 0;+ h->dash_timer += DT;+}++static void fixed_update(void) {+ Hero *h = &g_hero;+ if (h->cs.recoiling_left || h->cs.recoiling_right) {+ if (h->recoil_steps <= RECOIL_HOR_STEPS) h->recoil_steps++;+ else cancel_recoil_horizontal();+ }+ if (h->cs.dead) h->body.vx = h->body.vy = 0;+ if (h->state == HS_HARD_LANDING || h->state == HS_DASH_LANDING)+ reset_motion();+ else if (h->state == HS_NO_INPUT) {+ if (h->cs.transitioning) {+ if (h->transition_state == TS_EXITING_SCENE) {+ affected_by_gravity(false);+ h->body.vx = h->transition_vx, h->body.vy = h->transition_vy + h->body.vy;+ } else if (h->transition_state == TS_ENTERING_SCENE)+ h->body.vx = h->transition_vx, h->body.vy = h->transition_vy;+ else if (h->transition_state == TS_DROPPING_DOWN)+ h->body.vx = h->transition_vx;+ } else if (h->cs.recoiling) {+ affected_by_gravity(false);+ h->body.vx = h->recoil_vx, h->body.vy = h->recoil_vy;+ }+ } else {+ if (h->state == HS_RUNNING) {+ if (h->move_input > 0) {+ if (check_for_bump(0)) h->body.vy = BUMP_VELOCITY;+ } else if (h->move_input < 0 && check_for_bump(1))+ h->body.vy = BUMP_VELOCITY;+ }+ if (!h->cs.dashing) {+ move(h->move_input);+ if (!h->cs.attacking || h->attack_time >= ATTACK_RECOVERY_TIME) {+ if (h->move_input > 0 && !h->cs.facing_right) flip_sprite(), cancel_attack();+ else if (h->move_input < 0 && h->cs.facing_right) flip_sprite(), cancel_attack();+ }+ if (h->cs.recoiling_left) {+ float v = h->recoil_large ? RECOIL_HOR_VELOCITY_LONG : RECOIL_HOR_VELOCITY;+ h->body.vx = h->body.vx > -v ? -v : h->body.vx - v;+ }+ if (h->cs.recoiling_right) {+ float v = h->recoil_large ? RECOIL_HOR_VELOCITY_LONG : RECOIL_HOR_VELOCITY;+ h->body.vx = h->body.vx < v ? v : h->body.vx + v;+ }+ }+ if ((h->cs.looking_up || h->cs.looking_down) && fabsf(h->move_input) > 0.6f) reset_look();+ if (h->cs.jumping) jump();+ if (h->cs.dashing) dash();+ if (h->cs.casting) {+ if (h->cs.cast_recoiling) h->body.vx = h->cs.facing_right ? -10.0f : 10.0f, h->body.vy = 0;+ else h->body.vx = h->body.vy = 0;+ }+ if (h->cs.bouncing) h->body.vy = BOUNCE_VELOCITY;+ }+ if (h->body.vy < -MAX_FALL_VELOCITY && !h->control_relinquished) h->body.vy = -MAX_FALL_VELOCITY;+ if (h->jump_queuing) h->jump_queue_steps++;+ if (h->dash_queuing) h->dash_queue_steps++;+ if (h->attack_queuing) h->attack_queue_steps++;+ if (h->landing_buffer_steps > 0) h->landing_buffer_steps--;+ if (h->ledge_buffer_steps > 0) h->ledge_buffer_steps--;+ if (h->head_bump_steps > 0) h->head_bump_steps--;+ h->cs.was_on_ground = h->cs.on_ground;+}++/* ---------------------------------------------------------------- collisions (OnCollisionEnter2D, Stay, Exit) */+static bool should_hard_land(int col) {+ Hero *h = &g_hero;+ return !(phys_col_flags(col) & CF_NOHARDLAND) && h->cs.will_hard_land && h->state != HS_HARD_LANDING;+}++static void on_enter(const BodyEvent *e) {+ Hero *h = &g_hero;+ uint8_t f = phys_col_flags(e->col);+ if ((f & CF_TERRAIN) && hero_touching_ground()) h->landed_event = true; /* HeroCtrl-Landed */+ if (h->state != HS_NO_INPUT) {+ if (!(f & CF_TERRAIN)) return;+ int side = e->ny >= 0.5f ? SIDE_BOTTOM : e->ny <= -0.5f ? SIDE_TOP : e->nx < 0 ? SIDE_RIGHT : SIDE_LEFT;+ if (side == SIDE_TOP) {+ h->head_bump_steps = HEAD_BUMP_STEPS;+ if (h->cs.jumping) cancel_jump();+ if (h->cs.bouncing) cancel_bounce(), h->body.vy = 0;+ }+ if (side == SIDE_BOTTOM) {+ if (h->cs.attacking) cancel_down_attack();+ if (should_hard_land(e->col)) do_hard_landing();+ else if (!(f & CF_STEEP) && h->state != HS_HARD_LANDING) back_on_ground();+ }+ } else if (h->transition_state == TS_DROPPING_DOWN && (h->gate_position == GATE_BOTTOM || h->gate_position == GATE_TOP))+ hero_finished_entering_scene();+}++static void on_stay(const BodyEvent *e) {+ Hero *h = &g_hero;+ uint8_t f = phys_col_flags(e->col);+ if (h->state == HS_NO_INPUT || !(f & CF_TERRAIN)) return;+ if (!(f & CF_NONSLIDER)) {+ h->cs.touching_non_slider = false;+ if (check_still_touching_wall(1, false)) h->cs.touching_wall = true, h->touching_wall_l = true, h->touching_wall_r = false;+ else if (check_still_touching_wall(0, false)) h->cs.touching_wall = true, h->touching_wall_l = false, h->touching_wall_r = true;+ else h->cs.touching_wall = false, h->touching_wall_l = h->touching_wall_r = false;+ if (hero_touching_ground()) {+ if (should_hard_land(e->col)) do_hard_landing();+ else if (h->state != HS_HARD_LANDING && h->state != HS_DASH_LANDING && h->cs.falling) back_on_ground();+ } else if (h->cs.jumping || h->cs.falling) {+ h->cs.on_ground = false;+ set_state(HS_AIRBORNE);+ }+ } else+ h->cs.touching_non_slider = true;+}++static void on_exit(const BodyEvent *e) {+ Hero *h = &g_hero;+ uint8_t f = phys_col_flags(e->col);+ if (h->cs.recoiling_left || h->cs.recoiling_right) h->cs.touching_wall = h->touching_wall_l = h->touching_wall_r = false, h->cs.touching_non_slider = false;+ if (h->touching_wall_l && !check_still_touching_wall(1, false)) h->cs.touching_wall = false, h->touching_wall_l = false;+ if (h->touching_wall_r && !check_still_touching_wall(0, false)) h->cs.touching_wall = false, h->touching_wall_r = false;+ if (h->state == HS_NO_INPUT || h->cs.recoiling || !(f & CF_TERRAIN) || hero_touching_ground()) return;+ h->cs.on_ground = false;+ set_state(HS_AIRBORNE);+ if (h->cs.was_on_ground) h->ledge_buffer_steps = LEDGE_BUFFER_STEPS;+}++/* ---------------------------------------------------------------- Update */+static void fall_check(void) {+ Hero *h = &g_hero;+ if (h->body.vy <= -1e-6f) {+ if (hero_touching_ground()) return;+ h->cs.falling = true;+ h->cs.on_ground = false;+ if (h->state != HS_NO_INPUT) set_state(HS_AIRBORNE);+ h->fall_timer += DT;+ if (h->fall_timer > BIG_FALL_TIME) h->cs.will_hard_land = true;+ } else {+ h->cs.falling = false;+ h->fall_timer = 0;+ if (h->transition_state != TS_ENTERING_SCENE) h->cs.will_hard_land = false;+ }+}++static void fail_safe_checks(void) {+ Hero *h = &g_hero;+ if (h->state == HS_HARD_LANDING) {+ h->hard_land_fail_safe_timer += DT;+ if (h->hard_land_fail_safe_timer > HARD_LANDING_TIME + 0.3f) set_state(HS_GROUNDED), back_on_ground(), h->hard_land_fail_safe_timer = 0;+ } else+ h->hard_land_fail_safe_timer = 0;+ if (h->body.vy != 0 || h->cs.on_ground || h->cs.falling || h->cs.jumping || h->cs.dashing || h->state == HS_HARD_LANDING ||+ h->state == HS_NO_INPUT)+ return;+ if (hero_touching_ground()) {+ h->floating_buffer_timer += DT;+ if (h->floating_buffer_timer > FLOATING_CHECK_TIME) {+ if (h->cs.recoiling) h->cs.recoiling = false, h->recoil_timer = 0, reset_motion(), affected_by_gravity(true);+ back_on_ground();+ h->floating_buffer_timer = 0;+ }+ } else+ h->floating_buffer_timer = 0;+}++static void look_for_input(void) {+ Hero *h = &g_hero;+ if (!h->accepting_input || g_game.paused) return;+ h->move_input = held(K_RIGHT) && !held(K_LEFT) ? 1.0f : held(K_LEFT) && !held(K_RIGHT) ? -1.0f : 0.0f;+ h->vertical_input = held(K_UP) && !held(K_DOWN) ? 1.0f : held(K_DOWN) && !held(K_UP) ? -1.0f : 0.0f;+ if (!held(K_JUMP)) jump_released();+ if (!held(K_DASH)) {+ if (h->cs.prevent_dash && !h->cs.dash_cooldown) h->cs.prevent_dash = false;+ h->dash_queuing = false;+ }+ if (!held(K_ATTACK)) h->attack_queuing = false;+}++static void look_for_queue_input(void) {+ Hero *h = &g_hero;+ if (!h->accepting_input || g_game.paused) return;+ if (pressed(K_JUMP)) {+ if (can_jump()) hero_jump();+ else h->jump_queue_steps = 0, h->jump_queuing = true;+ }+ if (pressed(K_DASH)) {+ if (can_dash()) hero_dash();+ else h->dash_queue_steps = 0, h->dash_queuing = true;+ }+ if (pressed(K_ATTACK)) {+ if (can_attack()) do_attack();+ else h->attack_queue_steps = 0, h->attack_queuing = true;+ }+ if (held(K_JUMP) && h->jump_queue_steps <= JUMP_QUEUE_STEPS && can_jump() && h->jump_queuing) hero_jump();+ if (held(K_DASH) && h->dash_queue_steps <= DASH_QUEUE_STEPS && can_dash() && h->dash_queuing) hero_dash();+ if (held(K_ATTACK) && h->attack_queue_steps <= ATTACK_QUEUE_STEPS && can_attack() && h->attack_queuing) do_attack();+}++static void update(void) {+ Hero *h = &g_hero;+ fall_check();+ fail_safe_checks();+ if (h->state == HS_DASH_LANDING) {+ h->dash_landing_timer += DT;+ if (h->dash_landing_timer > DOWN_DASH_TIME) back_on_ground();+ }+ if (h->state == HS_HARD_LANDING) {+ h->hard_landing_timer += DT;+ if (h->hard_landing_timer > HARD_LANDING_TIME) set_state(HS_GROUNDED), back_on_ground();+ } else if (h->state == HS_NO_INPUT) {+ if (h->cs.recoiling) {+ if (h->recoil_timer < RECOIL_DURATION) h->recoil_timer += DT;+ else {+ h->cs.recoiling = false, h->recoil_timer = 0, reset_motion(), affected_by_gravity(true);+ h->damage_mode = DAMAGE_FULL;+ if ((h->prev_state == HS_IDLE || h->prev_state == HS_RUNNING) && !hero_touching_ground()) {+ h->cs.on_ground = false;+ set_state(HS_AIRBORNE);+ } else+ set_state(HS_PREVIOUS);+ }+ }+ } else {+ look_for_input();+ if (h->cs.recoiling) h->cs.recoiling = false, affected_by_gravity(true);+ if (h->cs.attacking && !h->cs.dashing) {+ h->attack_time += DT;+ if (h->attack_time >= h->attack_duration) {+ reset_attacks();+ /* (HeroAnimationController.StopAttack) */+ if (anim_is_playing(&h->anim, CLIP_KNIGHT_UPSLASH) || anim_is_playing(&h->anim, CLIP_KNIGHT_DOWNSLASH)) h->anim.playing = false;+ }+ }+ if (h->cs.bouncing) {+ if (h->bounce_timer < BOUNCE_TIME) h->bounce_timer += DT;+ else cancel_bounce(), h->body.vy = 0;+ }+ if (h->state == HS_IDLE) {+ if (!h->control_relinquished && !g_game.paused) {+ if (held(K_UP)) {+ h->cs.looking_down = h->cs.looking_down_anim = false;+ if (h->look_delay_timer >= LOOK_DELAY) h->cs.looking_up = true;+ else h->look_delay_timer += DT;+ h->cs.looking_up_anim = h->look_delay_timer >= LOOK_ANIM_DELAY;+ } else if (held(K_DOWN)) {+ h->cs.looking_up = h->cs.looking_up_anim = false;+ if (h->look_delay_timer >= LOOK_DELAY) h->cs.looking_down = true;+ else h->look_delay_timer += DT;+ h->cs.looking_down_anim = h->look_delay_timer >= LOOK_ANIM_DELAY;+ } else+ reset_look();+ }+ }+ }+ look_for_queue_input();+ if (h->attack_cooldown > 0) h->attack_cooldown -= DT;+ if (h->dash_cooldown_timer > 0) h->dash_cooldown_timer -= DT;+ terrain_thunk();+}++/* ---------------------------------------------------------------- HeroAnimationController */+static void play_idle(void) {+ Hero *h = &g_hero;+ if (g_pd.health == 1 && g_pd.health_blue < 1) anim_play(&h->anim, CLIP_KNIGHT_IDLE_HURT);+ else if (anim_is_playing(&h->anim, CLIP_KNIGHT_LOOKUP)) anim_play(&h->anim, CLIP_KNIGHT_LOOKUPEND);+ else if (anim_is_playing(&h->anim, CLIP_KNIGHT_LOOKDOWN)) anim_play(&h->anim, CLIP_KNIGHT_LOOKDOWNEND);+ else anim_play(&h->anim, CLIP_KNIGHT_IDLE);+}++static void anim_update_state(int s) {+ Hero *h = &g_hero;+ if (!h->anim_control || s == h->anim_state) return;+ if (h->anim_state == HS_AIRBORNE && s == HS_IDLE && !h->play_landing) h->play_landing = true;+ if (h->anim_state == HS_RUNNING && s == HS_IDLE && !h->play_run_to_idle && !h->cs.in_walk_zone && !h->cs.attacking) h->play_run_to_idle = true;+ h->anim_state = (uint8_t)s;+}++/* the clip that finished, as AnimationCompleteDelegate (for the clips played with it) */+static void anim_completed(void) {+ Hero *h = &g_hero;+ int c = h->anim.clip;+ if (h->complete_delegate &&+ (c == CLIP_KNIGHT_LAND || c == CLIP_KNIGHT_RUN_TO_IDLE || c == CLIP_KNIGHT_DASH_TO_IDLE || c == CLIP_KNIGHT_EXIT_DOOR_TO_IDLE))+ play_idle();+}++static bool can_play_idle(void) {+ const Anim *a = &g_hero.anim;+ return !anim_is_playing(a, CLIP_KNIGHT_LAND) && !anim_is_playing(a, CLIP_KNIGHT_RUN_TO_IDLE) &&+ !anim_is_playing(a, CLIP_KNIGHT_DASH_TO_IDLE) && !anim_is_playing(a, CLIP_KNIGHT_LOOKUPEND) &&+ !anim_is_playing(a, CLIP_KNIGHT_LOOKDOWNEND) && !anim_is_playing(a, CLIP_KNIGHT_EXIT_DOOR_TO_IDLE) &&+ !anim_is_playing(a, CLIP_KNIGHT_WAKE_UP_GROUND) && !anim_is_playing(a, CLIP_KNIGHT_HAZARD_RESPAWN);+}+static bool can_play_turn(void) {+ return !anim_is_playing(&g_hero.anim, CLIP_KNIGHT_WAKE_UP_GROUND) && !anim_is_playing(&g_hero.anim, CLIP_KNIGHT_HAZARD_RESPAWN);+}++static void play(int clip) {+ anim_play(&g_hero.anim, clip);+}++static void animation(void) {+ Hero *h = &g_hero;+ Anim *a = &h->anim;+ if (h->play_landing) play(CLIP_KNIGHT_LAND), h->complete_delegate = true, h->play_landing = false;+ if (h->play_run_to_idle) play(CLIP_KNIGHT_RUN_TO_IDLE), h->complete_delegate = true, h->play_run_to_idle = false;+ if (h->play_dash_to_idle) play(CLIP_KNIGHT_DASH_TO_IDLE), h->complete_delegate = true, h->play_dash_to_idle = false;+ if (h->anim_state == HS_NO_INPUT) {+ if (h->cs.recoil_frozen) play(CLIP_KNIGHT_STUN);+ else if (h->cs.recoiling) play(CLIP_KNIGHT_RECOIL);+ else if (h->cs.transitioning) {+ if (h->cs.on_ground) {+ if (h->transition_state == TS_EXITING_SCENE) {+ if (!anim_is_playing(a, CLIP_KNIGHT_RUN)) play(CLIP_KNIGHT_RUN);+ } else if (h->transition_state == TS_ENTERING_SCENE) {+ if (!anim_is_playing(a, CLIP_KNIGHT_RUN)) anim_play_from_frame(a, CLIP_KNIGHT_RUN, 3);+ }+ } else if (h->transition_state == TS_EXITING_SCENE || h->transition_state == TS_WAITING_TO_ENTER_LEVEL) {+ if (!anim_is_playing(a, CLIP_KNIGHT_AIRBORNE)) anim_play_from_frame(a, CLIP_KNIGHT_AIRBORNE, 7);+ } else if (h->transition_state == TS_ENTERING_SCENE && !h->set_entry_anim) {+ if (h->gate_position == GATE_TOP) anim_play_from_frame(a, CLIP_KNIGHT_AIRBORNE, 7);+ else if (h->gate_position == GATE_BOTTOM) anim_play_from_frame(a, CLIP_KNIGHT_AIRBORNE, 3);+ h->set_entry_anim = true;+ }+ }+ } else if (h->set_entry_anim)+ h->set_entry_anim = false;+ else if (h->cs.dashing)+ play(CLIP_KNIGHT_DASH);+ else if (h->cs.attacking) {+ if (h->cs.up_attacking) play(CLIP_KNIGHT_UPSLASH);+ else if (h->cs.down_attacking) play(CLIP_KNIGHT_DOWNSLASH);+ else if (!h->cs.alt_attack) play(CLIP_KNIGHT_SLASH);+ else play(CLIP_KNIGHT_SLASHALT);+ } else if (h->cs.casting) {+ /* (the spell's own animation plays) */+ } else if (h->anim_state == HS_IDLE) {+ if (h->cs.looking_up_anim && !anim_is_playing(a, CLIP_KNIGHT_LOOKUP)) play(CLIP_KNIGHT_LOOKUP);+ else if (h->cs.looking_down_anim) play(CLIP_KNIGHT_LOOKDOWN);+ else if (!h->cs.looking_up_anim && !h->cs.looking_down_anim && can_play_idle()) play_idle();+ } else if (h->anim_state == HS_RUNNING) {+ if (!anim_is_playing(a, CLIP_KNIGHT_TURN)) {+ if (h->cs.in_walk_zone) {+ if (!anim_is_playing(a, CLIP_KNIGHT_WALK)) play(CLIP_KNIGHT_WALK);+ } else if (h->was_attacking)+ anim_play_from_frame(a, CLIP_KNIGHT_RUN, 3);+ else+ play(CLIP_KNIGHT_RUN);+ }+ } else if (h->anim_state == HS_AIRBORNE) {+ if (h->cs.jumping) {+ if (!anim_is_playing(a, CLIP_KNIGHT_AIRBORNE)) anim_play_from_frame(a, CLIP_KNIGHT_AIRBORNE, 0);+ } else if (h->cs.falling) {+ if (!anim_is_playing(a, CLIP_KNIGHT_AIRBORNE)) anim_play_from_frame(a, CLIP_KNIGHT_AIRBORNE, 5);+ } else if (!anim_is_playing(a, CLIP_KNIGHT_AIRBORNE))+ anim_play_from_frame(a, CLIP_KNIGHT_AIRBORNE, 3);+ } else if (h->anim_state == HS_HARD_LANDING)+ play(CLIP_KNIGHT_HARDLAND);+ if (h->cs.facing_right) {+ if (!h->was_facing_right && h->cs.on_ground && can_play_turn()) play(CLIP_KNIGHT_TURN);+ h->was_facing_right = true;+ } else {+ if (h->was_facing_right && h->cs.on_ground && can_play_turn()) play(CLIP_KNIGHT_TURN);+ h->was_facing_right = false;+ }+ h->was_attacking = h->cs.attacking;+}++/* ---------------------------------------------------------------- the tick */+void hero_init(float x, float y, bool facing_right) {+ Hero *h = &g_hero;+ memset(h, 0, sizeof *h);+ h->body.x = x, h->body.y = y;+ h->body.ox = 0, h->body.oy = -0.75f, h->body.hx = 0.25f, h->body.hy = 0.640625f; /* the Knight's BoxCollider2D */+ h->body.gravity_scale = DEFAULT_GRAVITY;+ h->prev_gravity = DEFAULT_GRAVITY;+ h->body.mask = CF_SOLID;+ h->cs.facing_right = h->was_facing_right = facing_right;+ h->accepting_input = true;+ h->anim_control = true;+ h->state = h->anim_state = HS_AIRBORNE;+ h->transition_state = TS_WAITING_TO_TRANSITION;+ if (hero_touching_ground()) {+ h->cs.on_ground = true;+ set_state(HS_GROUNDED);+ h->anim_state = h->state;+ play_idle();+ } else+ anim_play_from_frame(&h->anim, CLIP_KNIGHT_AIRBORNE, 7);+}++void hero_fixed(uint32_t keys) {+ Hero *h = &g_hero;+ h->prev_keys = h->keys, h->keys = keys;+ h->time_since_level += DT;+ fixed_update();+ body_step(&h->body, DT);+ for (int i = 0; i < h->body.nevents; i++) {+ const BodyEvent *e = &h->body.events[i];+ if (e->kind == EV_ENTER) on_enter(e);+ else if (e->kind == EV_STAY) on_stay(e);+ else on_exit(e);+ }+}++void hero_update(void) {+ Hero *h = &g_hero;+ update();+ if (h->anim_control) animation();+ h->anim.events = 0;+ anim_update(&h->anim, DT);+ if (h->anim.events & ANIM_DONE) anim_completed();+ if (!(h->anim.clip == CLIP_KNIGHT_LAND || h->anim.clip == CLIP_KNIGHT_RUN_TO_IDLE || h->anim.clip == CLIP_KNIGHT_DASH_TO_IDLE))+ h->complete_delegate = false;+ slash_tick();+}++void hero_draw(void) {+ Hero *h = &g_hero;+ Inst in;+ sprite_inst(h->anim.sprite, h->body.x, h->body.y, 0.004f, h->cs.facing_right ? -1.0f : 1.0f, 1, 0, &in);+ gfx_actor(&in, SORT_KEY(0, 0));+ slash_draw();+}++/* ---------------------------------------------------------------- NailSlash: the slash effect, a child of the Knight */+static const struct {+ int clip;+ float x, y, z, sx, sy; /* its place and scale on the Knight */+} slashes[4] = {+ {CLIP_KNIGHT_SLASHEFFECT, -0.01f, -0.41f, -0.001f, 1.6010780f, 1.6452440f},+ {CLIP_KNIGHT_SLASHEFFECTALT, 0.08f, -0.436f, -0.001f, 1.2569700f, 1.4224339f},+ {CLIP_KNIGHT_UPSLASHEFFECT, 0.0f, 0.69f, -0.001f, 1.15f, 1.4f},+ {CLIP_KNIGHT_DOWNSLASHEFFECT, 0.16f, -1.59f, 0.0f, 1.125f, 1.28002f},+};+static struct {+ int kind;+ bool slashing, shown, anim_completed;+ int step_counter, poly_counter;+ bool poly;+ Anim anim;+} sl;++void slash_start(int kind) {+ sl.kind = kind;+ anim_play(&sl.anim, slashes[kind].clip);+ anim_play_from_frame(&sl.anim, slashes[kind].clip, 0);+ sl.step_counter = sl.poly_counter = 0;+ sl.poly = false;+ sl.anim_completed = false;+ sl.slashing = sl.shown = true;+}++/* (NailSlash.CancelAttack: the hit shape off, then the slash is done) */+void slash_cancel(void) {+ sl.slashing = false;+ sl.poly = false;+ sl.shown = false;+}++void slash_tick(void) {+ /* FixedUpdate */+ if (sl.slashing) {+ if (sl.step_counter == 1) sl.poly = true;+ if (sl.step_counter >= 5 && sl.poly_counter > 0) sl.poly = false;+ if (sl.anim_completed && sl.poly_counter > 1) slash_cancel();+ if (sl.poly) sl.poly_counter++;+ sl.step_counter++;+ }+ if (!sl.shown) return;+ sl.anim.events = 0;+ anim_update(&sl.anim, DT);+ if (sl.anim.events & ANIM_DONE) {+ /* (Disable) */+ sl.anim_completed = true;+ sl.shown = false;+ }+}++void slash_draw(void) {+ if (!sl.shown) return;+ Hero *h = &g_hero;+ float k = h->cs.facing_right ? -1.0f : 1.0f; /* the Knight's x scale */+ const typeof(slashes[0]) *s = &slashes[sl.kind];+ Inst in;+ sprite_inst(sl.anim.sprite, h->body.x + k * s->x, h->body.y + s->y, 0.004f + s->z, k * s->sx, s->sy, 0, &in);+ gfx_actor(&in, SORT_KEY(0, 0));+}++void fx_dash_burst(float x, float y, bool facing_right, bool on_ground) { (void)x, (void)y, (void)facing_right, (void)on_ground; }++void hero_finished_entering_scene(void) {+ Hero *h = &g_hero;+ h->transition_state = TS_WAITING_TO_TRANSITION;+ h->cs.transitioning = false;+ h->state = HS_IDLE;+ set_state(HS_GROUNDED);+}diff --git a/games/hollowknight/src/hk.h b/games/hollowknight/src/hk.hnew file mode 100644index 00000000..2138e6a7--- /dev/null+++ b/games/hollowknight/src/hk.h@@ -0,0 +1,188 @@+/* Hollow Knight for the NumWorks calculator.+ *+ * Inspired by Hollow Knight, not affiliated with Team Cherry.+ * Made by Mason Chen as part of NumPlay. */+#pragma once+#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>+#include <string.h>+#include "data.h"++#define SCREEN_W 320+#define SCREEN_H 240+/* the game keeps a 16:10 view (ForceCameraAspect): bars above and below */+#define VIEW_W 320+#define VIEW_H 200+#define VIEW_Y 20++/* the camera: perspective, 24 degrees high at 16:9, 38.1 units in front of the gameplay plane */+#define CAM_Z (-38.1f)+#define FOCAL 421.94f /* (VIEW_H / 2) / tan(fov / 2), fov = 24 * (16/9) / 1.6 */++/* ---------------------------------------------------------------- platform */+enum {+ K_LEFT = 1, K_RIGHT = 2, K_UP = 4, K_DOWN = 8,+ K_JUMP = 16, K_ATTACK = 32, K_FOCUS = 64, K_SPELL = 128, K_DASH = 256,+ K_OK = 512, K_BACK = 1024, K_PAUSE = 2048, K_MAP = 4096, K_INV = 8192, K_HOME = 16384, K_ANY = 32768,+};+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);++/* ---------------------------------------------------------------- data.bin */+extern const uint8_t *hk_bin;+const uint8_t *section(int id);+uint32_t section_size(int id);+static inline uint16_t rd16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); }+static inline uint32_t rd32(const uint8_t *p) { return (uint32_t)(p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24); }+void lz_decode(const uint8_t *src, uint32_t comp, uint8_t *dst, uint32_t raw);+/* decoders' working memory (LZMA probabilities or the tile coder's), one at a time */+extern uint16_t g_scratch[4096];+float f16(uint16_t h);+const char *str_at(int id); /* the shared string table (SEC_STR) */++/* ---------------------------------------------------------------- textures (tex.c) */+typedef struct {+ uint16_t w, h;+ uint8_t tw, th, fmt, flags; /* flags: TEX_SMOOTH (drawn interpolated: the blurred background) */+ uint32_t pal_off, map_off, blk_first;+} TexRec;+#define TEX_SMOOTH 1+enum { FMT_PAL4 = 0, FMT_ALPHA2 = 1, FMT_SOFT = 2, FMT_SOFTA = 3 };+#define TILE 16+#define TILE_SHIFT(fmt) ((fmt) == FMT_ALPHA2 ? 5 : 4) /* a tile's width, log 2 */+#define TEX_NONE 0xFFFF+const TexRec *tex_rec(uint16_t t);+/* the tile's texels (128 bytes: 16x16 of 4 bits, or 32x16 of 2 bits for FMT_ALPHA2), NULL for an empty one; decodes+ * on demand */+const uint8_t *tex_tile(uint16_t t, int tx, int ty);+/* the same, as a cache slot (-1: an empty tile): it holds until the cache runs out of room in a frame */+int tex_slot(uint16_t t, int tx, int ty);+const uint8_t *tex_slot_px(int s);+extern bool g_tex_overload;+/* a tile row's codes: 0 empty, 1 a tile, 3 an opaque tile (2 bits each) */+const uint8_t *tex_row_codes(uint16_t t, int ty);+void tex_frame(void); /* a new frame: tiles used from now on are this frame's */+extern uint32_t g_tex_decodes, g_tex_misses, g_tex_calls;++/* ---------------------------------------------------------------- rooms (room.c) */+typedef struct {+ int16_t ax, ay; /* the texture's top-left corner (1/64 unit) */+ int16_t z; /* depth (1/128 unit) */+ uint16_t tex;+ uint8_t tint, flags;+ uint16_t a, b; /* world units a texel along u and v (half floats, signed) */+ int16_t rot; /* the u axis' angle (1/65536 turn) */+} Inst;+enum { BL_ALPHA = 0, BL_ADD, BL_SCREEN, BL_LINEARLIGHT, BL_OVERLAY, BL_MULTIPLY };+#define F_BLEND 7+#define F_LIT 8+#define F_ROT 16+#define F_SOLID 32+#define F_DYN 64+#define F_GRASS 128+typedef struct {+ uint16_t version, nsec, ntint, axis;+ float w, h, blur_z, saturation;+ float ambient[4];+ float hero_light[4];+ float lo, hi; /* the camera's range along the axis the room is split on */+ uint16_t ninst;+ uint16_t nseg, ncol, gw, gh; /* the ground (phys.c) */+ uint16_t nent; /* game objects (game.h: Ent) */+ uint32_t ground, ents; /* (in SEC_RBLOB) */+ uint8_t lut[3][64];+} RoomHdr;+typedef struct {+ uint32_t off, len; /* its instances, in draw order (read in place) */+ uint16_t count, pad;+ float start, end; /* camera positions from which its instances can show */+} SectorRec;+#define MAX_LOADED 16+typedef struct {+ int id;+ RoomHdr *h;+ const uint8_t *tints; /* RGBA */+ const SectorRec *secs;+ int nnear;+ uint8_t near[MAX_LOADED]; /* the sectors near the camera */+} Room;+extern Room g_room;+bool room_load(int id);+void room_near(float cx, float cy); /* picks the sectors near the camera */+/* their instances, merged back to front: room_first, then room_next until it says no more; with each, its sorting+ * layer and order */+void room_first(void);+bool room_next(Inst *out, uint32_t *group);+#define SORT_KEY(layer, order) ((uint32_t)(layer) << 16 | (uint32_t)((order) + 32768))+const char *room_name(int id);++/* ---------------------------------------------------------------- sprites and animations (anim.c) */+typedef struct {+ uint16_t tex, pad;+ float lx, ty; /* the texture's top-left corner, from the sprite's origin (units) */+ float tu, tv; /* units a texel */+} SpriteRec;+const SpriteRec *sprite_rec(int id);+enum { ANIM_DONE = 1, ANIM_TRIGGER = 2 };+typedef struct {+ int16_t clip, frame, sprite;+ float time, fps; /* time in frames */+ bool playing, paused;+ uint8_t events; /* ANIM_*: what happened since the owner last cleared them */+} Anim;+void anim_play(Anim *a, int clip); /* (a clip already playing goes on) */+void anim_play_from(Anim *a, int clip, float start);+void anim_play_from_frame(Anim *a, int clip, int frame);+bool anim_is_playing(const Anim *a, int clip);+void anim_update(Anim *a, float dt);+float clip_duration(int clip);+int clip_frames_count(int clip);+uint16_t to_f16(float f);+void sprite_inst(int sprite, float x, float y, float z, float sx, float sy, uint8_t tint, Inst *out);++/* ---------------------------------------------------------------- the ground (phys.c) */+/* a collider's flags (tools/coll.py) */+enum { CF_TERRAIN = 1, CF_STEEP = 2, CF_NONSLIDER = 4, CF_NOHARDLAND = 8, CF_ROOF = 16, CF_SOLID = 32 };+typedef struct {+ float dist, x, y, nx, ny; /* where, and the ground's normal there */+ int col;+} PhysHit;+/* a ray from (x, y) along (dx, dy) (a unit vector) for dist: the nearest ground (of colliders with a flag in mask) */+bool phys_ray(float x, float y, float dx, float dy, float dist, uint8_t mask, PhysHit *hit);+uint8_t phys_col_flags(int col);+bool phys_tile_solid(int x, int y);++enum { EV_ENTER, EV_STAY, EV_EXIT };+typedef struct {+ uint8_t kind, col;+ float nx, ny; /* the contact's normal, towards the body */+} BodyEvent;+#define MAX_CONTACTS 8+#define MAX_EVENTS 16+/* a rigid body with a box collider, as Unity moves it (Rigidbody2D, Box2D) */+typedef struct {+ float x, y, vx, vy; /* its position (the transform's) and velocity */+ float ox, oy, hx, hy; /* the box: its center from the position, half its size */+ float gravity_scale;+ uint8_t mask; /* the colliders that stop it (CF_*) */+ int ncontacts;+ uint8_t ccol[MAX_CONTACTS];+ float cnx[MAX_CONTACTS], cny[MAX_CONTACTS];+ int nevents; /* the last step's: OnCollisionEnter2D, Stay, Exit */+ BodyEvent events[MAX_EVENTS];+} Body;+void body_step(Body *b, float dt);++/* ---------------------------------------------------------------- drawing (gfx.c) */+extern float g_cam_x, g_cam_y; /* the view's center (world units) */+void gfx_frame(void); /* draws the room at the camera into the screen */+/* a sprite of the Knight, an enemy, an effect... for the next frame, among the room's by its sorting layer and order+ * (SORT_KEY), then depth */+bool gfx_actor(const Inst *in, uint32_t group);+extern uint32_t g_gfx_items, g_gfx_pixels;diff --git a/games/hollowknight/src/icon.png b/games/hollowknight/src/icon.pngnew file mode 100644index 00000000..bdef12f7Binary files /dev/null and b/games/hollowknight/src/icon.png differdiff --git a/games/hollowknight/src/lzma/7zTypes.h b/games/hollowknight/src/lzma/7zTypes.hnew file mode 100644index 00000000..4977cdaa--- /dev/null+++ b/games/hollowknight/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++#endifdiff --git a/games/hollowknight/src/lzma/LzmaDec.c b/games/hollowknight/src/lzma/LzmaDec.cnew file mode 100644index 00000000..962b94bb--- /dev/null+++ b/games/hollowknight/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/hollowknight/src/lzma/LzmaDec.h b/games/hollowknight/src/lzma/LzmaDec.hnew file mode 100644index 00000000..28ce60c3--- /dev/null+++ b/games/hollowknight/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++#endifdiff --git a/games/hollowknight/src/lzma/Precomp.h b/games/hollowknight/src/lzma/Precomp.hnew file mode 100644index 00000000..fdaa2452--- /dev/null+++ b/games/hollowknight/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+#endifdiff --git a/games/hollowknight/src/main.c b/games/hollowknight/src/main.cnew file mode 100644index 00000000..3ad3390d--- /dev/null+++ b/games/hollowknight/src/main.c@@ -0,0 +1,88 @@+/* Hollow Knight for the NumWorks calculator.+ *+ * Inspired by Hollow Knight, not affiliated with Team Cherry.+ * Made by Mason Chen as part of NumPlay. */+#include "game.h"++#ifndef HOST+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Hollow Knight";+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;+extern const uint8_t hk_data[];++void plat_begin(void);+int plat_end(void);++uint32_t perf_frames __attribute__((used)); /* read by tools/emu.py */+uint32_t perf_updates __attribute__((used));++#define TICK_MS 20 /* the game's step (Unity's fixed step) */+#define MAX_TICKS 4 /* steps caught up before a frame is drawn */++#ifdef PERF_ROOM+/* timing: the camera panning across a room */+#ifndef PERF_X+#define PERF_X 30+#endif+#ifndef PERF_Y+#define PERF_Y 40+#endif+#ifndef PERF_DX+#define PERF_DX 0.15f+#endif+int main(void) {+ plat_begin();+ hk_bin = hk_data;+ plat_fill(0, 0, SCREEN_W, SCREEN_H, 0);+ room_load(PERF_ROOM);+ g_cam_x = PERF_X, g_cam_y = PERF_Y;+ for (;;) {+ if (plat_keys() & K_HOME) break;+ gfx_frame();+ perf_frames++, perf_updates++;+ g_cam_x += PERF_DX;+ if (g_cam_x > g_room.h->w - 14.6f) g_cam_x = 14.6f;+ }+ return plat_end();+}+#else+/* a new game: the Knight at King's Pass' respawn point */+static void start(void) {+ game_new();+ room_load(ROOM_TUTORIAL_01);+ int n;+ const Ent *e = room_ents(&n);+ float x = 35.46f, y = 11.37f;+ bool right = true;+ for (int i = 0; i < n; i++)+ if (e[i].type == ENT_RESPAWN) x = e[i].x0, y = e[i].y0, right = e[i].flags & FACING_RIGHT;+ game_enter(ROOM_TUTORIAL_01, x, y, right);+}++int main(void) {+ plat_begin();+ hk_bin = hk_data;+ plat_fill(0, 0, SCREEN_W, SCREEN_H, 0);+ start();+ uint32_t last = plat_millis(), acc = 0;+ for (;;) {+ uint32_t keys = plat_keys();+ if (keys & K_HOME) break;+ uint32_t now = plat_millis();+ acc += now - last, last = now;+ int ticks = 0;+ while (acc >= TICK_MS && ticks < MAX_TICKS) {+ game_tick(keys);+ acc -= TICK_MS, ticks++, perf_updates++;+ }+ if (ticks == MAX_TICKS) acc = 0; /* (too slow to catch up: the game slows down instead) */+ if (!ticks) {+ plat_sleep(TICK_MS - acc);+ continue;+ }+ game_draw();+ perf_frames++;+ }+ return plat_end();+}+#endif+#endifdiff --git a/games/hollowknight/src/phys.c b/games/hollowknight/src/phys.cnew file mode 100644index 00000000..12811e6e--- /dev/null+++ b/games/hollowknight/src/phys.c@@ -0,0 +1,275 @@+/* The room's ground (tools/coll.py: segments, read in place) and what the game asks of Unity's 2D physics: rays, and+ * bodies (a box) that fall, slide along the ground and say which colliders they touch. */+#include <math.h>+#include "hk.h"+#ifdef HOST+#include <stdio.h>+#include <stdlib.h>+#endif++#define UNIT (1.0f / 128)+#define CELL 8.0f+#define SKIN 0.01f /* how far a body rests from the ground (Box2D's polygon radius) */++typedef struct {+ int16_t x0, y0, x1, y1; /* (1/128 unit) */+} Seg;++static const uint8_t *g_cols, *g_tiles, *g_seg_col;+static const Seg *g_segs;+static const uint16_t *g_cell_first, *g_cell_list;+static int g_tw, g_th, g_row_bytes;+static int g_room_ground = -1;++static void ground_init(void) {+ if (g_room_ground == g_room.id) return;+ const RoomHdr *h = g_room.h;+ const uint8_t *p = section(SEC_RBLOB) + h->ground;+ g_cols = p;+ p += (h->ncol + 1u) & ~1u;+ g_tw = rd16(p), g_th = rd16(p + 2);+ g_row_bytes = (g_tw + 7) / 8;+ g_tiles = p + 4;+ p += (4u + (uint32_t)g_th * g_row_bytes + 1) & ~1u;+ g_segs = (const Seg *)(const void *)p;+ p += sizeof(Seg) * h->nseg;+ g_seg_col = p;+ p += (h->nseg + 1u) & ~1u;+ g_cell_first = (const uint16_t *)(const void *)p;+ g_cell_list = g_cell_first + h->gw * h->gh + 1;+ g_room_ground = g_room.id;+}++uint8_t phys_col_flags(int col) {+ ground_init();+ return g_cols[col];+}++bool phys_tile_solid(int x, int y) {+ ground_init();+ if ((unsigned)x >= (unsigned)g_tw || (unsigned)y >= (unsigned)g_th) return false;+ return g_tiles[y * g_row_bytes + (x >> 3)] >> (x & 7) & 1;+}++static inline int cell_x(float x) {+ int c = (int)floorf(x / CELL) + 1, w = g_room.h->gw;+ return c < 0 ? 0 : c >= w ? w - 1 : c;+}+static inline int cell_y(float y) {+ int c = (int)floorf(y / CELL) + 1, h = g_room.h->gh;+ return c < 0 ? 0 : c >= h ? h - 1 : c;+}++/* the ground's segments near a box: the room's (maybe twice) and the tilemap's faces between solid and open tiles */+typedef struct {+ float ax, ay, bx, by;+ uint8_t col;+} Cand;+#define MAX_CAND 192++static int gather(float x0, float y0, float x1, float y1, uint8_t mask, Cand *out) {+ ground_init();+ int n = 0;+ int gw = g_room.h->gw;+ for (int cy = cell_y(y0), cy1 = cell_y(y1); cy <= cy1; cy++)+ for (int cx = cell_x(x0), cx1 = cell_x(x1); cx <= cx1; cx++)+ for (int k = g_cell_first[cy * gw + cx], e = g_cell_first[cy * gw + cx + 1]; k < e; k++) {+ int i = g_cell_list[k];+ uint8_t col = g_seg_col[i];+ if (!(g_cols[col] & mask) || n == MAX_CAND) continue;+ const Seg *s = &g_segs[i];+ float ax = s->x0 * UNIT, ay = s->y0 * UNIT, bx = s->x1 * UNIT, by = s->y1 * UNIT;+ if ((ax < x0 && bx < x0) || (ax > x1 && bx > x1) || (ay < y0 && by < y0) || (ay > y1 && by > y1)) continue;+ out[n++] = (Cand){ax, ay, bx, by, col};+ }+ if (!(g_cols[0] & mask)) return n;+ int tx0 = (int)floorf(x0) - 1, tx1 = (int)floorf(x1) + 1, ty0 = (int)floorf(y0) - 1, ty1 = (int)floorf(y1) + 1;+ if (tx0 < 0) tx0 = 0;+ if (ty0 < 0) ty0 = 0;+ if (tx1 >= g_tw) tx1 = g_tw - 1;+ if (ty1 >= g_th) ty1 = g_th - 1;+ for (int ty = ty0; ty <= ty1; ty++)+ for (int tx = tx0; tx <= tx1; tx++) {+ if (!phys_tile_solid(tx, ty) || n > MAX_CAND - 4) continue;+ float X = (float)tx, Y = (float)ty;+ if (!phys_tile_solid(tx - 1, ty)) out[n++] = (Cand){X, Y, X, Y + 1, 0};+ if (!phys_tile_solid(tx + 1, ty)) out[n++] = (Cand){X + 1, Y, X + 1, Y + 1, 0};+ if (!phys_tile_solid(tx, ty - 1)) out[n++] = (Cand){X, Y, X + 1, Y, 0};+ if (!phys_tile_solid(tx, ty + 1)) out[n++] = (Cand){X, Y + 1, X + 1, Y + 1, 0};+ }+ return n;+}++/* ---------------------------------------------------------------- rays */+bool phys_ray(float x, float y, float dx, float dy, float dist, uint8_t mask, PhysHit *hit) {+ float ex = x + dx * dist, ey = y + dy * dist;+ Cand cand[MAX_CAND];+ int n = gather(fminf(x, ex), fminf(y, ey), fmaxf(x, ex), fmaxf(y, ey), mask, cand);+ float best = dist + 1;+ int bcol = -1;+ float bnx = 0, bny = 0;+ for (int i = 0; i < n; i++) {+ const Cand *s = &cand[i];+ float sx = s->bx - s->ax, sy = s->by - s->ay;+ float den = dx * sy - dy * sx;+ if (fabsf(den) < 1e-9f) continue;+ float qx = s->ax - x, qy = s->ay - y;+ float t = (qx * sy - qy * sx) / den; /* along the ray */+ float u = (qx * dy - qy * dx) / den; /* along the segment */+ if (t < 0 || t > dist || u < 0 || u > 1 || t >= best) continue;+ best = t, bcol = s->col;+ float l = sqrtf(sx * sx + sy * sy);+ bnx = -sy / l, bny = sx / l;+ if (bnx * dx + bny * dy > 0) bnx = -bnx, bny = -bny; /* facing the ray */+ }+ if (bcol < 0) return false;+ if (hit) hit->dist = best, hit->x = x + dx * best, hit->y = y + dy * best, hit->nx = bnx, hit->ny = bny, hit->col = bcol;+ return true;+}++/* ---------------------------------------------------------------- a box against a segment (separating axes) */+/* the box (center cx, cy, half sizes hx, hy) moving by (dx, dy) and the segment: the first time (0..1) they touch and the+ * normal there (towards the box); false if they do not. Already overlapping: time 0 and the shortest way out (depth). */+static bool box_seg(float cx, float cy, float hx, float hy, float dx, float dy, const Cand *s, float *toi, float *nx,+ float *ny, float *depth) {+ float ax = s->ax, ay = s->ay, bx = s->bx, by = s->by;+ float sx = bx - ax, sy = by - ay, l = sqrtf(sx * sx + sy * sy);+ if (l < 1e-6f) return false;+ float axes[3][2] = {{1, 0}, {0, 1}, {-sy / l, sx / l}};+ float t0 = -1e30f, t1 = 1e30f, tnx = 0, tny = 0, pen = 1e30f, pnx = 0, pny = 0;+ bool inside = true; /* (overlapping on every axis now, not just touching) */+ for (int i = 0; i < 3; i++) {+ float ux = axes[i][0], uy = axes[i][1];+ float r = hx * fabsf(ux) + hy * fabsf(uy);+ float c = cx * ux + cy * uy, pa = ax * ux + ay * uy, pb = bx * ux + by * uy;+ float lo = (pa < pb ? pa : pb) - r, hi = (pa < pb ? pb : pa) + r; /* where the box center overlaps */+ float v = dx * ux + dy * uy;+ /* overlap now: how deep, and which way out */+ if (c > lo + 1e-5f && c < hi - 1e-5f) {+ float out_lo = c - lo, out_hi = hi - c;+ if (out_lo < pen) pen = out_lo, pnx = -ux, pny = -uy; /* (out past lo: the negative way) */+ if (out_hi < pen) pen = out_hi, pnx = ux, pny = uy;+ } else+ inside = false;+ if (fabsf(v) < 1e-12f) {+ if (c <= lo || c >= hi) return false; /* never meet on this axis */+ continue;+ }+ float ta = (lo - c) / v, tb = (hi - c) / v;+ float enter = ta < tb ? ta : tb, leave = ta < tb ? tb : ta;+ if (enter > t0) {+ t0 = enter;+ /* the normal opposes the motion on this axis */+ tnx = v > 0 ? -ux : ux, tny = v > 0 ? -uy : uy;+ }+ if (leave < t1) t1 = leave;+ if (t0 > t1) return false;+ }+ if (t1 < 0 || t0 > 1) return false;+ if (t0 < 0) {+ /* overlapping already; or just touching, and not moving into it */+ if (!inside) return false;+ *toi = 0, *nx = pnx, *ny = pny, *depth = pen;+ return true;+ }+ *toi = t0, *nx = tnx, *ny = tny, *depth = 0;+ return true;+}++/* ---------------------------------------------------------------- bodies */+#define GRAVITY (-60.0f)++static void body_box(const Body *b, float *cx, float *cy) { *cx = b->x + b->ox, *cy = b->y + b->oy; }++/* the colliders the box touches now, with a normal each (towards the box) */+static int touching(const Body *b, uint8_t mask, uint8_t *cols, float *nxs, float *nys, int max) {+ float cx, cy;+ body_box(b, &cx, &cy);+ float hx = b->hx + SKIN * 2, hy = b->hy + SKIN * 2;+ Cand cand[MAX_CAND];+ int nc = gather(cx - hx, cy - hy, cx + hx, cy + hy, mask, cand), n = 0;+ for (int k = 0; k < nc; k++) {+ const Cand *s = &cand[k];+ float toi, nx, ny, depth;+ if (!box_seg(cx, cy, hx, hy, 0, 0, s, &toi, &nx, &ny, &depth)) continue;+ int i = 0;+ while (i < n && cols[i] != s->col) i++;+ if (i < n) {+ /* (the most upward normal of its contacts: standing beats touching a side) */+ if (ny > nys[i]) nxs[i] = nx, nys[i] = ny;+ continue;+ }+ if (n == max) break;+ cols[n] = s->col, nxs[n] = nx, nys[n] = ny, n++;+ }+ return n;+}++void body_step(Body *b, float dt) {+ if (b->gravity_scale) b->vy += GRAVITY * b->gravity_scale * dt;+ /* resting contacts take away the velocity into them (the solver), then the box moves and slides */+ for (int i = 0; i < b->ncontacts; i++) {+ float vn = b->vx * b->cnx[i] + b->vy * b->cny[i];+ if (vn < 0) b->vx -= vn * b->cnx[i], b->vy -= vn * b->cny[i];+ }+ float left = 1;+ for (int it = 0; it < 4 && left > 0; it++) {+ float dx = b->vx * dt * left, dy = b->vy * dt * left;+ float cx, cy;+ body_box(b, &cx, &cy);+ float hx = b->hx + SKIN, hy = b->hy + SKIN;+ float bx0 = fminf(cx, cx + dx) - hx, bx1 = fmaxf(cx, cx + dx) + hx, by0 = fminf(cy, cy + dy) - hy, by1 = fmaxf(cy, cy + dy) + hy;+ float best = 2, bnx = 0, bny = 0, deep = 0, dnx = 0, dny = 0;+ Cand cand[MAX_CAND];+ int nc = gather(bx0, by0, bx1, by1, b->mask, cand);+ for (int k = 0; k < nc; k++) {+ const Cand *s = &cand[k];+ float toi, nx, ny, depth;+ if (!box_seg(cx, cy, hx, hy, dx, dy, s, &toi, &nx, &ny, &depth)) continue;+ if (depth > 0) {+#ifdef HOST+ if (getenv("PHYSDBG")) fprintf(stderr, " deep seg %.3f,%.3f-%.3f,%.3f col %d depth %.3f n %.2f,%.2f box c %.3f,%.3f h %.3f,%.3f\n", s->ax, s->ay, s->bx, s->by, s->col, depth, nx, ny, cx, cy, hx, hy);+#endif+ if (depth > deep) deep = depth, dnx = nx, dny = ny;+ continue;+ }+ if (nx * dx + ny * dy >= 0) continue; /* moving away from it */+ if (toi < best) best = toi, bnx = nx, bny = ny;+ }+#ifdef HOST+ if (getenv("PHYSDBG")) fprintf(stderr, "it %d d %.4f,%.4f best %.3f n %.2f,%.2f deep %.4f dn %.2f,%.2f nc %d\n", it, dx, dy, best, bnx, bny, deep, dnx, dny, nc);+#endif+ if (deep > 0) {+ /* inside the ground (it moved, or the body was put there): out the shortest way */+ b->x += dnx * deep, b->y += dny * deep;+ float vn = b->vx * dnx + b->vy * dny;+ if (vn < 0) b->vx -= vn * dnx, b->vy -= vn * dny;+ continue;+ }+ if (best > 1) {+ b->x += dx, b->y += dy;+ break;+ }+ b->x += dx * best, b->y += dy * best;+ float vn = b->vx * bnx + b->vy * bny;+ if (vn < 0) b->vx -= vn * bnx, b->vy -= vn * bny;+ left *= 1 - best;+ }+ /* what it touches now: enter, stay, exit */+ uint8_t cols[MAX_CONTACTS];+ float nxs[MAX_CONTACTS], nys[MAX_CONTACTS];+ int n = touching(b, b->mask, cols, nxs, nys, MAX_CONTACTS);+ b->nevents = 0;+ for (int i = 0; i < b->ncontacts; i++) {+ int j = 0;+ while (j < n && cols[j] != b->ccol[i]) j++;+ if (j == n && b->nevents < MAX_EVENTS) b->events[b->nevents++] = (BodyEvent){EV_EXIT, b->ccol[i], b->cnx[i], b->cny[i]};+ }+ for (int j = 0; j < n; j++) {+ int i = 0;+ while (i < b->ncontacts && b->ccol[i] != cols[j]) i++;+ if (b->nevents < MAX_EVENTS) b->events[b->nevents++] = (BodyEvent){i == b->ncontacts ? EV_ENTER : EV_STAY, cols[j], nxs[j], nys[j]};+ }+ b->ncontacts = n;+ for (int j = 0; j < n; j++) b->ccol[j] = cols[j], b->cnx[j] = nxs[j], b->cny[j] = nys[j];+}diff --git a/games/hollowknight/src/plat_eadk.c b/games/hollowknight/src/plat_eadk.cnew file mode 100644index 00000000..f283a011--- /dev/null+++ b/games/hollowknight/src/plat_eadk.c@@ -0,0 +1,40 @@+/* The calculator: EADK display, keyboard, time and files. */+#include <eadk.h>+#include "../../common/epsilon_app.h"+#include "../../common/epsilon_files.h"+#include "hk.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)) r |= K_LEFT;+ if (k & KEY(eadk_key_right)) r |= K_RIGHT;+ if (k & KEY(eadk_key_up)) r |= K_UP;+ if (k & KEY(eadk_key_down)) r |= K_DOWN;+ if (k & KEY(eadk_key_ok)) r |= K_JUMP | K_OK;+ if (k & KEY(eadk_key_back)) r |= K_ATTACK | K_BACK;+ if (k & KEY(eadk_key_shift)) r |= K_DASH;+ if (k & KEY(eadk_key_alpha)) r |= K_SPELL | K_FOCUS;+ if (k & KEY(eadk_key_exe)) r |= K_OK;+ if (k & KEY(eadk_key_backspace)) r |= K_PAUSE;+ if (k & KEY(eadk_key_toolbox)) r |= K_INV;+ if (k & KEY(eadk_key_var)) r |= K_MAP;+ 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); }+void plat_begin(void) { np_app_begin(); }+int plat_end(void) { return np_app_end(); }diff --git a/games/hollowknight/src/plat_host.c b/games/hollowknight/src/plat_host.cnew file mode 100644index 00000000..14bcca65--- /dev/null+++ b/games/hollowknight/src/plat_host.c@@ -0,0 +1,57 @@+/* 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 "hk.h"++uint16_t host_fb[SCREEN_W * SCREEN_H];+uint32_t host_time, 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;+ fwrite(data, 1, len, f);+ fclose(f);+ return true;+}+static uint8_t loaded[65536];+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;+ *len = (uint32_t)fread(loaded, 1, sizeof loaded, f);+ fclose(f);+ return loaded;+}+void plat_begin(void) {}+int plat_end(void) { return 0; }++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/hollowknight/src/res.c b/games/hollowknight/src/res.cnew file mode 100644index 00000000..089fbca7--- /dev/null+++ b/games/hollowknight/src/res.c@@ -0,0 +1,50 @@+/* data.bin: its sections, LZMA streams, half floats. */+#include "hk.h"+#include "lzma/LzmaDec.h"++const uint8_t *hk_bin;++const uint8_t *section(int id) { return hk_bin + rd32(hk_bin + 8 + 8 * id); }+uint32_t section_size(int id) { return rd32(hk_bin + 12 + 8 * id); }++uint16_t g_scratch[4096];+#define LZ_PROBS ((CLzmaProb *)g_scratch) /* NUM_BASE_PROBS + LZMA_LIT_SIZE << (lc + lp) = 2752, lc = lp = 0 */++/* a raw LZMA stream (lc = lp = pb = 0) decoded whole: the output is its own dictionary */+void lz_decode(const uint8_t *src, uint32_t comp, uint8_t *dst, uint32_t raw) {+ CLzmaDec dec;+ memset(&dec, 0, sizeof dec);+ dec.prop.lc = 0, dec.prop.lp = 0, dec.prop.pb = 0, dec.prop.dicSize = raw;+ dec.probs = LZ_PROBS;+ dec.probs_1664 = LZ_PROBS + 1664;+ dec.numProbs = 1984 + 768;+ dec.dic = dst;+ dec.dicBufSize = raw;+ LzmaDec_Init(&dec);+ SizeT inlen = comp;+ ELzmaStatus st;+ if (LzmaDec_DecodeToDic(&dec, raw, src, &inlen, LZMA_FINISH_ANY, &st) != SZ_OK || dec.dicPos != raw)+ memset(dst + dec.dicPos, 0, raw - dec.dicPos); /* (never: the data is ours) */+}++float f16(uint16_t h) {+ uint32_t s = (uint32_t)(h & 0x8000) << 16, e = (h >> 10) & 31, m = h & 1023, f;+ if (e == 0) {+ if (!m) f = s;+ else { /* subnormal */+ e = 113;+ while (!(m & 1024)) m <<= 1, e--;+ f = s | e << 23 | (m & 1023) << 13;+ }+ } else if (e == 31) f = s | 0x7F800000 | m << 13;+ else f = s | (e + 112) << 23 | m << 13;+ float r;+ memcpy(&r, &f, 4);+ return r;+}++const char *str_at(int id) {+ const uint8_t *s = section(SEC_STR);+ if ((uint32_t)id >= rd32(s)) return "";+ return (const char *)s + 4 + 4 * rd32(s) + rd32(s + 4 + 4 * id);+}diff --git a/games/hollowknight/src/room.c b/games/hollowknight/src/room.cnew file mode 100644index 00000000..a84044f5--- /dev/null+++ b/games/hollowknight/src/room.c@@ -0,0 +1,116 @@+/* Rooms: a scene's header in RAM, its instances in sectors along its long axis, read in place near the camera. */+#include "hk.h"++#define HDR_RAM 2048+#define ENTRY 44 /* name (32), header offset, packed size, size */+static uint32_t hdr_ram[HDR_RAM / 4];+Room g_room = {.id = -1};++static const uint8_t *room_entry(int id) { return section(SEC_ROOMS) + 4 + ENTRY * id; }+const char *room_name(int id) { return (const char *)room_entry(id); }++bool room_load(int id) {+ if (id < 0 || id >= NUM_ROOMS) return false;+ const uint8_t *e = room_entry(id);+ uint32_t off = rd32(e + 32), comp = rd32(e + 36), raw = rd32(e + 40);+ if (raw > sizeof hdr_ram) return false;+ lz_decode(section(SEC_RBLOB) + off, comp, (uint8_t *)hdr_ram, raw);+ RoomHdr *h = (RoomHdr *)hdr_ram;+ g_room.id = id;+ g_room.h = h;+ g_room.tints = (const uint8_t *)hdr_ram + sizeof(RoomHdr);+ g_room.secs = (const SectorRec *)((const uint8_t *)hdr_ram + ((sizeof(RoomHdr) + 4u * h->ntint + 3) & ~3u));+ g_room.nnear = 0;+ return true;+}++void room_near(float cx, float cy) {+ const RoomHdr *h = g_room.h;+ float p = h->axis ? cy : cx;+ int n = 0;+ for (int i = 0; i < h->nsec && n < MAX_LOADED; i++)+ if (g_room.secs[i].start <= p + 2 && g_room.secs[i].end >= p - 2) g_room.near[n++] = (uint8_t)i;+ g_room.nnear = n;+}++/* ---------------------------------------------------------------- reading the sectors (tools/pack.py: sector_stream) */+typedef struct {+ const uint8_t *p;+ uint16_t left, rank;+ uint32_t group; /* its sorting layer and order (room.h: SORT_KEY) */+ Inst in; /* the one read last */+} Stream;+static Stream streams[MAX_LOADED];+static int nstreams;++static inline uint32_t uvar(const uint8_t **pp) {+ const uint8_t *p = *pp;+ uint32_t v = 0;+ int s = 0;+ uint8_t c;+ do {+ c = *p++;+ v |= (uint32_t)(c & 127) << s;+ s += 7;+ } while (c & 128);+ *pp = p;+ return v;+}+static inline int32_t svar(const uint8_t **pp) {+ uint32_t u = uvar(pp);+ return (int32_t)(u >> 1) ^ -(int32_t)(u & 1);+}++/* the stream's next instance (into s->in), false at its end */+static bool advance(Stream *s) {+ if (!s->left) return false;+ s->left--;+ const uint8_t *p = s->p;+ Inst *in = &s->in;+ uint8_t flags = *p++, aux = *p++;+ in->flags = flags;+ s->rank = (uint16_t)(s->rank + ((aux & 64) ? 1 : uvar(&p) + 2));+ if (aux & 128) {+ uint8_t layer = *p++;+ s->group = SORT_KEY(layer, svar(&p));+ }+ if (!(aux & 2)) in->tex = (uint16_t)(in->tex + svar(&p));+ in->tint = (aux & 1) ? *p++ : 0;+ in->ax = (int16_t)(in->ax + svar(&p));+ in->ay = (int16_t)(in->ay + svar(&p));+ if (!(aux & 4)) in->z = (int16_t)(in->z + svar(&p));+ if (!(aux & 32)) in->a = rd16(p), p += 2;+ switch (aux >> 3 & 3) {+ case 0: in->b = rd16(p), p += 2; break;+ case 1: in->b = in->a; break;+ case 2: in->b = in->a ^ 0x8000; break;+ default: break;+ }+ if (flags & F_ROT) in->rot = (int16_t)rd16(p), p += 2;+ else in->rot = 0;+ s->p = p;+ return true;+}++void room_first(void) {+ const uint8_t *blob = section(SEC_RBLOB);+ nstreams = 0;+ for (int j = 0; j < g_room.nnear; j++) {+ const SectorRec *r = &g_room.secs[g_room.near[j]];+ Stream *s = &streams[nstreams];+ memset(s, 0, sizeof *s);+ s->p = blob + r->off, s->left = r->count, s->rank = 0xFFFF;+ if (advance(s)) nstreams++;+ }+}++bool room_next(Inst *out, uint32_t *group) {+ if (!nstreams) return false;+ int best = 0;+ for (int j = 1; j < nstreams; j++)+ if (streams[j].rank < streams[best].rank) best = j;+ Stream *s = &streams[best];+ *out = s->in, *group = s->group;+ if (!advance(s)) streams[best] = streams[--nstreams];+ return true;+}diff --git a/games/hollowknight/src/tex.c b/games/hollowknight/src/tex.cnew file mode 100644index 00000000..85ad7168--- /dev/null+++ b/games/hollowknight/src/tex.c@@ -0,0 +1,242 @@+/* Scenery textures: 16x16 tiles (32x16 at 2 bits), decoded from their LZMA blocks into a cache when first drawn. */+#include "hk.h"+#include "tilecode.h"++#ifndef NSLOTS+#define NSLOTS 400+#endif+#define NHASH 512+#define NO 0xFFFF+#define BLOCK_TILES 16++static uint8_t slot_px[NSLOTS][128];+static uint32_t slot_key[NSLOTS];+static uint16_t slot_next[NSLOTS], slot_frame[NSLOTS];+static uint16_t head[NHASH];+static uint16_t frame = 1, hand;+static uint8_t block_buf[BLOCK_TILES * 128];+#define tcp g_scratch /* TC_CTX4 * 16 */++/* ---------------------------------------------------------------- the tile decoder (tilecode.h) */+/* one binary step: the range coder's state in locals (rng, code, src), the probability at pr */+#define RC_BIT(pr, bit) \+ do { \+ uint16_t *pr_ = (pr); \+ uint32_t pv_ = *pr_, bound_ = (rng >> TC_PROB_BITS) * (pv_ >> 4); \+ uint32_t n_ = pv_ & 15, sh_ = n_ + 1 < TC_LIM ? n_ + 1 : TC_LIM, p_ = pv_ >> 4; \+ if (code < bound_) rng = bound_, bit = 0, p_ += (4096 - p_) >> sh_; \+ else code -= bound_, rng -= bound_, bit = 1, p_ -= p_ >> sh_; \+ while (rng < (1u << 24)) rng <<= 8, code = code << 8 | *src++; \+ *pr_ = (uint16_t)(p_ << 4 | (n_ < 15 ? n_ + 1 : 15)); \+ } while (0)++/* n tiles of a block, packed (4 bits a texel, or 2 in tiles twice as wide) into out, 128 bytes each */+static void decode_block(const uint8_t *src, int n, bool two, uint8_t *out) {+ /* the trained probabilities, already packed (pack.py) */+ const uint8_t *prior = section(SEC_PRIOR);+ if (two) memcpy(tcp, prior + TC_CTX4 * 16 * 2, TC_CTX2 * 4 * 2);+ else memcpy(tcp, prior, TC_CTX4 * 16 * 2);+ uint32_t rng = 0xFFFFFFFFu, code = 0;+ for (int i = 0; i < 5; i++) code = code << 8 | *src++;+ uint8_t img[512];+ for (int t = 0; t < n; t++) {+ if (two) {+ for (int y = 0; y < 16; y++)+ for (int x = 0; x < 32; x++) {+ int l = tc_left(img, x, y, 32), u = tc_up(img, x, y, l, 32), b0, b1;+ uint16_t *p = tcp + (l * 4 + u) * 4;+ RC_BIT(p + 1, b0);+ RC_BIT(p + 2 + b0, b1);+ img[y * 32 + x] = (uint8_t)(b0 << 1 | b1);+ }+ for (int i = 0; i < 128; i++)+ out[t * 128 + i] = (uint8_t)(img[4 * i] | img[4 * i + 1] << 2 | img[4 * i + 2] << 4 | img[4 * i + 3] << 6);+ } else {+ for (int y = 0; y < 16; y++)+ for (int x = 0; x < 16; x++) {+ int l = tc_left(img, x, y, 16), u = tc_up(img, x, y, l, 16), bit, node = 1;+ uint16_t *p = tcp + (l * 16 + u) * 16;+ RC_BIT(p + node, bit);+ node = node * 2 + bit;+ RC_BIT(p + node, bit);+ node = node * 2 + bit;+ RC_BIT(p + node, bit);+ node = node * 2 + bit;+ RC_BIT(p + node, bit);+ node = node * 2 + bit;+ img[y * 16 + x] = (uint8_t)(node - 16);+ }+ for (int i = 0; i < 128; i++) out[t * 128 + i] = (uint8_t)(img[2 * i] | img[2 * i + 1] << 4);+ }+ }+}+static bool inited;+uint32_t g_tex_decodes, g_tex_misses, g_tex_calls;+bool g_tex_overload;++static const uint8_t *sec_tex, *sec_tmap, *sec_bidx, *sec_blk;+const TexRec *tex_rec(uint16_t t) {+ if (!sec_tex) sec_tex = section(SEC_TEX) + 4;+ return (const TexRec *)(sec_tex + sizeof(TexRec) * t);+}++static const uint8_t *row_base(const TexRec *r, int ty) { return sec_tmap + r->map_off + ty * (2 + (r->tw + 3) / 4); }+const uint8_t *tex_row_codes(uint16_t t, int ty) {+ if (!sec_tmap) sec_tmap = section(SEC_TMAP);+ return row_base(tex_rec(t), ty) + 2;+}++static int code_at(const uint8_t *codes, int tx) { return codes[tx >> 2] >> ((tx & 3) * 2) & 3; }++/* how many of a code byte's 4 tiles are kept */+static uint8_t kept4[256];+static void init_kept4(void) {+ for (int i = 0; i < 256; i++) kept4[i] = (uint8_t)(((i & 3) != 0) + ((i >> 2 & 3) != 0) + ((i >> 4 & 3) != 0) + ((i >> 6 & 3) != 0));+}++/* the tile's number among the texture's kept tiles */+static int tile_rank(const TexRec *r, int tx, int ty) {+ const uint8_t *b = row_base(r, ty), *c = b + 2;+ int n = rd16(b), i = 0;+ for (; i + 4 <= tx; i += 4) n += kept4[c[i >> 2]];+ for (; i < tx; i++) n += code_at(c, i) != 0;+ return n;+}+static int tex_tiles(const TexRec *r) {+ const uint8_t *b = row_base(r, r->th - 1), *c = b + 2;+ int n = rd16(b);+ for (int i = 0; i < r->tw; i++) n += code_at(c, i) != 0;+ return n;+}++static void init(void) {+ init_kept4();+ sec_tex = section(SEC_TEX) + 4, sec_tmap = section(SEC_TMAP), sec_bidx = section(SEC_BIDX), sec_blk = section(SEC_BLK);+ for (int i = 0; i < NHASH; i++) head[i] = NO;+ for (int i = 0; i < NSLOTS; i++) slot_key[i] = 0xFFFFFFFF, slot_next[i] = NO, slot_frame[i] = 0;+ inited = true;+}++static unsigned hash(uint32_t k) { return (k * 2654435761u) >> 23 & (NHASH - 1); }++static int find(uint32_t key) {+ for (int s = head[hash(key)]; s != NO; s = slot_next[s])+ if (slot_key[s] == key) return s;+ return -1;+}++static void unlink_slot(int s) {+ if (slot_key[s] == 0xFFFFFFFF) return;+ uint16_t *p = &head[hash(slot_key[s])];+ while (*p != NO && *p != s) p = &slot_next[*p];+ if (*p == s) *p = slot_next[s];+ slot_key[s] = 0xFFFFFFFF;+}++/* a slot to reuse: one unused for a while, else one not drawn this frame, else any */+static int victim(void) {+ int last = -1;+ for (int n = 0; n < NSLOTS; n++) {+ int s = hand;+ hand = (uint16_t)((hand + 1) % NSLOTS);+ uint16_t age = (uint16_t)(frame - slot_frame[s]);+ if (age > 1) return s;+ if (age == 1 && last < 0) last = s;+ }+ if (last >= 0) return last;+ g_tex_overload = true;+ int s = hand; /* the view needs more tiles than the cache holds */+ hand = (uint16_t)((hand + 1) % NSLOTS);+ return s;+}++static int insert(uint32_t key, const uint8_t *px, int bytes) {+ int s = victim();+ unlink_slot(s);+ slot_key[s] = key;+ unsigned h = hash(key);+ slot_next[s] = head[h];+ head[h] = (uint16_t)s;+ memcpy(slot_px[s], px, (size_t)bytes);+ return s;+}++/* a slot not drawn this frame or the last one, for the rest of a decoded block (-1: none, keep what is used) */+static int stale_slot(void) {+ for (int n = 0; n < 64; n++) {+ int s = hand;+ hand = (uint16_t)((hand + 1) % NSLOTS);+ if ((uint16_t)(frame - slot_frame[s]) > 1) return s;+ }+ return -1;+}++const uint8_t *tex_slot_px(int s) { return slot_px[s]; }+++const uint8_t *tex_tile(uint16_t t, int tx, int ty) {+ int s = tex_slot(t, tx, ty);+ return s < 0 ? NULL : slot_px[s];+}++int tex_slot(uint16_t t, int tx, int ty) {+ if (!inited) init();+ g_tex_calls++;+ const TexRec *r = tex_rec(t);+ if ((unsigned)tx >= r->tw || (unsigned)ty >= r->th) return -1;+ if (!code_at(row_base(r, ty) + 2, tx)) return -1;+ int rank = tile_rank(r, tx, ty);+ uint32_t key = (uint32_t)t << 16 | (uint32_t)rank;+ int s = find(key);+ if (s >= 0) {+ slot_frame[s] = frame;+ return s;+ }+ g_tex_misses++;+ /* decode the block */+ int bytes = 128;+ int blk = rank / BLOCK_TILES, first = blk * BLOCK_TILES;+ int ntiles = tex_tiles(r) - first;+ if (ntiles > BLOCK_TILES) ntiles = BLOCK_TILES;+ const uint8_t *bidx = sec_bidx + 4 * (r->blk_first + blk);+ decode_block(sec_blk + rd32(bidx), ntiles, r->fmt == FMT_ALPHA2, block_buf);+ g_tex_decodes++;+ int want = insert((uint32_t)t << 16 | (uint32_t)rank, block_buf + (rank - first) * bytes, bytes);+ slot_frame[want] = frame;+ /* the block's other tiles, where they push out nothing in use */+ for (int i = 0; i < ntiles; i++) {+ uint32_t k = (uint32_t)t << 16 | (uint32_t)(first + i);+ if (first + i == rank || find(k) >= 0) continue;+ int ns = stale_slot();+ if (ns < 0) break;+ unlink_slot(ns);+ slot_key[ns] = k;+ unsigned hh = hash(k);+ slot_next[ns] = head[hh];+ head[hh] = (uint16_t)ns;+ memcpy(slot_px[ns], block_buf + i * bytes, (size_t)bytes);+ slot_frame[ns] = (uint16_t)(frame - 2); /* not drawn yet: the first to go */+ }+ return want;+}++uint32_t g_tex_used; /* tiles drawn last frame */+void tex_frame(void) {+ if (!inited) init();+ g_tex_overload = false;+ g_tex_used = 0;+ for (int i = 0; i < NSLOTS; i++) g_tex_used += slot_frame[i] == frame;+ frame++;+ if (!frame) frame = 1;+}++#ifdef HOST+#include <stdio.h>+void tex_dump_used(const char *path) {+ FILE *f = fopen(path, "w");+ for (int i = 0; i < NSLOTS; i++)+ if (slot_frame[i] == frame && slot_key[i] != 0xFFFFFFFF) fprintf(f, "%u\n", slot_key[i] >> 16);+ fclose(f);+}+#endif+diff --git a/games/hollowknight/src/tilecode.h b/games/hollowknight/src/tilecode.hnew file mode 100644index 00000000..13c1eb9c--- /dev/null+++ b/games/hollowknight/src/tilecode.h@@ -0,0 +1,30 @@+/* The scenery tiles' coding: each texel coded in binary steps with the texel to its left and the one above as+ * context, by a range coder. Probabilities start from tables trained on all tiles and adapt quickly within a block.+ * Shared by the game (decoding) and tools/tilecode.c (training, encoding). */+#pragma once+#include <stdint.h>++/* tiles are 16 texels high, 16 wide (4 bits) or 32 (2 bits) */+#define TC_TILE 16+#define TC_PROB_BITS 12+#define TC_LIM 4 /* the slowest adaptation (shift) */+#define TC_N0 1 /* how sure the trained probabilities are at first */+/* 4-bit tiles: 256 contexts x 16 nodes (1..15 used); 2-bit tiles: 16 contexts x 4 nodes (1..3 used) */+#define TC_CTX4 256+#define TC_CTX2 16++/* a probability: 12 bits (of a 0) and a 4-bit count of updates */+static inline uint16_t tc_pack(int p, int n) { return (uint16_t)(p << 4 | n); }++static inline int tc_left(const uint8_t *img, int x, int y, int w) {+ return x ? img[y * w + x - 1] : (y ? img[(y - 1) * w] : 0);+}+static inline int tc_up(const uint8_t *img, int x, int y, int left, int w) { return y ? img[(y - 1) * w + x] : left; }++static inline void tc_update(uint16_t *pr, int bit) {+ int p = *pr >> 4, n = *pr & 15, sh = n + 1 < TC_LIM ? n + 1 : TC_LIM;+ if (!bit) p += (4096 - p) >> sh;+ else p -= p >> sh;+ if (n < 15) n++;+ *pr = tc_pack(p, n);+}diff --git a/games/hollowknight/tests/play.c b/games/hollowknight/tests/play.cnew file mode 100644index 00000000..8584b08d--- /dev/null+++ b/games/hollowknight/tests/play.c@@ -0,0 +1,142 @@+/* Host runner: draws rooms and plays the game with scripted keys, saving screenshots.+ * play DATA.bin --room NAME --cam X,Y --shot PATH */+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <time.h>+#include "../src/game.h"++extern uint32_t host_keys, host_time;+void host_shot(const char *path);++int main(int argc, char **argv) {+ if (argc < 2) return 1;+ FILE *f = fopen(argv[1], "rb");+ if (!f) return 1;+ fseek(f, 0, SEEK_END);+ long n = ftell(f);+ fseek(f, 0, SEEK_SET);+ uint8_t *data = malloc((size_t)n);+ if (fread(data, 1, (size_t)n, f) != (size_t)n) return 1;+ fclose(f);+ hk_bin = data;+ const char *room = "Tutorial_01", *shot = NULL;+ float cx = 40, cy = 14;+ int repeat = 1, pan = 0, sweep = 0;+ float step = 2;+ const char *items_out = NULL, *play = NULL, *shots = NULL;+ float px = 20, py = 20;+ int shot_every = 0, trace = 0;+ float dx = 0.15f;+ for (int i = 2; i < argc; i++) {+ if (!strcmp(argv[i], "--room")) room = argv[++i];+ else if (!strcmp(argv[i], "--cam")) sscanf(argv[++i], "%f,%f", &cx, &cy);+ else if (!strcmp(argv[i], "--shot")) shot = argv[++i];+ else if (!strcmp(argv[i], "--repeat")) repeat = atoi(argv[++i]);+ else if (!strcmp(argv[i], "--pan")) pan = atoi(argv[++i]);+ else if (!strcmp(argv[i], "--items")) items_out = argv[++i];+ else if (!strcmp(argv[i], "--dx")) dx = (float)atof(argv[++i]);+ else if (!strcmp(argv[i], "--sweep2d")) sweep = 2, step = (float)atof(argv[++i]);+ else if (!strcmp(argv[i], "--play")) play = argv[++i];+ else if (!strcmp(argv[i], "--at")) sscanf(argv[++i], "%f,%f", &px, &py);+ else if (!strcmp(argv[i], "--shots")) shots = argv[++i], shot_every = atoi(argv[++i]);+ else if (!strcmp(argv[i], "--trace")) trace = 1;+ }+ int id = -1;+ for (int i = 0; i < NUM_ROOMS; i++)+ if (!strcmp(room_name(i), room)) id = i;+ if (id < 0 || !room_load(id)) {+ fprintf(stderr, "no room %s\n", room);+ return 1;+ }+ g_cam_x = cx, g_cam_y = cy;+ if (play) {+ /* the game with scripted keys: "KEYS*TICKS,..." (L R U D J jump A attack S dash F focus/cast, _ none) */+ game_new();+ g_pd.can_dash = true;+ game_enter(id, px, py, true);+ int tick = 0;+ for (const char *p = play; *p;) {+ uint32_t keys = 0;+ for (; *p && *p != '*'; p++)+ keys |= *p == 'L' ? K_LEFT : *p == 'R' ? K_RIGHT : *p == 'U' ? K_UP : *p == 'D' ? K_DOWN : *p == 'J' ? K_JUMP+ : *p == 'A' ? K_ATTACK : *p == 'S' ? K_DASH : *p == 'F' ? K_FOCUS | K_SPELL : 0;+ int n = *p == '*' ? atoi(++p) : 1;+ while (*p && *p != ',') p++;+ if (*p == ',') p++;+ for (int i = 0; i < n; i++, tick++) {+ game_tick(keys);+ if (trace)+ printf("%4d keys %02x pos %.3f,%.3f v %.3f,%.3f state %d ground %d jump %d fall %d clip %d frame %d cam %.2f,%.2f\n", tick,+ keys, g_hero.body.x, g_hero.body.y, g_hero.body.vx, g_hero.body.vy, g_hero.state, g_hero.cs.on_ground,+ g_hero.cs.jumping, g_hero.cs.falling, g_hero.anim.clip, g_hero.anim.frame, g_cam_x, g_cam_y);+ if (shots && shot_every && tick % shot_every == 0) {+ char path[256];+ snprintf(path, sizeof path, "%s/%05d.ppm", shots, tick);+ game_draw();+ host_shot(path);+ }+ }+ }+ if (shot) game_draw(), host_shot(shot);+ printf("end: pos %.3f,%.3f state %d\n", g_hero.body.x, g_hero.body.y, g_hero.state);+ return 0;+ }+ if (sweep == 2) {+ /* every camera position on a grid, drawn twice (the second frame's tiles are the view's): the most tiles a view+ * uses, and where */+ extern uint32_t g_tex_used;+ const RoomHdr *h = g_room.h;+ float x0 = 14.6f, x1 = h->w - 14.6f, y0 = 8.3f, y1 = h->h - 8.3f;+ if (x1 < x0) x1 = x0;+ if (y1 < y0) y1 = y0;+ uint32_t worst = 0, maxitems = 0, maxfront = 0;+ float wx = 0, wy = 0;+ for (float y = y0; y <= y1 + 0.01f; y += step)+ for (float x = x0; x <= x1 + 0.01f; x += step) {+ g_cam_x = x, g_cam_y = y;+ gfx_frame();+ gfx_frame();+ tex_frame();+ if (g_tex_used > worst) worst = g_tex_used, wx = x, wy = y;+ if (g_gfx_items > maxitems) maxitems = g_gfx_items;+ { extern uint32_t g_gfx_dropped; if (g_gfx_dropped > maxfront) maxfront = g_gfx_dropped; }+ }+ extern uint32_t g_peak_pals, g_peak_arena, g_peak_soft;+ printf("%s %u %.1f %.1f items %u dropped %u pals %u arena %u soft %u\n", room, worst, wx, wy, maxitems, maxfront, g_peak_pals,+ g_peak_arena, g_peak_soft);+ return 0;+ }+ if (pan) {+ extern uint32_t g_tex_used;+ uint32_t d0 = g_tex_decodes, maxd = 0, maxp = 0, maxu = 0, sumu = 0;+ for (int fr = 0; fr < pan; fr++) {+ uint32_t a = g_tex_decodes;+ gfx_frame();+ if (fr > 2 && g_tex_decodes - a > maxd) maxd = g_tex_decodes - a;+ if (g_gfx_pixels > maxp) maxp = g_gfx_pixels;+ if (fr > 0) { sumu += g_tex_used; if (g_tex_used > maxu) maxu = g_tex_used; }+ g_cam_x += dx;+ }+ extern uint32_t g_soft_misses;+ printf("%s pan %d frames: %.1f decodes/frame (max %u), max pixels %u, tiles used avg %u max %u, soft misses %.1f/frame\n", room, pan,+ (g_tex_decodes - d0) / (double)pan, maxd, maxp, sumu / (pan - 1), maxu, g_soft_misses / (double)pan);+ return 0;+ }+#ifdef HOST+ { extern uint32_t g_kind_px[6]; gfx_frame(); memset(g_kind_px, 0, sizeof g_kind_px); gfx_frame();+ printf("run pixels: solid %u axis %u turned %u soft %u bilinear %u (soft mono turned %u)\n", g_kind_px[0], g_kind_px[1], g_kind_px[2], g_kind_px[3], g_kind_px[4], g_kind_px[5]); }+#endif+ clock_t t0 = clock();+ for (int r = 0; r < repeat; r++) gfx_frame();+ double ms = (double)(clock() - t0) * 1000.0 / CLOCKS_PER_SEC / repeat;+ extern uint32_t g_tex_calls;+ printf("%s %.1f,%.1f: %u items, %u pixels, %u decodes, %u misses, %u tile lookups, %.2f ms/frame\n", room, cx, cy, g_gfx_items,+ g_gfx_pixels, g_tex_decodes, g_tex_misses, g_tex_calls / repeat, ms);+ if (shot) host_shot(shot);+ if (getenv("TEXUSED")) {+ void tex_dump_used(const char *);+ tex_dump_used(getenv("TEXUSED"));+ }+ return 0;+}diff --git a/games/hollowknight/tools/actors.py b/games/hollowknight/tools/actors.pynew file mode 100644index 00000000..b524d46a--- /dev/null+++ b/games/hollowknight/tools/actors.py@@ -0,0 +1,60 @@+"""The game's characters and effects (2D Toolkit): their sprite frames at the size they are seen, and their animation+clips. Each sprite frame becomes a texture like the scenery's; pack.py writes the frames' placements (SPR) and the+clips (CLIP)."""+import numpy as np+from PIL import Image+import unity, tk2d, scene, art++# the Knight's clips the game uses (from the Knight's library, resources.assets)+KNIGHT = ("resources.assets", 20600, [+ "Idle", "Idle Hurt", "Idle Wind", "Run", "Run To Idle", "Walk", "Turn", "TurnToIdle", "Airborne", "Fall", "Land",+ "HardLand", "Dash", "Dash To Idle", "Dash Effect", "Slash", "SlashAlt", "UpSlash", "DownSlash", "SlashEffect",+ "SlashEffectAlt", "UpSlashEffect", "DownSlashEffect", "LookUp", "LookUpEnd", "LookUpToIdle", "LookDown",+ "LookDownEnd", "LookDownToIdle", "Recoil", "Stun", "Death", "Death Head Normal", "Spike Death",+ "Spike Death Antic", "Hazard Respawn", "Respawn Wake", "Focus", "Focus Get", "Focus Get Once", "Focus End",+ "Fireball Antic", "Fireball1 Cast", "Sit", "Sit Lean", "Sit Idle", "Sitting Asleep", "Sit Fall Asleep", "Wake",+ "Wake To Sit", "Get Off", "Sit Map Open", "Sit Map Close", "Map Open", "Map Idle", "Map Walk", "Map Turn",+ "Map Away", "Map Update", "Enter", "Exit", "Exit Door To Idle", "TurnToBG", "TurnFromBG", "Roar Lock",+ "Prostrate", "Prostrate Rise", "Wake Up Ground", "Collect Normal 1", "Collect Normal 2", "Collect Normal 3",+ "Collect Magical 1", "Collect Magical 2", "Collect Magical 3", "Collect Magical Fall", "Collect Magical Land",+ "Collect Heart Piece", "Collect Heart Piece End", "Collect StandToIdle", "GetUpToIdle",+])++ACTORS = {"knight": KNIGHT}+# clips drawn bigger than their sprites (the object's scale): their frames are kept that much finer+DRAWN_SCALE = {"SlashEffect": 1.645, "SlashEffectAlt": 1.422, "UpSlashEffect": 1.4, "DownSlashEffect": 1.28}+K0 = scene.FOCAL / (0.004 - scene.CAMZ) # screen pixels a unit, where actors are (z near 0)+++def clip_id(actor, name):+ return ("CLIP_%s_%s" % (actor, name)).upper().replace(" ", "_")+++def build():+ """-> (sprites, clips). sprites: [{key, job, lx, ty, tu, tv}] (texture top-left in local units, units a texel);+ clips: [{id, fps, wrap, loop, frames: [(sprite, trigger)]}]."""+ sprites, index, clips = [], {}, []+ for actor, (path, pid, names) in ACTORS.items():+ lib = tk2d.animation(path, pid)+ byname = {unity.S(c["name"]): c for c in lib["clips"]}+ for name in names:+ c = byname[name]+ frames = []+ for f in c["frames"]:+ cpath, cpid = tk2d.ref_file(path, f["spriteCollection"])+ key = (cpath, cpid, f["spriteId"])+ if key not in index:+ col = tk2d.collection(cpath, cpid)+ img, lx, ty, upp, (wu, hu) = tk2d.sprite_image(cpath, col, f["spriteId"])+ k = K0 * DRAWN_SCALE.get(name, 1.0)+ w = max(1, round(img.width * upp * k))+ h = max(1, round(img.height * upp * k))+ small = img.resize((w, h), Image.BOX)+ arr = np.asarray(small).copy()+ index[key] = len(sprites)+ sprites.append({"key": key, "job": art.ImageJob(arr, "%s/%s" % (actor, name)),+ "lx": lx, "ty": ty, "tu": wu / w, "tv": hu / h})+ frames.append((index[key], bool(f.get("triggerEvent"))))+ clips.append({"id": clip_id(actor, name), "fps": float(c["fps"]), "wrap": int(c["wrapMode"]),+ "loop": int(c.get("loopStart", 0)), "frames": frames})+ return sprites, clipsdiff --git a/games/hollowknight/tools/art.py b/games/hollowknight/tools/art.pynew file mode 100644index 00000000..5704426f--- /dev/null+++ b/games/hollowknight/tools/art.py@@ -0,0 +1,370 @@+"""Scenery textures for the calculator: each sprite at the size it is seen (a smaller copy for far instances, a+blurred half-size copy behind the background blur plane), 16 colors with alpha (or alpha alone for sprites only+ever drawn black), cut in 16x16 tiles (32x16 for alpha alone); only tiles that can ever be seen are kept, in blocks of up to 16 tiles+compressed with LZMA."""+import math, lzma, struct, os+import numpy as np+from PIL import Image, ImageFilter+import unity, scene, visible++TILE = 16+WIDE = 32 # alpha-only tiles are 32 texels wide (2 bits each: 128 bytes too)+BLOCK_TILES = int(os.environ.get("HK_BLOCK_TILES", "16"))+LEVEL_RATIO = 0.6 # an instance this much smaller than its texture gets a smaller copy+BLUR_SIGMA = 1.2 # background blur, calculator pixels (LightBlurredBackground)+BLUR_SCALE = float(os.environ.get("HK_BLUR_SCALE", "0.25")) # texels a screen pixel behind the blur plane+FG_SCALE = float(os.environ.get("HK_FG_SCALE", "0.6")) # ... in front of the gameplay plane (z < FG_Z)+FG_Z = -2.5+BLUR_PRE = False # (the game blurs the background as a whole: the calculator does too)+LZMA_FILTERS = [{"id": lzma.FILTER_LZMA1, "lc": 0, "lp": 0, "pb": 0, "dict_size": 1 << 12, "preset": 9 | lzma.PRESET_EXTREME}]++FMT_PAL4 = 0 # 4 bits per texel, 15 colors + transparent+FMT_ALPHA2 = 1 # 2 bits per texel: alpha only (sprites always drawn black)+FMT_SOFT = 2 # smooth (glows, fog, soft masks): a few RGBA texels, drawn interpolated+FMT_SOFTA = 3 # the same, all one color: a few alpha texels and the color+SOFT_MAX = 2304 # texels+SOFT_ERR = 14 # the largest error (99th percentile, 0..255) a smaller copy may have+SOFT_RGBA_MAX = 400 # texels at most (4 bytes each once graded)+SOFT_MONO_MAX = 1600 # (1 byte each)+++def lzma_raw(b):+ return lzma.compress(b, format=lzma.FORMAT_RAW, filters=LZMA_FILTERS)+++class Variant:+ """A texture: one sprite at one scale, maybe blurred, maybe alpha only."""+ def __init__(self, sprite, scale, blur, alpha_only):+ self.sprite, self.scale, self.blur, self.alpha_only = sprite, scale, blur, alpha_only+ self.insts = []+ self.cells = set() # visible 8-pixel cells of the sprite+ self.all_cells = False # (scripted instances: everything)+++def gaussian(arr, sigma):+ """Separable gaussian blur of a float array (H x W x C)."""+ r = int(math.ceil(sigma * 3))+ k = np.exp(-0.5 * (np.arange(-r, r + 1) / sigma) ** 2)+ k /= k.sum()+ out = arr+ for axis in (0, 1):+ pad = [(0, 0)] * arr.ndim+ pad[axis] = (r, r)+ p = np.pad(out, pad, mode="constant")+ acc = np.zeros_like(out)+ for i, kv in enumerate(k):+ sl = [slice(None)] * arr.ndim+ sl[axis] = slice(i, i + out.shape[axis])+ acc += kv * p[tuple(sl)]+ out = acc+ return out+++def kmeans_palette(px, k, iters=10, seed=0):+ """px: N x 4 float features. Returns centers (k x 4) and labels."""+ rng = np.random.default_rng(seed)+ n = len(px)+ samp = px[rng.choice(n, min(n, 20000), replace=False)] if n > 20000 else px+ uniq = np.unique(samp, axis=0)+ if len(uniq) <= k:+ c = uniq.astype(np.float32)+ else:+ # k-means++ init+ c = [samp[rng.integers(len(samp))]]+ d2 = ((samp - c[0]) ** 2).sum(1)+ for _ in range(1, k):+ p = d2 / d2.sum() if d2.sum() > 0 else None+ c.append(samp[rng.choice(len(samp), p=p)])+ d2 = np.minimum(d2, ((samp - c[-1]) ** 2).sum(1))+ c = np.array(c, np.float32)+ for _ in range(iters):+ lab = ((samp[:, None, :] - c[None]) ** 2).sum(-1).argmin(1)+ for j in range(len(c)):+ sel = samp[lab == j]+ if len(sel):+ c[j] = sel.mean(0)+ labels = np.empty(n, np.int32)+ for i in range(0, n, 65536):+ labels[i:i + 65536] = ((px[i:i + 65536, None, :] - c[None]) ** 2).sum(-1).argmin(1)+ return c, labels+++def quantize(a):+ """RGBA uint8 image -> (indices: 0 transparent, 1..15), palette 15 x RGBA (straight alpha)."""+ alpha = a[..., 3].astype(np.float32)+ mask = alpha >= 8+ idx = np.zeros(alpha.shape, np.uint8)+ pal = np.zeros((15, 4), np.uint8)+ if not mask.any():+ return idx, pal+ p = a[mask].astype(np.float32)+ al = p[:, 3:4] / 255.0+ feat = np.concatenate([p[:, :3] * al, p[:, 3:4] * 1.5], 1)+ c, lab = kmeans_palette(feat, 15)+ ca = np.clip(c[:, 3] / 1.5, 1, 255)+ ca[ca >= 250] = 255 # (nearly opaque colors are opaque: whole tiles of them hide what is behind)+ rgb = np.clip(c[:, :3] / (ca[:, None] / 255.0), 0, 255)+ cols = np.concatenate([rgb, ca[:, None]], 1)+ # palette sorted by brightness (helps compression)+ order = np.argsort(cols[:, :3].sum(1) * cols[:, 3])+ inv = np.empty_like(order)+ inv[order] = np.arange(len(order))+ pal[:len(order)] = np.round(cols[order]).astype(np.uint8)+ idx[mask] = (inv[lab] + 1).astype(np.uint8)+ return idx, pal+++_black = {}+++def black_sprite(s):+ """A sprite drawn black whatever its tint (masks, silhouettes): its alpha is all there is."""+ if s.key not in _black:+ a = np.asarray(unity.sprite_image(s))+ m = a[..., 3] > 8+ _black[s.key] = bool(m.any()) and int(a[m][:, :3].max()) <= 12+ return _black[s.key]+++FIT = {} # room -> texture scale factor (fit.py: so that every view's tiles fit the calculator's cache)+++def build_variants(rooms, vis_of):+ """Assign every instance a texture variant. vis_of(room) -> (weights, cells)."""+ variants = {}+ per_room = {}+ for r in rooms:+ inst = scene.instances(r)+ st = scene.settings(unity.scene(r))+ w, cells = vis_of(r)+ bz = st["blur_z"] if st["blur_z"] is not None else 1e9+ keep = []+ for it in inst:+ if it.solid:+ keep.append(it)+ continue+ if not it.dynamic and w[it.id] < 0.5:+ continue # never seen+ sc = scene.display_scale(it)+ if sc <= 0:+ continue+ it.blur = it.z > bz and not it.dynamic+ it.alpha_only = it.color[:3] == (0, 0, 0) or black_sprite(it.sprite)+ it.want = min(1.0, sc) * (BLUR_SCALE if it.blur else FG_SCALE if it.z < FG_Z else 1.0)+ if not it.blur:+ it.want *= FIT.get(r, 1.0)+ it.cells = None if it.dynamic else cells.get(it.id)+ keep.append(it)+ per_room[r] = (keep, st)+ for it in keep:+ if it.solid:+ continue+ key = (it.sprite.key, it.blur, it.alpha_only)+ variants.setdefault(key, []).append(it)+ # scale levels per sprite: the largest wanted size, then a smaller copy for instances much smaller than that+ out = []+ for key, its in variants.items():+ its.sort(key=lambda i: -i.want)+ groups = []+ for it in its:+ if groups and it.want >= groups[-1][0] * LEVEL_RATIO:+ groups[-1][1].append(it)+ else:+ groups.append((it.want, [it]))+ for scale, g in groups:+ v = Variant(g[0].sprite, scale, key[1], key[2])+ for it in g:+ v.insts.append(it)+ it.variant = v+ if it.cells is None or v.blur:+ v.all_cells = True # (scripted, or blurred: its soft edges show what is near the parts seen)+ else:+ v.cells.update(it.cells.tolist())+ out.append(v)+ return out, per_room+++class Job:+ """What a worker needs to make a variant's texture (picklable)."""+ def __init__(self, v):+ self.key, self.scale, self.blur, self.alpha_only = v.sprite.key, v.scale, v.blur, v.alpha_only+ self.all_cells = v.all_cells+ self.cells = sorted(v.cells)+ self.magnified = min(scene.display_scale(i) for i in v.insts) >= 1.5+++_SRC_HASH = None+++def encode_job(job):+ """encode_variant, remembered in cache/tex (by the job and this file)."""+ import hashlib, pickle+ global _SRC_HASH+ if _SRC_HASH is None:+ _SRC_HASH = hashlib.sha1(open(__file__, "rb").read()).hexdigest()+ if isinstance(job, ImageJob):+ key = hashlib.sha1(_SRC_HASH.encode() + job.arr.tobytes() + repr(job.arr.shape).encode()).hexdigest()+ else:+ key = hashlib.sha1(repr((_SRC_HASH, job.key, job.scale, job.blur, job.alpha_only, job.all_cells, job.cells,+ job.magnified)).encode()).hexdigest()+ path = os.path.join(unity.CACHE, "tex", key + ".pkl")+ if os.path.exists(path):+ with open(path, "rb") as f:+ return pickle.load(f)+ if not isinstance(job, ImageJob):+ job.sprite = unity.sprite_by_key(job.key)+ t = encode_variant(job)+ os.makedirs(os.path.dirname(path), exist_ok=True)+ tmp = "%s.%d.tmp" % (path, os.getpid())+ with open(tmp, "wb") as f:+ pickle.dump(t, f)+ os.replace(tmp, path)+ return t+++def render_variant(v):+ """The variant's texels as RGBA (resized, blurred) and its visible-tile mask."""+ s = v.sprite+ img = unity.sprite_image(s)+ w = max(1, round(s.w * v.scale))+ h = max(1, round(s.h * v.scale))+ if v.blur and BLUR_PRE:+ # blur at the screen scale, then down+ w2, h2 = max(1, round(s.w * v.scale / BLUR_SCALE)), max(1, round(s.h * v.scale / BLUR_SCALE))+ big = img.resize((w2, h2), Image.BOX)+ pad = int(BLUR_SIGMA * 3) + 1+ canvas = Image.new("RGBA", (w2 + 2 * pad, h2 + 2 * pad))+ canvas.paste(big, (pad, pad))+ prem = np.asarray(canvas, np.float32)+ prem[..., :3] *= prem[..., 3:4] / 255.0+ arr = gaussian(prem, BLUR_SIGMA)[pad:pad + h2, pad:pad + w2]+ a = np.maximum(arr[..., 3:4], 1e-3)+ arr[..., :3] = arr[..., :3] / (a / 255.0)+ img2 = Image.fromarray(np.clip(arr, 0, 255).astype(np.uint8), "RGBA")+ im = img2.resize((w, h), Image.BOX)+ else:+ im = img.resize((w, h), Image.BOX) if (w, h) != img.size else img+ arr = np.asarray(im).copy()+ TW = WIDE if v.alpha_only else TILE+ tw, th = (w + TW - 1) // TW, (h + TILE - 1) // TILE+ if v.all_cells:+ tmask = np.ones((th, tw), bool)+ else:+ # visible cells (8 sprite pixels), grown by one, in texels+ tmask = np.zeros((th, tw), bool)+ k = v.scale * visible.CELL+ for c in v.cells:+ cu, cv = c % 4096, c // 4096+ x0, x1 = (cu - 1) * k, (cu + 2) * k+ y0, y1 = (cv - 1) * k, (cv + 2) * k+ tx0, tx1 = max(0, int(x0 // TW)), min(tw - 1, int((x1 - 1e-6) // TW))+ ty0, ty1 = max(0, int(y0 // TILE)), min(th - 1, int((y1 - 1e-6) // TILE))+ tmask[ty0:ty1 + 1, tx0:tx1 + 1] = True+ return arr, tmask+++class Texture:+ pass+++def soft_factor(arr, magnified):+ """How much smaller a smooth texture can be stored (1: not smooth)."""+ h, w = arr.shape[:2]+ a = arr.astype(np.float32)+ a[..., :3] *= a[..., 3:4] / 255+ best = 1+ for f in (2, 4, 8, 16):+ sw, sh = round(w / f), round(h / f)+ if sw < 3 or sh < 3:+ break+ small = Image.fromarray(np.clip(a, 0, 255).astype(np.uint8)).resize((sw, sh), Image.BOX)+ back = np.asarray(small.resize((w, h), Image.BILINEAR), np.float32)+ err = np.percentile(np.abs(back - a), 99)+ if err <= SOFT_ERR or (magnified and f == 2 and err <= 2 * SOFT_ERR):+ best = f+ else:+ break+ if best > 1 and round(w / best) * round(h / best) > SOFT_MAX:+ return 1+ return best+++class ImageJob:+ """A texture made from an image already at its size (actors' sprite frames): all of it kept."""+ def __init__(self, arr, name):+ self.arr, self.name = arr, name+ self.alpha_only = False+ self.blur = False+ self.magnified = False+++def encode_variant(v):+ """-> Texture with header fields and its tiles (or its few texels, if smooth)."""+ if isinstance(v, ImageJob):+ arr = v.arr+ tmask = np.ones(((arr.shape[0] + TILE - 1) // TILE, (arr.shape[1] + TILE - 1) // TILE), bool)+ else:+ arr, tmask = render_variant(v)+ h, w = arr.shape[:2]+ if True:+ f = soft_factor(arr, getattr(v, "magnified", False))+ if f > 1:+ t = Texture()+ t.base = 0+ mono = False+ m = arr[..., 3] > 16+ if m.any():+ rgb = arr[m][:, :3].astype(np.float32)+ base = np.median(rgb, 0)+ if np.percentile(np.abs(rgb - base).max(1), 95) <= 24:+ mono = True+ b = np.clip(np.round(base), 0, 255).astype(int)+ t.base = int(b[0]) | int(b[1]) << 8 | int(b[2]) << 16+ # the game keeps a frame's smooth textures together (gfx.c: SOFT_POOL): big ones get coarser+ cap = SOFT_MONO_MAX if mono else SOFT_RGBA_MAX+ while round(w / f) * round(h / f) > cap and f < 64:+ f *= 2+ sw, sh = max(2, round(w / f)), max(2, round(h / f))+ a = arr.astype(np.float32)+ a[..., :3] *= a[..., 3:4] / 255+ small = np.asarray(Image.fromarray(np.clip(a, 0, 255).astype(np.uint8)).resize((sw, sh), Image.BOX))+ t.w, t.h, t.tw, t.th = sw, sh, 0, 0+ t.fmt = FMT_SOFTA if mono else FMT_SOFT+ t.soft = small[..., 3].tobytes() if mono else small.tobytes() # (premultiplied RGBA)+ t.pal, t.tiles, t.ntiles, t.bits = None, [], 0, 4+ t.scale_f = f+ return t+ tw, th = tmask.shape[1], tmask.shape[0]+ t = Texture()+ t.w, t.h, t.tw, t.th = w, h, tw, th+ t.fmt = FMT_ALPHA2 if v.alpha_only else FMT_PAL4+ if v.alpha_only:+ idx = np.clip(np.round(arr[..., 3] / 85.0), 0, 3).astype(np.uint8)+ t.pal = None+ else:+ idx, t.pal = quantize(arr)+ TW = WIDE if v.alpha_only else TILE+ pad = np.zeros((th * TILE, tw * TW), np.uint8)+ pad[:h, :w] = idx+ tiles = []+ t.empty = np.zeros((th, tw), bool)+ t.opaque = np.zeros((th, tw), bool)+ opaque_ids = None+ if not v.alpha_only:+ opaque_ids = set(i + 1 for i in range(15) if t.pal[i][3] >= 250)+ for ty in range(th):+ for tx in range(tw):+ blk = pad[ty * TILE:(ty + 1) * TILE, tx * TW:(tx + 1) * TW]+ if not tmask[ty, tx] or not blk.any():+ t.empty[ty, tx] = True+ continue+ full = (tx + 1) * TW <= w and (ty + 1) * TILE <= h+ if v.alpha_only:+ t.opaque[ty, tx] = full and (blk == 3).all()+ else:+ t.opaque[ty, tx] = full and np.isin(blk, list(opaque_ids)).all() if opaque_ids else False+ tiles.append(blk.astype(np.uint8).tobytes())+ t.tiles = tiles+ t.bits = 2 if v.alpha_only else 4+ t.ntiles = len(tiles)+ return tdiff --git a/games/hollowknight/tools/coll.py b/games/hollowknight/tools/coll.pynew file mode 100644index 00000000..c0f80263--- /dev/null+++ b/games/hollowknight/tools/coll.py@@ -0,0 +1,164 @@+"""A room's solid ground for the Knight: the outlines of its terrain colliders (edges, polygons, boxes, circles) as+line segments in world units, joined where they run on in a line, and a grid of the segments near each cell."""+import math+import numpy as np+import unity++SOLID_LAYERS = {8, 25} # Terrain, Soft Terrain (the Knight collides with these; its rays see Terrain only)+CELL = 8.0 # grid cell (units)+UNIT = 128 # segment ends are stored in 1/128 unit+# collider flags (src/hk.h: CF_*)+CF_TERRAIN, CF_STEEP, CF_NONSLIDER, CF_NOHARDLAND, CF_ROOF, CF_SOLID = 1, 2, 4, 8, 16, 32+++def _world(o, pts, off):+ m = np.array(o["m3"]).reshape(3, 3)+ p = np.array(o["pos"])+ return [tuple((m @ np.array([x + off[0], y + off[1], 0.0]) + p)[:2]) for x, y in pts]+++def _merge(chain, closed):+ """Drops the points of a polyline that lie on the line through their neighbours."""+ pts = list(chain)+ changed = True+ while changed and len(pts) > 2:+ changed = False+ out = []+ n = len(pts)+ for i, q in enumerate(pts):+ if not closed and (i == 0 or i == n - 1):+ out.append(q)+ continue+ a, b = pts[i - 1], pts[(i + 1) % n]+ cross = (q[0] - a[0]) * (b[1] - a[1]) - (q[1] - a[1]) * (b[0] - a[0])+ if abs(cross) < 1e-4 and (q[0] - a[0]) * (b[0] - q[0]) + (q[1] - a[1]) * (b[1] - q[1]) >= 0:+ changed = True+ continue+ out.append(q)+ pts = out+ return pts+++def _tilemap_solid(edges, w, h):+ """The tiles inside the tilemap's outlines (each tile's center: odd crossings of the vertical edges to its right)."""+ tw, th = int(math.ceil(w)), int(math.ceil(h))+ solid = np.zeros((th, tw), bool)+ vert = [(x0, min(y0, y1), max(y0, y1)) for x0, y0, x1, y1 in edges if abs(x0 - x1) < 1e-4]+ for ty in range(th):+ cy = ty + 0.5+ xs = sorted(x for x, a, b in vert if a < cy < b)+ for i in range(0, len(xs) - 1, 2):+ a, b = int(round(xs[i])), int(round(xs[i + 1]))+ solid[ty, max(0, a):max(0, min(tw, b))] = True+ if len(xs) % 2:+ print("coll: tilemap outline open at row", ty)+ return solid+++def tile_faces(solid):+ """The unit edges between solid and open tiles (outside the map is open)."""+ th, tw = solid.shape+ f = set()+ def s(x, y):+ return 0 <= x < tw and 0 <= y < th and solid[y, x]+ for y in range(th):+ for x in range(tw):+ if not solid[y, x]:+ continue+ if not s(x - 1, y): f.add(("v", x, y))+ if not s(x + 1, y): f.add(("v", x + 1, y))+ if not s(x, y - 1): f.add(("h", x, y))+ if not s(x, y + 1): f.add(("h", x, y + 1))+ return f+++def _unit_edges(edges):+ out = set()+ for x0, y0, x1, y1 in edges:+ if abs(x0 - x1) < 1e-4:+ for y in range(int(round(min(y0, y1))), int(round(max(y0, y1)))):+ out.add(("v", int(round(x0)), y))+ else:+ for x in range(int(round(min(x0, x1))), int(round(max(x0, x1)))):+ out.add(("h", x, int(round(y0))))+ return out+++def room(d, w, h):+ """-> (solid tiles of the tilemap, segments [(x0, y0, x1, y1, collider)], colliders [flags]); collider 0 is the+ tilemap's."""+ segs, cols = [], [CF_SOLID | CF_TERRAIN]+ tm_edges = []+ for o in d["objects"]:+ if not o["active"] or o["layer"] not in SOLID_LAYERS:+ continue+ if "TileMap Render Data/" in o["path"]:+ for c in o["c"]:+ v = c.get("v")+ if c["type"] == "EdgeCollider2D" and v and not v.get("m_IsTrigger") and v.get("m_Enabled", 1):+ off = (v["m_Offset"]["x"], v["m_Offset"]["y"])+ pts = _world(o, [(p["x"], p["y"]) for p in v["m_Points"]], off)+ tm_edges += [(a[0], a[1], b[0], b[1]) for a, b in zip(pts, pts[1:]) if a != b]+ continue+ scripts = {c.get("class") for c in o["c"] if c["type"] == "MonoBehaviour"}+ for c in o["c"]:+ t, v = c["type"], c.get("v")+ if t not in ("EdgeCollider2D", "PolygonCollider2D", "BoxCollider2D", "CircleCollider2D"):+ continue+ if v is None:+ print("coll: %s: %s not read" % (o["path"], t))+ continue+ if v.get("m_IsTrigger") or not v.get("m_Enabled", 1):+ continue+ off = (v["m_Offset"]["x"], v["m_Offset"]["y"])+ chains = []+ if t == "EdgeCollider2D":+ chains.append((_world(o, [(p["x"], p["y"]) for p in v["m_Points"]], off), False))+ elif t == "PolygonCollider2D":+ paths = v["m_Points"]["m_Paths"] if isinstance(v["m_Points"], dict) else v["m_Points"]+ for path in paths:+ chains.append((_world(o, [(p["x"], p["y"]) for p in path], off), True))+ elif t == "BoxCollider2D":+ sx, sy = v["m_Size"]["x"] / 2, v["m_Size"]["y"] / 2+ chains.append((_world(o, [(-sx, -sy), (sx, -sy), (sx, sy), (-sx, sy)], off), True))+ else:+ r = v["m_Radius"]+ chains.append((_world(o, [(r * math.cos(a * math.pi / 4), r * math.sin(a * math.pi / 4)) for a in range(8)], off), True))+ flags = CF_SOLID | (CF_TERRAIN if o["layer"] == 8 else 0)+ if "SteepSlope" in scripts:+ flags |= CF_STEEP+ if "NonSlider" in scripts:+ flags |= CF_NONSLIDER+ if "NoHardLanding" in scripts:+ flags |= CF_NOHARDLAND+ if "Roof" in scripts:+ flags |= CF_ROOF+ ci = len(cols)+ cols.append(flags)+ for pts, closed in chains:+ pts = _merge(pts, closed)+ n = len(pts)+ for i in range(n if closed else n - 1):+ a, b = pts[i], pts[(i + 1) % n]+ if a != b:+ segs.append((a[0], a[1], b[0], b[1], ci))+ solid = _tilemap_solid(tm_edges, w, h)+ want, got = _unit_edges(tm_edges), tile_faces(solid)+ if want != got:+ print("coll: tilemap faces differ: %d missing, %d extra" % (len(want - got), len(got - want)))+ return solid, segs, cols+++def grid(segs, w, h):+ """Cells (CELL units, the room from 0, 0, a cell of margin around) -> segment indices whose box touches them."""+ gw, gh = int(math.ceil(w / CELL)) + 2, int(math.ceil(h / CELL)) + 2+ cells = [[] for _ in range(gw * gh)]+ for i, (x0, y0, x1, y1, _) in enumerate(segs):+ cx0 = max(0, min(gw - 1, int(math.floor(min(x0, x1) / CELL)) + 1))+ cx1 = max(0, min(gw - 1, int(math.floor(max(x0, x1) / CELL)) + 1))+ cy0 = max(0, min(gh - 1, int(math.floor(min(y0, y1) / CELL)) + 1))+ cy1 = max(0, min(gh - 1, int(math.floor(max(y0, y1) / CELL)) + 1))+ for cy in range(cy0, cy1 + 1):+ for cx in range(cx0, cx1 + 1):+ cells[cy * gw + cx].append(i)+ return gw, gh, cellsdiff --git a/games/hollowknight/tools/ents.py b/games/hollowknight/tools/ents.pynew file mode 100644index 00000000..621e2018--- /dev/null+++ b/games/hollowknight/tools/ents.py@@ -0,0 +1,116 @@+"""A room's game objects that are not scenery: camera lock areas, gates to other rooms, respawn points and the triggers+that set them. Each becomes a record (src/game.h: Ent) with its trigger box (world units) and its own values; names go to+a shared string table."""+import struct+import numpy as np++# record types (src/game.h: ENT_*)+ENT_CAMLOCK, ENT_GATE, ENT_HAZARD_MARKER, ENT_RESPAWN, ENT_HAZARD_TRIGGER = 1, 2, 3, 4, 5+# flags+CL_PREVENT_UP, CL_PREVENT_DOWN, CL_MAX_PRIORITY = 1, 2, 4+G_DOOR, G_ENTER_RIGHT, G_ENTER_LEFT, G_DONT_WALK_OUT, G_NON_HAZARD = 1, 2, 4, 8, 16+FACING_RIGHT = 1+REC = "<BBHffffffffHH" # type, flags, a, box (x0, y0, x1, y1), p0..p3, s0, s1+++class Strings:+ def __init__(self):+ self.list, self.index = [], {}++ def id(self, s):+ if s not in self.index:+ self.index[s] = len(self.list)+ self.list.append(s)+ return self.index[s]++ def blob(self):+ offs, body = [], bytearray()+ for s in self.list:+ offs.append(len(body))+ body += s.encode() + b"\0"+ return struct.pack("<I", len(self.list)) + b"".join(struct.pack("<I", o) for o in offs) + bytes(body)+++def _box(o, c):+ """A collider's world bounds (box colliders; others by their points)."""+ v = c["v"]+ m = np.array(o["m3"]).reshape(3, 3)+ p = np.array(o["pos"])+ off = (v["m_Offset"]["x"], v["m_Offset"]["y"])+ if c["type"] == "BoxCollider2D":+ sx, sy = v["m_Size"]["x"] / 2, v["m_Size"]["y"] / 2+ pts = [(-sx, -sy), (sx, -sy), (sx, sy), (-sx, sy)]+ elif c["type"] == "PolygonCollider2D":+ paths = v["m_Points"]["m_Paths"] if isinstance(v["m_Points"], dict) else v["m_Points"]+ pts = [(q["x"], q["y"]) for path in paths for q in path]+ elif c["type"] == "CircleCollider2D":+ r = v["m_Radius"]+ pts = [(-r, -r), (r, r)]+ else:+ return None+ w = [m @ np.array([x + off[0], y + off[1], 0.0]) + p for x, y in pts]+ xs, ys = [q[0] for q in w], [q[1] for q in w]+ return (min(xs), min(ys), max(xs), max(ys))+++def _trigger(o):+ for c in o["c"]:+ if c["type"] in ("BoxCollider2D", "PolygonCollider2D", "CircleCollider2D") and c.get("v") and c["v"].get("m_IsTrigger"):+ return _box(o, c)+ return None+++def room(d, rooms, strings):+ """-> list of packed records."""+ recs = []+ marker_index = {}+ objs = [o for o in d["objects"] if o["active"]]+ # markers first: the triggers refer to them+ for o in objs:+ for c in o["c"]:+ cls, v = c.get("class"), c.get("v") or {}+ if cls == "HazardRespawnMarker":+ marker_index[o["id"]] = len(recs)+ x, y = o["pos"][:2]+ recs.append(struct.pack(REC, ENT_HAZARD_MARKER, FACING_RIGHT if v.get("respawnFacingRight") else 0, 0,+ x, y, x, y, 0, 0, 0, 0, 0, strings.id(o["name"])))+ elif cls == "RespawnMarker":+ x, y = o["pos"][:2]+ recs.append(struct.pack(REC, ENT_RESPAWN, FACING_RIGHT if v.get("respawnFacingRight") else 0, 0,+ x, y, x, y, 0, 0, 0, 0, strings.id(o["name"]), 0))+ for o in objs:+ for c in o["c"]:+ cls, v = c.get("class"), c.get("v") or {}+ if cls == "CameraLockArea":+ box = _trigger(o)+ if box is None:+ continue+ f = (CL_PREVENT_UP if v.get("preventLookUp") else 0) | (CL_PREVENT_DOWN if v.get("preventLookDown") else 0) | \+ (CL_MAX_PRIORITY if v.get("maxPriority") else 0)+ recs.append(struct.pack(REC, ENT_CAMLOCK, f, 0, *box, v["cameraXMin"], v["cameraYMin"], v["cameraXMax"],+ v["cameraYMax"], 0, 0))+ elif cls == "TransitionPoint":+ box = _trigger(o)+ if box is None:+ continue+ f = (G_DOOR if v.get("isADoor") else 0) | (G_ENTER_RIGHT if v.get("alwaysEnterRight") else 0) | \+ (G_ENTER_LEFT if v.get("alwaysEnterLeft") else 0) | (G_DONT_WALK_OUT if v.get("dontWalkOutOfDoor") else 0) | \+ (G_NON_HAZARD if v.get("nonHazardGate") else 0)+ target = v.get("targetScene") or ""+ ti = rooms.index(target) if target in rooms else 0xFFFF+ recs.append(struct.pack(REC, ENT_GATE, f, ti, *box, float(v.get("entryDelay", 0)), 0, 0, 0,+ strings.id(o["name"]), strings.id(v.get("entryPoint") or "")))+ elif cls == "HazardRespawnTrigger":+ box = _trigger(o)+ ref = v.get("respawnMarker")+ mid = ref[1] if isinstance(ref, (list, tuple)) else (ref or {}).get("m_PathID") if isinstance(ref, dict) else None+ # (the marker is a component: find its object)+ target = None+ for oo in objs:+ for cc in oo["c"]:+ if cc.get("pid") == mid:+ target = oo["id"]+ if box is None or target not in marker_index:+ continue+ recs.append(struct.pack(REC, ENT_HAZARD_TRIGGER, 0, marker_index[target], *box, 0, 0, 0, 0, 0, 0))+ return recsdiff --git a/games/hollowknight/tools/fit.json b/games/hollowknight/tools/fit.jsonnew file mode 100644index 00000000..c38b6f97--- /dev/null+++ b/games/hollowknight/tools/fit.json@@ -0,0 +1,28 @@+{+ "Crossroads_01": 0.63,+ "Crossroads_03": 0.869,+ "Crossroads_04": 0.796,+ "Crossroads_06": 0.904,+ "Crossroads_08": 0.902,+ "Crossroads_11_alt": 0.865,+ "Crossroads_16": 0.863,+ "Crossroads_19": 0.775,+ "Crossroads_21": 0.902,+ "Crossroads_30": 0.86,+ "Crossroads_33": 0.829,+ "Crossroads_38": 0.815,+ "Crossroads_47": 0.973,+ "Crossroads_ShamanTemple": 0.841,+ "Fungus1_01": 0.828,+ "Fungus1_02": 0.649,+ "Fungus1_03": 0.867,+ "Fungus1_04": 0.808,+ "Fungus1_16_alt": 0.711,+ "Fungus1_17": 0.726,+ "Fungus1_21": 0.747,+ "Fungus1_22": 0.845,+ "Fungus1_31": 0.669,+ "Fungus1_32": 0.951,+ "Room_Town_Stag_Station": 0.809,+ "Tutorial_01": 0.859+}\ No newline at end of filediff --git a/games/hollowknight/tools/fit.py b/games/hollowknight/tools/fit.pynew file mode 100644index 00000000..2e9c571d--- /dev/null+++ b/games/hollowknight/tools/fit.py@@ -0,0 +1,37 @@+"""Fits each room's texture sizes to the calculator's tile cache: packs, then draws every camera position of every+room on the computer (tests/play.c --sweep2d), and makes the textures of rooms whose busiest view needs more tiles than+BUDGET smaller, until all fit. Writes fit.json (read by pack.py)."""+import os, sys, json, subprocess, math, multiprocessing as mp+HERE = os.path.dirname(os.path.abspath(__file__))+GAME = os.path.join(HERE, "..")+BUDGET = int(os.environ.get("HK_TILE_BUDGET", "520")) # tex.c NSLOTS, less what the Knight, enemies and effects need+ROOMS = [l.strip() for l in open(os.path.join(HERE, "rooms.txt")) if l.strip() and not l.startswith("#")]+EXE = os.path.join(GAME, "build", "sweep")+++def build():+ src = ["src/res.c", "src/tex.c", "src/room.c", "src/gfx.c", "src/lzma/LzmaDec.c", "src/plat_host.c", "tests/play.c"]+ subprocess.check_call(["cc", "-std=gnu11", "-O2", "-Isrc", "-DHOST", "-DNSLOTS=4000"] + src + ["-lm", "-o", EXE], cwd=GAME)+++def sweep(room):+ out = subprocess.run([EXE, "src/data.bin", "--room", room, "--sweep2d", "2"], cwd=GAME, capture_output=True, text=True).stdout.split()+ return room, (int(out[1]) if len(out) >= 2 else 0)+++if __name__ == "__main__":+ fp = os.path.join(HERE, "fit.json")+ fit = json.load(open(fp)) if os.path.exists(fp) else {}+ build()+ for it in range(6):+ subprocess.check_call([sys.executable, os.path.join(HERE, "pack.py")], stdout=subprocess.DEVNULL)+ with mp.Pool(4) as p:+ res = dict(p.map(sweep, ROOMS))+ over = {r: n for r, n in res.items() if n > BUDGET}+ print("round", it, "over:", over, flush=True)+ if not over:+ break+ for r, n in over.items():+ fit[r] = round(fit.get(r, 1.0) * math.sqrt(BUDGET / n) * 0.98, 3)+ json.dump(fit, open(fp, "w"), indent=1, sort_keys=True)+ print("fit", fit)diff --git a/games/hollowknight/tools/fsm.py b/games/hollowknight/tools/fsm.pynew file mode 100644index 00000000..74eb5c86--- /dev/null+++ b/games/hollowknight/tools/fsm.py@@ -0,0 +1,282 @@+"""PlayMaker FSM decoder: turns a parsed PlayMakerFSM MonoBehaviour (tt.parse) into readable states, actions with+their parameters, transitions and variables. Reference tool, follows ActionData.cs (PlayMaker.dll)."""+import struct++PT = ["Integer", "Boolean", "Float", "String", "Color", "ObjectReference", "LayerMask", "Enum", "Vector2", "Vector3",+ "Vector4", "Rect", "Array", "Character", "AnimationCurve", "FsmFloat", "FsmInt", "FsmBool", "FsmString",+ "FsmGameObject", "FsmOwnerDefault", "FunctionCall", "FsmAnimationCurve", "FsmEvent", "FsmObject", "FsmColor",+ "Unsupported", "GameObject", "FsmVector3", "LayoutOption", "FsmRect", "FsmEventTarget", "FsmMaterial",+ "FsmTexture", "Quaternion", "FsmQuaternion", "FsmProperty", "FsmVector2", "FsmTemplateControl", "FsmVar",+ "CustomClass", "FsmArray", "FsmEnum"]+++def S(x):+ if isinstance(x, (bytes, bytearray)):+ return x.decode("utf8", "replace")+ return x+++def _f(b, p): return struct.unpack_from("<f", b, p)[0]+def _i(b, p): return struct.unpack_from("<i", b, p)[0]+++def rnd(v):+ if isinstance(v, float):+ r = round(v, 4)+ return int(r) if r == int(r) and abs(r) < 1e9 else r+ if isinstance(v, (list, tuple)):+ return type(v)(rnd(x) for x in v)+ return v+++def named(d, val):+ """FsmFloat/FsmInt/...: a variable reference ('$name') or a value."""+ if d is None:+ return None+ n = S(d.get("name", b""))+ if n:+ return "$" + n+ if d.get("useVariable") and not n:+ return None # 'None' variable: unset+ return rnd(val(d))+++def vec(d, keys):+ return tuple(d[k] for k in keys)+++def ref(r):+ if not r:+ return None+ if isinstance(r, dict) and "m_PathID" in r:+ return ("ref", r["m_FileID"], r["m_PathID"]) if r["m_PathID"] else None+ return r+++def decode_params(ad, data_version, names_of=None):+ """Returns per-action list of (paramName, value)."""+ b = bytes(ad["byteData"])+ types = ad["paramDataType"]+ pnames = [S(x) for x in ad["paramName"]]+ pos = ad["paramDataPos"]+ size = ad["paramByteDataSize"]+ out = []++ def one(i):+ t = PT[types[i]]+ p = pos[i]+ n = size[i]+ if t == "Integer" or t == "LayerMask" or t == "Enum":+ return _i(b, p)+ if t == "Float":+ return rnd(_f(b, p))+ if t == "Boolean":+ return bool(b[p])+ if t == "Character":+ return chr(b[p])+ if t == "String":+ if data_version > 1 and ad["stringParams"]:+ return S(ad["stringParams"][p])+ return b[p:p + n].decode("utf8", "replace")+ if t == "Color":+ return rnd(struct.unpack_from("<4f", b, p))+ if t == "Vector2":+ return rnd(struct.unpack_from("<2f", b, p))+ if t in ("Vector3",):+ return rnd(struct.unpack_from("<3f", b, p))+ if t in ("Vector4", "Rect", "Quaternion"):+ return rnd(struct.unpack_from("<4f", b, p))+ if t == "FsmEvent":+ if data_version > 1 and ad["stringParams"]:+ s = S(ad["stringParams"][p])+ else:+ s = b[p:p + n].decode("utf8", "replace")+ return ("event", s) if s else None+ if t == "FsmFloat":+ if data_version > 1:+ return named(ad["fsmFloatParams"][p], lambda d: d["value"])+ nm = b[p + 5:p + n].decode()+ return "$" + nm if nm else (None if b[p + 4] else rnd(_f(b, p)))+ if t == "FsmInt":+ if data_version > 1:+ return named(ad["fsmIntParams"][p], lambda d: d["value"])+ nm = b[p + 5:p + n].decode()+ return "$" + nm if nm else (None if b[p + 4] else _i(b, p))+ if t == "FsmBool":+ if data_version > 1:+ return named(ad["fsmBoolParams"][p], lambda d: bool(d["value"]))+ nm = b[p + 2:p + n].decode()+ return "$" + nm if nm else (None if b[p + 1] else bool(b[p]))+ if t == "FsmVector2":+ if data_version > 1:+ return named(ad["fsmVector2Params"][p], lambda d: vec(d["value"], "xy"))+ nm = b[p + 9:p + n].decode()+ return "$" + nm if nm else (None if b[p + 8] else rnd(struct.unpack_from("<2f", b, p)))+ if t == "FsmVector3":+ if data_version > 1:+ return named(ad["fsmVector3Params"][p], lambda d: vec(d["value"], "xyz"))+ nm = b[p + 13:p + n].decode()+ return "$" + nm if nm else (None if b[p + 12] else rnd(struct.unpack_from("<3f", b, p)))+ if t == "FsmColor":+ if data_version > 1:+ return named(ad["fsmColorParams"][p], lambda d: vec(d["value"], "rgba"))+ nm = b[p + 17:p + n].decode()+ return "$" + nm if nm else (None if b[p + 16] else rnd(struct.unpack_from("<4f", b, p)))+ if t == "FsmRect":+ if data_version > 1:+ return named(ad["fsmRectParams"][p], lambda d: vec(d["value"], ("x", "y", "width", "height")))+ return rnd(struct.unpack_from("<4f", b, p))+ if t == "FsmQuaternion":+ if data_version > 1:+ return named(ad["fsmQuaternionParams"][p], lambda d: vec(d["value"], "xyzw"))+ return rnd(struct.unpack_from("<4f", b, p))+ if t == "FsmString":+ return named(ad["fsmStringParams"][p], lambda d: S(d["value"]))+ if t == "FsmGameObject":+ d = ad["fsmGameObjectParams"][p]+ return named(d, lambda d: ref(d["value"]))+ if t == "FsmOwnerDefault":+ d = ad["fsmOwnerDefaultParams"][p]+ if d["ownerOption"] == 0:+ return "Owner"+ go = d["gameObject"]+ return named(go, lambda d: ref(d["value"]))+ if t in ("FsmObject", "FsmMaterial", "FsmTexture"):+ d = ad["fsmObjectParams"][p]+ return named(d, lambda d: ref(d["value"]))+ if t == "ObjectReference":+ return ref(ad["unityObjectParams"][p])+ if t == "FsmVar":+ d = ad["fsmVarParams"][p]+ vn = S(d.get("variableName", b""))+ if vn:+ return "$" + vn+ return {"type": d.get("type"), "f": d.get("floatValue"), "i": d.get("intValue"),+ "b": d.get("boolValue"), "s": S(d.get("stringValue", b""))}+ if t == "FsmArray":+ d = ad["fsmArrayParams"][p]+ n2 = S(d.get("name", b""))+ if n2:+ return "$" + n2+ return {k: (rnd(v) if not isinstance(v, (bytes, bytearray)) else S(v)) for k, v in d.items()+ if k in ("type", "floatValues", "intValues", "boolValues", "stringValues")+ and v}+ if t == "FsmEnum":+ d = ad["fsmEnumParams"][p]+ return named(d, lambda d: d["intValue"])+ if t == "FsmEventTarget":+ d = ad["fsmEventTargetParams"][p]+ tgt = {0: "Self", 1: "GameObject", 2: "GameObjectFSM", 3: "FSMComponent", 4: "BroadcastAll",+ 5: "HostFSM", 6: "SubFSMs"}.get(d["target"], d["target"])+ if tgt == "Self":+ return "Self"+ go = d["gameObject"]+ fsmname = d["fsmName"]+ return {"target": tgt, "go": "Owner" if go["ownerOption"] == 0 else named(go["gameObject"], lambda d: ref(d["value"])),+ "fsm": named(fsmname, lambda d: S(d["value"]))}+ if t == "FsmProperty":+ d = ad["fsmPropertyParams"][p]+ return {"prop": S(d.get("PropertyName", b"")), "target": named(d.get("TargetObject"), lambda d: ref(d["value"]))}+ if t == "FunctionCall":+ d = ad["functionCallParams"][p]+ return {"fn": S(d.get("FunctionName", b"")), "type": S(d.get("ParameterType", b""))}+ if t in ("AnimationCurve", "FsmAnimationCurve"):+ d = ad["animationCurveParams"][p]+ c = d.get("curve", d)+ keys = c.get("m_Curve", [])+ return ("curve", [rnd((k["time"], k["value"])) for k in keys])+ if t == "FsmTemplateControl":+ return "template"+ if t == "LayoutOption":+ return "layout"+ if t == "GameObject":+ return ref(ad["unityObjectParams"][p]) if ad["unityObjectParams"] else None+ return "?" + t++ # arrays and custom classes: their elements follow as separate params+ i = 0+ flat = []+ while i < len(types):+ t = PT[types[i]]+ if t == "Array":+ p = pos[i]+ cnt = ad["arrayParamSizes"][p]+ el = []+ for k in range(cnt):+ el.append(one(i + 1 + k))+ flat.append((pnames[i], el))+ i += 1 + cnt+ continue+ if t == "CustomClass":+ p = pos[i]+ cnt = ad["customTypeSizes"][p]+ fields = {}+ for k in range(cnt):+ fields[pnames[i + 1 + k]] = one(i + 1 + k)+ flat.append((pnames[i], fields))+ i += 1 + cnt+ continue+ flat.append((pnames[i], one(i)))+ i += 1+ return flat+++def split_actions(ad, flat_count_fn=None):+ return ad["actionStartIndex"]+++def decode(v):+ """v: tt.parse() of a PlayMakerFSM. Returns a dict."""+ f = v["fsm"]+ dv = f.get("dataVersion", 2)+ states = []+ for st in f["states"]:+ ad = st["actionData"]+ names = [S(x) for x in ad["actionNames"]]+ starts = list(ad["actionStartIndex"])+ enabled = bytes(ad["actionEnabled"])+ # decode params per action: params between start[i] and start[i+1] (raw param indices)+ types = ad["paramDataType"]+ acts = []+ for ai, nm in enumerate(names):+ a = starts[ai]+ e = starts[ai + 1] if ai + 1 < len(starts) else len(types)+ sub = {k: ad[k] for k in ad}+ for key in ("paramDataType", "paramName", "paramDataPos", "paramByteDataSize"):+ sub[key] = ad[key][a:e]+ params = decode_params(sub, dv)+ acts.append({"name": nm.split(".")[-1], "enabled": bool(enabled[ai]) if ai < len(enabled) else True,+ "params": params})+ trans = [(S(t["fsmEvent"]["name"]), S(t["toState"])) for t in st["transitions"]]+ states.append({"name": S(st["name"]), "actions": acts, "transitions": trans})+ gtrans = [(S(t["fsmEvent"]["name"]), S(t["toState"])) for t in f.get("globalTransitions", [])]+ vars_ = {}+ V = f.get("variables", {})+ for key, fn in (("floatVariables", lambda d: rnd(d["value"])), ("intVariables", lambda d: d["value"]),+ ("boolVariables", lambda d: bool(d["value"])), ("stringVariables", lambda d: S(d["value"])),+ ("vector2Variables", lambda d: rnd(vec(d["value"], "xy"))),+ ("vector3Variables", lambda d: rnd(vec(d["value"], "xyz"))),+ ("colorVariables", lambda d: rnd(vec(d["value"], "rgba"))),+ ("rectVariables", lambda d: rnd(vec(d["value"], ("x", "y", "width", "height")))),+ ("gameObjectVariables", lambda d: ref(d["value"])),+ ("objectVariables", lambda d: ref(d["value"]))):+ for d in V.get(key, []):+ vars_[S(d["name"])] = (key.replace("Variables", ""), fn(d))+ return {"name": S(f["name"]), "start": S(f["startState"]), "states": states, "global": gtrans, "vars": vars_,+ "events": [S(e["name"]) for e in f.get("events", [])]}+++def fmt(d, go=""):+ lines = ["FSM %r on %r start=%s" % (d["name"], go, d["start"])]+ if d["vars"]:+ lines.append(" vars: " + ", ".join("%s:%s=%s" % (k, t, v) for k, (t, v) in d["vars"].items()))+ if d["global"]:+ lines.append(" global: " + ", ".join("%s->%s" % t for t in d["global"]))+ for st in d["states"]:+ lines.append(" [%s]" % st["name"])+ for a in st["actions"]:+ ps = ", ".join("%s=%s" % (k, v) for k, v in a["params"] if v not in (None, "", [], {}) and k not in ("everyFrame",) or (k == "everyFrame" and v))+ lines.append(" %s%s(%s)" % ("" if a["enabled"] else "#", a["name"], ps))+ for e, t in st["transitions"]:+ lines.append(" %s -> %s" % (e, t))+ return "\n".join(lines)diff --git a/games/hollowknight/tools/pack.py b/games/hollowknight/tools/pack.pynew file mode 100644index 00000000..afb75d53--- /dev/null+++ b/games/hollowknight/tools/pack.py@@ -0,0 +1,387 @@+"""Hollow Knight for the NumWorks calculator: makes src/data.bin (and src/data.h) from the game's files.+HOLLOWKNIGHT=<the game's Data folder> python3 pack.py"""+import os, sys, struct, math, lzma, time, multiprocessing as mp+import numpy as np+HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import unity, scene, visible, art, actors, coll, ents++SRC = os.path.join(HERE, "..", "src")+ROOMS = [l.strip() for l in open(os.path.join(HERE, "rooms.txt")) if l.strip() and not l.startswith("#")]+STRINGS = ents.Strings()++SECTIONS = ["TEX", "TMAP", "PAL", "BIDX", "BLK", "ROOMS", "RBLOB", "PRIOR", "SOFT", "SPR", "CLIP", "STR"]+BLENDS = {"alpha": 0, "add": 1, "screen": 2, "linearlight": 3, "overlay": 4, "multiply": 5}+F_LIT, F_ROT, F_SOLID, F_DYN, F_GRASS = 8, 16, 32, 64, 128++TC_N0 = 1 # (src/tilecode.h)+LZ = [{"id": lzma.FILTER_LZMA1, "lc": 0, "lp": 0, "pb": 0, "dict_size": 1 << 16, "preset": 9 | lzma.PRESET_EXTREME}]+++def lz(b):+ return lzma.compress(b, format=lzma.FORMAT_RAW, filters=LZ)+++def f16(x):+ return int(np.array(x, np.float16).view(np.uint16))+++def i16(x):+ return max(-32768, min(32767, int(round(x))))+++def f16s(x):+ """A half float's bits as a signed 16-bit value (for struct 'h')."""+ v = f16(x)+ return v - 65536 if v >= 32768 else v+++class Blob:+ def __init__(self):+ self.b = bytearray()++ def align(self, n=4):+ while len(self.b) % n:+ self.b.append(0)++ def add(self, data):+ self.align()+ o = len(self.b)+ self.b += data+ return o+++SECTOR = 16.0 # sectors along the room's long camera axis (units)+GLOBAL_SPAN = 40.0 # instances seen over a longer stretch of camera positions are always kept+MARGIN = 2.0+++def inst_record(it, tex_id, tints):+ """An instance: where, its texture, how it is drawn."""+ q = it.quad # bl, br, tr, tl (world)+ tl, tr, bl = q[3], q[2], q[0]+ flags = BLENDS.get(it.blend, 0)+ if it.lit:+ flags |= F_LIT+ if it.dynamic:+ flags |= F_DYN+ if it.grass:+ flags |= F_GRASS+ color = it.color+ if it.solid and it.sprite.name == "black_solid":+ color = (0, 0, 0, color[3])+ col = tuple(int(round(min(1, max(0, c)) * 255)) for c in color)+ if col not in tints:+ tints.append(col)+ tint = min(255, tints.index(col))+ rot = 0+ if it.solid:+ flags |= F_SOLID+ tex = 0xFFFF+ ax, ay = min(p[0] for p in q), max(p[1] for p in q)+ a, b = max(p[0] for p in q) - ax, -(ay - min(p[1] for p in q))+ else:+ t = tex_id[id(it.variant)]+ tex, tw, th = t+ eu = (tr - tl) / tw+ ev = (bl - tl) / th+ ax, ay = tl[0], tl[1]+ a = math.hypot(eu[0], eu[1])+ ang = math.atan2(eu[1], eu[0])+ # flips: keep the angle small, put the sign in a+ if abs(ang) > math.pi / 2:+ ang = ang - math.pi if ang > 0 else ang + math.pi+ a = -a+ c, s_ = math.cos(ang), math.sin(ang)+ b = ev[0] * -s_ + ev[1] * c # along (-sin, cos)+ rot = int(round(ang / (2 * math.pi) * 65536))+ if rot:+ flags |= F_ROT+ return (ax, ay, it.z, tex, tint, flags, a, b, rot)+++def uvar(u):+ out = bytearray()+ while u >= 128:+ out.append(u & 127 | 128)+ u >>= 7+ out.append(u)+ return out+++def svar(v):+ return uvar(v << 1 if v >= 0 else ((-v) << 1) - 1)+++def sector_stream(recs):+ """A sector's instances in draw order, each relative to the one before (read in place by room.c):+ flags, aux (1 tint, 2 same texture, 4 same z, 8|16 b: 0 its own, 1 = a, 2 = -a, 3 same as before, 32 same a,+ 64 next rank, 128 another sorting layer or order), [rank step - 2], [layer, order], [texture step], [tint],+ x step, y step, [z step], [a], [b], [angle]."""+ out = bytearray()+ pr, pt, px, py, pz, pa, pb, pg = -1, 0, 0, 0, 0, 0, 0, None+ for rank, (ax, ay, z, tex, tint, flags, a, b, rot), group in recs:+ X, Y, Z, A, B = i16(ax * 64), i16(ay * 64), i16(z * 128), f16s(a) & 0xFFFF, f16s(b) & 0xFFFF+ aux = 0+ if tint:+ aux |= 1+ if tex == pt:+ aux |= 2+ if Z == pz:+ aux |= 4+ bm = 1 if B == A else 2 if B == A ^ 0x8000 else 3 if B == pb else 0+ aux |= bm << 3+ if A == pa:+ aux |= 32+ if rank == pr + 1:+ aux |= 64+ if group != pg:+ aux |= 128+ out += bytes([flags, aux])+ if not aux & 64:+ out += uvar(rank - pr - 2)+ if aux & 128:+ out += bytes([group[0]]) + svar(group[1])+ if not aux & 2:+ out += svar(tex - pt)+ if tint:+ out.append(tint)+ out += svar(X - px) + svar(Y - py)+ if not aux & 4:+ out += svar(Z - pz)+ if not aux & 32:+ out += struct.pack("<H", A)+ if bm == 0:+ out += struct.pack("<H", B)+ if flags & F_ROT:+ out += struct.pack("<h", rot)+ pr, pt, px, py, pz, pa, pb, pg = rank, tex, X, Y, Z, A, B, group+ return bytes(out)+++def room_blobs(name, keep, st, tex_id):+ """A room: its header (kept in RAM) and its instances in sectors (decoded when the camera is near)."""+ w, h = st["size"] if st["size"] else (40, 24)+ cx0, cx1, cy0, cy1 = scene.camera_range(st) if st["size"] else (20, 20, 12, 12)+ axis = 0 if (cx1 - cx0) >= (cy1 - cy0) else 1+ lo, hi = (cx0, cx1) if axis == 0 else (cy0, cy1)+ HWU, HHU = scene.VIEW_W / 2 / scene.FOCAL, scene.VIEW_H / 2 / scene.FOCAL+ tints = [(255, 255, 255, 255)]+ secs = {}+ for rank, it in enumerate(keep):+ rec = inst_record(it, tex_id, tints)+ q = np.array(it.quad)+ dist = max(0.5, it.z - scene.CAMZ)+ half = (HWU if axis == 0 else HHU) * dist+ p0, p1 = (q[:, 0].min(), q[:, 0].max()) if axis == 0 else (q[:, 1].min(), q[:, 1].max())+ va, vb = max(lo, p0 - half - MARGIN), min(hi, p1 + half + MARGIN)+ if it.dynamic or vb - va > GLOBAL_SPAN or vb < va:+ sec = -1+ else:+ sec = int((va - lo) // SECTOR)+ e = secs.setdefault(sec, [[], 1e9, -1e9])+ e[0].append((rank, rec, (it.layer, it.order)))+ e[1] = min(e[1], va)+ e[2] = max(e[2], vb)+ order = sorted(secs.keys())+ luts, sat = scene.grading_luts(st, 64)+ lut = bytes(int(round(luts[c][i] * 255)) for c in range(3) for i in range(64))+ bz = st["blur_z"] if st["blur_z"] is not None else 1000.0+ blobs = []+ table = bytearray()+ for k in order:+ recs, va, vb = secs[k]+ blobs.append((sector_stream(recs), len(recs)))+ if k < 0:+ va, vb = -1e9, 1e9+ table += struct.pack("<IIHHff", 0, 0, len(recs), 0, va, vb) # (offsets filled in by main)+ HDR = 84 + 192+ solid, segs, cols = coll.room(unity.scene(name), w, h)+ gw, gh, cells = coll.grid(segs, w, h)+ recs = ents.room(unity.scene(name), ROOMS, STRINGS)+ hdr = struct.pack("<4H4f4f4fff6HII", 6, len(order), len(tints), axis, w, h, bz, sat, *st["ambient"], 0.0,+ *st["hero_light"], lo, hi, len(keep), len(segs), len(cols), gw, gh, len(recs), 0, 0) + lut+ assert len(hdr) == HDR, len(hdr)+ body = bytearray(hdr)+ body += b"".join(struct.pack("<4B", *t) for t in tints)+ while len(body) % 4:+ body.append(0)+ o_sec = len(body)+ body += table+ # the ground (read in place): colliders' flags (0: the tilemap's), the tilemap's solid tiles (1 bit each, rows from+ # the bottom), segments (1/128 unit), their colliders, cells' first entries, entries+ cb = bytearray(bytes(cols))+ if len(cb) % 2:+ cb.append(0)+ th, tw = solid.shape+ cb += struct.pack("<HH", tw, th)+ rowb = (tw + 7) // 8+ for y in range(th):+ row = bytearray(rowb)+ for x in range(tw):+ if solid[y, x]:+ row[x >> 3] |= 1 << (x & 7)+ cb += row+ if len(cb) % 2:+ cb.append(0)+ for x0, y0, x1, y1, ci in segs:+ cb += struct.pack("<4h", *(i16(c * coll.UNIT) for c in (x0, y0, x1, y1)))+ cb += bytes(ci for x0, y0, x1, y1, ci in segs)+ if len(cb) % 2:+ cb.append(0)+ first = 0+ for c in cells:+ cb += struct.pack("<H", first)+ first += len(c)+ cb += struct.pack("<H", first)+ for c in cells:+ cb += struct.pack("<%dH" % len(c), *c)+ return body, o_sec, blobs, bytes(cb), b"".join(recs)+++def tilecode(blocks):+ """Trains the tile coder's starting probabilities on every block and encodes them (tools/tilecode.c)."""+ import subprocess, tempfile+ tmp = tempfile.mkdtemp()+ exe = os.path.join(tmp, "tilecode")+ subprocess.check_call(["cc", "-O2", "-o", exe, os.path.join(HERE, "tilecode.c")])+ job = bytearray(struct.pack("<I", len(blocks)))+ for bits, tiles in blocks:+ job += struct.pack("<BBH", bits, 0, len(tiles)) + b"".join(tiles)+ open(os.path.join(tmp, "in.bin"), "wb").write(job)+ subprocess.check_call([exe, "train", os.path.join(tmp, "in.bin"), os.path.join(tmp, "prior.bin")])+ subprocess.check_call([exe, "encode", os.path.join(tmp, "in.bin"), os.path.join(tmp, "prior.bin"), os.path.join(tmp, "out.bin")])+ prior = open(os.path.join(tmp, "prior.bin"), "rb").read()+ out = open(os.path.join(tmp, "out.bin"), "rb").read()+ res, p = [], 0+ for _ in blocks:+ n = struct.unpack_from("<I", out, p)[0]+ res.append(out[p + 4:p + 4 + n])+ p += 4 + n+ return prior, res+++def main():+ t0 = time.time()+ fp = os.path.join(HERE, "fit.json")+ if os.path.exists(fp):+ import json+ art.FIT.update(json.load(open(fp)))+ variants, per_room = art.build_variants(ROOMS, visible.compute)+ print("variants", len(variants), "%.0fs" % (time.time() - t0), flush=True)+ jobs = [art.Job(v) for v in variants]+ sprites, clips = actors.build()+ print("actor frames", len(sprites), "clips", len(clips), "%.0fs" % (time.time() - t0), flush=True)+ jobs += [sp["job"] for sp in sprites]+ with mp.get_context("spawn").Pool(min(4, os.cpu_count() or 1)) as pool:+ texs = pool.map(art.encode_job, jobs, chunksize=4)+ # (the actors' textures come after the scenery's)+ variants = variants + [sp["job"] for sp in sprites]+ print("textures %.0fs" % (time.time() - t0), flush=True)+ blocks = []+ for t in texs:+ t.first_block = len(blocks)+ for i in range(0, t.ntiles, art.BLOCK_TILES):+ blocks.append((t.bits, t.tiles[i:i + art.BLOCK_TILES]))+ prior, coded = tilecode(blocks)+ print("tiles coded %.0fs" % (time.time() - t0), flush=True)+ secs = {k: Blob() for k in SECTIONS}+ # the starting probabilities as the game uses them: each with its count (tilecode.h: tc_pack)+ secs["PRIOR"].b += b"".join(struct.pack("<H", v << 4 | TC_N0) for v in struct.unpack("<%dH" % (len(prior) // 2), prior))+ tex_id = {}+ nblk = 0+ texrec = bytearray()+ for i, (v, t) in enumerate(zip(variants, texs)):+ tex_id[id(v)] = (i, t.w, t.h)+ pal_off = 0xFFFFFFFF+ if t.pal is not None:+ pal_off = secs["PAL"].add(t.pal.tobytes())+ if t.fmt == art.FMT_SOFTA: # (alpha only: read in place)+ pal_off = secs["SOFT"].add(t.soft)+ texrec += struct.pack("<HHBBBBIII", t.w, t.h, 0, 0, t.fmt, 0, pal_off, t.base, 0)+ continue+ if t.fmt == art.FMT_SOFT:+ c = lz(t.soft)+ pal_off = secs["SOFT"].add(struct.pack("<I", len(c)) + c)+ texrec += struct.pack("<HHBBBBIII", t.w, t.h, 0, 0, t.fmt, 0, pal_off, t.base, 0)+ continue+ # tile map: per row, the rank of its first tile, then 2 bits a tile (0 empty, 1 tile, 3 opaque tile)+ m = bytearray()+ rank = 0+ for ty in range(t.th):+ m += struct.pack("<H", rank)+ row = bytearray((t.tw + 3) // 4)+ for tx in range(t.tw):+ code = 0 if t.empty[ty, tx] else (3 if t.opaque[ty, tx] else 1)+ row[tx >> 2] |= code << ((tx & 3) * 2)+ rank += code != 0+ m += row+ map_off = secs["TMAP"].add(bytes(m))+ bidx = secs["BIDX"].b+ first = len(bidx) // 4+ for bl in coded[t.first_block:t.first_block + (t.ntiles + art.BLOCK_TILES - 1) // art.BLOCK_TILES]:+ bidx += struct.pack("<I", len(secs["BLK"].b))+ secs["BLK"].b += bl+ bidx += struct.pack("<I", len(secs["BLK"].b))+ texrec += struct.pack("<HHBBBBIII", t.w, t.h, t.tw, t.th, t.fmt, 1 if v.blur else 0, pal_off, map_off, first)+ secs["TEX"].b += struct.pack("<I", len(variants)) + texrec+ # actors: each sprite frame's texture and where its top-left corner is (local units), units a texel; the clips+ first_actor = len(variants) - len(sprites)+ for i, sp in enumerate(sprites):+ secs["SPR"].b += struct.pack("<HHffff", first_actor + i, 0, sp["lx"], sp["ty"], sp["tu"], sp["tv"])+ secs["CLIP"].b += struct.pack("<I", len(clips))+ frames = []+ for c in clips:+ secs["CLIP"].b += struct.pack("<HHfBBH", len(frames), len(c["frames"]), c["fps"], c["wrap"], c["loop"], 0)+ frames += [sid | (0x8000 if trig else 0) for sid, trig in c["frames"]]+ secs["CLIP"].b += struct.pack("<%dH" % len(frames), *frames)+ with open(os.path.join(unity.CACHE, "texnames.txt"), "w") as f:+ for i, (v, t) in enumerate(zip(variants, texs)):+ name = v.name if isinstance(v, art.ImageJob) else v.sprite.name+ f.write("%d %s %.3f %d %d %dx%d %d\n" % (i, name.replace(" ", "_"), getattr(v, "scale", 1.0), v.blur, v.alpha_only,+ t.w, t.h, t.ntiles))+ rooms = bytearray(struct.pack("<I", len(ROOMS)))+ for r in ROOMS:+ keep, st = per_room[r]+ body, o_sec, blobs, ground, recs = room_blobs(r, keep, st, tex_id)+ struct.pack_into("<I", body, 76, secs["RBLOB"].add(ground))+ struct.pack_into("<I", body, 80, secs["RBLOB"].add(recs))+ packed = 0+ for i, (c, n) in enumerate(blobs):+ off = secs["RBLOB"].add(c)+ struct.pack_into("<II", body, o_sec + 20 * i, off, len(c))+ packed += len(c)+ hc = lz(bytes(body))+ off = secs["RBLOB"].add(hc)+ assert len(r) < 32, r+ rooms += struct.pack("<32sIII", r.encode(), off, len(hc), len(body))+ print("room %-26s %5d instances in %2d sectors, %6d packed" % (r, len(keep), len(blobs), packed + len(hc)), flush=True)+ secs["ROOMS"].b += rooms+ secs["STR"].b += STRINGS.blob()+ # the file: "HKNW", count, then (offset, size) per section+ head = struct.pack("<4sI", b"HKNW", len(SECTIONS))+ pos = len(head) + 8 * len(SECTIONS)+ table = bytearray()+ body = bytearray()+ for k in SECTIONS:+ while (pos + len(body)) % 4:+ body.append(0)+ table += struct.pack("<II", pos + len(body), len(secs[k].b))+ body += secs[k].b+ data = head + table + body+ open(os.path.join(SRC, "data.bin"), "wb").write(data)+ sizes = {k: len(secs[k].b) for k in SECTIONS}+ print("data.bin", len(data), sizes, "%.0fs" % (time.time() - t0))+ with open(os.path.join(SRC, "data.h"), "w") as f:+ f.write("/* made by tools/pack.py */\n#pragma once\n")+ for i, k in enumerate(SECTIONS):+ f.write("#define SEC_%s %d\n" % (k, i))+ f.write("#define NUM_ROOMS %d\n" % len(ROOMS))+ for i, r in enumerate(ROOMS):+ f.write("#define ROOM_%s %d\n" % (r.upper(), i))+ for i, c in enumerate(clips):+ f.write("#define %s %d\n" % (c["id"], i))+++if __name__ == "__main__":+ main()diff --git a/games/hollowknight/tools/ref.py b/games/hollowknight/tools/ref.pynew file mode 100644index 00000000..c4e44025--- /dev/null+++ b/games/hollowknight/tools/ref.py@@ -0,0 +1,77 @@+"""Reference picture of a scene at the calculator's view, at full quality: the game's sprites in draw order with+lighting, blend modes, the background blur and the color grading. For checking the calculator's drawing.+python3 ref.py SCENE CX CY OUT.png [scale]"""+import sys, math+import numpy as np+from PIL import Image+import unity, scene, art+++def layer(it, q, W, H, ambient):+ img = unity.sprite_image(it.sprite)+ w, h = img.size+ tl, tr, bl = np.array(q[3]), np.array(q[2]), np.array(q[0])+ A = np.array([[(tr - tl)[0] / w, (bl - tl)[0] / h, tl[0]], [(tr - tl)[1] / w, (bl - tl)[1] / h, tl[1]], [0, 0, 1]])+ try:+ Ai = np.linalg.inv(A)+ except np.linalg.LinAlgError:+ return None+ xs, ys = [p[0] for p in q], [p[1] for p in q]+ x0, y0 = max(0, int(math.floor(min(xs)))), max(0, int(math.floor(min(ys))))+ x1, y1 = min(W, int(math.ceil(max(xs)))), min(H, int(math.ceil(max(ys))))+ if x1 <= x0 or y1 <= y0:+ return None+ T = Ai @ np.array([[1, 0, x0], [0, 1, y0], [0, 0, 1]])+ out = np.asarray(img.transform((x1 - x0, y1 - y0), Image.AFFINE, tuple(T[:2].flatten()), resample=Image.BILINEAR), np.float32) / 255+ col = np.array(it.color, np.float32)+ if it.solid and it.sprite.name == "black_solid":+ col[:3] = 0+ rgb = out[..., :3] * col[:3]+ if it.lit:+ rgb = rgb * np.array(ambient, np.float32)+ return x0, y0, rgb, out[..., 3] * col[3]+++def composite(buf, x0, y0, rgb, a, blend):+ h, w = a.shape+ d = buf[y0:y0 + h, x0:x0 + w]+ a = a[..., None]+ if blend == "add":+ d[:] = np.minimum(1, d + rgb * a)+ elif blend == "screen":+ d[:] = 1 - (1 - d) * (1 - rgb * a)+ elif blend == "linearlight":+ d[:] = np.clip(d + (2 * rgb - 1) * a, 0, 1)+ else:+ d[:] = d * (1 - a) + rgb * a+++def render(name, cx, cy, scale=1):+ inst = scene.instances(name)+ st = scene.settings(unity.scene(name))+ W, H = scene.VIEW_W * scale, scene.VIEW_H * scale+ bz = st["blur_z"]+ bg = np.zeros((H, W, 3), np.float32)+ front = []+ for it in inst:+ q = [scene.project(p, cx, cy, scale) for p in it.quad]+ if any(p is None for p in q):+ continue+ r = layer(it, q, W, H, st["ambient"])+ if r is None:+ continue+ if bz is not None and it.z > bz and not it.dynamic:+ composite(bg, *r, it.blend)+ else:+ front.append((it, r))+ if bz is not None:+ bg = art.gaussian(bg, art.BLUR_SIGMA * scale)+ for it, r in front:+ composite(bg, *r, it.blend)+ return scene.grade(bg, st)+++if __name__ == "__main__":+ name, cx, cy, out = sys.argv[1], float(sys.argv[2]), float(sys.argv[3]), sys.argv[4]+ scale = int(sys.argv[5]) if len(sys.argv) > 5 else 1+ Image.fromarray((render(name, cx, cy, scale) * 255).astype(np.uint8)).save(out)diff --git a/games/hollowknight/tools/rooms.txt b/games/hollowknight/tools/rooms.txtnew file mode 100644index 00000000..6870a4fd--- /dev/null+++ b/games/hollowknight/tools/rooms.txt@@ -0,0 +1,41 @@+Tutorial_01+Town+Room_shop+Room_mapper+Room_Town_Stag_Station+Crossroads_01+Crossroads_02+Room_temple+Crossroads_07+Crossroads_38+Crossroads_33+Crossroads_06+Crossroads_ShamanTemple+Crossroads_10+Crossroads_10_boss+Crossroads_10_boss_defeated+Crossroads_21+Crossroads_39+Crossroads_14+Crossroads_16+Crossroads_03+Crossroads_47+Crossroads_19+Crossroads_04+Room_ruinhouse+Room_Charm_Shop+Crossroads_08+Crossroads_30+Crossroads_11_alt+Fungus1_01+Fungus1_01b+Fungus1_02+Fungus1_17+Fungus1_03+Fungus1_31+Fungus1_32+Fungus1_21+Fungus1_22+Fungus1_16_alt+Fungus1_04+Fungus1_04_bossdiff --git a/games/hollowknight/tools/scene.py b/games/hollowknight/tools/scene.pynew file mode 100644index 00000000..9952db04--- /dev/null+++ b/games/hollowknight/tools/scene.py@@ -0,0 +1,220 @@+"""A scene's scenery as the game draws it: sprite instances with their world quads, draw order, blend, tint and+lighting; the scene's settings (size, color grading, ambient light, background blur plane); and the camera's view."""+import math, functools+import numpy as np+import unity++# sorting layers in render order (TagManager)+LAYER_ORDER = [0, 3315419377, 1459018367, 4015848369, 2917268371, 1270309357, 3557629463, 3868594333, 3784110789,+ 31172181, 1371964999, 2577183099, 1038907033, 3945752401, 629535577, 957720295]+LAYER_NAMES = ["Default", "Far BG 2", "Far BG 1", "Mid BG", "Immediate BG", "Actors", "Player", "Tiles",+ "MID Dressing", "Immediate FG", "Scene Border", "Far FG", "Vignette", "Over", "HUD", "Inventory"]+++def layer_index(uid):+ uid &= 0xffffffff+ return LAYER_ORDER.index(uid) if uid in LAYER_ORDER else 0+++# the camera (GameCameras: perspective, field of view 24 at 16:9; ForceCameraAspect keeps 16:10 on the calculator)+CAMZ = -38.1+FOV_V = 24.0 * (16 / 9) / 1.6+VIEW_W, VIEW_H = 320, 200+FOCAL = (VIEW_H / 2) / math.tan(math.radians(FOV_V / 2))+PXU = FOCAL / -CAMZ # pixels per unit at z = 0+CAM_XMIN, CAM_YMIN = 14.6, 8.3 # CameraController limits++SOLIDS = ("black_solid", "white_solid")+++def blend_of(shader):+ s = shader.lower()+ if "screen" in s:+ return "screen"+ if "linearlight" in s:+ return "linearlight"+ if "lineardodge" in s or "additive" in s:+ return "add"+ if "overlay" in s:+ return "overlay"+ if "multiply" in s:+ return "multiply"+ return "alpha"+++def dynamic_ids(d):+ """Objects run by scripts (FSMs, breakables, grass...), animated or physical, with everything under them."""+ ob = unity.by_id(d)+ dyn = {}++ def is_dyn(o):+ i = o["id"]+ if i in dyn:+ return dyn[i]+ r = any(c["type"] in ("MonoBehaviour", "Animator", "Rigidbody2D", "Animation") for c in o["c"])+ if not r and o["parent"]:+ r = is_dyn(ob[o["parent"]])+ dyn[i] = r+ return r+ for o in d["objects"]:+ is_dyn(o)+ return dyn+++def settings(d):+ st = {"saturation": 1.0, "curves": None, "ambient": (1.0, 1.0, 1.0), "blur_z": None, "size": None,+ "hero_light": (1, 1, 1, 0.5), "darkness": 0}+ for o in d["objects"]:+ for c in o["c"]:+ cl = c.get("class")+ v = c.get("v") or {}+ if cl == "SceneManager" and o["active"]:+ st["saturation"] = v["saturation"] + (0 if v.get("ignorePlatformSaturationModifiers") else 0.17)+ st["curves"] = [v["redChannel"]["m_Curve"], v["greenChannel"]["m_Curve"], v["blueChannel"]["m_Curve"]]+ dc = v["defaultColor"]+ k = 1 + (v["defaultIntensity"] - 1) * 0.5 # SceneManager.SetLighting (AmbientIntesityMix 0.5)+ st["ambient"] = (dc["r"] * k, dc["g"] * k, dc["b"] * k)+ h = v["heroLightColor"]+ st["hero_light"] = (h["r"], h["g"], h["b"], h["a"])+ st["darkness"] = v.get("darknessLevel", 0)+ st["map_zone"] = v.get("mapZone", 0)+ st["manager"] = v+ elif cl == "BlurPlane" and o["active"]:+ z = o["pos"][2]+ if st["blur_z"] is None or z < st["blur_z"]:+ st["blur_z"] = z+ elif cl == "tk2dTileMap":+ st["size"] = (v["width"], v["height"])+ return st+++def hermite(keys, t):+ """Unity AnimationCurve.Evaluate (hermite between keys, clamped outside)."""+ if not keys:+ return t+ if t <= keys[0]["time"]:+ return keys[0]["value"]+ if t >= keys[-1]["time"]:+ return keys[-1]["value"]+ for a, b in zip(keys, keys[1:]):+ if a["time"] <= t <= b["time"]:+ dt = b["time"] - a["time"]+ if dt <= 0:+ return b["value"]+ u = (t - a["time"]) / dt+ m0, m1 = a["outSlope"] * dt, b["inSlope"] * dt+ if math.isinf(m0) or math.isinf(m1):+ return a["value"]+ u2, u3 = u * u, u * u * u+ return (2 * u3 - 3 * u2 + 1) * a["value"] + (u3 - 2 * u2 + u) * m0 + (-2 * u3 + 3 * u2) * b["value"] + (u3 - u2) * m1+ return t+++def grading_luts(st, n=256):+ """ColorCorrectionCurves: a curve per channel, then saturation."""+ if st["curves"] is None:+ return [np.arange(n) / (n - 1)] * 3, st["saturation"]+ return [np.array([min(1.0, max(0.0, hermite(k, i / (n - 1)))) for i in range(n)]) for k in st["curves"]], st["saturation"]+++def grade(rgb, st):+ luts, sat = grading_luts(st)+ idx = np.clip(np.round(rgb * 255), 0, 255).astype(np.int32)+ out = np.stack([luts[c][idx[..., c]] for c in range(3)], -1)+ lum = (out * np.array([0.2126, 0.7152, 0.0722])).sum(-1, keepdims=True)+ return np.clip(lum + (out - lum) * sat, 0, 1)+++class Inst:+ pass+++def instances(name):+ """The scene's SpriteRenderers, active and enabled, in a fixed draw order (sorting layer, order, depth)."""+ d = unity.scene(name)+ level, exts = d["level"], tuple(d["externals"])+ dyn = dynamic_ids(d)+ out = []+ for o in d["objects"]:+ if not o["active"]:+ continue+ for c in o["c"]:+ if c["type"] != "SpriteRenderer":+ continue+ v = c["v"]+ if not v.get("m_Enabled", 1) or not v.get("m_Sprite"):+ continue+ s = unity.sprite(level, exts, *v["m_Sprite"])+ if s is None:+ continue+ mats = v.get("m_Materials") or []+ mat = unity.material(unity.ref_path(d, mats[0][0]), mats[0][1]) if mats and mats[0] else ("?", "?")+ col = v["m_Color"]+ it = Inst()+ it.obj, it.sprite, it.mat = o, s, mat+ it.pos, it.m3 = o["pos"], o["m3"]+ it.color = (col["r"], col["g"], col["b"], col["a"])+ it.layer = layer_index(v["m_SortingLayerID"])+ it.order = v["m_SortingOrder"]+ it.flip = (v.get("m_FlipX", 0), v.get("m_FlipY", 0))+ it.blend = blend_of(mat[1])+ it.lit = "Lit" in mat[1] or "Grass" in mat[1] or "Diffuse" in mat[0]+ it.grass = "Grass" in mat[1]+ it.draw_mode = v.get("m_DrawMode", 0)+ it.size = (v.get("m_Size", {}).get("x", 0), v.get("m_Size", {}).get("y", 0))+ it.dynamic = dyn[o["id"]]+ it.solid = s.name in SOLIDS+ it.quad = world_quad(it)+ it.center = sum(it.quad) / 4+ it.z = float(it.center[2])+ out.append(it)+ # the game sorts by distance from the camera within a layer and order: far first, a fixed order here+ out.sort(key=lambda i: (i.layer, i.order, -i.z))+ for k, it in enumerate(out):+ it.id = k+ return out+++def local_quad(it):+ s = it.sprite+ w, h = s.w / s.ppu, s.h / s.ppu+ if it.draw_mode and it.size[0]:+ w, h = it.size+ x0, y0 = -s.px * w, -s.py * h+ fx = -1 if it.flip[0] else 1+ fy = -1 if it.flip[1] else 1+ # bottom-left, bottom-right, top-right, top-left+ return [(x0 * fx, y0 * fy), ((x0 + w) * fx, y0 * fy), ((x0 + w) * fx, (y0 + h) * fy), (x0 * fx, (y0 + h) * fy)]+++def world_quad(it):+ m = np.array(it.m3).reshape(3, 3)+ p = np.array(it.pos)+ return [m @ np.array([x, y, 0.0]) + p for x, y in local_quad(it)]+++def project(pt, cx, cy, scale=1):+ dz = pt[2] - CAMZ+ if dz <= 0.05:+ return None+ k = FOCAL * scale / dz+ return (VIEW_W * scale / 2 + (pt[0] - cx) * k, VIEW_H * scale / 2 - (pt[1] - cy) * k)+++def camera_range(st):+ w, h = st["size"]+ return (CAM_XMIN, max(CAM_XMIN, w - CAM_XMIN), CAM_YMIN, max(CAM_YMIN, h - CAM_YMIN))+++def display_scale(it):+ """Screen pixels per sprite pixel (the larger axis) at the instance's depth."""+ m = it.m3+ sx, sy = math.hypot(m[0], m[3]), math.hypot(m[1], m[4])+ dz = it.z - CAMZ+ if dz < 0.5:+ return 0+ s = it.sprite+ if it.draw_mode and it.size[0]:+ sx *= it.size[0] / (s.w / s.ppu)+ sy *= it.size[1] / (s.h / s.ppu)+ return max(sx, sy) * FOCAL / dz / s.ppudiff --git a/games/hollowknight/tools/tilecode.c b/games/hollowknight/tools/tilecode.cnew file mode 100644index 00000000..611e22ab--- /dev/null+++ b/games/hollowknight/tools/tilecode.c@@ -0,0 +1,168 @@+/* Scenery tile coding for pack.py: trains the starting probabilities and encodes blocks of tiles.+ * tilecode train IN PRIOR (PRIOR: 256x16 then 16x4 uint16 probabilities)+ * tilecode encode IN PRIOR OUT+ * IN: u32 blocks, then per block: u8 bits (4 or 2), u8 0, u16 tiles, tiles x 256 (or 512, 2 bits) texels (one a byte).+ * OUT: per block, u32 size and its bytes. */+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include "../src/tilecode.h"++typedef struct {+ int bits, n;+ uint8_t *tex;+} Block;++static Block *blocks;+static int nblocks;++static void load(const char *path) {+ FILE *f = fopen(path, "rb");+ if (!f) exit(1);+ uint32_t n;+ if (fread(&n, 4, 1, f) != 1) exit(1);+ nblocks = (int)n;+ blocks = calloc(n, sizeof *blocks);+ for (uint32_t i = 0; i < n; i++) {+ uint8_t h[4];+ if (fread(h, 1, 4, f) != 4) exit(1);+ blocks[i].bits = h[0];+ blocks[i].n = h[2] | h[3] << 8;+ size_t sz = blocks[i].bits == 2 ? 512 : 256;+ blocks[i].tex = malloc((size_t)blocks[i].n * sz);+ if (fread(blocks[i].tex, sz, (size_t)blocks[i].n, f) != (size_t)blocks[i].n) exit(1);+ }+ fclose(f);+}++static double cnt4[TC_CTX4][16][2], cnt2[TC_CTX2][4][2];+static uint16_t prior4[TC_CTX4][16], prior2[TC_CTX2][4];++static void train(void) {+ for (int b = 0; b < nblocks; b++) {+ Block *B = &blocks[b];+ for (int t = 0; t < B->n; t++) {+ int W = B->bits == 2 ? 32 : 16;+ const uint8_t *img = B->tex + (size_t)(W * 16) * t;+ for (int y = 0; y < 16; y++)+ for (int x = 0; x < W; x++) {+ int l = tc_left(img, x, y, W), u = tc_up(img, x, y, l, W), s = img[y * W + x], node = 1;+ if (B->bits == 4) {+ int c = l * 16 + u;+ for (int k = 3; k >= 0; k--) {+ int bit = s >> k & 1;+ cnt4[c][node][bit] += 1;+ node = node * 2 + bit;+ }+ } else {+ int c = l * 4 + u;+ for (int k = 1; k >= 0; k--) {+ int bit = s >> k & 1;+ cnt2[c][node][bit] += 1;+ node = node * 2 + bit;+ }+ }+ }+ }+ }+}++static int clip_p(double c0, double c1) {+ int p = (int)(4096.0 * (c0 + 0.5) / (c0 + c1 + 1.0) + 0.5);+ return p < 64 ? 64 : p > 4032 ? 4032 : p;+}++/* ---------------------------------------------------------------- range coder (LZMA's) */+static uint8_t *out;+static size_t outn, outcap;+static uint64_t low;+static uint32_t range;+static uint8_t cache;+static uint64_t cache_size;++static void put(uint8_t b) {+ if (outn == outcap) out = realloc(out, outcap = outcap ? outcap * 2 : 4096);+ out[outn++] = b;+}+static void shift_low(void) {+ if ((uint32_t)low < 0xFF000000u || (low >> 32)) {+ uint8_t temp = cache;+ do {+ put((uint8_t)(temp + (uint8_t)(low >> 32)));+ temp = 0xFF;+ } while (--cache_size);+ cache = (uint8_t)(low >> 24);+ }+ cache_size++;+ low = (low & 0x00FFFFFFu) << 8;+}+static void enc_bit(uint16_t *pr, int bit) {+ uint32_t bound = (range >> TC_PROB_BITS) * (uint32_t)(*pr >> 4);+ if (!bit) range = bound;+ else low += bound, range -= bound;+ while (range < (1u << 24)) range <<= 8, shift_low();+ tc_update(pr, bit);+}++static uint16_t p4[TC_CTX4][16], p2[TC_CTX2][4];++static void encode_block(const Block *B) {+ low = 0, range = 0xFFFFFFFFu, cache = 0, cache_size = 1, outn = 0;+ for (int c = 0; c < TC_CTX4; c++)+ for (int k = 0; k < 16; k++) p4[c][k] = tc_pack(prior4[c][k], TC_N0);+ for (int c = 0; c < TC_CTX2; c++)+ for (int k = 0; k < 4; k++) p2[c][k] = tc_pack(prior2[c][k], TC_N0);+ for (int t = 0; t < B->n; t++) {+ int W = B->bits == 2 ? 32 : 16;+ const uint8_t *img = B->tex + (size_t)(W * 16) * t;+ for (int y = 0; y < 16; y++)+ for (int x = 0; x < W; x++) {+ int l = tc_left(img, x, y, W), u = tc_up(img, x, y, l, W), s = img[y * W + x], node = 1;+ if (B->bits == 4)+ for (int k = 3; k >= 0; k--) {+ int bit = s >> k & 1;+ enc_bit(&p4[l * 16 + u][node], bit);+ node = node * 2 + bit;+ }+ else+ for (int k = 1; k >= 0; k--) {+ int bit = s >> k & 1;+ enc_bit(&p2[l * 4 + u][node], bit);+ node = node * 2 + bit;+ }+ }+ }+ for (int i = 0; i < 5; i++) shift_low();+}++int main(int argc, char **argv) {+ if (argc < 4) return 1;+ load(argv[2]);+ if (!strcmp(argv[1], "train")) {+ train();+ for (int c = 0; c < TC_CTX4; c++)+ for (int k = 0; k < 16; k++) prior4[c][k] = (uint16_t)clip_p(cnt4[c][k][0], cnt4[c][k][1]);+ for (int c = 0; c < TC_CTX2; c++)+ for (int k = 0; k < 4; k++) prior2[c][k] = (uint16_t)clip_p(cnt2[c][k][0], cnt2[c][k][1]);+ FILE *f = fopen(argv[3], "wb");+ fwrite(prior4, sizeof prior4, 1, f);+ fwrite(prior2, sizeof prior2, 1, f);+ fclose(f);+ return 0;+ }+ if (!strcmp(argv[1], "encode") && argc >= 5) {+ FILE *f = fopen(argv[3], "rb");+ if (!f || fread(prior4, sizeof prior4, 1, f) != 1 || fread(prior2, sizeof prior2, 1, f) != 1) return 1;+ fclose(f);+ FILE *o = fopen(argv[4], "wb");+ for (int b = 0; b < nblocks; b++) {+ encode_block(&blocks[b]);+ uint32_t n = (uint32_t)outn;+ fwrite(&n, 4, 1, o);+ fwrite(out, 1, outn, o);+ }+ fclose(o);+ return 0;+ }+ return 1;+}diff --git a/games/hollowknight/tools/tk2d.py b/games/hollowknight/tools/tk2d.pynew file mode 100644index 00000000..9503ef51--- /dev/null+++ b/games/hollowknight/tools/tk2d.py@@ -0,0 +1,106 @@+"""2D Toolkit sprites and animations (the Knight, enemies, effects, HUD): collections, their sprite definitions+cut from the atlases, and animation clips."""+import functools, math+import numpy as np+from PIL import Image+import unity, typetree+++def _parse(f, pid):+ o = f.objects[pid]+ with unity.in_data():+ mb = o.read(check_read=False)+ sc = mb.m_Script.read()+ v, _, _ = typetree.parse(o, sc)+ return sc.m_ClassName, v++[email protected]_cache(maxsize=None)+def index(path):+ """Collections and animations in a file: {'collections': {name: pid}, 'animations': [(pid, clip names)]}."""+ f = unity.asset_file(path)+ cols, anims = {}, []+ if f is None:+ return {"collections": cols, "animations": anims}+ with unity.in_data():+ for pid, o in f.objects.items():+ if o.type.name != "MonoBehaviour":+ continue+ try:+ mb = o.read(check_read=False)+ sc = mb.m_Script.read()+ except Exception:+ continue+ if sc.m_ClassName == "tk2dSpriteCollectionData":+ v, _, _ = typetree.parse(o, sc)+ cols[unity.S(v["spriteCollectionName"])] = pid+ elif sc.m_ClassName == "tk2dSpriteAnimation":+ v, _, _ = typetree.parse(o, sc)+ anims.append((pid, [unity.S(c["name"]) for c in v["clips"]]))+ return {"collections": cols, "animations": anims}++[email protected]_cache(maxsize=None)+def collection(path, pid):+ _, v = _parse(unity.asset_file(path), pid)+ return v++[email protected]_cache(maxsize=None)+def animation(path, pid):+ _, v = _parse(unity.asset_file(path), pid)+ return v+++def ref_file(path, ref):+ """A PPtr inside `path` -> (file, path id)."""+ fid, pid = ref["m_FileID"], ref["m_PathID"]+ if fid == 0:+ return path, pid+ f = unity.asset_file(path)+ return f.externals[fid - 1].path, pid++[email protected]_cache(maxsize=64)+def atlas(path, pid):+ f = unity.asset_file(path)+ with unity.in_data():+ return f.objects[pid].read().image.convert("RGBA")+++def material_texture(path, mref):+ mp, mpid = ref_file(path, mref)+ f = unity.asset_file(mp)+ with unity.in_data():+ m = f.objects[mpid].read_typetree()+ for t in m["m_SavedProperties"]["m_TexEnvs"]:+ name = t[0] if isinstance(t, (list, tuple)) else t.get("first")+ tex = t[1] if isinstance(t, (list, tuple)) else t.get("second")+ if name == "_MainTex":+ return ref_file(mp, tex["m_Texture"])+ return None+++def sprite_image(path, col, sid):+ """A sprite definition: (RGBA image, local x of its left edge, local y of its top edge, units per pixel)."""+ d = col["spriteDefinitions"][sid]+ mats = col["materials"]+ mref = mats[d["materialId"]] if mats else d["material"]+ tp = material_texture(path, mref)+ img = atlas(*tp)+ W, H = img.size+ uv = d["uvs"]+ us = [p["x"] for p in uv]+ vs = [p["y"] for p in uv]+ x0, x1 = round(min(us) * W), round(max(us) * W)+ y0, y1 = round((1 - max(vs)) * H), round((1 - min(vs)) * H)+ crop = img.crop((x0, y0, x1, y1))+ if d["flipped"]:+ # tk2d stores some sprites turned in the atlas+ crop = crop.transpose(Image.Transpose.ROTATE_90).transpose(Image.Transpose.FLIP_TOP_BOTTOM)+ pos = d["positions"]+ px = [p["x"] for p in pos]+ py = [p["y"] for p in pos]+ lx, rx, by, ty = min(px), max(px), min(py), max(py)+ upp = (rx - lx) / max(1, crop.width)+ return crop, lx, ty, upp, (rx - lx, ty - by)diff --git a/games/hollowknight/tools/typetree.py b/games/hollowknight/tools/typetree.pynew file mode 100644index 00000000..7f00c157--- /dev/null+++ b/games/hollowknight/tools/typetree.py@@ -0,0 +1,74 @@+"""Type trees for the game's MonoBehaviours, made from its own assemblies (TypeTreeGeneratorAPI), and a reader+for their serialized fields."""+import struct, functools+from UnityPy.helpers.TypeTreeGenerator import TypeTreeGenerator+GEN = None+MANAGED = None # the game's Managed folder (set by unity.py)+UNITY_VERSION = "6000.0.61f1"+++def gen():+ global GEN+ if GEN is None:+ GEN = TypeTreeGenerator(UNITY_VERSION)+ GEN.load_local_dll_folder(MANAGED)+ return GEN++class Node:+ __slots__ = ("level", "type", "name", "flag", "children")+ def __init__(s, l, t, n, f): s.level, s.type, s.name, s.flag, s.children = l, t, n, f, []+[email protected]_cache(maxsize=None)+def tree(asm, full):+ base = gen().get_nodes(asm if asm.endswith(".dll") else asm + ".dll", full)+ root = None; stack = []+ for b in base:+ n = Node(b.m_Level, b.m_Type, b.m_Name, b.m_MetaFlag or 0)+ if b.m_Level == 1 and b.m_Name == "m_Enabled": n.flag |= 0x4000+ while stack and stack[-1].level >= n.level: stack.pop()+ if stack: stack[-1].children.append(n)+ else: root = n+ stack.append(n)+ return root++PRIM = {"int": "<i", "SInt32": "<i", "UInt32": "<I", "unsigned int": "<I", "float": "<f", "double": "<d", "SInt64": "<q",+ "UInt64": "<Q", "SInt16": "<h", "UInt16": "<H", "short": "<h", "unsigned short": "<H", "SInt8": "<b", "UInt8": "<B",+ "char": "<B", "bool": "<B", "long long": "<q", "FileSize": "<Q"}++class R:+ def __init__(s, b): s.b, s.p = b, 0+ def align(s): s.p = (s.p + 3) & ~3++def read(node, r, path=""):+ p = path + "/" + node.name+ if node.children and node.children[0].type == "Array":+ arr = node.children[0]+ n = struct.unpack_from("<i", r.b, r.p)[0]; r.p += 4+ if n < 0 or n > 10_000_000: raise ValueError(f"bad array len {n} at {r.p} in {p}")+ el = arr.children[1]+ if el.type in ("UInt8", "char", "SInt8", "bool") and not el.children:+ v = r.b[r.p:r.p + n]; r.p += n+ else:+ v = [read(el, r, p + f"[{i}]") for i in range(n)]+ if arr.flag & 0x4000: r.align()+ elif node.type in PRIM:+ fmt = PRIM[node.type]; v = struct.unpack_from(fmt, r.b, r.p)[0]; r.p += struct.calcsize(fmt)+ elif node.type == "string":+ n = struct.unpack_from("<i", r.b, r.p)[0]+ if n < 0 or r.p + 4 + n > len(r.b): raise ValueError(f"bad string len {n} at {r.p} in {p}")+ v = r.b[r.p + 4:r.p + 4 + n].decode("utf8", "replace"); r.p += 4 + n; r.align()+ elif node.type == "Array":+ raise ValueError("bare array " + p)+ else:+ v = {}+ for c in node.children: v[c.name] = read(c, r, p)+ if node.flag & 0x4000: r.align()+ return v++def parse(obj, script):+ full = (script.m_Namespace + "." if script.m_Namespace else "") + script.m_ClassName+ t = tree(script.m_AssemblyName, full)+ raw = obj.get_raw_data()+ r = R(raw)+ v = read(t, r)+ return v, r.p, len(raw)diff --git a/games/hollowknight/tools/unity.py b/games/hollowknight/tools/unity.pynew file mode 100644index 00000000..f24d9226--- /dev/null+++ b/games/hollowknight/tools/unity.py@@ -0,0 +1,278 @@+"""Reading the game's Unity files: scenes (GameObjects with world transforms and components), sprites, textures,+and MonoBehaviour fields through type trees made from the game's own assemblies.+The game's Data folder comes from HOLLOWKNIGHT (default: the owner's copy)."""+import os, sys, json, math, functools+import numpy as np++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import UnityPy+import typetree, fsm as fsmdec++DATA = os.environ.get("HOLLOWKNIGHT", "/root/numplay-work/gamesrc/hk/Hollow Knight/hollow_knight.app/Contents/Resources/Data")+CACHE = os.path.join(HERE, "cache")+typetree.MANAGED = os.path.join(DATA, "Managed")+S = fsmdec.S+rnd = fsmdec.rnd++_loaded = {}+++class in_data:+ """Unity resolves a file's references from the working directory: work in the game's Data folder."""+ def __enter__(self):+ self.old = os.getcwd()+ os.chdir(DATA)++ def __exit__(self, *a):+ os.chdir(self.old)+++def asset_file(path):+ """A serialized file of the game by name, loaded once."""+ f = _loaded.get(path)+ if f is None:+ with in_data():+ e = UnityPy.load(path)+ f = e.files.get(path)+ _loaded[path] = f+ return f++[email protected]_cache(maxsize=None)+def scene_index():+ """Scene name -> level number (BuildSettings)."""+ gg = asset_file("globalgamemanagers")+ for o in gg.objects.values():+ if o.type.name == "BuildSettings":+ d = o.read_typetree()+ return {os.path.basename(p).replace(".unity", ""): i for i, p in enumerate(d["scenes"])}+ raise RuntimeError("no BuildSettings")+++def quat_mat(q):+ x, y, z, w = q["x"], q["y"], q["z"], q["w"]+ return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],+ [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],+ [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])+++def local_mat(t):+ m = np.eye(4)+ s = t["m_LocalScale"]+ m[:3, :3] = quat_mat(t["m_LocalRotation"]) @ np.diag([s["x"], s["y"], s["z"]])+ p = t["m_LocalPosition"]+ m[:3, 3] = [p["x"], p["y"], p["z"]]+ return m+++def clean(x):+ if isinstance(x, (bytes, bytearray)):+ try:+ s = x.decode("utf8")+ if all(c.isprintable() or c in "\n\t\r" for c in s):+ return s+ except Exception:+ pass+ return "bytes%d" % len(x)+ if isinstance(x, float):+ return rnd(x)+ if isinstance(x, dict):+ if set(x.keys()) == {"m_FileID", "m_PathID"}:+ return [x["m_FileID"], x["m_PathID"]] if x["m_PathID"] else None+ return {k: clean(v) for k, v in x.items()}+ if isinstance(x, list):+ if len(x) > 2000:+ return ["%d items" % len(x)]+ return [clean(v) for v in x]+ return x+++def _dump(name):+ level = "level%d" % scene_index()[name]+ lv = asset_file(level)+ exts = [e.path for e in lv.externals]+ objs = lv.objects+ tr, gos = {}, {}+ for pid, o in objs.items():+ if o.type.name in ("Transform", "RectTransform"):+ tr[pid] = o.read_typetree()+ elif o.type.name == "GameObject":+ gos[pid] = o.read_typetree()+ wm = {}+ sys.setrecursionlimit(20000)++ def world(pid):+ if pid not in wm:+ d = tr[pid]+ m = local_mat(d)+ f = d["m_Father"]["m_PathID"]+ if f and f in tr:+ m = world(f) @ m+ wm[pid] = m+ return wm[pid]+ go_tr = {d["m_GameObject"]["m_PathID"]: pid for pid, d in tr.items()}+ act, paths = {}, {}++ def parent_go(gpid):+ tp = go_tr.get(gpid)+ if tp is None:+ return 0+ f = tr[tp]["m_Father"]["m_PathID"]+ return tr[f]["m_GameObject"]["m_PathID"] if f and f in tr else 0++ def active(gpid):+ if gpid not in act:+ a = bool(gos[gpid]["m_IsActive"])+ p = parent_go(gpid)+ act[gpid] = a and (active(p) if p else True)+ return act[gpid]++ def path(gpid):+ if gpid not in paths:+ p = parent_go(gpid)+ paths[gpid] = (path(p) + "/" if p else "") + S(gos[gpid]["m_Name"])+ return paths[gpid]+ out = {"scene": name, "level": level, "externals": exts, "objects": []}+ for gpid, g in gos.items():+ tp = go_tr.get(gpid)+ rec = {"id": gpid, "name": S(g["m_Name"]), "path": path(gpid), "active": active(gpid),+ "self_active": bool(g["m_IsActive"]), "layer": g["m_Layer"], "tag": g.get("m_Tag", 0),+ "parent": parent_go(gpid)}+ if tp is not None:+ m = world(tp)+ rec["pos"] = rnd([float(m[0, 3]), float(m[1, 3]), float(m[2, 3])])+ rec["m3"] = rnd([float(x) for x in m[:3, :3].flatten()])+ d = tr[tp]+ rec["lpos"] = rnd([d["m_LocalPosition"][k] for k in "xyz"])+ rec["lscale"] = rnd([d["m_LocalScale"][k] for k in "xyz"])+ q = d["m_LocalRotation"]+ rec["lrot"] = rnd([q[k] for k in "xyzw"])+ rec["children"] = [tr[c["m_PathID"]]["m_GameObject"]["m_PathID"] for c in d["m_Children"] if c["m_PathID"] in tr]+ cl = []+ for c in g["m_Component"]:+ o = objs.get(c["component"]["m_PathID"])+ if o is None or o.type.name in ("Transform", "RectTransform"):+ continue+ t = o.type.name+ ent = {"type": t, "pid": o.path_id}+ try:+ if t == "MonoBehaviour":+ mb = o.read(check_read=False)+ sc = mb.m_Script.read()+ ent["class"] = sc.m_ClassName+ try:+ v, _, _ = typetree.parse(o, sc)+ ent["enabled"] = bool(v.get("m_Enabled", 1))+ if sc.m_ClassName == "PlayMakerFSM":+ dfs = fsmdec.decode(v)+ ent["fsm"] = clean(dfs)+ else:+ ent["v"] = clean({k: x for k, x in v.items() if k not in ("m_GameObject", "m_Enabled", "m_Script", "m_Name")})+ except Exception as e:+ ent["err"] = repr(e)[:160]+ elif t == "Mesh":+ continue+ else:+ d = o.read_typetree()+ d.pop("m_GameObject", None)+ if t == "ParticleSystem":+ ent["v"] = {"note": "particles"}+ elif t == "AudioSource":+ ent["v"] = {}+ else:+ ent["v"] = clean(d)+ except Exception as e:+ ent["err"] = repr(e)[:160]+ cl.append(ent)+ rec["c"] = cl+ out["objects"].append(rec)+ return out++[email protected]_cache(maxsize=None)+def scene(name):+ """A scene as a dict (cached as JSON in tools/cache)."""+ os.makedirs(CACHE, exist_ok=True)+ p = os.path.join(CACHE, name + ".json")+ if os.path.exists(p):+ return json.load(open(p))+ with in_data():+ d = _dump(name)+ json.dump(d, open(p, "w"), separators=(",", ":"))+ return d+++def comp(o, cls=None, typ=None):+ for c in o["c"]:+ if (cls and c.get("class") == cls) or (typ and c["type"] == typ):+ return c+ return None+++def by_id(d):+ return {o["id"]: o for o in d["objects"]}+++class Sprite:+ pass+++_sprites = {}+++def sprite(level, exts, fid, pid):+ """A Sprite (name, rect size, pixels per unit, pivot, image on demand) from a scene's reference."""+ path = exts[fid - 1] if fid > 0 else level+ key = (path, pid)+ s = _sprites.get(key)+ if s is None:+ f = asset_file(path)+ if f is None or pid not in f.objects:+ return None+ with in_data():+ o = f.objects[pid].read()+ s = Sprite()+ s.key, s.name = key, o.m_Name+ s.w, s.h = o.m_Rect.width, o.m_Rect.height+ s.ppu = o.m_PixelsToUnits+ s.px, s.py = o.m_Pivot.x, o.m_Pivot.y+ b = o.m_Border+ s.border = (b.x, b.y, b.z, b.w)+ s._obj = f.objects[pid]+ s.tex = None+ _sprites[key] = s+ return s+++def sprite_by_key(key):+ """A Sprite from its (file, path id)."""+ s = _sprites.get(key)+ if s is None:+ s = sprite(None, (key[0],), 1, key[1])+ return s+++def sprite_image(s):+ if s.tex is None:+ with in_data():+ s.tex = s._obj.read().image.convert("RGBA")+ return s.tex++[email protected]_cache(maxsize=None)+def material(path, pid):+ f = asset_file(path)+ if f is None or pid not in f.objects:+ return ("?", "?")+ with in_data():+ m = f.objects[pid].read()+ try:+ shn = m.m_Shader.read().m_ParsedForm.m_Name+ except Exception:+ shn = "?"+ return (m.m_Name, shn)+++def ref_path(d, fid):+ return d["externals"][fid - 1] if fid > 0 else d["level"]diff --git a/games/hollowknight/tools/visible.py b/games/hollowknight/tools/visible.pynew file mode 100644index 00000000..eca5cbe7--- /dev/null+++ b/games/hollowknight/tools/visible.py@@ -0,0 +1,117 @@+"""Which scenery can ever be seen: the scene drawn from camera positions all over its range, at the calculator's+resolution, front to back. Every sprite instance gets the parts of its sprite that show (cells of 8 sprite pixels);+instances that never show are dropped. Only static scenery hides what is behind it (scripted objects can move or+fade). Results are cached in tools/cache/NAME.vis.npz."""+import os, sys, math, multiprocessing as mp+import numpy as np+from PIL import Image+import unity, scene++CELL = 8+STEP = 2.0 # camera grid (units)+ALPHA_MIN = 0.02 # a pixel shows an instance when its weight (alpha x what is left in front) is above this++_sc = None+++def _load(name):+ global _sc+ if _sc is None or _sc[0] != name:+ inst = scene.instances(name)+ st = scene.settings(unity.scene(name))+ alphas = {}+ _sc = (name, inst, st, alphas)+ return _sc+++def alpha_of(it, alphas):+ s = it.sprite+ a = alphas.get(s.key)+ if a is None:+ a = unity.sprite_image(s).getchannel("A")+ alphas[s.key] = a+ return a+++def view(args):+ name, cx, cy = args+ _, inst, st, alphas = _load(name)+ W, H = scene.VIEW_W, scene.VIEW_H+ T = np.ones((H, W), np.float32)+ seen = []+ lst = []+ for it in inst:+ q = [scene.project(p, cx, cy) for p in it.quad]+ if any(p is None for p in q):+ continue+ xs = [p[0] for p in q]+ ys = [p[1] for p in q]+ if max(xs) < 0 or min(xs) > W or max(ys) < 0 or min(ys) > H:+ continue+ lst.append((it, q))+ for it, q in reversed(lst):+ a_img = alpha_of(it, alphas)+ w, h = a_img.size+ tl, tr, bl = np.array(q[3]), np.array(q[2]), np.array(q[0])+ A = np.array([[(tr - tl)[0] / w, (bl - tl)[0] / h, tl[0]], [(tr - tl)[1] / w, (bl - tl)[1] / h, tl[1]], [0, 0, 1]])+ try:+ Ai = np.linalg.inv(A)+ except np.linalg.LinAlgError:+ continue+ xs = [p[0] for p in q]+ ys = [p[1] for p in q]+ x0, y0 = max(0, int(math.floor(min(xs)))), max(0, int(math.floor(min(ys))))+ x1, y1 = min(W, int(math.ceil(max(xs)))), min(H, int(math.ceil(max(ys))))+ if x1 <= x0 or y1 <= y0:+ continue+ Tm = Ai @ np.array([[1, 0, x0], [0, 1, y0], [0, 0, 1]])+ a = np.asarray(a_img.transform((x1 - x0, y1 - y0), Image.AFFINE, tuple(Tm[:2].flatten()), resample=Image.BILINEAR),+ dtype=np.float32) / 255.0 * it.color[3]+ t = T[y0:y1, x0:x1]+ wgt = a * t+ vis = wgt > ALPHA_MIN+ if vis.any():+ ys_, xs_ = np.nonzero(vis)+ px, py = xs_ + x0 + 0.5, ys_ + y0 + 0.5+ u = Ai[0, 0] * px + Ai[0, 1] * py + Ai[0, 2]+ v = Ai[1, 0] * px + Ai[1, 1] * py + Ai[1, 2]+ cu = np.clip((u // CELL).astype(np.int32), 0, (w - 1) // CELL)+ cv = np.clip((v // CELL).astype(np.int32), 0, (h - 1) // CELL)+ seen.append((it.id, float(wgt.sum()), np.unique(cv * 4096 + cu)))+ if not it.dynamic and it.blend == "alpha":+ t *= (1 - a)+ return seen+++def compute(name):+ p = os.path.join(unity.CACHE, name + ".vis.npz")+ if os.path.exists(p):+ z = np.load(p, allow_pickle=True)+ return z["weight"], z["cells"].item()+ inst = scene.instances(name)+ st = scene.settings(unity.scene(name))+ if st["size"] is None:+ n = len(inst)+ return np.ones(n), {}+ x0, x1, y0, y1 = scene.camera_range(st)+ xs = np.arange(x0, x1 + 1e-6, STEP) if x1 > x0 else [x0]+ ys = np.arange(y0, y1 + 1e-6, STEP) if y1 > y0 else [y0]+ xs = sorted(set(list(xs) + [x1]))+ ys = sorted(set(list(ys) + [y1]))+ jobs = [(name, float(cx), float(cy)) for cx in xs for cy in ys]+ weight = np.zeros(len(inst))+ cells = {}+ with mp.get_context("spawn").Pool(min(4, os.cpu_count() or 1)) as pool:+ for seen in pool.imap_unordered(view, jobs, chunksize=4):+ for i, wsum, c in seen:+ weight[i] = max(weight[i], wsum)+ cells.setdefault(i, set()).update(c.tolist())+ cells = {i: np.array(sorted(c), np.int32) for i, c in cells.items()}+ np.savez_compressed(p, weight=weight, cells=np.array(cells, dtype=object))+ print("visible", name, len(jobs), "views:", int((weight >= 0.5).sum()), "of", len(inst), "instances show", flush=True)+ return weight, cells+++if __name__ == "__main__":+ for n in sys.argv[1:]:+ compute(n)