Skip to content

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

Hollow Knight: camera lock areas, room triggers, masks that fade as the Knight enters

Mason Chen87c3c71c603c
diff --git a/games/hollowknight/Makefile b/games/hollowknight/Makefile
index ee783404..b13483fc 100644
--- a/games/hollowknight/Makefile
+++ b/games/hollowknight/Makefile
@@ -9,7 +9,7 @@ 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
+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/world.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
diff --git a/games/hollowknight/src/data.bin b/games/hollowknight/src/data.bin
index 88d4049c..670fbaa7 100644
Binary files a/games/hollowknight/src/data.bin and b/games/hollowknight/src/data.bin differ
diff --git a/games/hollowknight/src/game.c b/games/hollowknight/src/game.c
index 0839f324..69cb8d1b 100644
--- a/games/hollowknight/src/game.c
+++ b/games/hollowknight/src/game.c
@@ -15,8 +15,10 @@ void game_new(void) {
bool game_enter(int room, float x, float y, bool facing_right) {
if (!room_load(room)) return false;
memset(inside, 0, sizeof inside);
+ world_enter();
hero_init(x, y, facing_right);
cam_init();
+ world_hero_in_position();
return true;
}
@@ -42,6 +44,7 @@ static void trigger_event(int i, const Ent *e, int kind) {
}
break;
default:
+ world_trigger(i, kind);
break;
}
(void)h;
@@ -55,7 +58,7 @@ static void triggers_tick(void) {
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;
+ if (e->type != ENT_CAMLOCK && e->type != ENT_GATE && e->type != ENT_HAZARD_TRIGGER && e->type != ENT_MASK) 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));
@@ -69,6 +72,7 @@ void game_tick(uint32_t keys) {
hero_fixed(keys);
triggers_tick();
hero_update();
+ world_tick();
cam_tick();
}
diff --git a/games/hollowknight/src/game.h b/games/hollowknight/src/game.h
index 104b6e1f..69e73b2a 100644
--- a/games/hollowknight/src/game.h
+++ b/games/hollowknight/src/game.h
@@ -3,7 +3,9 @@
#include "hk.h"
/* ---------------------------------------------------------------- PlayerData (what a save keeps) */
+#define MAX_PERSIST 1024
typedef struct {
+ uint8_t persist[MAX_PERSIST / 8]; /* the objects' states (PersistentBoolItem) */
int8_t health, max_health, health_blue;
int16_t mp, mp_reserve, max_mp;
int32_t geo;
@@ -14,17 +16,27 @@ typedef struct {
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 { ENT_CAMLOCK = 1, ENT_GATE, ENT_HAZARD_MARKER, ENT_RESPAWN, ENT_HAZARD_TRIGGER, ENT_MASK };
+enum { MK_SECRET = 1, MK_REMASK = 2, MK_SIMPLE = 4 }; /* masks: the unmasker, remasker and inverse FSMs */
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;
+ uint8_t group, group2; /* its render groups */
uint16_t a; /* gate: the room it leads to; hazard trigger: its marker */
+ uint16_t persist; /* its bit in the save (NO_PERSIST: none) */
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 */
+ float p0, p1, p2, p3; /* camera lock: x min, y min, x max, y max (-1: none); gate: entry delay; mask: fade time,
+ pause, then the trigger kind (simple) or the alphas of Idle and Fade Out (remasker) */
uint16_t s0, s1; /* names (str_at): a gate's own and its entry point's */
} Ent;
+#define NO_PERSIST 0xFFFF
+void world_enter(void); /* the room's objects, as the room starts */
+void world_tick(void); /* 1/50 s */
+void world_trigger(int ent, int kind); /* the Knight entering, staying in, leaving an object's trigger (EV_*) */
+void world_hero_in_position(void); /* the Knight done entering the room (WaitForHeroInPosition) */
+void group_fade(int group, float alpha, float time); /* iTweenFadeTo (linear) */
const Ent *room_ents(int *n);
#define MAX_ENTS 160
diff --git a/games/hollowknight/src/gfx.c b/games/hollowknight/src/gfx.c
index c6a7c800..3fc5d649 100644
--- a/games/hollowknight/src/gfx.c
+++ b/games/hollowknight/src/gfx.c
@@ -101,12 +101,20 @@ static uint32_t grade(float r, float g, float b, float a) {
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);
+uint8_t g_group_alpha[MAX_GROUPS];
+
+/* the instance's alpha: its tint's, times its render group's */
+static inline uint32_t inst_alpha(const Inst *in) {
+ uint32_t a = g_room.tints[4 * in->tint + 3];
+ return in->group ? (a * g_group_alpha[in->group] + 127) / 255 : a;
+}
+
+static int pal_get(uint16_t tex, uint8_t tint, uint8_t flags, uint32_t alpha) {
+ uint32_t key = (uint32_t)tex << 16 | alpha << 8 | (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 */
+ if (r->fmt == FMT_ALPHA2) key = 0xFFFE0000u | alpha; /* black: only the alpha matters */
}
for (int i = 0; i < NPAL; i++)
if (pals[i].key == key) {
@@ -126,8 +134,8 @@ static int pal_get(uint16_t tex, uint8_t tint, uint8_t flags) {
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;
+ p->solid = alpha == 255;
+ float tr = t[0] / 255.0f, tg = t[1] / 255.0f, tb = t[2] / 255.0f, ta = alpha / 255.0f;
if (flags & F_LIT) {
const float *am = g_room.h->ambient;
tr *= am[0], tg *= am[1], tb *= am[2];
@@ -169,10 +177,10 @@ 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) {
+static const uint32_t *soft_get(uint16_t tex, uint8_t tint, uint8_t flags, uint32_t alpha) {
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);
+ uint32_t key = (uint32_t)tex << 16 | alpha << 8 | (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;
@@ -199,7 +207,7 @@ static const uint32_t *soft_get(uint16_t tex, uint8_t tint, uint8_t flags) {
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;
+ float tr = t[0] / 255.0f, tg = t[1] / 255.0f, tb = t[2] / 255.0f, ta = alpha / 255.0f;
if (flags & F_LIT) {
const float *am = g_room.h->ambient;
tr *= am[0], tg *= am[1], tb *= am[2];
@@ -718,7 +726,7 @@ __attribute__((noinline)) static void draw_item(int idx, Item *it, int sy0, int
c.m = &m;
if (c.r->fmt >= FMT_SOFT) {
kind = 3;
- soft = soft_get(in->tex, in->tint, in->flags);
+ soft = soft_get(in->tex, in->tint, in->flags, inst_alpha(in));
if (!soft) return;
if (c.r->fmt == FMT_SOFTA) {
const uint8_t *t = g_room.tints + 4 * in->tint;
@@ -726,7 +734,7 @@ __attribute__((noinline)) static void draw_item(int idx, Item *it, int sy0, int
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;
+ crb = col & 0xFF00FF, cg = col & 0xFF00, ta = inst_alpha(in) + 1u;
}
} else if ((c.r->flags & TEX_SMOOTH) && c.r->fmt == FMT_PAL4) {
kind = 4;
@@ -817,7 +825,7 @@ static void draw_bg_item(Item *it) {
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);
+ soft = soft_get(in->tex, in->tint, in->flags, inst_alpha(in));
if (!soft) return;
if (r->fmt == FMT_SOFTA) {
const uint8_t *t = g_room.tints + 4 * in->tint;
@@ -825,7 +833,7 @@ static void draw_bg_item(Item *it) {
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;
+ crb = c & 0xFF00FF, cg = c & 0xFF00, ta = inst_alpha(in) + 1u;
}
}
BiTex bt = {in->tex, r->tw, r, NULL, pal};
@@ -1016,8 +1024,10 @@ bool gfx_actor(const Inst *in, uint32_t group) {
static void add_item(const Inst *in, float blur_z) {
Item cur;
cur.in = *in;
+ uint32_t alpha = inst_alpha(in);
+ if (!alpha) return; /* (a hidden group, or a clear tint) */
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);
+ cur.pal = (uint8_t)pal_get(cur.in.flags & F_SOLID ? TEX_NONE : cur.in.tex, cur.in.tint, cur.in.flags, alpha);
if (cur.in.z * (1.0f / 128) > blur_z) {
arena_take(&cur, false);
if (!bg_on) memset(bgbuf, 0, sizeof bgbuf), bg_on = true;
diff --git a/games/hollowknight/src/hk.h b/games/hollowknight/src/hk.h
index 2138e6a7..6c43ef2d 100644
--- a/games/hollowknight/src/hk.h
+++ b/games/hollowknight/src/hk.h
@@ -78,7 +78,10 @@ typedef struct {
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) */
+ uint8_t group; /* its render group (F_DYN): faded or hidden as the game wants (g_group_alpha) */
} Inst;
+#define MAX_GROUPS 64
+extern uint8_t g_group_alpha[MAX_GROUPS]; /* 255 shown, 0 hidden */
enum { BL_ALPHA = 0, BL_ADD, BL_SCREEN, BL_LINEARLIGHT, BL_OVERLAY, BL_MULTIPLY };
#define F_BLEND 7
#define F_LIT 8
diff --git a/games/hollowknight/src/room.c b/games/hollowknight/src/room.c
index a84044f5..df5020ff 100644
--- a/games/hollowknight/src/room.c
+++ b/games/hollowknight/src/room.c
@@ -88,6 +88,7 @@ static bool advance(Stream *s) {
}
if (flags & F_ROT) in->rot = (int16_t)rd16(p), p += 2;
else in->rot = 0;
+ in->group = (flags & F_DYN) ? (*p++ & (MAX_GROUPS - 1)) : 0;
s->p = p;
return true;
}
diff --git a/games/hollowknight/src/world.c b/games/hollowknight/src/world.c
new file mode 100644
index 00000000..1f420cf3
--- /dev/null
+++ b/games/hollowknight/src/world.c
@@ -0,0 +1,135 @@
+/* The room's game objects: their state, run each tick; the render groups they fade. */
+#include "game.h"
+
+#define DT 0.02f
+
+/* ---------------------------------------------------------------- render groups: iTweenFadeTo */
+static struct {
+ float from, to, t, time;
+ bool on;
+} fades[MAX_GROUPS];
+
+void group_fade(int g, float alpha, float time) {
+ if (g <= 0 || g >= MAX_GROUPS) return;
+ fades[g].from = g_group_alpha[g] / 255.0f, fades[g].to = alpha, fades[g].t = 0, fades[g].time = time, fades[g].on = true;
+ if (time <= 0) {
+ g_group_alpha[g] = (uint8_t)(alpha * 255 + 0.5f);
+ fades[g].on = false;
+ }
+}
+
+static void fades_tick(void) {
+ for (int g = 1; g < MAX_GROUPS; g++) {
+ if (!fades[g].on) continue;
+ fades[g].t += DT;
+ float k = fades[g].t >= fades[g].time ? 1 : fades[g].t / fades[g].time;
+ float a = fades[g].from + (fades[g].to - fades[g].from) * k;
+ g_group_alpha[g] = (uint8_t)(a * 255 + 0.5f);
+ if (k >= 1) fades[g].on = false;
+ }
+}
+
+/* ---------------------------------------------------------------- the objects' state */
+typedef struct {
+ uint8_t state;
+ float timer;
+} EntState;
+static EntState es[MAX_ENTS];
+static bool hero_in_position;
+
+static bool persist_get(int i) { return i != NO_PERSIST && (g_pd.persist[i >> 3] >> (i & 7) & 1); }
+static void persist_set(int i) {
+ if (i != NO_PERSIST) g_pd.persist[i >> 3] |= (uint8_t)(1 << (i & 7));
+}
+
+/* masks' states (their FSMs') */
+enum { M_PAUSE, M_IDLE, M_IDLE_STAY, M_FADE_OUT, M_FADE_IN, M_DONE };
+
+static void mask_idle(const Ent *e, EntState *s) {
+ if (e->flags == MK_SECRET) {
+ if (persist_get(e->persist)) {
+ group_fade(e->group, 0, 0.1f); /* (Activate) */
+ s->state = M_DONE;
+ } else
+ s->state = M_IDLE_STAY;
+ return;
+ }
+ if (e->flags == MK_REMASK && e->p2 >= 0) {
+ /* (Idle fades the owner at once; an inverse mask child the other way) */
+ group_fade(e->group, e->p2, 0.01f);
+ group_fade(e->group2, 1 - e->p2, 0.01f);
+ }
+ s->state = M_IDLE;
+}
+
+static void mask_tick(const Ent *e, EntState *s) {
+ if (s->state == M_PAUSE && hero_in_position) {
+ s->timer += DT;
+ if (s->timer >= e->p1) mask_idle(e, s);
+ }
+}
+
+static void mask_trigger(const Ent *e, EntState *s, int kind) {
+ float t = e->p0;
+ switch (e->flags) {
+ case MK_SECRET:
+ if (s->state == M_IDLE_STAY && kind == EV_STAY) {
+ group_fade(e->group, 0, t);
+ persist_set(e->persist);
+ s->state = M_DONE;
+ }
+ break;
+ case MK_REMASK: {
+ float out = e->p3 < 0 ? 0 : e->p3; /* (Fade Out's alpha; Fade In's the other) */
+ if ((s->state == M_IDLE || s->state == M_FADE_IN) && kind == EV_STAY) {
+ group_fade(e->group, out, t);
+ group_fade(e->group2, 1 - out, t);
+ persist_set(e->persist);
+ s->state = M_FADE_OUT;
+ } else if (s->state == M_FADE_OUT && kind == EV_EXIT) {
+ group_fade(e->group, 1 - out, t);
+ group_fade(e->group2, out, t);
+ s->state = M_FADE_IN;
+ }
+ break;
+ }
+ case MK_SIMPLE:
+ if (s->state == M_IDLE && ((e->p2 == 0 && kind == EV_ENTER) || (e->p2 == 1 && kind == EV_STAY))) {
+ group_fade(e->group, 0, t);
+ s->state = M_DONE;
+ }
+ break;
+ }
+}
+
+/* ---------------------------------------------------------------- the room */
+void world_enter(void) {
+ memset(es, 0, sizeof es);
+ memset(fades, 0, sizeof fades);
+ memset(g_group_alpha, 255, sizeof g_group_alpha);
+ hero_in_position = false;
+ int n;
+ const Ent *e = room_ents(&n);
+ for (int i = 0; i < n && i < MAX_ENTS; i++) {
+ if (e[i].type != ENT_MASK) continue;
+ if (e[i].flags == MK_SIMPLE) es[i].state = M_IDLE;
+ else es[i].state = M_PAUSE;
+ if (e[i].group2) group_fade(e[i].group2, 0, 0); /* (Pause: the inverse mask hidden) */
+ }
+}
+
+void world_hero_in_position(void) { hero_in_position = true; }
+
+void world_trigger(int i, int kind) {
+ int n;
+ const Ent *e = &room_ents(&n)[i];
+ if (e->type == ENT_MASK) mask_trigger(e, &es[i], kind);
+}
+
+void world_tick(void) {
+ int n;
+ const Ent *e = room_ents(&n);
+ for (int i = 0; i < n && i < MAX_ENTS; i++)
+ if (e[i].type == ENT_MASK) mask_tick(&e[i], &es[i]);
+ fades_tick();
+}
diff --git a/games/hollowknight/tools/ents.py b/games/hollowknight/tools/ents.py
index 621e2018..fb2cc5d7 100644
--- a/games/hollowknight/tools/ents.py
+++ b/games/hollowknight/tools/ents.py
@@ -5,12 +5,24 @@ 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
+ENT_CAMLOCK, ENT_GATE, ENT_HAZARD_MARKER, ENT_RESPAWN, ENT_HAZARD_TRIGGER, ENT_MASK = 1, 2, 3, 4, 5, 6
+# masks (the unmasker, remasker and remasker_inverse FSMs)
+MK_SECRET, MK_REMASK, MK_SIMPLE = 1, 2, 4
# 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
+REC = "<BBBBHHffffffffHH" # type, flags, group, group2, a, persist, box (x0, y0, x1, y1), p0..p3, s0, s1
+NO_PERSIST = 0xFFFF
+
+
+class Persist:
+ """The objects whose state a save keeps (PersistentBoolItem): one bit each."""
+ def __init__(self):
+ self.keys = {}
+
+ def id(self, room, path):
+ return self.keys.setdefault((room, path), len(self.keys))
class Strings:
@@ -60,11 +72,104 @@ def _trigger(o):
return None
-def room(d, rooms, strings):
- """-> list of packed records."""
+def rec(type_, flags=0, box=(0, 0, 0, 0), p=(0, 0, 0, 0), a=0, group=0, group2=0, persist=NO_PERSIST, s0=0, s1=0):
+ return struct.pack(REC, type_, flags, group, group2, a, persist, *box, *p, s0, s1)
+
+
+def _fsm(o, names):
+ for c in o["c"]:
+ f = c.get("fsm")
+ if f and f.get("name") in names:
+ return f
+ return None
+
+
+def _state(f, name):
+ for st in f["states"]:
+ if st["name"] == name:
+ return st
+ return None
+
+
+def _param(action, key):
+ for k, v in action["params"]:
+ if k == key:
+ return v
+ return None
+
+
+def _value(f, v, default=0.0):
+ """A parameter: a number, or an FSM variable ("$Name")."""
+ if isinstance(v, str) and v.startswith("$"):
+ var = f.get("vars", {}).get(v[1:])
+ return float(var[1]) if var and isinstance(var[1], (int, float)) else default
+ return float(v) if isinstance(v, (int, float)) else default
+
+
+def _fade_time(f, state):
+ st = _state(f, state)
+ for a in (st["actions"] if st else []):
+ if a["name"] == "iTweenFadeTo" and a.get("enabled", True):
+ return _value(f, _param(a, "time"), 0.5)
+ return 0.5
+
+
+def _owner_alpha(f, state):
+ """The alpha the state fades its owner to (-1: none)."""
+ st = _state(f, state)
+ for a in (st["actions"] if st else []):
+ if a["name"] == "iTweenFadeTo" and a.get("enabled", True) and _param(a, "gameObject") == "Owner":
+ return _value(f, _param(a, "alpha"), 0)
+ return -1.0
+
+
+def _mask(o, f, objs_by_id):
+ """-> (kind, fade time, pause, p2, p3, inverse child id) or None: p2, p3 the trigger kind (simple masks), or the
+ alphas Idle and Fade Out give the owner (remaskers)."""
+ names = [st["name"] for st in f["states"]]
+ inverse = None
+ for cid in o.get("children", []):
+ if objs_by_id.get(cid, {}).get("name") == "Inverse Mask":
+ inverse = cid
+ pause = 0.0
+ ps = _state(f, "Pause")
+ if ps:
+ for a in ps["actions"]:
+ if a["name"] == "Wait" and a.get("enabled", True):
+ pause = _value(f, _param(a, "time"), 0)
+ if "Idle Stay" in names:
+ return MK_SECRET, _fade_time(f, "Fade"), pause, 1, 0, None
+ if "Fade Out" in names and "Fade In" in names:
+ # (what Idle and Fade Out fade the owner to; Fade In the other way; an inverse mask child the other way still)
+ return MK_REMASK, _fade_time(f, "Fade Out"), pause, _owner_alpha(f, "Idle"), _owner_alpha(f, "Fade Out"), inverse
+ if "Fade" in names:
+ trig = 3 # (no trigger: another object uncovers it)
+ idle = _state(f, f["start"])
+ for a in (idle["actions"] if idle else []):
+ if a["name"] == "Trigger2dEvent" and a.get("enabled", True):
+ trig = int(_param(a, "trigger") or 0)
+ return MK_SIMPLE, _fade_time(f, "Fade"), 0.0, trig, 0, None
+ return None
+
+
+def room(d, rooms, strings, persist, name):
+ """-> (packed records, {object id: render group})."""
recs = []
+ groups = {}
marker_index = {}
objs = [o for o in d["objects"] if o["active"]]
+ by_id = {o["id"]: o for o in d["objects"]}
+
+ def subtree(oid, g):
+ groups[oid] = g
+ for c in by_id[oid].get("children", []):
+ subtree(c, g)
+ ngroups = [0]
+
+ def new_group(oid):
+ ngroups[0] += 1
+ subtree(oid, ngroups[0])
+ return ngroups[0]
# markers first: the triggers refer to them
for o in objs:
for c in o["c"]:
@@ -72,38 +177,48 @@ def room(d, rooms, strings):
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"])))
+ recs.append(rec(ENT_HAZARD_MARKER, FACING_RIGHT if v.get("respawnFacingRight") else 0, (x, y, x, y),
+ s1=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))
+ recs.append(rec(ENT_RESPAWN, FACING_RIGHT if v.get("respawnFacingRight") else 0, (x, y, x, y),
+ s0=strings.id(o["name"])))
for o in objs:
+ f = _fsm(o, ("unmasker", "remasker", "remasker_inverse"))
+ if f:
+ m = _mask(o, f, by_id)
+ box = _trigger(o) or (0, 0, 0, 0)
+ if m:
+ kind, fade, pause, p2, p3, inverse = m
+ g = new_group(o["id"])
+ g2 = new_group(inverse) if inverse else 0
+ persistent = any(c.get("class") == "PersistentBoolItem" for c in o["c"])
+ recs.append(rec(ENT_MASK, kind, box, (fade, pause, p2, p3), group=g, group2=g2,
+ persist=persist.id(name, o["path"]) if persistent else NO_PERSIST))
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) | \
+ fl = (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))
+ recs.append(rec(ENT_CAMLOCK, fl, box, (v["cameraXMin"], v["cameraYMin"], v["cameraXMax"], v["cameraYMax"])))
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) | \
+ fl = (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 "")))
+ recs.append(rec(ENT_GATE, fl, box, (float(v.get("entryDelay", 0)), 0, 0, 0), a=ti, s0=strings.id(o["name"]),
+ s1=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
+ mid = ref[1] if isinstance(ref, (list, tuple)) else None
# (the marker is a component: find its object)
target = None
for oo in objs:
@@ -112,5 +227,6 @@ def room(d, rooms, strings):
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 recs
+ recs.append(rec(ENT_HAZARD_TRIGGER, box=box, a=marker_index[target]))
+ assert ngroups[0] < 64, ngroups[0]
+ return recs, groups
diff --git a/games/hollowknight/tools/pack.py b/games/hollowknight/tools/pack.py
index afb75d53..62beb42f 100644
--- a/games/hollowknight/tools/pack.py
+++ b/games/hollowknight/tools/pack.py
@@ -9,6 +9,7 @@ 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()
+PERSIST = ents.Persist()
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}
@@ -63,8 +64,8 @@ def inst_record(it, tex_id, tints):
flags = BLENDS.get(it.blend, 0)
if it.lit:
flags |= F_LIT
- if it.dynamic:
- flags |= F_DYN
+ if it.group:
+ flags |= F_DYN # (in a render group: a byte more)
if it.grass:
flags |= F_GRASS
color = it.color
@@ -97,7 +98,7 @@ def inst_record(it, tex_id, tints):
rot = int(round(ang / (2 * math.pi) * 65536))
if rot:
flags |= F_ROT
- return (ax, ay, it.z, tex, tint, flags, a, b, rot)
+ return (ax, ay, it.z, tex, tint, flags, a, b, rot, it.group)
def uvar(u):
@@ -117,10 +118,10 @@ 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]."""
+ x step, y step, [z step], [a], [b], [angle], [render group (F_DYN)]."""
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:
+ for rank, (ax, ay, z, tex, tint, flags, a, b, rot, rgroup), 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:
@@ -155,6 +156,8 @@ def sector_stream(recs):
out += struct.pack("<H", B)
if flags & F_ROT:
out += struct.pack("<h", rot)
+ if flags & F_DYN:
+ out.append(rgroup)
pr, pt, px, py, pz, pa, pb, pg = rank, tex, X, Y, Z, A, B, group
return bytes(out)
@@ -166,6 +169,9 @@ def room_blobs(name, keep, st, tex_id):
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
+ erecs, groups = ents.room(unity.scene(name), ROOMS, STRINGS, PERSIST, name)
+ for it in keep:
+ it.group = groups.get(it.obj["id"], 0)
tints = [(255, 255, 255, 255)]
secs = {}
for rank, it in enumerate(keep):
@@ -198,9 +204,8 @@ def room_blobs(name, keep, st, tex_id):
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
+ *st["hero_light"], lo, hi, len(keep), len(segs), len(cols), gw, gh, len(erecs), 0, 0) + lut
assert len(hdr) == HDR, len(hdr)
body = bytearray(hdr)
body += b"".join(struct.pack("<4B", *t) for t in tints)
@@ -236,7 +241,7 @@ def room_blobs(name, keep, st, tex_id):
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)
+ return body, o_sec, blobs, bytes(cb), b"".join(erecs)
def tilecode(blocks):