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: nail hits, breakable walls and props

Mason Chen8c937b73753a
diff --git a/games/hollowknight/Makefile b/games/hollowknight/Makefile
index b13483fc..ba715ece 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/world.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/obj.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/anim.c b/games/hollowknight/src/anim.c
index b0627648..6aedf966 100644
--- a/games/hollowknight/src/anim.c
+++ b/games/hollowknight/src/anim.c
@@ -165,3 +165,16 @@ void sprite_inst(int sprite, float x, float y, float z, float sx, float sy, uint
out->rot = 0;
out->group = 0;
}
+
+/* turned (degrees, counterclockwise) about its place */
+void sprite_inst_rot(int sprite, float x, float y, float z, float sx, float sy, float degrees, uint8_t tint, Inst *out) {
+ sprite_inst(sprite, x, y, z, sx, sy, tint, out);
+ float r = degrees * (float)M_PI / 180, c = cosf(r), s = sinf(r);
+ const SpriteRec *sp = sprite_rec(sprite);
+ float lx = sx * sp->lx, ty = sy * sp->ty;
+ out->ax = (int16_t)lrintf((x + c * lx - s * ty) * 64);
+ out->ay = (int16_t)lrintf((y + s * lx + c * ty) * 64);
+ int32_t rot = (int32_t)lrintf(degrees / 360.0f * 65536.0f);
+ out->rot = (int16_t)(rot & 0xFFFF);
+ if (out->rot) out->flags |= F_ROT;
+}
diff --git a/games/hollowknight/src/camera.c b/games/hollowknight/src/camera.c
index d6d84fac..b97c1d64 100644
--- a/games/hollowknight/src/camera.c
+++ b/games/hollowknight/src/camera.c
@@ -64,9 +64,33 @@ static void keep_in_scene(float *x, float *y) {
if (*y > c.y_limit) *y = c.y_limit;
}
+/* the CameraShake FSM (on the camera's parent): a shake of higher priority replaces the one going on; ShakePositionV2
+ * moves the camera at random, less and less */
+static struct {
+ float ex, time, t, priority;
+ float dx, dy;
+} sh;
+
+void cam_shake(int kind) {
+ static const float shakes[][3] = {{0, 0, 0}, {0.105f, 0.5f, 6}, {0.15f, 1, 7}, {0.5f, 1, 10}}; /* extents, time, priority */
+ if (kind <= 0 || kind > SHAKE_BIG || shakes[kind][2] <= sh.priority) return;
+ sh.ex = shakes[kind][0], sh.time = shakes[kind][1], sh.priority = shakes[kind][2], sh.t = 0;
+}
+
+static void shake_tick(void) {
+ sh.dx = sh.dy = 0;
+ if (sh.priority <= 0) return;
+ sh.t += 0.02f * g_game.time_scale;
+ float k = 1 - sh.t / sh.time;
+ if (k < 0) k = 0;
+ sh.dx = sh.ex * rand_range(-1, 1) * k, sh.dy = sh.ex * rand_range(-1, 1) * k;
+ if (sh.t > sh.time) sh.priority = 0, sh.dx = sh.dy = 0;
+}
+
void cam_init(void) {
const Hero *h = &g_hero;
memset(&c, 0, sizeof c);
+ memset(&sh, 0, sizeof sh); /* (New Scene Reset) */
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;
@@ -285,7 +309,8 @@ static void controller_late_update(void) {
void cam_tick(void) {
target_update();
controller_late_update();
- g_cam_x = c.cx, g_cam_y = c.cy;
+ shake_tick();
+ g_cam_x = c.cx + sh.dx, g_cam_y = c.cy + sh.dy;
}
/* after a respawn: the camera with the Knight (PositionToHero) */
diff --git a/games/hollowknight/src/data.bin b/games/hollowknight/src/data.bin
index 8c7b58db..33df4cce 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 230690d0..c7c2db9a 100644
--- a/games/hollowknight/src/game.c
+++ b/games/hollowknight/src/game.c
@@ -163,6 +163,7 @@ void game_tick(uint32_t keys) {
}
void game_draw(void) {
+ obj_draw();
hero_draw();
gfx_frame();
}
diff --git a/games/hollowknight/src/game.h b/games/hollowknight/src/game.h
index 3200f05d..6fe7ca80 100644
--- a/games/hollowknight/src/game.h
+++ b/games/hollowknight/src/game.h
@@ -17,7 +17,9 @@ 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, ENT_MASK, ENT_DAMAGE, ENT_SHAPE,
- ENT_BOX }; /* (shape, box: more of the record before) */
+ ENT_BOX, ENT_OBJ, ENT_PIECE }; /* (shape, box, piece: more of the record before) */
+enum { OK_BREAKABLE = 1 }; /* objects (ENT_OBJ's flags) */
+enum { HB_BOUNCE = 1, HB_RECOIL = 2 }; /* a hit box (ENT_BOX's flags): a down slash bounces off it, a slash recoils */
enum { HAZ_NONE, HAZ_NORMAL, HAZ_SPIKES, HAZ_ACID, HAZ_LAVA, HAZ_PIT }; /* DamageHero.hazardType */
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 };
@@ -38,9 +40,21 @@ void world_enter(void); /* the room's objects, as the room s
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 world_send_hit(int ent); /* HIT to an object's FSM (from another's) */
void group_fade(int group, float alpha, float time); /* iTweenFadeTo (linear) */
+bool persist_get(int bit); /* an object's state in the save (PersistentBoolItem) */
+void persist_set(int bit);
+
+/* the objects the Knight acts on (obj.c) */
+void obj_enter(void);
+void obj_tick(void);
+void obj_draw(void);
+void obj_swing_start(void); /* a slash's hit shape on: what it hits, once */
+int obj_nail(const float *pts, int npts, float direction); /* -> HB_* of what it touches */
+float rand_range(float lo, float hi); /* Random.Range (floats) */
+int cardinal(float degrees); /* DirectionUtils.GetCardinalDirection */
const Ent *room_ents(int *n);
-#define MAX_ENTS 160
+#define MAX_ENTS 320
/* ---------------------------------------------------------------- the game */
typedef struct {
@@ -145,6 +159,8 @@ void game_draw(void);
void cam_init(void);
void cam_tick(void);
void cam_snap_to_hero(void); /* (after a respawn) */
+enum { SHAKE_ENEMY_KILL = 1, SHAKE_AVERAGE, SHAKE_BIG }; /* the CameraShake FSM's events */
+void cam_shake(int kind);
void cam_freeze(void); /* FreezeInPlace (both) */
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/hero.c b/games/hollowknight/src/hero.c
index 45c70b42..ae7f5268 100644
--- a/games/hollowknight/src/hero.c
+++ b/games/hollowknight/src/hero.c
@@ -97,6 +97,8 @@ static void anim_update_state(int s);
static void invulnerable_tick(void);
static void respawn_tick(void);
static void die_from_hazard(void);
+static void slash_fixed(void);
+static void slash_hits(void);
void hero_die(void);
static bool can_exit_no_input(void) { return !g_hero.doing_hazard_respawn && !g_hero.cs.dead; }
@@ -329,11 +331,13 @@ static void terrain_thunk(void) {
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) {
+ /* (a box cast, as three rays across the box: the nearest ground; not a NonThunker's) */
+ PhysHit best = {0}, ph;
+ best.dist = 1e9f;
+ for (int i = -1; i <= 1; i++)
+ if (phys_ray(ox + (dy ? i * hs : 0), oy + (dx ? i * hs : 0), dx, dy, len + hs, CF_SOLID, &ph) && ph.dist < best.dist)
+ best = ph;
+ if (best.dist < 1e9f && !(phys_col_flags(best.col) & CF_NONTHUNKER)) {
h->thunk_hit = true;
if (h->thunk_dir == ATK_NORMAL) {
if (h->cs.facing_right) hero_recoil_left();
@@ -772,6 +776,7 @@ void hero_fixed(uint32_t keys) {
h->prev_keys = h->keys, h->keys = keys;
h->time_since_level += DT;
fixed_update();
+ slash_fixed();
body_step(&h->body, DT);
for (int i = 0; i < h->body.nevents; i++) {
const BodyEvent *e = &h->body.events[i];
@@ -779,6 +784,7 @@ void hero_fixed(uint32_t keys) {
else if (e->kind == EV_STAY) on_stay(e);
else on_exit(e);
}
+ slash_hits();
}
void hero_update(void) {
@@ -848,15 +854,51 @@ void slash_cancel(void) {
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++;
+/* NailSlash.FixedUpdate: the hit shape on from the second step to the sixth */
+static void slash_fixed(void) {
+ if (!sl.slashing) return;
+ if (sl.step_counter == 1) {
+ sl.poly = true;
+ obj_swing_start(); /* (LimitSendEvents: its collider switched on) */
+ }
+ 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++;
+}
+
+/* the slash's PolygonCollider2D (local, before its scale) */
+static const float slash_poly[4][12] = {
+ {-1.2709147f, 0.7413744f, -1.9154043f, 0.3402300f, -2.0418284f, -0.1750279f, -1.6737577f, -0.4435550f, -0.0747072f,
+ -0.6419125f, 0.0078668f, 0.9683739f},
+ {-1.2172120f, 0.9806359f, -2.3899105f, 0.5705993f, -2.6464114f, -0.0792437f, -2.1236799f, -0.5379019f, -0.3672335f,
+ -0.6931571f, -0.2434342f, 1.0901221f},
+ {-0.4705164f, 1.4424964f, 0.4715460f, 1.4633876f, 1.0817832f, 0.6738139f, 1.1484641f, -0.8903970f, -1.2853814f,
+ -0.8659905f, -1.0722543f, 0.6188976f},
+ {1.2783164f, 0.6065824f, 1.1190680f, -0.8765929f, 0.5875434f, -1.6216662f, -0.4472086f, -1.6460726f, -1.0696145f,
+ -0.7312644f, -1.3820535f, 0.6370943f},
+};
+
+/* the slash's trigger: what it touches is hit (the damages_enemy FSM), and the Knight recoils or bounces off (NailSlash) */
+static void slash_hits(void) {
+ if (!sl.poly) 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];
+ float pts[12];
+ for (int i = 0; i < 6; i++) {
+ pts[2 * i] = h->body.x + k * (s->x + s->sx * slash_poly[sl.kind][2 * i]);
+ pts[2 * i + 1] = h->body.y + s->y + s->sy * slash_poly[sl.kind][2 * i + 1];
}
+ float direction = sl.kind == SLASH_UP ? 90 : sl.kind == SLASH_DOWN ? 270 : h->cs.facing_right ? 0 : 180;
+ int fl = obj_nail(pts, 6, direction);
+ if (direction == 0 && (fl & HB_RECOIL)) hero_recoil_left();
+ else if (direction == 180 && (fl & HB_RECOIL)) hero_recoil_right();
+ else if (direction == 90 && (fl & HB_RECOIL)) hero_recoil_down();
+ else if (direction == 270 && (fl & HB_BOUNCE)) hero_bounce();
+}
+
+void slash_tick(void) {
if (!sl.shown) return;
sl.anim.events = 0;
anim_update(&sl.anim, DT);
diff --git a/games/hollowknight/src/hk.h b/games/hollowknight/src/hk.h
index b4cfde4a..c0e416cc 100644
--- a/games/hollowknight/src/hk.h
+++ b/games/hollowknight/src/hk.h
@@ -80,7 +80,7 @@ typedef struct {
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
+#define MAX_GROUPS 256
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
@@ -148,10 +148,11 @@ 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);
+void sprite_inst_rot(int sprite, float x, float y, float z, float sx, float sy, float degrees, 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 };
+enum { CF_TERRAIN = 1, CF_STEEP = 2, CF_NONSLIDER = 4, CF_NOHARDLAND = 8, CF_ROOF = 16, CF_SOLID = 32, CF_NONTHUNKER = 64 };
typedef struct {
float dist, x, y, nx, ny; /* where, and the ground's normal there */
int col;
@@ -160,6 +161,8 @@ typedef struct {
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);
+void phys_collider_enable(int col, bool on); /* (a breakable's: off when it breaks) */
+void phys_colliders_reset(void); /* all on (a room starts) */
/* a box and a convex polygon (n points, x y pairs): do they overlap? */
bool box_meets_shape(float x0, float y0, float x1, float y1, const float *pts, int n);
diff --git a/games/hollowknight/src/obj.c b/games/hollowknight/src/obj.c
new file mode 100644
index 00000000..165f32be
--- /dev/null
+++ b/games/hollowknight/src/obj.c
@@ -0,0 +1,189 @@
+/* The room's objects that the Knight acts on (tools/ents.py: ENT_OBJ and the records after each): what the nail hits,
+ * breakables and the debris they fling. */
+#include <math.h>
+#include "game.h"
+
+#define DT 0.02f
+#define MAX_OBJS 64
+#define MAX_PIECES 24
+
+typedef struct {
+ uint8_t kind, state;
+ uint16_t ent; /* its record */
+} Obj;
+static Obj objs[MAX_OBJS];
+static int nobjs;
+static uint32_t swing_hit[MAX_OBJS / 32]; /* (LimitSendEvents: an object is hit once a swing) */
+
+enum { BR_WHOLE, BR_BROKEN };
+
+/* ---------------------------------------------------------------- Unity's Random (an xorshift here) */
+static uint32_t rng = 0x2545F491u;
+float rand_range(float lo, float hi) {
+ rng ^= rng << 13, rng ^= rng >> 17, rng ^= rng << 5;
+ return lo + (hi - lo) * (float)(rng >> 8) * (1.0f / 16777216.0f);
+}
+
+static const Ent *ent_at(int i) {
+ int n;
+ return &room_ents(&n)[i];
+}
+
+/* ---------------------------------------------------------------- debris (Rigidbody2D, ObjectBounce, SpinSelf) */
+typedef struct {
+ int16_t sprite;
+ uint8_t layer, steps;
+ uint16_t order;
+ bool on, resting, spin;
+ float x, y, z, vx, vy, ang, w; /* (w: degrees a second) */
+ float gravity, bounce, spin_factor, mirror, speed;
+} Piece;
+static Piece pieces[MAX_PIECES];
+
+static void piece_fling(const Ent *p, float ox, float oy, float angle_offset, float amin, float amax, float smin, float smax,
+ float mult) {
+ Piece *q = NULL;
+ for (int i = 0; i < MAX_PIECES && !q; i++)
+ if (!pieces[i].on) q = &pieces[i];
+ if (!q) return; /* (all in use: this one is not seen) */
+ q->on = true, q->resting = false, q->steps = 0;
+ q->sprite = (int16_t)p->s0, q->layer = p->group, q->order = p->a;
+ q->x = ox + p->x0, q->y = oy + p->y0, q->z = p->y1;
+ q->spin = p->flags & 1;
+ /* (Break turns it by the angle offset; SpinSelf.Start, after, at random) */
+ q->ang = q->spin ? rand_range(0, 360) : p->x1 + angle_offset;
+ q->gravity = p->p0, q->bounce = p->p1, q->spin_factor = p->p2, q->mirror = p->p3;
+ float a = rand_range(amin, amax) * (float)M_PI / 180, s = rand_range(smin, smax) * mult;
+ q->vx = cosf(a) * s, q->vy = sinf(a) * s;
+ q->w = 0, q->speed = s;
+}
+
+static void pieces_tick(void) {
+ for (int i = 0; i < MAX_PIECES; i++) {
+ Piece *q = &pieces[i];
+ if (!q->on || q->resting) continue;
+ /* SpinSelf: one push of torque on its second step (a polygon of about a unit: this many degrees a second) */
+ if (q->spin && q->steps == 1) q->w = q->vx * q->spin_factor * 60;
+ if (q->steps < 255) q->steps++;
+ q->vy -= 60 * q->gravity * DT;
+ q->w *= 1 - 0.05f * DT;
+ float dx = q->vx * DT, dy = q->vy * DT, len = sqrtf(dx * dx + dy * dy);
+ PhysHit hit;
+ if (len > 0 && phys_ray(q->x, q->y, dx / len, dy / len, len + 0.05f, CF_TERRAIN, &hit)) {
+ q->x = hit.x + hit.nx * 0.05f, q->y = hit.y + hit.ny * 0.05f;
+ float speed = sqrtf(q->vx * q->vx + q->vy * q->vy);
+ if (q->bounce >= 0 && speed > 1) {
+ /* ObjectBounce: off the normal, at its speed times the bounce factor */
+ float d = q->vx * hit.nx + q->vy * hit.ny;
+ float rx = q->vx - 2 * d * hit.nx, ry = q->vy - 2 * d * hit.ny, k = speed * q->bounce * rand_range(0.8f, 1.2f) / speed;
+ q->vx = rx * k, q->vy = ry * k;
+ q->w *= 0.5f;
+ if (hit.ny > 0.5f && fabsf(q->vy) < 1.5f) q->resting = true;
+ } else if (hit.ny > 0.5f)
+ q->resting = true;
+ else
+ q->vx = 0;
+ } else
+ q->x += dx, q->y += dy;
+ q->ang += q->w * DT;
+ if (q->y < -20) q->on = false;
+ }
+}
+
+static void pieces_draw(void) {
+ for (int i = 0; i < MAX_PIECES; i++) {
+ const Piece *q = &pieces[i];
+ if (!q->on) continue;
+ Inst in;
+ sprite_inst_rot(q->sprite, q->x, q->y, q->z, q->mirror, 1, q->ang, 0, &in);
+ gfx_actor(&in, SORT_KEY(q->layer, (int)q->order - 32768));
+ }
+}
+
+/* ---------------------------------------------------------------- Breakable */
+/* SetStaticPartsActivation (broken) */
+static void breakable_set_broken(const Obj *o, const Ent *e) {
+ group_fade(e->group, 0, 0); /* (the whole renderer and parts off) */
+ if (e->group2) group_fade(e->group2, 1, 0); /* (the remnants on) */
+ for (int c = e->a; c < e->a + e->s0; c++) phys_collider_enable(c, false);
+ if (e->y1 > 0) world_send_hit((int)e->y1 - 1); /* (its hitEventReciever) */
+ (void)o;
+}
+
+static void breakable_enter(Obj *o, const Ent *e) {
+ if (e->group2) group_fade(e->group2, 0, 0); /* (Start: the remnants off) */
+ if (persist_get(e->persist)) {
+ o->state = BR_BROKEN;
+ breakable_set_broken(o, e);
+ }
+}
+
+/* Breakable.Hit: which way the debris flies, then Break */
+static void breakable_hit(Obj *o, const Ent *e, float direction) {
+ if (o->state == BR_BROKEN) return;
+ int dir = cardinal(direction);
+ float angle_offset = e->p2, amin, amax, mult = 1;
+ switch (dir) {
+ case 2: angle_offset = -angle_offset, amin = 120, amax = 160; break;
+ case 0: amin = 30, amax = 70; break;
+ case 1: angle_offset = 0, amin = 70, amax = 110, mult = 1.5f; break;
+ default: angle_offset = 0, amin = 160, amax = 380; break;
+ }
+ o->state = BR_BROKEN;
+ breakable_set_broken(o, e);
+ persist_set(e->persist);
+ const Ent *p = e + 1 + e->s1;
+ for (int i = 0; i < (int)e->p3; i++, p++)
+ if (p->type == ENT_PIECE) piece_fling(p, e->x0, e->y0, angle_offset, amin, amax, e->p0, e->p1, mult);
+ cam_shake(SHAKE_ENEMY_KILL);
+}
+
+/* ---------------------------------------------------------------- the room */
+void obj_enter(void) {
+ nobjs = 0;
+ phys_colliders_reset();
+ memset(pieces, 0, sizeof pieces);
+ memset(swing_hit, 0, sizeof swing_hit);
+ int n;
+ const Ent *es = room_ents(&n);
+ for (int i = 0; i < n && nobjs < MAX_OBJS; i++) {
+ if (es[i].type != ENT_OBJ) continue;
+ Obj *o = &objs[nobjs++];
+ o->kind = es[i].flags, o->state = 0, o->ent = (uint16_t)i;
+ if (o->kind == OK_BREAKABLE) breakable_enter(o, &es[i]);
+ }
+}
+
+void obj_tick(void) { pieces_tick(); }
+
+void obj_draw(void) { pieces_draw(); }
+
+/* ---------------------------------------------------------------- the nail */
+void obj_swing_start(void) { memset(swing_hit, 0, sizeof swing_hit); }
+
+/* the slash's shape this step (world, convex): what it touches is hit (once a swing), the direction (degrees) the
+ * blow goes; -> what the Knight does (HB_*: bounce, recoil) */
+int obj_nail(const float *pts, int npts, float direction) {
+ int out = 0;
+ for (int k = 0; k < nobjs; k++) {
+ Obj *o = &objs[k];
+ const Ent *e = ent_at(o->ent);
+ bool touched = false;
+ for (int j = 0; j < e->s1; j++) {
+ const Ent *b = e + 1 + j;
+ if (b->type != ENT_BOX || !box_meets_shape(b->x0, b->y0, b->x1, b->y1, pts, npts)) continue;
+ touched = true;
+ out |= b->flags;
+ }
+ if (!touched || (swing_hit[k >> 5] >> (k & 31) & 1)) continue;
+ swing_hit[k >> 5] |= 1u << (k & 31);
+ if (o->kind == OK_BREAKABLE) breakable_hit(o, e, direction);
+ }
+ return out;
+}
+
+/* DirectionUtils.GetCardinalDirection: 0 right, 1 up, 2 left, 3 down */
+int cardinal(float degrees) {
+ int d = (int)lrintf(degrees / 90.0f) % 4;
+ return d < 0 ? d + 4 : d;
+}
diff --git a/games/hollowknight/src/phys.c b/games/hollowknight/src/phys.c
index 57cc342d..b4398763 100644
--- a/games/hollowknight/src/phys.c
+++ b/games/hollowknight/src/phys.c
@@ -20,6 +20,15 @@ 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 uint8_t g_col_off[256 / 8]; /* colliders switched off (a broken wall's) */
+
+void phys_collider_enable(int col, bool on) {
+ if (col <= 0 || col >= 256) return;
+ if (on) g_col_off[col >> 3] &= (uint8_t)~(1 << (col & 7));
+ else g_col_off[col >> 3] |= (uint8_t)(1 << (col & 7));
+}
+
+void phys_colliders_reset(void) { memset(g_col_off, 0, sizeof g_col_off); }
static void ground_init(void) {
if (g_room_ground == g_room.id) return;
@@ -76,7 +85,7 @@ static int gather(float x0, float y0, float x1, float y1, uint8_t mask, Cand *ou
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;
+ if (!(g_cols[col] & mask) || (g_col_off[col >> 3] >> (col & 7) & 1) || 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;
diff --git a/games/hollowknight/src/world.c b/games/hollowknight/src/world.c
index 34adf1a5..dfbb10b4 100644
--- a/games/hollowknight/src/world.c
+++ b/games/hollowknight/src/world.c
@@ -4,41 +4,50 @@
#define DT 0.02f
/* ---------------------------------------------------------------- render groups: iTweenFadeTo */
+#define MAX_FADES 16
static struct {
+ uint8_t group; /* (0: free) */
float from, to, t, time;
- bool on;
-} fades[MAX_GROUPS];
+} fades[MAX_FADES];
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) {
+ /* (a new fade on a group replaces its old one) */
+ int k = -1;
+ for (int i = 0; i < MAX_FADES && k < 0; i++)
+ if (fades[i].group == g) k = i;
+ for (int i = 0; i < MAX_FADES && k < 0; i++)
+ if (!fades[i].group) k = i;
+ if (time <= 0 || k < 0) {
g_group_alpha[g] = (uint8_t)(alpha * 255 + 0.5f);
- fades[g].on = false;
+ if (k >= 0 && fades[k].group == g) fades[k].group = 0;
+ return;
}
+ fades[k].group = (uint8_t)g;
+ fades[k].from = g_group_alpha[g] / 255.0f, fades[k].to = alpha, fades[k].t = 0, fades[k].time = time;
}
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;
+ for (int i = 0; i < MAX_FADES; i++) {
+ int g = fades[i].group;
+ if (!g) continue;
+ fades[i].t += DT;
+ float k = fades[i].t >= fades[i].time ? 1 : fades[i].t / fades[i].time;
+ float a = fades[i].from + (fades[i].to - fades[i].from) * k;
g_group_alpha[g] = (uint8_t)(a * 255 + 0.5f);
- if (k >= 1) fades[g].on = false;
+ if (k >= 1) fades[i].group = 0;
}
}
/* ---------------------------------------------------------------- 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) {
+bool persist_get(int i) { return i != NO_PERSIST && (g_pd.persist[i >> 3] >> (i & 7) & 1); }
+void persist_set(int i) {
if (i != NO_PERSIST) g_pd.persist[i >> 3] |= (uint8_t)(1 << (i & 7));
}
@@ -62,6 +71,13 @@ static void mask_idle(const Ent *e, EntState *s) {
s->state = M_IDLE;
}
+/* a simple mask's Idle: HIT fades it */
+static void mask_hit(const Ent *e, EntState *s) {
+ if (e->flags != MK_SIMPLE || s->state != M_IDLE) return;
+ group_fade(e->group, 0, e->p0);
+ s->state = M_DONE;
+}
+
static void mask_trigger(const Ent *e, EntState *s, int kind) {
float t = e->p0;
switch (e->flags) {
@@ -86,11 +102,8 @@ static void mask_trigger(const Ent *e, EntState *s, int kind) {
}
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;
- }
+ case MK_SIMPLE: /* (its trigger sends HIT) */
+ if ((e->p2 == 0 && kind == EV_ENTER) || (e->p2 == 1 && kind == EV_STAY)) mask_hit(e, s);
break;
}
}
@@ -109,6 +122,7 @@ void world_enter(void) {
else es[i].state = M_PAUSE;
if (e[i].group2) group_fade(e[i].group2, 0, 0); /* (Pause: the inverse mask hidden) */
}
+ obj_enter();
}
/* (Pause's WaitForHeroInPosition: the masks start as the Knight is placed; its Wait only counts when it was placed
@@ -122,10 +136,21 @@ void world_hero_in_position(void) {
if (e[i].type == ENT_MASK && es[i].state == M_PAUSE) mask_idle(&e[i], &es[i]);
}
+/* an object's FSM sent HIT to another (a breakable's hitEventReciever) */
+void world_send_hit(int i) {
+ int n;
+ const Ent *e = room_ents(&n);
+ if (i < 0 || i >= n || i >= MAX_ENTS) return;
+ if (e[i].type == ENT_MASK) mask_hit(&e[i], &es[i]);
+}
+
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) { fades_tick(); }
+void world_tick(void) {
+ obj_tick();
+ fades_tick();
+}
diff --git a/games/hollowknight/tools/actors.py b/games/hollowknight/tools/actors.py
index b524d46a..8b30b828 100644
--- a/games/hollowknight/tools/actors.py
+++ b/games/hollowknight/tools/actors.py
@@ -58,3 +58,18 @@ def build():
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, clips
+
+
+def unity_sprites(keys):
+ """Unity sprites objects show as actors (ents.Sprites: debris...) -> sprite records like build()'s; each at its
+ object's scale."""
+ out = []
+ for level, exts, fid, pid, scale in keys:
+ s = unity.sprite(level, list(exts), fid, pid)
+ img = unity.sprite_image(s)
+ wu, hu = s.w / s.ppu * scale, s.h / s.ppu * scale
+ w, h = max(1, round(wu * K0)), max(1, round(hu * K0))
+ arr = np.asarray(img.resize((w, h), Image.BOX)).copy()
+ out.append({"key": (level, fid, pid), "job": art.ImageJob(arr, "piece/%s" % s.name),
+ "lx": -s.px * wu, "ty": (1 - s.py) * hu, "tu": wu / w, "tv": hu / h})
+ return out
diff --git a/games/hollowknight/tools/coll.py b/games/hollowknight/tools/coll.py
index 7ecfa4b5..78ae9267 100644
--- a/games/hollowknight/tools/coll.py
+++ b/games/hollowknight/tools/coll.py
@@ -8,7 +8,7 @@ SOLID_LAYERS = {8, 25} # Terrain, Soft Terrain (the Knight collides wit
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
+CF_TERRAIN, CF_STEEP, CF_NONSLIDER, CF_NOHARDLAND, CF_ROOF, CF_SOLID, CF_NONTHUNKER = 1, 2, 4, 8, 16, 32, 64
def _world(o, pts, off):
@@ -84,12 +84,26 @@ def _unit_edges(edges):
return out
+def path_key(d):
+ """A sort key that keeps every object's subtree together: (name, id) from the root down."""
+ by = {o["id"]: o for o in d["objects"]}
+ keys = {}
+
+ def key(o):
+ k = keys.get(o["id"])
+ if k is None:
+ p = by.get(o["parent"])
+ k = keys[o["id"]] = (key(p) if p else ()) + ((o["name"], o["id"]),)
+ return k
+ return key
+
+
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]
+ """-> (solid tiles of the tilemap, segments [(x0, y0, x1, y1, collider)], colliders [flags], each collider's object
+ id); collider 0 is the tilemap's. An object's subtree has consecutive colliders (subtree_colliders)."""
+ segs, cols, owners = [], [CF_SOLID | CF_TERRAIN], [0]
tm_edges = []
- for o in d["objects"]:
+ for o in sorted(d["objects"], key=path_key(d)):
if not o["active"] or o["layer"] not in SOLID_LAYERS:
continue
if "TileMap Render Data/" in o["path"]:
@@ -133,8 +147,11 @@ def room(d, w, h):
flags |= CF_NOHARDLAND
if "Roof" in scripts:
flags |= CF_ROOF
+ if any(c.get("class") == "NonThunker" and (c.get("v") or {}).get("active", True) for c in o["c"]):
+ flags |= CF_NONTHUNKER
ci = len(cols)
cols.append(flags)
+ owners.append(o["id"])
for pts, closed in chains:
pts = _merge(pts, closed)
n = len(pts)
@@ -152,7 +169,24 @@ def room(d, w, h):
got = 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
+ assert len(cols) <= 256, len(cols)
+ return solid, segs, cols, owners
+
+
+def subtree_colliders(d, owners, oid):
+ """The colliders of an object and everything under it -> (first, count)."""
+ by = {o["id"]: o for o in d["objects"]}
+ ids = set()
+ todo = [oid]
+ while todo:
+ i = todo.pop()
+ ids.add(i)
+ todo += by[i].get("children", [])
+ idx = [k for k, ow in enumerate(owners) if k and ow in ids]
+ if not idx:
+ return 0, 0
+ assert idx == list(range(idx[0], idx[-1] + 1)), idx
+ return idx[0], len(idx)
def grid(segs, w, h):
diff --git a/games/hollowknight/tools/ents.py b/games/hollowknight/tools/ents.py
index 32d22452..074894a9 100644
--- a/games/hollowknight/tools/ents.py
+++ b/games/hollowknight/tools/ents.py
@@ -5,8 +5,13 @@ import struct
import numpy as np
# record types (src/game.h: ENT_*)
-ENT_CAMLOCK, ENT_GATE, ENT_HAZARD_MARKER, ENT_RESPAWN, ENT_HAZARD_TRIGGER, ENT_MASK, ENT_DAMAGE, ENT_SHAPE, ENT_BOX = \
- 1, 2, 3, 4, 5, 6, 7, 8, 9
+ENT_CAMLOCK, ENT_GATE, ENT_HAZARD_MARKER, ENT_RESPAWN, ENT_HAZARD_TRIGGER, ENT_MASK, ENT_DAMAGE, ENT_SHAPE, ENT_BOX, \
+ ENT_OBJ, ENT_PIECE = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
+# objects (ENT_OBJ's flags: src/obj.c)
+OK_BREAKABLE = 1
+# the layers the nail's slashes touch (Physics2D's collision matrix, layer 17 Attack)
+ATTACK_HITS = {3, 6, 7, 8, 11, 12, 17, 19, 20, 21, 25, 31}
+MAX_GROUPS = 256
# masks (the unmasker, remasker and remasker_inverse FSMs)
MK_SECRET, MK_REMASK, MK_SIMPLE = 1, 2, 4
# flags
@@ -44,6 +49,46 @@ class Strings:
return struct.pack("<I", len(self.list)) + b"".join(struct.pack("<I", o) for o in offs) + bytes(body)
+class Sprites:
+ """Unity sprites objects show as actors (debris...): pack.py makes them like the actors' frames, after those."""
+ def __init__(self):
+ self.list, self.index, self.base = [], {}, 0
+
+ def id(self, d, ref, scale):
+ key = (d["level"], tuple(d["externals"]), ref[0], ref[1], round(scale, 3))
+ if key not in self.index:
+ self.index[key] = len(self.list)
+ self.list.append(key)
+ return self.base + self.index[key]
+
+
+def _colliders(o):
+ return [c for c in o["c"] if c["type"] in ("BoxCollider2D", "PolygonCollider2D", "CircleCollider2D", "EdgeCollider2D")
+ and c.get("v") and c["v"].get("m_Enabled", 1)]
+
+
+HB_BOUNCE, HB_RECOIL = 1, 2
+
+
+def _hit_boxes(o, by, depth=2):
+ """Where the nail hits an object: its colliders, and its children's and grandchildren's (HitTaker looks three levels
+ up from what it touched), on the layers the slashes touch -> [(box, HB_* flags)]: whether a down slash bounces off
+ it, whether a slash recoils the Knight (NailSlash: enemies, attacks, interactive objects without NonBouncer)."""
+ out = []
+ if o["active"] and o["layer"] in ATTACK_HITS:
+ nb = any(c.get("class") == "NonBouncer" and (c.get("v") or {}).get("active", True) for c in o["c"])
+ fl = 0
+ if not nb and o["layer"] in (11, 17, 19):
+ fl |= HB_BOUNCE
+ if not nb and o["layer"] == 11:
+ fl |= HB_RECOIL
+ out += [(b, fl) for b in (_box(o, c) for c in _colliders(o) if c["type"] != "EdgeCollider2D") if b]
+ if depth:
+ for ch in o.get("children", []):
+ out += _hit_boxes(by[ch], by, depth - 1)
+ return out
+
+
def _box(o, c):
"""A collider's world bounds (box colliders; others by their points)."""
v = c["v"]
@@ -184,9 +229,43 @@ def _mask(o, f, objs_by_id):
return None
-def room(d, rooms, strings, persist, name):
- """-> (packed records, {object id: render group})."""
+def _pieces(d, o, ids, by_id, sprites):
+ """Debris an object flings (inactive children with a sprite and a Rigidbody2D) -> ENT_PIECE records: where each is
+ from the object, its sprite, how it falls, bounces and spins."""
+ import scene
+ out = []
+ for pid in ids:
+ q = by_id.get(pid)
+ if q is None:
+ continue
+ sr = next((c for c in q["c"] if c["type"] == "SpriteRenderer" and (c.get("v") or {}).get("m_Sprite")), None)
+ if sr is None:
+ continue
+ v = sr["v"]
+ m = np.array(q["m3"]).reshape(3, 3)
+ sx, sy = float(np.hypot(m[0, 0], m[1, 0])), float(np.hypot(m[0, 1], m[1, 1]))
+ mirror = -1.0 if np.linalg.det(m[:2, :2]) < 0 else 1.0
+ rot = float(np.degrees(np.arctan2(m[1, 0], m[0, 0]))) if mirror > 0 else float(np.degrees(np.arctan2(-m[1, 0], -m[0, 0])))
+ rb = next((c.get("v") or {} for c in q["c"] if c["type"] == "Rigidbody2D"), {})
+ ob = next((c.get("v") or {} for c in q["c"] if c.get("class") == "ObjectBounce"), None)
+ sp = next((c.get("v") or {} for c in q["c"] if c.get("class") == "SpinSelf"), None)
+ sid = sprites.id(d, v["m_Sprite"], max(sx, sy))
+ dx, dy = q["pos"][0] - o["pos"][0], q["pos"][1] - o["pos"][1]
+ layer = scene.layer_index(v.get("m_SortingLayerID", 0))
+ out.append(rec(ENT_PIECE, 1 if sp is not None else 0, (dx, dy, rot, q["pos"][2]),
+ (rb.get("m_GravityScale", 1), ob.get("bounceFactor", 0) if ob else -1,
+ sp.get("spinFactor", -7.5) if sp else 0, mirror),
+ a=v.get("m_SortingOrder", 0) + 32768, group=layer, s0=sid))
+ return out
+
+
+def room(d, rooms, strings, persist, name, sprites=None, owners=None):
+ """-> (packed records, {object id: render group}). owners: each collider's object (coll.room); sprites: where the
+ objects' own sprites go (Sprites)."""
+ import coll
+ sprites = sprites or Sprites()
recs = []
+ rec_of, receivers = {}, [] # (an object's record; the records that send HIT to another object's)
groups = {}
marker_index = {}
objs = [o for o in d["objects"] if o["active"]]
@@ -222,6 +301,7 @@ def room(d, rooms, strings, persist, name):
box = _trigger(o) or (0, 0, 0, 0)
if m:
kind, fade, pause, p2, p3, inverse = m
+ rec_of[o["id"]] = len(recs)
g = new_group(o["id"])
g2 = new_group(inverse) if inverse else 0
persistent = any(c.get("class") == "PersistentBoolItem" for c in o["c"])
@@ -229,6 +309,35 @@ def room(d, rooms, strings, persist, name):
persist=persist.id(name, o["path"]) if persistent else NO_PERSIST))
recs += _more_boxes(o)
classes = {c.get("class") for c in o["c"]}
+ br = next((c for c in o["c"] if c.get("class") == "Breakable" and c.get("v") is not None), None)
+ if br is not None:
+ v = br["v"]
+ z = o["pos"][2]
+ hits = _hit_boxes(o, by_id)
+ if hits and v.get("inertForegroundThreshold", -1) <= z <= v.get("inertBackgroundThreshold", 1):
+ g = new_group(o["id"])
+ rem = [r[1] for r in v.get("remnantParts") or [] if r and r[1] in by_id]
+ g2 = 0
+ if rem:
+ ngroups[0] += 1
+ g2 = ngroups[0]
+ for r in rem:
+ subtree(r, g2)
+ c0, cn = coll.subtree_colliders(d, owners, o["id"]) if owners else (0, 0)
+ if rem and owners and any(coll.subtree_colliders(d, owners, r)[1] for r in rem):
+ print("ents: %s: remnant colliders not handled" % o["path"])
+ debris = [r[1] for r in v.get("debrisParts") or [] if r]
+ pieces = _pieces(d, o, debris, by_id, sprites)
+ sign = -1.0 if o.get("lscale", [1])[0] < 0 else 1.0
+ persistent = any(c.get("class") == "PersistentBoolItem" for c in o["c"])
+ if v.get("hitEventReciever"):
+ receivers.append((len(recs), v["hitEventReciever"][1]))
+ recs.append(rec(ENT_OBJ, OK_BREAKABLE, (o["pos"][0], o["pos"][1], o["pos"][2], 0),
+ (v.get("flingSpeedMin", 10), v.get("flingSpeedMax", 17), v.get("angleOffset", -60) * sign,
+ len(pieces)), a=c0, group=g, group2=g2,
+ persist=persist.id(name, o["path"]) if persistent else NO_PERSIST, s0=cn, s1=len(hits)))
+ recs += [rec(ENT_BOX, fl, box=b) for b, fl in hits]
+ recs += pieces
dh = [c for c in o["c"] if c.get("class") == "DamageHero"]
if dh and not classes & {"HealthManager", "StalactiteControl"}:
# a hazard (spikes, acid): its colliders' outlines, as boxes or as shapes after it
@@ -286,5 +395,14 @@ def room(d, rooms, strings, persist, name):
continue
recs.append(rec(ENT_HAZARD_TRIGGER, box=box, a=marker_index[target]))
recs += _more_boxes(o)
- assert ngroups[0] < 64, ngroups[0]
+ # (an object that sends HIT to another: that one's record + 1 in its box's y1)
+ for i, target in receivers:
+ if target in rec_of:
+ b = bytearray(recs[i])
+ struct.pack_into("<f", b, 20, rec_of[target] + 1)
+ recs[i] = bytes(b)
+ else:
+ print("ents: %s: HIT receiver %d has no record" % (name, target))
+ assert ngroups[0] < MAX_GROUPS, ngroups[0]
+ assert len(recs) <= 320, len(recs) # (src/game.h: MAX_ENTS)
return recs, groups
diff --git a/games/hollowknight/tools/pack.py b/games/hollowknight/tools/pack.py
index 62beb42f..08dbcb74 100644
--- a/games/hollowknight/tools/pack.py
+++ b/games/hollowknight/tools/pack.py
@@ -10,6 +10,19 @@ 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()
+SPRITES = ents.Sprites()
+ROOM_DATA = {} # name -> (coll.room's, ents.room's)
+
+
+def room_data(name):
+ """A room's ground and objects (once: the objects' sprites go into SPRITES)."""
+ if name not in ROOM_DATA:
+ d = unity.scene(name)
+ st = scene.settings(d)
+ w, h = st["size"] if st["size"] else (40, 24)
+ cr = coll.room(d, w, h)
+ ROOM_DATA[name] = (cr, ents.room(d, ROOMS, STRINGS, PERSIST, name, SPRITES, cr[3]))
+ return ROOM_DATA[name]
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}
@@ -169,7 +182,7 @@ 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)
+ (solid, segs, cols, _), (erecs, groups) = room_data(name)
for it in keep:
it.group = groups.get(it.obj["id"], 0)
tints = [(255, 255, 255, 255)]
@@ -202,7 +215,6 @@ def room_blobs(name, keep, st, tex_id):
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)
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(erecs), 0, 0) + lut
@@ -276,6 +288,11 @@ def main():
print("variants", len(variants), "%.0fs" % (time.time() - t0), flush=True)
jobs = [art.Job(v) for v in variants]
sprites, clips = actors.build()
+ # the rooms' objects, and the sprites they show (after the actors')
+ SPRITES.base = len(sprites)
+ for r in ROOMS:
+ room_data(r)
+ sprites += actors.unity_sprites(SPRITES.list)
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:
diff --git a/games/hollowknight/tools/unity.py b/games/hollowknight/tools/unity.py
index b11874b3..6a9dd00f 100644
--- a/games/hollowknight/tools/unity.py
+++ b/games/hollowknight/tools/unity.py
@@ -90,15 +90,31 @@ def clean(x):
def _dump(name):
level = "level%d" % scene_index()[name]
- lv = asset_file(level)
+ return _dump_objects(asset_file(level), name, level)
+
+
+def _dump_objects(lv, name, level, root=None):
+ """The file's GameObjects (or those under the GameObject root), as scene() gives them."""
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()
+ if root is None:
+ 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()
+ else:
+ # the subtree: up to its root's transform (for world matrices), then down through the children
+ todo = [root]
+ while todo:
+ gpid = todo.pop()
+ g = gos[gpid] = objs[gpid].read_typetree()
+ for c in g["m_Component"]:
+ o = objs.get(c["component"]["m_PathID"])
+ if o is not None and o.type.name in ("Transform", "RectTransform"):
+ tr[o.path_id] = t = o.read_typetree()
+ todo += [objs[ch["m_PathID"]].read_typetree()["m_GameObject"]["m_PathID"] for ch in t["m_Children"]]
wm = {}
sys.setrecursionlimit(20000)
@@ -227,6 +243,31 @@ def scene(name):
return d
[email protected]_cache(maxsize=None)
+def prefab(path, gpid):
+ """A prefab (a GameObject of an asset file and its children) like a scene (cached as JSON in tools/cache)."""
+ os.makedirs(CACHE, exist_ok=True)
+ p = os.path.join(CACHE, "prefab_%s_%d.json" % (os.path.basename(path), gpid))
+ if os.path.exists(p):
+ return json.load(open(p))
+ with in_data():
+ d = _dump_objects(asset_file(path), "%s:%d" % (path, gpid), path, gpid)
+ json.dump(d, open(p, "w"), separators=(",", ":"))
+ return d
+
+
+def find_objects(path, names):
+ """GameObjects of an asset file by name -> [(name, pid)]."""
+ f = asset_file(path)
+ out = []
+ for pid, o in f.objects.items():
+ if o.type.name == "GameObject":
+ n = S(o.read_typetree()["m_Name"])
+ if n in names:
+ out.append((n, pid))
+ return out
+
+
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):