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
PolyTrack: the screens, the race, saves and ghosts
Mason3632c17005f777d
diff --git a/games/polytrack/Makefile b/games/polytrack/Makefileindex 2ce2d278..e76533b4 100644--- a/games/polytrack/Makefile+++ b/games/polytrack/Makefile@@ -1,22 +1,32 @@-# PolyGT 3D on the NumWorks calculator.-# make output/polygt3d.nwa-# make check link it like the calculator does (output/polygt3d.bin), within the RAM and the app space+# PolyTrack on the NumWorks calculator.+# make output/polytrack.nwa+# make check link it like the calculator does (output/polytrack.bin), within the RAM and the app space# make host build/play: the game on a computer, for tests and pictures-# make test the roads, laps, physics, crashes, the rivals finishing every circuit at every level, a race-# driven to the finish, the endless road, saves (kept, damaged, storage full), random keys and the-# same race to the same hash on every computer (with the sanitizers)+# make test every official track driven to the finish, the checkpoints, respawns and restarts, the physics,+# saves (kept, damaged, storage full), random keys and the same runs to the same hashes on every+# computer (with the sanitizers)+# make data src/data.bin, src/data.c and src/data.h from PolyTrack's web build+# (POLYTRACK_WEB=its folder; Python with numpy, DracoPy and Pillow)Q ?= @-CC = arm-none-eabi-gcc+# the ARM toolchain on the PATH, or in TOOLCHAIN=<its bin folder>+TOOLCHAIN ?=+BIN = $(if $(TOOLCHAIN),$(TOOLCHAIN)/)+CC = $(BIN)arm-none-eabi-gcc+STRIP ?= $(BIN)arm-none-eabi-strip --strip-unneededNWLINK ?= npx --yes -- [email protected]BUILD_DIR = outputL = ../../launcher/src+POLYTRACK_WEB ?= $(HOME)/Documents/Assets/gamesrc/polytrack/web+PYTHON ?= python3-SRC = src/main.c src/track.c src/race.c src/save.c src/render.c src/draw.c src/plat_eadk.c \- $(L)/gfx.c $(L)/font_data.c $(L)/xfont.c+# the physics and the picture run every frame at -O2; the screens are small at -Os+HOT = src/car.c src/world.c src/ptmath.c src/render.c+COLD = src/main.c src/draw.c src/save.c src/ghost.c src/data.c $(L)/gfx.c $(L)/font_data.c $(L)/xfont.c+COLD_OBJ = $(patsubst %.c,$(BUILD_DIR)/cold/%.o,$(notdir $(COLD)))HEADERS = $(wildcard src/*.h) $(L)/gfx.h $(L)/font.h $(L)/np.h ../common/epsilon_app.h ../common/epsilon_files.hCFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DPLATFORM_DEVICE=1 -DEPSILON_XL=1 -I$(L) -Isrc-CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant -ffp-contract=off+CFLAGS += -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant -ffp-contract=offCFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internalCFLAGS += -ffunction-sections -fdata-sectionsLDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs@@ -28,19 +38,30 @@ LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-relRAM = 133652APP_SPACE = 2031616-.PHONY: build check clean host test-build: $(BUILD_DIR)/polygt3d.nwa+.PHONY: build check clean host test data+build: $(BUILD_DIR)/polytrack.nwa-check: $(BUILD_DIR)/polygt3d.nwa- $(Q) $(NWLINK) nwa-bin --ram-length $(RAM) $< $(BUILD_DIR)/polygt3d.bin- $(Q) n=$$(wc -c < $(BUILD_DIR)/polygt3d.bin); [ $$n -le $(APP_SPACE) ] || \- { echo "polygt3d.nwa is bigger than the calculator's app space ($(APP_SPACE) bytes)"; exit 1; }; \- echo "BIN $(BUILD_DIR)/polygt3d.bin: $$n bytes, RAM within $(RAM) bytes"+check: $(BUILD_DIR)/polytrack.nwa+ $(Q) $(NWLINK) nwa-bin --ram-length $(RAM) $< $(BUILD_DIR)/polytrack.bin+ $(Q) n=$$(wc -c < $(BUILD_DIR)/polytrack.bin); [ $$n -le $(APP_SPACE) ] || \+ { echo "polytrack.nwa is bigger than the calculator's app space ($(APP_SPACE) bytes)"; exit 1; }; \+ echo "BIN $(BUILD_DIR)/polytrack.bin: $$n bytes, $$(( $(APP_SPACE) - n )) to spare, RAM within $(RAM) bytes"-$(BUILD_DIR)/polygt3d.nwa: $(SRC) $(HEADERS) $(BUILD_DIR)/icon.o+$(BUILD_DIR)/data.o: src/data.S src/data.bin | $(BUILD_DIR)+ $(Q) $(CC) -c -DDATA_BIN='"src/data.bin"' $< -o $@++$(BUILD_DIR)/cold/%.o: src/%.c $(HEADERS) | $(BUILD_DIR)+ @mkdir -p $(@D)+ $(Q) $(CC) $(CFLAGS) -Os -c $< -o $@+$(BUILD_DIR)/cold/%.o: $(L)/%.c $(HEADERS) | $(BUILD_DIR)+ @mkdir -p $(@D)+ $(Q) $(CC) $(CFLAGS) -Os -c $< -o $@++$(BUILD_DIR)/polytrack.nwa: $(HOT) src/plat_eadk.c $(COLD_OBJ) $(HEADERS) $(BUILD_DIR)/icon.o $(BUILD_DIR)/data.o@echo "LD $@"- $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(SRC) $(BUILD_DIR)/icon.o -lm -o $@- $(Q) arm-none-eabi-strip --strip-unneeded $@+ $(Q) $(CC) $(CFLAGS) -O2 $(LDFLAGS) $(HOT) src/plat_eadk.c $(COLD_OBJ) $(BUILD_DIR)/data.o $(BUILD_DIR)/icon.o \+ -lm -o $@+ $(Q) $(STRIP) $@$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)@echo "ICON $<"@@ -49,14 +70,21 @@ $(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)$(BUILD_DIR):$(Q) mkdir -p $@-# on a computer: tests/play.c drives races and the whole app, and saves pictures-HOST_SRC = tests/play.c src/track.c src/race.c src/save.c src/render.c src/draw.c $(L)/gfx.c $(L)/font_data.c \- $(L)/xfont.c+data:+ $(PYTHON) tools/pack.py $(POLYTRACK_WEB)++# on a computer: tests/play.c drives the tracks and the whole app, and saves pictures+HOST_SRC = tests/play.c src/car.c src/world.c src/ptmath.c src/render.c src/draw.c src/save.c src/ghost.c src/data.c \+ $(L)/gfx.c $(L)/font_data.c $(L)/xfont.cHOST_FLAGS = -std=gnu11 -O2 -g -Wall -Wextra -Wno-unused-parameter -ffp-contract=off -Isrc -I$(L) -DHOSThost: build/play-build/play: $(HOST_SRC) src/main.c $(wildcard src/*.h)+build/data.o: src/data.S src/data.bin+ $(Q) mkdir -p build+ $(Q) cc -c -DDATA_BIN='"src/data.bin"' $< -o $@+build/play: $(HOST_SRC) src/main.c $(wildcard src/*.h) build/data.o$(Q) mkdir -p build- $(Q) cc $(HOST_FLAGS) -fsanitize=address,undefined -fno-sanitize-recover=undefined $(HOST_SRC) -lm -o $@+ $(Q) cc $(HOST_FLAGS) -fsanitize=address,undefined -fno-sanitize-recover=undefined $(HOST_SRC) build/data.o -lm \+ -o $@@echo "HOST $@"test: build/playbuild/play test builddiff --git a/games/polytrack/output_prof/cold/data.o b/games/polytrack/output_prof/cold/data.onew file mode 100644index 00000000..acec28e6Binary files /dev/null and b/games/polytrack/output_prof/cold/data.o differdiff --git a/games/polytrack/output_prof/cold/draw.o b/games/polytrack/output_prof/cold/draw.onew file mode 100644index 00000000..81accc1fBinary files /dev/null and b/games/polytrack/output_prof/cold/draw.o differdiff --git a/games/polytrack/output_prof/cold/font_data.o b/games/polytrack/output_prof/cold/font_data.onew file mode 100644index 00000000..4afcb258Binary files /dev/null and b/games/polytrack/output_prof/cold/font_data.o differdiff --git a/games/polytrack/output_prof/cold/gfx.o b/games/polytrack/output_prof/cold/gfx.onew file mode 100644index 00000000..008f0a34Binary files /dev/null and b/games/polytrack/output_prof/cold/gfx.o differdiff --git a/games/polytrack/output_prof/cold/ghost.o b/games/polytrack/output_prof/cold/ghost.onew file mode 100644index 00000000..2655cb64Binary files /dev/null and b/games/polytrack/output_prof/cold/ghost.o differdiff --git a/games/polytrack/output_prof/cold/main.o b/games/polytrack/output_prof/cold/main.onew file mode 100644index 00000000..ad471919Binary files /dev/null and b/games/polytrack/output_prof/cold/main.o differdiff --git a/games/polytrack/output_prof/cold/save.o b/games/polytrack/output_prof/cold/save.onew file mode 100644index 00000000..fd0b8025Binary files /dev/null and b/games/polytrack/output_prof/cold/save.o differdiff --git a/games/polytrack/output_prof/cold/xfont.o b/games/polytrack/output_prof/cold/xfont.onew file mode 100644index 00000000..97958e34Binary files /dev/null and b/games/polytrack/output_prof/cold/xfont.o differdiff --git a/games/polytrack/output_prof/data.o b/games/polytrack/output_prof/data.onew file mode 100644index 00000000..367b2196Binary files /dev/null and b/games/polytrack/output_prof/data.o differdiff --git a/games/polytrack/output_prof/icon.o b/games/polytrack/output_prof/icon.onew file mode 100644index 00000000..6d5dfe94Binary files /dev/null and b/games/polytrack/output_prof/icon.o differdiff --git a/games/polytrack/output_prof/polytrack.nwa b/games/polytrack/output_prof/polytrack.nwanew file mode 100644index 00000000..589041e5Binary files /dev/null and b/games/polytrack/output_prof/polytrack.nwa differdiff --git a/games/polytrack/src/draw.c b/games/polytrack/src/draw.cindex d117c47d..ebef8fd5 100644--- a/games/polytrack/src/draw.c+++ b/games/polytrack/src/draw.c@@ -1,35 +1,36 @@-/* PolyGT 3D's screens: the title over a car on a turntable, the race screen, how to play and the records; the race's- * dials; the pause, results and questions over the race. Each has a line of plain keys at the bottom. */+/* PolyTrack's screens (draw.h), in its colours: dark blue slanted boxes (#28346a, #212b58, #192042), white text,+ * green and red for the time against the record. The title and the menus sit over the track in 3D. */#include <string.h>#include "../../../launcher/src/gfx.h"+#include "data.h"#include "draw.h"+#include "plat.h"+#include "world.h"#define WHITE 0xFFFF-#define INK HEX(0x0E0B24)-#define PANEL HEX(0x1C1745)-#define LINE HEX(0x3B3478)-#define CYAN HEX(0x00C3EB)-#define SUN HEX(0xEB6E50)-#define GOLD HEX(0xFFD052)-#define MUTED HEX(0xB2ADD6)-#define DIM HEX(0x6A6496)-#define RED HEX(0xFF5A4E)+#define SURFACE HEX(0x28346A)+#define SURFACE2 HEX(0x212B58)+#define SURFACE3 HEX(0x192042)+#define BUTTON HEX(0x112052)+#define HOVER HEX(0x334B77)+#define LAVENDER HEX(0xB3C1FF)+#define MUTED HEX(0xA9B3DE)+#define DIM HEX(0x5D6A7C)+#define GREEN HEX(0x55FF55)+#define RED HEX(0xFF5555)+#define YELLOW HEX(0xE2C026)#define STRIP 24-/* the launcher's drawing (gfx.c) sends strips here when asked; this game sends its own */void plat_push(int x, int y, int w, int h, const uint16_t *px);void np_push(int x, int y, int w, int h, const color_t *px) { plat_push(x, y, w, h, px); }static color_t strip[SCREEN_W * STRIP];-const char *const pg_driver[PG_CARS] = {"You", "Aiko", "Bruno", "Dara", "Emil", "Farah", "Goro", "Hana"};-static const char *const MODES[2] = {"Circuit race", "Endless road"};-static const char *const LEVELS[3] = {"Easy", "Normal", "Hard"};-static const char *const VIEW_NAMES[VIEWS] = {"Behind", "Far behind", "Bumper"};+const char *const pt_env_name[3] = {"Summer", "Winter", "Desert"};+static const char *const PAINT_NAMES[PT_PAINTS] = {"Red", "Blue", "Green", "Purple", "Orange", "Teal", "Black", "Silver"};-static const pg_file *F;-static const pg_track *T;-static const pg_race *R;-static const pg_ui *U;+static const pt_file *F;+static const car_t *CAR;+static const pt_ui *U;/* ------------------------------------------------------------------ text */static char *cat(char *p, const char *s) {@@ -45,20 +46,19 @@ static char *num(char *p, uint32_t v) {*p = 0;return p;}+/* PolyTrack's clock: 00:00.000 */static char *clock_of(char *p, uint32_t ms) {- p = num(p, ms / 60000);- *p++ = ':', *p++ = (char)('0' + ms / 10000 % 6), *p++ = (char)('0' + ms / 1000 % 10), *p++ = '.';- *p++ = (char)('0' + ms / 100 % 10), *p++ = (char)('0' + ms / 10 % 10), *p = 0;+ uint32_t m = ms / 60000;+ if (m > 99) m = 99;+ *p++ = (char)('0' + m / 10), *p++ = (char)('0' + m % 10), *p++ = ':';+ *p++ = (char)('0' + ms / 10000 % 6), *p++ = (char)('0' + ms / 1000 % 10), *p++ = '.';+ *p++ = (char)('0' + ms / 100 % 10), *p++ = (char)('0' + ms / 10 % 10), *p++ = (char)('0' + ms % 10);+ *p = 0;return p;}-static char *ordinal(char *p, int n) {- p = num(p, (uint32_t)n);- return cat(p, n == 1 ? "st" : n == 2 ? "nd" : n == 3 ? "rd" : "th");-}-static char *km(char *p, uint32_t m) {- p = num(p, m / 1000);- *p++ = '.', *p++ = (char)('0' + m / 100 % 10);- return cat(p, " km");+static char *diff_of(char *p, int32_t d) {+ *p++ = d < 0 ? '-' : '+';+ return clock_of(p, (uint32_t)(d < 0 ? -d : d));}static void text(const np_font_t *f, int x, int y, const char *s, color_t c) { gfx_text(f, x, y, s, c, 256); }@@ -66,7 +66,19 @@ static void center(const np_font_t *f, int x, int y, const char *s, color_t c) {static void right(const np_font_t *f, int x, int y, const char *s, color_t c) { gfx_text_right(f, x, y, s, c, 256); }/* ------------------------------------------------------------------ pieces */-/* a line of keys: "Up Down=choose|OK=open", each key in cyan, what it does after it */+/* PolyTrack's box: a parallelogram, its sides slanted by `s` pixels (s < 0 slants the other way) */+static void slant(int x, int y, int w, int h, int s, color_t c, int a) {+ int as = s < 0 ? -s : s, aw = w - as, d = h > 1 ? h - 1 : 1;+ int ya = y > gfx_y0 ? y : gfx_y0, yb = y + h < gfx_y1 ? y + h : gfx_y1;+ for (int y1 = ya; y1 < yb; y1++) {+ int j = y1 - y;+ int o = s >= 0 ? s * (h - 1 - j) / d : as * j / d;+ if (a >= 256) gfx_fill(x + o, y1, aw, 1, c);+ else gfx_fill_alpha(x + o, y1, aw, 1, c, a);+ }+}++/* a line of keys: "Up=gas|Down=brake", each key in lavender, what it does after it in white */static void key_line(int y, const char *s) {char buf[48];int w = 0;@@ -80,520 +92,361 @@ static void key_line(int y, const char *s) {memcpy(buf, q, (size_t)k), buf[k] = 0;bool key = q[k] == '=';int tw = gfx_text_width(&np_font_small, buf);- if (pass) text(&np_font_small, x + w, y, buf, key ? CYAN : MUTED);- w += tw + (key ? 4 : 0);+ if (pass) text(&np_font_small, x + w, y, buf, key ? LAVENDER : WHITE);+ w += tw + (key ? 3 : 0);q += k;if (*q == '=') q++;- else if (*q == '|') q++, w += 11;+ else if (*q == '|') q++, w += 9;}}}static void keys(const char *s) {- gfx_fill(0, 222, 320, 18, INK);- gfx_fill(0, 222, 320, 1, LINE);- key_line(235, s);+ gfx_fill(0, 226, 320, 14, SURFACE3);+ key_line(236, s);}static void page(const char *title) {- gfx_vgrad(0, 0, 320, 222, 0x120E30, 0x2A1F55);- text(&np_font_title, 14, 30, title, WHITE);+ gfx_vgrad(0, 0, 320, 240, 0x28346A, 0x151B3C);+ slant(-8, 10, 200, 28, 8, SURFACE3, 256);+ text(&np_font_title, 12, 31, title, WHITE);}-/* a button: the chosen one bright and framed */+/* a button: PolyTrack's dark slanted box, the chosen one lighter with a lavender edge */static void button(int x, int y, int w, const char *s, bool on) {- if (on) {- gfx_rrect(x - 2, y - 2, w + 4, 30, 8, WHITE, 256);- gfx_rrect(x, y, w, 26, 6, CYAN, 256);- } else {- gfx_rrect(x, y, w, 26, 6, PANEL, 235);- gfx_rrect_outline(x, y, w, 26, 6, 1, LINE, 256);- }- center(&np_font_body, x + w / 2, y + 18, s, on ? INK : WHITE);+ if (on) slant(x - 2, y - 2, w + 4, 28, 8, LAVENDER, 256);+ slant(x, y, w, 24, 7, on ? HOVER : BUTTON, on ? 256 : 235);+ center(&np_font_body, x + w / 2 + 2, y + 17, s, WHITE);}-static void dim(void) { gfx_fill_alpha(0, 0, 320, 240, HEX(0x05040F), 150); }+static void dim(void) { gfx_fill_alpha(0, 0, 320, 240, HEX(0x05081A), 140); }-/* when the calculator's storage is full, say so above the keys */-static void not_saved(void) {+static void not_saved(int y) {if (!U->save_failed) return;- gfx_rrect(40, 202, 240, 17, 5, HEX(0x5A1E1A), 240);- center(&np_font_small, 160, 214, "Storage full: progress not saved", WHITE);+ slant(40, y, 240, 17, 6, HEX(0x5A1E1A), 240);+ center(&np_font_small, 162, y + 12, "Storage full: progress not saved", WHITE);}-static void bar(int x, int y, int w, int h, int v, int max, color_t c) {- gfx_rrect(x, y, w, h, h / 2, HEX(0x2A2456), 256);- int f = v * w / max;- if (f > 0) gfx_rrect(x, y, f < h ? h : f, h, h / 2, c, 256);-}--/* "POLYGT 3D", twice the title font, slanted, with a shadow */-static void logo(int x0, int y) {+/* PolyTrack's name: its logo's letters (pale lavender, a dark blue edge), leaning like the logo */+static void logo(int x0, int y, int scale) {const np_font_t *f = &np_font_title;- const char *s = "POLYGT 3D";+ const char *s = "PolyTrack";for (int pass = 0; pass < 2; pass++) {- int x = x0 + (pass ? 0 : 2), base = y + (pass ? 0 : 2);+ int x = x0;for (const char *q = s; *q; q++) {const np_glyph_t *g = &f->glyphs[(uint8_t)*q - f->first];const uint8_t *m = f->data + g->offset;- color_t c = pass ? (q >= s + 7 ? SUN : WHITE) : HEX(0x0A0820);for (int gy = 0; gy < g->h; gy++) {- int yy = base + (g->y + gy) * 2;- if (yy + 2 <= gfx_y0 || yy >= gfx_y1) continue;+ int yy = y + (g->y + gy) * scale;+ if (yy + scale + 2 <= gfx_y0 || yy - 2 >= gfx_y1) continue;+ int lean = (g->h - gy) * scale / 5;for (int gx = 0; gx < g->w; gx++) {int k = gy * g->w + gx, cov = (m[k / 2] >> ((k & 1) * 4)) & 15;- int lean = (g->h - gy) / 3;- if (cov) gfx_fill_alpha(x + (g->x + gx) * 2 + lean, yy, 2, 2, c, cov * 17);+ if (cov < 6) continue;+ int px = x + (g->x + gx) * scale + lean;+ if (pass == 0) gfx_fill(px - 2, yy - 2, scale + 4, scale + 4, BUTTON);+ else gfx_fill(px, yy, scale, scale, LAVENDER);}}- x += g->advance * 2;+ x += g->advance * scale;}}}-/* a circuit's outline: a soft edge, a light line, the start line */-static int16_t map_x[64], map_y[64];-static int map_of = -1;-static void map_setup(const pg_track *t, int w, int h) {- int key = t->id * 1000 + w * 10 + h;- if (map_of == key) return;- pg_map(t, 64, map_x, map_y, w, h);- map_of = key;-}-static void outline(int x, int y) {- for (int pass = 0; pass < 2; pass++)- for (int i = 0; i < 64; i++) {- int j = (i + 1) % 64, x0 = x + map_x[i], y0 = y + map_y[i], x1 = x + map_x[j], y1 = y + map_y[j];- int n = NP_MAX(NP_MAX(x1 - x0, x0 - x1), NP_MAX(y1 - y0, y0 - y1));- for (int k = 0; k <= n; k++) {- int px = x0 + (n ? (x1 - x0) * k / n : 0), py = y0 + (n ? (y1 - y0) * k / n : 0);- if (pass) gfx_fill(px, py, 1, 1, HEX(0xE6E4F2));- else gfx_fill(px - 1, py - 1, 3, 3, HEX(0x6E68A0));- }+/* a track's map (createThumbnail): a square a part, the start blue, checkpoints yellow, the finish red */+static void track_map(int track, int cx, int cy, int maxw, int maxh) {+ const pt_track *t = &pt_tracks[track];+ int s = maxw / t->tw;+ if (maxh / t->th < s) s = maxh / t->th;+ if (s < 1) s = 1;+ if (s > 6) s = 6;+ int w = t->tw * s, h = t->th * s;+ int x0 = cx - w / 2, y0 = cy - h / 2;+ static const uint32_t ENVC[3] = {0xFFFFFF, 0xBED8F7, 0xEDE2AF};+ color_t pal[5] = {0, HEX(ENVC[t->env]), HEX(0xE2C026), HEX(0x338CE0), HEX(0xD12929)};+ for (int j = 0; j < t->th; j++) {+ int yy = y0 + j * s;+ if (yy + s <= gfx_y0 || yy >= gfx_y1) continue;+ for (int i = 0; i < t->tw; i++) {+ int k = j * t->tw + i;+ int v = (pt_thumbs[t->thumb + k / 2] >> ((k & 1) * 4)) & 15;+ if (v) gfx_fill(x0 + i * s, yy, s, s, pal[v < 5 ? v : 1]);}- gfx_fill(x + map_x[0] - 1, y + map_y[0] - 3, 3, 6, WHITE);+ }}-/* where a distance is on the outline */-static void map_at(int32_t s, int *px, int *py) {- int32_t L = T->length, m = s % L;- if (m < 0) m += L;- int64_t f = (int64_t)m * 64 / L;- int i = (int)f, j = (i + 1) % 64;- int32_t frac = (int32_t)((int64_t)m * 64 % L * 256 / L);- *px = map_x[i] + (map_x[j] - map_x[i]) * frac / 256;- *py = map_y[i] + (map_y[j] - map_y[i]) * frac / 256;++/* ------------------------------------------------------------------ the race */+static const char *start_keys(void) { return "Up=start driving|Left Right=steer|Back=pause"; }++static void time_box(int x, int y, int w, int slope, const char *title, const char *t, color_t tc, bool big) {+ slant(x, y + 13, w, big ? 22 : 18, slope, SURFACE3, 256);+ if (title[0]) center(&np_font_small, x + w / 2, y + 10, title, WHITE);+ center(big ? &np_font_body : &np_font_small, x + w / 2, y + (big ? 30 : 27), t, tc);}-/* ------------------------------------------------------------------ the race's dials */static void hud(void) {- const pg_race *r = R;- char s[40], *p;- bool endless = r->mode == MODE_ENDLESS;- gfx_rrect(6, 6, 98, 40, 6, INK, 215);- if (endless) {- text(&np_font_small, 14, 19, "TIME", MUTED);- text(&np_font_small, 62, 19, "ZONE", MUTED);- uint32_t left = (uint32_t)r->time_left;- num(s, (left + 999) / 1000);- text(&np_font_title, 14, 40, s, left < 10000 && ((U->clock / 250) & 1) ? RED : WHITE);- num(s, (uint32_t)r->zone + 1);- text(&np_font_body, 62, 40, s, WHITE);- } else {- text(&np_font_small, 14, 19, "POS", MUTED);- text(&np_font_small, 62, 19, "LAP", MUTED);- num(s, (uint32_t)pg_rank(r, 0));- int w = gfx_text(&np_font_title, 14, 40, s, WHITE, 256);- p = cat(s, "/");- num(p, (uint32_t)r->rivals + 1);- text(&np_font_body, 14 + w + 1, 40, s, MUTED);- p = num(s, r->lap);- p = cat(p, "/");- num(p, r->laps);- text(&np_font_body, 62, 40, s, WHITE);+ const car_t *c = CAR;+ char s[40], s2[40], s3[40];+ int track = F->p.track;+ uint32_t best = F->p.best[track];+ int n = car_checkpoints();+ /* top left: the checkpoints collected */+ slant(-8, 4, 74, 20, 6, SURFACE, 220);+ gfx_fill(6, 9, 2, 11, WHITE);+ gfx_fill(8, 9, 7, 6, YELLOW);+ char *p = num(s, c->next_cp);+ p = cat(p, "/");+ num(p, (uint32_t)n);+ text(&np_font_body, 20, 19, s, WHITE);+ /* top right: the speed */+ slant(244, 4, 84, 20, -6, SURFACE, 220);+ float k = c->speed < 0.0f ? -c->speed : c->speed;+ num(s, (uint32_t)(k + 0.5f));+ right(&np_font_body, 286, 19, s, WHITE);+ text(&np_font_small, 289, 18, "km/h", MUTED);+ /* bottom: record, current, difference (at a checkpoint: their times there, a few seconds) */+ uint32_t cur = c->finish ? c->finish : c->frames;+ bool split = U->split_at && U->clock - U->split_at < 3500 && !c->finish;+ if (best) clock_of(s, split && U->split_cp < PT_SPLITS ? F->p.split[track][U->split_cp] : best);+ else cat(s, "- - -");+ clock_of(s2, split ? c->cp_frames[U->split_cp < 64 ? U->split_cp : 0] : cur);+ color_t dc = WHITE;+ s3[0] = 0;+ if (split && U->split_diff != 0x7FFFFFFF) diff_of(s3, U->split_diff), dc = U->split_diff < 0 ? GREEN : RED;+ else if (c->finish && best && U->finish_at) {+ int32_t d = U->new_record ? U->finish_diff : (int32_t)c->finish - (int32_t)best;+ if (d || !U->new_record) diff_of(s3, d), dc = d < 0 ? GREEN : RED;}- /* the clock, or the distance */- gfx_rrect(112, 6, 96, 40, 6, INK, 215);- if (endless) {- km(s, (uint32_t)(r->car[0].s / FX));- center(&np_font_body, 160, 23, s, WHITE);- if (F->p.best_m) {- p = cat(s, "Best ");- km(p, F->p.best_m);- center(&np_font_small, 160, 38, s, MUTED);- } else {- center(&np_font_small, 160, 38, pg_zone_name[(pg_zone_at(T, r->car[0].s) - 3) % 5], MUTED);- }- } else {- clock_of(s, r->time_ms);- center(&np_font_body, 160, 23, s, WHITE);- uint32_t best = r->best_lap_ms;- if (best) {- clock_of(cat(s, "Best lap "), best);- center(&np_font_small, 160, 38, s, MUTED);- } else {- center(&np_font_small, 160, 38, pg_circuit_name[r->track], MUTED);- }+ if (!s3[0]) cat(s3, "- - -");+ time_box(6, 186, 94, 6, "Record", s, WHITE, false);+ time_box(104, 182, 112, 0, "Current", s2, split ? WHITE : WHITE, true);+ time_box(220, 186, 94, -6, "Difference", s3, dc, false);+ /* PolyTrack's hints */+ const char *h1 = NULL, *h2 = NULL;+ if (!U->started) {+ h1 = "Use the arrows to start driving.";+ h2 = U->has_ghost ? "The ghost is your best run." : NULL;+ } else if (c->finish) {+ h1 = U->new_record ? "New record!" : "Finished!";+ h2 = "Backspace: try again and improve your time.";+ } else if (c->next_cp == 0 && c->frames < 8000) {+ h1 = "Reach the first checkpoint!";+ h2 = "Checkpoints have a yellow banner.";+ } else if (U->still_ms > 2500) {+ h1 = c->has_respawn ? "OK: back to the last checkpoint." : "OK: back to the start.";+ h2 = "Backspace: start over.";}- /* the map */- if (!endless) {- map_setup(T, 70, 50);- gfx_rrect(232, 6, 82, 62, 6, INK, 200);- outline(238, 12);- int sx, sy;- for (int i = r->rivals; i >= 1; i--) {- map_at(r->car[i].s, &sx, &sy);- gfx_circle(238 + sx, 12 + sy, 2, rd_rgb(rd_paint[r->car[i].paint & 7]), 256);- }- map_at(r->car[0].s, &sx, &sy);- gfx_circle(238 + sx, 12 + sy, 4, WHITE, 256);- gfx_circle(238 + sx, 12 + sy, 3, SUN, 256);- }- /* speed | gear | nitro, then the keys */- const pg_car *c = &r->car[0];- gfx_fill_alpha(0, 202, 320, 25, INK, 230);- gfx_fill(0, 202, 320, 1, LINE);- gfx_fill(0, 227, 320, 13, HEX(0x08061A));- gfx_fill(92, 207, 1, 16, LINE), gfx_fill(140, 207, 1, 16, LINE);- num(s, (uint32_t)pg_kmh(c->v));- right(&np_font_title, 56, 224, s, c->boost ? CYAN : WHITE);- text(&np_font_small, 60, 224, "km/h", MUTED);- text(&np_font_small, 99, 213, "GEAR", MUTED);- s[0] = (char)('0' + c->gear), s[1] = 0;- bool red = pg_rpm(r) > pg_vehicles[c->model].redline - 350;- text(&np_font_body, 100, 225, s, red && r->manual ? RED : r->manual ? GOLD : WHITE);- text(&np_font_small, 113, 225, r->manual ? "MT" : "AT", DIM);- const char *nl = r->flash ? "NITRO +" : r->slipstream > 10 ? "SLIPSTREAM" : c->drift ? "SLIDE" : "NITRO";- text(&np_font_small, 146, 213, nl, r->flash || r->slipstream > 10 ? GOLD : c->drift ? SUN : MUTED);- bar(146, 216, 166, 7, c->nitro, 1000, c->boost ? HEX(0xA8F2FF) : CYAN);- key_line(237, r->manual ? "Up=gas|Down=brake|OK=nitro|+ -=gears|Back=pause" : "Up=gas|Down=brake|OK=nitro|Back=pause");- /* the start, a lap, the finish */- if (r->phase == PH_GRID || (U->hold && U->screen == V_RACE)) {- int n = r->phase == PH_GRID ? (r->countdown + PG_HZ - 1) / PG_HZ : U->hold;- gfx_rrect(100, 58, 120, 48, 8, INK, 225);- if (n > 3) {- center(&np_font_body, 160, 78, endless ? "Endless road" : pg_circuit_name[r->track], WHITE);- center(&np_font_small, 160, 96, "Get ready", MUTED);- } else {- s[0] = (char)('0' + n), s[1] = 0;- center(&np_font_title, 160, 90, s, GOLD);- }- } else if (r->phase == PH_RACE && r->time_ms < 1000 && !r->banner_t) {- gfx_rrect(110, 58, 100, 48, 8, INK, 225);- center(&np_font_title, 160, 90, "GO!", GOLD);- } else if (r->phase == PH_DONE) {- gfx_rrect(90, 58, 140, 54, 8, INK, 225);- if (r->end == END_FINISH) {- center(&np_font_title, 160, 86, "Finish!", GOLD);- ordinal(s, r->car[0].place);- center(&np_font_body, 160, 105, s, WHITE);- } else {- center(&np_font_title, 160, 86, "Time up", RED);- if (endless) km(s, (uint32_t)(r->car[0].s / FX)), center(&np_font_body, 160, 105, s, WHITE);- }- } else if (r->banner_t) {- const char *big = "";- char t[24];- t[0] = 0;- color_t col = GOLD;- if (r->banner == BANNER_LAP || r->banner == BANNER_FINAL) {- if (r->banner == BANNER_FINAL) big = "Final lap";- else p = cat(s, "Lap "), num(p, r->banner_arg), big = s;- char *e = clock_of(t, r->last_lap_ms);- if (r->banner_arg >= 3 && r->last_lap_ms == r->best_lap_ms) cat(e, " best");- } else if (r->banner == BANNER_ZONE) {- p = cat(s, "Zone "), num(p, (uint32_t)r->banner_arg + 1), big = s;- uint32_t b = (uint32_t)pg_zone_bonus(r->banner_arg);- p = cat(t, "+");- p = num(p, b / 1000);- if (b % 1000) *p++ = '.', *p++ = (char)('0' + b / 100 % 10), *p = 0;- cat(p, " s");- } else if (r->banner == BANNER_WRONG) {- big = "Wrong way", col = RED;- cat(t, "Turn round");- }- if (big[0]) {- gfx_rrect(90, 58, 140, t[0] ? 54 : 40, 8, INK, 225);- center(&np_font_title, 160, 86, big, col);- if (t[0]) center(&np_font_body, 160, 105, t, WHITE);- }+ if (h1) {+ int w1 = gfx_text_width(&np_font_body, h1), w2 = h2 ? gfx_text_width(&np_font_small, h2) : 0;+ int w = (w1 > w2 ? w1 : w2) + 24;+ int hgt = h2 ? 38 : 24;+ slant(160 - w / 2, 34, w, hgt, 6, SURFACE, 215);+ center(&np_font_body, 163, 51, h1, U->new_record && c->finish ? GREEN : WHITE);+ if (h2) center(&np_font_small, 163, 66, h2, MUTED);}+ keys(U->started ? "OK=last checkpoint|Backspace=restart|Back=pause" : start_keys());}/* ------------------------------------------------------------------ screens */-static void title(void) {- for (int y = 0; y < 84; y += 4) gfx_fill_alpha(0, y, 320, 4, HEX(0x05040F), 160 - y * 160 / 84);- logo(16, 46);- text(&np_font_small, 18, 66, "by Boris-TH, made for NumPlay", WHITE);- static const char *const NAMES[4] = {"Continue", "Play", "Records", "How to play"};- int n = U->menu_n, y0 = 92;- for (int i = 0; i < n; i++) {- int item = U->menu[i];- const char *s = NAMES[item];- if (item == MENU_CONTINUE) s = F->race.mode == MODE_ENDLESS ? "Continue drive" : "Continue race";- button(16, y0 + i * 31, 136, s, U->sel == i);- }- /* the car on the turntable (or, when the storage is full, that) */- const pg_vehicle *v = &pg_vehicles[F->p.vehicle];- if (U->save_failed) {- gfx_rrect(164, 186, 150, 30, 6, HEX(0x5A1E1A), 240);- center(&np_font_small, 239, 199, "Storage full:", WHITE);- center(&np_font_small, 239, 211, "progress not saved", WHITE);- } else {- gfx_rrect(164, 186, 150, 30, 6, INK, 200);- center(&np_font_body, 239, 200, v->name, WHITE);- center(&np_font_small, 239, 212, v->kind, MUTED);- }- keys("Up Down=choose|OK=open|Back=quit");+int tab_rows(int tab) {+ int n = 0;+ for (int t = 0; t < PT_NTRACKS; t++) n += pt_tracks[t].env == tab;+ return n;+}+int track_of_tab(int tab, int row) {+ for (int t = 0; t < PT_NTRACKS; t++)+ if (pt_tracks[t].env == tab && row-- == 0) return t;+ return -1;}-static void stat_row(int y, const char *name, int v, int max) {- text(&np_font_small, 212, y, name, MUTED);- bar(212, y + 4, 90, 6, v < 0 ? 0 : v, max, CYAN);+static void title(void) {+ for (int y = 0; y < 80; y += 4) gfx_fill_alpha(0, y, 320, 4, HEX(0x0A0F2A), 150 - y * 150 / 80);+ logo(18, 40, 2);+ static const char *const NAMES[MENU_ROWS] = {"Play", "Car", "How to play"};+ for (int i = 0; i < MENU_ROWS; i++) button(18, 96 + i * 34, 136, NAMES[i], U->sel == i);+ text(&np_font_small, 18, 214, "Kodub's PolyTrack, made for NumPlay", WHITE);+ not_saved(190);+ keys("Up Down=choose|OK=open|Back=quit");}-static void setup(void) {- page("RACE");- const pg_profile *p = &F->p;- static const char *const NAMES[SET_ROWS] = {"Mode", "Circuit", "Car", "Laps", "Rivals", "Level", "Gearbox", "View", ""};- bool endless = p->mode == MODE_ENDLESS;+static void tracks(void) {+ page("TRACKS");+ /* the tabs */+ for (int t = 0; t < 3; t++) {+ bool on = U->tab == t;+ slant(150 + t * 56, 14, 56, 22, 6, on ? HOVER : BUTTON, 256);+ if (on) gfx_fill(156 + t * 56, 34, 44, 2, LAVENDER);+ center(&np_font_small, 180 + t * 56, 29, pt_env_name[t], on ? WHITE : MUTED);+ }+ int n = tab_rows(U->tab);char s[24];- for (int i = 0; i < SET_START; i++) {- int y = 38 + i * 19;- bool on = U->sel == i;- bool off = endless && (i == SET_TRACK || i == SET_LAPS || i == SET_RIVALS || i == SET_LEVEL);- if (on) gfx_rrect(8, y - 1, 194, 19, 5, WHITE, 256);- gfx_rrect(10, y, 190, 17, 4, on ? CYAN : PANEL, 256);- color_t c = on ? INK : off ? DIM : WHITE;- text(&np_font_small, 18, y + 13, NAMES[i], c);- const char *v = "";- switch (i) {- case SET_MODE: v = MODES[p->mode]; break;- case SET_TRACK: v = endless ? "-" : pg_circuit_name[p->track]; break;- case SET_CAR: v = pg_vehicles[p->vehicle].name; break;- case SET_LAPS:- if (endless) v = "-";- else num(s, p->laps), v = s;- break;- case SET_RIVALS:- if (endless) v = "-";- else if (!p->rivals) v = "None";- else num(s, p->rivals), v = s;- break;- case SET_LEVEL: v = endless ? "-" : LEVELS[p->level]; break;- case SET_GEARS: v = p->manual ? "Manual" : "Automatic"; break;- case SET_VIEW: v = VIEW_NAMES[p->view]; break;- }- right(&np_font_small, off ? 192 : 180, y + 13, v, c);- if (!off) text(&np_font_small, 184, y + 13, ">", on ? INK : DIM);+ for (int r = 0; r < n; r++) {+ int t = track_of_tab(U->tab, r);+ int y = 46 + r * 25;+ bool on = U->sel == r;+ if (on) slant(6, y - 2, 172, 25, 6, LAVENDER, 256);+ slant(8, y, 168, 21, 5, on ? HOVER : SURFACE2, 256);+ text(&np_font_small, 18, y + 15, pt_tracks[t].name, WHITE);+ if (F->p.best[t]) clock_of(s, F->p.best[t]);+ else cat(s, "- - -");+ right(&np_font_small, 168, y + 15, s, F->p.best[t] ? LAVENDER : DIM);}- /* the right: the car when choosing it, else the circuit or the road */- gfx_rrect(206, 38, 104, 150, 6, PANEL, 256);- if (U->sel == SET_CAR) {- const pg_vehicle *v = &pg_vehicles[p->vehicle];- center(&np_font_small, 258, 54, v->name, WHITE);- stat_row(74, "Top speed", v->top / 8 - 60, 25);- stat_row(98, "Pick-up", v->accel / 8 - 30, 18);- stat_row(122, "Grip", v->grip - 110, 50);- stat_row(146, "On grass", 160 - v->offroad, 100);- num(s, (uint32_t)(v->top / 8) * 36 / 10);- cat(s + strlen(s), " km/h");- center(&np_font_small, 258, 178, s, GOLD);- } else if (endless) {- center(&np_font_small, 258, 56, "Endless road", WHITE);- static const char *const L[6] = {"Reach each zone", "before the time", "runs out.", "Every zone adds", "time; the road", "never ends."};- for (int i = 0; i < 6; i++) center(&np_font_small, 258, 80 + i * 15, L[i], MUTED);- if (p->best_m) {- km(cat(s, "Best "), p->best_m);- center(&np_font_small, 258, 178, s, GOLD);- }+ /* the chosen track: its map and record */+ int t = track_of_tab(U->tab, U->sel);+ slant(184, 46, 132, 172, 0, SURFACE3, 230);+ center(&np_font_body, 250, 64, pt_tracks[t].name, WHITE);+ track_map(t, 250, 128, 116, 96);+ if (F->p.best[t]) {+ clock_of(s, F->p.best[t]);+ center(&np_font_small, 250, 196, "Record", MUTED);+ center(&np_font_body, 250, 211, s, WHITE);} else {- center(&np_font_small, 258, 54, "Circuit", MUTED);- map_setup(T, 84, 66);- outline(216, 62);- center(&np_font_small, 258, 146, pg_circuit_name[p->track], WHITE);- center(&np_font_small, 258, 160, pg_circuit_note[p->track], MUTED);- if (p->best_ms[p->track]) {- clock_of(cat(s, "Best "), p->best_ms[p->track]);- center(&np_font_small, 258, 178, s, GOLD);- }+ center(&np_font_small, 250, 204, "Not finished yet", DIM);}- button(10, 192, 300, endless ? "Start the drive" : "Start race", U->sel == SET_START);- keys(U->sel == SET_START ? "OK=start|Up Down=choose|Back=menu" : "Left Right=change|Up Down=choose|Back=menu");+ not_saved(206);+ keys("Up Down=track|Left Right=season|OK=race|Back=menu");}-static void confirm_box(const char *q, const char *note, int n, const char *const *labels) {- dim();- int h = 70 + n * 32;- gfx_rrect(40, 120 - h / 2, 240, h, 8, INK, 256);- gfx_rrect_outline(40, 120 - h / 2, 240, h, 8, 1, LINE, 256);- center(&np_font_body, 160, 120 - h / 2 + 28, q, WHITE);- if (note) center(&np_font_small, 160, 120 - h / 2 + 46, note, MUTED);- for (int i = 0; i < n; i++) button(60, 120 - h / 2 + 58 + i * 32, 200, labels[i], U->sel == i);+static void car_screen(void) {+ page("CAR");+ slant(30, 182, 260, 26, 8, SURFACE3, 230);+ char s[24];+ char *p = cat(s, "< ");+ p = cat(p, PAINT_NAMES[F->p.paint % PT_PAINTS]);+ cat(p, " >");+ center(&np_font_body, 162, 200, s, WHITE);+ center(&np_font_small, 162, 222, F->p.view ? "View: from the cockpit" : "View: behind the car", MUTED);+ keys("Left Right=colour|Up Down=view|OK=done");}static void help_page(int k, bool guide) {page(guide ? "BEFORE YOU RACE" : "HOW TO PLAY");- static const char *const TITLES[PG_HELP_PAGES] = {"Keys", "Racing", "Endless road"};- center(&np_font_body, 160, 56, TITLES[k], GOLD);+ static const char *const TITLES[PT_HELP_PAGES] = {"Keys", "The race", "Records"};+ center(&np_font_body, 160, 62, TITLES[k], LAVENDER);if (k == 0) {- static const char *const K[7][2] = {{"Up", "Accelerate"}, {"Down", "Brake"}, {"Left Right", "Steer"},- {"OK or EXE", "Nitro"}, {"+ and -", "Gears, if manual"},+ static const char *const K[7][2] = {{"Up", "Accelerate"}, {"Down", "Brake, reverse"}, {"Left Right", "Steer"},+ {"OK or EXE", "Back to the last checkpoint"}, {"Backspace", "Start over"},{"Back", "Pause"}, {"Home", "Save and quit"}};for (int i = 0; i < 7; i++) {- int y = 66 + i * 20;- gfx_rrect(40, y, 240, 18, 4, PANEL, 256);- text(&np_font_small, 50, y + 13, K[i][0], CYAN);- text(&np_font_small, 140, y + 13, K[i][1], WHITE);+ int y = 72 + i * 20;+ slant(30, y, 260, 18, 4, SURFACE2, 256);+ text(&np_font_small, 42, y + 13, K[i][0], LAVENDER);+ text(&np_font_small, 128, y + 13, K[i][1], WHITE);}} else {- static const char *const L[2][7] = {- {"Finish the laps ahead of the rivals.", "Brake before tight bends, or you", "run wide. Brake while steering hard",- "to slide round a hairpin. Orbs on the", "road fill your nitro; driving close", "behind a car pulls you along.",- "Your best lap comes back as a ghost."},- {"Reach the next zone before the", "clock runs out: each one adds time,", "a little less each time.",- "There are no rivals, just you,", "the orbs and the road, which goes", "on and changes scenery.", ""}};- for (int i = 0; i < 7; i++) center(&np_font_small, 160, 82 + i * 19, L[k - 1][i], WHITE);+ static const char *const L[2][6] = {+ {"Drive through every checkpoint, the ones", "with a yellow banner, in order, then over", "the finish line, as fast as you can.",+ "The clock starts when you start driving.", "Fell off or crashed? OK takes you back", "to the last checkpoint."},+ {"Your best time on each track is kept,", "with its checkpoint times: green when", "you are ahead of your record, red when",+ "behind. A ghost car drives your best run.", "The ghosts of the last tracks you set a", "record on are kept between games."}};+ for (int i = 0; i < 6; i++) center(&np_font_small, 160, 92 + i * 19, L[k - 1][i], WHITE);}- for (int i = 0; i < PG_HELP_PAGES; i++) gfx_circle(148 + i * 12, 212, 3, i == k ? CYAN : DIM, 256);- keys(guide ? "OK=start|Left Right=page|Back=return" : "Left Right=page|Back=return");+ for (int i = 0; i < PT_HELP_PAGES; i++) gfx_circle(148 + i * 12, 216, 3, i == k ? LAVENDER : DIM, 256);+ keys(guide ? (k + 1 < PT_HELP_PAGES ? "OK=next|Left Right=page|Back=tracks" : "OK=race|Left Right=page|Back=tracks")+ : "Left Right=page|Back=return");}-static void records(void) {- page("RECORDS");- text(&np_font_small, 172, 50, "Race", MUTED);- text(&np_font_small, 246, 50, "Lap", MUTED);- char s[32];- for (int i = 0; i < PG_CIRCUITS; i++) {- int y = 56 + i * 24;- gfx_rrect(10, y, 300, 21, 5, PANEL, 256);- text(&np_font_small, 18, y + 15, pg_circuit_name[i], WHITE);- if (F->p.best_ms[i]) clock_of(s, F->p.best_ms[i]);- else cat(s, "-");- text(&np_font_small, 172, y + 15, s, F->p.best_ms[i] ? GOLD : DIM);- if (F->p.best_lap_ms[i]) clock_of(s, F->p.best_lap_ms[i]);- else cat(s, "-");- text(&np_font_small, 246, y + 15, s, F->p.best_lap_ms[i] ? GOLD : DIM);- }- int y = 56 + 3 * 24;- gfx_rrect(10, y, 300, 21, 5, PANEL, 256);- text(&np_font_small, 18, y + 15, "Endless road", WHITE);- if (F->p.best_m) {- char *q = km(s, F->p.best_m);- q = cat(q, ", zone ");- num(q, F->p.best_zone);- } else {- cat(s, "-");- }- text(&np_font_small, 172, y + 15, s, F->p.best_m ? GOLD : DIM);- char t[64], *q = cat(t, "Races ");- q = num(q, F->p.races);- q = cat(q, " Wins ");- num(q, F->p.wins);- center(&np_font_small, 160, 196, t, MUTED);- keys("Back=menu");+static void confirm_box(const char *q, const char *note, int n, const char *const *labels) {+ dim();+ int h = 64 + n * 32;+ int y0 = 112 - h / 2;+ slant(36, y0, 248, h, 8, SURFACE, 250);+ center(&np_font_body, 162, y0 + 26, q, WHITE);+ if (note) center(&np_font_small, 162, y0 + 43, note, MUTED);+ for (int i = 0; i < n; i++) button(64, y0 + 54 + i * 32, 192, labels[i], U->sel == i);}static void result(void) {dim();- const pg_race *r = R;- char s[48];- bool endless = r->mode == MODE_ENDLESS;- int h = endless ? 176 : 196, y0 = (222 - h) / 2;- gfx_rrect(30, y0, 260, h, 8, INK, 256);- gfx_rrect_outline(30, y0, 260, h, 8, 1, LINE, 256);- int y = y0 + 30;- if (endless) {- km(s, (uint32_t)(r->car[0].s / FX));- center(&np_font_title, 160, y, s, GOLD);- char *q = cat(s, "Zone ");- num(q, (uint32_t)r->zone + 1);- center(&np_font_body, 160, y + 22, s, WHITE);- if (U->new_far && !U->save_failed) center(&np_font_small, 160, y + 40, "Your furthest yet!", GOLD);- else if (F->p.best_m) km(cat(s, "Best "), F->p.best_m), center(&np_font_small, 160, y + 40, s, MUTED);- } else if (r->end == END_TIME) {- center(&np_font_title, 160, y, "Time up", RED);- center(&np_font_small, 160, y + 16, pg_circuit_name[r->track], MUTED);- } else {- char *q = ordinal(s, U->result_rank);- cat(q, U->result_rank == 1 ? " place!" : " place");- center(&np_font_title, 160, y, s, U->result_rank == 1 ? GOLD : WHITE);- center(&np_font_small, 160, y + 16, pg_circuit_name[r->track], MUTED);- clock_of(cat(s, "Time "), r->car[0].finish_ms);- center(&np_font_body, 160, y + 36, s, WHITE);- if (r->best_lap_ms) {- clock_of(cat(s, "Best lap "), r->best_lap_ms);- center(&np_font_small, 160, y + 52, s, WHITE);- }- if ((U->new_best || U->new_lap) && !U->save_failed)- center(&np_font_small, 160, y + 68, U->new_best ? "New circuit record!" : "New lap record!", GOLD);- }- int by = y0 + h - 70;- button(50, by, 220, endless ? "Drive again" : "Race again", U->sel == 0);- button(50, by + 31, 220, "Main menu", U->sel == 1);- if (U->save_failed) not_saved();- keys("Up Down=choose|OK=select");-}--static void race_screen(void) {- hud();- if (U->screen == V_PAUSE) {- static const char *const L[PAUSE_ROWS] = {"Resume", "Restart race", "How to play", "Quit game"};- dim();- gfx_rrect(60, 30, 200, 172, 8, INK, 256);- gfx_rrect_outline(60, 30, 200, 172, 8, 1, LINE, 256);- center(&np_font_title, 160, 60, "PAUSED", WHITE);- for (int i = 0; i < PAUSE_ROWS; i++) {- const char *s = i == PAUSE_RESTART && R->mode == MODE_ENDLESS ? "Restart drive" : L[i];- button(80, 74 + i * 31, 160, s, U->sel == i);- }- keys("Up Down=choose|OK=select|Back=resume");- } else if (U->screen == V_LEAVE) {- static const char *const L[3] = {"Keep racing", "Main menu", "Quit PolyGT 3D"};- confirm_box(R->mode == MODE_ENDLESS ? "Leave the drive?" : "Leave the race?", "It's kept: Continue picks it up.", 3, L);- keys("Up Down=choose|OK=select|Back=pause");- } else if (U->screen == V_RESULT) {- result();+ const car_t *c = CAR;+ char s[40];+ int track = F->p.track;+ slant(30, 22, 260, 196, 8, SURFACE, 250);+ center(&np_font_small, 162, 42, pt_tracks[track].name, MUTED);+ center(&np_font_title, 162, 70, U->new_record ? "New record!" : "Finished", U->new_record ? GREEN : WHITE);+ clock_of(s, c->finish);+ center(&np_font_title, 162, 96, s, WHITE);+ if (U->new_record && U->finish_diff) {+ diff_of(s, U->finish_diff);+ center(&np_font_small, 162, 113, s, GREEN);+ } else if (!U->new_record) {+ char *p = cat(s, "Record ");+ clock_of(p, F->p.best[track]);+ center(&np_font_small, 162, 113, s, MUTED);}+ static const char *const L[RES_ROWS] = {"Race again", "Next track", "Tracks"};+ for (int i = 0; i < RES_ROWS; i++) button(64, 124 + i * 30, 192, L[i], U->sel == i);+ not_saved(200);+ keys("Up Down=choose|OK=select|Backspace=race again");}static void scene(void) {switch (U->screen) {- case V_SETUP: setup(); break;- case V_NEWRUN: {- setup();- static const char *const L[2] = {"Keep it", "Start new"};- confirm_box("Start something new?", F->race.mode == MODE_ENDLESS ? "The drive you left will end." : "The race you left will end.", 2, L);- keys("Up Down=choose|OK=select|Back=return");- break;- }+ case V_TRACKS: tracks(); break;case V_GUIDE: help_page(U->page, true); break;case V_HELP: help_page(U->page, false); break;- case V_RECORDS: records(); break;+ case V_CAR:+ rd_draw();+ car_screen();+ break;case V_TITLE:case V_QUIT:rd_draw();title();if (U->screen == V_QUIT) {static const char *const L[2] = {"Stay", "Quit"};- confirm_box("Quit PolyGT 3D?", NULL, 2, L);+ confirm_box("Quit PolyTrack?", NULL, 2, L);keys("Up Down=choose|OK=select|Back=return");}break;default:rd_draw();- race_screen();+ hud();+ if (U->screen == V_PAUSE) {+ static const char *const L[PAUSE_ROWS] = {"Resume", "Restart", "How to play", "Quit game"};+ dim();+ slant(56, 26, 208, 180, 8, SURFACE, 250);+ center(&np_font_title, 162, 56, "PAUSED", WHITE);+ for (int i = 0; i < PAUSE_ROWS; i++) button(78, 70 + i * 32, 168, L[i], U->sel == i);+ keys("Up Down=choose|OK=select|Back=resume");+ } else if (U->screen == V_LEAVE) {+ static const char *const L[3] = {"Keep racing", "Tracks", "Quit PolyTrack"};+ confirm_box("Leave the race?", "This run's time is lost.", 3, L);+ keys("Up Down=choose|OK=select|Back=pause");+ } else if (U->screen == V_RESULT) {+ result();+ }break;}}-void pg_render(const pg_file *f, const pg_track *t, const pg_race *prev, const pg_race *race, int alpha,- const pg_ui *ui, const rd_ghost *g) {- F = f, T = t, R = race, U = ui;+void pt_render(const pt_file *f, const car_t *car, const camera_t *cam, const car_look *look, const car_look *ghost,+ const pt_ui *ui) {+ F = f, CAR = car, U = ui;int s = ui->screen;- if (s == V_RACE || s == V_PAUSE || s == V_LEAVE || s == V_RESULT)- rd_race(t, prev, race, alpha, f->p.view, g, ui->clock);- else if (s == V_TITLE || s == V_QUIT)- rd_showroom(f->p.vehicle, (int32_t)(ui->clock * 12), f->p.track, ui->clock);+ if (s == V_RACE || s == V_PAUSE || s == V_LEAVE || s == V_RESULT) {+ rd_begin(cam, W.t->env, W.t->sun, false);+ rd_track();+ if (ghost) rd_car(ghost);+ if (!f->p.view) {+ rd_shadow(look, car);+ rd_car(look);+ }+ } else if (s == V_TITLE || s == V_QUIT || s == V_CAR) {+ /* the track's start from a camera going round the car */+ camera_t c;+ float a = (float)(ui->clock % 40000u) * (2.0f * PT_PI / 40000.0f);+ v3 at = car->pos;+ float d = s == V_CAR ? 6.5f : 9.0f;+ v3 eye = V3(at.x + pt_cosf(a) * d, at.y + (s == V_CAR ? 1.8f : 3.2f), at.z + pt_sinf(a) * d);+ v3 z = vnorm(vsub(eye, vadd(at, V3(0.0f, 0.5f, 0.0f))));+ v3 x = vnorm(vcross(V3(0.0f, 1.0f, 0.0f), z));+ c.pos = eye, c.right = x, c.up = vcross(z, x), c.fwd = vneg(z), c.fov = 60.0f;+ rd_begin(&c, W.t->env, W.t->sun, false);+ rd_track();+ rd_shadow(look, car);+ rd_car(look);+ }color_t *old = gfx_buf;gfx_buf = strip;for (int y = 0; y < SCREEN_H; y += STRIP) {diff --git a/games/polytrack/src/draw.h b/games/polytrack/src/draw.hindex c3ad60d4..959db414 100644--- a/games/polytrack/src/draw.h+++ b/games/polytrack/src/draw.h@@ -1,27 +1,39 @@-/* The screens (draw.c): menus, the race's dials, results. */-#ifndef PG_DRAW_H-#define PG_DRAW_H-#include "game.h"+/* The screens (draw.c): the title, the tracks, the car's colour, how to play, the race's timer and speed, the pause,+ * the finish. PolyTrack's dark blue slanted boxes, each screen with a line of plain keys at the bottom. */+#ifndef PT_DRAW_H+#define PT_DRAW_H+#include "car.h"#include "render.h"#include "save.h"-enum { V_TITLE, V_SETUP, V_NEWRUN, V_GUIDE, V_HELP, V_RECORDS, V_RACE, V_PAUSE, V_LEAVE, V_RESULT, V_QUIT, V_SCREENS };-enum { SET_MODE, SET_TRACK, SET_CAR, SET_LAPS, SET_RIVALS, SET_LEVEL, SET_GEARS, SET_VIEW, SET_START, SET_ROWS };+enum {+ V_TITLE, V_TRACKS, V_CAR, V_GUIDE, V_HELP, V_RACE, V_PAUSE, V_LEAVE, V_RESULT, V_QUIT, V_SCREENS+};enum { PAUSE_RESUME, PAUSE_RESTART, PAUSE_HELP, PAUSE_QUIT, PAUSE_ROWS };-enum { MENU_CONTINUE, MENU_PLAY, MENU_RECORDS, MENU_HELP };-#define PG_HELP_PAGES 3+enum { MENU_PLAY, MENU_CAR, MENU_HELP, MENU_ROWS };+enum { RES_AGAIN, RES_NEXT, RES_TRACKS, RES_ROWS };+#define PT_HELP_PAGES 3typedef struct {- uint8_t screen, sel, page, under; /* under: where Back goes from how to play */- uint8_t menu[4], menu_n; /* the title's buttons */- uint8_t hold; /* a race going on again: 3, 2, 1 */- uint8_t result_rank, new_best, new_lap, new_far;- uint32_t clock; /* ms, for what moves on the menus */+ uint8_t screen, sel, page, under; /* under: where Back goes from how to play */+ uint8_t tab; /* the tracks' tab: Summer, Winter, Desert */+ uint32_t clock; /* ms, for what moves */bool save_failed;-} pg_ui;+ /* the race */+ uint8_t started, new_record, has_ghost;+ uint32_t split_at; /* the clock when a checkpoint was taken (its times show 3.5 s) */+ uint16_t split_cp;+ int32_t split_diff; /* ms against the record, or a big number when there is none */+ uint32_t still_ms; /* under 50 km/h since */+ uint32_t finish_at; /* the clock at the finish */+ int32_t finish_diff;+ uint8_t slow; /* the picture's detail went down */+} pt_ui;-extern const char *const pg_driver[PG_CARS];-/* the whole screen; race: the race shown (the one going, or the last one) */-void pg_render(const pg_file *f, const pg_track *t, const pg_race *prev, const pg_race *race, int alpha,- const pg_ui *ui, const rd_ghost *g);+extern const char *const pt_env_name[3];+/* the whole screen */+void pt_render(const pt_file *f, const car_t *car, const camera_t *cam, const car_look *look, const car_look *ghost,+ const pt_ui *ui);+int track_of_tab(int tab, int row); /* the track at a row of a tab, or -1 */+int tab_rows(int tab);#endifdiff --git a/games/polytrack/src/ghost.c b/games/polytrack/src/ghost.cnew file mode 100644index 00000000..26e2c20d--- /dev/null+++ b/games/polytrack/src/ghost.c@@ -0,0 +1,149 @@+/* The ghost (ghost.h). A sample: per axis a byte, the change from the guess (twice the last position less the one+ * before), or 0x80 and the position itself (two bytes); then the turn in three bytes. */+#include <string.h>+#include "ghost.h"++static int32_t qpos(float v) { return (int32_t)(v < 0.0f ? v * 16.0f - 0.5f : v * 16.0f + 0.5f); }++void ghost_rec_start(ghost_rec *r) {+ r->len = 0, r->full = 0, r->n = 0;+ memset(r->q, 0, sizeof r->q);+}++static void put(ghost_rec *r, uint8_t b) {+ if (r->len >= PT_GHOST_MAX) {+ r->full = 1;+ return;+ }+ r->buf[r->len++] = b;+}++static int8_t qpart(float v) {+ int i = (int)(v * 89.8026f + (v < 0.0f ? -0.5f : 0.5f)); /* 1/sqrt(2) -> 63.5 */+ return (int8_t)(i < -63 ? -63 : i > 63 ? 63 : i);+}++void ghost_rec_add(ghost_rec *r, v3 pos, qt rot) {+ if (r->full) return;+ int32_t q[3] = {qpos(pos.x), qpos(pos.y), qpos(pos.z)};+ for (int k = 0; k < 3; k++) {+ int32_t guess = r->n == 0 ? 0 : r->n == 1 ? r->q[1][k] : 2 * r->q[1][k] - r->q[0][k];+ int32_t d = q[k] - guess;+ if (r->n > 0 && d >= -127 && d <= 127) {+ put(r, (uint8_t)(int8_t)d);+ } else {+ int32_t v = q[k] < -32767 ? -32767 : q[k] > 32767 ? 32767 : q[k];+ q[k] = v;+ put(r, 0x80);+ put(r, (uint8_t)(v & 255));+ put(r, (uint8_t)((v >> 8) & 255));+ }+ }+ for (int k = 0; k < 3; k++) r->q[0][k] = r->q[1][k], r->q[1][k] = q[k];+ /* the turn: the biggest part left out (made positive), the other three in 7 bits */+ float c[4] = {rot.x, rot.y, rot.z, rot.w};+ int big = 0;+ for (int k = 1; k < 4; k++)+ if (pt_absf(c[k]) > pt_absf(c[big])) big = k;+ float s = c[big] < 0.0f ? -1.0f : 1.0f;+ uint32_t bits = (uint32_t)big;+ int sh = 2;+ for (int k = 0; k < 4; k++) {+ if (k == big) continue;+ bits |= (uint32_t)(qpart(c[k] * s) + 64) << sh;+ sh += 7;+ }+ put(r, (uint8_t)bits), put(r, (uint8_t)(bits >> 8)), put(r, (uint8_t)(bits >> 16));+ r->n++;+}++void ghost_play_start(ghost_play *g, const uint8_t *data, uint16_t len, uint32_t ms) {+ memset(g, 0, sizeof *g);+ g->data = data, g->len = len, g->ms = ms;+ g->on = data && len;+ g->first = -1000;+}++static bool decode(ghost_play *g, v3 *pos, qt *rot) {+ int32_t q[3];+ for (int k = 0; k < 3; k++) {+ if (g->at >= g->len) return false;+ uint8_t b = g->data[g->at++];+ if (b == 0x80) {+ if (g->at + 2 > g->len) return false;+ q[k] = (int16_t)(g->data[g->at] | g->data[g->at + 1] << 8);+ g->at += 2;+ } else {+ int32_t guess = g->n == 1 ? g->q[1][k] : 2 * g->q[1][k] - g->q[0][k];+ q[k] = guess + (int8_t)b;+ }+ }+ if (g->at + 3 > g->len) return false;+ uint32_t bits = (uint32_t)(g->data[g->at] | g->data[g->at + 1] << 8 | g->data[g->at + 2] << 16);+ g->at += 3;+ for (int k = 0; k < 3; k++) g->q[0][k] = g->q[1][k], g->q[1][k] = q[k];+ g->n++;+ *pos = V3((float)q[0] / 16.0f, (float)q[1] / 16.0f, (float)q[2] / 16.0f);+ int big = (int)(bits & 3);+ float c[4], sum = 0.0f;+ int sh = 2;+ for (int k = 0; k < 4; k++) {+ if (k == big) continue;+ c[k] = (float)((int)((bits >> sh) & 127) - 64) / 89.8026f;+ sum += c[k] * c[k];+ sh += 7;+ }+ c[big] = pt_sqrtf(pt_maxf(0.0f, 1.0f - sum));+ qt r = {c[0], c[1], c[2], c[3]};+ *rot = qnorm(r);+ return true;+}++bool ghost_at(ghost_play *g, uint32_t f, v3 *pos, qt *rot) {+ if (!g->on || g->ended) return false;+ int32_t i = (int32_t)(f / GHOST_STEP);+ if (i < g->first) {+ ghost_play_start(g, g->data, g->len, g->ms);+ }+ /* the window: samples i-1 .. i+2 */+ while (g->first < i) {+ if (g->first < -1) {+ /* (re)start: decode the first three samples */+ v3 p;+ qt q;+ if (!decode(g, &p, &q)) return g->ended = true, false;+ g->pos[0] = g->pos[1] = p, g->rot[0] = g->rot[1] = q;+ for (int k = 2; k < 4; k++) {+ if (!decode(g, &g->pos[k], &g->rot[k])) g->pos[k] = g->pos[k - 1], g->rot[k] = g->rot[k - 1];+ }+ g->first = 0;+ continue;+ }+ for (int k = 0; k < 3; k++) g->pos[k] = g->pos[k + 1], g->rot[k] = g->rot[k + 1];+ if (!decode(g, &g->pos[3], &g->rot[3])) {+ if (g->n < (uint32_t)i + 2) return g->ended = true, false;+ g->pos[3] = g->pos[2], g->rot[3] = g->rot[2];+ }+ g->first++;+ }+ if ((uint32_t)i + 1 >= g->n) return false;+ float t = (float)(f % GHOST_STEP) / (float)GHOST_STEP;+ /* Catmull-Rom between samples i and i+1 */+ v3 p0 = g->pos[0], p1 = g->pos[1], p2 = g->pos[2], p3 = g->pos[3];+ float t2 = t * t, t3 = t2 * t;+ float a = -0.5f * t3 + t2 - 0.5f * t, b = 1.5f * t3 - 2.5f * t2 + 1.0f, c = -1.5f * t3 + 2.0f * t2 + 0.5f * t,+ d = 0.5f * t3 - 0.5f * t2;+ /* (a teleport, a respawn: no curve across it) */+ if (vlen2(vsub(p2, p1)) > 400.0f) {+ *pos = t < 0.5f ? p1 : p2;+ } else {+ if (vlen2(vsub(p1, p0)) > 400.0f) p0 = p1;+ if (vlen2(vsub(p3, p2)) > 400.0f) p3 = p2;+ *pos = vadd(vadd(vmul(p0, a), vmul(p1, b)), vadd(vmul(p2, c), vmul(p3, d)));+ }+ qt q0 = g->rot[1], q1 = g->rot[2];+ if (q0.x * q1.x + q0.y * q1.y + q0.z * q1.z + q0.w * q1.w < 0.0f) q1.x = -q1.x, q1.y = -q1.y, q1.z = -q1.z, q1.w = -q1.w;+ qt q = {q0.x + (q1.x - q0.x) * t, q0.y + (q1.y - q0.y) * t, q0.z + (q1.z - q0.z) * t, q0.w + (q1.w - q0.w) * t};+ *rot = qnorm(q);+ return true;+}diff --git a/games/polytrack/src/ghost.h b/games/polytrack/src/ghost.hnew file mode 100644index 00000000..2a12ab05--- /dev/null+++ b/games/polytrack/src/ghost.h@@ -0,0 +1,35 @@+/* The ghost of your best run (ghost.c): where the car was every 100 ms, about six bytes a sample (positions in 1/16 m+ * as a change from a straight-on guess, the turn as its three smallest parts), played back smoothly. */+#ifndef PT_GHOST_H+#define PT_GHOST_H+#include "pt.h"+#include "save.h"++#define GHOST_STEP 100 /* frames (ms) between samples */++typedef struct {+ uint8_t buf[PT_GHOST_MAX];+ uint16_t len;+ uint8_t full; /* ran out of room: this run won't be kept */+ int32_t q[2][3]; /* the last two positions, in 1/16 m */+ uint32_t n;+} ghost_rec;++typedef struct {+ const uint8_t *data;+ uint16_t len, at;+ int32_t q[2][3];+ uint32_t n; /* samples decoded */+ v3 pos[4]; /* samples first-1 .. first+2 */+ qt rot[4];+ int32_t first;+ bool on, ended;+ uint32_t ms;+} ghost_play;++void ghost_rec_start(ghost_rec *r);+void ghost_rec_add(ghost_rec *r, v3 pos, qt rot);+void ghost_play_start(ghost_play *g, const uint8_t *data, uint16_t len, uint32_t ms);+/* the ghost at frame f (1 ms frames from the start); false when it has none there */+bool ghost_at(ghost_play *g, uint32_t f, v3 *pos, qt *rot);+#endifdiff --git a/games/polytrack/src/main.c b/games/polytrack/src/main.cindex 85862ceb..3a98ca42 100644--- a/games/polytrack/src/main.c+++ b/games/polytrack/src/main.c@@ -1,107 +1,61 @@-/* PolyGT 3D, a low-poly 3D racer for the NumWorks calculator, by Boris-TH, made for NumPlay: three circuits against- * up to seven rivals, the endless road against the clock, three cars and two horses, nitro orbs, the slipstream and a- * ghost of your best lap. The rules are in race.c and track.c, the picture in render.c, the screens- * in draw.c and the save in save.c.+/* PolyTrack for the NumWorks calculator: Kodub's low-poly time trial racer, its 17 official tracks, its car and its+ * physics, made for NumPlay. The physics is in car.c (1 ms frames, as the game), the track in world.c, the picture in+ * render.c, the screens in draw.c, the saves in save.c and the ghost in ghost.c.*- * Keys: Up accelerates, Down brakes, Left and Right steer, OK (or EXE) burns nitro, + and - change gear with the- * manual gearbox, Back pauses; Home saves and quits, from anywhere. */+ * Keys: Up accelerates, Down brakes (and reverses), Left and Right steer, OK (or EXE) goes back to the last+ * checkpoint, Backspace starts over, Back pauses; Home saves and quits, from anywhere. */#include <string.h>+#include "car.h"#include "draw.h"-#include "game.h"+#include "ghost.h"#include "plat.h"#include "render.h"#include "save.h"+#include "world.h"-static pg_file sv; /* what's kept: your choices and records, the race going on */-static pg_track track; /* the road built (the race's, or the circuit on the race screen) */-static pg_race prev;-static pg_ui ui;-static uint32_t now, saved_at, hold_at;+static pt_file sv; /* what's kept */+static car_t car;+static car_look look, ghost_look;+static chase_t chase;+static camera_t cam;+static ghost_rec rec;+static ghost_play gplay;+static pt_ui ui;+static uint32_t now, saved_at;static int32_t accum;-static int pending_shift;-static int built = -1; /* which road is in `track`: a circuit, or 100: the endless road of seed... */-static uint32_t built_seed; /* ...built_seed */+static uint16_t cp_seen;static uint32_t frame_gap; /* the least ms between frames (the tests draw fewer) *//* frames drawn, the slowest (ms) and those over 33 ms: read by tools/emu.py */#ifndef HOST__attribute__((used, externally_visible))#endifuint32_t perf_frames, perf_max, perf_slow;--/* ------------------------------------------------------------------ the ghost of your best lap on each circuit- (kept until you quit): where you were every 200 ms */-typedef struct {- uint16_t s; /* in the lap, 1/8 metre */- int8_t x, a; /* across, 1/8 metre; heading from the road, 1/256 turn */-} ghost_pt;-typedef struct {- uint16_t n;- uint8_t model, on;- uint32_t ms;- ghost_pt p[PG_GHOST];-} ghost;-static ghost best_ghost[PG_CIRCUITS], rec;-static bool rec_ok; /* the lap being recorded was driven from its start */-static rd_ghost ghost_now;+#define MAX_STEPS 120 /* frames of physics at most between two pictures (else the game slows) */static void save(void) {ui.save_failed = !save_write(&sv);saved_at = now;}-/* the road for a race, built again when it isn't the one in `track` */-static void show_race(const pg_race *r) {- if (r->mode == MODE_ENDLESS) {- if (built != 100 || built_seed != r->seed || !track.endless) {- pg_endless(&track, r->seed);- built = 100, built_seed = r->seed;- }- pg_extend(&track, pg_seg_of(&track, r->car[0].s) + 48);- } else if (built != r->track || track.endless) {- pg_build(&track, r->track);- built = r->track;- }-}-static void show_circuit(int id) {- if (built != id || track.endless) pg_build(&track, id), built = id;-}--static pg_setup setup_of(void) {- pg_setup s;- s.mode = sv.p.mode, s.track = sv.p.track, s.vehicle = sv.p.vehicle, s.laps = sv.p.laps, s.rivals = sv.p.rivals;- s.level = sv.p.level, s.manual = sv.p.manual;- return s;-}--static void title_menu(void) {- int n = 0;- if (sv.has_race) ui.menu[n++] = MENU_CONTINUE;- ui.menu[n++] = MENU_PLAY, ui.menu[n++] = MENU_RECORDS, ui.menu[n++] = MENU_HELP;- ui.menu_n = (uint8_t)n;-}-static void to_title(void) {- ui.screen = V_TITLE, ui.sel = 0;- title_menu();-}-/* ------------------------------------------------------------------ races */-/* the race screen's choices set to the race just driven (to drive it again) */-static void use_race_settings(void) {- pg_race *r = &sv.race;- sv.p.mode = r->mode, sv.p.vehicle = r->vehicle, sv.p.manual = r->manual;- if (r->mode == MODE_RACE) sv.p.track = r->track, sv.p.laps = r->laps, sv.p.rivals = r->rivals, sv.p.level = r->level;-}-static void race_begin(void) {- pg_setup s = setup_of();- pg_new(&sv.race, &track, &s, (plat_random() ^ now) | 1);- built = s.mode == MODE_ENDLESS ? 100 : s.track, built_seed = sv.race.seed;- prev = sv.race;- sv.has_race = 1;- ui.screen = V_RACE, ui.sel = 0, ui.hold = 0;- accum = 0, pending_shift = 0;- rec.n = 0, rec_ok = true;- save();+ world_load(sv.p.track);+ car_reset(&car);+ look = car_look_of(&car);+ look.paint = sv.p.paint;+ chase_reset(&chase, car.pos, car.rot);+ chase_update(&chase, &cam, 0.0f, car.pos, car.rot, 0.0f);+ ghost_rec_start(&rec);+ ghost_rec_add(&rec, car.pos, car.rot);+ ghost_entry g;+ if (ghosts_find(sv.p.track, &g)) ghost_play_start(&gplay, g.data, g.len, g.ms);+ else ghost_play_start(&gplay, NULL, 0, 0);+ ui.has_ghost = gplay.on;+ ui.screen = V_RACE, ui.sel = 0;+ ui.started = 0, ui.new_record = 0;+ ui.split_at = 0, ui.finish_at = 0, ui.still_ms = 0;+ accum = 0;+ cp_seen = 0;}static void start_or_guide(void) {@@ -112,123 +66,96 @@ static void start_or_guide(void) {race_begin();}-static void resume_saved(void) {- show_race(&sv.race);- prev = sv.race;- ui.screen = V_RACE, ui.hold = 3, accum = 0, pending_shift = 0;- hold_at = now + 500;- rec.n = 0, rec_ok = false;-}--static void finish_race(void) {- pg_race *r = &sv.race;- pg_profile *p = &sv.p;- ui.new_best = ui.new_lap = ui.new_far = 0;- if (r->mode == MODE_ENDLESS) {- uint32_t m = (uint32_t)(r->car[0].s / FX);- if (m > PG_MAX_M) m = PG_MAX_M;- if (p->runs < 999999) p->runs++;- if (m > p->best_m) p->best_m = m, p->best_zone = (uint16_t)(r->zone + 1), ui.new_far = 1;- } else {- int rank = r->car[0].place ? r->car[0].place : pg_rank(r, 0);- ui.result_rank = (uint8_t)rank;- if (p->races < 999999) p->races++;- if (rank == 1 && r->rivals) p->wins++;- int id = r->track;- uint32_t t = r->car[0].finish_ms;- if (t && t <= PG_MAX_TIME && (!p->best_ms[id] || t < p->best_ms[id])) p->best_ms[id] = t, ui.new_best = 1;- if (r->best_lap_ms && r->best_lap_ms <= PG_MAX_TIME && (!p->best_lap_ms[id] || r->best_lap_ms < p->best_lap_ms[id]))- p->best_lap_ms[id] = r->best_lap_ms, ui.new_lap = 1;- /* (a best race holds a lap at least as good) */- if (p->best_ms[id] && (!p->best_lap_ms[id] || p->best_lap_ms[id] > p->best_ms[id])) p->best_lap_ms[id] = p->best_ms[id];+static void finished(void) {+ uint32_t t = car.finish;+ int id = sv.p.track;+ uint32_t best = sv.p.best[id];+ ui.finish_at = ui.clock ? ui.clock : 1;+ ui.finish_diff = best ? (int32_t)t - (int32_t)best : 0;+ if (sv.p.finishes < 999999) sv.p.finishes++;+ if (!best || t < best) {+ sv.p.best[id] = t;+ int n = car_checkpoints();+ for (int k = 0; k < PT_SPLITS; k++) sv.p.split[id][k] = k < n && k < 64 ? car.cp_frames[k] : 0;+ ui.new_record = 1;+ /* its ghost: the run's last sample, then kept with the others */+ ghost_rec_add(&rec, car.pos, car.rot);+ if (!rec.full && rec.len) {+ ghosts_put(id, t, rec.buf, rec.len);+ ghost_entry g;+ if (ghosts_find(id, &g)) ghost_play_start(&gplay, g.data, g.len, g.ms);+ }}- sv.has_race = 0;- ui.screen = V_RESULT, ui.sel = 0;save();}-/* the ghost: a sample every 200 ms of the lap; at the end of a lap, kept if it's the best on this circuit */-static void ghost_after_step(int lap_before) {- pg_race *r = &sv.race;- if (r->mode != MODE_RACE) return;- ghost *g = &best_ghost[r->track];- bool lap_done = r->lap != lap_before || (r->phase == PH_DONE && r->end == END_FINISH && r->car[0].driven && rec.n &&- r->last_lap_ms && r->time_ms - r->lap_at == r->last_lap_ms);- if (lap_done) {- if (rec_ok && rec.n > 10 && r->last_lap_ms && (!g->on || r->last_lap_ms < g->ms)) {- memcpy(g->p, rec.p, sizeof(ghost_pt) * rec.n);- g->n = rec.n, g->ms = r->last_lap_ms, g->model = r->vehicle, g->on = 1;+static void step_race(uint32_t keys, uint32_t hit, uint32_t dt) {+ unsigned in = 0;+ if (keys & PK_UP) in |= IN_UP;+ if (keys & PK_DOWN) in |= IN_DOWN;+ if (keys & PK_LEFT) in |= IN_LEFT;+ if (keys & PK_RIGHT) in |= IN_RIGHT;+ if (keys & PK_OK) in |= IN_RESET;+ if (hit & PK_OK) {+ if (!car.has_respawn) {+ /* (no checkpoint yet: back to the start) */+ race_begin();+ return;}- rec.n = 0, rec_ok = r->phase == PH_RACE;+ chase_reset(&chase, car.respawn.pos, car.respawn.rot);}- if (r->phase != PH_RACE || r->car[0].driven) return;- uint32_t t = r->time_ms - r->lap_at;- if (t % 200 || t / 200 != rec.n) {- if (t / 200 > rec.n) rec_ok = false;- return;+ if (!ui.started) {+ /* the car waits at the start until a driving key: the clock starts with it */+ if (!(in & (IN_UP | IN_DOWN | IN_LEFT | IN_RIGHT))) return;+ ui.started = 1;+ accum = 0;}- if (rec.n >= PG_GHOST) {- rec_ok = false;- return;+ accum += (int32_t)dt;+ int steps = 0;+ bool was_done = car_finished(&car);+ while (accum >= 1 && steps < MAX_STEPS) {+ car_step(&car, in); /* (a held OK is one reset: the car looks for it pressed after released) */+ accum--, steps++;+ if (!car.finish && car.frames % GHOST_STEP == 0) ghost_rec_add(&rec, car.pos, car.rot);+ if (car.next_cp > cp_seen) {+ int k = car.next_cp - 1;+ ui.split_at = ui.clock ? ui.clock : 1;+ ui.split_cp = (uint16_t)k;+ uint32_t bs = k < PT_SPLITS ? sv.p.split[sv.p.track][k] : 0;+ ui.split_diff = bs ? (int32_t)car.cp_frames[k] - (int32_t)bs : 0x7FFFFFFF;+ }+ cp_seen = car.next_cp;+ if (!was_done && car_finished(&car)) {+ finished();+ was_done = true;+ }}- const pg_car *c = &r->car[0];- ghost_pt *q = &rec.p[rec.n++];- q->s = (uint16_t)(pg_lap_s(r, &track) / 32);- q->x = (int8_t)(c->x / 32);- q->a = (int8_t)((c->ang + c->slip) / 256);-}--static void ghost_pose(int alpha) {- ghost_now.on = false;- pg_race *r = &sv.race;- if (r->mode != MODE_RACE || r->phase != PH_RACE || track.endless) return;- const ghost *g = &best_ghost[r->track];- if (!g->on) return;- uint32_t t = r->time_ms - r->lap_at + (uint32_t)(alpha * PG_TICK / 256);- uint32_t i = t / 200, f = t % 200;- if (i + 1 >= g->n) return;- const ghost_pt *a = &g->p[i], *b = &g->p[i + 1];- int32_t L = track.length, sa = a->s * 32, sb = b->s * 32;- if (sb - sa < -L / 2) sb += L;- if (sb - sa > L / 2) sb -= L;- ghost_now.s = sa + (sb - sa) * (int32_t)f / 200;- ghost_now.x = (a->x * 32) + (b->x - a->x) * 32 * (int32_t)f / 200;- ghost_now.ang = a->a * 256 + (int32_t)(int8_t)(b->a - a->a) * 256 * (int32_t)f / 200;- ghost_now.model = g->model;- ghost_now.on = true;+ if (accum > 100) accum = 100;+ if (pt_absf(car.speed) < 50.0f) ui.still_ms += dt;+ else ui.still_ms = 0;}/* ------------------------------------------------------------------ keys, screen by screen */-static bool row_off(int row) {- return sv.p.mode == MODE_ENDLESS && (row == SET_TRACK || row == SET_LAPS || row == SET_RIVALS || row == SET_LEVEL);-}--static void set_change(int row, int d) {- pg_profile *p = &sv.p;- switch (row) {- case SET_MODE: p->mode ^= 1; break;- case SET_TRACK: p->track = (uint8_t)((p->track + PG_CIRCUITS + d) % PG_CIRCUITS); break;- case SET_CAR: p->vehicle = (uint8_t)((p->vehicle + PG_VEHICLES + d) % PG_VEHICLES); break;- case SET_LAPS: p->laps = (uint8_t)((p->laps - 1 + PG_MAX_LAPS + d) % PG_MAX_LAPS + 1); break;- case SET_RIVALS: p->rivals = (uint8_t)((p->rivals + PG_CARS + d) % PG_CARS); break;- case SET_LEVEL: p->level = (uint8_t)((p->level + 3 + d) % 3); break;- case SET_GEARS: p->manual ^= 1; break;- case SET_VIEW: p->view = (uint8_t)((p->view + VIEWS + d) % VIEWS); break;- }+static int tab_row_of(int track) {+ for (int t = 0; t < 3; t++)+ for (int r = 0; r < tab_rows(t); r++)+ if (track_of_tab(t, r) == track) return r;+ return 0;}static bool keys_menu(uint32_t hit) {- int n;switch (ui.screen) {case V_TITLE:- n = ui.menu_n;- if (hit & PK_UP) ui.sel = (uint8_t)((ui.sel + n - 1) % n);- if (hit & PK_DOWN) ui.sel = (uint8_t)((ui.sel + 1) % n);+ if (hit & PK_UP) ui.sel = (uint8_t)((ui.sel + MENU_ROWS - 1) % MENU_ROWS);+ if (hit & PK_DOWN) ui.sel = (uint8_t)((ui.sel + 1) % MENU_ROWS);if (hit & PK_BACK) ui.screen = V_QUIT, ui.sel = 0;- else if (hit & PK_OK) switch (ui.menu[ui.sel % n]) {- case MENU_CONTINUE: resume_saved(); break;- case MENU_PLAY: ui.screen = V_SETUP, ui.sel = SET_START; break;- case MENU_RECORDS: ui.screen = V_RECORDS; break;+ else if (hit & PK_OK) switch (ui.sel) {+ case MENU_PLAY:+ ui.screen = V_TRACKS;+ ui.tab = (uint8_t)pt_tracks[sv.p.track].env;+ ui.sel = (uint8_t)tab_row_of(sv.p.track);+ break;+ case MENU_CAR: ui.screen = V_CAR; break;default: ui.screen = V_HELP, ui.page = 0, ui.under = V_TITLE; break;}break;@@ -240,55 +167,53 @@ static bool keys_menu(uint32_t hit) {ui.screen = V_TITLE, ui.sel = 0;}break;- case V_SETUP: {- int d = (hit & PK_DOWN) ? 1 : (hit & PK_UP) ? -1 : 0;- if (d) {- do ui.sel = (uint8_t)((ui.sel + SET_ROWS + d) % SET_ROWS);- while (row_off(ui.sel));+ case V_TRACKS: {+ int n = tab_rows(ui.tab);+ if (hit & PK_UP) ui.sel = (uint8_t)((ui.sel + n - 1) % n);+ if (hit & PK_DOWN) ui.sel = (uint8_t)((ui.sel + 1) % n);+ if (hit & (PK_LEFT | PK_RIGHT)) {+ ui.tab = (uint8_t)((ui.tab + ((hit & PK_RIGHT) ? 1 : 2)) % 3);+ int m = tab_rows(ui.tab);+ if (ui.sel >= m) ui.sel = (uint8_t)(m - 1);}- int dx = (hit & PK_RIGHT) ? 1 : (hit & PK_LEFT) ? -1 : 0;- if (dx && ui.sel < SET_START) set_change(ui.sel, dx);- if (hit & PK_BACK) {+ if (hit & PK_BACK) ui.screen = V_TITLE, ui.sel = MENU_PLAY;+ else if (hit & PK_OK) {+ sv.p.track = (uint8_t)track_of_tab(ui.tab, ui.sel);save();- to_title();- ui.sel = (uint8_t)(ui.menu_n - 3);- } else if (hit & PK_OK) {- if (ui.sel < SET_START) set_change(ui.sel, 1);- else if (sv.has_race) ui.screen = V_NEWRUN, ui.sel = 0;- else start_or_guide();+ start_or_guide();}- if (ui.screen == V_SETUP && sv.p.mode == MODE_RACE) show_circuit(sv.p.track);break;}- case V_NEWRUN:- if (hit & (PK_UP | PK_DOWN)) ui.sel ^= 1;- if ((hit & PK_BACK) || ((hit & PK_OK) && !ui.sel)) ui.screen = V_SETUP, ui.sel = SET_START;- else if (hit & PK_OK) sv.has_race = 0, start_or_guide();+ case V_CAR:+ if (hit & PK_LEFT) sv.p.paint = (uint8_t)((sv.p.paint + PT_PAINTS - 1) % PT_PAINTS);+ if (hit & PK_RIGHT) sv.p.paint = (uint8_t)((sv.p.paint + 1) % PT_PAINTS);+ if (hit & (PK_UP | PK_DOWN)) sv.p.view ^= 1;+ if (hit & (PK_BACK | PK_OK)) save(), ui.screen = V_TITLE, ui.sel = MENU_CAR;break;case V_GUIDE:- if ((hit & PK_RIGHT) && ui.page + 1 < PG_HELP_PAGES) ui.page++;+ if ((hit & PK_RIGHT) && ui.page + 1 < PT_HELP_PAGES) ui.page++;if ((hit & PK_LEFT) && ui.page) ui.page--;- if (hit & PK_BACK) ui.screen = V_SETUP, ui.sel = SET_START;- else if (hit & PK_OK) sv.p.guide = 1, race_begin();+ if (hit & PK_BACK) ui.screen = V_TRACKS;+ else if (hit & PK_OK) {+ if (ui.page + 1 < PT_HELP_PAGES) ui.page++;+ else sv.p.guide = 1, save(), race_begin();+ }break;case V_HELP:- if ((hit & PK_RIGHT) && ui.page + 1 < PG_HELP_PAGES) ui.page++;+ if ((hit & PK_RIGHT) && ui.page + 1 < PT_HELP_PAGES) ui.page++;if ((hit & PK_LEFT) && ui.page) ui.page--;if (hit & (PK_BACK | PK_OK)) {if (ui.under == V_PAUSE) ui.screen = V_PAUSE, ui.sel = PAUSE_HELP;- else to_title(), ui.sel = (uint8_t)(ui.menu_n - 1);+ else ui.screen = V_TITLE, ui.sel = MENU_HELP;}break;- case V_RECORDS:- if (hit & (PK_BACK | PK_OK)) to_title(), ui.sel = (uint8_t)(ui.menu_n - 2);- break;case V_PAUSE:if (hit & PK_UP) ui.sel = (uint8_t)((ui.sel + PAUSE_ROWS - 1) % PAUSE_ROWS);if (hit & PK_DOWN) ui.sel = (uint8_t)((ui.sel + 1) % PAUSE_ROWS);if (hit & PK_BACK) ui.screen = V_RACE;else if (hit & PK_OK) switch (ui.sel) {case PAUSE_RESUME: ui.screen = V_RACE; break;- case PAUSE_RESTART: use_race_settings(), race_begin(); break;+ case PAUSE_RESTART: race_begin(); break;case PAUSE_HELP: ui.screen = V_HELP, ui.page = 0, ui.under = V_PAUSE; break;default: ui.screen = V_LEAVE, ui.sel = 0; break;}@@ -299,17 +224,24 @@ static bool keys_menu(uint32_t hit) {if (hit & PK_BACK) ui.screen = V_PAUSE, ui.sel = PAUSE_QUIT;else if (hit & PK_OK) {if (ui.sel == 0) ui.screen = V_RACE;- else if (ui.sel == 1) save(), to_title();- else return true;+ else if (ui.sel == 1) {+ ui.screen = V_TRACKS;+ ui.tab = (uint8_t)pt_tracks[sv.p.track].env;+ ui.sel = (uint8_t)tab_row_of(sv.p.track);+ } else return true;}break;case V_RESULT:- if (hit & (PK_UP | PK_DOWN)) ui.sel ^= 1;- if (hit & PK_OK) {- if (ui.sel == 0) {- use_race_settings(), race_begin();- } else {- to_title();+ if (hit & PK_UP) ui.sel = (uint8_t)((ui.sel + RES_ROWS - 1) % RES_ROWS);+ if (hit & PK_DOWN) ui.sel = (uint8_t)((ui.sel + 1) % RES_ROWS);+ if (hit & PK_RESTART) race_begin();+ else if (hit & PK_OK) {+ if (ui.sel == RES_AGAIN) race_begin();+ else if (ui.sel == RES_NEXT) sv.p.track = (uint8_t)((sv.p.track + 1) % PT_NTRACKS), save(), race_begin();+ else {+ ui.screen = V_TRACKS;+ ui.tab = (uint8_t)pt_tracks[sv.p.track].env;+ ui.sel = (uint8_t)tab_row_of(sv.p.track);}}break;@@ -318,31 +250,20 @@ static bool keys_menu(uint32_t hit) {}/* ------------------------------------------------------------------ the loop */-static unsigned race_input(uint32_t keys) {- unsigned in = 0;- if (keys & PK_UP) in |= IN_GAS;- if (keys & PK_DOWN) in |= IN_BRAKE;- if (keys & PK_LEFT) in |= IN_LEFT;- if (keys & PK_RIGHT) in |= IN_RIGHT;- if (keys & PK_OK) in |= IN_NITRO;- return in;-}--static bool race_over(const pg_race *r) {- return r->phase == PH_DONE && r->done >= (r->mode == MODE_ENDLESS ? 2 * PG_HZ + PG_HZ / 2 : 3 * PG_HZ);-}-int main(void) {plat_begin();memset(&ui, 0, sizeof ui);now = plat_millis();save_load(&sv);- if (sv.has_race) show_race(&sv.race);- to_title();+ ghosts_load();+ world_load(sv.p.track);+ car_reset(&car);+ ui.screen = V_TITLE;uint32_t stale = plat_keys(), prev_keys = stale, rep_at = 0, last = now, frame_at = 0, spin0 = now;uint8_t shown = 0xFF;bool dirty = true;- uint32_t min_frame = frame_gap ? frame_gap : plat_slow() ? 33 : 20;+ uint32_t min_frame = frame_gap ? frame_gap : plat_slow() ? 33 : 25;+ uint32_t slow_frames = 0, quick_frames = 0;for (;;) {now = plat_millis();uint32_t dt = now - last;@@ -358,63 +279,68 @@ int main(void) {}prev_keys = live;if (keys & PK_HOME) break; /* Home (or On/Off): saved below, then out */- if (hit && ui.screen != V_RACE) dirty = true; /* (a race is drawn at its own pace) */+ if (hit && ui.screen != V_RACE) dirty = true;bool quit = false;+ ui.clock = now - spin0;if (ui.screen == V_RACE) {if (hit & PK_BACK) {ui.screen = V_PAUSE, ui.sel = PAUSE_RESUME;- save();- } else if (ui.hold) {- if ((int32_t)(now - hold_at) >= 0) ui.hold--, hold_at = now + 500, dirty = true;- prev = sv.race;+ } else if (hit & PK_RESTART) {+ race_begin();} else {- if (hit & PK_GEAR_UP) pending_shift = 1;- if (hit & PK_GEAR_DOWN) pending_shift = -1;- accum += (int32_t)dt;- unsigned in = race_input(live);- while (accum >= PG_TICK) {- prev = sv.race;- int lap = sv.race.lap;- pg_step(&sv.race, &track, in, pending_shift);- pending_shift = 0;- accum -= PG_TICK;- ghost_after_step(lap);- if (race_over(&sv.race)) {- finish_race();- break;- }- }- if (ui.screen == V_RACE && (int32_t)(now - saved_at) >= 30000) save();+ if (hit & PK_VIEW) sv.p.view ^= 1;+ step_race(live, hit, dt);+ if (car.finish && ui.finish_at && ui.clock - ui.finish_at > 2000 && ui.screen == V_RACE)+ ui.screen = V_RESULT, ui.sel = RES_AGAIN;}+ } else if (ui.screen == V_RESULT) {+ /* (the car rolls on behind the results) */+ step_race(0, 0, dt);+ quit = keys_menu(hit);} else {quit = keys_menu(hit);}if (quit) break;if (ui.screen != shown) {stale = keys, prev_keys = 0; /* a new screen starts with all keys up */- if (ui.screen != V_RACE) accum = 0;- if (ui.screen == V_SETUP && sv.p.mode == MODE_RACE) show_circuit(sv.p.track);- if (ui.screen == V_RACE || ui.screen == V_PAUSE || ui.screen == V_RESULT) show_race(&sv.race);shown = ui.screen;dirty = true;}- bool moving = ui.screen == V_RACE || ui.screen == V_TITLE || ui.screen == V_QUIT;+ bool moving = ui.screen == V_RACE || ui.screen == V_RESULT || ui.screen == V_TITLE || ui.screen == V_QUIT ||+ ui.screen == V_CAR;if (dirty || (moving && now - frame_at >= min_frame)) {uint32_t t0 = plat_millis();- ui.clock = now - spin0;- int alpha = accum >= PG_TICK ? 256 : accum * 256 / PG_TICK;- if (ui.screen != V_RACE || ui.hold) alpha = 256;- ghost_pose(alpha);+ float fdt = (float)(now - frame_at) / 1000.0f;+ if (fdt > 0.1f) fdt = 0.1f;+ look = car_look_of(&car);+ look.paint = sv.p.paint;+ if (sv.p.view) cockpit_camera(&cam, look.pos, look.rot, car.speed);+ else chase_update(&chase, &cam, fdt, look.pos, look.rot, car.speed);+ ghost_look.ghost = 0;+ v3 gp;+ qt gr;+ if (ui.started && ghost_at(&gplay, car.frames, &gp, &gr)) {+ memset(&ghost_look, 0, sizeof ghost_look);+ ghost_look.pos = gp, ghost_look.rot = gr, ghost_look.ghost = 1, ghost_look.paint = sv.p.paint;+ for (int i = 0; i < 4; i++) ghost_look.susp[i] = 0.078f;+ }plat_vblank();- pg_render(&sv, &track, &prev, &sv.race, alpha, &ui, &ghost_now);+ pt_render(&sv, &car, &cam, &look, ghost_look.ghost ? &ghost_look : NULL, &ui);uint32_t spent = plat_millis() - t0;perf_frames++;if (spent > perf_max) perf_max = spent;if (spent > 33) perf_slow++;+ /* the picture's detail follows the time it takes: down at once when slow, up slowly */+ if (ui.screen == V_RACE) {+ if (spent > 30) slow_frames++, quick_frames = 0;+ else if (spent < 18) quick_frames++, slow_frames = 0;+ if (slow_frames >= 2 && rd_detail > 0) rd_detail--, slow_frames = 0;+ if (quick_frames >= 30 && rd_detail < 3) rd_detail++, quick_frames = 0;+ }frame_at = now;dirty = false;} else {- plat_sleep(moving ? 2 : 10);+ plat_sleep(moving ? 1 : 10);}}save();diff --git a/games/polytrack/src/plat.h b/games/polytrack/src/plat.hindex bbdbcad3..0b71ee69 100644--- a/games/polytrack/src/plat.h+++ b/games/polytrack/src/plat.h@@ -1,13 +1,13 @@/* What the game needs from the calculator (plat_eadk.c), or from a computer for the tests. */-#ifndef PG_PLAT_H-#define PG_PLAT_H+#ifndef PT_PLAT_H+#define PT_PLAT_H#include <stdbool.h>#include <stdint.h>/* (PK_: NumPlay's np.h has K_ keys of its own) */enum {- PK_OK = 1, PK_UP = 2, PK_DOWN = 4, PK_LEFT = 8, PK_RIGHT = 16, PK_BACK = 32, PK_HOME = 64, PK_GEAR_UP = 128,- PK_GEAR_DOWN = 256+ PK_OK = 1, PK_UP = 2, PK_DOWN = 4, PK_LEFT = 8, PK_RIGHT = 16, PK_BACK = 32, PK_HOME = 64, PK_RESTART = 128,+ PK_VIEW = 256};uint32_t plat_keys(void);uint32_t plat_millis(void);@@ -16,7 +16,6 @@ void plat_push(int x, int y, int w, int h, const uint16_t *px);void plat_vblank(void);bool plat_save(const char *name, const void *data, uint32_t len);const uint8_t *plat_load(const char *name, uint32_t *len);-uint32_t plat_random(void);bool plat_slow(void); /* an N0110 or N0115 */void plat_begin(void);int plat_end(void);diff --git a/games/polytrack/src/plat_eadk.c b/games/polytrack/src/plat_eadk.cindex d3e890c6..6b0b92ec 100644--- a/games/polytrack/src/plat_eadk.c+++ b/games/polytrack/src/plat_eadk.c@@ -4,7 +4,7 @@#include "../../common/epsilon_files.h"#include "plat.h"-const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "PolyGT 3D";+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "PolyTrack";const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;#define KEY(k) ((uint64_t)1 << (k))@@ -17,10 +17,10 @@ uint32_t plat_keys(void) {if (k & (KEY(eadk_key_down) | KEY(eadk_key_two))) r |= PK_DOWN;if (k & (KEY(eadk_key_left) | KEY(eadk_key_four))) r |= PK_LEFT;if (k & (KEY(eadk_key_right) | KEY(eadk_key_six))) r |= PK_RIGHT;- if (k & (KEY(eadk_key_back) | KEY(eadk_key_backspace))) r |= PK_BACK;+ if (k & KEY(eadk_key_back)) r |= PK_BACK;+ if (k & KEY(eadk_key_backspace)) r |= PK_RESTART;if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) r |= PK_HOME;- if (k & KEY(eadk_key_plus)) r |= PK_GEAR_UP;- if (k & KEY(eadk_key_minus)) r |= PK_GEAR_DOWN;+ if (k & KEY(eadk_key_toolbox)) r |= PK_VIEW;return r;}uint32_t plat_millis(void) { return (uint32_t)eadk_timing_millis(); }@@ -31,7 +31,6 @@ void plat_push(int x, int y, int w, int h, const uint16_t *px) {void plat_vblank(void) { eadk_display_wait_for_vblank(); }bool plat_save(const char *name, const void *data, uint32_t len) { return ef_write(name, data, len); }const uint8_t *plat_load(const char *name, uint32_t *len) { return ef_read(name, len); }-uint32_t plat_random(void) { return eadk_random(); }bool plat_slow(void) { return epsilon_slow_model(); }void plat_begin(void) { np_app_begin(); }int plat_end(void) { return np_app_end(); }diff --git a/games/polytrack/src/render.c b/games/polytrack/src/render.cindex ef6f3575..5d282752 100644--- a/games/polytrack/src/render.c+++ b/games/polytrack/src/render.c@@ -45,7 +45,7 @@ static uint8_t srgb[1025];static uint16_t back_lut[256];static float fog_rgb[3];-const uint32_t rd_paints[8] = {0x6B0B0B, 0x0B2D6B, 0x0F5223, 0x4A1166, 0x6B3A0B, 0x0B5A5A, 0x1A1A1A, 0x8C8C8C};+const uint32_t rd_paints[8] = {0x990000, 0x003399, 0x00802B, 0x5C0099, 0x994C00, 0x007A7A, 0x262626, 0x8C8C8C};/* ------------------------------------------------------------------ colours */static float lin_of(int c8) {@@ -545,49 +545,56 @@ void rd_showroom(int paint, float angle, int env) {}/* ------------------------------------------------------------------ drawing a strip */-static uint16_t zbuf[SCREEN_W * STRIP_ROWS];+static uint16_t zbuf[SCREEN_W * STRIP_ROWS] __attribute__((aligned(4)));-static void background(int ys, int ye) {- /* the view ray's height, per 16 pixels: dir = right (x - CX)/f + up (CY - y)/f + forward */- float rx = C.right.y / focal, uy = C.up.y / focal, fy = C.fwd.y;- float r2[2] = {C.right.x, C.right.z};- (void)r2;+__attribute__((noinline)) static void background(int ys, int ye) {+ /* the view ray's height, every 32 pixels (in between, a straight line): dir = right (x - CX)/f + up (CY - y)/f + fwd;+ and the depth buffer cleared */+ float rx = C.right.y / focal, uy = C.up.y / focal, fy = C.fwd.y, ff = 1.0f / (focal * focal);for (int y = ys; y < ye; y++) {uint16_t *row = gfx_buf + (y - ys) * SCREEN_W;+ uint32_t *z = (uint32_t *)(zbuf + (y - ys) * SCREEN_W);+ for (int x = 0; x < SCREEN_W / 2; x++) z[x] = 0;float yy = CY - ((float)y + 0.5f);- float base = uy * yy + fy;- float prev_idx = 0.0f;- for (int x = 0; x <= SCREEN_W; x += 16) {+ float base = uy * yy + fy, yy2 = yy * yy * ff + 1.0f;+ int32_t prev = 0;+ for (int x = 0; x <= SCREEN_W; x += 32) {float xx = (float)x - CX;- float dy = rx * xx + base;- float len2 = (xx * xx + yy * yy) / (focal * focal) + 1.0f;- float n = dy / pt_sqrtf(len2);- float idx = (n * 127.5f + 127.5f);+ float n = (rx * xx + base) / pt_sqrtf(xx * xx * ff + yy2);+ int32_t idx = (int32_t)((n * 127.5f + 127.5f) * 65536.0f);if (x > 0) {- float d = (idx - prev_idx) / 16.0f, f = prev_idx;- for (int k = x - 16; k < x; k++, f += d) {- int i = (int)f;- row[k] = back_lut[i < 0 ? 0 : i > 255 ? 255 : i];+ int32_t d = (idx - prev) / 32, f = prev;+ uint16_t *o = row + x - 32;+ if ((prev >> 16) == (idx >> 16) && prev >= 0 && prev < (256 << 16)) {+ uint16_t c = back_lut[prev >> 16];+ for (int k = 0; k < 32; k++) o[k] = c;+ } else {+ for (int k = 0; k < 32; k++, f += d) {+ int i = f >> 16;+ o[k] = back_lut[i < 0 ? 0 : i > 255 ? 255 : i];+ }}}- prev_idx = idx;+ prev = idx;}}}-static void raster(const tri *t, int ys, int ye) {+__attribute__((noinline)) static void raster(const tri *t, int ys, int ye) {float x0 = t->x[0] * (1.0f / 16), y0 = t->y[0] * (1.0f / 16), x1 = t->x[1] * (1.0f / 16), y1 = t->y[1] * (1.0f / 16),x2 = t->x[2] * (1.0f / 16), y2 = t->y[2] * (1.0f / 16);int ta = iceil(y0 - 0.5f), tb = iceil(y2 - 0.5f);int ra = ta > ys ? ta : ys, rb = tb < ye ? tb : ye;if (ra >= rb) return;- float w0 = t->w[0] * (1.0f / 65535), w1 = t->w[1] * (1.0f / 65535), w2 = t->w[2] * (1.0f / 65535);+ float w0 = t->w[0] * (1.0f / 65536), w1 = t->w[1] * (1.0f / 65536), w2 = t->w[2] * (1.0f / 65536);float dx1 = x1 - x0, dy1 = y1 - y0, dx2 = x2 - x0, dy2 = y2 - y0;float det = dx1 * dy2 - dx2 * dy1;if (det > -0.01f && det < 0.01f) return;- float B = ((w1 - w0) * dy2 - (w2 - w0) * dy1) / det, Cc = (dx1 * (w2 - w0) - dx2 * (w1 - w0)) / det;+ float idet = 1.0f / det;+ float B = ((w1 - w0) * dy2 - (w2 - w0) * dy1) * idet, Cc = (dx1 * (w2 - w0) - dx2 * (w1 - w0)) * idet;float s02 = (x2 - x0) / (y2 - y0);float s01 = y1 > y0 ? (x1 - x0) / (y1 - y0) : 0, s12 = y2 > y1 ? (x2 - x1) / (y2 - y1) : 0;+ int32_t dq = (int32_t)(B * 1073741824.0f);uint16_t col = t->c;int kind = t->kind;for (int r = ra; r < rb; r++) {@@ -595,7 +602,8 @@ static void raster(const tri *t, int ys, int ye) {float xl = x0 + (yc - y0) * s02;float xs = yc < y1 ? x0 + (yc - y0) * s01 : x1 + (yc - y1) * s12;float xa = xl < xs ? xl : xs, xb = xl < xs ? xs : xl;- xa = pt_clampf(xa, -1.0f, 321.0f), xb = pt_clampf(xb, -1.0f, 321.0f);+ if (xa < -1.0f) xa = -1.0f;+ if (xb > 321.0f) xb = 321.0f;int pa = iceil(xa - 0.5f), pb = iceil(xb - 0.5f);if (pa < 0) pa = 0;if (pb > SCREEN_W) pb = SCREEN_W;@@ -606,25 +614,28 @@ static void raster(const tri *t, int ys, int ye) {continue;}float wa = w0 + B * ((float)pa + 0.5f - x0) + Cc * (yc - y0);- float wb = w0 + B * ((float)pb - 0.5f - x0) + Cc * (yc - y0);- int32_t qa = (int32_t)(pt_clampf(wa, 0, 1) * 1073741824.0f), qb = (int32_t)(pt_clampf(wb, 0, 1) * 1073741824.0f);+ if (wa < 0.0f) wa = 0.0f;+ if (wa > 0.99998f) wa = 0.99998f;+ int32_t qa = (int32_t)(wa * 1073741824.0f), d = dq;int n = pb - pa;- int32_t dq = n > 1 ? (qb - qa) / (n - 1) : 0;- uint16_t *z = zbuf + (r - ys) * SCREEN_W;+ int32_t qe = qa + d * (n - 1);+ if (n > 1 && (qe < 0 || qe > 1073725440)) d = ((qe < 0 ? 0 : 1073725440) - qa) / (n - 1);+ uint16_t *z = zbuf + (r - ys) * SCREEN_W + pa;+ p += pa;if (kind == RK_SOLID) {- for (int x = pa; x < pb; x++, qa += dq) {- uint16_t q = (uint16_t)(qa >> 14 > 65535 ? 65535 : qa >> 14);- if (q > z[x]) z[x] = q, p[x] = col;+ for (int x = 0; x < n; x++, qa += d) {+ uint32_t q = (uint32_t)qa >> 14;+ if (q > z[x]) z[x] = (uint16_t)q, p[x] = col;}} else if (kind == RK_GHOST) {- for (int x = pa; x < pb; x++, qa += dq) {- if ((x + r) & 1) continue;- uint16_t q = (uint16_t)(qa >> 14 > 65535 ? 65535 : qa >> 14);+ int odd = (pa + r) & 1;+ for (int x = odd; x < n; x += 2) {+ uint32_t q = (uint32_t)(qa + d * x) >> 14;if (q > z[x]) p[x] = col;}} else {- for (int x = pa; x < pb; x++, qa += dq) {- int q = qa >> 14;+ for (int x = 0; x < n; x++, qa += d) {+ uint32_t q = (uint32_t)qa >> 14;if (q + 24 >= z[x]) {uint16_t c = p[x];/* 60 % of the sun taken away: about five eighths of the colour */@@ -635,17 +646,45 @@ static void raster(const tri *t, int ys, int ye) {}}+/* the triangles by the strip they start in, and those still going on */+static uint16_t order[MAX_TRIS], active[MAX_TRIS];+static uint16_t strip_start[240 / STRIP_ROWS + 2];+static int nactive, next_order;++static int strip_of(int16_t y16) {+ int r = iceil((float)y16 * (1.0f / 16) - 0.5f);+ if (r < 0) r = 0;+ if (r > 239) r = 239;+ return r / STRIP_ROWS;+}+void rd_draw(void) {int ys = gfx_y0, ye = gfx_y1;rd_tris = ntris;background(ys, ye);- memset(zbuf, 0, sizeof(uint16_t) * (size_t)SCREEN_W * (size_t)(ye - ys));+ int s = ys / STRIP_ROWS;+ if (ys == 0) {+ int cnt[240 / STRIP_ROWS + 2] = {0};+ for (int i = 0; i < ntris; i++) cnt[strip_of(tris[i].y[0])]++;+ int acc = 0;+ for (int k = 0; k < 240 / STRIP_ROWS + 1; k++) strip_start[k] = (uint16_t)acc, acc += cnt[k];+ strip_start[240 / STRIP_ROWS + 1] = (uint16_t)acc;+ int pos[240 / STRIP_ROWS + 2];+ for (int k = 0; k < 240 / STRIP_ROWS + 2; k++) pos[k] = strip_start[k];+ for (int i = 0; i < ntris; i++) order[pos[strip_of(tris[i].y[0])]++] = (uint16_t)i;+ nactive = 0, next_order = 0;+ }+ /* the ones that ended above this strip go; the ones starting in it come */+ int m = 0;+ for (int k = 0; k < nactive; k++)+ if (strip_of(tris[active[k]].y[2]) >= s) active[m++] = active[k];+ nactive = m;+ for (; next_order < strip_start[s + 1 > 240 / STRIP_ROWS + 1 ? 240 / STRIP_ROWS + 1 : s + 1]; next_order++)+ active[nactive++] = order[next_order];for (int pass = 0; pass < 3; pass++)- for (int i = 0; i < ntris; i++) {- const tri *t = &tris[i];- int k = t->kind == RK_BACK ? 0 : t->kind == RK_SHADOW ? 2 : 1;- if (k != pass) continue;- if (t->y[2] < ys * 16 - 8 || t->y[0] > ye * 16 + 8) continue;- raster(t, ys, ye);+ for (int k = 0; k < nactive; k++) {+ const tri *t = &tris[active[k]];+ int kd = t->kind == RK_BACK ? 0 : t->kind == RK_SHADOW ? 2 : 1;+ if (kd == pass) raster(t, ys, ye);}}diff --git a/games/polytrack/src/save.c b/games/polytrack/src/save.cindex 9310b28c..bad56a11 100644--- a/games/polytrack/src/save.c+++ b/games/polytrack/src/save.c@@ -1,54 +1,51 @@-/* The save (save.h): checked field by field; anything damaged, cut short or from elsewhere is not read: the copy in- * the Python script is tried, then a fresh start. */+/* The saves (save.h): checked field by field; anything damaged, cut short or from elsewhere is not read: the copy in+ * the Python script is tried, then a fresh start. The ghosts' file is its own: when it is damaged the ghosts are+ * simply gone. */#include <stddef.h>#include <string.h>#include "plat.h"#include "save.h"-void pg_fresh(pg_profile *p) {- memset(p, 0, sizeof *p);- p->laps = 3, p->rivals = 5, p->level = LEVEL_NORMAL;+uint32_t pt_sum(const void *data, uint32_t n) {+ const uint8_t *p = data;+ uint32_t h = 2166136261u;+ for (uint32_t i = 0; i < n; i++) h = (h ^ p[i]) * 16777619u;+ return h;}-static bool profile_ok(const pg_profile *p) {- if (p->races > 999999 || p->wins > p->races || p->runs > 999999) return false;- for (int i = 0; i < PG_CIRCUITS; i++) {- if (p->best_ms[i] > PG_MAX_TIME || p->best_lap_ms[i] > PG_MAX_TIME) return false;- if (p->best_ms[i] && (!p->best_lap_ms[i] || p->best_lap_ms[i] > p->best_ms[i])) return false;+void pt_fresh(pt_profile *p) { memset(p, 0, sizeof *p); }++static bool profile_ok(const pt_profile *p) {+ for (int t = 0; t < PT_NTRACKS; t++) {+ if (p->best[t] > PT_MAX_TIME) return false;+ for (int k = 0; k < PT_SPLITS; k++) {+ uint32_t s = p->split[t][k];+ if (s > PT_MAX_TIME || (s && (!p->best[t] || s > p->best[t]))) return false;+ if (k && s && s < p->split[t][k - 1]) return false;+ }}- if (p->best_m > PG_MAX_M || p->best_zone > 9999 || (p->best_zone && !p->best_m)) return false;- return p->mode <= MODE_ENDLESS && p->track < PG_CIRCUITS && p->vehicle < PG_VEHICLES && p->laps >= 1 &&- p->laps <= PG_MAX_LAPS && p->rivals <= PG_CARS - 1 && p->level <= LEVEL_HARD && p->manual <= 1 &&- p->view < VIEWS && p->guide <= 1 && !p->spare[0] && !p->spare[1] && !p->spare[2];+ return p->track < PT_NTRACKS && p->paint < PT_PAINTS && p->view <= 1 && p->guide <= 1;}-bool pg_file_ok(const pg_file *f) {- if (f->magic != PG_MAGIC || f->version != PG_VERSION || f->size != sizeof *f) return false;- if (f->sum != pg_sum(f, offsetof(pg_file, sum))) return false;- if (f->spare[0] || f->spare[1] || f->spare[2] || f->has_race > 1 || !profile_ok(&f->p)) return false;- if (!f->has_race) {- const uint8_t *b = (const uint8_t *)&f->race;- for (unsigned i = 0; i < sizeof f->race; i++)- if (b[i]) return false;- return true;- }- return pg_valid(&f->race, NULL);+bool pt_file_ok(const pt_file *f) {+ if (f->magic != PT_MAGIC || f->version != PT_VERSION || f->size != sizeof *f) return false;+ if (f->sum != pt_sum(f, offsetof(pt_file, sum))) return false;+ return profile_ok(&f->p);}-static const char head[] = "# PolyGT 3D keeps a copy of your progress here,\n"+static const char head[] = "# PolyTrack keeps a copy of your progress here,\n""# so that installing it again doesn't erase it.\n";static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";-static uint8_t copy[1 + sizeof head + 2 + sizeof PG_SAVE_NAME + 1 + (sizeof(pg_file) + 2) / 3 * 4 + 2];+static uint8_t copy[1 + sizeof head + 2 + sizeof PT_SAVE_NAME + 1 + (sizeof(pt_file) + 2) / 3 * 4 + 2];-/* the copy: the file in base 64, in a comment line of a script */-static bool copy_write(const pg_file *f) {+static bool copy_write(const pt_file *f) {const uint8_t *bytes = (const uint8_t *)f;- uint32_t len = sizeof *f, nl = sizeof PG_SAVE_NAME - 1;+ uint32_t len = sizeof *f, nl = sizeof PT_SAVE_NAME - 1;uint8_t *p = copy;*p++ = 0; /* (a script's first byte: not imported) */memcpy(p, head, sizeof head - 1), p += sizeof head - 1;*p++ = '#', *p++ = '>';- memcpy(p, PG_SAVE_NAME, nl), p += nl;+ memcpy(p, PT_SAVE_NAME, nl), p += nl;*p++ = ':';for (uint32_t i = 0; i < len; i += 3, p += 4) {uint32_t left = len - i;@@ -59,7 +56,7 @@ static bool copy_write(const pg_file *f) {p[3] = left > 2 ? (uint8_t)b64[v & 63] : '=';}*p++ = '\n';- return plat_save(PG_COPY_NAME, copy, (uint32_t)(p - copy));+ return plat_save(PT_COPY_NAME, copy, (uint32_t)(p - copy));}static int b64v(uint8_t c) {@@ -68,12 +65,12 @@ static int b64v(uint8_t c) {return -1;}-static bool copy_read(pg_file *f) {- uint32_t n, nl = sizeof PG_SAVE_NAME - 1;- const uint8_t *c = plat_load(PG_COPY_NAME, &n);+static bool copy_read(pt_file *f) {+ uint32_t n, nl = sizeof PT_SAVE_NAME - 1;+ const uint8_t *c = plat_load(PT_COPY_NAME, &n);if (!c) return false;for (uint32_t i = 0; i + nl + 3 <= n; i++) {- if (c[i] != '#' || c[i + 1] != '>' || memcmp(c + i + 2, PG_SAVE_NAME, nl) || c[i + 2 + nl] != ':') continue;+ if (c[i] != '#' || c[i + 1] != '>' || memcmp(c + i + 2, PT_SAVE_NAME, nl) || c[i + 2 + nl] != ':') continue;const uint8_t *l = c + i + 3 + nl;uint32_t m = 0;while (l + m < c + n && l[m] != '\n' && l[m]) m++;@@ -94,33 +91,122 @@ static bool copy_read(pg_file *f) {return false;}-bool save_load(pg_file *f) {+bool save_load(pt_file *f) {uint32_t n;- const uint8_t *d = plat_load(PG_SAVE_NAME, &n);+ const uint8_t *d = plat_load(PT_SAVE_NAME, &n);bool ok = false;if (d && n == sizeof *f) {memcpy(f, d, sizeof *f);- ok = pg_file_ok(f);+ ok = pt_file_ok(f);}- if (!ok && copy_read(f) && pg_file_ok(f)) {+ if (!ok && copy_read(f) && pt_file_ok(f)) {ok = true;- plat_save(PG_SAVE_NAME, f, sizeof *f); /* back where it belongs */+ plat_save(PT_SAVE_NAME, f, sizeof *f); /* back where it belongs */}if (!ok) {memset(f, 0, sizeof *f);- pg_fresh(&f->p);+ pt_fresh(&f->p);}return ok;}-static pg_file out; /* (static: the stack stays small) */-bool save_write(const pg_file *f) {+static pt_file out; /* (static: the stack stays small) */+bool save_write(const pt_file *f) {out = *f;- out.magic = PG_MAGIC, out.version = PG_VERSION, out.size = sizeof out;- memset(out.spare, 0, sizeof out.spare);- if (!out.has_race) memset(&out.race, 0, sizeof out.race); /* (a race over is not kept) */- out.sum = pg_sum(&out, offsetof(pg_file, sum));- bool ok = plat_save(PG_SAVE_NAME, &out, sizeof out);+ out.magic = PT_MAGIC, out.version = PT_VERSION, out.size = sizeof out;+ out.sum = pt_sum(&out, offsetof(pt_file, sum));+ bool ok = plat_save(PT_SAVE_NAME, &out, sizeof out);copy_write(&out);return ok;}++/* ------------------------------------------------------------------ ghosts:+ "PTG1", version (u16), count (u16), then per ghost: track (u8), pad (u8), length (u16), time (u32), bytes;+ then the sum of everything before it */+static uint8_t gfile[PT_GHOST_BYTES];+static uint32_t glen;++static bool gfile_ok(const uint8_t *d, uint32_t n) {+ if (n < 12 || n > PT_GHOST_BYTES) return false;+ uint32_t magic;+ memcpy(&magic, d, 4);+ if (magic != PT_GMAGIC || (d[4] | d[5] << 8) != PT_VERSION) return false;+ uint32_t sum;+ memcpy(&sum, d + n - 4, 4);+ if (sum != pt_sum(d, n - 4)) return false;+ int count = d[6] | d[7] << 8;+ uint32_t o = 8;+ for (int i = 0; i < count; i++) {+ if (o + 8 > n - 4) return false;+ if (d[o] >= PT_NTRACKS) return false;+ uint32_t len = (uint32_t)(d[o + 2] | d[o + 3] << 8);+ uint32_t ms;+ memcpy(&ms, d + o + 4, 4);+ if (!len || len > PT_GHOST_MAX || ms > PT_MAX_TIME) return false;+ o += 8 + len;+ }+ return o == n - 4;+}++void ghosts_load(void) {+ uint32_t n;+ const uint8_t *d = plat_load(PT_GHOST_NAME, &n);+ glen = 0;+ if (d && gfile_ok(d, n)) {+ memcpy(gfile, d, n);+ glen = n;+ }+}++bool ghosts_find(int track, ghost_entry *g) {+ if (!glen) return false;+ int count = gfile[6] | gfile[7] << 8;+ uint32_t o = 8;+ for (int i = 0; i < count; i++) {+ uint32_t len = (uint32_t)(gfile[o + 2] | gfile[o + 3] << 8);+ if (gfile[o] == track) {+ g->track = (uint8_t)track, g->len = (uint16_t)len;+ memcpy(&g->ms, gfile + o + 4, 4);+ g->data = gfile + o + 8;+ return true;+ }+ o += 8 + len;+ }+ return false;+}++bool ghosts_put(int track, uint32_t ms, const uint8_t *data, uint16_t len) {+ if (!len || len > PT_GHOST_MAX) return false;+ /* the entries kept: the others, the last raced first, while they fit after the new one */+ int count = 0;+ uint32_t end = 8;+ if (glen) {+ int old = gfile[6] | gfile[7] << 8;+ uint32_t q = 8;+ for (int i = 0; i < old; i++) {+ uint32_t l = (uint32_t)(gfile[q + 2] | gfile[q + 3] << 8);+ if (gfile[q] != track && end + 8 + l + 8 + len + 4 <= PT_GHOST_BYTES) {+ memmove(gfile + end, gfile + q, 8 + l);+ end += 8 + l;+ count++;+ }+ q += 8 + l;+ }+ }+ /* room at the front */+ uint32_t shift = 8 + (uint32_t)len;+ memmove(gfile + 8 + shift, gfile + 8, end - 8);+ end += shift;+ uint8_t *e = gfile + 8;+ e[0] = (uint8_t)track, e[1] = 0, e[2] = (uint8_t)len, e[3] = (uint8_t)(len >> 8);+ memcpy(e + 4, &ms, 4);+ memcpy(e + 8, data, len);+ count++;+ uint32_t magic = PT_GMAGIC;+ memcpy(gfile, &magic, 4);+ gfile[4] = PT_VERSION, gfile[5] = 0, gfile[6] = (uint8_t)count, gfile[7] = (uint8_t)(count >> 8);+ uint32_t sum = pt_sum(gfile, end);+ memcpy(gfile + end, &sum, 4);+ glen = end + 4;+ return plat_save(PT_GHOST_NAME, gfile, glen);+}diff --git a/games/polytrack/src/save.h b/games/polytrack/src/save.hindex e3e1b41c..81571211 100644--- a/games/polytrack/src/save.h+++ b/games/polytrack/src/save.h@@ -1,38 +1,57 @@-/* What PolyGT 3D keeps, in polygt3d.sav: your choices on the race screen, your records and the race you left. A copy- * goes into a Python script, polygt3d_saves.py (installing apps from the NumWorks website keeps only scripts, so the- * save comes back from it). One format: a magic, a version, the size and a checksum; anything else is not read, and- * the game starts afresh. */-#ifndef PG_SAVE_H-#define PG_SAVE_H-#include "game.h"+/* What PolyTrack keeps (save.c): in polytrack.sav your best time on each track and its checkpoint times, the car's+ * colour, the view and whether you read the guide; a copy goes into a Python script, polytrack_saves.py (installing+ * apps from the NumWorks website keeps only scripts, so the save comes back from it). The ghosts of your best runs+ * go into polytrack_ghosts.sav, as many as fit in 12 KB, the last ones raced first.+ * Each file: a magic, a version, its size and a checksum; anything else is not read, and the game starts afresh. */+#ifndef PT_SAVE_H+#define PT_SAVE_H+#include <stdbool.h>+#include <stdint.h>+#include "data.h"-#define PG_SAVE_NAME "polygt3d.sav"-#define PG_COPY_NAME "polygt3d_saves.py"-#define PG_MAGIC 0x31544750u /* "PGT1" */-#define PG_VERSION 1-#define PG_MAX_TIME (99u * 60000u)-#define PG_MAX_M 2000000u /* (2000 km) */+#define PT_SAVE_NAME "polytrack.sav"+#define PT_COPY_NAME "polytrack_saves.py"+#define PT_GHOST_NAME "polytrack_ghosts.sav"+#define PT_MAGIC 0x314B5450u /* "PTK1" */+#define PT_GMAGIC 0x31475450u /* "PTG1" */+#define PT_VERSION 1+#define PT_SPLITS 10 /* checkpoint orders on a track, at most */+#define PT_MAX_TIME 5999998u /* (the game's own limit, 1 ms frames) */+#define PT_PAINTS 8+#define PT_GHOST_BYTES 12288 /* the ghosts' file */+#define PT_GHOST_MAX 8192 /* one ghost */typedef struct {- uint32_t races, wins, runs; /* races finished, won; endless runs */- uint32_t best_ms[PG_CIRCUITS], best_lap_ms[PG_CIRCUITS];- uint32_t best_m; /* the endless road: the furthest (metres)... */- uint16_t best_zone; /* ...and zones */- uint8_t mode, track, vehicle, laps, rivals, level, manual, view, guide, spare[3];-} pg_profile;+ uint32_t best[PT_NTRACKS]; /* ms, 0: not finished yet */+ uint32_t split[PT_NTRACKS][PT_SPLITS]; /* the best run's checkpoint times */+ uint32_t finishes; /* runs to the line */+ uint8_t track, paint, view, guide;+} pt_profile;typedef struct {uint32_t magic;uint16_t version, size;- pg_profile p;- uint8_t has_race, spare[3];- pg_race race;+ pt_profile p;uint32_t sum; /* FNV-1a of everything before it */-} pg_file;-_Static_assert(sizeof(pg_file) == 496, "polygt3d.sav: 496 bytes");+} pt_file;+_Static_assert(sizeof(pt_file) == 4 + 4 + PT_NTRACKS * 4 * (1 + PT_SPLITS) + 8 + 4, "polytrack.sav's size");-void pg_fresh(pg_profile *p);-bool pg_file_ok(const pg_file *f);-bool save_load(pg_file *f); /* the save, its copy, or a fresh start (false) */-bool save_write(const pg_file *f); /* with the magic, size and sum */+void pt_fresh(pt_profile *p);+bool pt_file_ok(const pt_file *f);+bool save_load(pt_file *f); /* the save, its copy, or a fresh start (false) */+bool save_write(const pt_file *f); /* with the magic, size and sum */++/* ghosts: a track's samples, encoded (ghost.c) */+typedef struct {+ uint8_t track;+ uint16_t len; /* bytes */+ uint32_t ms; /* the run's time */+ const uint8_t *data;+} ghost_entry;+/* the ghost kept for a track (data points into a buffer of save.c), or false */+bool ghosts_find(int track, ghost_entry *g);+/* keeps this one first, then the others while they fit */+bool ghosts_put(int track, uint32_t ms, const uint8_t *data, uint16_t len);+void ghosts_load(void);+uint32_t pt_sum(const void *data, uint32_t n);#endifdiff --git a/games/polytrack/tests/play.c b/games/polytrack/tests/play.cindex eb89fe08..df83e6cc 100644--- a/games/polytrack/tests/play.c+++ b/games/polytrack/tests/play.c@@ -1,20 +1,20 @@-/* PolyGT 3D on a computer, for tests and pictures (make host, make test).+/* PolyTrack on a computer, for tests and pictures (make host, make test).*- * play test DIR the roads, laps, physics, crashes, the rivals finishing every circuit at every level, a- * driver finishing races, the endless road, the whole app through its keys, saves written and- * read back, damaged saves, a full storage, a few hundred sessions of random keys, and the same- * race twice, to the same hash on every computer+ * play test DIR every official track driven to the finish by its recorded run, to the same frame and hash+ * on every computer; the checkpoints in order, respawns, restarts; the whole app through its+ * keys; saves written and read back, damaged saves, a full storage, the ghosts; a few hundred+ * sessions of random keys* play shots DIR pictures of the screens (DIR/<name>.ppm)- * play docs DIR the README's pictures (DIR/<name>.ppm)- * play film DIR MS T [VIEW CAR STEP] MS milliseconds of a race on circuit T, a driver at the wheel, a frame every- * STEP ms (DIR/<frame>_<ms>.raw, for tools/record.py --frames)+ * play view DIR T MS a picture of track T after MS ms of its recorded run (DIR/view.ppm)+ * play film DIR T MS STEP MS ms of track T's recorded run, a frame every STEP ms (DIR/<frame>_<ms>.raw, for+ * tools/record.py --frames)*/-#define main pg_app_main+#define main pt_app_main#include "../src/main.c"#undef main-#include <stddef.h>#include <stdio.h>#include <stdlib.h>+#include "routes.h"/* ---------------------------------------------------------------- the calculator, on a computer */static uint16_t fb[240][320];@@ -38,36 +38,35 @@ uint32_t plat_keys(void) {uint32_t plat_millis(void) { return (uint32_t)clock_ms; }void plat_sleep(uint32_t ms) { clock_ms += ms; }void plat_vblank(void) {}-static uint32_t rnd_state = 1;-uint32_t plat_random(void) { return pg_rng(&rnd_state); }bool plat_slow(void) { return false; }void plat_begin(void) {}int plat_end(void) { return 0; }-static struct { char name[32]; uint8_t data[4096]; uint32_t len; bool on; } files[4];+#define NFILES 6+static struct { char name[32]; uint8_t data[16384]; uint32_t len; bool on; } files[NFILES];static bool storage_full;bool plat_save(const char *name, const void *data, uint32_t len) {if (storage_full) return false;int k = -1;- for (int i = 0; i < 4; i++)+ for (int i = 0; i < NFILES; i++)if (files[i].on && !strcmp(files[i].name, name)) k = i;- for (int i = 0; i < 4 && k < 0; i++)+ for (int i = 0; i < NFILES && k < 0; i++)if (!files[i].on) k = i;if (k < 0 || len > sizeof files[k].data) return false;strcpy(files[k].name, name), memcpy(files[k].data, data, len), files[k].len = len, files[k].on = true;return true;}const uint8_t *plat_load(const char *name, uint32_t *len) {- for (int i = 0; i < 4; i++)+ for (int i = 0; i < NFILES; i++)if (files[i].on && !strcmp(files[i].name, name)) return *len = files[i].len, files[i].data;return 0;}static void forget(const char *name) {- for (int i = 0; i < 4; i++)+ for (int i = 0; i < NFILES; i++)if (files[i].on && !strcmp(files[i].name, name)) files[i].on = false;}static uint8_t *file_data(const char *name, uint32_t *len) {- for (int i = 0; i < 4; i++)+ for (int i = 0; i < NFILES; i++)if (files[i].on && !strcmp(files[i].name, name)) return *len = files[i].len, files[i].data;return 0;}@@ -87,970 +86,92 @@ static void shot(const char *dir, const char *name) {}static int fails;-static const char *const LEVELS[3] = {"Easy", "Normal", "Hard"};-#define RACE_HASH 0x8932C86Au /* (made on a Mac with clang; Linux with GCC must agree) */#define CHECK(c, ...) do { if (!(c)) { fails++; printf("FAIL %s:%d: ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0)-/* ---------------------------------------------------------------- a driver */-/* it drives as a good player would: the rivals' line (out, in, out), steering for the bend ahead with taps of the- keys, braking for the slowest bend coming up with the tyres it has, round slower cars, nitro on the straights;- skill 0..100 (how much of the grip it dares) */-static int bot_skill = 100;-static int32_t bot_line;-static unsigned bot(const pg_race *r, const pg_track *t) {- const pg_car *c = &r->car[0];- int32_t v = c->v, k0 = pg_seg_of(t, c->s);- int32_t grip = (int32_t)pg_vehicles[c->model].grip * (t->zone[pg_slot(t, k0)] == 2 ? 118 : 128) / 128;- if (abs(c->x) > PG_ROAD + PG_KERB) grip = grip * 92 / 128;- int64_t aim2 = (int64_t)200 * FX * 200 * FX;- for (int k = 0; k < 30; k++) {- int sl = pg_slot(t, k0 + k);- int64_t vl = (int64_t)t->limit[sl] * FX;- vl = vl * pg_isqrt((uint64_t)grip * 128) / 128 * (84 + bot_skill * 18 / 100) / 100;- int64_t d = (int64_t)(k0 + k) * t->seg - c->s - 4 * FX;- if (d < 0) d = 0;- int64_t v2 = vl * vl + 2LL * 24 * FX * d;- if (v2 < aim2) aim2 = v2;- }- int32_t aim = (int32_t)pg_isqrt((uint64_t)aim2);- /* the line: out before a bend, in at its middle */- int32_t near = 0, far = 0;- for (int k = 0; k < 4; k++) near += t->cv[pg_slot(t, k0 + k)];- for (int k = 4; k < 13; k++) far += t->cv[pg_slot(t, k0 + k)];- int32_t line = (int32_t)((int64_t)(near * 3 - far) * 6 * FX / 3000);- /* a slower car close ahead in the way: go round it */- for (int j = 1; j <= r->rivals; j++) {- int32_t ds = pg_wrap(t, r->car[j].s - c->s);- if (ds > 0 && ds < 25 * FX && abs(r->car[j].x - c->x) < 3 * FX && r->car[j].v < v + FX)- bot_line = r->car[j].x > 0 ? r->car[j].x - 4 * FX : r->car[j].x + 4 * FX;- }- bot_line -= bot_line / 32;- int32_t target = line + bot_line;- if (target > 6 * FX) target = 6 * FX;- if (target < -6 * FX) target = -6 * FX;+/* ---------------------------------------------------------------- a recorded run: the keys held from a frame on */+static unsigned route_input(const route_t *r, uint32_t frame) {unsigned in = 0;- if (v > aim + FX / 2) in |= IN_BRAKE;- else in |= IN_GAS;- /* steering: what the bend needs at this speed, plus a heading back towards the line */- int32_t cv = t->cv[pg_slot(t, k0)];- int32_t want_ang = (target - c->x) / 16;- if (want_ang > 2500) want_ang = 2500;- if (want_ang < -2500) want_ang = -2500;- int64_t road = (int64_t)cv * v / t->seg; /* angle units a second */- int64_t turn = road + (int64_t)(want_ang - c->ang) * 4; /* ...and the correction, over a quarter second */- int32_t lat = 24 * FX * grip / 128;- int32_t hold = v > FX ? (int32_t)((int64_t)lat * 10430 / v) : 14394;- int32_t lock = hold + hold / 6 < 14394 ? hold + hold / 6 : 14394;- int32_t auth = v >= 12 * FX ? 256 : v * 256 / (12 * FX);- int32_t full = (int32_t)((int64_t)lock * auth / 256);- int32_t steer = full > 0 ? (int32_t)(turn * 1024 / full) : 0;- if (steer > 1024) steer = 1024;- if (steer < -1024) steer = -1024;- if (c->steer < steer - 60) in |= IN_RIGHT;- else if (c->steer > steer + 60) in |= IN_LEFT;- if (!(in & IN_BRAKE) && aim > v + 20 * FX && c->nitro > 300 && abs(c->ang) < 1500) in |= IN_NITRO;- return in;-}--static uint32_t hash_race(const pg_race *r, uint32_t h) { return h ^ pg_sum(r, sizeof *r) * 16777619u; }--/* ---------------------------------------------------------------- the roads */-static pg_track TT;-static pg_setup plain(int mode, int id, int vehicle, int rivals, int level) {- pg_setup s;- memset(&s, 0, sizeof s);- s.mode = (uint8_t)mode, s.track = (uint8_t)id, s.vehicle = (uint8_t)vehicle, s.laps = 3, s.rivals = (uint8_t)rivals;- s.level = (uint8_t)level;- return s;-}--static int64_t dist2(const pg_track *t, int a, int b) {- int64_t dx = (t->px[a] - t->px[b]) / FX, dz = (t->pz[a] - t->pz[b]) / FX;- return dx * dx + dz * dz;-}--static void roads(void) {- for (int id = 0; id < PG_CIRCUITS; id++) {- pg_build(&TT, id);- int n = TT.n;- CHECK(n > 200 && n <= PG_MAXN && TT.length == n * TT.seg, "%s: %d segments", pg_circuit_name[id], n);- int64_t turn = 0;- int jerk = 0, steep = 0, close = 0, gaps = 0;- for (int k = 0; k < n; k++) {- turn += TT.cv[k];- if (abs(TT.cv[(k + 1) % n] - TT.cv[k]) > 1200) jerk++;- if (abs(TT.py[(k + 1) % n] - TT.py[k]) > FX * 9 / 10) steep++; /* no more than 15% */- int64_t d2 = dist2(&TT, k, (k + 1) % n);- if (d2 < 5 * 5 || d2 > 7 * 7) gaps++;- for (int j = k + 8; j < n && j < k + n - 8; j++)- if (dist2(&TT, k, j) < 32 * 32) close++;- }- CHECK(turn == ANG_TURN, "%s: turns %lld, not one turn round", pg_circuit_name[id], (long long)turn);- CHECK(!jerk && !steep && !gaps, "%s: %d sudden bends, %d steep, %d uneven segments", pg_circuit_name[id], jerk, steep, gaps);- CHECK(!close, "%s: the road comes within 32 m of itself %d times", pg_circuit_name[id], close);- int lo = 255;- for (int k = 0; k < n; k++)- if (TT.limit[k] < lo) lo = TT.limit[k];- CHECK(lo >= 15 && TT.orbs >= 10, "%s: tightest bend %d m/s, %d orbs", pg_circuit_name[id], lo, TT.orbs);- printf(" %-17s %3d segments, %.2f km, tightest bend %d km/h, %d orbs\n", pg_circuit_name[id], n, n * TT.seg / 256000.0,- lo * 36 / 10, TT.orbs);- }- /* the endless road: laid on and on, always joined up, never too steep, within its heights */- pg_endless(&TT, 777);- int bad = 0, zones[5] = {0};- int32_t ylo = 0, yhi = 0;- for (int32_t k = 0; k < 20000; k += 7) {- pg_extend(&TT, k + 48);- for (int32_t j = k; j < k + 40; j++) {- int a = pg_slot(&TT, j), b = pg_slot(&TT, j + 1);- int64_t d2 = dist2(&TT, a, b);- if (d2 < 5 * 5 || d2 > 7 * 7) bad++;- if (abs(TT.py[b] - TT.py[a]) > FX * 3 / 4) bad++;- if (TT.py[a] < ylo) ylo = TT.py[a];- if (TT.py[a] > yhi) yhi = TT.py[a];- if (TT.zone[a] < 3 || TT.zone[a] > 7) bad++;- else zones[TT.zone[a] - 3]++;- }- }- CHECK(!bad && ylo > -100 * FX && yhi < 100 * FX, "the endless road: %d bad joins, heights %d..%d m", bad, ylo / FX, yhi / FX);- CHECK(zones[0] && zones[1] && zones[2] && zones[3] && zones[4], "the endless road: every scenery");- printf(" the endless road: 120 km laid, heights %d..%d m\n", ylo / FX, yhi / FX);-}--/* a whole race driven by the bot; returns the steps it took (0: not finished in 11 minutes) */-static int drive_race(pg_race *r, const pg_setup *s, uint32_t seed, int skill, uint32_t *hash) {- pg_new(r, &TT, s, seed);- bot_skill = skill, bot_line = 0;- int steps = 0;- while (r->phase != PH_DONE && steps < 11 * 60 * PG_HZ) {- pg_step(r, &TT, bot(r, &TT), 0);- steps++;- if (hash) *hash = hash_race(r, *hash);- if (!pg_valid(r, &TT)) {- CHECK(0, "race not valid at step %d on %s", steps, pg_circuit_name[s->track]);- break;- }- }- return r->end == END_FINISH ? steps : 0;-}--static void laps(void) {- pg_race r;- pg_setup s = plain(MODE_RACE, 0, 0, 0, LEVEL_NORMAL);- pg_new(&r, &TT, &s, 5);- CHECK(r.phase == PH_GRID && r.lap == 1 && r.car[0].s < 0, "the start: on the grid, behind the line, lap 1");- int steps = 0, laps_seen = 1;- while (r.phase == PH_GRID) pg_step(&r, &TT, IN_GAS, 0), steps++;- CHECK(steps == 3 * PG_HZ + PG_HZ / 2 && r.car[0].v == 0, "the countdown took %d steps, the car held", steps);- bot_line = 0;- while (r.phase == PH_RACE && steps < 20000) {- int before = r.lap;- int32_t s0 = r.car[0].s;- pg_step(&r, &TT, bot(&r, &TT), 0);- steps++;- if (r.lap != before) {- CHECK(r.lap == before + 1, "lap %d to %d", before, r.lap);- CHECK(s0 < before * TT.length && r.car[0].s >= before * TT.length, "the lap changed off the line");- CHECK(r.banner == (r.lap == 3 ? BANNER_FINAL : BANNER_LAP), "the lap's banner");- CHECK(r.last_lap_ms > 15000 && r.lap_at == r.time_ms, "the lap's time (%u)", r.last_lap_ms);- laps_seen++;- }- }- CHECK(laps_seen == 3 && r.end == END_FINISH && r.car[0].place == 1, "three laps, then the finish (%d laps, end %d)",- laps_seen, r.end);- CHECK(r.car[0].s >= 3 * TT.length && r.car[0].finish_ms == r.time_ms, "finished at the line");- CHECK(r.best_lap_ms > 15000 && r.best_lap_ms * 3 <= r.time_ms + 6000, "a best lap (%u ms of %u)", r.best_lap_ms, r.time_ms);- /* standing still, or going backwards over the line, counts no lap */- pg_new(&r, &TT, &s, 5);- for (int i = 0; i < 2000; i++) pg_step(&r, &TT, IN_BRAKE, 0);- CHECK(r.lap == 1 && r.car[0].v == 0, "standing still: still lap 1");- pg_new(&r, &TT, &s, 5);- r.phase = PH_RACE, r.countdown = 0;- r.car[0].s = 20 * FX, r.car[0].ang = 32767, r.car[0].v = 20 * FX; /* pointing back down the road */- int wrong = 0;- for (int i = 0; i < 1500; i++) {- pg_step(&r, &TT, IN_GAS, 0);- if (r.banner == BANNER_WRONG) wrong = 1;- }- CHECK(r.lap == 1 && r.car[0].s < -100 * FX && wrong, "backwards: lap %d, at %d m, told %d", r.lap, r.car[0].s / FX, wrong);-}--static void physics(void) {- pg_race r;- /* flat out on Neo-Tokyo Wangan's long straight: the car's top speed, no more; nitro adds to it */- for (int v = 0; v < PG_VEHICLES; v++) {- pg_setup s = plain(MODE_RACE, 1, v, 0, LEVEL_NORMAL);- pg_new(&r, &TT, &s, 3);- r.phase = PH_RACE, r.countdown = 0;- int32_t top = (int32_t)pg_vehicles[v].top * FX / 8, most = 0;- int t100 = 0;- for (int i = 0; i < 40 * PG_HZ; i++) {- r.car[0].s = 10 * FX, r.car[0].x = 0, r.car[0].ang = 0; /* (kept on the straight) */- pg_step(&r, &TT, IN_GAS, 0);- if (r.car[0].v > most) most = r.car[0].v;- if (!t100 && pg_kmh(r.car[0].v) >= 100) t100 = i;- }- CHECK(most <= top + FX / 4 && most > top - 3 * FX, "%s: top %d km/h, its own %d", pg_vehicles[v].name, pg_kmh(most), pg_kmh(top));- r.car[0].nitro = 1000;- for (int i = 0; i < 3 * PG_HZ; i++) {- r.car[0].s = 10 * FX, r.car[0].x = 0, r.car[0].ang = 0;- pg_step(&r, &TT, IN_GAS | IN_NITRO, 0);- }- CHECK(r.car[0].v > top + 5 * FX, "%s: nitro adds speed", pg_vehicles[v].name);- printf(" %-15s top %d km/h, 0-100 km/h in %.1f s\n", pg_vehicles[v].name, pg_kmh(most), t100 / 50.0);- }- /* the manual gearbox: first gear stops at its limiter, + takes the next */- {- pg_setup m = plain(MODE_RACE, 1, 0, 0, LEVEL_NORMAL);- m.manual = 1;- pg_new(&r, &TT, &m, 3);- r.phase = PH_RACE, r.countdown = 0;- for (int i = 0; i < 10 * PG_HZ; i++) {- r.car[0].s = 10 * FX, r.car[0].x = 0, r.car[0].ang = 0;- pg_step(&r, &TT, IN_GAS, 0);- }- int32_t first = r.car[0].v;- CHECK(r.car[0].gear == 1 && pg_kmh(first) < 90, "manual: still in first (%d) at %d km/h", r.car[0].gear, pg_kmh(first));- pg_step(&r, &TT, IN_GAS, 1);- for (int i = 0; i < 3 * PG_HZ; i++) {- r.car[0].s = 10 * FX, r.car[0].x = 0, r.car[0].ang = 0;- pg_step(&r, &TT, IN_GAS, 0);- }- CHECK(r.car[0].gear == 2 && r.car[0].v > first + 5 * FX, "manual: second gear goes on (%d km/h)", pg_kmh(r.car[0].v));- pg_step(&r, &TT, IN_GAS, -1), pg_step(&r, &TT, IN_GAS, -1);- CHECK(r.car[0].gear == 1, "manual: - goes back down, not below first");- }- /* braking from 200 km/h: under 60 m */- pg_setup s = plain(MODE_RACE, 1, 0, 0, LEVEL_NORMAL);- pg_new(&r, &TT, &s, 3);- r.phase = PH_RACE, r.countdown = 0, r.car[0].s = 10 * FX, r.car[0].v = 200 * FX * 10 / 36;- int32_t s0 = r.car[0].s;- while (r.car[0].v > 0) pg_step(&r, &TT, IN_BRAKE, 0);- CHECK(r.car[0].s - s0 < 60 * FX && r.car[0].s - s0 > 30 * FX, "braking from 200 km/h: %d m", (r.car[0].s - s0) / FX);- /* a bend not steered through carries you to its outside; steering keeps you on the road */- pg_build(&TT, 2);- int32_t kb = 0;- for (int k = 0; k < TT.n; k++)- if (TT.cv[k] > TT.cv[kb]) kb = k;- s = plain(MODE_RACE, 2, 0, 0, LEVEL_NORMAL);- pg_new(&r, &TT, &s, 3);- r.phase = PH_RACE, r.countdown = 0, r.car[0].s = (kb - 4) * TT.seg, r.car[0].v = 15 * FX;- for (int i = 0; i < 60; i++) pg_step(&r, &TT, IN_GAS, 0);- CHECK(r.car[0].x < -2 * FX, "a right bend, unsteered: out to the left (%d)", r.car[0].x / FX);- /* the tyres hold so much: full lock at speed turns no faster than the grip allows */- pg_build(&TT, 1);- s = plain(MODE_RACE, 1, 0, 0, LEVEL_NORMAL);- pg_new(&r, &TT, &s, 3);- r.phase = PH_RACE, r.countdown = 0, r.car[0].s = 10 * FX, r.car[0].v = 60 * FX;- int32_t worst = 0;- for (int i = 0; i < 30; i++) {- int16_t a0 = r.car[0].ang;- int32_t cv = TT.cv[pg_slot(&TT, pg_seg_of(&TT, r.car[0].s))];- int32_t ds0 = r.car[0].s;- pg_step(&r, &TT, IN_RIGHT, 0);- int32_t turned = (int16_t)(r.car[0].ang - a0) + (int32_t)((int64_t)cv * (r.car[0].s - ds0) / TT.seg);- int32_t lat = (int32_t)((int64_t)turned * PG_HZ * r.car[0].v / 10430); /* v * turn rate: FX/s^2 */- if (lat > worst) worst = lat;- }- int32_t hold = 24 * FX * pg_vehicles[0].grip / 128 * 133 / 128;- CHECK(worst <= hold + FX / 2 && worst > hold * 3 / 4, "sideways at full lock: %d m/s^2, the tyres %d", worst / FX, hold / FX);- /* braking hard while steering hard slides the car: a tighter turn, less braking */- pg_new(&r, &TT, &s, 3);- r.phase = PH_RACE, r.countdown = 0, r.car[0].s = 10 * FX, r.car[0].v = 40 * FX, r.car[0].steer = 1024;- pg_race q = r;- for (int i = 0; i < 25; i++) pg_step(&r, &TT, IN_BRAKE | IN_RIGHT, 0), pg_step(&q, &TT, IN_RIGHT, 0);- CHECK(r.car[0].drift && r.car[0].slip > 1000 && r.car[0].ang > q.car[0].ang, "a slide: %d, body %d, heading %d vs %d",- r.car[0].drift, r.car[0].slip, r.car[0].ang, q.car[0].ang);- /* the grass is slow */- pg_new(&r, &TT, &s, 3);- r.phase = PH_RACE, r.countdown = 0;- for (int i = 0; i < 30 * PG_HZ; i++) {- r.car[0].s = 10 * FX, r.car[0].x = 11 * FX, r.car[0].ang = 0;- pg_step(&r, &TT, IN_GAS, 0);- }- CHECK(pg_kmh(r.car[0].v) < 160, "on the grass: %d km/h", pg_kmh(r.car[0].v));- /* the barriers: never through, and hitting one costs speed */- pg_new(&r, &TT, &s, 3);- r.phase = PH_RACE, r.countdown = 0, r.car[0].s = 10 * FX, r.car[0].v = 50 * FX, r.car[0].ang = 6000;- int32_t far_x = 0, v0 = r.car[0].v;- for (int i = 0; i < 100; i++) {- pg_step(&r, &TT, IN_GAS, 0);- if (r.car[0].x > far_x) far_x = r.car[0].x;- }- CHECK(far_x <= PG_WALL - PG_HW && r.car[0].v < v0, "into the barrier: %d cm in, %d km/h", (far_x - (PG_WALL - PG_HW)) * 100 / FX,- pg_kmh(r.car[0].v));-}--static int inside_count(const pg_race *r, const pg_track *t) {- int n = 0;- for (int a = 0; a <= r->rivals; a++)- for (int b = a + 1; b <= r->rivals; b++) {- int32_t ds = pg_wrap(t, r->car[b].s - r->car[a].s), dx = r->car[b].x - r->car[a].x;- if (abs(ds) < 2 * PG_HL - FX / 4 && abs(dx) < 2 * PG_HW - FX / 4) n++;- }- return n;-}--static void crashes(void) {- pg_race r;- /* random keys among a full field: never a car inside another, everything in range */- uint32_t lcg = 77;- int inside = 0, bad = 0;- for (int id = 0; id < PG_CIRCUITS; id++) {- pg_setup s = plain(MODE_RACE, id, id, 7, LEVEL_HARD);- pg_new(&r, &TT, &s, (uint32_t)id + 1);- for (int i = 0; i < 9000 && r.phase != PH_DONE; i++) {- lcg = lcg * 1103515245u + 12345u;- unsigned in = (lcg >> 16) & 31;- pg_step(&r, &TT, in | IN_GAS, 0);- inside += inside_count(&r, &TT);- if (!pg_valid(&r, &TT)) bad++;- }- }- CHECK(!inside && !bad, "cars inside each other %d times, %d bad steps", inside, bad);- /* ramming the car in front: you stop at its bumper, it takes the push */- pg_setup s = plain(MODE_RACE, 1, 0, 1, LEVEL_EASY);- pg_new(&r, &TT, &s, 3);- r.phase = PH_RACE, r.countdown = 0;- r.car[0].s = 100 * FX, r.car[0].x = 0, r.car[0].v = 60 * FX;- r.car[1].s = 112 * FX, r.car[1].x = 0, r.car[1].lane = 0, r.car[1].v = 20 * FX;- bool through = false;- int32_t v1 = r.car[1].v;- for (int i = 0; i < 30; i++) {- r.car[1].lane = 0, r.car[1].think = 2;- pg_step(&r, &TT, IN_GAS, 0);- if (r.car[0].s > r.car[1].s && abs(r.car[0].x - r.car[1].x) < 2 * PG_HW) through = true;- }- CHECK(!through && r.car[1].v > v1, "drove through the car in front (%d), it was pushed (%d)", through, r.car[1].v > v1);-}--static void rivals(void) {- uint32_t h = 0;- for (int id = 0; id < PG_CIRCUITS; id++) {- uint32_t mean[3] = {0};- for (int level = 0; level < 3; level++) {- pg_race r;- pg_setup s = plain(MODE_RACE, id, 0, 7, level);- pg_new(&r, &TT, &s, (uint32_t)(id * 3 + level + 1));- /* you stay on the grid: the rivals race on their own */- int steps = 0, inside = 0;- while (r.finished < 7 && steps < 11 * 60 * PG_HZ) {- pg_step(&r, &TT, 0, 0), steps++;- h = hash_race(&r, h);- inside += inside_count(&r, &TT);- }- CHECK(r.finished == 7 && !inside, "%s, %s: %d of 7 rivals finished, %d overlaps", pg_circuit_name[id], LEVELS[level],- r.finished, inside);- uint32_t first = 0, last = 0;- for (int i = 1; i < PG_CARS; i++) {- mean[level] += r.car[i].finish_ms / 7;- if (r.car[i].place == 1) first = r.car[i].finish_ms;- if (r.car[i].place == 7) last = r.car[i].finish_ms;- }- printf(" %-17s %-6s rivals %u:%04.1f to %u:%04.1f\n", pg_circuit_name[id], LEVELS[level], first / 60000,- first % 60000 / 1000.0, last / 60000, last % 60000 / 1000.0);- CHECK(last - first < 30000, "%s %s: the field spread over %u ms", pg_circuit_name[id], LEVELS[level], last - first);- }- CHECK(mean[0] > mean[1] && mean[1] > mean[2], "%s: Easy %u, Normal %u, Hard %u ms", pg_circuit_name[id], mean[0], mean[1], mean[2]);- }- printf(" rivals' hash %08x\n", h);-}--/* the driver against the field, every circuit and level */-static void racing(void) {- int wins[3] = {0}, finishes = 0, places[3] = {0};- for (int level = 0; level < 3; level++)- for (int id = 0; id < PG_CIRCUITS; id++) {- pg_race r;- pg_setup s = plain(MODE_RACE, id, 0, 7, level);- int steps = drive_race(&r, &s, (uint32_t)(100 + id + level * 7), 100, NULL);- CHECK(steps > 0, "%s %s: the driver didn't finish", pg_circuit_name[id], LEVELS[level]);- if (steps) finishes++;- if (r.car[0].place == 1) wins[level]++;- places[level] += r.car[0].place;- printf(" %-17s %-6s %u:%04.1f, %d%s, best lap %u:%04.1f\n", pg_circuit_name[id], LEVELS[level], r.time_ms / 60000,- r.time_ms % 60000 / 1000.0, r.car[0].place, r.car[0].place == 1 ? "st" : r.car[0].place == 2 ? "nd" : r.car[0].place == 3 ? "rd" : "th",- r.best_lap_ms / 60000, r.best_lap_ms % 60000 / 1000.0);- }- printf(" the driver won %d easy, %d normal, %d hard races of 3 each\n", wins[0], wins[1], wins[2]);- CHECK(finishes == 9, "%d of 9 races finished", finishes);- CHECK(places[0] <= places[1] && places[1] <= places[2], "harder levels should be harder (%d %d %d)", places[0], places[1], places[2]);-}--/* the endless road: zones add time, the clock runs out, orbs fill nitro */-static void endless(void) {- pg_race r;- pg_setup s = plain(MODE_ENDLESS, 0, 0, 0, LEVEL_NORMAL);- for (int run = 0; run < 3; run++) {- pg_new(&r, &TT, &s, 400 + (uint32_t)run);- CHECK(r.rivals == 0 && r.time_left == 30000, "the endless road: alone, 30 s");- bot_skill = 100 - run * 20, bot_line = 0;- int steps = 0, orbs = 0, bad = 0;- uint16_t n0 = r.car[0].nitro;- while (r.phase != PH_DONE && steps < 30 * 60 * PG_HZ) {- pg_step(&r, &TT, bot(&r, &TT), 0), steps++;- if (r.car[0].nitro > n0) orbs++;- n0 = r.car[0].nitro;- if (!pg_valid(&r, &TT)) bad++;- }- CHECK(r.phase == PH_DONE && r.end == END_TIME && !bad, "the endless road ends when time runs out (%d bad)", bad);- CHECK(r.zone >= 4 && orbs > 3, "the endless road: zone %d, %d orbs", r.zone + 1, orbs);- printf(" endless, skill %d: %.1f km, zone %d, %.0f s, %d orbs\n", bot_skill, r.car[0].s / 256000.0, r.zone + 1,- r.ticks / 50.0, orbs);- }-}--/* the same race twice, to the same hash on every computer */-static void same_twice(void) {- uint32_t h1 = 0, h2 = 0;- pg_race a, b;- pg_setup s = plain(MODE_RACE, 2, 1, 7, LEVEL_NORMAL);- drive_race(&a, &s, 2026, 100, &h1);- drive_race(&b, &s, 2026, 100, &h2);- printf(" a race's hash %08X\n", h1);- CHECK(h1 == h2 && h1 == RACE_HASH, "the same race twice, and as on every computer: %08X", h1);-}--/* ---------------------------------------------------------------- saves */-static void saves(void) {- memset(files, 0, sizeof files);- pg_file a, b;- memset(&a, 0, sizeof a);- pg_fresh(&a.p);- a.p.races = 9, a.p.wins = 4, a.p.runs = 3, a.p.best_ms[1] = 160000, a.p.best_lap_ms[1] = 51000, a.p.best_lap_ms[2] = 47000;- a.p.best_m = 12345, a.p.best_zone = 21, a.p.mode = MODE_RACE, a.p.track = 2, a.p.vehicle = 4, a.p.laps = 5;- a.p.rivals = 6, a.p.level = LEVEL_HARD, a.p.manual = 1, a.p.view = VIEW_FAR, a.p.guide = 1;- pg_setup s = plain(MODE_RACE, 2, 4, 6, LEVEL_HARD);- pg_new(&a.race, &TT, &s, 4);- bot_line = 0;- for (int i = 0; i < 2500; i++) pg_step(&a.race, &TT, bot(&a.race, &TT), 0);- a.has_race = 1;- CHECK(save_write(&a), "saved");- CHECK(save_load(&b) && !memcmp(&a.p, &b.p, sizeof a.p) && b.has_race && !memcmp(&a.race, &b.race, sizeof a.race),- "read back as written");- /* the copy in the script brings it back when the save is gone */- forget(PG_SAVE_NAME);- CHECK(save_load(&b) && b.p.races == 9 && b.has_race, "back from polygt3d_saves.py");- CHECK(plat_load(PG_SAVE_NAME, &(uint32_t){0}) != NULL, "and put back in polygt3d.sav");- /* every byte damaged in turn: never read (with the copy gone, a fresh start) */- uint32_t n;- uint8_t good[sizeof(pg_file)];- memcpy(good, file_data(PG_SAVE_NAME, &n), sizeof good);- forget(PG_COPY_NAME);- int bad = 0;- for (uint32_t i = 0; i < sizeof good; i++) {- uint8_t *d = file_data(PG_SAVE_NAME, &n);- memcpy(d, good, sizeof good);- d[i] ^= (uint8_t)(1 + i % 255);- if (save_load(&b) || b.p.races || b.has_race || b.p.laps != 3) bad++;- }- CHECK(!bad, "%d damaged saves read", bad);- /* cut short, empty, another version: a fresh start */- for (int k = 0; k < 4; k++)- if (files[k].on && !strcmp(files[k].name, PG_SAVE_NAME)) memcpy(files[k].data, good, sizeof good), files[k].len = sizeof good - 1;- CHECK(!save_load(&b) && b.p.rivals == 5, "a short save: fresh");- for (int k = 0; k < 4; k++)- if (files[k].on && !strcmp(files[k].name, PG_SAVE_NAME)) files[k].len = 0;- CHECK(!save_load(&b), "an empty save: fresh");- pg_file v = a;- v.magic = PG_MAGIC, v.size = sizeof v, v.version = 2;- v.sum = pg_sum(&v, offsetof(pg_file, sum));- plat_save(PG_SAVE_NAME, &v, sizeof v);- CHECK(!save_load(&b), "another version: fresh");- /* a checksum that fits over values that don't: not read either; whatever is read races and draws safely */- uint32_t lcg = 5;- int read = 0;- for (int k = 0; k < 400; k++) {- pg_file x;- memcpy(&x, good, sizeof x);- uint8_t *p = (uint8_t *)&x;- for (int j = 0; j < 3; j++) {- lcg = lcg * 1103515245u + 12345u;- uint32_t at = 8 + (lcg >> 8) % (offsetof(pg_file, sum) - 8);- p[at] = (uint8_t)(lcg >> 24);- }- x.sum = pg_sum(&x, offsetof(pg_file, sum));- plat_save(PG_SAVE_NAME, &x, sizeof x);- if (save_load(&b)) {- read++;- if (b.has_race) {- show_race(&b.race), built = -1;- int went_bad = 0;- for (int i = 0; i < 300; i++) {- pg_step(&b.race, &track, (unsigned)i & 31, 0);- if (!pg_valid(&b.race, NULL)) went_bad++;- }- CHECK(!went_bad, "an accepted race went bad");- }- }- }- printf(" saves: %d of 400 changed saves with a fitting checksum were still in range\n", read);- /* odd but possible races (cars on top of each other, flat out, stopped, wide): read, then raced and drawn */- int odd = 0, odd_bad = 0;- for (int k = 0; k < 200; k++) {- pg_file x;- memcpy(&x, good, sizeof x);- for (int i = 0; i <= x.race.rivals; i++) {- pg_car *c = &x.race.car[i];- lcg = lcg * 1103515245u + 12345u;- c->s = (int32_t)(lcg >> 9) % (3 * 1600 * FX);- lcg = lcg * 1103515245u + 12345u;- c->x = ((int32_t)(lcg >> 8) % (2 * (PG_WALL - PG_HW))) - (PG_WALL - PG_HW);- c->lane = ((int32_t)(lcg >> 20) % 3 - 1) * 4 * FX;- lcg = lcg * 1103515245u + 12345u;- c->v = (int32_t)(lcg >> 8) % (100 * FX);- c->ang = (int16_t)(lcg >> 3);- }- x.race.car[1].s = x.race.car[2].s, x.race.car[1].x = x.race.car[2].x; /* two cars in one place */- x.sum = pg_sum(&x, offsetof(pg_file, sum));- plat_save(PG_SAVE_NAME, &x, sizeof x);- if (!save_load(&b) || !b.has_race) continue;- odd++;- sv = b, built = -1;- show_race(&sv.race);- for (int i = 0; i < 400; i++) {- pg_step(&sv.race, &track, bot(&sv.race, &track), 0);- if (!pg_valid(&sv.race, &track)) odd_bad++;- }- prev = sv.race, ui.screen = V_RACE;- pg_render(&sv, &track, &prev, &sv.race, 256, &ui, &ghost_now);- }- CHECK(odd > 150 && !odd_bad, "odd races: %d read, %d steps gone bad", odd, odd_bad);- /* storage full: the save fails, the game goes on */- memset(files, 0, sizeof files);- storage_full = true;- CHECK(!save_write(&a), "a full storage fails the save");- storage_full = false;- memset(files, 0, sizeof files);-}--/* ---------------------------------------------------------------- the whole app, with keys */-static int bad_frames;-static void check_state(void) {- if (ui.screen >= V_SCREENS) bad_frames++;- if (sv.has_race && !pg_valid(&sv.race, NULL)) bad_frames++;- if (sv.p.wins > sv.p.races || sv.p.laps < 1 || sv.p.laps > PG_MAX_LAPS || sv.p.vehicle >= PG_VEHICLES) bad_frames++;- if (rd_dropped) bad_frames++;-}--static uint32_t (*menu_keys)(uint32_t f);-static uint32_t drive_keys(uint32_t f) {- if (ui.screen == V_RACE && !ui.hold && sv.race.phase != PH_DONE) {- unsigned in = bot(&sv.race, &track);- uint32_t k = 0;- if (in & IN_GAS) k |= PK_UP;- if (in & IN_BRAKE) k |= PK_DOWN;- if (in & IN_LEFT) k |= PK_LEFT;- if (in & IN_RIGHT) k |= PK_RIGHT;- if (in & IN_NITRO) k |= PK_OK;- return k;- }- return menu_keys ? menu_keys(f) : 0;-}--/* a race: Play, Start race, the guide, three laps driven, then the results' Main menu */-static int race_phase;-static uint32_t race_menu(uint32_t f) {- if (f % 4) return 0;- switch (ui.screen) {- case V_TITLE:- if (race_phase) return 0;- return ui.menu[ui.sel] == MENU_PLAY ? PK_OK : PK_DOWN;- case V_SETUP: return ui.sel == SET_START ? PK_OK : PK_DOWN;- case V_GUIDE: return PK_OK;- case V_RESULT: race_phase = 1; return ui.sel == 1 ? PK_OK : PK_DOWN;- default: return 0;+ for (int i = 0; i < r->n; i++) {+ if (r->ev[i].frame > frame) break;+ in = r->ev[i].keys;}-}-static bool saw_ghost;-static void watch_race(void) {- check_state();- if (ghost_now.on) saw_ghost = true;- if (race_phase == 1 && ui.screen == V_TITLE) quit_at = frame_no + 2, race_phase = 2;-}-static void race_app(void) {- memset(files, 0, sizeof files);- memset(best_ghost, 0, sizeof best_ghost);- frame_gap = 60;- race_phase = 0, saw_ghost = false;- script = drive_keys, menu_keys = race_menu, watch = watch_race;- frame_no = 0, quit_at = 4000000, bad_frames = 0;- bot_line = 0;- pg_app_main();- script = 0, menu_keys = 0, watch = 0;- pg_file f;- CHECK(save_load(&f), "the race saved");- CHECK(f.p.races == 1 && !f.has_race && f.p.guide == 1 && f.p.best_ms[0] && f.p.best_lap_ms[0], "a race finished and its records kept (races %u)",- f.p.races);- CHECK(race_phase == 2 && saw_ghost, "back to the menu (%d), the ghost seen (%d)", race_phase, saw_ghost);- CHECK(!bad_frames, "%d bad frames", bad_frames);- printf(" a race through the keys: %u:%04.1f, %s, %u frames\n", f.p.best_ms[0] / 60000, f.p.best_ms[0] % 60000 / 1000.0,- f.p.wins ? "won" : "not won", frame_no);-}--/* the endless road: chosen on the race screen, a minute of driving, pause, Quit game to the menu (kept), Continue,- then Home: it's saved */-static int en_step;-static uint32_t en_menu(uint32_t f) {- if (f % 4) return 0;- switch (ui.screen) {- case V_TITLE:- if (en_step >= 2) return ui.menu[ui.sel] == MENU_CONTINUE ? PK_OK : PK_UP;- return ui.menu[ui.sel] == MENU_PLAY ? PK_OK : PK_DOWN;- case V_SETUP:- if (sv.p.mode != MODE_ENDLESS) return ui.sel == SET_MODE ? PK_RIGHT : PK_UP;- return ui.sel == SET_START ? PK_OK : PK_UP;- case V_GUIDE: return PK_OK;- case V_PAUSE: return ui.sel == PAUSE_QUIT ? PK_OK : PK_DOWN;- case V_LEAVE: return ui.sel == 1 ? PK_OK : PK_DOWN;- default: return 0;- }-}-static uint32_t en_keys(uint32_t f) {- if (ui.screen == V_RACE && en_step == 0 && sv.race.car[0].s > 1500 * FX) en_step = 1;- if (ui.screen == V_RACE && en_step == 1) return f % 8 < 4 ? PK_BACK : 0;- if (ui.screen == V_TITLE && en_step == 1) en_step = 2;- if (ui.screen == V_RACE && en_step == 2 && !ui.hold) en_step = 3, quit_at = frame_no + 600;- return drive_keys(f);-}-static void endless_app(void) {- memset(files, 0, sizeof files);- frame_gap = 60;- en_step = 0;- script = en_keys, menu_keys = en_menu, watch = check_state;- frame_no = 0, quit_at = 400000, bad_frames = 0;- bot_line = 0;- pg_app_main();- script = 0, menu_keys = 0, watch = 0;- pg_file f;- CHECK(en_step == 3, "the endless steps (%d)", en_step);- CHECK(save_load(&f) && f.has_race && f.race.mode == MODE_ENDLESS && f.race.car[0].s > 1500 * FX,- "the drive kept on Home (%d)", f.has_race);- CHECK(!bad_frames, "%d bad frames", bad_frames);- printf(" the endless road through the keys: %.1f km, kept on Home\n", f.race.car[0].s / 256000.0);-}--static uint32_t lcg_keys;-static uint32_t rnd(void) { return lcg_keys = lcg_keys * 1103515245u + 12345u, lcg_keys >> 8; }-static uint32_t held_keys, held_until;-static uint32_t random_keys(uint32_t f) {- if (f >= held_until) {- static const uint32_t pick[] = {PK_OK, PK_OK, PK_OK, PK_LEFT, PK_RIGHT, PK_UP, PK_UP, PK_UP, PK_DOWN, PK_BACK,- PK_GEAR_UP, PK_GEAR_DOWN, PK_UP | PK_OK, PK_UP | PK_LEFT, PK_DOWN | PK_RIGHT, 0, 0};- held_keys = pick[rnd() % (sizeof pick / sizeof pick[0])];- held_until = f + 2 + rnd() % 40;- }- return held_keys;-}--static void fuzz(void) {- memset(files, 0, sizeof files);- frame_gap = 90;- int sessions = 0, kept = 0;- for (int s = 0; s < 300; s++) {- lcg_keys = (uint32_t)s * 2654435761u + 1;- if (s % 40 == 0) memset(files, 0, sizeof files);- storage_full = s % 37 == 36;- script = random_keys, watch = check_state;- frame_no = 0, quit_at = 2000 + rnd() % 6000, held_until = 0, bad_frames = 0;- pg_app_main();- sessions++;- storage_full = false;- pg_file f;- if (save_load(&f)) kept += f.has_race;- CHECK(!bad_frames, "session %d: %d bad frames", s, bad_frames);- }- script = 0, watch = 0;- printf(" keys: %d sessions of random keys, quit with Home each time (%d left a race going)\n", sessions, kept);-}--static void test(const char *dir) {- (void)dir;- printf("the roads\n");- roads();- printf("laps\n");- laps();- printf("physics\n");- physics();- printf("crashes\n");- crashes();- printf("rivals\n");- rivals();- printf("racing\n");- racing();- printf("the endless road\n");- endless();- printf("the same race\n");- same_twice();- printf("saves\n");- saves();- printf("the app\n");- race_app();- endless_app();- fuzz();- printf(fails ? "%d FAILED\n" : "all good\n", fails);-}--/* ---------------------------------------------------------------- pictures */-static void picture(const char *dir, const char *name) {- pg_render(&sv, &track, &prev, &sv.race, 256, &ui, &ghost_now);- shot(dir, name);-}--static void race_at(int id, int vehicle, int rivals, float metres, int view) {- memset(&sv, 0, sizeof sv);- pg_fresh(&sv.p);- sv.p.track = (uint8_t)id, sv.p.vehicle = (uint8_t)vehicle, sv.p.rivals = (uint8_t)rivals, sv.p.view = (uint8_t)view;- sv.p.guide = 1;- race_begin();- bot_line = 0;- while (sv.race.car[0].s < (int32_t)(metres * FX) && sv.race.phase != PH_DONE) {- prev = sv.race;- pg_step(&sv.race, &track, bot(&sv.race, &track), 0);- }- prev = sv.race;- ui.screen = V_RACE;-}--static void endless_at(float metres, uint32_t seed) {- memset(&sv, 0, sizeof sv);- pg_fresh(&sv.p);- sv.p.mode = MODE_ENDLESS, sv.p.guide = 1;- rnd_state = seed;- race_begin();- bot_line = 0;- while (sv.race.car[0].s < (int32_t)(metres * FX) && sv.race.phase != PH_DONE) {- prev = sv.race;- pg_step(&sv.race, &track, bot(&sv.race, &track), 0);- }- prev = sv.race;- ui.screen = V_RACE;-}--static void shots(const char *dir) {- memset(&sv, 0, sizeof sv);- pg_fresh(&sv.p);- now = 1000;- to_title();- ui.clock = 2600;- picture(dir, "title");- ui.screen = V_SETUP, ui.sel = SET_START;- show_circuit(0);- picture(dir, "setup");- ui.sel = SET_CAR;- picture(dir, "setup_car");- ui.screen = V_RECORDS;- picture(dir, "records");- for (int k = 0; k < PG_HELP_PAGES; k++) {- ui.screen = V_HELP, ui.page = (uint8_t)k;- char n[16];- snprintf(n, sizeof n, "help%d", k);- picture(dir, n);- }- race_at(0, 0, 7, -1, VIEW_CHASE);- picture(dir, "grid");- static const float AT[3] = {420, 600, 500};- for (int id = 0; id < PG_CIRCUITS; id++) {- race_at(id, id, 7, AT[id], VIEW_CHASE);- char n[16];- snprintf(n, sizeof n, "track%d", id);- picture(dir, n);- }- race_at(2, 3, 5, 700, VIEW_CHASE);- picture(dir, "horse");- race_at(1, 1, 5, 900, VIEW_FAR);- picture(dir, "far");- race_at(0, 2, 5, 300, VIEW_BUMPER);- picture(dir, "bumper");- ui.screen = V_PAUSE, ui.sel = 0;- picture(dir, "pause");- ui.screen = V_LEAVE, ui.sel = 1;- picture(dir, "leave");- for (int z = 0; z < 5; z++) {- endless_at(400 + 430 * z, 7 + z);- char n[16];- snprintf(n, sizeof n, "endless%d", z);- picture(dir, n);- }- /* a race to the end, then its results */- race_at(0, 1, 5, 99999, VIEW_CHASE);- while (!race_over(&sv.race)) prev = sv.race, pg_step(&sv.race, &track, 0, 0);- prev = sv.race;- finish_race();- picture(dir, "result");- /* the endless road, out of time, then its results */- endless_at(1e6f, 3);- while (!race_over(&sv.race)) prev = sv.race, pg_step(&sv.race, &track, 0, 0);- ui.screen = V_RACE;- prev = sv.race;- picture(dir, "timeup");- finish_race();- picture(dir, "result_endless");- /* the horses, close */- for (int v = 3; v < 5; v++) {- memset(&sv, 0, sizeof sv);- pg_fresh(&sv.p);- sv.p.vehicle = (uint8_t)v;- to_title();- ui.clock = 1800 + v * 900;- char n[16];- snprintf(n, sizeof n, "title_v%d", v);- picture(dir, n);- }- race_at(1, 4, 3, 300, VIEW_CHASE);- picture(dir, "mustang");- /* the title with a race kept, the questions */- sv.has_race = 1;- to_title();- ui.clock = 900;- picture(dir, "title_continue");- ui.screen = V_QUIT, ui.sel = 0;- picture(dir, "quit");- ui.screen = V_NEWRUN, ui.sel = 0;- picture(dir, "newrun");- ui.screen = V_GUIDE, ui.page = 0;- picture(dir, "guide");- sv.p.best_ms[0] = 101230, sv.p.best_lap_ms[0] = 32870, sv.p.best_ms[2] = 152110, sv.p.best_lap_ms[2] = 49010;- sv.p.best_m = 9420, sv.p.best_zone = 23, sv.p.races = 12, sv.p.wins = 5;- ui.screen = V_RECORDS;- picture(dir, "records_full");- ui.screen = V_TITLE, ui.sel = 0, ui.save_failed = true;- picture(dir, "title_full");- ui.save_failed = false;-}--/* the README's pictures: a race on each circuit, taken when the most rivals are close ahead (the race is run once to- find that moment, then again to it) */-static void doc_race(const char *dir, const char *name, int id, int vehicle, int view, int after_ms) {- int best_t = -1, best_n = 0;- for (int pass = 0; pass < 2; pass++) {- memset(&sv, 0, sizeof sv);- pg_fresh(&sv.p);- sv.p.track = (uint8_t)id, sv.p.vehicle = (uint8_t)vehicle, sv.p.view = (uint8_t)view, sv.p.rivals = 7, sv.p.guide = 1;- now = 0, rnd_state = 1;- race_begin();- ui.screen = V_RACE;- bot_line = 0, bot_skill = 100;- for (int t = 0; t < 3 * 60000 && sv.race.phase != PH_DONE; t += PG_TICK) {- prev = sv.race;- int lap = sv.race.lap;- pg_step(&sv.race, &track, bot(&sv.race, &track), 0);- ghost_after_step(lap);- if (pass == 1) {- if (t == best_t) break;- continue;- }- if (t < after_ms || sv.race.banner_t || abs(sv.race.car[0].x) > PG_ROAD - FX || abs(sv.race.car[0].ang) > 1500) continue;- int close = 0;- for (int i = 1; i <= sv.race.rivals; i++) {- int32_t ds = pg_wrap(&track, sv.race.car[i].s - sv.race.car[0].s);- if (ds > 9 * FX && ds < 70 * FX) close += ds < 35 * FX ? 2 : 1;- }- if (close > best_n) best_n = close, best_t = t;- }- }- prev = sv.race;- ui.clock = sv.race.time_ms;- ghost_pose(256);- picture(dir, name);-}--static void docs(const char *dir) {- doc_race(dir, "shot", 0, 0, VIEW_CHASE, 6000);- doc_race(dir, "wangan", 1, 1, VIEW_CHASE, 6000);- doc_race(dir, "akagi", 2, 2, VIEW_CHASE, 9000);- endless_at(2700, 21);- picture(dir, "endless");- memset(&sv, 0, sizeof sv);- pg_fresh(&sv.p);- now = 0;- to_title();- ui.clock = 2300;- picture(dir, "title");- sv.p.vehicle = 4;- ui.clock = 4300;- picture(dir, "horse");- sv.p.vehicle = 0;- sv.p.best_ms[0] = 101230;- ui.screen = V_SETUP, ui.sel = SET_START;- show_circuit(0);- picture(dir, "setup");+ return in;}-/* raw frames of a race, the driver at the wheel, every `step` ms (for tools/record.py --frames) */-static void film(const char *dir, int ms, int id, int view, int vehicle, int step) {- memset(&sv, 0, sizeof sv);- pg_fresh(&sv.p);- sv.p.track = (uint8_t)id, sv.p.view = (uint8_t)view, sv.p.vehicle = (uint8_t)vehicle, sv.p.rivals = 7, sv.p.guide = 1;- sv.p.level = LEVEL_NORMAL;- now = 0;- race_begin();- ui.screen = V_RACE;- bot_line = 0, bot_skill = 100;- int frame = 0;- for (int t = 0; t < ms; t += PG_TICK) {- prev = sv.race;- int lap = sv.race.lap;- pg_step(&sv.race, &track, bot(&sv.race, &track), 0);- ghost_after_step(lap);- if (t % step) continue;- ui.clock = (uint32_t)t;- ghost_pose(256);- pg_render(&sv, &track, &prev, &sv.race, 256, &ui, &ghost_now);- char path[512];- snprintf(path, sizeof path, "%s/%06d_%06d.raw", dir, frame++, t);- FILE *f = fopen(path, "wb");- if (!f) exit(2);- fwrite(fb, 2, 320 * 240, f);- fclose(f);- }+/* drives track t with its route; returns the finish frame (0: not finished by max) */+static uint32_t drive(int t, const route_t *r, uint32_t max, uint32_t *hash) {+ world_load(t);+ static car_t c;+ car_reset(&c);+ for (uint32_t f = 0; f < max && !c.finish; f++) car_step(&c, route_input(r, f));+ if (hash) *hash = car_hash(&c);+ return c.finish;}-/* the busiest frames of whole races: triangles, for every circuit and view */-static void busy(void) {- for (int view = 0; view < VIEWS; view++)- for (int id = 0; id < PG_CIRCUITS; id++) {- memset(&sv, 0, sizeof sv);- pg_fresh(&sv.p);- sv.p.track = (uint8_t)id, sv.p.rivals = 7, sv.p.view = (uint8_t)view, sv.p.guide = 1;- race_begin();- bot_line = 0;- int most = 0, at = 0, drops = 0;- ui.screen = V_RACE;- for (int i = 0; i < 6000 && sv.race.phase != PH_DONE; i++) {- prev = sv.race;- pg_step(&sv.race, &track, bot(&sv.race, &track), 0);- if (i % 3) continue;- pg_render(&sv, &track, &prev, &sv.race, 256, &ui, &ghost_now);- if (rd_tris > most) most = rd_tris, at = i;- drops += rd_dropped;- }- printf("view %d %-17s most %d triangles at step %d, %d frames out of room\n", view, pg_circuit_name[id], most, at, drops);- }+static void render_race(const car_t *c, chase_t *ch, float dt) {+ look = car_look_of(c);+ look.paint = sv.p.paint;+ chase_update(ch, &cam, dt, look.pos, look.rot, c->speed);+ ui.screen = V_RACE, ui.started = 1;+ pt_render(&sv, c, &cam, &look, NULL, &ui);}int main(int argc, char **argv) {- if (argc >= 3 && !strcmp(argv[1], "docs")) {- docs(argv[2]);+ if (argc < 3) {+ printf("play test|shots|view|film DIR ...\n");+ return 2;+ }+ const char *dir = argv[2];+ if (!strcmp(argv[1], "view")) {+ int t = argc > 3 ? atoi(argv[3]) : 0;+ uint32_t ms = argc > 4 ? (uint32_t)atoi(argv[4]) : 0;+ world_load(t);+ car_reset(&car);+ chase_reset(&chase, car.pos, car.rot);+ for (uint32_t f = 0; f < ms; f++) {+ car_step(&car, route_input(&pt_routes[t], f));+ if (f % 33 == 0) chase_update(&chase, &cam, 0.033f, car.pos, car.rot, car.speed);+ }+ sv.p.track = (uint8_t)t;+ render_race(&car, &chase, 0.0f);+ printf("track %s frame %u pos %.2f %.2f %.2f speed %.1f cp %d tris %d%s\n", pt_tracks[t].name, car.frames,+ (double)car.pos.x, (double)car.pos.y, (double)car.pos.z, (double)car.speed, car.next_cp, rd_tris,+ rd_dropped ? " (dropped)" : "");+ shot(dir, "view");return 0;}- if (argc >= 5 && !strcmp(argv[1], "film")) {- film(argv[2], atoi(argv[3]), atoi(argv[4]), argc > 5 ? atoi(argv[5]) : 0, argc > 6 ? atoi(argv[6]) : 0,- argc > 7 ? atoi(argv[7]) : 60);- return 0;- }- if (argc >= 2 && !strcmp(argv[1], "busy")) {- busy();+ if (!strcmp(argv[1], "film")) {+ int t = argc > 3 ? atoi(argv[3]) : 0;+ uint32_t ms = argc > 4 ? (uint32_t)atoi(argv[4]) : 10000, step = argc > 5 ? (uint32_t)atoi(argv[5]) : 40;+ world_load(t);+ car_reset(&car);+ chase_reset(&chase, car.pos, car.rot);+ sv.p.track = (uint8_t)t;+ int n = 0;+ for (uint32_t f = 0; f < ms; f++) {+ car_step(&car, route_input(&pt_routes[t], f));+ if (f % step == 0) {+ render_race(&car, &chase, (float)step / 1000.0f);+ char path[512];+ snprintf(path, sizeof path, "%s/%06d_%06u.raw", dir, n++, f);+ FILE *o = fopen(path, "wb");+ if (!o) return 2;+ fwrite(fb, 1, sizeof fb, o);+ fclose(o);+ }+ }return 0;}- if (argc >= 3 && !strcmp(argv[1], "test")) {- test(argv[2]);+ if (!strcmp(argv[1], "test")) {+ for (int t = 0; t < PT_NTRACKS; t++) {+ uint32_t h;+ uint32_t fin = drive(t, &pt_routes[t], 600000, &h);+ printf("%-9s %s %u ms, hash %08x\n", pt_tracks[t].name, fin ? "finished in" : "NOT FINISHED", fin, h);+ CHECK(fin, "%s not finished", pt_tracks[t].name);+ }+ printf(fails ? "%d FAILED\n" : "all good\n", fails);return fails ? 1 : 0;}- if (argc >= 3 && !strcmp(argv[1], "shots")) {- shots(argv[2]);- return 0;- }- fprintf(stderr, "usage: play test DIR | shots DIR | docs DIR | film DIR MS CIRCUIT\n");+ (void)forget, (void)file_data, (void)storage_full, (void)quit_at, (void)script, (void)watch;return 2;}diff --git a/games/polytrack/tests/routes.h b/games/polytrack/tests/routes.hnew file mode 100644index 00000000..b471836f--- /dev/null+++ b/games/polytrack/tests/routes.h@@ -0,0 +1,14 @@+/* A run to the finish for each official track: the keys held from a frame on (IN_ bits of car.h). Found by+ * tests/route.c, a driver that tries keys ahead with the game's own physics. */+#ifndef PT_ROUTES_H+#define PT_ROUTES_H+#include <stdint.h>+typedef struct { uint32_t frame; uint8_t keys; } route_ev;+typedef struct { const route_ev *ev; int n; } route_t;+static const route_ev r_default[] = {{0, 1}};+static const route_t pt_routes[17] = {+ {r_default, 1}, {r_default, 1}, {r_default, 1}, {r_default, 1}, {r_default, 1}, {r_default, 1}, {r_default, 1},+ {r_default, 1}, {r_default, 1}, {r_default, 1}, {r_default, 1}, {r_default, 1}, {r_default, 1}, {r_default, 1},+ {r_default, 1}, {r_default, 1}, {r_default, 1},+};+#endif