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: game text, dialogue box and prompt markers
Mason Chen27bb56ca15be
diff --git a/games/hollowknight/Makefile b/games/hollowknight/Makefileindex f360e21d..4af86547 100644--- a/games/hollowknight/Makefile+++ b/games/hollowknight/Makefile@@ -9,7 +9,7 @@ CC = arm-none-eabi-gccNWLINK ?= npx --yes -- [email protected]STRIP ?= arm-none-eabi-strip --strip-unneededBUILD_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/obj.c src/enemy.c src/hud.c src/spell.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/enemy.c src/hud.c src/spell.c src/text.c src/lzma/LzmaDec.cSRC = $(GAME) src/plat_eadk.c src/main.cHEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.hdiff --git a/games/hollowknight/src/data.bin b/games/hollowknight/src/data.binindex 1093dc72..1a9a716d 100644Binary files a/games/hollowknight/src/data.bin and b/games/hollowknight/src/data.bin differdiff --git a/games/hollowknight/src/data.h b/games/hollowknight/src/data.hindex 4c70b5bd..675b4611 100644--- a/games/hollowknight/src/data.h+++ b/games/hollowknight/src/data.h@@ -12,6 +12,8 @@#define SEC_SPR 9#define SEC_CLIP 10#define SEC_STR 11+#define SEC_TEXT 12+#define SEC_FONT 13#define NUM_ROOMS 41#define ROOM_TUTORIAL_01 0#define ROOM_TOWN 1@@ -181,6 +183,38 @@#define CLIP_GEO_MED_AIR 124#define CLIP_GEO_LARGE_IDLE 125#define CLIP_GEO_LARGE_AIR 126-#define SPRITE_HERO_LIGHT 534-#define SPRITE_DIGIT0 715+#define CLIP_DIALOGUE_ARROW_UP 127+#define CLIP_DIALOGUE_ARROW_DOWN 128+#define CLIP_DIALOGUE_STOP_UP 129+#define CLIP_DIALOGUE_STOP_DOWN 130+#define CLIP_DIALOGUE_FLEUR_TOP_UP 131+#define CLIP_DIALOGUE_FLEUR_TOP_DOWN 132+#define CLIP_DIALOGUE_FLEUR_BOT_UP 133+#define CLIP_DIALOGUE_FLEUR_BOT_DOWN 134+#define CLIP_PROMPT_UP 135+#define CLIP_PROMPT_DOWN 136+#define CLIP_PROMPT_BLANK 137+#define SPRITE_HERO_LIGHT 577+#define SPRITE_DIALOGUE_BACKBOARD 578+#define SPRITE_PROMPT_SHADOW 579+#define SPRITE_DIGIT0 760+#define STYLE_DIALOGUE 0+#define STYLE_PROMPT 1+#define TEXT_K 1.333333f+#define FONT_PHASES 4+#define TXT_PROMPT_LISTEN 0+#define TXT_PROMPT_REST 1+#define TXT_PROMPT_INSPECT 2+#define TXT_PROMPT_ENTER 3+#define TXT_PROMPT_SIT 4+#define TXT_PROMPT_SHOP 5+#define TXT_PROMPT_TRAVEL 6+#define TXT_PROMPT_ASCEND 7+#define TXT_PROMPT_DESCEND 8+#define TXT_PROMPT_EXIT 9+#define TXT_PROMPT_ACCEPT 10+#define TXT_PROMPT_TRADE 11+#define TXT_PROMPT_WATCH 12+#define TXT_PROMPT_CHALLENGE 13+#define PROMPT_SORT 884737u#define DIGIT_ADV {0.4182f, 0.4182f, 0.4182f, 0.4182f, 0.4182f, 0.4182f, 0.4182f, 0.4182f, 0.4182f, 0.4182f}diff --git a/games/hollowknight/src/enemy.c b/games/hollowknight/src/enemy.cindex e0c3e0f5..a81d7e64 100644--- a/games/hollowknight/src/enemy.c+++ b/games/hollowknight/src/enemy.c@@ -524,7 +524,7 @@ void enemies_draw(void) {Inst in;const Ent *d = ent_at(e->ent);float z = e->mode == EM_CORPSE ? 0.0085f : d->x1;- sprite_inst(e->anim.sprite, e->body.x, e->body.y, z, e->sx, 1, flash_tint(e, 2 + i % 6), &in);+ sprite_inst(e->anim.sprite, e->body.x, e->body.y, z, e->sx, 1, flash_tint(e, 2 + i % 5), &in);gfx_actor(&in, SORT_KEY(0, 0));}for (int i = 0; i < MAX_GEO; i++) {diff --git a/games/hollowknight/src/game.c b/games/hollowknight/src/game.cindex 451b21e1..9d492e2c 100644--- a/games/hollowknight/src/game.c+++ b/games/hollowknight/src/game.c@@ -13,11 +13,14 @@ void game_new(void) {g_pd.max_mp = 99;g_pd.nail_damage = 5;g_pd.can_dash = false;+ dialogue_reset();+ prompts_reset();}bool game_enter(int room, float x, float y, bool facing_right) {if (!room_load(room)) return false;memset(inside, 0, sizeof inside);+ prompts_reset();world_enter();hero_init(x, y, facing_right);cam_init();@@ -84,6 +87,7 @@ static void scene_load(void) {g->scene_phase = SC_NONE;if (!room_load(g->next_room)) return;memset(inside, 0, sizeof inside);+ prompts_reset(); /* (PromptMarker.RecycleOnLevelLoad) */world_enter();int n;const Ent *es = room_ents(&n);@@ -241,6 +245,8 @@ static void step(uint32_t keys) {hero_check_damage();hero_update();world_tick();+ prompts_tick();+ dialogue_tick();hazard_tick();fade_tick();hero_late_update();@@ -262,6 +268,8 @@ void game_tick(uint32_t keys) {void game_draw(void) {hud_draw();+ dialogue_draw();+ prompts_draw();obj_draw();hero_draw();gfx_frame();diff --git a/games/hollowknight/src/game.h b/games/hollowknight/src/game.hindex 4411ed3e..0c5d76eb 100644--- a/games/hollowknight/src/game.h+++ b/games/hollowknight/src/game.h@@ -200,8 +200,32 @@ 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);+/* ---------------------------------------------------------------- text (text.c) */+#define TEXT_BR 10 /* (in a text: a line break, a page break) */+#define TEXT_PAGE 12+const uint8_t *text_get(int id);+float text_width(int style, const uint8_t *s, int n);+/* the dialogue box (DialogueManager): its BOX UP and BOX DOWN; a conversation in it (DialogueBox.StartConversation),+ * paged with the continue keys until CONVO_FINISH */+void dialogue_reset(void);+void dialogue_box_up(void);+void dialogue_box_down(void);+void dialogue_start(int text);+bool dialogue_finished(void);+bool dialogue_box_shown(void);+void dialogue_cancel(void);+void dialogue_tick(void);+void dialogue_draw(void);+/* prompt markers (ShowPromptMarker, HidePromptMarker): a label at a place; handle: the one stored (-1: none) */+int prompt_show(int handle, int label, float x, float y);+void prompt_hide(int handle);+void prompts_reset(void);+void prompts_tick(void);+void prompts_draw(void);+/* ---------------------------------------------------------------- the HUD (hud.c) */void hud_reset(void);+void hud_slide(bool out); /* the Hud Canvas's Slide Out FSM: OUT, IN */void hud_tick(void);void hud_draw(void);diff --git a/games/hollowknight/src/gfx.c b/games/hollowknight/src/gfx.cindex ab3821a4..65edf91d 100644--- a/games/hollowknight/src/gfx.c+++ b/games/hollowknight/src/gfx.c@@ -1092,6 +1092,67 @@ void gfx_hud_clip(int clip, float x, float y, float r) {hud_clips[clip - 1] = (HudClip){VIEW_W / 2 + x * k, VIEW_H / 2 - y * k, r * k};}+/* text: lines of glyphs (4-bit alpha), drawn in front of what is behind them in their layer */+typedef struct {+ const uint8_t *s;+ const uint8_t *style;+ float x; /* the pen's start (view pixels) */+ int16_t y, y0, y1; /* the baseline; the rows it can cover */+ uint8_t n, layer;+ uint32_t rgb; /* (premultiplied by its alpha: 0xAARRGGBB) */+} TextRun;+#define MAX_RUNS 20+static TextRun runs[MAX_RUNS];+static int nruns;++bool gfx_text(int style, float x, float y, const uint8_t *s, int n, uint32_t argb, int layer) {+ uint32_t a = argb >> 24;+ if (nruns >= MAX_RUNS || n <= 0 || !a) return false;+ const uint8_t *st = font_style(style);+ TextRun *r = &runs[nruns++];+ r->s = s, r->style = st, r->x = x, r->n = (uint8_t)(n > 255 ? 255 : n), r->layer = (uint8_t)layer;+ r->y = (int16_t)lrintf(y);+ r->y0 = (int16_t)(r->y - (int)font_asc(st) - 3), r->y1 = (int16_t)(r->y + (int)font_desc(st) + 3);+ uint32_t cr = (argb >> 16 & 255) * a / 255, cg = (argb >> 8 & 255) * a / 255, cb = (argb & 255) * a / 255;+ r->rgb = a << 24 | cr << 16 | cg << 8 | cb;+ return true;+}++static void draw_runs(int layer, int sy0, int sy1) {+ for (int k = 0; k < nruns; k++) {+ const TextRun *r = &runs[k];+ if (r->layer != layer || r->y0 >= sy1 || r->y1 <= sy0) continue;+ uint32_t a0 = r->rgb >> 24, rb0 = r->rgb & 0xFF00FF, g0 = r->rgb >> 8 & 255;+ float pen = r->x;+ for (int i = 0; i < r->n; i++) {+ float fl = floorf(pen);+ int ip = (int)fl, ph = (int)((pen - fl) * FONT_PHASES + 0.5f);+ if (ph >= FONT_PHASES) ph = 0, ip++;+ const Glyph *g = font_glyph(r->style, r->s[i], ph);+ if (!g) continue;+ int gx = ip + g->left, gy = r->y - g->top;+ pen += g->adv * (1.0f / 64);+ if (!g->w || gy >= sy1 || gy + g->h <= sy0 || gx >= VIEW_W || gx + g->w <= 0) continue;+ int stride = (g->w + 1) >> 1;+ const uint8_t *bits = (const uint8_t *)(g + 1);+ int ya = gy < sy0 ? sy0 : gy, yb = gy + g->h > sy1 ? sy1 : gy + g->h;+ int xa = gx < 0 ? 0 : gx, xb = gx + g->w > VIEW_W ? VIEW_W : gx + g->w;+ for (int y = ya; y < yb; y++) {+ const uint8_t *row = bits + (y - gy) * stride;+ int p = (y - sy0) * VIEW_W;+ for (int x = xa; x < xb; x++) {+ int u = x - gx;+ uint32_t v = row[u >> 1] >> ((u & 1) * 4) & 15;+ if (!v) continue;+ uint32_t w = v * 17 * 257 >> 8; /* (0 .. 256) */+ uint32_t s = (a0 * w >> 8) << 24 | (((rb0 * w) >> 8) & 0xFF00FF) | ((g0 * w >> 8) << 8);+ take_over(y - sy0, x, p + x, s);+ }+ }+ }+ }+}+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 */@@ -1179,6 +1240,7 @@ void gfx_frame(void) {for (int sy0 = 0; sy0 < VIEW_H; sy0 += STRIP_H) {int sy1 = sy0 + STRIP_H;memset(cov, 0, sizeof cov);+ if (nruns) draw_runs(0, sy0, sy1);for (int i = nitems - 1; i >= nscene; i--)if (items[i].y0 < sy1 && items[i].y1 > sy0) draw_item(i, &items[i], sy0, sy1);if (g_screen_fade) {@@ -1190,11 +1252,13 @@ void gfx_frame(void) {trans[p] = (uint8_t)t;}}+ if (g_screen_fade < 255 && nruns) draw_runs(1, sy0, sy1);if (g_screen_fade < 255)for (int i = nscene - 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);}+ nruns = 0;#ifdef HOST{extern uint32_t g_peak_soft;diff --git a/games/hollowknight/src/hero.c b/games/hollowknight/src/hero.cindex ec44b8ec..33cc3fd6 100644--- a/games/hollowknight/src/hero.c+++ b/games/hollowknight/src/hero.c@@ -945,6 +945,7 @@ void fx_dash_burst(float x, float y, bool facing_right, bool on_ground) { (void)void hero_leave_scene(int gate) {Hero *h = &g_hero;spell_cancel(); /* (LEAVING SCENE) */+ dialogue_cancel();h->accepting_input = false; /* (IgnoreInputWithoutReset) */h->hard_landing_timer = 0;set_state(HS_NO_INPUT);diff --git a/games/hollowknight/src/hk.h b/games/hollowknight/src/hk.hindex bb7ec7e4..56826f57 100644--- a/games/hollowknight/src/hk.h+++ b/games/hollowknight/src/hk.h@@ -202,4 +202,29 @@ uint8_t gfx_dyn_tint(int slot, uint8_t r, uint8_t g, uint8_t b, uint8_t a); /*/* the same, flashing: its colors towards (fr, fg, fb) by amount (SpriteFlash) */uint8_t gfx_dyn_flash(int slot, uint8_t r, uint8_t g, uint8_t b, uint8_t a, uint8_t fr, uint8_t fg, uint8_t fb, uint8_t amount);extern uint8_t g_screen_fade; /* 0 .. 255: the screen faded to black */+/* a line of text (n glyphs of a style), its pen starting at (x, y) on the baseline (view pixels), of a color (0xAARRGGBB);+ * layer 0: the HUD's (in front of all), 1: the room's (in front of it, behind the HUD and the fade) */+bool gfx_text(int style, float x, float y, const uint8_t *s, int n, uint32_t argb, int layer);++/* ---------------------------------------------------------------- fonts (text.c) */+typedef struct {+ uint8_t w, h;+ int8_t left, top; /* from the pen, on the baseline (pixels) */+ uint16_t adv; /* 1/64 pixels; then rows of 4-bit alpha, low nibble first */+} Glyph;+const uint8_t *font_style(int style);+static inline float font_f(const uint8_t *st, int i) {+ float f;+ memcpy(&f, st + 4 * i, 4);+ return f;+}+#define font_em(st) font_f(st, 0)+#define font_line(st) font_f(st, 1)+#define font_asc(st) font_f(st, 2)+#define font_desc(st) font_f(st, 3)+/* a code's glyph, the pen phase (0 .. FONT_PHASES - 1) parts of a pixel right of a whole pixel */+static inline const Glyph *font_glyph(const uint8_t *st, uint8_t c, int phase) {+ uint16_t o = rd16(st + 16 + 2 * (c * FONT_PHASES + phase));+ return o ? (const Glyph *)(const void *)(st + o) : NULL;+}extern uint32_t g_gfx_items, g_gfx_pixels;diff --git a/games/hollowknight/src/hud.c b/games/hollowknight/src/hud.cindex af9a345a..7f1415d4 100644--- a/games/hollowknight/src/hud.c+++ b/games/hollowknight/src/hud.c@@ -25,11 +25,23 @@ static struct {Anim frame, liquid, coin;float liquid_grey; /* (Liquid Control: grey while it cannot heal) */bool started;+ /* Slide Out: the canvas shrinks about its corner (iTweenScaleTo, 0.15 s), then goes off the screen */+ bool out, off;+ float scale, scale_from, scale_t;} hd;+#define SCALE_TIME 0.15f+void hud_slide(bool out) {+ if (!hd.started || out == hd.out) return;+ hd.out = out;+ if (!out) hd.off = false; /* (Come In: back at its place) */+ hd.scale_from = hd.scale, hd.scale_t = 0;+}+void hud_reset(void) {memset(&hd, 0, sizeof hd);hd.shown_health = -1;+ hd.scale = 1, hd.scale_t = SCALE_TIME;anim_play(&hd.frame, CLIP_HUD_HUD_FRAME_IDLE);anim_play(&hd.liquid, CLIP_LIQUID_IDLE);anim_play(&hd.coin, CLIP_HUD_COIN_IDLE);@@ -54,6 +66,12 @@ void hud_tick(void) {anim_update(&hd.frame, DT);anim_update(&hd.liquid, DT);anim_update(&hd.coin, DT);+ if (hd.scale_t < SCALE_TIME) {+ hd.scale_t += DT;+ float t = hd.scale_t >= SCALE_TIME ? 1 : hd.scale_t / SCALE_TIME, to = hd.out ? 0.75f : 1;+ hd.scale = hd.scale_from + (to - hd.scale_from) * (hd.out ? 1 - cosf(t * 1.5707964f) : sinf(t * 1.5707964f));+ if (hd.out && hd.scale_t >= SCALE_TIME) hd.off = true; /* (Out, after 0.15 s) */+ }/* EaseColor over 0.2 s, to grey or white */float to = g_pd.mp < FOCUS_MP ? 1 : 0;if (hd.liquid_grey < to) hd.liquid_grey = fminf(to, hd.liquid_grey + DT / 0.2f);@@ -61,19 +79,22 @@ void hud_tick(void) {}static void hud_sprite(int sprite, float x, float y, float sx, uint8_t tint, int clip) {+ /* (on the canvas: about its corner, at its scale) */+ float k = hd.scale;Inst in;- sprite_inst(sprite, x, y, 0, sx, 1, tint, &in);+ sprite_inst(sprite, CANVAS_X + (x - CANVAS_X) * k, CANVAS_Y + (y - CANVAS_Y) * k, 0, sx * k, k, tint, &in);gfx_hud(&in, clip);}void hud_draw(void) {- if (!hd.started) return;+ if (!hd.started || hd.off) return;+ float k = hd.scale;uint8_t white = gfx_dyn_tint(8, 255, 255, 255, 255);/* the soul orb: its liquid (in the orb's circle), the frame over it */- if (g_pd.mp > 1) {+ if (g_pd.mp > 1 && !hd.out) { /* (the liquid's renderer off while the HUD is out) */float y = FILL_Y + LIQUID_BOTTOM_Y + g_pd.mp * LIQUID_Y_PER_MP;uint8_t g = (uint8_t)(255 - (255 - 110) * hd.liquid_grey);- gfx_hud_clip(1, FILL_X - 2.28f, FILL_Y + 1.32f, 0.97f);+ gfx_hud_clip(1, CANVAS_X + (FILL_X - 2.28f - CANVAS_X) * k, CANVAS_Y + (FILL_Y + 1.32f - CANVAS_Y) * k, 0.97f * k);hud_sprite(hd.liquid.sprite, FILL_X - 2.23f, y, 1, gfx_dyn_tint(9, g, g, g, 255), 1);}hud_sprite(hd.frame.sprite, ORB_X + 0.12f, ORB_Y + 0.92f, 1, white, 0);diff --git a/games/hollowknight/src/text.c b/games/hollowknight/src/text.cnew file mode 100644index 00000000..701fc5a9--- /dev/null+++ b/games/hollowknight/src/text.c@@ -0,0 +1,360 @@+/* Text: the game's sheets' entries (TEXT, in the pack's own code page) in its fonts (FONT: glyphs of 4-bit alpha);+ * the dialogue box (DialogueManager: Box Open, its Text's DialogueBox and Dialogue Page Control) and the prompt+ * markers over what the Knight can act on (PromptMarker). Text is a third bigger than the game's (tools/text.py),+ * the boxes with it. */+#include <math.h>+#include "game.h"++#define DT 0.02f+#define HUD_PX (FOCAL / (-1.342f - CAM_Z)) /* (the HUD's pixels a unit) */++const uint8_t *text_get(int id) {+ const uint8_t *s = section(SEC_TEXT);+ if ((uint32_t)id >= rd32(s)) return (const uint8_t *)"";+ return s + 4 + 4 * rd32(s) + rd32(s + 4 + 4 * id);+}++const uint8_t *font_style(int style) {+ const uint8_t *f = section(SEC_FONT);+ return f + rd32(f + 4 + 4 * style);+}++static float adv_of(const uint8_t *st, uint8_t c) {+ const Glyph *g = font_glyph(st, c, 0);+ return g ? g->adv * (1.0f / 64) : 0;+}++float text_width(int style, const uint8_t *s, int n) {+ const uint8_t *st = font_style(style);+ float w = 0;+ for (int i = 0; i < n && s[i]; i++) w += adv_of(st, s[i]);+ return w;+}++/* a line from s[i] in width (word wrapped as TextMeshPro does): its end; *next where the next line starts */+static int line_end(const uint8_t *st, const uint8_t *s, int i, float width, int *next) {+ float w = 0;+ int space = -1;+ for (int j = i;; j++) {+ uint8_t c = s[j];+ if (!c || c == TEXT_PAGE) return *next = j, j;+ if (c == TEXT_BR) return *next = j + 1, j;+ float a = adv_of(st, c);+ if (c != ' ' && w + a > width && j > i) {+ if (space > i) return *next = space + 1, space;+ return *next = j, j;+ }+ if (c == ' ') space = j;+ w += a;+ }+}++/* ---------------------------------------------------------------- the dialogue box */+#define BOX_X 0.0f+#define BOX_Y 4.51f /* (DialogueBox's place: the box scales about it) */+#define TEXT_X (-0.1031f) /* (Text: its rect's center, its size) */+#define TEXT_Y 4.49f+#define TEXT_W 17.9475f+#define TEXT_H 4.1109f+#define REVEAL_SPEED 65.0f /* (DialogueBox.revealSpeed; sped up: 200) */+#define MAX_PAGES 24+#define KEYS_CONTINUE (K_JUMP | K_ATTACK | K_SPELL | K_FOCUS | K_DASH | K_OK | K_BACK | K_PAUSE | K_MAP | K_INV)++enum { PC_IDLE, PC_PAGE_END, PC_STOP_PAUSE, PC_CONV_END, PC_SFX, PC_END };+static struct {+ /* Box Open: the box's scale (iTweenScaleTo) and its FadeGroup (0.5 s up, 0.3 s down, to 0.6) */+ bool up;+ float scale, scale_from, scale_to, scale_t, scale_time;+ float alpha, fade_t;+ Anim fleur_top, fleur_bot;+ bool fleurs_on;+ /* DialogueBox */+ const uint8_t *text;+ uint16_t page_start[MAX_PAGES + 1];+ uint8_t npages, page;+ int visible; /* maxVisibleCharacters */+ float reveal, speed;+ bool typing, fast;+ /* Dialogue Page Control, the arrow and the stop marker (Arrow Anim) */+ uint8_t pc;+ Anim arrow, stop;+ bool arrow_on, stop_on;+ bool finished; /* CONVO_FINISH, since dialogue_start */+ uint32_t prev_keys;+} dl;++static float ease_sine(float t, bool out) { return out ? sinf(t * 1.5707964f) : 1 - cosf(t * 1.5707964f); }++static void box_scale_to(float to, float time) {+ dl.scale_from = dl.scale, dl.scale_to = to, dl.scale_t = 0, dl.scale_time = time;+}++void dialogue_box_up(void) {+ /* (Box Up) */+ dl.up = true;+ hud_slide(true);+ box_scale_to(1, 0.5f);+ dl.fade_t = 0;+ anim_play_from_frame(&dl.fleur_top, CLIP_DIALOGUE_FLEUR_TOP_UP, 0);+ anim_play_from_frame(&dl.fleur_bot, CLIP_DIALOGUE_FLEUR_BOT_UP, 0);+ dl.fleurs_on = true;+}++void dialogue_box_down(void) {+ if (!dl.up) return;+ dl.up = false;+ hud_slide(false);+ box_scale_to(0.75f, 0.3f);+ dl.fade_t = 0;+ anim_play_from_frame(&dl.fleur_top, CLIP_DIALOGUE_FLEUR_TOP_DOWN, 0);+ anim_play_from_frame(&dl.fleur_bot, CLIP_DIALOGUE_FLEUR_BOT_DOWN, 0);+}++static int lines_per_page(const uint8_t *st) {+ float h = TEXT_H * HUD_PX * TEXT_K;+ return 1 + (int)((h - font_asc(st) - font_desc(st)) / font_line(st));+}++/* SetConversation: its pages (TextMeshPro's page mode: as many lines as the rect holds, and <page>) */+static void set_conversation(const uint8_t *s) {+ const uint8_t *st = font_style(STYLE_DIALOGUE);+ float width = TEXT_W * HUD_PX * TEXT_K;+ int per = lines_per_page(st);+ dl.text = s, dl.npages = 0;+ int i = 0;+ while (s[i] && dl.npages < MAX_PAGES) {+ dl.page_start[dl.npages++] = (uint16_t)i;+ for (int l = 0; l < per && s[i] && s[i] != TEXT_PAGE; l++) line_end(st, s, i, width, &i);+ if (s[i] == TEXT_PAGE) i++;+ }+ if (!dl.npages) dl.page_start[dl.npages++] = 0;+ dl.page_start[dl.npages] = (uint16_t)i;+}++static int page_last(void) { /* (the page's end: its last character's index + 1) */+ int e = dl.page_start[dl.page + 1];+ while (e > dl.page_start[dl.page] && (dl.text[e - 1] == TEXT_PAGE)) e--;+ return e;+}++static void show_page(int p) {+ if (p >= dl.npages) {+ dl.pc = PC_STOP_PAUSE; /* (CONVERSATION_END) */+ return;+ }+ dl.page = (uint8_t)p;+ dl.visible = dl.page_start[p];+ dl.typing = true, dl.fast = false, dl.speed = REVEAL_SPEED, dl.reveal = 1; /* (the first at once) */+}++void dialogue_start(int text) {+ /* StartConversation */+ set_conversation(text_get(text));+ dl.finished = false;+ dl.pc = PC_IDLE;+ dl.prev_keys = g_hero.keys;+ show_page(0);+}++bool dialogue_finished(void) { return dl.finished; }+bool dialogue_box_shown(void) { return dl.up || dl.alpha > 0; }++static void end_conversation(void) {+ /* End Conversation: the markers down, the text hidden, CONVO_FINISH */+ if (dl.stop_on) anim_play_from_frame(&dl.stop, CLIP_DIALOGUE_STOP_DOWN, 0);+ if (dl.arrow_on) anim_play_from_frame(&dl.arrow, CLIP_DIALOGUE_ARROW_DOWN, 0);+ dl.text = NULL;+ dl.finished = true;+ dl.pc = PC_IDLE;+}++void dialogue_cancel(void) {+ /* (CONVO CANCEL, LEAVING SCENE) */+ if (dl.text) end_conversation();+}++void dialogue_tick(void) {+ uint32_t keys = g_hero.keys, pressed = keys & ~dl.prev_keys;+ dl.prev_keys = keys;+ bool cont = (pressed & KEYS_CONTINUE) != 0; /* (ListenForPromptContinue) */+ /* the box */+ if (dl.scale_t < dl.scale_time) {+ dl.scale_t += DT;+ float t = dl.scale_t >= dl.scale_time ? 1 : dl.scale_t / dl.scale_time;+ dl.scale = dl.scale_from + (dl.scale_to - dl.scale_from) * ease_sine(t, dl.scale_to > dl.scale_from);+ }+ dl.fade_t += DT;+ if (dl.up) dl.alpha = fminf(1, dl.fade_t / 0.5f);+ else if (dl.alpha > 0) dl.alpha = fmaxf(0, 1 - dl.fade_t / 0.3f);+ if (dl.fleurs_on) {+ dl.fleur_top.events = dl.fleur_bot.events = 0;+ anim_update(&dl.fleur_top, DT);+ anim_update(&dl.fleur_bot, DT);+ if (!dl.up && !dl.fleur_top.playing && !dl.fleur_bot.playing) dl.fleurs_on = false;+ }+ if (dl.arrow_on) anim_update(&dl.arrow, DT);+ if (dl.stop_on) anim_update(&dl.stop, DT);+ if (!dl.text) return;+ /* DialogueBox's typewriter */+ if (dl.typing) {+ int last = page_last();+ dl.reveal += DT * dl.speed;+ while (dl.reveal >= 1 && dl.visible < last) dl.visible++, dl.reveal -= 1;+ if (dl.visible >= last) {+ dl.typing = false;+ if (dl.page + 1 >= dl.npages) dl.pc = PC_STOP_PAUSE; /* CONVERSATION_END */+ else {+ /* PAGE_END: the arrow up */+ dl.pc = PC_PAGE_END;+ dl.arrow_on = true;+ anim_play_from_frame(&dl.arrow, CLIP_DIALOGUE_ARROW_UP, 0);+ return;+ }+ }+ }+ switch (dl.pc) {+ case PC_IDLE:+ if (cont && dl.typing && !dl.fast) dl.fast = true, dl.speed = 200; /* (SpeedupTypewriter) */+ break;+ case PC_PAGE_END:+ if (cont) {+ /* Show Next Page */+ anim_play_from_frame(&dl.arrow, CLIP_DIALOGUE_ARROW_DOWN, 0);+ dl.pc = PC_IDLE;+ show_page(dl.page + 1);+ }+ break;+ case PC_STOP_PAUSE:+ /* (Stop Pause: 0 s) then the stop marker up */+ dl.stop_on = true, dl.arrow_on = false;+ anim_play_from_frame(&dl.stop, CLIP_DIALOGUE_STOP_UP, 0);+ dl.pc = PC_CONV_END;+ break;+ case PC_CONV_END:+ if (cont) dl.pc = PC_SFX; /* (the text cleared, the next frame) */+ break;+ case PC_SFX:+ dl.visible = dl.page_start[dl.page];+ dl.pc = PC_END;+ break;+ case PC_END:+ end_conversation();+ break;+ }+}++static void box_sprite(int sprite, float x, float y, float sx, float sy, uint8_t tint) {+ /* (placed about the box's place at its scale and the text's; sized at its scale) */+ float k = dl.scale * TEXT_K;+ Inst in;+ sprite_inst(sprite, BOX_X + (x - BOX_X) * k, BOX_Y + (y - BOX_Y) * k, 0, sx * dl.scale, sy * dl.scale, tint, &in);+ gfx_hud(&in, 0);+}+#define MARKER_K (1.3f * TEXT_K) /* (the arrow's and the stop's scale) */++void dialogue_draw(void) {+ if (dl.alpha > 0 || dl.fleurs_on) {+ /* the backboard (0.6 of its color's alpha), the fleurs */+ uint8_t a = (uint8_t)(dl.alpha * 0.6f * 0.616f * 255);+ if (a) box_sprite(SPRITE_DIALOGUE_BACKBOARD, 0, 4.51f - 0.09f, 1, 1.2527f / 2.325f, gfx_dyn_tint(12, 255, 255, 255, a));+ uint8_t white = gfx_dyn_tint(13, 255, 255, 255, 255);+ if (dl.fleurs_on) {+ box_sprite(dl.fleur_top.sprite, 0, 4.51f + 2.85f, TEXT_K, TEXT_K, white);+ box_sprite(dl.fleur_bot.sprite, 0, 4.51f - 2.73f, TEXT_K, TEXT_K, white);+ }+ }+ uint8_t white = gfx_dyn_tint(14, 255, 255, 255, 255);+ if (dl.arrow_on && dl.arrow.sprite >= 0) box_sprite(dl.arrow.sprite, 0.0069f, 1.695f, MARKER_K, MARKER_K, white);+ if (dl.stop_on && dl.stop.sprite >= 0) box_sprite(dl.stop.sprite, -0.0231f, 1.695f, MARKER_K, MARKER_K, white);+ if (!dl.text) return;+ /* the page's lines, top left in the rect, as far as the typewriter shows */+ const uint8_t *st = font_style(STYLE_DIALOGUE);+ float w = TEXT_W * HUD_PX * TEXT_K, h = TEXT_H * HUD_PX * TEXT_K;+ float left = VIEW_W / 2 + TEXT_X * HUD_PX - w / 2;+ float y = VIEW_H / 2 - (BOX_Y + (TEXT_Y - BOX_Y) * TEXT_K) * HUD_PX - h / 2 + font_asc(st);+ int i = dl.page_start[dl.page], last = page_last(), per = lines_per_page(st);+ for (int l = 0; l < per && i < last; l++) {+ int next, e = line_end(st, dl.text, i, w, &next);+ int n = (e < dl.visible ? e : dl.visible) - i;+ if (n > 0) gfx_text(STYLE_DIALOGUE, left, y, dl.text + i, n, 0xFFFFFFFFu, 0);+ if (dl.visible <= e) break;+ i = next, y += font_line(st);+ }+}++void dialogue_reset(void) {+ memset(&dl, 0, sizeof dl);+ dl.scale = 0.75f;+ dl.arrow.sprite = dl.stop.sprite = -1;+}++/* ---------------------------------------------------------------- prompt markers */+#define MAX_PROMPTS 4+#define PROMPT_FADE_IN 0.4f+#define PROMPT_FADE_OUT 0.233f+typedef struct {+ bool used, visible;+ int16_t label; /* its text */+ float x, y, t;+ Anim anim;+} Prompt;+static Prompt prompts[MAX_PROMPTS];++int prompt_show(int handle, int label, float x, float y) {+ /* ShowPromptMarker: the stored one again, or a new one */+ Prompt *p = handle >= 0 && handle < MAX_PROMPTS && prompts[handle].used ? &prompts[handle] : NULL;+ if (!p) {+ for (int i = 0; i < MAX_PROMPTS && !p; i++)+ if (!prompts[i].used) p = &prompts[i], handle = i;+ if (!p) return -1;+ memset(p, 0, sizeof *p);+ p->used = true;+ }+ p->label = (int16_t)label, p->x = x, p->y = y;+ anim_play_from_frame(&p->anim, CLIP_PROMPT_UP, 0);+ p->visible = true, p->t = 0;+ return handle;+}++void prompt_hide(int handle) {+ if (handle < 0 || handle >= MAX_PROMPTS || !prompts[handle].used || !prompts[handle].visible) return;+ Prompt *p = &prompts[handle];+ anim_play_from_frame(&p->anim, CLIP_PROMPT_DOWN, 0);+ p->visible = false, p->t = 0; /* (recycled after the fade) */+}++void prompts_reset(void) { memset(prompts, 0, sizeof prompts); }++void prompts_tick(void) {+ for (int i = 0; i < MAX_PROMPTS; i++) {+ Prompt *p = &prompts[i];+ if (!p->used) continue;+ p->t += DT;+ anim_update(&p->anim, DT);+ if (!p->visible && p->t >= PROMPT_FADE_OUT) p->used = false;+ }+}++void prompts_draw(void) {+ for (int i = 0; i < MAX_PROMPTS; i++) {+ Prompt *p = &prompts[i];+ if (!p->used) continue;+ float a = p->visible ? fminf(1, p->t / PROMPT_FADE_IN) : fmaxf(0, 1 - p->t / PROMPT_FADE_OUT);+ Inst in;+ if (p->anim.sprite >= 0) {+ sprite_inst(p->anim.sprite, p->x, p->y, 0, 1, 1, 0, &in); /* (the room's tint 0: white) */+ gfx_actor(&in, PROMPT_SORT);+ }+ /* the shadow (black, faded with the label) */+ sprite_inst(SPRITE_PROMPT_SHADOW, p->x - 0.14f, p->y + 0.42f, 0.01f, 1, 0.58f / 0.8f, gfx_dyn_tint(7, 0, 0, 0, (uint8_t)(a * 255)), &in);+ gfx_actor(&in, PROMPT_SORT);+ /* the label, centered on (0, 0.249) */+ const uint8_t *s = text_get(p->label);+ int n = (int)strlen((const char *)s);+ const uint8_t *st = font_style(STYLE_PROMPT);+ float k = FOCAL / (0 - CAM_Z);+ float cx = VIEW_W / 2 + (p->x - g_cam_x) * k, cy = VIEW_H / 2 - (p->y + 0.249f - g_cam_y) * k;+ gfx_text(STYLE_PROMPT, cx - text_width(STYLE_PROMPT, s, n) / 2, cy + font_asc(st) / 2, s, n,+ (uint32_t)(a * 255) << 24 | 0xFFFFFF, 1);+ }+}diff --git a/games/hollowknight/tests/play.c b/games/hollowknight/tests/play.cindex a41ed1f0..8f33da44 100644--- a/games/hollowknight/tests/play.c+++ b/games/hollowknight/tests/play.c@@ -67,6 +67,13 @@ int main(int argc, char **argv) {while (*p && *p != ',') p++;if (*p == ',') p++;for (int i = 0; i < n; i++, tick++) {+ /* (HKTALK=tick:text a conversation then; HKPROMPT=tick a prompt over the Knight then) */+ if (getenv("HKTALK") && atoi(getenv("HKTALK")) == tick) {+ dialogue_box_up();+ dialogue_start(atoi(strchr(getenv("HKTALK"), ':') + 1));+ }+ if (getenv("HKPROMPT") && atoi(getenv("HKPROMPT")) == tick)+ prompt_show(-1, TXT_PROMPT_LISTEN, g_hero.body.x, g_hero.body.y + 1.5f);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,diff --git a/games/hollowknight/tools/actors.py b/games/hollowknight/tools/actors.pyindex 51f7787f..6ffee6bf 100644--- a/games/hollowknight/tools/actors.py+++ b/games/hollowknight/tools/actors.py@@ -3,7 +3,7 @@ clips. Each sprite frame becomes a texture like the scenery's; pack.py writes thclips (CLIP)."""import numpy as npfrom PIL import Image-import unity, tk2d, scene, art+import unity, tk2d, scene, art, text# the Knight's clips the game uses (from the Knight's library, resources.assets)KNIGHT = ("resources.assets", 20600, [@@ -31,31 +31,39 @@ ACTORS = {"knight": KNIGHT,"Blue Appear", "Blue Idle", "Blue Break", "HUD Frame", "HUD Frame Idle","Coin Appear", "Coin Idle", "Coin Get", "Soul Burst"]),"liquid": ("resources.assets", 20843, None),- "geo": ("resources.assets", 23266, ["Small Idle", "Small Air", "Med Idle", "Med Air", "Large Idle", "Large Air"])}+ "geo": ("resources.assets", 23266, ["Small Idle", "Small Air", "Med Idle", "Med Air", "Large Idle", "Large Air"]),+ # the dialogue box (on the HUD, a third bigger with its text) and the prompt markers+ "dialogue": ("resources.assets", 20724, ["Arrow Up", "Arrow Down", "Stop Up", "Stop Down", "Fleur Top Up",+ "Fleur Top Down", "Fleur Bot Up", "Fleur Bot Down"]),+ "prompt": ("resources.assets", 23333, ["Up", "Down", "Blank"])}# sprites of prefab objects the game draws itself: name -> (file, prefab, object, resolution)NAMED = {"HERO_LIGHT": ("resources.assets", 3916, "Knight/HeroLight", 1.0),+ # (these at a scale of their own: the box's, with its text's; the shadow's x)+ "DIALOGUE_BACKBOARD": ("resources.assets", 4446, "DialogueManager/DialogueBox/backboard", "hud", 2.325 * text.TEXT_K),+ "PROMPT_SHADOW": ("resources.assets", 8342, "Arrow Prompt New/Shadow", 1.0, 0.8),}def named_sprites(sprites):"""Registers NAMED in sprites (ents.Sprites) -> {name: sprite id}."""out = {}- for name, (path, gid, opath, res) in NAMED.items():+ for name, (path, gid, opath, res, *scale) in NAMED.items():d = unity.prefab(path, gid)o = next(o for o in d["objects"] if o["path"] == opath)v = next(c["v"] for c in o["c"] if c["type"] == "SpriteRenderer")m = np.array(o["m3"]).reshape(3, 3)- out[name] = sprites.id(d, v["m_Sprite"], float(max(np.hypot(m[0, 0], m[1, 0]), np.hypot(m[0, 1], m[1, 1]))), res)+ k = scale[0] if scale else float(max(np.hypot(m[0, 0], m[1, 0]), np.hypot(m[0, 1], m[1, 1])))+ out[name] = sprites.id(d, v["m_Sprite"], k, HUD_K / K0 if res == "hud" else res)return out# 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,+DRAWN_SCALE = {"Arrow Up": 1.3, "Arrow Down": 1.3, "Stop Up": 1.3, "Stop Down": 1.3, "SlashEffect": 1.645, "SlashEffectAlt": 1.422, "UpSlashEffect": 1.4, "DownSlashEffect": 1.28,"Small Idle": 1.5, "Small Air": 1.5, "Med Idle": 1.5, "Med Air": 1.5, "Large Idle": 1.5, "Large Air": 1.5}K0 = scene.FOCAL / (0.004 - scene.CAMZ) # screen pixels a unit, where actors are (z near 0)HUD_K = (scene.VIEW_H / 2) / 8.7107 # the HUD's (its orthographic camera)# (actor, clip): drawn bigger or smaller than their sprites-ACTOR_SCALE = {"hud": HUD_K / K0, "liquid": 1.4 * HUD_K / K0}+ACTOR_SCALE = {"hud": HUD_K / K0, "liquid": 1.4 * HUD_K / K0, "dialogue": text.TEXT_K * HUD_K / K0}HUD_MASK = 0.7135diff --git a/games/hollowknight/tools/font.py b/games/hollowknight/tools/font.pyindex ca4fd693..6f76c83e 100644--- a/games/hollowknight/tools/font.py+++ b/games/hollowknight/tools/font.py@@ -42,3 +42,28 @@ def glyphs(name, chars, em_px, scale_units):"tu": w / ss * scale_units / W, "tv": h / ss * scale_units / H})adv.append(ft.getlength(ch) / ss * scale_units)return out, adv+++def bitmaps(name, chars, em_px, phase=0.0, ss=4, gamma=0.8):+ """Glyphs at em_px pixels an em, unhinted (as the game's text is), from 4x, the pen phase pixels right of a whole+ pixel: [(alpha rows, left, top from the pen's pixel on the baseline, advance in pixels)]. (Thin strokes a little+ stronger: gamma.)"""+ ft = ImageFont.truetype(io.BytesIO(font_data(name)), em_px * ss)+ pad = int(em_px) + 2+ out = []+ for ch in chars:+ adv = ft.getlength(ch) / ss+ W, H = (int(em_px * 3) + 2 * pad) * ss, (int(em_px * 3) + 2 * pad) * ss+ im = Image.new("L", (W, H), 0)+ # the pen at (pad, base) in pixels: the baseline at a whole pixel+ base = int(em_px * 2) + pad+ ImageDraw.Draw(im).text((pad * ss + round(phase * ss), base * ss), ch, font=ft, fill=255, anchor="ls")+ a = np.asarray(im.resize((W // ss, H // ss), Image.BOX)).astype(np.float32) / 255+ a = (a ** gamma * 255).round().astype(np.uint8)+ ys, xs = np.nonzero(a > 8)+ if not len(ys):+ out.append((np.zeros((0, 0), np.uint8), 0, 0, adv))+ continue+ a = a[ys.min():ys.max() + 1, xs.min():xs.max() + 1]+ out.append((a, int(xs.min()) - pad, base - int(ys.min()), adv))+ return outdiff --git a/games/hollowknight/tools/pack.py b/games/hollowknight/tools/pack.pyindex c145b3c0..2ea0bbc0 100644--- a/games/hollowknight/tools/pack.py+++ b/games/hollowknight/tools/pack.py@@ -4,13 +4,17 @@ import os, sys, struct, math, lzma, time, multiprocessing as mpimport numpy as npHERE = os.path.dirname(os.path.abspath(__file__))sys.path.insert(0, HERE)-import unity, scene, visible, art, actors, coll, ents, font+import unity, scene, visible, art, actors, coll, ents, font, textSRC = 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()+TEXTS = text.Texts()+# the prompt markers' labels (Arrow Prompt New's)+PROMPTS = ["Listen", "Rest", "Inspect", "Enter", "Sit", "Shop", "Travel", "Ascend", "Descend", "Exit", "Accept", "Trade",+ "Watch", "Challenge"]ROOM_DATA = {} # name -> (coll.room's, ents.room's)@@ -24,7 +28,7 @@ def room_data(name):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"]+SECTIONS = ["TEX", "TMAP", "PAL", "BIDX", "BLK", "ROOMS", "RBLOB", "PRIOR", "SOFT", "SPR", "CLIP", "STR", "TEXT", "FONT"]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@@ -291,6 +295,8 @@ def main():# the rooms' objects, and the sprites they show (after the actors')SPRITES.base = len(sprites)named = actors.named_sprites(SPRITES)+ prompt_ids = {p: TEXTS.id("Prompts", p.upper(), "PROMPT") for p in PROMPTS}+ TEXTS.id("Elderbug", "ELDERBUG_INTRO_MAIN") # (until the NPCs: a conversation to try)for r in ROOMS:room_data(r)sprites += actors.unity_sprites(SPRITES.list)@@ -385,6 +391,8 @@ def main():print("room %-26s %5d instances in %2d sectors, %6d packed" % (r, len(keep), len(blobs), packed + len(hc)), flush=True)secs["ROOMS"].b += roomssecs["STR"].b += STRINGS.blob()+ secs["TEXT"].b += TEXTS.blob()+ secs["FONT"].b += TEXTS.fonts()# the file: "HKNW", count, then (offset, size) per sectionhead = struct.pack("<4sI", b"HKNW", len(SECTIONS))pos = len(head) + 8 * len(SECTIONS)@@ -411,6 +419,12 @@ def main():for k, v in named.items():f.write("#define SPRITE_%s %d\n" % (k, v))f.write("#define SPRITE_DIGIT0 %d\n" % digit_base)+ for i, k in enumerate(text.STYLES):+ f.write("#define STYLE_%s %d\n" % (k, i))+ f.write("#define TEXT_K %.6ff\n#define FONT_PHASES %d\n" % (text.TEXT_K, text.PHASES))+ for k, v in prompt_ids.items():+ f.write("#define TXT_PROMPT_%s %d\n" % (k.upper(), v))+ f.write("#define PROMPT_SORT %du\n" % ((scene.layer_index(-349214895) << 16) | (1 + 32768)))f.write("#define DIGIT_ADV {%s}\n" % ", ".join("%.4ff" % a for a in digit_adv))diff --git a/games/hollowknight/tools/text.py b/games/hollowknight/tools/text.pynew file mode 100644index 00000000..6118a835--- /dev/null+++ b/games/hollowknight/tools/text.py@@ -0,0 +1,162 @@+"""The game's text: its language sheets (EN_*.txt TextAssets, encrypted; the key is found in the game's own assembly),+as {sheet: {key: text}}."""+import base64, functools, html, os, re, struct+import numpy as np+import unity+++def _candidates(dll):+ """32-character alphanumeric strings in an assembly's user strings (UTF-16)."""+ data = open(dll, "rb").read()+ for m in re.finditer(rb"(?:[A-Za-z0-9]\x00){32}", data):+ s = m.group(0).decode("utf-16-le")+ yield s+++def _decrypt(key, b64):+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes+ raw = base64.b64decode(b64)+ d = Cipher(algorithms.AES(key.encode()), modes.ECB()).decryptor()+ out = d.update(raw) + d.finalize()+ pad = out[-1]+ if not 1 <= pad <= 16 or out[-pad:] != bytes([pad]) * pad:+ raise ValueError("padding")+ return out[:-pad].decode("utf-8")+++def _assets():+ f = unity.asset_file("resources.assets")+ out = {}+ for o in f.objects.values():+ if o.type.name == "TextAsset":+ t = o.read()+ if t.m_Name.startswith("EN_"):+ data = t.m_Script+ out[t.m_Name[3:]] = data if isinstance(data, str) else data.decode("utf-8", "replace")+ return out++[email protected]_cache(maxsize=None)+def _key():+ sample = _assets()["General"]+ dll = os.path.join(unity.DATA, "Managed", "Assembly-CSharp.dll")+ for k in _candidates(dll):+ try:+ _decrypt(k, sample)+ return k+ except Exception:+ continue+ raise RuntimeError("no key for the language sheets")++[email protected]_cache(maxsize=None)+def sheets():+ """{sheet name (EN_ less): {entry key: text}}"""+ out = {}+ key = _key()+ for name, b64 in _assets().items():+ xml = _decrypt(key, b64)+ out[name] = {m.group(1): m.group(2) for m in re.finditer(r'<entry name="([^"]*)">(.*?)</entry>', xml, re.S)}+ return out+++# ---------------------------------------------------------------- the texts the game shows, in its own code page+TEXT_K = 4 / 3 # text a third bigger than the game's (its sizes at this screen's are hard to read), boxes with it+BR, PAGE = 10, 12+PHASES = 4 # glyphs drawn a quarter pixel apart++# the styles: (font, em in pixels, line advance in pixels, ascender, descender in pixels)+# TextMeshPro: an em is font size / 10 units; a line is (the font's line height + line spacing) / point size ems+HUD_PX = 100 / 8.7107 # (the HUD camera's: pixels a unit)+WORLD_PX = 421.94 / 38.1 # (the room's camera, at z = 0)+++def _style(font, size, px, line_height, line_spacing, point, asc, desc):+ em = size * 0.1 * px * TEXT_K+ return (font, em, (line_height + line_spacing) / point * em, asc / point * em, -desc / point * em)+++STYLES = {+ "DIALOGUE": _style("Perpetua", 7.2, HUD_PX, 134.0625, 24.6, 117, 95.9375, -38.1875),+ "PROMPT": _style("TrajanPro-Bold", 6.67, WORLD_PX, 84, 0, 70, 52.5, -17.5),+}+++def clean(s):+ """A sheet's entry as shown: its markup to breaks and pages."""+ s = html.unescape(s)+ s = s.replace("<br>", "\n").replace("<page>", "\f")+ return s.strip(" ")+++class Texts:+ def __init__(self):+ self.list, self.index = [], {}++ def id(self, sheet, key, style="DIALOGUE"):+ """A sheet's entry, by its key (shown in a style): its index."""+ return self.add(clean(sheets()[sheet][key]), style)++ def add(self, s, style):+ k = (s, style)+ if k not in self.index:+ self.index[k] = len(self.list)+ self.list.append(k)+ return self.index[k]++ def code_page(self):+ extra = sorted({c for s, _ in self.list for c in s if not (32 <= ord(c) < 127 or c in "\n\f")})+ assert len(extra) <= 128, extra+ cp = {chr(i): i for i in range(32, 127)}+ cp["\n"], cp["\f"] = BR, PAGE+ for i, c in enumerate(extra):+ cp[c] = 128 + i+ return cp++ def blob(self):+ """TEXT: count, offsets, then each text (its code page's bytes, 0 ended)"""+ cp = self.code_page()+ offs, body = [], bytearray()+ for s, _ in self.list:+ offs.append(len(body))+ body += bytes(cp[c] for c in s) + b"\0"+ return struct.pack("<I", len(self.list)) + b"".join(struct.pack("<I", o) for o in offs) + bytes(body)++ def fonts(self):+ """FONT: per style (as STYLES' order) its offset; a style: em, line advance, ascender, descender (floats),+ 256 x PHASES glyph offsets (u16, from the style, 0 none: a code's glyph with the pen 0, 1/4... of a pixel right+ of a whole pixel), then the glyphs: width, height, left, top (from the pen's pixel on the baseline, pixels),+ advance (1/64 pixels, u16), then rows of 4-bit alpha (low nibble first)."""+ import font+ cp = self.code_page()+ blocks = []+ for name, (fname, em, line, asc, desc) in STYLES.items():+ chars = sorted({c for s, st in self.list if st == name for c in s if c not in "\n\f"} | {" ", "-"})+ head = bytearray(struct.pack("<ffff", em, line, asc, desc))+ offs = [0] * (256 * PHASES)+ body = bytearray()+ base = len(head) + 2 * len(offs)+ for ph in range(PHASES):+ for ch, g in zip(chars, font.bitmaps(fname, chars, em, ph / PHASES)):+ a, left, top, adv = g+ h, w = a.shape+ offs[cp[ch] * PHASES + ph] = base + len(body)+ body += struct.pack("<BBbbH", w, h, left, top, min(65535, round(adv * 64)))+ q = (a.astype(np.uint16) * 15 + 127) // 255+ for row in q:+ r = list(row) + [0] * (w & 1)+ body += bytes(r[i] | r[i + 1] << 4 for i in range(0, len(r), 2))+ if len(body) & 1:+ body.append(0)+ assert base + len(body) < 65536, name+ while len(body) % 4:+ body.append(0)+ blocks.append(bytes(head) + struct.pack("<%dH" % len(offs), *offs) + bytes(body))+ out = bytearray(struct.pack("<I", len(blocks)))+ pos = 4 + 4 * len(blocks)+ for b in blocks:+ out += struct.pack("<I", pos)+ pos += len(b)+ for b in blocks:+ out += b+ return bytes(out)diff --git a/games/hollowknight/tools/unity.py b/games/hollowknight/tools/unity.pyindex 6a9dd00f..ff0c0208 100644--- a/games/hollowknight/tools/unity.py+++ b/games/hollowknight/tools/unity.py@@ -117,6 +117,28 @@ def _dump_objects(lv, name, level, root=None):todo += [objs[ch["m_PathID"]].read_typetree()["m_GameObject"]["m_PathID"] for ch in t["m_Children"]]wm = {}sys.setrecursionlimit(20000)+ # (a RectTransform's place is its anchored position, from its anchors in its parent's rect)+ sizes = {}++ def rect_size(pid):+ if pid not in sizes:+ d = tr[pid]+ if "m_SizeDelta" not in d:+ sizes[pid] = (0.0, 0.0)+ else:+ f = d["m_Father"]["m_PathID"]+ ps = rect_size(f) if f in tr else (0.0, 0.0)+ sizes[pid] = tuple(d["m_SizeDelta"][k] + (d["m_AnchorMax"][k] - d["m_AnchorMin"][k]) * ps[i]+ for i, k in enumerate("xy"))+ return sizes[pid]+ for pid, d in tr.items():+ if "m_AnchoredPosition" in d:+ f = d["m_Father"]["m_PathID"]+ ps = rect_size(f) if f in tr else (0.0, 0.0)+ pp = tr[f].get("m_Pivot", {"x": 0.5, "y": 0.5}) if f in tr else {"x": 0.5, "y": 0.5}+ for i, k in enumerate("xy"):+ a0, a1, pv = d["m_AnchorMin"][k], d["m_AnchorMax"][k], d["m_Pivot"][k]+ d["m_LocalPosition"][k] = (a0 + (a1 - a0) * pv - pp[k]) * ps[i] + d["m_AnchoredPosition"][k]def world(pid):if pid not in wm: