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
Balatro: the TI-84 Plus CE version's start
Mason36343bdc0ba7445
diff --git a/games/balatro/ce/.gitignore b/games/balatro/ce/.gitignorenew file mode 100644index 00000000..74c7332a--- /dev/null+++ b/games/balatro/ce/.gitignore@@ -0,0 +1,3 @@+bin/+obj/+gen/diff --git a/games/balatro/ce/ce.ld b/games/balatro/ce/ce.ldnew file mode 100644index 00000000..8e33eb61--- /dev/null+++ b/games/balatro/ce/ce.ld@@ -0,0 +1,108 @@+/* Balatro on the TI-84 Plus CE: where its code goes. The game's code is bigger than a program can have in RAM, so+ * part of it goes where a program has no code otherwise (tools/place.py picks which, biggest first):+ * vram the second half of the screen's memory (the game shows 8-bit colour: the first half is the screen),+ * pshadow the pixel shadow, under the static data,+ * bssx the static data's room left after the game's own,+ * and the rest stays in the program (convbin splits it into appvars past 64 KB). src/ce_main.c's loader copies them+ * into place from appvars (BALCV0, BALCV1, BALCP, BALCB) when the game starts: the loader and what it calls stay in+ * the program (.text.boot, the C library's .text and .text.__*). */+INCLUDE gen/place.ld++MEMORY+{+ prgm : ORIGIN = LOAD_ADDR, LENGTH = 0x25000+ pshadow : ORIGIN = 0xD031F6, LENGTH = BSSHEAP_LOW - 0xD031F6+ bss : ORIGIN = BSSHEAP_LOW, LENGTH = BSS_SIZE+ bssx : ORIGIN = BSSHEAP_LOW + BSS_SIZE, LENGTH = BSSHEAP_HIGH - BSSHEAP_LOW - BSS_SIZE+ vram : ORIGIN = 0xD52C00, LENGTH = 0x12C00+}++SECTIONS+{+ . = LOAD_ADDR;++ .header :+ {+ KEEP (*(.header))+ KEEP (*(.header.icon))+ } >prgm++ .init :+ {+ *(.init)+ } >prgm++ /* the places outside the program, filled by tools/place.py (named before .text, so they take their sections) */+ .vram : { _ce_vram_lo = .; INCLUDE gen/place_vram.ld _ce_vram_hi = .; } >vram+ .pshadow : { _ce_pshadow_lo = .; INCLUDE gen/place_pshadow.ld _ce_pshadow_hi = .; } >pshadow+ .bssx : { _ce_bssx_lo = .; INCLUDE gen/place_bssx.ld _ce_bssx_hi = .; } >bssx++ .text :+ {+ *(.text.boot .text.boot.*)+ *(.rodata.boot .rodata.boot.*)+ *(.text .stub .text.__*)+ *(.text.*)+ } >prgm++ .rodata :+ {+ *(.rodata .rodata.* .gnu.linkonce.r.*)+ } >prgm++ .init_array :+ {+ PROVIDE_HIDDEN (__init_array_start = .);+ KEEP (*(.preinit_array))+ KEEP (*(SORT_BY_INIT_PRIORITY(.init_array.*)))+ KEEP (*(.init_array))+ PROVIDE_HIDDEN (__init_array_end = .);+ } >prgm+ .fini_array :+ {+ PROVIDE_HIDDEN (__fini_array_start = .);+ KEEP (*(SORT_BY_INIT_PRIORITY(.fini_array.*)))+ KEEP (*(.fini_array))+ PROVIDE_HIDDEN (__fini_array_end = .);+ } >prgm+ ___data_low = .;+ .data :+ {+ *(.data .data.* .gnu.linkonce.d.*)+ SORT(CONSTRUCTORS)+ *(.data1)+ ___runprgm_reloc_start = .;+ *(.runprgm.reloc)+ ___runprgm_reloc_end = .;+ } >prgm+ ___data_high = .;+ ___data_len = ___data_high - ___data_low;++ .bss (NOLOAD) :+ {+ ___bss_low = .;+ *(.dynbss)+ *(.bss .bss.* .gnu.linkonce.b.*)+ *(COMMON)+ ___bss_high = .;+ } >bss+ ___bss_len = ___bss_high - ___bss_low;++ /* no heap: the room after the static data holds code */+ ___heap_low = BSSHEAP_HIGH;+ ___heap_high = BSSHEAP_HIGH;++ .runprgm 0xE30800 : AT(___runprgm_reloc_start) {+ KEEP(*(.runprgm.reloc))+ }++ /DISCARD/ :+ {+ *(.comment)+ *(.note*)+ *(.debug*)+ *(.eh_frame)+ }+}++PROVIDE(___runprgm_reloc_len = ___runprgm_reloc_end - ___runprgm_reloc_start);diff --git a/games/balatro/ce/icon.png b/games/balatro/ce/icon.pngnew file mode 100644index 00000000..d8bb434cBinary files /dev/null and b/games/balatro/ce/icon.png differdiff --git a/games/balatro/ce/makefile b/games/balatro/ce/makefilenew file mode 100644index 00000000..265aa6ab--- /dev/null+++ b/games/balatro/ce/makefile@@ -0,0 +1,89 @@+# Balatro for the TI-84 Plus CE (CE C toolchain v15: cedev-config on the PATH). `make` builds bin/: BALATRO.8xp+# (with BALATRO0... when the program is past 64 KB), the code the loader puts in place (BALCV0, BALCV1, BALCB), the art+# (BALART0...) and tables (BALLUT, BALFIRE, BALBG0, BALBG1). The game's rules and screens are the NumWorks version's+# (../src); src/ is the CE's own: the screen at 8 bits a pixel, the background's colours turning, the keys, the files.+# make host the same code on a computer (tools/host.c, SDL 3): bin/host/balatro+NAME = BALATRO+ICON = icon.png+DESCRIPTION = "Balatro"+COMPRESSED = NO+ARCHIVED = YES+LTO = YES+OUTPUT_MAP = YES+GEN = gen+DBL ?= -Xclang -mdouble=64+SHARED = game score jokers cons ev util save ui draw+CEFLAGS = $(DBL) -DNP_PORT=1 -DNP_CE=1 -DNP_APP_ID=\"balatro\" -DNP_APP_NAME=\"Balatro\" \+ -I../src -I../../../platform/include -I$(GEN) -Isrc -Wno-unused-function -Wno-unused-parameter+# (no inlining: 11 KB smaller)+CFLAGS = -Wall -Oz -fno-inline-functions $(XFLAGS) $(CEFLAGS)+EXTRA_C_SOURCES = $(SHARED:%=../src/%.c) $(GEN)/main.c $(GEN)/data.c $(GEN)/ce_art.c+DEPS = $(GEN)/ce_art.h $(GEN)/main.c $(GEN)/data.c+LINKER_SCRIPT = ce.ld+# (the toolchain's makefile builds bin/BALATRO.all: everything linked; the rules below cut it up)+TARGET = $(NAME).all+PY ?= python3++.DEFAULT_GOAL := all+include $(shell cedev-config --makefile)++CODEVARS = BALCV0 BALCV1 BALCP BALCB+ARTVARS = $(shell cat $(GEN)/appvars.txt 2>/dev/null)++.PHONY: all host check+all: $(BINDIR)/$(NAME).8xp $(CODEVARS:%=$(BINDIR)/%.8xv) $(BINDIR)/art.stamp++$(GEN)/main.c: ../src/main.c tools/cekeys.py+ $(Q)mkdir -p $(GEN)+ $(Q)$(PY) tools/cekeys.py $< $@++$(GEN)/data.c: ../src/data.c tools/cedata.py+ $(Q)mkdir -p $(GEN)+ $(Q)$(PY) tools/cedata.py $< $@++$(GEN)/ce_art.h: ../src/assets.c ../src/assets.h ../src/data.c ../tools/rc.py tools/mkart.py tools/artsrc.py \+ tools/palette.py tools/cedata.py+ $(Q)mkdir -p $(GEN)+ $(Q)echo [mkart] $(GEN)+ $(Q)$(PY) tools/mkart.py $(GEN) $(CONVBIN)+$(GEN)/ce_art.c $(GEN)/appvars.txt: $(GEN)/ce_art.h++# where the code goes (tools/place.py), before the link+$(GEN)/place.ld: $(OBJDIR)/$(TARGETTMP) tools/place.py+ $(Q)$(PY) tools/place.py $(BINUTILS_BIN)/z80-none-elf-objdump $< $@+$(BINDIR)/$(TARGETOBJ): $(GEN)/place.ld ce.ld++# the program: everything but the code that goes elsewhere+$(BINDIR)/prgm.elf: $(BINDIR)/$(TARGETOBJ)+ $(Q)$(OBJCOPY) --remove-section=.vram --remove-section=.pshadow --remove-section=.bssx $< $@+$(BINDIR)/$(NAME).8xp: $(BINDIR)/prgm.elf+ $(Q)$(CONVBIN) $(CONVBINFLAGS) -j elf -i $< -o $@++# the code that the loader copies: the screen memory's half (in two appvars), the pixel shadow, after the data+$(BINDIR)/code.stamp: $(BINDIR)/$(TARGETOBJ)+ $(Q)for s in vram pshadow bssx; do $(OBJCOPY) -O binary --only-section=.$$s $< $(BINDIR)/$$s.bin || exit 1; done+ $(Q)$(PY) -c "import sys; d=open('$(BINDIR)/vram.bin','rb').read(); h=(len(d)+1)//2; \+ open('$(BINDIR)/BALCV0.bin','wb').write(d[:h]); open('$(BINDIR)/BALCV1.bin','wb').write(d[h:])"+ $(Q)cp $(BINDIR)/pshadow.bin $(BINDIR)/BALCP.bin+ $(Q)cp $(BINDIR)/bssx.bin $(BINDIR)/BALCB.bin+ $(Q)for v in $(CODEVARS); do $(CONVBIN) -j bin -i $(BINDIR)/$$v.bin -k 8xv -r -n $$v -o $(BINDIR)/$$v.8xv -l 1 || exit 1; done+ $(Q)touch $@+$(CODEVARS:%=$(BINDIR)/%.8xv): $(BINDIR)/code.stamp++# the art and the tables+$(BINDIR)/art.stamp: $(GEN)/ce_art.h+ $(Q)mkdir -p $(BINDIR)+ $(Q)for v in $(ARTVARS); do $(CONVBIN) -j bin -i $(GEN)/$$v.bin -k 8xv -r -n $$v -o $(BINDIR)/$$v.8xv -l 1 || exit 1; done+ $(Q)touch $@++EXTRA_CLEAN = rm -rf $(GEN)++# the computer build+HOSTCC ?= cc+HOST_SRC = $(wildcard src/*.c) $(EXTRA_C_SOURCES) tools/host.c+host: $(BINDIR)/host/balatro+$(BINDIR)/host/balatro: $(HOST_SRC) $(wildcard src/*.h) $(DEPS) $(BINDIR)/art.stamp+ $(Q)mkdir -p $(@D)+ $(Q)$(HOSTCC) -std=gnu11 -O1 -g -Wall -DNP_HOST=1 $(filter-out -Xclang -mdouble=64,$(CEFLAGS)) \+ $(shell pkg-config --cflags sdl3 2>/dev/null) $(HOST_SRC) $(shell pkg-config --libs sdl3 2>/dev/null) -lm -o $@+ $(Q)echo [host] $@diff --git a/games/balatro/ce/src/archive.S b/games/balatro/ce/src/archive.Snew file mode 100644index 00000000..4964cc38--- /dev/null+++ b/games/balatro/ce/src/archive.S@@ -0,0 +1,31 @@+/* void ce_archive(const char *var): puts a variable in the archive if it is in RAM. var: its 9 bytes for OP1+ * (type, then the name). It stays in the program (see ce.ld): the loader calls it first. */+ .assume adl = 1+ .section .text.boot.ce_archive, "ax", @progbits+ .global _ce_archive+ .type _ce_archive, @function++ .equ flags, 0xD00080+ .equ Mov9ToOP1, 0x020320+ .equ ChkFindSym, 0x02050C+ .equ ChkInRam, 0x021F98+ .equ Arc_Unarc, 0x021448++_ce_archive:+ pop de+ pop hl+ push hl+ push de+ push ix+ push iy+ ld iy, flags+ call Mov9ToOP1+ call ChkFindSym+ jr c, .L.done+ call ChkInRam+ jr nz, .L.done+ call Arc_Unarc+.L.done:+ pop iy+ pop ix+ retdiff --git a/games/balatro/ce/src/art_ce.c b/games/balatro/ce/src/art_ce.cnew file mode 100644index 00000000..450a7ef3--- /dev/null+++ b/games/balatro/ce/src/art_ce.c@@ -0,0 +1,57 @@+/* The art on the TI-84 Plus CE: read where it is, in the archived appvars (tools/mkart.py). The cards' size of art+ * (Jokers, Tarots, Planets, Spectrals, Vouchers, packs) is zx0-packed there and unpacked into a few slots of RAM when+ * shown, the least recently used one making way. */+#include <string.h>+#include "art.h"+#include "assets.h"+#include "ce.h"+#ifndef NP_HOST+#include <compression.h>+#else+void zx0_Decompress(void *dst, const void *src);+#endif++#define NSLOT 6++const uint8_t *ce_lut, *ce_fire, *ce_edpat;+const uint8_t *ce_text_blob; /* src/data.c's texts (gen/data.c reads them here) */+static const uint8_t *vars[CE_ART_NVARS];+static struct {+ int16_t id;+ uint16_t used;+} slot[NSLOT];+static uint8_t slot_px[NSLOT][CE_PACKED_MAX];+static uint16_t clock_;++int ce_art_init(void) {+ size_t n;+ for (int i = 0; i < CE_ART_NVARS; i++)+ if (!(vars[i] = ce_appvar(ce_art_vars[i], &n))) return 0;+ if (!(ce_lut = ce_appvar("BALLUT", &n)) || !(ce_fire = ce_appvar("BALFIRE", &n)) || !(ce_edpat = ce_appvar("BALED", &n)))+ return 0;+ ce_text_blob = ce_lut + LUT_TEXT;+ art_flush();+ return 1;+}++void art_flush(void) {+ for (int i = 0; i < NSLOT; i++) slot[i].id = -1, slot[i].used = 0;+}++const uint8_t *ce_sprite(int id) {+ const art_sprite_t *s = &art_sprites[id];+ const uint8_t *src = vars[s->group >> 1] + s->off;+ if (!(s->group & 1)) return src;+ clock_++;+ int lru = 0;+ for (int i = 0; i < NSLOT; i++) {+ if (slot[i].id == id) {+ slot[i].used = clock_;+ return slot_px[i];+ }+ if ((uint16_t)(clock_ - slot[i].used) > (uint16_t)(clock_ - slot[lru].used)) lru = i;+ }+ zx0_Decompress(slot_px[lru], src);+ slot[lru].id = (int16_t)id, slot[lru].used = clock_;+ return slot_px[lru];+}diff --git a/games/balatro/ce/src/bg_ce.c b/games/balatro/ce/src/bg_ce.cnew file mode 100644index 00000000..00619e1e--- /dev/null+++ b/games/balatro/ce/src/bg_ce.c@@ -0,0 +1,151 @@+/* Balatro's paint background on the TI-84 Plus CE. Its shaders (worked out as the NumWorks version does, src/bg.c)+ * give a picture of the paint's value, 16 levels (tools/mkart.py: BALBG0 in a run, BALBG1 on the title screen); the+ * 64 palette entries those levels use take the shader's colours, and the colours run through the levels with time:+ * the paint flows without a pixel being drawn. Four banks of the 16 levels, darker and darker, are the background+ * under the shaded panels and the cards' shadows. */+#include <string.h>+#include "bg.h"+#include "ce.h"++uint8_t ce_bg_ver;+static const uint8_t *field[2];+static int mode;+static float colours[3][3], target[3][3], contrast = 1, contrast_target = 1, spin, spin_target;+static int lut_dirty = 1;+static uint8_t lut[33][3]; /* the colour every 8 paint values */+static unsigned phase; /* 0..511 in 1/256 units of the paint: where the colours are */+static uint32_t phase_frac;++int ce_bg_init(void) {+ size_t n;+ field[0] = ce_appvar("BALBG0", &n);+ field[1] = ce_appvar("BALBG1", &n);+ return field[0] && field[1];+}++static float fabsf_(float x) { return x < 0 ? -x : x; }+static float fmaxf_(float a, float b) { return a > b ? a : b; }+static float fminf_(float a, float b) { return a < b ? a : b; }++/* src/bg.c's colour of a paint value */+static void colour_at(int v, uint8_t out[3]) {+ float r = v / 127.5f, o[3];+ if (mode == 0) {+ float cm = 0.25f * contrast + 0.5f * spin + 1.2f;+ float c1p = fmaxf_(0.f, 1.f - cm * fabsf_(1.f - r));+ float c2p = fmaxf_(0.f, 1.f - cm * fabsf_(r));+ float c3p = 1.f - fminf_(1.f, c1p + c2p);+ float k = 0.3f / contrast;+ for (int j = 0; j < 3; j++)+ o[j] = k * colours[0][j] + (1 - k) * (colours[0][j] * c1p + colours[1][j] * c2p + colours[2][j] * c3p);+ } else {+ float s = r * 2.f - 2.f;+ float c1p = fmaxf_(0.f, 1.f - 2.f * fabsf_(1.f - s));+ float c2p = fmaxf_(0.f, 1.f - 2.f * s);+ float cb = 1.f - fminf_(1.f, c1p + c2p);+ static const float red[3] = {0xFE / 255.f, 0x5F / 255.f, 0x55 / 255.f};+ static const float blue[3] = {0x00, 0x9D / 255.f, 1.f};+ static const float black[3] = {0.6f * 79 / 255.f, 0.6f * 99 / 255.f, 0.6f * 103 / 255.f};+ float fl = fmaxf_(c1p, c2p) * 5.f - 4.4f;+ if (fl < 0) fl = 0;+ for (int j = 0; j < 3; j++) {+ float w = red[j] * c1p + blue[j] * c2p + black[j] * cb;+ o[j] = w * (1 - fl) + fl;+ }+ }+ for (int j = 0; j < 3; j++) out[j] = (uint8_t)(fminf_(1.f, fmaxf_(0.f, o[j])) * 255.f + .5f);+}++static void make_lut(void) {+ for (int i = 0; i <= 32; i++) colour_at(i * 8 > 255 ? 255 : i * 8, lut[i]);+ lut_dirty = 0;+}++void bg_mode(int m) {+ if (m != mode) {+ mode = m;+ lut_dirty = 1;+ ce_bg_ver++;+ }+}++static void set3(float d[3], uint32_t hex, float k) {+ d[0] = ((hex >> 16) & 255) / 255.f * k;+ d[1] = ((hex >> 8) & 255) / 255.f * k;+ d[2] = (hex & 255) / 255.f * k;+}++/* Balatro's ease_background_colour, as src/bg.c */+void bg_colours(uint32_t col, uint32_t special, uint32_t tertiary, float contr, float spin_amount, int instant) {+ if (special && tertiary) {+ set3(target[1], col, 1.f);+ set3(target[0], special, 1.f);+ set3(target[2], tertiary, 1.f);+ } else {+ set3(target[1], col, 1.3f);+ set3(target[2], col, special ? 0.4f : 0.7f);+ if (special) set3(target[0], special, 1.f);+ else set3(target[0], col, 0.9f);+ }+ contrast_target = contr;+ spin_target = spin_amount;+ if (instant) {+ memcpy(colours, target, sizeof colours);+ contrast = contr;+ spin = spin_amount;+ }+ lut_dirty = 1;+}++void bg_reset(void) { lut_dirty = 1; }++/* the colours: eased like the game, then run through the levels */+void bg_update(float dt, int rows) {+ (void)rows;+ float k = dt / 0.6f * 3.f;+ if (k > 1) k = 1;+ for (int i = 0; i < 3; i++)+ for (int j = 0; j < 3; j++) {+ float d = target[i][j] - colours[i][j];+ if (d > 0.002f || d < -0.002f) lut_dirty = 1, colours[i][j] += d * k;+ else colours[i][j] = target[i][j];+ }+ float dc = contrast_target - contrast, ds = spin_target - spin;+ if (dc > 0.01f || dc < -0.01f) lut_dirty = 1, contrast += dc * k;+ else contrast = contrast_target;+ if (ds > 0.001f || ds < -0.001f) lut_dirty = 1, spin += ds * (dt * 2.f > 1 ? 1 : dt * 2.f);+ else spin = spin_target;+ if (lut_dirty) make_lut();+ /* a full turn of the colours every 8 s in a run, 4 s on the title (in 1/65536 of a paint value) */+ phase_frac += (uint32_t)(dt * (mode ? 128.f : 64.f) * 65536.f);+ phase = (phase + (unsigned)(phase_frac >> 16)) & 511;+ phase_frac &= 0xFFFF;+ static const uint8_t dark[CE_BANKS] = CE_BANK_DARK;+ uint16_t pal[CE_BANKS * CE_LEVELS];+ for (int l = 0; l < CE_LEVELS; l++) {+ unsigned p = (unsigned)(l * 16 + 8 + (int)phase) & 511;+ if (p > 255) p = 511 - p;+ int i = (int)(p >> 3), f = (int)(p & 7);+ int rgb[3];+ for (int j = 0; j < 3; j++) rgb[j] = (lut[i][j] * (8 - f) + lut[i + 1][j] * f) >> 3;+ for (int b = 0; b < CE_BANKS; b++) {+ int m = 32 - dark[b], r = rgb[0] * m >> 5, g = rgb[1] * m >> 5, bl = rgb[2] * m >> 5;+ pal[b * CE_LEVELS + l] = (uint16_t)((r & 248) << 7 | (g & 248) << 2 | bl >> 3);+ }+ }+ ce_set_palette(CE_SWIRL0, CE_BANKS * CE_LEVELS, pal);+}++void bg_row(C *dst, int y, int x0, int x1) { (void)dst, (void)y, (void)x0, (void)x1; }++void ce_bg_row(uint8_t *dst, int y, int x0) {+ if (mode == 0) {+ const uint8_t *row = field[0] + y * BG_RUN_W;+ int x = x0;+ for (; x < BG_RUN_X; x++) dst[x] = row[BG_RUN_X - x < BG_RUN_W ? BG_RUN_X - x : 0]; /* (mirrored: a sidebar covers it) */+ memcpy(dst + x, row + (x - BG_RUN_X), (size_t)(SCR_W - x));+ } else {+ const uint8_t *row = field[1] + (y >> 1) * BG_TITLE_W;+ for (int x = x0 & ~1; x < SCR_W; x += 2) dst[x] = dst[x + 1] = row[x >> 1];+ }+}diff --git a/games/balatro/ce/src/ce.h b/games/balatro/ce/src/ce.hnew file mode 100644index 00000000..4af26a52--- /dev/null+++ b/games/balatro/ce/src/ce.h@@ -0,0 +1,42 @@+/* What the TI-84 Plus CE's own files share: the screen (8 bits a pixel through a palette of 256 colours), the+ * appvars, the colours' tables. On a computer (NP_HOST) tools/host.c stands in for the calculator. */+#ifndef CE_H+#define CE_H+#include <stddef.h>+#include <stdint.h>+#include "ce_art.h"+#include "gfx.h"++#define SCR_W 320+#define SCR_H 240++/* ---- the calculator, or tools/host.c */+extern uint8_t *ce_vram; /* the screen: 320 x 240 palette indices */+void ce_set_palette(int first, int n, const uint16_t *c); /* colours as the CE's 1555: 0rrrrrgg gggbbbbb */+const uint8_t *ce_appvar(const char *name, size_t *size); /* an appvar's content, where it is (flash), or NULL */+uint32_t ce_ms(void); /* milliseconds */++/* ---- colours (gfx_ce.c) */+uint8_t ce_pal(C c); /* the palette index showing c: a fixed colour, or one taken for it */+const uint8_t *ce_shade_tab(int alpha); /* every index darkened by alpha/32 */+static inline uint16_t ce_1555(C c) { return (uint16_t)((c >> 11) << 10 | ((c >> 6) & 31) << 5 | (c & 31)); }++/* ---- the art (art_ce.c) */+int ce_art_init(void); /* 0 when an appvar is missing */+const uint8_t *ce_sprite(int id); /* its rows (see tools/mkart.py), unpacked if it was packed */+extern const uint8_t *ce_lut; /* BALLUT: shading, editions' and fire's colours, texts, fonts */+extern const uint8_t *ce_fire; /* BALFIRE: the fire's smoke */+extern const uint8_t *ce_edpat; /* BALED: the editions' sheen */++/* ---- the background (bg_ce.c) */+void ce_bg_row(uint8_t *dst, int y, int x0); /* row y's background, from x0 to the right edge */+extern uint8_t ce_bg_ver; /* changes when the background's picture does (not its colours) */+int ce_bg_init(void);++/* ---- the fire (flame_ce.c) */+void ce_flame_rows(int k, int x, int y, int w, int h, int top, uint8_t *strip, int y0, int ya, int yb, int cx0, int cx1);+int ce_flame_frame(void); /* changes when the fire does */++/* ---- the files (ce_main.c): kept when the game ends */+extern uint8_t ce_save_pending;+#endifdiff --git a/games/balatro/ce/src/ce_main.c b/games/balatro/ce/src/ce_main.cnew file mode 100644index 00000000..212ae506--- /dev/null+++ b/games/balatro/ce/src/ce_main.c@@ -0,0 +1,216 @@+/* Balatro on the TI-84 Plus CE: the start (the code put in place, the screen at 8 bits a pixel), the keys+ * (platform/ti84ce/README.md: 2nd OK, enter EXE, clear Back, mode and on Home, del backspace, y= shift, alpha, math+ * toolbox, vars var), the clock and the files (the appvar NPbalato, archived when the game ends). The game itself is+ * the NumWorks version's (../src, its main() as balatro_main()). */+#include <string.h>+#include <eadk.h>+#include "ce.h"+#include "np_port.h"++int balatro_main(void);++/* ------------------------------------------------------------------ files */+/* The records (games/common/epsilon_files.h) live in the appvar itself, in RAM while the game runs (a fixed size:+ it never moves), archived when it ends. */+#define STORAGE_SIZE 5120+static const char SAVE_NAME[] = "NPbalato";+static uint8_t *storage;+uint8_t ce_save_pending;+uint8_t *ce_storage_open(const char *name, size_t size); /* the file's RAM bytes, its old content kept (or zeros) */++uint8_t *np_storage(uint32_t *size) {+ static uint8_t none[4];+ if (!storage) {+ storage = ce_storage_open(SAVE_NAME, STORAGE_SIZE);+ if (storage) {+ uint32_t at = 0;+ while (at + 2 <= STORAGE_SIZE && (storage[at] | storage[at + 1] << 8)) at += storage[at] | storage[at + 1] << 8;+ if (at + 2 > STORAGE_SIZE) memset(storage, 0, STORAGE_SIZE);+ }+ }+ if (!storage) { /* no room in RAM: no saves */+ *size = sizeof none;+ return none;+ }+ *size = STORAGE_SIZE;+ return storage;+}+void ce_storage_keep(void);+void np_storage_changed(void) {+ ce_save_pending = 1;+ ce_storage_keep();+}+bool np_slow(void) { return true; }+const char *np_target(void) { return "ti84ce"; }++/* ------------------------------------------------------------------ random */+static uint32_t rs = 0x9E3779B9u;+uint32_t eadk_random(void) {+ rs ^= rs << 13;+ rs ^= rs >> 17;+ rs ^= rs << 5;+ return rs;+}++#ifndef NP_HOST+/* ================================================================== the calculator */+#include <sys/lcd.h>+#include <sys/rtc.h>+#include <ti/getcsc.h>+#include <ti/screen.h>+#include <ti/vars.h>+#include <time.h>++uint8_t *ce_vram = (uint8_t *)0xD40000;++void ce_set_palette(int first, int n, const uint16_t *c) {+ volatile uint16_t *p = (volatile uint16_t *)0xE30200 + first;+ for (int i = 0; i < n; i++) p[i] = c[i];+}++const uint8_t *ce_appvar(const char *name, size_t *size) {+ var_t *v = os_GetAppVarData(name, 0);+ if (!v) return 0;+ *size = v->size;+ return v->data;+}++/* the clock: the 32768 Hz timer the C library starts for clock() */+uint64_t eadk_timing_millis(void) {+ uint32_t c = (uint32_t)clock();+ return (uint64_t)(c >> 15) * 1000 + (((c & 32767) * 1000) >> 15);+}+uint32_t ce_ms(void) { return (uint32_t)eadk_timing_millis(); }+void eadk_timing_msleep(uint32_t ms) {+ uint64_t until = eadk_timing_millis() + ms;+ while (eadk_timing_millis() < until) {}+}++/* the keys: the keypad scanned once, its groups read */+#define KB_MODE (*(volatile uint8_t *)0xF50000)+#define KB_DATA(g) (*(volatile uint16_t *)(0xF50010 + 2 * (g)))+#define KB_ON (*(volatile uint8_t *)0xF00020 & 1)+static const struct {+ uint8_t group, bit, key;+} KEYS[] = {+ {7, 1 << 1, eadk_key_left}, {7, 1 << 2, eadk_key_right}, {7, 1 << 3, eadk_key_up}, {7, 1 << 0, eadk_key_down},+ {1, 1 << 5, eadk_key_ok}, {6, 1 << 0, eadk_key_exe}, {6, 1 << 6, eadk_key_back}, {1, 1 << 6, eadk_key_home},+ {1, 1 << 7, eadk_key_backspace}, {2, 1 << 7, eadk_key_alpha}, {1, 1 << 4, eadk_key_shift},+ {2, 1 << 6, eadk_key_toolbox}, {5, 1 << 6, eadk_key_var}, {3, 1 << 7, eadk_key_xnt},+};+eadk_keyboard_state_t eadk_keyboard_scan(void) {+ KB_MODE = 2;+ while (KB_MODE & 3) {}+ eadk_keyboard_state_t s = 0;+ for (unsigned i = 0; i < sizeof KEYS / sizeof KEYS[0]; i++)+ if ((uint8_t)KB_DATA(KEYS[i].group) & KEYS[i].bit) s |= (eadk_keyboard_state_t)1 << KEYS[i].key;+ if (KB_ON) s |= (eadk_keyboard_state_t)1 << eadk_key_home;+ return s;+}++/* the save in a RAM appvar of a fixed size while the game runs (archiving it could move the art in the archive: only+ when the game ends); an archived one, or one of another size, is copied into a new one (through the strip buffer) */+uint8_t *ce_storage_open(const char *name, size_t size) {+ int arch = 0, scr;+ var_t *v = os_GetAppVarData(name, &arch);+ size_t keep = 0;+ uint8_t *tmp = g_scratch(&scr);+ if (v && (arch || v->size != size)) {+ keep = v->size < size ? v->size : size;+ if (keep > (size_t)scr) keep = (size_t)scr;+ memcpy(tmp, v->data, keep);+ void *entry, *data;+ if (os_ChkFindSym(OS_TYPE_APPVAR, name, &entry, &data)) os_DelSymEntry(entry);+ v = 0;+ } else if (v)+ return v->data;+ v = os_CreateAppVar(name, (uint16_t)size);+ if (!v) return 0;+ memcpy(v->data, tmp, keep);+ memset(v->data + keep, 0, size - keep);+ return v->data;+}+void ce_storage_keep(void) {}++void np_begin(void) { rs ^= (uint32_t)rtc_Time() * 2654435761u ^ (uint32_t)clock(); }+int np_end(void) { return 0; }++/* ------------------------------------------------------------------ the start */+#define BOOT __attribute__((section(".text.boot")))+#define BOOTDATA __attribute__((section(".rodata.boot")))+extern uint8_t ce_vram_lo[], ce_vram_hi[], ce_pshadow_lo[], ce_pshadow_hi[], ce_bssx_lo[], ce_bssx_hi[];+void ce_archive(const char *op1);++/* the code's appvars (where each goes), then the others */+#define NCODE 4+static const char BOOTDATA var_names[][9] = {"BALCV0", "BALCV1", "BALCP", "BALCB", "BALLUT", "BALFIRE", "BALBG0",+ "BALBG1", "BALED", "BALART0", "BALART1", "BALART2", "BALART3", "BALART4"};+#define NVARS (NCODE + 5 + CE_ART_NVARS)+static const char BOOTDATA save_name[9] = "NPbalato";+static const char BOOTDATA msg_missing[] = "Balatro: a file is missing";+static const char BOOTDATA msg_send[] = "Send every Balatro file:";+static const char BOOTDATA msg_files[] = "BALATRO.8xp and BAL*.8xv";++BOOT static void boot_archive(const char *name) {+ char op1[9];+ op1[0] = OS_TYPE_APPVAR;+ for (int i = 0; i < 8; i++) op1[1 + i] = name[i];+ ce_archive(op1);+}++BOOT static void boot_fail(void) {+ os_ClrHomeFull();+ os_PutStrFull(msg_missing);+ os_NewLine();+ os_PutStrFull(msg_send);+ os_NewLine();+ os_PutStrFull(msg_files);+ while (!os_GetCSC()) {}+}++BOOT int main(void) {+ /* the appvars in the archive (where the art is read), then the code put in place */+ const uint8_t *src[NCODE];+ size_t len[NCODE];+ for (unsigned i = 0; i < NVARS; i++) boot_archive(var_names[i]);+ for (unsigned i = 0; i < NVARS; i++) {+ var_t *v = os_GetAppVarData(var_names[i], 0);+ if (!v) {+ boot_fail();+ return 0;+ }+ if (i < NCODE) src[i] = v->data, len[i] = v->size;+ }+ if (len[0] + len[1] != (size_t)(ce_vram_hi - ce_vram_lo) || len[2] != (size_t)(ce_pshadow_hi - ce_pshadow_lo) ||+ len[3] != (size_t)(ce_bssx_hi - ce_bssx_lo)) {+ boot_fail();+ return 0;+ }+ /* the screen at 8 bits a pixel, black while the code fills the half it no longer shows */+ volatile uint16_t *pal = (volatile uint16_t *)0xE30200;+ for (int i = 0; i < 256; i++) pal[i] = 0;+ memset((void *)0xD40000, 0, 320 * 240);+ lcd_UpBase = 0xD40000;+ lcd_Control = 0x927;+ memcpy(ce_vram_lo, src[0], len[0]);+ memcpy(ce_vram_lo + len[0], src[1], len[1]);+ memcpy(ce_pshadow_lo, src[2], len[2]);+ memcpy(ce_bssx_lo, src[3], len[3]);+ int ok = ce_art_init() && ce_bg_init();+ if (ok) {+ ce_set_palette(0, CE_NSTATIC, ce_palette);+ balatro_main();+ }+ /* the OS's screen, its pixel shadow cleared */+ memset((void *)0xD40000, 255, 320 * 240 * 2);+ memset((void *)0xD031F6, 0, 8400);+ lcd_Control = 0x92D;+ if (!ok) {+ boot_fail();+ return 0;+ }+ os_ClrHomeFull();+ if (ce_save_pending) boot_archive(save_name); /* (the screen's half with code is gone: names from here) */+ return 0;+}+#endifdiff --git a/games/balatro/ce/src/flame_ce.c b/games/balatro/ce/src/flame_ce.cnew file mode 100644index 00000000..043e77cb--- /dev/null+++ b/games/balatro/ce/src/flame_ce.c@@ -0,0 +1,96 @@+/* The fire behind chips and mult when a hand beats the blind, on the TI-84 Plus CE: the NumWorks version's flame+ * (src/flame.c: Balatro's shader, intensity and easing) with its smoke worked out ahead (tools/mkart.py: BALFIRE, a+ * few intensities, 24 moments) and its colours a table per row (BALLUT). */+#include <string.h>+#include "ce.h"+#include "flame.h"++typedef struct {+ float intensity, real, vel, timer;+} flame_t;+static flame_t fl[2];++/* log base 5 of v >= 1, from the double's bits */+static float log5(double v) {+ uint64_t b;+ memcpy(&b, &v, 8);+ int e = (int)((b >> 52) & 0x7FF) - 1023;+ uint32_t mb = 0x3F800000u | (uint32_t)((b >> 29) & 0x7FFFFF);+ float m;+ memcpy(&m, &mb, 4);+ float z = (m - 1) / (m + 1), z2 = z * z;+ float ln = 2.f * z * (1.f + z2 * (1.f / 3 + z2 * (1.f / 5 + z2 * (1.f / 7))));+ return (e * 0.69314718f + ln) * 0.62133493f;+}++void flame_update(int dt_ms, double earned, double required, int allowed, int calm) {+ float target = 0;+ if (allowed && required > 0 && earned >= required && earned > 1) {+ target = log5(earned) - 2.f;+ if (target < 0) target = 0;+ }+ for (int k = 0; k < 2; k++) {+ flame_t *f = &fl[k];+ f->intensity = target;+ int left = dt_ms;+ while (left > 0) {+ int step = left > 17 ? 17 : left;+ left -= step;+ float dt = step / 1000.f;+ float ex = 1.f - 0.4f * dt;+ f->timer += dt * (1 + f->intensity * 0.2f);+ if (f->vel < 0) f->vel *= 1 - 10 * dt;+ f->vel = (1 - ex) * (f->intensity - f->real) * dt * 25 + ex * f->vel;+ f->real += f->vel;+ if (calm) f->real -= f->real * 8 * dt + 0.02f;+ if (f->real < 0) f->real = 0;+ }+ if (f->timer > 2000) f->timer -= 2000;+ }+}++int flame_on(void) { return fl[0].real >= 0.1f || fl[1].real >= 0.1f; }++static const float levels[FL_LEVELS] = FL_I;+static int level_of(float I) {+ int best = 0;+ for (int i = 1; i < FL_LEVELS; i++)+ if ((I - levels[i]) * (I - levels[i]) < (I - levels[best]) * (I - levels[best])) best = i;+ return best;+}+static int frame_of(int k) { return ((int)(fl[k].timer / 0.11f) + (k ? 0 : 7)) % FL_FRAMES; }++int ce_flame_frame(void) {+ return frame_of(0) | frame_of(1) << 5 | level_of(fl[0].real) << 10 | level_of(fl[1].real) << 13 |+ (fl[0].real >= 0.1f) << 16 | (fl[1].real >= 0.1f) << 17;+}++/* rows ya..yb of flame k drawn at (x, y), w x h (the box under it ends at the bottom) */+void ce_flame_rows(int k, int x, int y, int w, int h, int top, uint8_t *strip, int y0, int ya, int yb, int cx0, int cx1) {+ const flame_t *f = &fl[k];+ if (f->real < 0.1f || w != FL_W || h != FL_H) return;+ int lv = level_of(f->real > 10 ? 10 : f->real);+ const uint8_t *g = ce_fire + (lv * FL_FRAMES + frame_of(k)) * (FL_GR * FL_GC);+ const uint8_t *cols = ce_lut + LUT_FCOL + ((k * FL_LEVELS + lv) * FL_ROWS) * 17;+ int r0 = ya - y, r1 = yb - y;+ if (r0 < 0) r0 = 0;+ if (r1 > FL_ROWS) r1 = FL_ROWS;+ int c0 = cx0 - x, c1 = cx1 - x;+ if (c0 < 0) c0 = 0;+ if (c1 > (FL_GC - 1) * 2) c1 = (FL_GC - 1) * 2;+ for (int r = r0; r < r1; r++) {+ int j = r >> 1;+ if (j + 1 >= FL_GR) break;+ const uint8_t *ra = g + j * FL_GC, *rb = ra + FL_GC, *lut = cols + r * 17;+ int wy = r & 1;+ /* the tips thin out in the last 3 pixels under the top limit */+ int fade = y + r - top < 3 ? (3 - (y + r - top)) * 3 : 0;+ uint8_t *d = strip + (y + r - y0) * SCR_W + x;+ for (int cx = c0; cx < c1; cx++) {+ int i = cx >> 1, a = ra[i], b = rb[i];+ if (cx & 1) a = (a + ra[i + 1]) >> 1, b = (b + rb[i + 1]) >> 1;+ int sm = (wy ? (a + b) >> 1 : a) + fade;+ if (sm < 16) d[cx] = lut[sm];+ }+ }+}diff --git a/games/balatro/ce/src/gfx_ce.c b/games/balatro/ce/src/gfx_ce.cnew file mode 100644index 00000000..fbe70ed6--- /dev/null+++ b/games/balatro/ce/src/gfx_ce.c@@ -0,0 +1,698 @@+/* The renderer on the TI-84 Plus CE: the NumWorks version's (src/gfx.c) list of what a frame shows, drawn at 8 bits a+ * pixel. The screen is cut in 15 strips of 16 rows; a strip is drawn again (in a buffer, then copied to the screen)+ * only when something in it changed: each strip keeps a hash of what covers it. The background's motion is its+ * colours turning (bg_ce.c), which needs no drawing at all.+ *+ * Colours: the interface's are fixed palette entries; a colour that has none (a boss's own, mixed shades of it) takes+ * one of 16 free entries while the screen shows it. Shading (panels, shadows, Options over the game) goes through+ * tables of every entry darkened. */+#include <string.h>+#include "art.h"+#include "assets.h"+#include "bg.h"+#include "ce.h"+#include "flame.h"++#define SH 16+#define NSTRIP (SCR_H / SH)+#define MAXI 300+#define MAXCLIP 16+#define NDYN 16+/* the fonts, read in the archive (BALLUT) */+#define font_small ((const glyph_t *)(ce_lut + LUT_FONT_SMALL))+#define font_med ((const glyph_t *)(ce_lut + LUT_FONT_MED))+#define font_large ((const glyph_t *)(ce_lut + LUT_FONT_LARGE))+#define font_large_digits ((const glyph_t *)(ce_lut + LUT_FONT_LARGE_DIGITS))+#define font_small_bits (ce_lut + LUT_FONT_SMALL_BITS)+#define font_med_bits (ce_lut + LUT_FONT_MED_BITS)+#define font_large_bits (ce_lut + LUT_FONT_LARGE_BITS)+#define font_large_digits_bits (ce_lut + LUT_FONT_LARGE_DIGITS_BITS)++enum { I_RECT, I_RRECT, I_SHADE, I_SPRITE, I_TEXT, I_FLAME, I_RSQ };++typedef struct {+ int16_t x, y, w, h;+ uint8_t type, clip, r, fx;+ uint16_t a, b;+ const char *s;+} item_t;++static item_t items[MAXI];+static char strbuf[4096];+static int strpos, nitems;+static int16_t clips[MAXCLIP][4];+static int nclips, cur_clip;+static uint8_t strip[SCR_W * SH];+static int bg_swirl, bg_cover_x;+static uint8_t bg_solid;+static unsigned strip_hash[NSTRIP];+static uint8_t drawn_once;+uint32_t g_time;++void *g_scratch(int *size) {+ *size = (int)sizeof strip;+ return strip;+}+void g_bg_cover(int x) { bg_cover_x = x; }++C darken(C a, int t) { return mix565(a, 0, t); }+C lighten(C a, int t) { return mix565(a, 0xFFFF, t); }++/* ------------------------------------------------------------------ colours */+static C dyn_col[NDYN];+static uint16_t strip_dyn[NSTRIP], frame_dyn; /* the taken entries each strip shows; those this frame uses */+static struct {+ C c;+ uint8_t v, ok;+} pcache[64];++static int dist(C a, uint16_t p) {+ int dr = (int)(a >> 11) - (int)(p >> 10 & 31), dg = (int)((a >> 6) & 31) - (int)(p >> 5 & 31),+ db = (int)(a & 31) - (int)(p & 31);+ return 2 * dr * dr + 4 * dg * dg + 3 * db * db;+}+static uint8_t nearest_fixed(C c, int *d) {+ int best = 0, bd = 1 << 20;+ for (int i = 0; i < CE_NSTATIC; i++) {+ int e = dist(c, ce_palette[i]);+ if (e < bd) bd = e, best = i;+ }+ if (d) *d = bd;+ return (uint8_t)best;+}++static void shade_tabs_reset(void);++uint8_t ce_pal(C c) {+ unsigned h = (c ^ c >> 6 ^ c >> 11) & 63;+ if (pcache[h].ok && pcache[h].c == c) {+ uint8_t v = pcache[h].v;+ if (v < CE_DYN0 || v >= CE_SWIRL0 || dyn_col[v - CE_DYN0] == c) {+ if (v >= CE_DYN0 && v < CE_SWIRL0) frame_dyn |= (uint16_t)(1u << (v - CE_DYN0));+ return v;+ }+ }+ int d;+ uint8_t v = nearest_fixed(c, &d);+ if (d > 6) {+ /* a free entry, or one already showing it */+ uint16_t used = frame_dyn;+ for (int s = 0; s < NSTRIP; s++) used |= strip_dyn[s];+ int k = -1;+ for (int i = 0; i < NDYN; i++)+ if (dyn_col[i] == c && (used >> i & 1)) k = i;+ if (k < 0)+ for (int i = 0; i < NDYN && k < 0; i++)+ if (!(used >> i & 1)) k = i;+ if (k >= 0) {+ if (dyn_col[k] != c) {+ dyn_col[k] = c;+ uint16_t p = ce_1555(c);+ ce_set_palette(CE_DYN0 + k, 1, &p);+ shade_tabs_reset();+ }+ frame_dyn |= (uint16_t)(1u << k);+ v = (uint8_t)(CE_DYN0 + k);+ }+ }+ pcache[h].c = c, pcache[h].v = v, pcache[h].ok = 1;+ return v;+}++/* darkened tables: a few kept, made when asked for (the taken entries' only while they are shown) */+#define NSTAB 8+static const int8_t bank_dark[CE_BANKS] = CE_BANK_DARK;+static struct {+ uint8_t alpha, ok;+ uint8_t t[256];+} stabs[NSTAB];+static uint8_t stab_next;+static void shade_tabs_reset(void) {+ for (int i = 0; i < NSTAB; i++) stabs[i].ok = 0;+}+const uint8_t *ce_shade_tab(int alpha) {+ if (alpha < 0) alpha = 0;+ if (alpha > 32) alpha = 32;+ for (int i = 0; i < NSTAB; i++)+ if (stabs[i].ok && stabs[i].alpha == alpha) return stabs[i].t;+ int i = stab_next;+ stab_next = (uint8_t)((stab_next + 1) % NSTAB);+ uint8_t *t = stabs[i].t;+ memcpy(t, ce_lut + LUT_SHADE + alpha * CE_NSTATIC, CE_NSTATIC);+ uint16_t used = frame_dyn;+ for (int s = 0; s < NSTRIP; s++) used |= strip_dyn[s];+ for (int k = 0; k < NDYN; k++) t[CE_DYN0 + k] = used >> k & 1 ? nearest_fixed(mix565(dyn_col[k], 0, alpha), 0) : 0;+ for (int b = 0; b < CE_BANKS; b++) {+ /* the background's banks: the darkness after shading, to the nearest bank */+ int dark = 32 - (32 - bank_dark[b]) * (32 - alpha) / 32, nb = 0;+ for (int q = 1; q < CE_BANKS; q++)+ if ((dark - bank_dark[q]) * (dark - bank_dark[q]) < (dark - bank_dark[nb]) * (dark - bank_dark[nb])) nb = q;+ for (int l = 0; l < CE_LEVELS; l++) t[CE_SWIRL0 + b * CE_LEVELS + l] = (uint8_t)(CE_SWIRL0 + nb * CE_LEVELS + l);+ }+ stabs[i].alpha = (uint8_t)alpha, stabs[i].ok = 1;+ return t;+}++/* ------------------------------------------------------------------ the list */+#define MAXR 8 /* (the interface's corners are 7 at most) */+static uint8_t cov[MAXR + 1][MAXR][MAXR];++void g_init(void) {+ for (int r = 1; r <= MAXR; r++)+ for (int y = 0; y < r; y++)+ for (int x = 0; x < r; x++) {+ /* 4x4 samples of the quarter circle centred at (r, r) */+ int n = 0;+ for (int sy = 0; sy < 4; sy++)+ for (int sx = 0; sx < 4; sx++) {+ int dx = 8 * r - (8 * x + 2 * sx + 1), dy = 8 * r - (8 * y + 2 * sy + 1);+ if (dx * dx + dy * dy <= 64 * r * r) n++;+ }+ cov[r][y][x] = (uint8_t)(n * 2);+ }+ drawn_once = 0;+}++void g_begin(void) {+ nitems = 0;+ bg_cover_x = 0;+ strpos = 0;+ nclips = 1;+ cur_clip = 0;+ frame_dyn = 0;+ clips[0][0] = 0, clips[0][1] = 0, clips[0][2] = SCR_W, clips[0][3] = SCR_H;+}++void g_clip(int x, int y, int w, int h) {+ if (nclips >= MAXCLIP) return;+ clips[nclips][0] = (int16_t)(x < 0 ? 0 : x);+ clips[nclips][1] = (int16_t)(y < 0 ? 0 : y);+ clips[nclips][2] = (int16_t)(x + w > SCR_W ? SCR_W : x + w);+ clips[nclips][3] = (int16_t)(y + h > SCR_H ? SCR_H : y + h);+ cur_clip = nclips++;+}+void g_noclip(void) { cur_clip = 0; }++static item_t *add(int type, int x, int y, int w, int h) {+ if (nitems >= MAXI || w <= 0 || h <= 0) return 0;+ const int16_t *c = clips[cur_clip];+ if (x >= c[2] || y >= c[3] || x + w <= c[0] || y + h <= c[1]) return 0;+ item_t *it = &items[nitems++];+ it->type = (uint8_t)type;+ it->x = (int16_t)x, it->y = (int16_t)y, it->w = (int16_t)w, it->h = (int16_t)h;+ it->clip = (uint8_t)cur_clip;+ it->fx = 0, it->r = 0, it->a = 0, it->b = 0, it->s = 0;+ return it;+}++void g_rect(int x, int y, int w, int h, C c) {+ item_t *it = add(I_RECT, x, y, w, h);+ if (it) it->a = ce_pal(c);+}+void g_line_h(int x, int y, int w, C c) { g_rect(x, y, w, 1, c); }+void g_rrect(int x, int y, int w, int h, int r, C c) {+ if (r > MAXR) r = MAXR;+ if (r > w / 2) r = w / 2;+ if (r > h / 2) r = h / 2;+ item_t *it = add(r > 0 ? I_RRECT : I_RECT, x, y, w, h);+ if (it) it->a = ce_pal(c), it->r = (uint8_t)r;+}+void g_shade(int x, int y, int w, int h, int r, int alpha) {+ if (r > MAXR) r = MAXR;+ if (r > w / 2) r = w / 2;+ if (r > h / 2) r = h / 2;+ item_t *it = add(I_SHADE, x, y, w, h);+ if (it) it->a = (uint16_t)alpha, it->r = (uint8_t)r;+}+void g_sprite(int id, int x, int y, int fx, int scale) {+ if (id < 0 || id >= ART_NSPRITES) return;+ const art_sprite_t *s = &art_sprites[id];+ int w = s->w, h = s->h;+ if (scale != 256) {+ int nw = (w * scale + 128) >> 8, nh = (h * scale + 128) >> 8;+ x += (w - nw) / 2, y += (h - nh) / 2;+ w = nw, h = nh;+ }+ item_t *it = add(I_SPRITE, x, y, w, h);+ if (it) it->a = (uint16_t)id, it->fx = (uint8_t)fx, it->b = (uint16_t)scale;+}+void g_sprite_wh(int id, int x, int y, int w, int h, int fx) {+ item_t *it = add(I_SPRITE, x, y, w, h);+ if (it) it->a = (uint16_t)id, it->fx = (uint8_t)fx, it->b = 0;+}+void g_rsquare(int cx, int cy, int hs, int angle, C c) {+ int R = hs * 3 / 2 + 1;+ item_t *it = add(I_RSQ, cx - R, cy - R, 2 * R + 1, 2 * R + 1);+ if (it) it->a = ce_pal(c), it->r = (uint8_t)hs, it->fx = (uint8_t)angle;+}+void g_flame(int k, int x, int y, int w, int h, int top) {+ if (!flame_on()) return;+ item_t *it = add(I_FLAME, x, y, w, h);+ if (it) it->a = (uint16_t)k, it->b = (uint16_t)top;+}+void g_bg(int swirl, C solid) {+ bg_swirl = swirl;+ bg_solid = ce_pal(solid);+}++/* ------------------------------------------------------------------ text */+static const C code_col[17] = {+ 0, 0xFFFF, HEXC(0x009DFF), HEXC(0xFE5F55), HEXC(0xFF9A00), HEXC(0xF3B958), HEXC(0x4BC292), HEXC(0x88888A),+ HEXC(0xA782D1), HEXC(0x13AFCE), 0, HEXC(0x4584FA), HEXC(0x4F6367), 0, 0xFFFF, HEXC(0x4CA893), 0,+};++static const glyph_t *font(int f) { return (f & T_LARGE) ? font_large : (f & T_MED) ? font_med : font_small; }+static const uint8_t *font_bits(int f) {+ return (f & T_LARGE) ? font_large_bits : (f & T_MED) ? font_med_bits : font_small_bits;+}+static int glyph_rows(int f) { return (f & T_LARGE) ? FONT_LARGE_H : (f & T_MED) ? FONT_MED_H : FONT_SMALL_H; }+int g_cap(int f) { return ((f & T_LARGE) ? 11 : (f & T_MED) ? 9 : 7) * ((f & T_X2) ? 2 : 1); }+int g_pitch(int f) { return ((f & T_LARGE) ? 15 : (f & T_MED) ? 13 : LINE_H) * ((f & T_X2) ? 2 : 1); }++static const glyph_t *glyph(int f, unsigned ch, const uint8_t **bits) {+ if ((f & (T_COND | T_LARGE)) == (T_COND | T_LARGE) && ch >= '0' && ch <= '9') {+ *bits = font_large_digits_bits;+ return &font_large_digits[ch - '0'];+ }+ *bits = font_bits(f);+ return &font(f)[ch - 32];+}+/* the condensed medium size: one column fewer (see src/gfx.c) */+static int drop_col(int f, unsigned ch, const glyph_t *g) {+ if ((f & (T_COND | T_MED)) != (T_COND | T_MED) || f & T_LARGE) return -1;+ if (ch == 'T' || ch == 'I' || ch == '1') return 0;+ if (ch == 'f' || ch == 't') return 4;+ switch (g->w) {+ case 5: return 3;+ case 6: return 2;+ case 7: return 3;+ case 8: return 4;+ }+ return ch == ' ' ? 99 : -1;+}+static int advance(int f, unsigned ch, const glyph_t *g) {+ int a = g->adv;+ if (drop_col(f, ch, g) >= 0) a--;+ if (f & T_TIGHT) a -= ch == ' ' ? 2 : 1;+ if ((f & T_COND) && (ch == ',' || ch == '.')) a--;+ return a;+}++static int textw(const char *s, int f, int one_line) {+ int w = 0, best = 0, badge = 0;+ const uint8_t *bits;+ for (; *s; s++) {+ unsigned char ch = (unsigned char)*s;+ if (ch == '\n') {+ if (badge) w += 2, badge = 0;+ if (w > best) best = w;+ if (one_line) break;+ w = 0;+ continue;+ }+ if (ch < 32) {+ if (ch == 14 && !badge) w += 2, badge = 1;+ else if (badge && ch != 14) w += 2, badge = 0;+ continue;+ }+ if (ch > (f & (T_LARGE | T_MED) ? 126 : 130)) ch = '?';+ w += advance(f, ch, glyph(f, ch, &bits));+ }+ if (badge) w += 2;+ if (w > best) best = w;+ if (best > 0) best--;+ return best * ((f & T_X2) ? 2 : 1);+}+int g_textw(const char *s, int f) { return textw(s, f, 0); }++int g_lines(const char *s) {+ int n = 1;+ for (; *s; s++) n += *s == '\n';+ return n;+}++static item_t *text_item(const char *s, int x, int y, int w, int h) {+ int n = (int)strlen(s);+ if (strpos + n + 1 > (int)sizeof strbuf) return 0;+ item_t *it = add(I_TEXT, x, y, w, h);+ if (!it) return 0;+ char *d = strbuf + strpos;+ memcpy(d, s, (size_t)n + 1);+ strpos += n + 1;+ it->s = d;+ return it;+}++void g_text(const char *s, int x, int y, int f, C c) {+ if (!s || !*s) return;+ item_t *it;+ if (f & T_ROT) {+ int len = g_textw(s, f & ~T_ROT);+ if (f & T_CENTER) y += len / 2;+ it = text_item(s, x - 2, y - len - 2, glyph_rows(f) + 4, len + 4);+ } else {+ int w = g_textw(s, f) + 2;+ if (f & T_CENTER) x -= (w - 2) / 2;+ if (f & T_RIGHT) x -= w - 2;+ int h = g_pitch(f) * (g_lines(s) - 1) + glyph_rows(f) * ((f & T_X2) ? 2 : 1) + 3;+ it = text_item(s, x - 2, y - 2, w + 4, h + 2);+ }+ if (it) it->a = ce_pal(c), it->b = (uint16_t)f;+}++void g_text_box(const char *s, int x, int y, int w, int h, int f, C c) {+ int th = g_cap(f) + g_pitch(f) * (g_lines(s) - 1);+ g_text(s, x + w / 2, y + (h - th + 1) / 2, (f & ~(T_RIGHT)) | T_CENTER, c);+}++/* one glyph's pixels (its shadow first), into the strip rows ra..rb, columns cx0..cx1 */+static void put_glyph(const glyph_t *g, const uint8_t *b, int f, int dc, int x, int y, uint8_t col, int y0, int ra,+ int rb, int cx0, int cx1, const uint8_t *shadow) {+ int sc = (f & T_X2) ? 2 : 1, gh = glyph_rows(f);+ for (int pass = shadow ? 0 : 1; pass < 2; pass++) {+ unsigned bit = g->off;+ int dy = pass ? 0 : sc;+ for (int gx = 0; gx < g->w; gx++) {+ if (gx == dc) {+ bit += gh;+ continue;+ }+ int px = x + (gx - (dc >= 0 && gx > dc)) * sc;+ for (int gy = 0; gy < gh; gy++, bit++) {+ if (!((b[bit >> 3] >> (bit & 7)) & 1)) continue;+ int py = y + gy * sc + dy;+ for (int k = 0; k < sc * sc; k++) {+ int X = px + (k & (sc - 1)), Y = py + (k >> (sc - 1));+ if (Y >= ra && Y < rb && X >= cx0 && X < cx1) {+ uint8_t *d = strip + (Y - y0) * SCR_W + X;+ *d = pass ? col : shadow[*d];+ }+ }+ }+ }+ }+}++static void draw_text_rot(item_t *it, int y0, int ra, int rb, int cx0, int cx1) {+ int f = it->b, gh = glyph_rows(f);+ int x = it->x + 2, pen = it->y + it->h - 2;+ const uint8_t *sh = ce_shade_tab(12);+ for (const char *s = it->s; *s; s++) {+ unsigned char ch = (unsigned char)*s;+ if (ch < 32 || ch > 126) continue;+ const uint8_t *b;+ const glyph_t *g = glyph(f, ch, &b);+ int dc = drop_col(f, ch, g);+ for (int pass = (f & T_SHADOW) ? 0 : 1; pass < 2; pass++) {+ unsigned bit = g->off;+ for (int gx = 0; gx < g->w; gx++)+ for (int gy = 0; gy < gh; gy++, bit++) {+ if (gx == dc || !((b[bit >> 3] >> (bit & 7)) & 1)) continue;+ int X = x + gy + (pass ? 0 : 1), Y = pen - 1 - (gx - (dc >= 0 && gx > dc));+ if (Y < ra || Y >= rb || X < cx0 || X >= cx1) continue;+ uint8_t *d = strip + (Y - y0) * SCR_W + X;+ *d = pass ? (uint8_t)it->a : sh[*d];+ }+ }+ pen -= advance(f, ch, g);+ }+}++static void draw_text(item_t *it, int y0, int ra, int rb, int cx0, int cx1) {+ int f = it->b;+ if (f & T_ROT) {+ draw_text_rot(it, y0, ra, rb, cx0, cx1);+ return;+ }+ int sc = (f & T_X2) ? 2 : 1, cap = g_cap(f) / sc, pitch = g_pitch(f);+ int x0 = it->x + 2, x = x0, y = it->y + 2;+ int multi = strchr(it->s, '\n') != 0;+ uint8_t col = (uint8_t)it->a, base = col;+ const uint8_t *sh = (f & (T_SHADOW | T_OUTLINE)) ? ce_shade_tab(12) : 0;+ int badge = 0;+ int align = (f & (T_CENTER | T_RIGHT)) && multi, total = it->w - 4;+ if (align) {+ int lw = textw(it->s, f, 1);+ x = x0 + ((f & T_RIGHT) ? total - lw : (total - lw) / 2);+ }+ for (const char *s = it->s; *s; s++) {+ unsigned char ch = (unsigned char)*s;+ if (ch == '\n') {+ badge = 0;+ y += pitch;+ x = x0;+ if (align) {+ int lw = textw(s + 1, f, 1);+ x = x0 + ((f & T_RIGHT) ? total - lw : (total - lw) / 2);+ }+ continue;+ }+ if (ch < 32) {+ if (badge && ch != 14) x += 2 * sc, badge = 0;+ if (ch == 16) col = base;+ else if (ch == 14) {+ /* a red badge behind the following text, until the next code */+ const char *e = s + 1;+ int bw = 0;+ const uint8_t *bb;+ while (*e && (unsigned char)*e >= 32) bw += advance(f, (unsigned char)*e, glyph(f, (unsigned char)*e, &bb)), e++;+ bw = bw * sc + 3;+ int by0 = y - 2, by1 = y + cap * sc + 2;+ uint8_t red = ce_pal(HEXC(0xFE5F55));+ for (int yy = by0 > ra ? by0 : ra; yy < by1 && yy < rb; yy++) {+ uint8_t *d = strip + (yy - y0) * SCR_W;+ int a = x, b = x + bw;+ if (yy == by0 || yy == by1 - 1) a++, b--;+ for (int xx = a < cx0 ? cx0 : a; xx < b && xx < cx1; xx++) d[xx] = red;+ }+ x += 2 * sc;+ col = ce_pal(0xFFFF);+ badge = 1;+ } else if (code_col[ch])+ col = ce_pal(code_col[ch]);+ continue;+ }+ if (ch > (f & (T_LARGE | T_MED) ? 126 : 130)) ch = '?';+ const uint8_t *b;+ const glyph_t *g = glyph(f, ch, &b);+ int adv = advance(f, ch, g) * sc;+ if (x < cx1 && x + adv + sc > cx0 && y < rb && y + glyph_rows(f) * sc + sc > ra)+ put_glyph(g, b, f, drop_col(f, ch, g), x, y, col, y0, ra, rb, cx0, cx1, sh);+ x += adv;+ }+}++/* ------------------------------------------------------------------ sprites */+/* editions: a level a 2 x 2 cell of the card, a frame every ED_DT_MS, each card a little behind the next */+static const uint8_t *ed_pattern(int ed, int x) {+ int f = (int)((g_time / ED_DT_MS + (unsigned)(x / 12)) % ED_FRAMES);+ return ce_edpat + ((ed - 1) * ED_FRAMES + f) * (ED_CH * ED_CW / 2);+}++static uint8_t rowbuf[256];++static void draw_sprite(item_t *it, int y0, int ra, int rb, int cx0, int cx1) {+ int id = it->a;+ const uint8_t *spr = ce_sprite(id);+ if (!spr) return;+ const art_sprite_t *s = &art_sprites[id];+ int w = it->w, h = it->h, sw = s->w, sh = s->h, fx = it->fx;+ int ya = it->y > ra ? it->y : ra, yb = it->y + h < rb ? it->y + h : rb;+ int xa = it->x > cx0 ? it->x : cx0, xb = it->x + w < cx1 ? it->x + w : cx1;+ if (xa >= xb || ya >= yb) return;+ int same = w == sw && h == sh, ed = fx & FX_EDMASK;+ const uint8_t *tab = 0, *dim = (fx & FX_DIM) ? ce_lut + LUT_SHADE + 14 * CE_NSTATIC : 0;+ const uint8_t *grey = (fx & FX_GREY) ? ce_lut + LUT_GREY : 0, *pat = ed ? ed_pattern(ed, it->x) : 0;+ const uint8_t *edl = ed ? ce_lut + LUT_EDLUT + (ed - 1) * ED_LEVELS * CE_NSTATIC : 0;+ if (fx & FX_SHADOW) tab = ce_shade_tab(11);+ int plain = !(fx & ~FX_SHADOW);+ for (int y = ya; y < yb; y++) {+ int sy = same ? y - it->y : (int)((unsigned)(y - it->y) * sh / h);+ const uint8_t *row = spr + (spr[2 * sy] | spr[2 * sy + 1] << 8);+ uint8_t *d = strip + (y - y0) * SCR_W;+ if (same && plain) {+ /* the runs straight in (or their shadow) */+ int x = it->x, end = it->x + sw;+ while (x < end) {+ x += row[0];+ int n = row[1];+ const uint8_t *p = row + 2;+ row = p + n;+ int a = x < xa ? xa : x, b = x + n > xb ? xb : x + n;+ if (a < b) {+ if (tab)+ for (int i = a; i < b; i++) d[i] = tab[d[i]];+ else+ memcpy(d + a, p + (a - x), (size_t)(b - a));+ }+ x += n;+ }+ continue;+ }+ /* the row unpacked, then each pixel with its effects */+ memset(rowbuf, 255, (size_t)sw);+ for (int x = 0; x < sw;) {+ x += row[0];+ int n = row[1];+ memcpy(rowbuf + x, row + 2, (size_t)n);+ row += 2 + n;+ x += n;+ }+ const uint8_t *prow = pat ? pat + (sy >> 1 < ED_CH ? sy >> 1 : ED_CH - 1) * (ED_CW / 2) : 0;+ unsigned step = ((unsigned)sw << 8) / (unsigned)w, sx8 = (unsigned)(xa - it->x) * step;+ for (int x = xa; x < xb; x++, sx8 += step) {+ int sx = same ? x - it->x : (int)(sx8 >> 8);+ int v = rowbuf[sx];+ if (v == 255) continue;+ if (fx & FX_SHADOW) {+ d[x] = tab[d[x]];+ continue;+ }+ if (fx & FX_WHITE) {+ d[x] = CE_WHITE;+ continue;+ }+ if (edl) {+ int cx = sx >> 1 < ED_CW ? sx >> 1 : ED_CW - 1;+ int lv = (prow[cx >> 1] >> ((cx & 1) * 4)) & 15;+ v = edl[lv * CE_NSTATIC + v];+ }+ if (grey) v = grey[v];+ if (dim) v = dim[v];+ d[x] = (uint8_t)v;+ }+ }+}++/* ------------------------------------------------------------------ shapes */+static void draw_rsq(item_t *it, int y0, int ra, int rb, int cx0, int cx1) {+ static const int16_t q[17] = {256, 255, 251, 245, 237, 226, 213, 198, 181, 162, 142, 121, 98, 74, 50, 25, 0};+ int i = (it->fx & 63) >> 2, co = q[i], si = q[16 - i];+ int hs = it->r * 256 + 128, R = it->w / 2, cx = it->x + R, cy = it->y + R;+ int ya = it->y > ra ? it->y : ra, yb = it->y + it->h < rb ? it->y + it->h : rb;+ int xa = it->x > cx0 ? it->x : cx0, xb = it->x + it->w < cx1 ? it->x + it->w : cx1;+ for (int y = ya; y < yb; y++) {+ uint8_t *d = strip + (y - y0) * SCR_W;+ int dy = y - cy;+ for (int x = xa; x < xb; x++) {+ int dx = x - cx;+ int u = dx * co + dy * si, v = dy * co - dx * si;+ if (u < 0) u = -u;+ if (v < 0) v = -v;+ if (u <= hs && v <= hs) d[x] = (uint8_t)it->a;+ }+ }+}++static void draw_rrect(item_t *it, int y0, int ra, int rb, int cx0, int cx1, int shade) {+ int r = it->r, x = it->x, w = it->w, h = it->h;+ int ya = it->y > ra ? it->y : ra, yb = it->y + h < rb ? it->y + h : rb;+ int xa = x > cx0 ? x : cx0, xb = x + w < cx1 ? x + w : cx1;+ uint8_t c = (uint8_t)it->a;+ const uint8_t *tab = shade ? ce_shade_tab(it->a) : 0;+ for (int yy = ya; yy < yb; yy++) {+ int j = yy - it->y, cy = -1;+ if (j < r) cy = j;+ else if (j >= h - r) cy = h - 1 - j;+ uint8_t *d = strip + (yy - y0) * SCR_W;+ int ma = xa, mb = xb;+ if (cy >= 0) {+ if (ma < x + r) ma = x + r;+ if (mb > x + w - r) mb = x + w - r;+ }+ if (ma < mb) {+ if (shade)+ for (int xx = ma; xx < mb; xx++) d[xx] = tab[d[xx]];+ else+ memset(d + ma, c, (size_t)(mb - ma));+ }+ if (cy < 0) continue;+ for (int side = 0; side < 2; side++) {+ int ea = side ? (mb > xa ? mb : xa) : xa, eb = side ? xb : (ma < xb ? ma : xb);+ for (int xx = ea; xx < eb; xx++) {+ int i = xx - x;+ int a = cov[r][cy][i < r ? i : w - 1 - i];+ if (!a) continue;+ if (a < 16) continue;+ d[xx] = shade ? tab[d[xx]] : c;+ }+ }+ }+}++static void draw_rect(item_t *it, int y0, int ra, int rb, int cx0, int cx1) {+ int ya = it->y > ra ? it->y : ra, yb = it->y + it->h < rb ? it->y + it->h : rb;+ int xa = it->x > cx0 ? it->x : cx0, xb = it->x + it->w < cx1 ? it->x + it->w : cx1;+ if (xa >= xb) return;+ for (int y = ya; y < yb; y++) memset(strip + (y - y0) * SCR_W + xa, it->a, (size_t)(xb - xa));+}++/* ------------------------------------------------------------------ the frame */+static unsigned mix(unsigned h, unsigned v) {+ h ^= v;+ return (h << 5) + h + (h >> 13);+}++static unsigned item_hash(const item_t *it) {+ unsigned h = mix(mix(mix((unsigned)(uint16_t)it->x, (unsigned)(uint16_t)it->y), (unsigned)it->w),+ (unsigned)it->h);+ h = mix(h, (unsigned)it->type | (unsigned)it->r << 8 | (unsigned)it->fx << 16);+ h = mix(h, (unsigned)it->a ^ (unsigned)it->b << 9);+ const int16_t *c = clips[it->clip];+ h = mix(h, (unsigned)(c[0] ^ c[1] << 9) ^ (unsigned)(c[2] << 3 ^ c[3] << 12));+ if (it->s)+ for (const char *p = it->s; *p; p++) h = mix(h, (unsigned char)*p);+ /* what moves on its own: the editions' sheen, the fire */+ if (it->type == I_SPRITE && (it->fx & FX_EDMASK)) h = mix(h, g_time / ED_DT_MS);+ if (it->type == I_FLAME) h = mix(h, (unsigned)ce_flame_frame());+ return h;+}++void g_end(void) {+ unsigned hs[NSTRIP];+ unsigned base = mix(mix((unsigned)bg_swirl, (unsigned)bg_cover_x), (unsigned)bg_solid ^ (unsigned)ce_bg_ver << 8);+ for (int s = 0; s < NSTRIP; s++) hs[s] = base + (unsigned)s;+ for (int i = 0; i < nitems; i++) {+ const item_t *it = &items[i];+ int s0 = it->y < 0 ? 0 : it->y / SH, s1 = (it->y + it->h - 1) / SH;+ if (s1 >= NSTRIP) s1 = NSTRIP - 1;+ if (s0 > s1) continue;+ unsigned h = item_hash(it) + (unsigned)i;+ for (int s = s0; s <= s1; s++) hs[s] = mix(hs[s], h);+ }+ for (int s = 0; s < NSTRIP; s++) {+ if (drawn_once && hs[s] == strip_hash[s]) continue;+ strip_hash[s] = hs[s];+ int y0 = s * SH, y1 = y0 + SH;+ uint16_t dyn = 0;+ if (bg_swirl) {+ for (int y = y0; y < y1; y++) {+ uint8_t *d = strip + (y - y0) * SCR_W;+ if (bg_cover_x > 0) memset(d, bg_solid, (size_t)(bg_cover_x < SCR_W ? bg_cover_x : SCR_W));+ if (bg_cover_x < SCR_W) ce_bg_row(d, y, bg_cover_x);+ }+ } else+ memset(strip, bg_solid, sizeof strip);+ for (int i = 0; i < nitems; i++) {+ item_t *it = &items[i];+ if (it->y >= y1 || it->y + it->h <= y0) continue;+ const int16_t *c = clips[it->clip];+ int cy0 = y0 > c[1] ? y0 : c[1], cy1 = y1 < c[3] ? y1 : c[3];+ if (cy0 >= cy1) continue;+ if (it->type != I_SPRITE && it->type != I_SHADE && it->type != I_FLAME && it->a >= CE_DYN0 && it->a < CE_SWIRL0)+ dyn |= (uint16_t)(1u << (it->a - CE_DYN0));+ switch (it->type) {+ case I_RECT: draw_rect(it, y0, cy0, cy1, c[0], c[2]); break;+ case I_RRECT: draw_rrect(it, y0, cy0, cy1, c[0], c[2], 0); break;+ case I_SHADE: draw_rrect(it, y0, cy0, cy1, c[0], c[2], 1); break;+ case I_SPRITE: draw_sprite(it, y0, cy0, cy1, c[0], c[2]); break;+ case I_TEXT: draw_text(it, y0, cy0, cy1, c[0], c[2]); break;+ case I_RSQ: draw_rsq(it, y0, cy0, cy1, c[0], c[2]); break;+ case I_FLAME: ce_flame_rows(it->a & 1, it->x, it->y, it->w, it->h, it->b, strip, y0, cy0, cy1, c[0], c[2]); break;+ }+ }+ strip_dyn[s] = dyn;+ memcpy(ce_vram + y0 * SCR_W, strip, sizeof strip);+ }+ drawn_once = 1;+}diff --git a/games/balatro/ce/tools/artsrc.py b/games/balatro/ce/tools/artsrc.pynew file mode 100644index 00000000..31f90001--- /dev/null+++ b/games/balatro/ce/tools/artsrc.py@@ -0,0 +1,82 @@+"""The NumWorks version's art, read back from games/balatro/src/assets.c: every sprite decoded (tools/rc.py) to+RGB565 colours (None where transparent), and the fonts as they are. The TI-84 Plus CE's art is made from these."""+import os+import re+import sys++HERE = os.path.dirname(os.path.abspath(__file__))+GAME = os.path.normpath(os.path.join(HERE, "..", ".."))+sys.path.insert(0, os.path.join(GAME, "tools"))+import rc # noqa: E402+++def _array(src, name):+ m = re.search(r"const \w+ " + name + r"\[[^\]]*\] = \{(.*?)\};", src, re.S)+ if not m:+ raise SystemExit(f"artsrc: no {name} in assets.c")+ return m.group(1)+++def _ints(body):+ return [int(v, 0) for v in re.findall(r"0x[0-9A-Fa-f]+|\d+", body)]+++class Art:+ def __init__(self, path=os.path.join(GAME, "src", "assets.c")):+ src = open(path).read()+ hdr = open(os.path.join(GAME, "src", "assets.h")).read()+ self.defines = {k: int(v) for k, v in re.findall(r"#define (\w+) (-?\d+)\n", hdr)}+ self.cw, self.ch = self.defines["ART_CW"], self.defines["ART_CH"]+ self.table = [tuple(map(int, t)) for t in re.findall(r"\{(\d+), (\d+), (\d+), (\d+)\}", _array(src, "art_sprites"))]+ self.blob = bytes(_ints(_array(src, "art_blob")))+ pal = _ints(_array(src, "art_pal"))+ offs = _ints(_array(src, "art_pal_off"))+ tmpl = [int(v) for v in re.findall(r"-?\d+", _array(src, "art_tmpl_of_group"))]+ self.pals = [pal[o:(offs[i + 1] if i + 1 < len(offs) else len(pal))] for i, o in enumerate(offs)]+ self.tmpl_of_group = tmpl+ self.fonts = {}+ for name in ("font_small", "font_med", "font_large", "font_large_digits"):+ glyphs = [tuple(map(int, g)) for g in re.findall(r"\{(\d+),(\d+),(\d+)\}", _array(src, name))]+ self.fonts[name] = (glyphs, bytes(_ints(_array(src, name + "_bits"))))+ self._idx = {}++ def indices(self, i):+ """sprite i as rows of its group's palette indices (0 transparent)"""+ if i in self._idx:+ return self._idx[i]+ off, g, w, h = self.table[i]+ t = self.tmpl_of_group[g]+ tm = None+ if t >= 0 and t != i and w == self.cw:+ tm = self.indices(t)+ end = self.table[i + 1][0] if i + 1 < len(self.table) else len(self.blob)+ pix = rc.decode_sprite(self.blob[off:end + 8], w, h, tm)+ self._idx[i] = pix+ return pix++ def rgb565(self, i):+ """sprite i as rows of RGB565 values, None where transparent"""+ g = self.table[i][1]+ pal = self.pals[g]+ return [[pal[v] if v else None for v in row] for row in self.indices(i)]++ def size(self, i):+ return self.table[i][2], self.table[i][3]+++def to888(c):+ r, g, b = c >> 11, (c >> 5) & 63, c & 31+ return (r << 3 | r >> 2, g << 2 | g >> 4, b << 3 | b >> 2)+++if __name__ == "__main__":+ import time+ t0 = time.time()+ a = Art()+ n = len(a.table)+ cols = []+ for i in range(n):+ px = a.rgb565(i)+ cols.append(len(set(v for r in px for v in r if v is not None)))+ print(f"{n} sprites decoded in {time.time() - t0:.1f} s; colours per sprite: max {max(cols)},",+ f"over 16: {sum(c > 16 for c in cols)}, over 24: {sum(c > 24 for c in cols)}")diff --git a/games/balatro/ce/tools/cedata.py b/games/balatro/ce/tools/cedata.pynew file mode 100644index 00000000..44f18d2e--- /dev/null+++ b/games/balatro/ce/tools/cedata.py@@ -0,0 +1,32 @@+#!/usr/bin/env python3+"""The NumWorks version's data.c for the TI-84 Plus CE: the same file without its 11 KB of texts, which the CE reads+from the archive (tools/mkart.py puts them in BALLUT; src/art_ce.c points ce_text_blob at them).++Usage: cedata.py ../src/data.c gen/data.c"""+import re+import sys+++def blob(src):+ """the texts' bytes, from data.c"""+ m = re.search(r"const uint8_t text_blob\[(\d+)\] = \{(.*?)\};", src, re.S)+ if not m:+ raise SystemExit("cedata: no text_blob in data.c")+ data = bytes(int(v, 0) for v in re.findall(r"0x[0-9A-Fa-f]+|\d+", m.group(2)))+ if len(data) != int(m.group(1)):+ raise SystemExit("cedata: text_blob's size")+ return data+++def main():+ src = open(sys.argv[1], encoding="utf-8").read()+ blob(src)+ out = re.sub(r"const uint8_t text_blob\[\d+\] = \{.*?\};\n", "", src, count=1, flags=re.S)+ out = out.replace('#include "data.h"\n', '#include "../../src/data.h"\nextern const uint8_t *ce_text_blob;\n'+ '#define text_blob ce_text_blob\n', 1)+ out = out.replace('#include "../../common/np_text.h"', '#include "../../../common/np_text.h"', 1)+ open(sys.argv[2], "w", encoding="utf-8").write("/* Made by tools/cedata.py from src/data.c: do not edit. */\n" + out)+++if __name__ == "__main__":+ main()diff --git a/games/balatro/ce/tools/cekeys.py b/games/balatro/ce/tools/cekeys.pynew file mode 100644index 00000000..a006c230--- /dev/null+++ b/games/balatro/ce/tools/cekeys.py@@ -0,0 +1,44 @@+#!/usr/bin/env python3+"""The NumWorks version's main.c for the TI-84 Plus CE: the same file with the CE's keys named where the screens+name keys (platform/ti84ce/README.md: 2nd is OK, enter is EXE, clear is Back, mode is Home, del is the NumWorks's+backspace, y= is shift, math is toolbox, vars is var), and its main() renamed for src/ce_main.c to call.+Every text below must be found, so a change to the NumWorks texts shows here.++Usage: cekeys.py ../src/main.c gen/main.c"""+import sys++SWAPS = [+ # the How to play page+ (r'\004OK\020 select a card', r'\0042nd\020 select a card'),+ (r'\004EXE\020 \002Play Hand\020 \004DEL\020 \003Discard\020',+ r'\004enter\020 \002Play Hand\020 \004del\020 \003Discard\020'),+ (r'\004shift\020 sort the hand', r'\004y=\020 sort the hand'),+ (r'\004left/right\020 to carry it, \004OK\020 to put it down', r'\004left/right\020 to carry it, \0042nd\020 to put it down'),+ (r'\004toolbox\020 Run Info \004var\020 view deck', r'\004math\020 Run Info \004vars\020 view deck'),+ (r'\004back\020 back / Options \004home\020 save, quit', r'\004clear\020 back / Options \004mode\020 save, quit'),+ (r'Hold \004OK\020 or \004EXE\020 to speed up scoring.', r'Hold \0042nd\020 or \004enter\020 to speed up scoring.'),+ # the keys under the round's buttons, the move hint+ ('keycap(px + pw / 2, 229, "exe");', 'keycap(px + pw / 2, 229, "enter");'),+ ('keycap(sx + sw / 2, 229, "shift");', 'keycap(sx + sw / 2, 229, "y=");'),+ ('const char *k = moving ? "OK" : "alpha"', 'const char *k = moving ? "2nd" : "alpha"'),+ # Run Info+ ('T("left/right: tabs back: close")', 'T("left/right: tabs clear: close")'),+ # the entry point+ ("int main(void) {", "int balatro_main(void) {"),+]+++def main():+ src, dst = sys.argv[1], sys.argv[2]+ s = open(src, encoding="utf-8").read()+ for a, b in SWAPS:+ if s.count(a) != 1:+ raise SystemExit(f"cekeys: {a!r} found {s.count(a)} times in {src}")+ s = s.replace(a, b)+ head = "/* Made by tools/cekeys.py from src/main.c: do not edit. */\n"+ s = head + s.replace('#include "', '#include "../../src/', s.count('#include "'))+ open(dst, "w", encoding="utf-8").write(s)+++if __name__ == "__main__":+ main()diff --git a/games/balatro/ce/tools/host.c b/games/balatro/ce/tools/host.cnew file mode 100644index 00000000..ff7ec0ee--- /dev/null+++ b/games/balatro/ce/tools/host.c@@ -0,0 +1,278 @@+/* The TI-84 Plus CE version on a computer, for testing: the calculator's 8-bit screen and palette, its keys, its+ * appvars (gen/*.bin, as tools/mkart.py makes them) and the save (a file), with SDL 3 for a window.+ *+ * In the environment, as platform/sdl/np_sdl.c: NP_HEADLESS=1 for no window (and a clock that only moves when the+ * game sleeps: fast, and the same every run), NP_KEYS "1500-1700:ok,3000:back" holds keys from one time to another+ * (ms; NumWorks names as eadk_key_* or the CE's: 2nd enter clear mode del y= math vars), NP_SHOTS "2000:a.ppm,..."+ * saves the screen then, NP_QUIT_MS holds mode then (the game saves and ends), NP_SAVE the save's file+ * (default bin/host/NPbalato.bin). Keys in the window: arrows, Z or space 2nd, return enter, backspace clear,+ * escape mode, D del, S y=, A alpha, M math, V vars. */+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <eadk.h>+#include "ce.h"+#include "np_port.h"+#ifdef __has_include+#if __has_include(<SDL3/SDL.h>)+#include <SDL3/SDL.h>+#define HAVE_SDL 1+#endif+#endif++int balatro_main(void);++static uint8_t vram[SCR_W * SCR_H];+uint8_t *ce_vram = vram;+static uint16_t palette[256];+static int headless;+static uint64_t vclock, t0;+static long frames;++void ce_set_palette(int first, int n, const uint16_t *c) { memcpy(palette + first, c, (size_t)n * 2); }++static struct {+ char name[9];+ uint8_t *data;+ size_t size;+} vars[24];+const uint8_t *ce_appvar(const char *name, size_t *size) {+ for (int i = 0; i < 24; i++) {+ if (vars[i].data && !strcmp(vars[i].name, name)) {+ *size = vars[i].size;+ return vars[i].data;+ }+ if (!vars[i].data) {+ char path[64];+ snprintf(path, sizeof path, "gen/%s.bin", name);+ FILE *f = fopen(path, "rb");+ if (!f) return 0;+ fseek(f, 0, SEEK_END);+ long n = ftell(f);+ fseek(f, 0, SEEK_SET);+ vars[i].data = malloc((size_t)n + 16);+ if (fread(vars[i].data, 1, (size_t)n, f) != (size_t)n) n = 0;+ fclose(f);+ snprintf(vars[i].name, sizeof vars[i].name, "%s", name);+ vars[i].size = (size_t)n;+ *size = (size_t)n;+ return vars[i].data;+ }+ }+ return 0;+}++/* ---- zx0 (as the CE's C library unpacks it) */+static const uint8_t *zin;+static uint8_t zmask, zbits, zlast, zback;+static uint8_t zbyte(void) { return zlast = *zin++; }+static int zbit(void) {+ if (zback) {+ zback = 0;+ return zlast & 1;+ }+ zmask >>= 1;+ if (!zmask) zmask = 128, zbits = zbyte();+ return zbits & zmask ? 1 : 0;+}+static int zgamma(int inv) {+ int v = 1;+ while (!zbit()) v = v << 1 | (zbit() ^ inv);+ return v;+}+void zx0_Decompress(void *dst, const void *src) {+ uint8_t *out = dst;+ zin = src, zmask = 0, zback = 0;+ int off = 1, len;+ for (;;) {+ len = zgamma(0);+ while (len--) *out++ = zbyte();+ if (!zbit()) {+ len = zgamma(0);+ while (len--) *out = out[-off], out++;+ if (!zbit()) continue;+ }+ for (;;) {+ off = zgamma(1);+ if (off == 256) return;+ off = off * 128 - (zbyte() >> 1);+ zback = 1;+ len = zgamma(0) + 1;+ while (len--) *out = out[-off], out++;+ if (!zbit()) break;+ }+ }+}++/* ---- time */+#ifdef HAVE_SDL+static uint64_t real_ms(void) { return SDL_GetTicks(); }+#else+#include <time.h>+static uint64_t real_ms(void) {+ struct timespec ts;+ clock_gettime(CLOCK_MONOTONIC, &ts);+ return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;+}+#endif+uint64_t eadk_timing_millis(void) { return headless ? vclock : real_ms() - t0; }+uint32_t ce_ms(void) { return (uint32_t)eadk_timing_millis(); }+void eadk_timing_msleep(uint32_t ms) {+ if (headless) vclock += ms;+#ifdef HAVE_SDL+ else SDL_Delay(ms);+#endif+}++/* ---- the screen */+static void to_rgb(uint8_t *rgb) {+ for (int i = 0; i < SCR_W * SCR_H; i++) {+ uint16_t c = palette[vram[i]];+ int r = c >> 10 & 31, g = c >> 5 & 31, b = c & 31;+ rgb[3 * i] = (uint8_t)(r << 3 | r >> 2), rgb[3 * i + 1] = (uint8_t)(g << 3 | g >> 2), rgb[3 * i + 2] = (uint8_t)(b << 3 | b >> 2);+ }+}+static void shot(const char *path) {+ static uint8_t rgb[SCR_W * SCR_H * 3];+ to_rgb(rgb);+ FILE *f = fopen(path, "wb");+ if (!f) return;+ fprintf(f, "P6\n%d %d\n255\n", SCR_W, SCR_H);+ fwrite(rgb, 1, sizeof rgb, f);+ fclose(f);+}++/* ---- keys */+static const struct {+ const char *name;+ int key;+} NAMES[] = {{"left", eadk_key_left}, {"up", eadk_key_up}, {"down", eadk_key_down}, {"right", eadk_key_right},+ {"ok", eadk_key_ok}, {"2nd", eadk_key_ok}, {"back", eadk_key_back}, {"clear", eadk_key_back},+ {"home", eadk_key_home}, {"mode", eadk_key_home}, {"shift", eadk_key_shift}, {"y=", eadk_key_shift},+ {"alpha", eadk_key_alpha}, {"var", eadk_key_var}, {"vars", eadk_key_var}, {"toolbox", eadk_key_toolbox},+ {"math", eadk_key_toolbox}, {"backspace", eadk_key_backspace}, {"del", eadk_key_backspace},+ {"exe", eadk_key_exe}, {"enter", eadk_key_exe}};+static eadk_keyboard_state_t script_keys(uint64_t now) {+ const char *s = getenv("NP_KEYS");+ eadk_keyboard_state_t k = 0;+ while (s && *s) {+ unsigned long a = strtoul(s, (char **)&s, 10), b = a + 90;+ if (*s == '-') b = strtoul(s + 1, (char **)&s, 10);+ if (*s++ != ':') break;+ size_t n = strcspn(s, ",");+ for (size_t i = 0; i < sizeof NAMES / sizeof NAMES[0]; i++)+ if (strlen(NAMES[i].name) == n && !strncmp(s, NAMES[i].name, n) && now >= a && now <= b)+ k |= (eadk_keyboard_state_t)1 << NAMES[i].key;+ s += n;+ if (*s == ',') s++;+ }+ const char *q = getenv("NP_QUIT_MS");+ if (q && now >= strtoull(q, 0, 10)) k |= (eadk_keyboard_state_t)1 << eadk_key_home;+ return k;+}+static void script_shots(uint64_t now) {+ static uint64_t done_until;+ const char *s = getenv("NP_SHOTS");+ while (s && *s) {+ unsigned long t = strtoul(s, (char **)&s, 10);+ if (*s++ != ':') break;+ size_t n = strcspn(s, ",");+ char path[256];+ snprintf(path, sizeof path, "%.*s", (int)n, s);+ if (t > done_until && t <= now) shot(path);+ s += n;+ if (*s == ',') s++;+ }+ done_until = now;+}++#ifdef HAVE_SDL+static SDL_Window *win;+static SDL_Renderer *ren;+static SDL_Texture *tex;+static void present(void) {+ static uint8_t rgb[SCR_W * SCR_H * 3];+ to_rgb(rgb);+ SDL_UpdateTexture(tex, 0, rgb, SCR_W * 3);+ SDL_RenderClear(ren);+ SDL_RenderTexture(ren, tex, 0, 0);+ SDL_RenderPresent(ren);+}+static const struct {+ SDL_Scancode sc;+ int key;+} KEYMAP[] = {{SDL_SCANCODE_LEFT, eadk_key_left}, {SDL_SCANCODE_RIGHT, eadk_key_right}, {SDL_SCANCODE_UP, eadk_key_up},+ {SDL_SCANCODE_DOWN, eadk_key_down}, {SDL_SCANCODE_Z, eadk_key_ok}, {SDL_SCANCODE_SPACE, eadk_key_ok},+ {SDL_SCANCODE_RETURN, eadk_key_exe}, {SDL_SCANCODE_BACKSPACE, eadk_key_back},+ {SDL_SCANCODE_ESCAPE, eadk_key_home}, {SDL_SCANCODE_D, eadk_key_backspace},+ {SDL_SCANCODE_S, eadk_key_shift}, {SDL_SCANCODE_A, eadk_key_alpha}, {SDL_SCANCODE_M, eadk_key_toolbox},+ {SDL_SCANCODE_V, eadk_key_var}};+#endif++eadk_keyboard_state_t eadk_keyboard_scan(void) {+ uint64_t now = eadk_timing_millis();+ frames++;+ script_shots(now);+ eadk_keyboard_state_t k = script_keys(now);+#ifdef HAVE_SDL+ if (!headless) {+ SDL_Event e;+ while (SDL_PollEvent(&e))+ if (e.type == SDL_EVENT_QUIT) k |= (eadk_keyboard_state_t)1 << eadk_key_home;+ const bool *ks = SDL_GetKeyboardState(0);+ for (size_t i = 0; i < sizeof KEYMAP / sizeof KEYMAP[0]; i++)+ if (ks[KEYMAP[i].sc]) k |= (eadk_keyboard_state_t)1 << KEYMAP[i].key;+ present();+ }+#endif+ return k;+}++/* ---- files */+static const char *save_path(void) { return getenv("NP_SAVE") ? getenv("NP_SAVE") : "bin/host/NPbalato.bin"; }+static uint8_t *store;+static size_t store_size;+uint8_t *ce_storage_open(const char *name, size_t size) {+ (void)name;+ store = calloc(1, size);+ store_size = size;+ FILE *f = fopen(save_path(), "rb");+ if (f) {+ if (fread(store, 1, size, f)) {}+ fclose(f);+ }+ return store;+}+void ce_storage_keep(void) {+ FILE *f = fopen(save_path(), "wb");+ if (!f) return;+ fwrite(store, 1, store_size, f);+ fclose(f);+}+void np_begin(void) {}+int np_end(void) { return 0; }++int main(void) {+ headless = getenv("NP_HEADLESS") && *getenv("NP_HEADLESS") == '1';+#ifdef HAVE_SDL+ if (!headless) {+ SDL_Init(SDL_INIT_VIDEO);+ int sc = getenv("NP_SCALE") ? atoi(getenv("NP_SCALE")) : 3;+ win = SDL_CreateWindow("Balatro (TI-84 Plus CE)", SCR_W * sc, SCR_H * sc, 0);+ ren = SDL_CreateRenderer(win, 0);+ tex = SDL_CreateTexture(ren, SDL_PIXELFORMAT_RGB24, SDL_TEXTUREACCESS_STREAMING, SCR_W, SCR_H);+ SDL_SetTextureScaleMode(tex, SDL_SCALEMODE_NEAREST);+ }+#else+ headless = 1;+#endif+ t0 = real_ms();+ if (!ce_art_init() || !ce_bg_init()) {+ fprintf(stderr, "host: an appvar is missing (make first)\n");+ return 1;+ }+ ce_set_palette(0, CE_NSTATIC, ce_palette);+ balatro_main();+ fprintf(stderr, "host: %ld frames in %llu ms\n", frames, (unsigned long long)eadk_timing_millis());+ return 0;+}diff --git a/games/balatro/ce/tools/mkart.py b/games/balatro/ce/tools/mkart.pynew file mode 100644index 00000000..b90bdd06--- /dev/null+++ b/games/balatro/ce/tools/mkart.py@@ -0,0 +1,533 @@+#!/usr/bin/env python3+"""The TI-84 Plus CE version's art and tables, made from the NumWorks version's (src/assets.c) and Balatro's shaders+as the NumWorks version works them out (src/bg.c, fx.c, flame.c). Python 3 only (and convbin for zx0).++ mkart.py OUTDIR CONVBIN++writes OUTDIR/ce_art.c (the sprites' table, the fonts, the fixed colours), OUTDIR/ce_art.h (constants), and the appvars'+contents as OUTDIR/<NAME>.bin, listed in OUTDIR/appvars.txt.++Colours: 0..175 fixed (tools/palette.py), 176..191 taken by screens as they need them, 192..255 the background's+(16 levels of its paint, in 4 banks: as it is, then darker under shaded panels and shadows).+Sprites: rows of runs (a skip, a length, the pixels), after a table of each row's start; the cards' size of art+(Jokers, Tarots, Planets, Spectrals, Vouchers, packs) is also zx0-packed, unpacked when shown (src/art_ce.c)."""+import math+import os+import subprocess+import sys++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+from artsrc import GAME, Art, to888 # noqa: E402+from palette import PALETTE # noqa: E402++GAME_SRC = os.path.join(GAME, "src")+NSTATIC, DYN0, SWIRL0, LEVELS, BANKS = 176, 176, 192, 16, 4+BANK_DARK = (0, 9, 15, 21) # how dark each bank is, of 32+MAXVAR = 65000 # bytes an appvar holds here+TRANSPARENT = 255+++# ------------------------------------------------------------------ colours+def lab(rgb):+ r, g, b = (v / 255.0 for v in rgb)+ y = 0.2126 * r ** 2.2 + 0.7152 * g ** 2.2 + 0.0722 * b ** 2.2+ return (y ** (1 / 3) * 100, (r - g) * 60, (g - b) * 40, (r - b) * 30)+++PLAB = [lab(c) for c in PALETTE]+_near = {}+++def nearest(rgb):+ """the closest fixed colour"""+ rgb = tuple(int(v) for v in rgb)+ if rgb not in _near:+ x = lab(rgb)+ best, bd = 0, 1e30+ for i, p in enumerate(PLAB):+ d = (p[0] - x[0]) ** 2 + (p[1] - x[1]) ** 2 + (p[2] - x[2]) ** 2 + (p[3] - x[3]) ** 2+ if d < bd:+ bd, best = d, i+ _near[rgb] = best+ return _near[rgb]+++def c1555(rgb):+ r, g, b = rgb+ return (r & 248) << 7 | (g & 248) << 2 | b >> 3+++def clamp01(v):+ return 0.0 if v < 0 else 1.0 if v > 1 else v+++# ------------------------------------------------------------------ sprites+def rle_rows(rows, w):+ """[row table: h x u16 offsets from the sprite's start] then the rows: (skip, length, pixels) until w"""+ h = len(rows)+ body = bytearray()+ offs = []+ for r in rows:+ offs.append(2 * h + len(body))+ x = 0+ while x < w:+ s = x+ while x < w and r[x] == TRANSPARENT and x - s < 255:+ x += 1+ l0 = x+ while x < w and r[x] != TRANSPARENT and x - l0 < 255:+ x += 1+ body += bytes((l0 - s, x - l0)) + bytes(r[l0:x])+ out = bytearray()+ for o in offs:+ out += bytes((o & 255, o >> 8))+ return bytes(out + body)+++def zx0(data, convbin, tmp):+ src, dst = os.path.join(tmp, "zx.in"), os.path.join(tmp, "zx.out")+ open(src, "wb").write(data)+ subprocess.run([convbin, "-j", "bin", "-i", src, "-k", "bin", "-c", "zx0", "-o", dst, "-l", "0"], check=True)+ return open(dst, "rb").read()+++# ------------------------------------------------------------------ the background (src/bg.c)+PI = math.pi+++def paint(sx, sy, mode, t_real, t_spin, spin, contrast):+ diag = 400.0+ ux, uy = (sx - 160.0) / diag, (sy - 120.0) / diag+ if mode == 0:+ ux -= 0.12+ ln = math.sqrt(ux * ux + uy * uy)+ if mode == 0:+ sp = t_spin * 0.5 * 0.2 + 302.2+ ang = math.atan2(uy, ux) + sp - 0.5 * 20.0 * (spin * ln + (1.0 - spin))+ vx, vy = ln * math.cos(ang) * 30.0, ln * math.sin(ang) * 30.0+ speed = t_real * 2.0+ else:+ s = t_real * 0.4+ ms = min(6.0, s)+ ang = math.atan2(uy, ux) + (2.2 + 0.4 * ms) * ln - 1.0 - s * 0.05 - ms * s * 0.02+ vx, vy = ln * math.cos(ang) * 30.0, ln * math.sin(ang) * 30.0+ speed = t_real * 6.0 * 0.4 + 1033.0+ u2x = u2y = vx + vy+ for _ in range(5):+ m = math.sin(max(vx, vy))+ u2x += m + vx+ u2y += m + vy+ vx += 0.5 * math.cos(5.1123314 + 0.353 * u2y + speed * 0.131121)+ vy += 0.5 * math.sin(u2x - 0.113 * speed)+ d = math.cos(vx + vy) - math.sin(vx * 0.711 - vy)+ vx -= d+ vy -= d+ l = math.sqrt(vx * vx + vy * vy)+ if mode == 0:+ cm = 0.25 * contrast + 0.5 * spin + 1.2+ r = min(2.0, max(0.0, l * 0.035 * cm))+ else:+ r = min(2.0, max(-2.0, 1.5 + l * 0.12 - 0.17 * 10.0))+ if r < 0.2:+ r = (r - 0.2) * 0.6 + 0.2+ r = (r + 2.0) * 0.5+ return min(255, max(0, int(r * 127.5 + 0.5)))+++BAYER = [[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]]+++def field(mode, x0, w, h, step):+ """the paint (0..255) every `step` pixels, then as levels 0..15 (ordered dither), as palette indices"""+ out = bytearray()+ for y in range(h):+ for x in range(w):+ sx, sy = x0 + x * step + (step - 1) / 2, y * step + (step - 1) / 2+ v = paint(sx, sy, mode, 20.0 if mode else 36.0, 0.0, 0.0, 1.0)+ lv = (v * (LEVELS - 1) * 16 // 255 + BAYER[y & 3][x & 3]) // 16+ out.append(SWIRL0 + min(LEVELS - 1, lv))+ return bytes(out)+++# ------------------------------------------------------------------ editions (src/fx.c)+def unpack(c):+ return c[0] / 255.0, c[1] / 255.0, c[2] / 255.0+++def over_art(o, n, k):+ d = (.3 * o[0] + .59 * o[1] + .11 * o[2]) - (.3 * n[0] + .59 * n[1] + .11 * n[2])+ n = [v + d for v in n]+ return [o[i] + (n[i] - o[i]) * k for i in range(3)]+++def hsl(r, g, b):+ lo, hi = min(r, g, b), max(r, g, b)+ d, s_ = hi - lo, hi + lo+ l = .5 * s_+ if d <= 0:+ return 0.0, 0.0, l+ s = d / s_ if l < .5 else d / (2.0 - s_)+ x = (g - b) / d if hi == r else (b - r) / d + 2.0 if hi == g else (r - g) / d + 4.0+ x /= 6+ return x - math.floor(x), s, l+++def hue(s, t, h):+ hs = (h - math.floor(h)) * 6.0+ if hs < 1:+ return (t - s) * hs + s+ if hs < 3:+ return t+ if hs < 4:+ return (t - s) * (4.0 - hs) + s+ return s+++def rgbh(h, s, l):+ if s < 0.0001:+ return l, l, l+ t = s * l + l if l < .5 else -s * l + (s + l)+ q = 2.0 * l - t+ return hue(q, t, h + 1 / 3), hue(q, t, h), hue(q, t, h - 1 / 3)+++def ed_foil(c, m):+ r, g, b = unpack(c)+ lo, hi = min(r, g, b), max(r, g, b)+ d = max(1.0 - lo, .5)+ d = min(d, hi)+ fr, fg, fb = r - d + d * m * .3, g - d + d * m * .3, b + d * m * 1.9+ a = (.3 + .9 * min(m * .1, .5)) * .8+ fr, fg, fb = clamp01(fr), clamp01(fg), clamp01(fb)+ return r + (fr - r) * a, g + (fg - g) * a, b + (fb - b) * a+++def ed_holo(c, shift):+ r, g, b = unpack(c)+ h, s, l = hsl(.5 * r, .5 * g, .5 * b + .5)+ lo, hi = min(r, g, b), max(r, g, b)+ d = .2 + .3 * (hi - lo) + .1 * hi+ hr, hg, hb = rgbh(h + shift, min(s * 1.3, 1), l * .6 + .4)+ n = [clamp01((1 - d) * r + d * hr * .9), clamp01((1 - d) * g + d * hg * .8), clamp01((1 - d) * b + d * hb * 1.2)]+ return over_art((r, g, b), n, .8)+++def ed_poly(c, shift):+ r, g, b = unpack(c)+ lo, hi = min(r, g, b), max(r, g, b)+ sf = 1.0 - (.05 * (1.1 - (hi - lo)) if 1.1 - (hi - lo) > 0 else 0)+ h, s, l = hsl(r * sf, g * sf, b)+ n = rgbh(h + shift, min(s + .5, .6), l)+ return over_art((r, g, b), n, .7)+++def ed_neg(c, sh):+ r, g, b = unpack(c)+ h, s, l = hsl(r, g, b)+ nr, ng, nb = rgbh(.2 - h, s, 1.0 - l)+ nr += .8 * 79 / 255+ ng += .8 * 99 / 255+ nb += .8 * 103 / 255+ return nr + sh * .6, ng + sh * .6, nb + sh+++def fsin(x):+ return math.sin(x)+++def fcos(x):+ return math.cos(x)+++def efield(u, v, k, t):+ x, y = (u - .5) * k, (v - .5) * k+ x1, y1 = x + 50 * fsin(-t / 143.634), y + 50 * fcos(-t / 99.4324)+ x2, y2 = x + 50 * fcos(t / 53.1532), y + 50 * fcos(t / 61.4532)+ x3, y3 = x + 50 * fsin(-t / 87.53218), y + 50 * fsin(-t / 49.0)+ return (1 + fcos(math.sqrt(x1 * x1 + y1 * y1) / 19.483) + fsin(math.sqrt(x2 * x2 + y2 * y2) / 33.155) * fcos(y2 / 15.73)+ + fcos(math.sqrt(x3 * x3 + y3 * y3) / 27.193) * fsin(x3 / 21.92)) * .5+++def cl(v, a, b):+ return a if v < a else b if v > b else v+++def foil_pattern(u, v, T):+ fr, fg = T / 28.0, T+ ax, ay = (u - .5) * (35.0 / 47.0), v - .5+ L = math.sqrt(ax * ax + ay * ay) + 1e-4+ fac = cl(2 * fsin(L * 90 + fr * 2 + 3 * (1 + .8 * fcos(L * 113.1121 - fr * 3.121))) - 1 - max(5 - L * 90, 0), 0, 1)+ rx, ry = fcos(fr * .1221), fsin(fr * .3512)+ ang = (rx * ax + ry * ay) / (math.sqrt(rx * rx + ry * ry) * L)+ fac2 = cl(5 * fcos(fg * .3 + ang * 3.14 * (2.2 + .9 * fsin(fr * 1.65 + .2 * fg))) - 4 - max(2 - L * 20, 0), 0, 1)+ fac3 = .3 * cl(2 * fsin(fr * 5 + u * 3 + 3 * (1 + .5 * fcos(fr * 7))) - 1, -1, 1)+ fac4 = .3 * cl(2 * fsin(fr * 6.66 + v * 3.8 + 3 * (1 + .5 * fcos(fr * 3.414))) - 1, -1, 1)+ mx = max(fac, fac2, fac3, fac4, 0)+ return max(0.0, mx + 2.2 * (fac + fac2 + fac3 + fac4))+++def holo_pattern(u, v, T):+ t = T * 8.221+ res = .5 + .5 * fcos((T / 28.0) * 2.612 + (efield(u, v, 125.0, t) - .5) * 3.14)+ gs = .79 * .5+ f1 = 7 * abs(fcos(u * gs * 20)) - 6+ f2 = 7 * fcos(v * gs * 45 + u * gs * 20) - 6+ f3 = 7 * fcos(v * gs * 45 - u * gs * 20) - 6+ fac = max(f1, f2, f3)+ return res + (.5 * fac if fac > 0 else 0)+++def poly_pattern(u, v, T):+ t = T * 3.221+ return .5 + .5 * fcos((T / 28.0) * 2.612 + (efield(u, v, 50.0, t) - .5) * 3.14)+++def neg_pattern(u, v, T):+ sh = .5 + .5 * fsin(11 * u + 4.32 * v + T * .43 * 12 + fcos(T * .19 + v * 4.2 - u * 4))+ return sh * sh * .12+++ED_FRAMES, ED_LEVELS, ED_CW, ED_CH = 32, 16, 18, 24+ED_DT = 0.3 # seconds between frames+# each edition's pattern range, cut into ED_LEVELS levels: (low, high, wraps)+ED_RANGE = [(0.0, 4.0, False), (0.0, 1.0, True), (0.0, 1.0, True), (0.0, 0.12, False)]+ED_FUN = [(foil_pattern, ed_foil), (holo_pattern, ed_holo), (poly_pattern, ed_poly), (neg_pattern, ed_neg)]+++def ed_level(e, val):+ lo, hi, wraps = ED_RANGE[e]+ f = (val - lo) / (hi - lo)+ if wraps:+ f -= math.floor(f)+ return int(f * ED_LEVELS) % ED_LEVELS+ return max(0, min(ED_LEVELS - 1, int(f * (ED_LEVELS - 1) + 0.5)))+++def ed_value(e, lv):+ lo, hi, wraps = ED_RANGE[e]+ if wraps:+ return lo + (hi - lo) * (lv + .5) / ED_LEVELS+ return lo + (hi - lo) * lv / (ED_LEVELS - 1)+++# ------------------------------------------------------------------ the flames (src/flame.c)+def len_term(ln):+ return 0.3 * (fcos(ln * 0.411) + 0.3344 * fsin(ln) - 0.23 * fcos(ln))+++def flame_params(k, I, t):+ idv = 91.0 if k else 37.0+ up = 4.0 * t - 5000.0 + 1.781 * idv+ scale = 7.5 + 3.0 / (2.0 + 2.0 * I)+ speed = (91.071 if k else 68.897) + fsin(t + idv) * fcos(t * 0.151 + idv)+ return dict(up=up, scale=scale, sp1=speed * 0.0812, sp2=speed * 0.1531, sp3=0.113785 * speed, sp4=0.13582 * speed,+ top_cut=max(0.0, 2.0 - 0.3 * I), damp=2.0 / (2.0 + I * 0.2), w1=0.2 * t, w2=0.931 * t)+++def smoke_at(q, fx, fy):+ if q["top_cut"] * 2 * (fy - .5) * (fy - .5) > 1.02:+ return 9.0+ wob = 0.01 * fsin(-1.123 * fx + q["w1"]) * fcos(5.3332 * fy + q["w2"])+ ucx, ucy = fx + fx * wob, fy + fy * wob+ svx, svy = ucx * q["scale"], ucy * q["scale"] + q["up"]+ s2x = s2y = 0.0+ for _ in range(5):+ ln = math.sqrt(svx * svx + svy * svy)+ add = len_term(ln)+ nx, ny = s2x + svx + 0.05 * s2y + add, s2y + svy + 0.05 * s2x + add+ s2x, s2y = nx, ny+ svx += 0.5 * fcos(fcos(s2y) + q["sp1"]) * fsin(3.22 + s2x - q["sp2"])+ svy += 0.5 * fsin(-s2x * 1.21222 + q["sp3"]) * fcos(s2y * 0.91213 - q["sp4"])+ dx, dy = svx / q["scale"] * 5, (svy - q["up"]) / q["scale"] * 5+ sm = max(0.0, (math.sqrt(dx * dx + dy * dy) + 0.1 * (math.sqrt(ucx * ucx + ucy * ucy) - .5)) * q["damp"])+ e = ucy - .5+ sm += q["top_cut"] * 2 * e * e+ if abs(fx) > 0.4:+ sm += 10 * (abs(fx) - 0.4)+ return sm+++FL_W, FL_H, FL_FRAMES, FL_LEVELS = 54, 47, 24, 5+FL_I = (0.6, 1.5, 3.0, 5.0, 8.0) # intensities kept+FL_GC, FL_GR = FL_W // 2 + 1, int(0.62 * FL_H) // 2 + 2+FL_ROWS = int(0.62 * FL_H)+COL1 = ((0.0, 0.616, 1.0), (0.996, 0.373, 0.333))+COL2 = ((0.36, 0.824, 0.36), (1.0, 0.618, 0.1))+++def flame_tables():+ """grids: [level][frame] FL_GR x FL_GC bytes, the smoke in 1/128 units capped at 17 (the flame shows under 16);+ colours: [k][level][row][17] palette indices"""+ grids = bytearray()+ for li, I in enumerate(FL_I):+ for f in range(FL_FRAMES):+ q = flame_params(1, I, f * 0.11)+ for j in range(FL_GR):+ for i in range(FL_GC):+ sm = smoke_at(q, i * 2.0 / FL_W - .5, j * 2.0 / FL_H - .5)+ grids.append(min(17, int(sm * 2048) >> 7))+ cols = bytearray()+ for k in range(2):+ for I in FL_I:+ for r in range(FL_ROWS):+ uy = (r + .5) / FL_H - .5+ d = 0.12 - uy+ base = [COL1[k][ch] * (1 - .5 * d) + 2.5 * d * COL2[k][ch] for ch in range(3)]+ for n in range(17):+ m = 1.0 + (-2.0 + 0.5 * I * (n / 16)) * d+ cols.append(nearest(tuple(int(clamp01(base[ch] * m) * 255 + .5) for ch in range(3))))+ return bytes(grids), bytes(cols)+++# ------------------------------------------------------------------ tables+def shade_luts():+ """33 x 176: each fixed colour darkened by a/32"""+ out = bytearray()+ for a in range(33):+ for c in PALETTE:+ out.append(nearest(tuple(v * (32 - a) // 32 for v in c)))+ return bytes(out)+++def grey_lut():+ out = bytearray()+ for c in PALETTE:+ r, g, b = c[0] >> 3, c[1] >> 2, c[2] >> 3+ l = (r * 2 + g + b * 2) // 5+ out.append(nearest((l << 3, l << 3, l << 3)))+ return bytes(out)+++def edition_luts():+ out = bytearray()+ for e in range(4):+ for lv in range(ED_LEVELS):+ val = ed_value(e, lv)+ for c in PALETTE:+ r, g, b = ED_FUN[e][1](c, val)+ out.append(nearest((int(clamp01(r) * 255 + .5), int(clamp01(g) * 255 + .5), int(clamp01(b) * 255 + .5))))+ return bytes(out)+++def edition_patterns():+ """[ed][frame][24 rows][9 bytes]: two cells a byte (low nibble first)"""+ out = bytearray()+ for e in range(4):+ pat = ED_FUN[e][0]+ for f in range(ED_FRAMES):+ T = 4.0 + f * ED_DT+ for cy in range(ED_CH):+ v = (cy * 2 + 1) / 47.0+ row = [ed_level(e, pat((cx * 2 + 1) / 35.0, v, T)) for cx in range(ED_CW)]+ for i in range(0, ED_CW, 2):+ out.append(row[i] | row[i + 1] << 4)+ return bytes(out)+++# ------------------------------------------------------------------ output+COMPRESSED_GROUPS = (0, 1, 2) # jokers, consumables, vouchers and packs+++def main():+ outdir, convbin = sys.argv[1], sys.argv[2]+ os.makedirs(outdir, exist_ok=True)+ art = Art()+ n = len(art.table)+ sprites = [] # (appvar, offset, w, h, packed)+ vars_ = {}+ order = []++ def put(prefix, data):+ """data into the first appvar of that prefix with room: (its index in order, offset)"""+ k = 0+ while True:+ name = f"{prefix}{k}"+ if name not in vars_:+ vars_[name] = bytearray()+ order.append(name)+ if len(vars_[name]) + len(data) <= MAXVAR:+ off = len(vars_[name])+ vars_[name] += data+ return order.index(name), off+ k += 1++ maxpacked = 0+ for i in range(n):+ w, h = art.size(i)+ g = art.table[i][1]+ px = art.rgb565(i)+ rows = [[TRANSPARENT if v is None else nearest(to888(v)) for v in r] for r in px]+ data = rle_rows(rows, w)+ packed = g in COMPRESSED_GROUPS and art.tmpl_of_group[g] != i+ if packed:+ maxpacked = max(maxpacked, len(data))+ data = zx0(data, convbin, outdir)+ v, off = put("BALART", data)+ sprites.append((v, off, w, h, packed))+ lut = bytearray()+ shade = shade_luts()+ grey = grey_lut()+ edl = edition_luts()+ edp = edition_patterns()+ fgrids, fcols = flame_tables()+ sys.path.insert(0, HERE)+ from cedata import blob as text_blob # noqa: E402+ texts = text_blob(open(os.path.join(GAME_SRC, "data.c"), encoding="utf-8").read())+ fonts = []+ for name, (glyphs, bits) in art.fonts.items():+ tab = bytearray()+ for o, w, a in glyphs:+ tab += bytes((o & 255, o >> 8, w, a))+ fonts += [(name, tab), (name + "_bits", bits)]+ parts = {}+ for name, blob in (("shade", shade), ("grey", grey), ("edlut", edl), ("fcol", fcols), ("text", texts)) + tuple(fonts):+ parts[name] = len(lut)+ lut += blob+ # the background: the run's paint right of the sidebar, the title's at half size+ bg_run = field(0, 102, 218, 240, 1)+ bg_title = field(1, 0, 160, 120, 2)+ blobs = dict(vars_)+ blobs["BALLUT"] = lut+ blobs["BALBG0"] = bg_run+ blobs["BALBG1"] = bg_title+ blobs["BALFIRE"] = fgrids+ blobs["BALED"] = edp+ if max(len(b) for b in blobs.values()) > MAXVAR:+ raise SystemExit("mkart: an appvar is too big")+ for name, blob in blobs.items():+ open(os.path.join(outdir, name + ".bin"), "wb").write(bytes(blob))+ open(os.path.join(outdir, "appvars.txt"), "w").write("\n".join(blobs) + "\n")+ # C: the table (the NumWorks's art_sprite_t: off = offset in its appvar, group = appvar * 2 + packed)+ c = ["/* Made by tools/mkart.py from src/assets.c: do not edit. */", '#include "ce_art.h"', '#include "assets.h"', ""]+ c.append("const art_sprite_t art_sprites[ART_NSPRITES] = {")+ for v, off, w, h, packed in sprites:+ c.append(f" {{{off}, {v * 2 + packed}, {w}, {h}}},")+ c.append("};")+ c.append("const char ce_art_vars[CE_ART_NVARS][9] = {" + ", ".join(f'"{x}"' for x in order) + "};")+ c.append("const uint16_t ce_palette[176] = {" + ",".join(str(c1555(p)) for p in PALETTE) + "};")+ open(os.path.join(outdir, "ce_art.c"), "w").write("\n".join(c) + "\n")+ h = ["/* Made by tools/mkart.py: do not edit. */", "#ifndef CE_ART_GEN_H", "#define CE_ART_GEN_H",+ "#include <stdint.h>",+ f"#define CE_ART_NVARS {len(order)}", f"#define CE_PACKED_MAX {maxpacked}",+ f"#define CE_NSTATIC {NSTATIC}", f"#define CE_DYN0 {DYN0}", f"#define CE_SWIRL0 {SWIRL0}",+ f"#define CE_LEVELS {LEVELS}", f"#define CE_BANKS {BANKS}",+ "#define CE_BANK_DARK {" + ",".join(map(str, BANK_DARK)) + "}",+ f"#define CE_WHITE {nearest((255, 255, 255))}",+ f"#define LUT_SHADE {parts['shade']}", f"#define LUT_GREY {parts['grey']}", f"#define LUT_EDLUT {parts['edlut']}",+ f"#define LUT_FCOL {parts['fcol']}", f"#define LUT_TEXT {parts['text']}",+ ] + [f"#define LUT_{name.upper()} {parts[name]}" for name, _ in fonts] + [+ f"#define ED_FRAMES {ED_FRAMES}", f"#define ED_LEVELS {ED_LEVELS}", f"#define ED_CW {ED_CW}",+ f"#define ED_CH {ED_CH}", f"#define ED_DT_MS {int(ED_DT * 1000)}",+ f"#define FL_W {FL_W}", f"#define FL_H {FL_H}", f"#define FL_FRAMES {FL_FRAMES}", f"#define FL_LEVELS {FL_LEVELS}",+ f"#define FL_GC {FL_GC}", f"#define FL_GR {FL_GR}", f"#define FL_ROWS {FL_ROWS}",+ "#define FL_I {" + ",".join(f"{v}f" for v in FL_I) + "}",+ "#define BG_RUN_X 102", "#define BG_RUN_W 218", "#define BG_TITLE_W 160", "#define BG_TITLE_H 120",+ "extern const char ce_art_vars[CE_ART_NVARS][9];", "extern const uint16_t ce_palette[176];", "#endif"]+ open(os.path.join(outdir, "ce_art.h"), "w").write("\n".join(h) + "\n")+ total = sum(len(b) for b in blobs.values())+ print(f"mkart: {n} sprites, {len(order)} art appvars, {total} bytes in all appvars")+++if __name__ == "__main__":+ main()diff --git a/games/balatro/ce/tools/mkpalette.py b/games/balatro/ce/tools/mkpalette.pynew file mode 100644index 00000000..5fcc2d5a--- /dev/null+++ b/games/balatro/ce/tools/mkpalette.py@@ -0,0 +1,103 @@+#!/usr/bin/env python3+"""Makes tools/palette.py, the TI-84 Plus CE's fixed colours (run once; its output is kept in the repository so every+build maps the art the same way). The CE's 8-bit screen has 256 colours: 64 move with the background (src/bg_ce.c),+16 are taken as screens need them (rare interface colours: a boss's own), the other 176 are these: the interface's+colours as they are, then the art's most used colours (k-means over every sprite's pixels, in a perceptual space).+Needs numpy. Usage: mkpalette.py"""+import os+import re+import sys++import numpy as np++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+from artsrc import GAME, Art, to888 # noqa: E402++NSTATIC = 176+++def ui_colours():+ """The interface's colours: HEXC(...) in the NumWorks interface's files and the C_ constants"""+ cols = set()+ for f in ("ui.h", "ui.c", "main.c", "draw.c", "gfx.c"):+ for h in re.findall(r"HEXC\(0x([0-9A-Fa-f]{6})\)", open(os.path.join(GAME, "src", f)).read()):+ cols.add(int(h, 16))+ cols |= {0xFFFFFF, 0x000000}+ out = []+ for c in sorted(cols):+ rgb = (c >> 16 & 0xF8, c >> 8 & 0xF8, c & 0xF8) # as the CE shows it (5 bits a channel)+ if rgb not in out:+ out.append(rgb)+ return out+++def lab(rgb):+ """a cheap perceptual space: weighted RGB with a lightness axis"""+ a = np.asarray(rgb, np.float64) / 255.0+ lin = a ** 2.2+ y = lin @ np.array([0.2126, 0.7152, 0.0722])+ return np.stack([y ** (1 / 3) * 100, (a[..., 0] - a[..., 1]) * 60, (a[..., 1] - a[..., 2]) * 40, (a[..., 0] - a[..., 2]) * 30], -1)+++def main():+ art = Art()+ counts = {}+ for i in range(len(art.table)):+ w, h = art.size(i)+ weight = 1.0 if w * h <= 35 * 47 else 0.25 # the logo: big but seen once+ for row in art.rgb565(i):+ for v in row:+ if v is not None:+ counts[v] = counts.get(v, 0) + weight+ cols = np.array([to888(c) for c in counts], np.float64)+ wts = np.array(list(counts.values()))+ fixed = np.array(ui_colours(), np.float64)+ k = NSTATIC - len(fixed)+ X, F = lab(cols), lab(fixed)+ rng = np.random.default_rng(1)+ # k-means++ seeds, away from the fixed colours+ d = ((X[:, None, :] - F[None, :, :]) ** 2).sum(-1).min(1)+ C = []+ for _ in range(k):+ p = d * wts+ c = X[rng.choice(len(X), p=p / p.sum())]+ C.append(c)+ d = np.minimum(d, ((X - c) ** 2).sum(-1))+ C = np.array(C)+ for it in range(60):+ allc = np.concatenate([F, C])+ lbl = ((X[:, None, :] - allc[None, :, :]) ** 2).sum(-1).argmin(1)+ newc = C.copy()+ for j in range(k):+ m = lbl == len(F) + j+ if m.any():+ newc[j] = (X[m] * wts[m, None]).sum(0) / wts[m].sum()+ if np.allclose(newc, C):+ break+ C = newc+ # back to RGB: the weighted mean of each cluster's colours+ allc = np.concatenate([F, C])+ lbl = ((X[:, None, :] - allc[None, :, :]) ** 2).sum(-1).argmin(1)+ pal = [tuple(int(v) for v in f) for f in fixed]+ for j in range(k):+ m = lbl == len(F) + j+ if not m.any():+ continue+ c = (cols[m] * wts[m, None]).sum(0) / wts[m].sum()+ rgb = tuple(int(round(v)) & 0xF8 for v in c)+ if rgb not in pal:+ pal.append(rgb)+ while len(pal) < NSTATIC:+ pal.append((0, 0, 0))+ with open(os.path.join(HERE, "palette.py"), "w") as f:+ f.write('"""Made by tools/mkpalette.py: the CE\'s 176 fixed colours (the interface\'s, then the art\'s)."""\n')+ f.write(f"NFIXED_UI = {len(fixed)}\nPALETTE = [\n")+ for i in range(0, len(pal), 6):+ f.write(" " + ", ".join(f"({r}, {g}, {b})" for r, g, b in pal[i:i + 6]) + ",\n")+ f.write("]\n")+ print(f"palette: {len(fixed)} interface colours, {len(pal) - len(fixed)} for the art")+++if __name__ == "__main__":+ main()diff --git a/games/balatro/ce/tools/palette.py b/games/balatro/ce/tools/palette.pynew file mode 100644index 00000000..e6d723ec--- /dev/null+++ b/games/balatro/ce/tools/palette.py@@ -0,0 +1,34 @@+"""Made by tools/mkpalette.py: the CE's 176 fixed colours (the interface's, then the art's)."""+NFIXED_UI = 44+PALETTE = [+ (0, 0, 0), (0, 152, 248), (8, 24, 24), (16, 168, 200), (24, 32, 32), (24, 32, 40),+ (24, 40, 40), (32, 88, 80), (40, 40, 40), (40, 56, 56), (48, 64, 64), (56, 64, 72),+ (56, 72, 72), (56, 80, 80), (56, 64, 104), (64, 128, 248), (72, 192, 144), (72, 168, 144),+ (72, 96, 96), (88, 112, 112), (96, 96, 96), (104, 120, 128), (120, 40, 40), (120, 136, 144),+ (136, 96, 160), (136, 136, 136), (136, 56, 48), (152, 168, 168), (160, 128, 208), (176, 104, 184),+ (184, 184, 184), (200, 224, 232), (216, 216, 216), (216, 224, 224), (232, 232, 232), (232, 192, 88),+ (240, 48, 96), (240, 104, 56), (240, 184, 88), (248, 104, 40), (248, 160, 0), (248, 88, 80),+ (248, 152, 0), (248, 248, 248), (232, 232, 168), (184, 112, 48), (96, 184, 240), (80, 128, 168),+ (248, 168, 168), (248, 224, 16), (72, 168, 168), (128, 112, 80), (160, 160, 136), (184, 192, 208),+ (216, 192, 144), (128, 200, 208), (248, 128, 128), (224, 96, 88), (240, 208, 152), (104, 112, 192),+ (176, 208, 232), (240, 232, 208), (56, 120, 136), (176, 88, 96), (144, 72, 224), (24, 144, 200),+ (192, 152, 88), (184, 48, 48), (136, 80, 120), (96, 192, 184), (112, 176, 184), (112, 160, 160),+ (232, 56, 56), (112, 144, 216), (216, 184, 120), (232, 144, 144), (152, 168, 208), (128, 184, 136),+ (136, 152, 176), (160, 112, 40), (160, 176, 176), (72, 88, 120), (128, 160, 120), (168, 136, 64),+ (176, 144, 232), (248, 208, 112), (96, 128, 208), (216, 216, 128), (112, 160, 192), (152, 160, 184),+ (144, 168, 176), (152, 200, 200), (208, 72, 88), (152, 120, 80), (216, 240, 248), (72, 64, 184),+ (88, 112, 144), (200, 80, 40), (72, 152, 112), (40, 128, 144), (232, 248, 248), (232, 192, 160),+ (208, 136, 56), (152, 128, 104), (152, 224, 208), (160, 112, 152), (240, 208, 200), (224, 216, 232),+ (248, 240, 120), (32, 112, 160), (104, 144, 144), (88, 104, 48), (128, 184, 176), (248, 224, 176),+ (184, 88, 8), (88, 152, 168), (208, 216, 232), (120, 200, 232), (32, 144, 168), (112, 104, 240),+ (16, 200, 248), (56, 80, 168), (128, 120, 160), (152, 176, 136), (120, 136, 152), (192, 136, 128),+ (96, 64, 72), (232, 144, 88), (176, 160, 144), (152, 184, 208), (152, 160, 128), (232, 240, 248),+ (208, 160, 168), (96, 128, 128), (240, 184, 104), (200, 128, 176), (248, 240, 232), (240, 216, 224),+ (200, 176, 160), (80, 120, 104), (24, 120, 80), (200, 160, 240), (144, 144, 112), (184, 136, 24),+ (176, 160, 176), (168, 96, 240), (80, 136, 128), (176, 152, 96), (112, 144, 128), (208, 80, 64),+ (184, 192, 136), (208, 200, 168), (240, 136, 56), (240, 216, 176), (168, 160, 224), (48, 168, 240),+ (88, 104, 168), (144, 200, 232), (200, 168, 104), (168, 56, 48), (224, 232, 248), (136, 88, 72),+ (144, 112, 32), (128, 104, 168), (240, 160, 40), (120, 136, 176), (120, 144, 112), (240, 192, 184),+ (208, 176, 88), (192, 208, 224), (72, 120, 128), (168, 192, 208), (224, 160, 152), (0, 0, 0),+ (0, 0, 0), (0, 0, 0),+]diff --git a/games/balatro/ce/tools/place.py b/games/balatro/ce/tools/place.pynew file mode 100644index 00000000..49ff4593--- /dev/null+++ b/games/balatro/ce/tools/place.py@@ -0,0 +1,53 @@+#!/usr/bin/env python3+"""Where Balatro's code goes on the TI-84 Plus CE (see ce.ld): the functions and constant data of the linked object,+biggest first, into the places outside the program where they fit (the screen memory's second half, the pixel+shadow, the room after the static data); the rest stays in the program. Writes gen/place.ld, which ce.ld includes.++Usage: place.py OBJDUMP obj/BALATRO.o gen/place.ld"""+import re+import subprocess+import sys++BSS_LOW, BSS_HIGH = 0xD052C6, 0xD13FD8+VRAM = 0x12C00 # 0xD52C00..0xD657FF+PSHADOW = 8400 # 0xD031F6..0xD052C6+KEEP = re.compile(r"^\.(text|rodata)\.boot|^\.text$|^\.text\.__") # the loader's, the library's: in the program+++def main():+ objdump, obj, out = sys.argv[1:4]+ txt = subprocess.run([objdump, "-h", obj], capture_output=True, text=True, check=True).stdout+ secs, bss = [], 0+ for m in re.finditer(r"^\s*\d+\s+(\S+)\s+([0-9a-f]+)\s", txt, re.M):+ name, size = m.group(1), int(m.group(2), 16)+ if name.startswith((".bss", "COMMON")):+ bss += size+ elif name.startswith((".text", ".rodata")) and size and not KEEP.match(name):+ secs.append((size, name))+ bss_size = (bss + 64 + 255) & ~255+ bins = [["vram", VRAM, []], ["pshadow", PSHADOW, []], ["bssx", BSS_HIGH - BSS_LOW - bss_size, []]]+ left = 0+ for size, name in sorted(secs, reverse=True):+ for b in bins:+ if size <= b[1]:+ b[1] -= size+ b[2].append(name)+ break+ else:+ left += size+ with open(out, "w") as f:+ f.write("/* Made by tools/place.py: do not edit. */\n")+ f.write(f"BSS_SIZE = {bss_size:#x};\n")+ for name, room, names in bins:+ f.write(f"/* {name}: {room} bytes left */\n")+ for name, _, names in bins:+ with open(out[:-3] + "_" + name + ".ld", "w") as g:+ g.write("".join(f" *({n})\n" for n in sorted(names)))+ used = {b[0]: (VRAM if b[0] == "vram" else PSHADOW if b[0] == "pshadow" else BSS_HIGH - BSS_LOW - bss_size) - b[1]+ for b in bins}+ print(f"place: static data {bss_size}; code in the screen's half {used['vram']}, the pixel shadow "+ f"{used['pshadow']}, after the data {used['bssx']}; in the program {left} (and the loader's, the library's)")+++if __name__ == "__main__":+ main()