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: the CE version's backgrounds

Mason363ace12522247a
diff --git a/games/celeste/ce/data/CEL10.bin b/games/celeste/ce/data/CEL10.bin
index d4a6661f..12c5a7fc 100644
Binary files a/games/celeste/ce/data/CEL10.bin and b/games/celeste/ce/data/CEL10.bin differ
diff --git a/games/celeste/ce/data/CEL11.bin b/games/celeste/ce/data/CEL11.bin
index 8bfb868d..359325a3 100644
Binary files a/games/celeste/ce/data/CEL11.bin and b/games/celeste/ce/data/CEL11.bin differ
diff --git a/games/celeste/ce/data/CEL12.bin b/games/celeste/ce/data/CEL12.bin
index 5a300ca2..a3bed0f1 100644
Binary files a/games/celeste/ce/data/CEL12.bin and b/games/celeste/ce/data/CEL12.bin differ
diff --git a/games/celeste/ce/data/CEL13.bin b/games/celeste/ce/data/CEL13.bin
index dda8a811..58d21b5a 100644
Binary files a/games/celeste/ce/data/CEL13.bin and b/games/celeste/ce/data/CEL13.bin differ
diff --git a/games/celeste/ce/data/CEL14.bin b/games/celeste/ce/data/CEL14.bin
new file mode 100644
index 00000000..7ef4fa81
Binary files /dev/null and b/games/celeste/ce/data/CEL14.bin differ
diff --git a/games/celeste/ce/host/plat_host.c b/games/celeste/ce/host/plat_host.c
index d0ca70b0..87b54026 100644
--- a/games/celeste/ce/host/plat_host.c
+++ b/games/celeste/ce/host/plat_host.c
@@ -120,6 +120,14 @@ void plat_palette(const uint16_t *p, int first, int n) { memcpy(pal + first, p,
unsigned plat_keys(void) {
updates++;
+ if (getenv("CEL_DEBUG") && updates == 2 && g_level.room) {
+ Room *rm = g_level.room;
+ int nf = 0, nb = 0, nt = 0;
+ for (int i = 0; i < rm->tw * rm->th; i++) nf += rm->grid[i] != 0, nb += rm->grid[rm->tw * rm->th + i] != 0;
+ for (int i = 0; i < 320 * 90; i++) nt += g_bg4[i] != 0;
+ printf("room %s tw %d th %d ntiles %d fg %d bg %d bg4 %d hasbg %d map %d %d %d\n", level_room_name(), rm->tw, rm->th,
+ rm->ntiles, nf, nb, nt, g_has_bg, g_bg_map[0], g_bg_map[1], g_bg_map[2]);
+ }
if (getenv("CEL_TRACE") && g_player.e)
printf("%ld st %d co %d x %d y %d sx %d sy %d ground %d dashes %d dead %d room %s\n", updates, g_player.state, g_player.co_step,
g_player.e->x, g_player.e->y, g_player.sx, g_player.sy, g_player.on_ground, g_player.dashes, g_player.dead,
diff --git a/games/celeste/ce/src/ce.h b/games/celeste/ce/src/ce.h
index 80073dfc..98e7ce80 100644
--- a/games/celeste/ce/src/ce.h
+++ b/games/celeste/ce/src/ce.h
@@ -79,8 +79,11 @@ const uint8_t *room_rec(int i);
const uint8_t *tile_data(int id);
const uint8_t *player_meta(int sprite_id); /* s8 hair x, s8 hair y, u8 bangs | has hair << 7 */
const uint16_t *hair_mask(int which); /* 0 hair, 1-3 bangs: 10 rows (mask), then 10 (dark) */
-extern const uint8_t *g_bg; /* the chapter's background (320 x 180), NULL if none */
-extern int g_bg_camx, g_bg_camy;
+extern bool g_has_bg; /* the chapter has backgrounds */
+extern int g_bg_scrollx, g_bg_scrolly; /* how they move with the camera (1/256) */
+extern uint8_t g_bg_map[16]; /* their 16 colours */
+extern uint8_t g_bg4[320 * 180 / 2]; /* the room's: 4 bits a pixel, the left one low */
+extern int g_bg_refx, g_bg_refy; /* the camera it was made for */
extern int g_chapter_berries; /* the chapter's strawberries */
extern const uint8_t *g_remap, *g_remap_red, *g_remap_half; /* sprites drawn through g_remap if set */
@@ -195,7 +198,8 @@ typedef struct {
uint8_t *grid; /* fg[tw * th], bg[tw * th], solid bits (rb a row) */
int rb;
const uint8_t *tiles[256];
- const uint8_t *decals, *ents, *trigs;
+ const uint8_t *decals, *ents, *trigs, *bg;
+ int bgx, bgy;
uint8_t ntiles;
uint8_t flags;
int8_t camx, camy;
diff --git a/games/celeste/ce/src/data.c b/games/celeste/ce/src/data.c
index 3ddc6d74..d75804e9 100644
--- a/games/celeste/ce/src/data.c
+++ b/games/celeste/ce/src/data.c
@@ -8,8 +8,9 @@ static const uint8_t *tile_chunks;
static int ntiles;
int g_nrooms;
static const uint8_t *rooms;
-const uint8_t *g_bg;
-int g_bg_camx, g_bg_camy;
+bool g_has_bg;
+int g_bg_scrollx, g_bg_scrolly;
+uint8_t g_bg_map[16];
int g_chapter_berries;
const uint8_t *g_remap, *g_remap_red, *g_remap_half;
static uint16_t pal[256];
@@ -56,9 +57,9 @@ bool chapter_open(int n) {
g_tile_flags = HPTR(p);
sprites_h = HPTR(p + 3);
p += 6;
- g_bg = p[0] ? HPTR(p + 7) : NULL;
- g_bg_camx = S24(p + 1), g_bg_camy = S24(p + 4);
- p += 10;
+ g_has_bg = p[0], g_bg_scrollx = p[1], g_bg_scrolly = p[2];
+ memcpy(g_bg_map, p + 3, 16);
+ p += 19;
g_nrooms = (int)R16(p);
rooms = p + 2;
return true;
diff --git a/games/celeste/ce/src/draw.c b/games/celeste/ce/src/draw.c
index ead0e42c..830e1651 100644
--- a/games/celeste/ce/src/draw.c
+++ b/games/celeste/ce/src/draw.c
@@ -186,19 +186,19 @@ static bool opaque_tile(const uint8_t *t) {
static const uint8_t *row_fg[COLS], *row_bg[COLS];
static uint8_t row_kind[COLS]; /* 0: an opaque fg tile, 1: an opaque bg tile, 2: the background shows */
+/* the room's backgrounds: the view's pixel (x, y) is the picture's ((x + ox) % 320, y + oy), the offset moving with the
+ * camera by the chapter's scroll factor (rows above or below it: its first or last) */
static void background_rows(int vy0, int vy1, int vx0, int vx1) {
- /* the background's pixel at view (x, y): the composite at (x + ox) % 320, y + oy (clamped) */
- int ox = fdiv((g_camx - g_bg_camx) * 21, 256), oy = fdiv((g_camy - g_bg_camy) * 15, 256);
+ int ox = fdiv((g_camx - g_bg_refx) * g_bg_scrollx, 256), oy = fdiv((g_camy - g_bg_refy) * g_bg_scrolly, 256);
ox = ((ox % 320) + 320) % 320;
for (int y = vy0; y < vy1; y++) {
- int sy = iclamp(y + oy, 0, VIEW_H - 1);
- const uint8_t *src = g_bg + sy * 320;
+ const uint8_t *src = g_bg4 + iclamp(y + oy, 0, VIEW_H - 1) * 160;
uint8_t *d = FB(0, y);
- int x = vx0;
- while (x < vx1) {
- int sx = (x + ox) % 320, n = imin(vx1 - x, 320 - sx);
- memcpy(d + x, src + sx, n);
- x += n;
+ int sx = (vx0 + ox) % 320;
+ for (int x = vx0; x < vx1; x++) {
+ uint8_t b = src[sx >> 1];
+ d[x] = g_bg_map[(sx & 1) ? b >> 4 : b & 15];
+ if (++sx == 320) sx = 0;
}
}
}
@@ -222,7 +222,7 @@ void draw_layers_back(void) {
while (e < COLS && row_kind[e] == 2) e++;
int x0 = imax(c * 8 - offx, 0), x1 = imin(e * 8 - offx, VIEW_W);
if (x0 < x1) {
- if (g_bg) background_rows(y0, y1, x0, x1);
+ if (g_has_bg) background_rows(y0, y1, x0, x1);
else
for (int y = y0; y < y1; y++) memset(FB(x0, y), 0, x1 - x0);
}
diff --git a/games/celeste/ce/src/level.c b/games/celeste/ce/src/level.c
index 6ebf889b..fff0e13e 100644
--- a/games/celeste/ce/src/level.c
+++ b/games/celeste/ce/src/level.c
@@ -40,6 +40,16 @@ const char *level_room_name(void) {
return buf;
}
+uint8_t g_bg4[320 * 180 / 2];
+int g_bg_refx, g_bg_refy;
+static const uint8_t *bg_loaded;
+static void background_load(const Room *rm) { /* the room's picture of the backgrounds, into RAM */
+ if (!rm->bg || rm->bg == bg_loaded) return;
+ plat_unpack(g_bg4, rm->bg);
+ bg_loaded = rm->bg;
+ g_bg_refx = rm->bgx, g_bg_refy = rm->bgy;
+}
+
static bool room_load(int slot, int index) {
Room *rm = &g_level.rooms[slot];
const uint8_t *r = room_rec(index), *p = rec_after_name(r);
@@ -63,6 +73,8 @@ static bool room_load(int slot, int index) {
rm->decals = HPTR(p + 5);
rm->ents = HPTR(p + 8);
rm->trigs = HPTR(p + 11);
+ rm->bgx = S24(p + 14), rm->bgy = S24(p + 17);
+ rm->bg = R24(p + 20) == 0xFFFFFF ? NULL : HPTR(p + 20);
rm->index = index;
return true;
}
@@ -144,6 +156,7 @@ static void load_into_current(int index, int intro) {
g_level.room = &g_level.rooms[0];
room_load(0, index);
Room *rm = g_level.room;
+ background_load(rm);
if (intro != INTRO_RESPAWN) spawn_near(rm->x, rm->y + rm->h);
ents_spawn_room(0);
player_spawn(g_level.respawn_x, g_level.respawn_y, intro);
@@ -155,6 +168,7 @@ static void load_into_current(int index, int intro) {
bool level_load(int chapter, int room, int intro) {
memset(&g_level, 0, sizeof g_level);
+ bg_loaded = NULL;
g_level.chapter = chapter;
g_level.rooms[0].index = g_level.rooms[1].index = -1;
if (room < 0) room = imax(level_room_at(0, 0), 0);
@@ -174,6 +188,7 @@ static void transition_to(int index, int dx, int dy) {
g_level.room = &g_level.rooms[slot];
ents_spawn_room(slot);
Room *rm = g_level.room;
+ background_load(rm);
g_level.transitioning = true;
g_level.tr_dirx = dx, g_level.tr_diry = dy;
g_level.tr_t = 0;
diff --git a/games/celeste/ce/tools/pack_ce.py b/games/celeste/ce/tools/pack_ce.py
index e1f5f15e..54da0e24 100644
--- a/games/celeste/ce/tools/pack_ce.py
+++ b/games/celeste/ce/tools/pack_ce.py
@@ -229,8 +229,9 @@ def kmeans(counts, fixed, k, iters=12):
class Palette:
"""256 colours (15-bit), index 0 black (also the tiles' see-through key: art never maps to it)."""
- def __init__(self, colors):
+ def __init__(self, colors, reserved=True):
assert len(colors) <= 256
+ self.reserved = reserved
self.colors = list(colors) + [0] * (256 - len(colors))
self.n = len(colors)
self.rgb = np.array([rgb_of(c) for c in self.colors[:self.n]])
@@ -240,7 +241,8 @@ class Palette:
if q in self.cache:
return self.cache[q]
d = ((self.rgb - rgb_of(q)) ** 2).sum(1)
- d[0] = d[HAIR] = d[HAIR_DARK] = np.inf
+ if self.reserved:
+ d[0] = d[HAIR] = d[HAIR_DARK] = np.inf
i = int(np.argmin(d))
self.cache[q] = i
return i
@@ -450,7 +452,7 @@ class Common:
extra = kmeans(counts, set(fixed), COMMON - len(fixed))
cols = fixed + extra
print(f"common: {len(counts)} colours -> {len(cols)}")
- return cols
+ return cols + [0] * (COMMON - len(cols)) # (the chapters' own start at COMMON)
def build(self):
self.collect()
@@ -671,46 +673,73 @@ class Chapter:
out.append(p)
return out
- def background(self):
- """The chapter's parallax backgrounds as one picture (320 x 180), as they look from the chapter's middle
- height: the CE has no time to draw five layers a frame. The foreground's additive gradient (purplesunset)
- is the chapter's tint, added to every colour (src/data.c)."""
+ def background_layers(self):
+ """The chapter's parallax backgrounds (stylegrounds) and its tint: the foreground's additive gradient
+ (purplesunset), added to every colour (src/data.c)."""
bgs, fgs = pack.styleground_list(self.ch)
- layers = [(n, a) for n, a in bgs if n == "parallax" and a.get("texture", "").startswith("bgs/")]
+ self.layers = [(n, a) for n, a in bgs if n == "parallax" and a.get("texture", "").startswith("bgs/")]
self.tint = (0, 0, 0)
for n, a in fgs:
if n == "parallax" and a.get("blendmode") == "additive" and a.get("texture") == "purplesunset":
g = Atlas("Misc")["purplesunset"].image()[..., :3].reshape(-1, 3).mean(0) * float(a.get("alpha", 1))
self.tint = tuple(int(v) for v in g)
- if not layers:
- return None
+ # the mean of their scroll factors: the CE moves the room's picture of them by one factor (1/256)
+ sx = [float(a.get("scrollx", 1)) for n, a in self.layers] or [0]
+ sy = [float(a.get("scrolly", 1)) for n, a in self.layers] or [0]
+ self.bg_scroll = (int(round(np.mean(sx) * 256)), int(round(np.mean(sy) * 256)))
+
+ def background_at(self, r, cx, cy):
+ """The backgrounds as Parallax.Render draws them with the camera at (cx, cy), in room r: 180 x 320 RGB."""
W, Hh = 320, 180
out = np.zeros((Hh, W, 3), np.float64)
- cams = [(r.x + r.w / 2 - 160, r.y + r.h / 2 - 90) for r in self.ch.rooms]
- cy = float(np.median([c[1] for c in cams]))
- self.bg_cam = (0, int(cy))
- for n, a in layers:
+ for n, a in self.layers:
+ if a.get("only") and not pack.room_matches(a["only"], r.name):
+ continue
+ if a.get("exclude") and pack.room_matches(a["exclude"], r.name):
+ continue
s = tex(a["texture"])
if s is None:
continue
img = s.image().astype(np.float64)
alpha = float(a.get("alpha", 1))
- py = int(np.floor(a.get("y", 0) - cy * a.get("scrolly", 0)))
- px = int(np.floor(a.get("x", 0)))
tw, th = img.shape[1], img.shape[0]
- for y in range(Hh):
- sy = y - py
- if not 0 <= sy < th:
- continue
- row = img[sy][(np.arange(W) - px) % tw]
- a1 = row[:, 3:4] / 255 * alpha
- out[y] = out[y] * (1 - a1) + row[:, :3] * alpha
+ px = int(np.floor(a.get("x", 0) - cx * float(a.get("scrollx", 0))))
+ py = int(np.floor(a.get("y", 0) - cy * float(a.get("scrolly", 0))))
+ if a.get("loopy"):
+ py %= th
+ py -= th if py > 0 else 0
+ ys = np.arange(Hh) - py
+ if a.get("loopy"):
+ ys %= th
+ ok = (ys >= 0) & (ys < th)
+ rows = img[ys[ok]][:, (np.arange(W) - px) % tw]
+ a1 = rows[..., 3:4] / 255 * alpha
+ out[ok] = out[ok] * (1 - a1) + rows[..., :3] * alpha
return np.clip(out, 0, 255).astype(np.uint8)
+ def room_backgrounds(self):
+ """Each room's backgrounds as seen from its first spawn point's camera (the room's picture of them)."""
+ self.bgs = {}
+ cache = {}
+ if not self.layers:
+ return
+ for r in self.ch.rooms:
+ ents = r.e.child("entities").children if r.e.child("entities") else []
+ sp = [(e["x"], e["y"]) for e in ents if e.name == "player"] or [(0, r.h)]
+ cx = min(max(r.x + sp[0][0] - 160, r.x), r.x + r.w - 320)
+ cy = min(max(r.y + sp[0][1] - 90, r.y), r.y + r.h - 180)
+ cx, cy = int(round(cx / 160)) * 160, int(round(cy / 64)) * 64 # (rooms near each other share one)
+ key = (cx, cy, tuple(n for n, a in self.layers if (not a.get("only") or pack.room_matches(a["only"], r.name))
+ and not (a.get("exclude") and pack.room_matches(a["exclude"], r.name))))
+ if key not in cache:
+ cache[key] = self.background_at(r, cx, cy)
+ self.bgs[r.name] = (cx, cy, cache[key])
+
# -------------------------------------------------------------- building
def build(self):
common = self.common
- bg = self.background()
+ self.background_layers()
+ self.room_backgrounds()
counts = collections.Counter()
cells = {}
for r in self.ch.rooms:
@@ -721,9 +750,12 @@ class Chapter:
for p in decals:
for s in decal_family(p):
count_colors(s.image(), counts)
- if bg is not None:
- bgc = np.concatenate([bg, np.full(bg.shape[:2] + (1,), 255, np.uint8)], 2)
- count_colors(bgc, counts)
+ bgcounts = collections.Counter()
+ for cx, cy, bg in self.bgs.values():
+ count_colors(np.concatenate([bg, np.full(bg.shape[:2] + (1,), 255, np.uint8)], 2), bgcounts)
+ bgcols = kmeans(bgcounts, set(), 15) # the backgrounds have 16 colours (4 bits a pixel in RAM)
+ for c in bgcols:
+ counts[c] += bgcounts.get(c, 1)
ent_paths = self.entity_images()
for p in ent_paths:
count_colors(self.image(p), counts)
@@ -744,6 +776,21 @@ class Chapter:
self.decal_ids[p] = (first, len(fam))
for p in ent_paths:
self.sprites.add(p, pal.map(self.image(p)))
+ # the backgrounds' 16 colours (chapter palette indices), then each room's picture: 4 bits a pixel (the left
+ # one low), zx0 packed; rooms with the same picture share it
+ bgpal = Palette([0] + bgcols, reserved=False)
+ bgmap = [BLACK] + [pal.index(c) for c in bgcols] + [0] * (15 - len(bgcols))
+ self.bg_items = {}
+ shared = {}
+ for name, (cx, cy, bg) in self.bgs.items():
+ q = bgpal.map(np.concatenate([bg, np.full(bg.shape[:2] + (1,), 255, np.uint8)], 2))
+ flat = q.reshape(-1).astype(np.uint8)
+ packed = bytes((flat[0::2] | (flat[1::2] << 4)).tolist())
+ key = packed
+ if key not in shared:
+ shared[key] = self.blob.item("background " + name).raw(zx0(packed))
+ self.bg_items[name] = (cx, cy, shared[key])
+ print(f"{self.name}: {len(shared)} backgrounds, {sum(it.size() for it in shared.values())} bytes")
rooms = []
for r in self.ch.rooms:
rooms.append(self.room(r, cells[r.name]))
@@ -759,12 +806,6 @@ class Chapter:
flags.u8(1 if self.tiles.opaque(i) else 0)
table = self.sprites.table()
self.blob.add(table)
- bgit = None
- if bg is not None:
- idx = pal.map(np.concatenate([bg, np.full(bg.shape[:2] + (1,), 255, np.uint8)], 2))
- bgit = []
- for y0 in range(0, idx.shape[0], 180):
- bgit.append(self.blob.item("background").raw(bytes(idx[y0:y0 + 180].reshape(-1).tolist())))
h = self.head
h.raw(b"CELC").u8(FORMAT).u8(self.number)
h.raw(pal.rgb1555(COMMON, 256))
@@ -781,10 +822,9 @@ class Chapter:
for c in chunks:
h.ref(c)
h.ref(flags).ref(table)
- if bgit:
- h.u8(1).s24(self.bg_cam[0]).s24(self.bg_cam[1]).ref(bgit[0])
- else:
- h.u8(0).s24(0).s24(0).u24(0)
+ h.u8(1 if self.bgs else 0).u8(self.bg_scroll[0]).u8(self.bg_scroll[1])
+ for v in bgmap:
+ h.u8(v)
h.u16(len(rooms))
for it in rooms:
h.ref(it)
@@ -856,6 +896,11 @@ class Chapter:
it.ref(self.decals(r))
ents, trigs = self.entities(r)
it.ref(ents).ref(trigs)
+ if r.name in self.bg_items:
+ cx, cy, bgit = self.bg_items[r.name]
+ it.s24(cx).s24(cy).ref(bgit)
+ else:
+ it.s24(0).s24(0).u24(0xFFFFFF)
return it
def rows(self, r, grid, solid):