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.

Celeste: each chapter's end picture (AreaComplete with its title), and the mountain behind the chapter select and the main menu

Mason Chen98deb23b7792
diff --git a/games/celeste/Makefile b/games/celeste/Makefile
index ad8b6594..73714f8d 100644
--- a/games/celeste/Makefile
+++ b/games/celeste/Makefile
@@ -10,7 +10,7 @@ NWLINK ?= npx --yes -- [email protected]
STRIP ?= arm-none-eabi-strip --strip-unneeded
BUILD_DIR = output
GAME = src/res.c src/gfx.c src/util.c src/ent.c src/level.c src/tiles.c src/style.c src/player.c src/entities.c \
- src/fx.c src/ptypes.c src/font.c src/light.c src/spinner.c src/berry.c src/save.c src/text.c src/wipe.c src/cutscene.c src/npc.c src/talk.c src/heart.c src/cassette.c src/dust.c src/breath.c src/menu.c $(wildcard src/ch*.c) src/game.c \
+ src/fx.c src/ptypes.c src/font.c src/light.c src/spinner.c src/berry.c src/save.c src/text.c src/wipe.c src/cutscene.c src/npc.c src/talk.c src/heart.c src/cassette.c src/dust.c src/breath.c src/pic.c src/menu.c $(wildcard src/ch*.c) src/game.c \
src/lzma/LzmaDec.c
SRC = $(GAME) src/plat_eadk.c src/main.c
HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h
diff --git a/games/celeste/README.md b/games/celeste/README.md
index c9703229..bab93438 100644
--- a/games/celeste/README.md
+++ b/games/celeste/README.md
@@ -26,7 +26,7 @@
* **Madeline moves like in the game:** the same jumps, dashes, climbing and wall jumps, down to the frame.
* **The story:** every conversation with Theo, Granny, Oshiro and Badeline, with their portraits, and the scenes between, from the campfires to the hug in Reflection.
* **Everything to find:** strawberries, golden strawberries, crystal hearts with their poems, cassettes that unlock the B-sides, the Summit's gems.
-* **The game's look:** its rooms, decorations and backgrounds, from dust bunnies and dream blocks to the Summit's wind.
+* **The game's look:** its rooms, decorations and backgrounds, from dust bunnies and dream blocks to the Summit's wind, the mountain behind the chapter select and the picture at the end of each chapter.
* **Saved as you go:** Home saves and quits, and Climb then offers Continue. Your progress is also copied into `celeste_saves.py`, so installing the app again doesn't erase it.
<table>
@@ -71,7 +71,7 @@ In menus, OK or EXE confirms and Back goes back. You can change the keys in Opti
* **One app at a time:** Celeste takes all the room the calculator has for apps. Installing it from the NumWorks website swaps out NumPlay and the other apps, and installing NumPlay again swaps it back out. Your progress in each one is kept.
* **No music:** the calculator has no speaker.
-* **A few effects are simpler:** some glows, color filters and screen distortions are left out, and the Epilogue's last picture is shown at half size.
+* **A few effects are simpler:** some glows, color filters and screen distortions are left out, the Epilogue's last picture and the chapters' end pictures are shown at half size, and the mountain doesn't turn: it fades from one view to the next.
* **Farewell isn't here:** the free chapter added after the game's release doesn't fit.
* **Reporting a bug:** turn on Options, then Room Code, and the corner of the screen shows which room you are in.
* **The game's cheat code works:** in the Prologue, walk left from the start into the hidden room, then press left, right, var, toolbox, up, up, down, left, toolbox and OK (toolbox is the grab key: use yours if you changed it). Every chapter opens with all its checkpoints, B-sides and C-sides, and the chapter panel gets a Room list to start anywhere.
diff --git a/games/celeste/src/celeste.h b/games/celeste/src/celeste.h
index 27a43147..f315e99f 100644
--- a/games/celeste/src/celeste.h
+++ b/games/celeste/src/celeste.h
@@ -151,6 +151,7 @@ typedef struct {
const uint8_t *map; /* TF_NIB: its colors (count, then their palette indices) */
} Tex;
enum { TF_RLE = 0, TF_RAW4 = 2, TF_ROW8 = 4, TF_NIB = 8, TF_SHARED = 16 }; /* ROW8, NIB, SHARED: drawn from flash only */
+#define ROW8_MAX 240 /* TF_ROW8 rows are shorter (lengths from it up: tools/pack.py direct_rows) */
void tex_row(const Tex *t, int r, uint8_t *out); /* row r's palette indices (0: transparent) */
bool tex_get(uint16_t id, Tex *t); /* false if not loaded (packed and not cached) */
const uint16_t *pal_colors(uint16_t pal, int *n);
@@ -173,6 +174,8 @@ bool res_cached(uint16_t id);
extern uint8_t *g_chapter_ram; /* the chapter files' own tables, while it is played */
extern uint8_t *g_chram[16]; /* each chapter file's (src/chN.c) part of it */
void res_chapter_ram(uint32_t bytes);
+uint16_t *res_picture_ram(uint32_t bytes); /* the menus' big picture, at the same place */
+extern uint8_t g_res_tops; /* changes when they take it (or a chapter does) */
void res_flush(void);
int tex_half_extent(uint16_t id); /* half the bigger side of its frame, known without loading it */
extern uint16_t g_res_frame;
@@ -212,6 +215,11 @@ void gfx_circle(float x, float y, float r, uint16_t c, uint8_t alpha, int resolu
/* layers drawn by callbacks, once per strip: y0 and y1 are view rows */
typedef void (*StripFn)(uint16_t *strip, int y0, int y1, void *ctx);
void gfx_custom(StripFn fn, void *ctx, int y0, int y1);
+/* the menus' big pictures (pic.c): decoded half size, drawn twice as big at view (x, y) by pic_strip (a gfx_custom) */
+typedef struct { const uint16_t *px; int16_t w, h, x, y; uint8_t alpha; } PicLayer;
+int pic_count(void);
+bool pic_decode(int id, uint16_t *out, int *w, int *h);
+void pic_strip(uint16_t *strip, int sy0, int sy1, void *ctx);
void gfx_keep(bool on); /* the layers that must be drawn (tiles, stylegrounds in front): commands kept for them */
void blit_line(uint16_t *strip, int sy0, int sy1, float x0, float y0, float x1, float y1, uint16_t col, uint8_t alpha);
void blit_rect(uint16_t *strip, int sy0, int sy1, float x, float y, float w, float h, uint16_t col, uint8_t alpha);
diff --git a/games/celeste/src/ch7.c b/games/celeste/src/ch7.c
index cbb1b9e0..89cc6b49 100644
--- a/games/celeste/src/ch7.c
+++ b/games/celeste/src/ch7.c
@@ -763,7 +763,6 @@ static void new_ascendm(const EData *d) {
}
/* ---------------------------------------------------------------- CS07_Ending (the summit) */
-static void credits_begin(void);
typedef struct {
Cutscene cs;
Ent *badeline, *tb;
@@ -856,10 +855,7 @@ static void ending7_tick(Ent *e) {
if (s->cam2_on == 2) s->cam2_on = 1;
else if (s->cam2_on && !camera_to(&s->cam2, s->cam2_to, 6, ease_cube_inout)) s->cam2_on = 0;
}
-static void ending7_wiped(void) {
- if (g_session.mode == M_A) credits_begin(); /* AreaComplete, then the credits (in this chapter's credits rooms) */
- else level_complete_area(false, true);
-}
+static void ending7_wiped(void) { level_complete_area(false, true); } /* AreaComplete (then the credits: menu.c) */
static void ending7_end(Ent *e, bool skipped) { /* Level.CompleteArea(spotlightWipe: false), Duration 2, EndTimer 1 */
(void)e, (void)skipped;
g_level.pause_lock = true;
@@ -992,13 +988,6 @@ enum { OFF_credits = ((END_streaks + 7) & ~7), END_credits = OFF_credits + (int)
#define cr (*(Credits *)(void *)(g_chram[7] + OFF_credits))
static bool have_ch7(void) { return g_level.ch && (rd16(g_level.ch + CH_FILES) >> 7 & 1); }
-static void credits_begin(void) { /* AreaComplete: the session goes on in credits-summit, with CS07_Credits */
- memset(&cr, 0, sizeof cr);
- cr.active = 1;
- cr.fade = 1;
- g_session.has_respawn = 0;
- level_goto("credits-summit");
-}
/* the Fill backdrop: black over the background */
static void fill_render(Ent *e) {
(void)e;
@@ -1736,7 +1725,14 @@ static void credits_render(Ent *e) {
static const EntClass CREDITS = {.name = "CS07_Credits", .update = credits_update, .render = credits_render};
static const EntClass CREDITSPOST = {.name = "CS07_CreditsPostUpdate", .update = credits_post};
/* a room of the credits loads: the cutscene, its backdrop fill and its post update are in it */
+uint8_t g_credits_next; /* the session goes on in credits-summit, with CS07_Credits (after AreaComplete: game_credits) */
static void credits_room(void) {
+ if (g_credits_next && have_ch7()) {
+ g_credits_next = 0;
+ memset(&cr, 0, sizeof cr);
+ cr.active = 1;
+ cr.fade = 1;
+ }
if (!have_ch7() || !cr.active || !g_level.room) return;
for (int i = 0; i < g_nents; i++) /* (one per load) */
if (g_ents[i].cls == &CREDITS) return;
diff --git a/games/celeste/src/data.bin b/games/celeste/src/data.bin
index 301f547f..7638a1b9 100644
Binary files a/games/celeste/src/data.bin and b/games/celeste/src/data.bin differ
diff --git a/games/celeste/src/data.h b/games/celeste/src/data.h
index cf9cc604..bc397da6 100644
--- a/games/celeste/src/data.h
+++ b/games/celeste/src/data.h
@@ -19,6 +19,7 @@
#define SEC_DIALOG 14
#define SEC_TEXDIM 15
#define SEC_UISTR 16
+#define SEC_PICS 17
#define SB_flutterBird 0
#define A_flutterBird_idle 0
@@ -7421,5 +7422,9 @@ static const uint8_t TRIG_ATTR_SIZE[] = {12,14,4,8,4,4,10,14,14,6,6,4,12,4,4,6,6
#define SG_tentacles 16
#define SG_blackhole 17
#define SG_starfield 18
+#define PIC_COMPLETE 0 /* the end screens, in COMPLETE_AREAS' order */
+#define PIC_MOUNTAIN 8 /* the mountain from each chapter's Idle camera */
+#define PIC_MAIN 18 /* and from the main menu's */
+static const int16_t PIC_SLIDE[8][2] = {{0, 800}, {0, 800}, {0, 800}, {0, 800}, {0, 800}, {0, 800}, {0, 800}, {0, 200}}; /* StartScroll - CenterScroll */
#endif
diff --git a/games/celeste/src/game.c b/games/celeste/src/game.c
index d1c2e669..ae888738 100644
--- a/games/celeste/src/game.c
+++ b/games/celeste/src/game.c
@@ -25,6 +25,20 @@ void game_play(int chapter, int checkpoint) {
level_start(resume ? INTRO_RESPAWN : session_intro(true));
}
+/* AreaComplete after the Summit's A-side: the session goes on in credits-summit, the credits on (ch7.c) */
+void game_credits(void) {
+ extern uint8_t g_credits_next;
+ int r = chapter_find_room(g_session.chapter, "credits-summit");
+ if (r < 0) return;
+ g_session.level = (uint8_t)r, g_session.has_respawn = 0;
+ g_credits_next = 1;
+ g_save.has_session = 1;
+ g_in_level = true;
+ g_menu = 0;
+ hud_reset();
+ level_start(INTRO_NONE);
+}
+
void game_init(void) {
res_init();
rnd_seed(&g_rnd, 0);
@@ -58,7 +72,7 @@ void game_level_exit(int mode) {
g_in_level = false;
wipe_start(WIPE_FADE, true, NULL);
if (mode == LEXIT_SAVEQUIT) menu_open_main();
- else menu_open_overworld(mode == LEXIT_COMPLETED, mode == LEXIT_COMPLETED && g_should_advance);
+ else menu_open_overworld(mode == LEXIT_COMPLETED && !g_level.in_credits, mode == LEXIT_COMPLETED && g_should_advance);
}
/* Home: the run is kept (Save & Quit) */
diff --git a/games/celeste/src/gfx.c b/games/celeste/src/gfx.c
index 4d1bba0e..0c7050a0 100644
--- a/games/celeste/src/gfx.c
+++ b/games/celeste/src/gfx.c
@@ -261,7 +261,8 @@ static inline void span_lit(uint16_t *d, int n, int step, const uint8_t *s) {
/* ---------------------------------------------------------------- blits */
/* an RLE texture's row r: its ops [*begin, *end). TF_ROW8 rows are found by adding the lengths
- * up, from the last row asked for when it is the same texture */
+ * up, from the last row asked for when it is the same texture; a length from ROW8_MAX up is a row met before
+ * (in flash: tools/pack.py direct_rows), three bytes: its length and where it is in DIRECT */
static const uint8_t *row_ops(const Tex *t, int r, const uint8_t **end) {
if (!(t->fmt & TF_ROW8)) {
const uint16_t *offs = (const uint16_t *)(const void *)t->px;
@@ -276,8 +277,13 @@ static const uint8_t *row_ops(const Tex *t, int r, const uint8_t **end) {
int i;
if (last_px == t->px && last_r <= r && last_gen == g_res_gen) p = last_p, i = last_r;
else p = t->px + t->h, i = 0;
- for (; i < r; i++) p += lens[i];
+ for (; i < r; i++) p += lens[i] >= ROW8_MAX ? 3 : lens[i];
last_px = t->px, last_r = r, last_p = p, last_gen = g_res_gen;
+ if (lens[r] >= ROW8_MAX) {
+ const uint8_t *o = section(SEC_DIRECT) + ((uint32_t)(lens[r] - ROW8_MAX) << 16 | p[1] | p[2] << 8);
+ *end = o + p[0];
+ return o;
+ }
*end = p + lens[r];
return p;
}
diff --git a/games/celeste/src/level.h b/games/celeste/src/level.h
index c307ade7..54d90214 100644
--- a/games/celeste/src/level.h
+++ b/games/celeste/src/level.h
@@ -254,6 +254,7 @@ void hud_update(void); /* TotalStrawberriesDisplay */
void hud_reset(void);
extern bool g_in_level;
void game_play(int chapter, int checkpoint); /* game.c: a chapter from a checkpoint (-1: start), or the saved session (chapter -1) */
+void game_credits(void); /* game.c: the Summit's credits, after its AreaComplete */
void level_start(int intro); /* the session's chapter, at its level */
void level_update(void);
diff --git a/games/celeste/src/menu.c b/games/celeste/src/menu.c
index 520c5477..e3b96ad7 100644
--- a/games/celeste/src/menu.c
+++ b/games/celeste/src/menu.c
@@ -16,9 +16,12 @@ static struct {
int16_t room; /* the panel's room picker (cheat mode): the room chosen, -1 when closed */
uint8_t hold, last_dir; /* the arrows' repeat */
uint8_t advance; /* after a first completion: 1 the panel waits, 2 and 3 the chapter select moves on */
+ uint8_t leaving; /* the chapter's end: wiping out to the overworld */
float t, wig, repeat;
} M;
uint8_t g_menu; /* the screen on (S_NONE while playing) */
+/* the big picture behind the screen (pic.c): the one in the cache (with g_res_tops then), how far it faded in */
+static struct { int8_t id; uint8_t tops; float fade; PicLayer l; } P = {.id = -1};
/* ---------------------------------------------------------------- drawing: pictures, then words */
static int pass; /* 0: pictures and boxes (commands), 1: words (into the strip) */
@@ -44,18 +47,24 @@ static uint16_t highlight(void) { /* TextMenu.HighlightColor: A and B in turn
/* HiresSnow's overlay over black: Overworld "overlay" added at White * 0.45 (x 0.2025, stored so, opaque),
* scrolling 32 and 20 pixels a second of 1920 x 1080, wrapping */
-static void snow_overlay(float time) {
+static void snow_overlay(float time, uint8_t flags) {
Tex t;
if (!tex_get(T__overlay, &t)) return;
int w = t.fw * t.scale, h = t.fh * t.scale;
int ox = (int)(time * 32 / 6) % w, oy = (int)(time * 20 / 6) % h;
for (int j = 0; j < 2; j++)
- for (int i = 0; i < 2; i++) gfx_tex(T__overlay, (float)(ox - i * w), (float)(oy - j * h), 0, WHITE, 255);
+ for (int i = 0; i < 2; i++) gfx_tex(T__overlay, (float)(ox - i * w), (float)(oy - j * h), flags, WHITE, 255);
+}
+/* the overworld behind the menus: the mountain, then HiresSnow (its overlay, added, and 50 flakes blown left) */
+static bool picture(void) {
+ if (P.id < 0 || P.tops != g_res_tops) return false;
+ if (!pass) gfx_custom(pic_strip, &P.l, 0, VIEW_H);
+ return true;
}
-/* the overworld behind the menus: HiresSnow (its overlay and 50 flakes blown left) */
static void backdrop(void) {
+ bool mountain = picture();
if (pass) return;
- snow_overlay(M.t + 100);
+ snow_overlay(M.t + 100, mountain ? GF_ADD : 0);
hires_snow(M.t + 100, 1);
}
/* HiresSnow's flakes at `time`, faded by alpha (screen coordinates) */
@@ -94,7 +103,7 @@ static void inputs_end(void) {
if (!g_in.move_x && !g_in.move_y) M.last_dir = 0;
}
static void go(int screen, int sel) {
- M.screen = (uint8_t)screen, M.sel = (int8_t)sel, M.t = 0, M.wig = 0, M.room = -1;
+ M.screen = (uint8_t)screen, M.sel = (int8_t)sel, M.t = 0, M.wig = 0, M.room = -1, M.leaving = 0;
g_menu = (uint8_t)screen;
btn_consume(&g_in.confirm);
btn_consume(&g_in.back);
@@ -277,7 +286,7 @@ static void reflection(float a, float sc) {
}
static void title_draw(void) {
float a = M.sel ? ease_cube_inout(clampf((M.t - 0.4f) / 0.6f, 0, 1)) : 1, sc = 0.5f + 0.5f * sinf(a * PI_F / 2);
- if (!pass) snow_overlay(M.t + 100);
+ if (!pass) snow_overlay(M.t + 100, 0);
pic(T__logo, 960, 540, 0.5f, 0.5f, sc, WHITE, a8(a));
if (!pass && a > 0) reflection(a, sc);
if (!pass) hires_snow(M.t + 100, 1);
@@ -578,34 +587,65 @@ static void credits_update(void) {
}
/* ---------------------------------------------------------------- the chapter's end (AreaComplete) */
+static int complete_pic(int a) { return PIC_COMPLETE + (a == 9 ? 7 : a - 1); } /* (pictures.py COMPLETE_AREAS) */
+static void leave_complete(void) { /* the FadeWipe's end: the overworld (its panel) */
+ go(S_PANEL, 0);
+ wipe_start(WIPE_FADE, true, NULL);
+}
static void complete_draw(void) {
- int a = M.area;
- box(0, 0, 1920, 1080, rgb(TITLE_BASE[a]), 255);
- box(0, 760, 1920, 320, rgb(TITLE_ACCENT[a]), 255);
- pic(area_icon(a), 960, 300, 0.5f, 0.5f, 1.5f, WHITE, 255);
- ModeStats *ms = &g_save.modes[a][M.mode];
- const char *head = M.mode == M_B ? "AREACOMPLETE_BSIDE" : M.mode == M_C ? "AREACOMPLETE_CSIDE"
- : (ms->flags & MS_FULLCLEAR) ? "AREACOMPLETE_NORMAL_FULLCLEAR" : "AREACOMPLETE_NORMAL";
- say(ui_str(head), 960, 560, 0.5f, 0.5f, 2, a == 7 ? 0 : WHITE, 255);
- char b[32], *p = b;
- int ch = chapter_index(a, M.mode);
- p += uitoa(popcount64(ms->berries), p);
- *p++ = '/';
- uitoa(ch >= 0 ? chapter_at(ch)[CH_DETECTED] : 0, p);
- if (!interlude(a)) {
- pic(T__collectables_strawberry, 640, 900, 0.5f, 0.5f, 0.8f, WHITE, 255);
- say(b, 700, 900, 0, 0.5f, 1, WHITE, 255);
- p = b;
- uitoa((int)g_session.deaths, p);
- pic(T__collectables_skullBlue, 1060, 900, 0.5f, 0.5f, 0.8f, WHITE, 255);
- say(b, 1110, 900, 0, 0.5f, 1, WHITE, 255);
+ int a = M.area, k = complete_pic(a) - PIC_COMPLETE;
+ /* CompleteRenderer: a second, then 1.5 to slide in (SineOut) out of black; its layers move as one here (as the
+ * nearer ones do, a tenth of the scroll) */
+ float p = clampf((M.t - 1) / 1.5f, 0, 1), e = ease_sine_out(p), shown = fminf(p * 2, 1); /* (words: under the fade) */
+ P.l.x = (int16_t)roundf(-PIC_SLIDE[k][0] * (1 - e) / 60), P.l.y = (int16_t)roundf(-PIC_SLIDE[k][1] * (1 - e) / 60);
+ if (!picture()) box(0, 0, 1920, 1080, rgb(TITLE_BASE[a]), 255);
+ if (a != 7) { /* AreaCompleteTitle (the Summit has none) */
+ ModeStats *ms = &g_save.modes[a][M.mode];
+ const char *head = ui_str(M.mode == M_B ? "AREACOMPLETE_BSIDE" : M.mode == M_C ? "AREACOMPLETE_CSIDE"
+ : (ms->flags & MS_FULLCLEAR) ? "AREACOMPLETE_NORMAL_FULLCLEAR" : "AREACOMPLETE_NORMAL");
+ float rect = ease_sine_out(clampf((M.t - 2.6f) / 0.5f, 0, 1)); /* DrawLineUI, after 2.6 */
+ if (rect > 0) box(0, 160, 1920 * rect, 80, 0, 166);
+ float sc = fminf(1600 / text_measure(head), 3), x = 960 - text_width(head, sc) / 2, y = 200 + 80 * sc / 2;
+ char c[2] = {0, 0};
+ for (int i = 0; head[i]; i++) { /* each letter in its turn along its curve, from 60 below to 100 above */
+ c[0] = head[i];
+ float w = text_width(c, sc), t = clampf((M.t - 0.2f - i * 0.02f) * 4, 0, 1);
+ if (head[i] != ' ' && t > 0) {
+ float ly = (1 - t) * (1 - t) * (y + 60) + 2 * (1 - t) * t * y + t * t * (y - 100);
+ uint8_t al = a8(clampf(t * 3, 0, 1) * shown);
+ if (t >= 1) say(c, x + w / 2, ly + 3.5f * sc, 0.5f, 1, sc, 0, a8(shown)); /* its shadow */
+ say(c, x + w / 2, ly, 0.5f, 1, sc, WHITE, al);
+ }
+ x += w;
+ }
+ }
+ int clock = g_save.options >> 2 & 3;
+ if (clock && M.t > 1.1f) { /* AreaComplete.Info: the speedrun clock, in from the left */
+ char b[24];
+ float x = 80 - 300 * (1 - ease_cube_out(clampf((M.t - 1.1f) * 2, 0, 1)));
+ time_text(clock == 2 ? g_save.time : g_session.time, b);
+ uint8_t al = a8(shown);
+ say(b, x, clock == 2 ? 984 : 1000, 0, 1, 1, WHITE, al);
+ if (clock == 2) {
+ const char *ch = ui_str("OPTIONS_SPEEDRUN_CHAPTER");
+ say(ch, x, 1024, 0, 1, 0.6f, WHITE, al);
+ say(":", x + text_width(ch, 0.6f), 1024, 0, 1, 0.6f, WHITE, al);
+ time_text(g_session.time, b);
+ say(b, x + text_width(ch, 0.6f) + text_width(":", 0.6f) + 8, 1024, 0, 1, 0.6f, WHITE, al);
+ }
}
- time_text(g_session.time, b);
- say(b, 960, 1000, 0.5f, 0.5f, 0.8f, WHITE, 255);
- if (M.t > 1 && fmodf(M.t, 1) < 0.75f) pic(T__textboxbutton, 1824, 984, 0.5f, 0.5f, 1, WHITE, 255);
+ if (p < 0.5f) box(0, 0, 1920, 1080, 0, a8(1 - p * 2)); /* fadeAlpha */
+ if (M.t < 2) hires_snow(M.t + 100, 1 - M.t / 2); /* the level's snow, going */
+}
+static void to_credits(void) { /* the Summit's A-side: its credits */
+ g_menu = M.screen = S_NONE;
+ game_credits();
}
static void complete_update(void) {
- if (M.t > 1 && (confirm() || cancel())) go(S_PANEL, 0);
+ if (M.t > 2.7f && !M.leaving && confirm()) { /* once slid in (and 0.2 more) */
+ M.leaving = 1;
+ wipe_start(WIPE_FADE, false, M.area == 7 && M.mode == M_A ? to_credits : leave_complete);
+ }
}
/* ---------------------------------------------------------------- the pause menu (Level.Pause) */
@@ -761,6 +801,36 @@ static void hud_draw(void) {
}
/* ---------------------------------------------------------------- the frame */
+/* the picture behind the screen: the chapter's end, the mountain from the chapter chosen, or the main menu's */
+static int wanted_picture(void) {
+ switch (M.screen) {
+ case S_COMPLETE: return complete_pic(M.area);
+ case S_CHAPTERS:
+ case S_PANEL: return PIC_MOUNTAIN + M.area;
+ case S_OPTIONS: return M.back == S_MAIN ? PIC_MAIN : -1;
+ case S_MAIN:
+ case S_KEYS:
+ case S_CREDITS: return PIC_MAIN;
+ }
+ return -1;
+}
+static void picture_update(void) {
+ int id = wanted_picture();
+ if (g_in_level || id < 0) return; /* (the cache's top is the chapter's while it is played) */
+ if (id != P.id || P.tops != g_res_tops) {
+ int w, h;
+ P.l.px = res_picture_ram(160 * 90 * 2);
+ if (!pic_decode(id, (uint16_t *)P.l.px, &w, &h) || w > 160 || h > 90) {
+ P.id = -1;
+ return;
+ }
+ P.id = (int8_t)id, P.tops = g_res_tops;
+ P.l.w = (int16_t)w, P.l.h = (int16_t)h, P.l.x = P.l.y = 0;
+ P.fade = M.screen == S_COMPLETE ? 1 : 0; /* (the mountain eases in, as its camera would move) */
+ }
+ P.fade = approach(P.fade, 1, RAW_DT * 2.5f);
+ P.l.alpha = a8(P.fade);
+}
void menu_update(void) {
M.t += RAW_DT, M.wig += RAW_DT;
switch (M.screen) {
@@ -776,6 +846,7 @@ void menu_update(void) {
case S_PAUSE: pause_update(); break;
case S_CONFIRM: confirm_update(); break;
}
+ picture_update();
inputs_end();
}
static void draw_screen(void) {
diff --git a/games/celeste/src/pic.c b/games/celeste/src/pic.c
new file mode 100644
index 00000000..e04825e1
--- /dev/null
+++ b/games/celeste/src/pic.c
@@ -0,0 +1,133 @@
+#if defined(__GNUC__) && !defined(__clang__)
+#pragma GCC optimize("Os") /* decoded once per picture: smaller over faster */
+#endif
+/* The big pictures of the menus: the chapters' end screens (CompleteRenderer) and the mountain behind the chapter
+ * select (MountainRenderer), half size as baseline JPEG (tools/pictures.py: its markers taken out). One is decoded
+ * into the cache at a time and drawn twice as big, smoothly. */
+#include "celeste.h"
+
+/* PICS: u16 n, u16 0, then per picture u16 w, h, u32 offset (from the section), u32 bytes; u8 quant[2][64] (zigzag
+ * order); the Huffman tables DC0, AC0, DC1, AC1 (16 counts, then the symbols); the pictures' entropy coded data */
+static const float COS[64] = {
+ 0.353553f, 0.353553f, 0.353553f, 0.353553f, 0.353553f, 0.353553f, 0.353553f, 0.353553f, 0.490393f, 0.415735f,
+ 0.277785f, 0.097545f, -0.097545f, -0.277785f, -0.415735f, -0.490393f, 0.461940f, 0.191342f, -0.191342f, -0.461940f,
+ -0.461940f, -0.191342f, 0.191342f, 0.461940f, 0.415735f, -0.097545f, -0.490393f, -0.277785f, 0.277785f, 0.490393f,
+ 0.097545f, -0.415735f, 0.353553f, -0.353553f, -0.353553f, 0.353553f, 0.353553f, -0.353553f, -0.353553f, 0.353553f,
+ 0.277785f, -0.490393f, 0.097545f, 0.415735f, -0.415735f, -0.097545f, 0.490393f, -0.277785f, 0.191342f, -0.461940f,
+ 0.461940f, -0.191342f, -0.191342f, 0.461940f, -0.461940f, 0.191342f, 0.097545f, -0.277785f, 0.415735f, -0.490393f,
+ 0.490393f, -0.415735f, 0.277785f, -0.097545f};
+static const uint8_t ZIGZAG[64] = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48,
+ 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23,
+ 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63};
+
+typedef struct {
+ const uint8_t *p, *end;
+ uint32_t acc;
+ int n;
+} Bits;
+static int bit(Bits *b) {
+ if (!b->n) b->acc = b->p < b->end ? *b->p++ : 0, b->n = 8;
+ return b->acc >> --b->n & 1;
+}
+static int receive(Bits *b, int s) { /* s bits, then their sign (EXTEND) */
+ int v = 0;
+ for (int i = 0; i < s; i++) v = v << 1 | bit(b);
+ return s && v < 1 << (s - 1) ? v - (1 << s) + 1 : v;
+}
+static int huff(Bits *b, const uint8_t *t) { /* t: 16 counts, then the symbols (canonical codes) */
+ int code = 0, first = 0, index = 0;
+ for (int len = 0; len < 16; len++) {
+ code |= bit(b);
+ int n = t[len];
+ if (code - first < n) return t[16 + index + code - first];
+ index += n, first = (first + n) << 1, code <<= 1;
+ }
+ return 0;
+}
+
+/* one 8x8 block: its coefficients, dequantized, then the inverse DCT into out (stride bytes a row), level shifted */
+static void block(Bits *b, const uint8_t *dc, const uint8_t *ac, const uint8_t *q, int *pred, uint8_t *out, int stride) {
+ float f[64], t[64];
+ memset(f, 0, sizeof f);
+ *pred += receive(b, huff(b, dc));
+ f[0] = (float)(*pred * q[0]);
+ for (int k = 1; k < 64;) {
+ int rs = huff(b, ac), r = rs >> 4, s = rs & 15;
+ if (!s) {
+ if (r != 15) break; /* end of block */
+ k += 16;
+ continue;
+ }
+ k += r;
+ if (k > 63) break;
+ f[ZIGZAG[k]] = (float)(receive(b, s) * q[k]);
+ k++;
+ }
+ for (int v = 0; v < 8; v++) /* rows: t[v][x] = sum over u of f[v][u] C[u][x] */
+ for (int x = 0; x < 8; x++) {
+ float s = 0;
+ for (int u = 0; u < 8; u++) s += f[v * 8 + u] * COS[u * 8 + x];
+ t[v * 8 + x] = s;
+ }
+ for (int y = 0; y < 8; y++)
+ for (int x = 0; x < 8; x++) {
+ float s = 128.5f;
+ for (int v = 0; v < 8; v++) s += t[v * 8 + x] * COS[v * 8 + y];
+ out[y * stride + x] = (uint8_t)clampi((int)s, 0, 255);
+ }
+}
+
+int pic_count(void) { return rd16(section(SEC_PICS)); }
+
+/* picture `id` into out (w * h colors, its size): false if there is none */
+bool pic_decode(int id, uint16_t *out, int *w, int *h) {
+ const uint8_t *s = section(SEC_PICS);
+ int n = rd16(s);
+ if (id < 0 || id >= n) return false;
+ const uint8_t *e = s + 4 + 12 * id, *q = s + 4 + 12 * n, *t = q + 128, *tab[4];
+ for (int i = 0; i < 4; i++) {
+ tab[i] = t;
+ int k = 16;
+ for (int j = 0; j < 16; j++) k += t[j];
+ t += k;
+ }
+ *w = rd16(e), *h = rd16(e + 2);
+ Bits b = {s + rd32(e + 4), s + rd32(e + 4) + rd32(e + 8), 0, 0};
+ int pred[3] = {0, 0, 0};
+ uint8_t y[256], cb[64], cr[64];
+ for (int my = 0; my < *h; my += 16)
+ for (int mx = 0; mx < *w; mx += 16) { /* 4:2:0: four luma blocks, then one of each chroma */
+ for (int k = 0; k < 4; k++) block(&b, tab[0], tab[1], q, &pred[0], y + (k >> 1) * 128 + (k & 1) * 8, 16);
+ block(&b, tab[2], tab[3], q + 64, &pred[1], cb, 8);
+ block(&b, tab[2], tab[3], q + 64, &pred[2], cr, 8);
+ for (int py = 0; py < 16 && my + py < *h; py++)
+ for (int px = 0; px < 16 && mx + px < *w; px++) {
+ int Y = y[py * 16 + px], c = (py >> 1) * 8 + (px >> 1), u = cb[c] - 128, v = cr[c] - 128;
+ int r = clampi(Y + ((91881 * v) >> 16), 0, 255), g = clampi(Y - ((22554 * u + 46802 * v) >> 16), 0, 255),
+ bl = clampi(Y + ((116130 * u) >> 16), 0, 255);
+ out[(my + py) * *w + mx + px] = (uint16_t)((r >> 3) << 11 | (g >> 2) << 5 | bl >> 3);
+ }
+ }
+ return true;
+}
+
+/* drawn twice as big with bilinear filtering (a strip layer: ctx is a PicLayer) */
+static inline uint32_t spread(uint16_t c) { return (c | (uint32_t)c << 16) & 0x07E0F81Fu; }
+void pic_strip(uint16_t *strip, int sy0, int sy1, void *ctx) {
+ const PicLayer *l = ctx;
+ int w = l->w, h = l->h;
+ for (int Y = sy0; Y < sy1; Y++) {
+ int ly = Y - l->y, j = ly >> 1, j2 = ly & 1 ? j + 1 : j - 1; /* the nearer row (3/4), then the other (1/4) */
+ j = clampi(j, 0, h - 1), j2 = clampi(j2, 0, h - 1);
+ const uint16_t *ra = l->px + j * w, *rb = l->px + j2 * w;
+ uint16_t *row = strip + (Y - sy0) * VIEW_W;
+ for (int X = 0; X < VIEW_W; X++) {
+ int lx = X - l->x, i = lx >> 1, i2 = lx & 1 ? i + 1 : i - 1;
+ i = clampi(i, 0, w - 1), i2 = clampi(i2, 0, w - 1);
+ uint32_t a = 3 * spread(ra[i]) + spread(rb[i]), c = 3 * spread(ra[i2]) + spread(rb[i2]);
+ uint32_t v = ((3 * a + c) >> 4) & 0x07E0F81Fu;
+ uint16_t px = (uint16_t)(v | v >> 16);
+ row[X] = l->alpha >= 255 ? px : blend565(row[X], px, l->alpha + 1);
+ }
+ }
+}
diff --git a/games/celeste/src/res.c b/games/celeste/src/res.c
index d9c957a6..e32b72ae 100644
--- a/games/celeste/src/res.c
+++ b/games/celeste/src/res.c
@@ -34,7 +34,7 @@ bool pal_opaque(uint16_t pal) {
}
/* ---------------------------------------------------------------- LZMA streams */
-#define DICT_SIZE 8192
+#define DICT_SIZE 9600 /* (tools/pack.py DICT: the strip, all of it) */
extern uint16_t g_strip[]; /* gfx.c: the ring buffer borrows the strip */
static CLzmaProb probs[1984 + 768]; /* NUM_BASE_PROBS + LZMA_LIT_SIZE << (lc + lp) */
@@ -359,9 +359,9 @@ static void finish_tex(Reader *r) {
uint16_t *rows = (uint16_t *)(void *)(data + ms);
rows[e->h] = (uint16_t)(r->out - (uint8_t *)rows);
e->bytes = (uint16_t)(r->out - data);
- /* rows all shorter than 256 bytes: a byte each for their lengths (TF_ROW8) */
+ /* rows all shorter than ROW8_MAX bytes: a byte each for their lengths (TF_ROW8) */
bool small = true;
- for (int y = 0; y < e->h && small; y++) small = rows[y + 1] - rows[y] < 256;
+ for (int y = 0; y < e->h && small; y++) small = rows[y + 1] - rows[y] < ROW8_MAX;
if (small) {
uint8_t *lens = (uint8_t *)rows;
uint32_t ops = 2u * (e->h + 1), n = rows[e->h] - ops;
@@ -591,16 +591,25 @@ uint8_t *res_scratch(uint32_t need, uint32_t *size) {
/* a chapter's own tables (its pools of torches, clutter...) take the top of the cache while it is played:
* `bytes` of zeroes, everything loaded before forgotten */
uint8_t *g_chapter_ram;
-void res_chapter_ram(uint32_t bytes) {
- bytes = (bytes + 7) & ~7u;
- if (bytes > CACHE_BYTES / 2) bytes = CACHE_BYTES / 2;
+uint8_t g_res_tops; /* counts the times the top changed hands */
+static void top_ram(uint32_t bytes) {
cache_top = 0;
- g_res_gen++;
+ g_res_gen++, g_res_tops++;
hash_rebuild();
cache_limit = CACHE_BYTES - bytes;
g_chapter_ram = cache + cache_limit;
+}
+void res_chapter_ram(uint32_t bytes) {
+ bytes = (bytes + 7) & ~7u;
+ if (bytes > CACHE_BYTES / 2) bytes = CACHE_BYTES / 2;
+ top_ram(bytes);
memset(g_chapter_ram, 0, bytes);
}
+/* the menus' big picture (pic.c) the same way, while no chapter is played */
+uint16_t *res_picture_ram(uint32_t bytes) {
+ top_ram((bytes + 7) & ~7u);
+ return (uint16_t *)(void *)g_chapter_ram;
+}
/* every loaded texture forgotten (the chapter's memory stays) */
void res_flush(void) {
diff --git a/games/celeste/tools/pack.py b/games/celeste/tools/pack.py
index 3965ce94..cef97c30 100644
--- a/games/celeste/tools/pack.py
+++ b/games/celeste/tools/pack.py
@@ -23,11 +23,13 @@ sys.path.insert(0, os.path.dirname(__file__))
from cel import CELESTE, Atlas, Element, read_map # noqa: E402
import tiles as T # noqa: E402
import entities as E # noqa: E402
+import pictures # noqa: E402
HERE = os.path.dirname(os.path.abspath(__file__))
OUT_BIN = os.path.join(HERE, "..", "src", "data.bin")
OUT_H = os.path.join(HERE, "..", "src", "data.h")
TORCH_BITS = 448 # Session.torches (src/level.h)
+PIC_HEADER = []
MAP_AREA = {"0-Intro": 0, "1-ForsakenCity": 1, "1H-ForsakenCity": 1, "1X-ForsakenCity": 1, "2-OldSite": 2,
"2H-OldSite": 2, "2X-OldSite": 2, "3-CelestialResort": 3, "3H-CelestialResort": 3,
@@ -49,7 +51,7 @@ CUTSCENE_ANIMS = {"tentacle_grab", "tentacle_grabbed", "tentacle_pull", "tentacl
"bigFallRecover", "roll", "rollGetUp", "downed", "faint", "fainted", "hug", "spawn", "angry",
"laugh", "pretendDead"}
LAZY_ANIMS = []
-DICT = 8 * 1024 # LZMA dictionary: the engine decodes through a ring buffer this big
+DICT = 9600 # LZMA dictionary: the engine decodes through a ring buffer this big (its strip)
MARGIN = 2 # tiles kept around each room for the autotiler
# ------------------------------------------------------------------ writers
@@ -310,8 +312,47 @@ def rle_direct_parts(idx):
"""(format flags, local palette, pixels). With 15 colors or fewer (flag 8), a local palette (count,
then the colors' indices, in the order the pixels first have them: textures alike but for their
colors get the same pixels) and the literals two pixels a byte (low nibble first), runs' values
- local too; rows whose ops all fit in a byte (flag 4) get a byte each (their lengths) instead of
- u16 offsets (kept even, from the table's start)."""
+ local too; rows whose ops all take fewer than ROW8_MAX bytes (flag 4) get a byte each (their lengths)
+ instead of u16 offsets (kept even, from the table's start)."""
+ flags, colors, rows = rle_direct_rows(idx)
+ out = bytearray()
+ if flags & 4:
+ out += bytes(len(r) for r in rows)
+ else:
+ off = 2 * (len(rows) + 1)
+ for r in rows:
+ out += struct.pack("<H", off)
+ off += len(r)
+ out += struct.pack("<H", off)
+ for r in rows:
+ out += r
+ return flags, colors, bytes(out)
+
+
+ROW8_MAX = 240 # a flag-4 row's length byte from ROW8_MAX up: the row is another's (direct_rows)
+
+
+def direct_rows(rows, at, pool):
+ """A flag-4 texture's rows written at `at` in DIRECT, the rows met before only pointing at them: length byte
+ ROW8_MAX + (offset >> 16), then the row's length and the offset's low 16 bits (the engine: gfx.c row_ops)."""
+ lens, ops = bytearray(), bytearray()
+ base = at + len(rows)
+ for r in rows:
+ o = pool.get(r)
+ if o is not None:
+ assert o >> 16 < 256 - ROW8_MAX
+ lens.append(ROW8_MAX + (o >> 16))
+ ops += bytes((len(r), o & 255, o >> 8 & 255))
+ else:
+ if len(r) > 3:
+ pool[r] = base + len(ops)
+ lens.append(len(r))
+ ops += r
+ return bytes(lens + ops)
+
+
+def rle_direct_rows(idx):
+ """rle_direct_parts' (format flags, local palette, ops of each row)."""
flat = idx.ravel()
_, first = np.unique(flat, return_index=True)
uniq = [int(flat[i]) for i in sorted(first) if flat[i] != 0]
@@ -368,22 +409,12 @@ def rle_direct_parts(idx):
rows.append(bytes(body))
flags = 0
colors = b""
- out = bytearray()
if nib:
flags |= 8
colors = bytes([len(uniq)] + uniq)
- if all(len(r) < 256 for r in rows):
+ if all(len(r) < ROW8_MAX for r in rows):
flags |= 4
- out += bytes(len(r) for r in rows)
- else:
- off = 2 * (h + 1)
- for r in rows:
- out += struct.pack("<H", off)
- off += len(r)
- out += struct.pack("<H", off)
- for r in rows:
- out += r
- return flags, colors, bytes(out)
+ return flags, colors, rows
# ------------------------------------------------------------------ maps
@@ -1571,7 +1602,7 @@ def room_matches(pattern, room):
# ------------------------------------------------------------------ main
SECTIONS = ["TEX", "PAL", "PACKS", "DIRECT", "BANKS", "PMETA", "TILESETS", "CHAPTERS", "STRINGS", "BLOBS", "ANIMTILES",
- "DECALANIM", "TEXNAMES", "FONTS", "DIALOG", "TEXDIM", "UISTR"]
+ "DECALANIM", "TEXNAMES", "FONTS", "DIALOG", "TEXDIM", "UISTR", "PICS"]
def fnv24(s, basis=2166136261):
@@ -1906,6 +1937,7 @@ def main():
direct = W()
same = {}
bodies = {}
+ pool = {} # rows written, for the textures after them (direct_rows)
for t in TEX.list:
if t.kind == 1:
hw = W()
@@ -1929,7 +1961,7 @@ def main():
if colors and not flags & 4 and len(colors) & 1:
direct.u8(0)
bodies[(flags, body)] = len(direct)
- direct.raw(body)
+ direct.raw(direct_rows(rle_direct_rows(t.idx)[2], len(direct), pool) if flags & 4 else body)
byfam = collections.Counter()
for t in TEX.list:
if t.kind == 1:
@@ -2420,6 +2452,12 @@ def main():
w.raw(data)
sec["STRINGS"] = w
+ # ---- PICS: the end screens and the mountain (tools/pictures.py)
+ w = W()
+ pics, PIC_HEADER[:] = pictures.build()
+ w.raw(pics)
+ sec["PICS"] = w
+
# ---- write
out = W()
out.raw(b"CLST")
@@ -2473,6 +2511,7 @@ def write_header(bank_names):
L.append("#define ROOM_POOL_BYTES %d /* %s */" % ((ROOM_POOL[0] + 64 + 3) & ~3, ROOM_POOL[1]))
for i, s in enumerate(STYLE_EFFECTS):
L.append("#define SG_%s %d" % (s, i))
+ L += PIC_HEADER
L.append("")
L.append("#endif")
open(OUT_H, "w").write("\n".join(L) + "\n")
diff --git a/games/celeste/tools/pictures.py b/games/celeste/tools/pictures.py
new file mode 100644
index 00000000..d15cd58a
--- /dev/null
+++ b/games/celeste/tools/pictures.py
@@ -0,0 +1,350 @@
+"""The menus' big pictures, made from the game's files for tools/pack.py:
+
+- the chapters' end screens: CompleteScreens.xml's layers where they rest once slid in (CompleteRenderer), one
+ picture each;
+- the mountain behind the chapter select: the Overworld models (mountain, its Core wall, the buildings) with their
+ textures, the skybox and the fog ring, seen from each chapter's Idle camera (AreaViews.xml), as MountainModel draws
+ them (no lighting: its shader only samples the textures), with the vignette over them; and one from the main
+ menu's turning camera.
+
+All at half the view's size (160 x 90), as baseline JPEG (Pillow's, standard tables): src/pic.c decodes one into
+the cache and draws it twice as big. PICS section: u16 n, u16 0, per picture u16 w, h, u32 offset, u32 bytes; the
+quantization tables (2 x 64, zigzag order); the Huffman tables DC0, AC0, DC1, AC1 (16 counts, then the symbols);
+then the pictures' entropy coded data (no markers, no 0xFF00 stuffing)."""
+import io
+import math
+import os
+import struct
+import xml.etree.ElementTree as ET
+
+import numpy as np
+from PIL import Image
+
+from cel import CELESTE, Atlas, Reader, read_data
+
+W, H = 160, 90
+QUALITY = 50
+COMPLETE = ["ForsakenCity", "OldSite", "CelestialResort", "Cliffside", "MirrorTemple", "Fall", "Summit", "Core"]
+COMPLETE_AREAS = [1, 2, 3, 4, 5, 6, 7, 9] # AreaData.CompleteScreenName (the Prologue and the Epilogue have none)
+ATLASES = os.path.join(CELESTE, "Graphics", "Atlases")
+OVERWORLD = os.path.join(CELESTE, "Overworld")
+CACHE = os.environ.get("CELESTE_CACHE", "/tmp/celeste_cache")
+
+
+# ------------------------------------------------------------------ the chapters' end screens
+
+def _meta(atlas):
+ """A PackerNoAtlas atlas (an image file each): name -> (x, y, w, h, frame x, frame y)."""
+ r = Reader(open(os.path.join(ATLASES, atlas + ".meta"), "rb").read())
+ r.i32()
+ r.str()
+ r.i32()
+ out = {}
+ for _ in range(r.i16()):
+ r.str()
+ for _ in range(r.i16()):
+ path = r.str().replace("\\", "/")
+ x, y, w, h = r.i16(), r.i16(), r.i16(), r.i16()
+ fx, fy = r.i16(), r.i16()
+ r.i16()
+ r.i16()
+ out[path] = (x, y, w, h, fx, fy)
+ return out
+
+
+def complete_screen(name):
+ """CompleteRenderer's layers at rest (Scroll = CenterScroll), first frames, 1920 x 1080 RGB floats."""
+ screen = ET.parse(os.path.join(CELESTE, "Graphics", "CompleteScreens.xml")).getroot().find(name)
+ atlas = screen.get("atlas")
+ meta = _meta(atlas)
+
+ def pos(e):
+ return (float(e.get("x", 0)), float(e.get("y", 0))) if e is not None else (0.0, 0.0)
+ center, offset = pos(screen.find("center")), pos(screen.find("offset"))
+ out = np.zeros((1080, 1920, 3), np.float32)
+ for e in screen.find("layers"):
+ if e.tag != "layer":
+ continue
+ if "scroll" in e.attrib:
+ sx = sy = float(e.get("scroll"))
+ else:
+ sx, sy = float(e.get("scrollX", 0)), float(e.get("scrollY", 0))
+ x, y = pos(e)
+ x, y = x + offset[0], y + offset[1]
+ # GetScrollPosition(-Scroll), floored
+ px, py = math.floor(x - center[0] * sx), math.floor(y - center[1] * sy)
+ img = e.get("img").split(",")[0]
+ if img not in meta:
+ continue
+ ix, iy, iw, ih, fx, fy = meta[img]
+ data = read_data(os.path.join(ATLASES, atlas, img + ".data"))[iy:iy + ih, ix:ix + iw]
+ src = data[1:ih - 1, 1:iw - 1].astype(np.float32) / 255 * float(e.get("alpha", 1)) # (ClipRect less a pixel)
+ X0, Y0 = px - fx, py - fy # + DrawOffset
+ x0, y0 = max(X0, 0), max(Y0, 0)
+ x1, y1 = min(X0 + src.shape[1], 1920), min(Y0 + src.shape[0], 1080)
+ if x0 < x1 and y0 < y1:
+ s = src[y0 - Y0:y1 - Y0, x0 - X0:x1 - X0]
+ out[y0:y1, x0:x1] = s[..., :3] + out[y0:y1, x0:x1] * (1 - s[..., 3:4]) # (premultiplied)
+ return out
+
+
+def complete_slide(name):
+ """StartScroll - CenterScroll: how far the end screen slides in."""
+ screen = ET.parse(os.path.join(CELESTE, "Graphics", "CompleteScreens.xml")).getroot().find(name)
+ s, c = screen.find("start"), screen.find("center")
+ return (float(s.get("x", 0)) - float(c.get("x", 0)), float(s.get("y", 0)) - float(c.get("y", 0)))
+
+
+# ------------------------------------------------------------------ the mountain
+
+def _texture(name):
+ path = os.path.join(CACHE, "mountain_" + name + ".npy")
+ if os.path.exists(path):
+ return np.load(path)
+ a = read_data(os.path.join(ATLASES, "Mountain", name + ".data")).astype(np.float32) / 255
+ os.makedirs(CACHE, exist_ok=True)
+ np.save(path, a)
+ return a
+
+
+def _model(name):
+ """ObjModel: triangles (n, 3, 3) and their texture coordinates (n, 3, 2), v going down."""
+ vs, vts, P, T = [], [], [], []
+ for line in open(os.path.join(OVERWORLD, name + ".obj")):
+ a = line.split()
+ if not a:
+ continue
+ if a[0] == "v":
+ vs.append([float(x) for x in a[1:4]])
+ elif a[0] == "vt":
+ vts.append([float(x) for x in a[1:3]])
+ elif a[0] == "f":
+ idx = [s.split("/") for s in a[1:4]]
+ P.append([vs[int(i[0]) - 1] for i in idx])
+ T.append([[vts[int(i[1]) - 1][0], 1 - vts[int(i[1]) - 1][1]] for i in idx])
+ return np.array(P, np.float32), np.array(T, np.float32)
+
+
+def _views():
+ out = {}
+ for a in ET.parse(os.path.join(OVERWORLD, "AreaViews.xml")).getroot():
+ d = {"state": int(a.get("state"))}
+ for c in a:
+ if c.tag != "Cursor":
+ d[c.tag] = ([float(x) for x in c.get("position").split(",")],
+ [float(x) for x in c.get("target").split(",")])
+ out[int(a.get("id"))] = d
+ return out
+
+
+class Raster:
+ """Triangles with a depth buffer, perspective correct, textures sampled bilinearly
+ (CreatePerspectiveFieldOfView(pi / 4, 320 / 180, 0.25, 50))."""
+
+ def __init__(self, w, h):
+ self.w, self.h = w, h
+ self.f = 1 / math.tan(math.pi / 8)
+ self.color = np.zeros((h, w, 3), np.float32)
+ self.depth = np.full((h, w), np.inf, np.float32)
+
+ def draw(self, rot, origin, P, T, tex, tint=(1, 1, 1, 1), depth=True, blend=False, wrap=False):
+ cam = ((P.reshape(-1, 3) - origin) @ rot.T).reshape(-1, 3, 3)
+ w = -cam[..., 2]
+ cx, cy = self.f * 180 / 320 * cam[..., 0], self.f * cam[..., 1]
+ tint = np.array(tint, np.float32)
+ for k in range(len(P)):
+ poly = [(cx[k, i], cy[k, i], w[k, i], T[k, i, 0], T[k, i, 1]) for i in range(3)]
+ if min(p[2] for p in poly) < 0.25:
+ poly = _clip(poly, 0.25)
+ for j in range(1, len(poly) - 1):
+ self._tri((poly[0], poly[j], poly[j + 1]), tex, tint, depth, blend, wrap)
+
+ def _tri(self, tri, tex, tint, depth, blend, wrap):
+ pts = []
+ for x, y, w, u, v in tri:
+ iw = 1 / w
+ pts.append(((x * iw * 0.5 + 0.5) * self.w, (0.5 - y * iw * 0.5) * self.h, iw, u * iw, v * iw))
+ (x0, y0, *_), (x1, y1, *_), (x2, y2, *_) = pts
+ area = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)
+ if area == 0:
+ return
+ xa, xb = max(int(math.floor(min(x0, x1, x2))), 0), min(int(math.ceil(max(x0, x1, x2))), self.w)
+ ya, yb = max(int(math.floor(min(y0, y1, y2))), 0), min(int(math.ceil(max(y0, y1, y2))), self.h)
+ if xa >= xb or ya >= yb:
+ return
+ X, Y = np.meshgrid(np.arange(xa, xb) + 0.5, np.arange(ya, yb) + 0.5)
+ l0 = ((x1 - X) * (y2 - Y) - (x2 - X) * (y1 - Y)) / area
+ l1 = ((x2 - X) * (y0 - Y) - (x0 - X) * (y2 - Y)) / area
+ l2 = 1 - l0 - l1
+ m = (l0 >= 0) & (l1 >= 0) & (l2 >= 0)
+ iw = l0 * pts[0][2] + l1 * pts[1][2] + l2 * pts[2][2]
+ z = 1 / np.where(m, iw, 1)
+ zb = self.depth[ya:yb, xa:xb]
+ if depth:
+ m &= z < zb
+ if not m.any():
+ return
+ u = (l0 * pts[0][3] + l1 * pts[1][3] + l2 * pts[2][3])[m] * z[m]
+ v = (l0 * pts[0][4] + l1 * pts[1][4] + l2 * pts[2][4])[m] * z[m]
+ s = _sample(tex, u, v, wrap) * tint
+ cb = self.color[ya:yb, xa:xb]
+ cb[m] = s[:, :3] + cb[m] * (1 - s[:, 3:4]) if blend else s[:, :3]
+ if depth:
+ zb[m] = z[m]
+
+
+def _clip(poly, near):
+ out = []
+ for i in range(len(poly)):
+ p, q = poly[i], poly[(i + 1) % len(poly)]
+ if p[2] >= near:
+ out.append(p)
+ if (p[2] >= near) != (q[2] >= near):
+ t = (near - p[2]) / (q[2] - p[2])
+ out.append(tuple(a + (b - a) * t for a, b in zip(p, q)))
+ return out
+
+
+def _sample(img, u, v, wrap):
+ h, w = img.shape[:2]
+ x, y = u * w - 0.5, v * h - 0.5
+ x0, y0 = np.floor(x).astype(np.int64), np.floor(y).astype(np.int64)
+ fx, fy = (x - x0)[:, None], (y - y0)[:, None]
+ xs = [x0 % w, (x0 + 1) % w] if wrap else [np.clip(x0, 0, w - 1), np.clip(x0 + 1, 0, w - 1)]
+ ys = [np.clip(y0, 0, h - 1), np.clip(y0 + 1, 0, h - 1)]
+ a = img[ys[0], xs[0]] * (1 - fx) + img[ys[0], xs[1]] * fx
+ b = img[ys[1], xs[0]] * (1 - fx) + img[ys[1], xs[1]] * fx
+ return a * (1 - fy) + b * fy
+
+
+def _look_at(pos, target): # Matrix.CreateLookAt's rotation (rows: right, up, back)
+ pos, target = np.array(pos, np.float64), np.array(target, np.float64)
+ z = (pos - target) / np.linalg.norm(pos - target)
+ x = np.cross((0, 1, 0), z)
+ x /= np.linalg.norm(x)
+ return np.stack([x, np.cross(z, x), z])
+
+
+def _skybox(tex, s=25.0): # Skybox: five faces of 820 pixels, from one texture
+ v = {1: (-s, s, -s), 2: (s, s, -s), 3: (s, s, s), 4: (-s, s, s), 5: (-s, -s, -s), 6: (s, -s, -s), 7: (s, -s, s),
+ 8: (-s, -s, s)}
+ faces = [(0, 1, 2, 3, 4, 820), (2460, 2, 1, 5, 6, 820), (820, 4, 3, 7, 8, 820), (3280, 3, 2, 6, 7, 819),
+ (1640, 1, 4, 8, 5, 820)]
+ h, w = tex.shape[:2]
+ P, T = [], []
+ for x, a, b, c, d, fw in faces:
+ l, t, r, bo = (x + 1) / w, 1 / h, (x + fw - 1) / w, 819 / h
+ P += [[v[a], v[b], v[c]], [v[a], v[c], v[d]]]
+ T += [[(l, t), (r, t), (r, bo)], [(l, t), (r, bo), (l, bo)]]
+ return np.array(P, np.float32), np.array(T, np.float32)
+
+
+def _ring(top, bottom, dist, steps=24):
+ P, T = [], []
+ for i in range(steps):
+ a0, a1 = (i - 1) / steps, i / steps
+ A = (math.cos(a0 * 2 * math.pi) * dist, math.sin(a0 * 2 * math.pi) * dist)
+ B = (math.cos(a1 * 2 * math.pi) * dist, math.sin(a1 * 2 * math.pi) * dist)
+ q = [(A[0], top, A[1]), (B[0], top, B[1]), (B[0], bottom, B[1]), (A[0], bottom, A[1])]
+ P += [[q[0], q[1], q[2]], [q[0], q[2], q[3]]]
+ T += [[(a0, 0.01), (a1, 0.01), (a1, 1)], [(a0, 0.01), (a1, 1), (a0, 1)]]
+ return np.array(P, np.float32), np.array(T, np.float32)
+
+
+FOG = {0: 0x010817, 1: 0x13203E, 2: 0x281A35} # MountainModel's states' fog colors
+_MODELS = {}
+
+
+def mountain_view(pos, target, state, core_door=0.0, near_fog=0.0, size=(640, 360)):
+ for name in ("mountain", "mountain_wall", "buildings"):
+ if name not in _MODELS:
+ _MODELS[name] = _model(name)
+ r = Raster(*size)
+ rot = _look_at(pos, target)
+ sky = _texture("skybox_%d" % state)
+ P, T = _skybox(sky)
+ r.draw(rot, np.array([0, pos[1] * 1.1 - 5, 0]), P, T, sky, depth=False)
+ terrain = _texture("mountain_%d" % state)
+ r.draw(rot, np.array(pos), *_MODELS["mountain"], terrain)
+ # the Core wall opens for chapter 9 (MountainRenderer's door)
+ r.draw(rot, np.array(pos) - np.array([1.5, -1.5, -1.0]) * core_door, *_MODELS["mountain_wall"], terrain)
+ r.draw(rot, np.array(pos), *_MODELS["buildings"], _texture("buildings_%d" % state))
+ fog, c = _texture("fog"), FOG[state]
+ r.draw(rot, np.array(pos), *_ring(6, -1, 20), fog, ((c >> 16) / 255, (c >> 8 & 255) / 255, (c & 255) / 255, 1),
+ blend=True, wrap=True)
+ if near_fog:
+ r.draw(rot, np.array(pos), *_ring(6, -4, 10), fog, (0.3 * near_fog,) * 4, blend=True, wrap=True)
+ # MountainRenderer: the vignette over it at 0.2
+ vig = Image.fromarray(Atlas("Overworld")["vignette"].image()[..., 3]).resize(size, Image.BILINEAR)
+ return r.color * (1 - 0.2 * np.asarray(vig, np.float32)[..., None] / 255)
+
+
+# ------------------------------------------------------------------ JPEG
+
+def _jpeg(img):
+ """Pillow's baseline JPEG of an RGB float image: (quantization tables, Huffman tables, entropy coded data)."""
+ im = Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8)).resize((W, H), Image.LANCZOS)
+ b = io.BytesIO()
+ im.save(b, "JPEG", quality=QUALITY, subsampling=2, optimize=False)
+ data = b.getvalue()
+ p, dqt, dht, scan = 2, {}, {}, None
+ while scan is None:
+ assert data[p] == 0xFF
+ m, n = data[p + 1], struct.unpack(">H", data[p + 2:p + 4])[0]
+ seg = data[p + 4:p + 2 + n]
+ if m == 0xDB:
+ for i in range(0, len(seg), 65):
+ assert seg[i] >> 4 == 0
+ dqt[seg[i] & 15] = bytes(seg[i + 1:i + 65])
+ elif m == 0xC4:
+ i = 0
+ while i < len(seg):
+ k = 17 + sum(seg[i + 1:i + 17])
+ dht[seg[i] >> 4, seg[i] & 15] = bytes(seg[i + 1:i + k])
+ i += k
+ elif m == 0xC0:
+ comps = [tuple(seg[6 + 3 * k:9 + 3 * k]) for k in range(seg[5])]
+ assert comps == [(1, 0x22, 0), (2, 0x11, 1), (3, 0x11, 1)], comps
+ elif m == 0xDA:
+ assert list(seg[1:7]) == [1, 0x00, 2, 0x11, 3, 0x11], list(seg)
+ q, ent = p + 2 + n, bytearray()
+ while not (data[q] == 0xFF and data[q + 1] != 0):
+ ent.append(data[q])
+ q += 2 if data[q] == 0xFF else 1
+ scan = bytes(ent)
+ elif m == 0xDD:
+ raise ValueError("restart markers")
+ p += 2 + n
+ return dqt[0] + dqt[1], dht[0, 0] + dht[1, 0] + dht[0, 1] + dht[1, 1], scan
+
+
+def build():
+ """The PICS section's bytes and what goes in src/data.h."""
+ images = []
+ for name in COMPLETE:
+ images.append(complete_screen(name))
+ views = _views()
+ for a in range(10):
+ pos, target = views[a]["Idle"]
+ images.append(mountain_view(pos, target, views[a]["state"], core_door=1.0 if a == 9 else 0.0))
+ # the main menu: MountainRenderer's turning camera (15 away, 3 up, looking at 0, 7, 0), the near fog on
+ images.append(mountain_view((0, 3, 15), (0, 7, 0), 0, near_fog=1.0))
+ tables, body, entries = None, bytearray(), []
+ for img in images:
+ q, h, scan = _jpeg(img)
+ assert tables in (None, q + h), "the pictures' tables differ"
+ tables = q + h
+ entries.append((len(body), len(scan)))
+ body += scan
+ out = bytearray(struct.pack("<HH", len(images), 0))
+ base = 4 + 12 * len(images) + len(tables)
+ for off, n in entries:
+ out += struct.pack("<HHII", W, H, base + off, n)
+ out += tables + body
+ header = ["#define PIC_COMPLETE %d /* the end screens, in COMPLETE_AREAS' order */" % 0,
+ "#define PIC_MOUNTAIN %d /* the mountain from each chapter's Idle camera */" % len(COMPLETE),
+ "#define PIC_MAIN %d /* and from the main menu's */" % (len(COMPLETE) + 10)]
+ slides = [complete_slide(n) for n in COMPLETE]
+ header.append("static const int16_t PIC_SLIDE[%d][2] = {%s}; /* StartScroll - CenterScroll */" % (
+ len(slides), ", ".join("{%d, %d}" % (round(x), round(y)) for x, y in slides)))
+ return bytes(out), header