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
Doom: Read This! shows the calculator's keys, more room for the levels, pictures and checks
Mason363804100778291
diff --git a/docs/media/doom.gif b/docs/media/doom.gifnew file mode 100644index 00000000..1c460933Binary files /dev/null and b/docs/media/doom.gif differdiff --git a/docs/media/gallery/doom.gif b/docs/media/gallery/doom.gifnew file mode 100644index 00000000..76db2c14Binary files /dev/null and b/docs/media/gallery/doom.gif differdiff --git a/docs/media/thumb_doom.png b/docs/media/thumb_doom.pngnew file mode 100644index 00000000..ce9796caBinary files /dev/null and b/docs/media/thumb_doom.png differdiff --git a/games/doom/Makefile b/games/doom/Makefileindex 70fd6c2d..f6e46907 100644--- a/games/doom/Makefile+++ b/games/doom/Makefile@@ -3,6 +3,7 @@# make check link it like the calculator does (output/doom.bin)# make host build/play: the game on a computer, for tests and screenshots# make test the game played on a computer (tests/check.py, with the sanitizers)+# make media the pictures of docs/ and the animations of the repository's docs/media (tools/media.py)# make data src/doom1.whx from the shareware DOOM1.WAD (tools/fetch.py downloads it; WAD=its path)Q ?= @# the ARM toolchain on the PATH, or in TOOLCHAIN=<its bin folder>@@ -41,7 +42,7 @@ comma = ,OBJ = $(patsubst src/%.c,$(BUILD_DIR)/obj/%.o,$(ENGINE) $(NW) src/nw/plat_eadk.c) $(BUILD_DIR)/obj/pd_render.o-.PHONY: build check clean host test data+.PHONY: build check clean host test data mediabuild: $(BUILD_DIR)/doom.nwa# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones)@@ -75,7 +76,7 @@ $(BUILD_DIR):$(Q) mkdir -p $@# on a computer: tests/play.c plays it with scripted keys and saves screenshots-HOST_FLAGS = -O1 -g -fwrapv -DHOST=1 $(INC) -I../common+HOST_FLAGS = -O1 -g -fwrapv -DHOST=1 $(INC) -I../common $(HOST_EXTRA)HOST_SAN = -fsanitize=address,undefined -fno-sanitize=shift -fno-sanitize-recover=undefinedHOST_OBJ = $(patsubst src/%.c,build/host/%.o,$(ENGINE) $(NW) src/nw/plat_host.c) build/host/pd_render.o \build/host/play.o build/host/data.o@@ -99,6 +100,9 @@ build/play: $(HOST_OBJ)test: build/playpython3 tests/check.py build/play+media: build/play+ python3 tools/media.py build/play+# the packed WAD: whd_gen (RP2040 Doom's converter) built on the computer, without the sounds and musicWHD_GEN = build/whd_genWHD_GEN_C = tools/whd_gen/musx_decoder.c tools/whd_gen/adpcm-lib.c src/tiny_huff.c src/image_decoder.cdiff --git a/games/doom/README.md b/games/doom/README.mdnew file mode 100644index 00000000..b1eaef42--- /dev/null+++ b/games/doom/README.md@@ -0,0 +1,108 @@+> **Doom is a [NumPlay](../../README.md) game that comes on its own.** It is too big to sit next to NumPlay. Get `Doom.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).++<p align="center">+ <img src="src/icon.png" width="84" alt="Doom icon">+</p>++<h1 align="center">Doom</h1>++<p align="center">+ <b>Rip and tear through the moon bases of Mars, on the NumWorks calculator.</b><br>+ id Software's Doom, the shareware episode: Knee-Deep in the Dead, all nine levels, run by the real Doom engine.+</p>++<p align="center">+ <a href="https://github.com/Mason363/NumPlay/releases/latest/download/Doom.nwa"><b>Download Doom.nwa</b></a>+ · <a href="#controls">Controls</a>+</p>++<p align="center">+ <img src="../../docs/media/doom.gif" width="640" alt="The marine fighting zombiemen and imps through the Phobos lab">+</p>++## Highlights++* **The real game:** the Doom engine itself (Chocolate Doom, by way of RP2040 Doom), not a lookalike. Monsters think, doors open, lifts rise and fall, barrels explode and the levels play exactly as on a PC in 1993: even the demos it plays on the title screen run as they were recorded.+* **Knee-Deep in the Dead, all of it:** Hangar, Nuclear Plant, Toxin Refinery, Command Control, Phobos Lab, Central Processing, Computer Station, Phobos Anomaly and the secret Military Base, with their secrets, keys, switches and the Barons of Hell at the end.+* **Everything from the shareware WAD:** every wall, floor, sprite, menu and screen, the status bar with the marine's face, the automap, the intermission maps of Phobos with your kills, items, secrets and time, and the episode's ending.+* **The whole 320 x 200 picture:** drawn at Doom's own resolution with its light levels and its palette, the screen flashing red when you're hurt and gold when you pick something up, and stretched to the calculator's 320 x 240 the way monitors of the day made Doom's pixels a little taller.+* **The five skill levels,** from I'm too young to die to Nightmare!, and the menus as they were: New Game, Options, Load Game, Save Game, Read This! and Quit Game.+* **Saved like in the game:** six save slots, named after their level. Home keeps the moment you were at, and the next start puts you back there. Your saves are also copied into `doom_saves.py`, so installing the app again doesn't erase them.++<table>+ <tr>+ <td align="center"><img src="docs/title.png" width="390" alt="The title screen"><br><sub>The title screen</sub></td>+ <td align="center"><img src="docs/hangar.png" width="390" alt="E1M1: Hangar, the courtyard"><br><sub>E1M1: Hangar</sub></td>+ </tr>+ <tr>+ <td align="center"><img src="docs/imps.png" width="390" alt="Imps coming down a corridor"><br><sub>Imps down the corridor</sub></td>+ <td align="center"><img src="docs/fight.png" width="390" alt="Shooting zombiemen and a sergeant"><br><sub>Zombiemen around the yellow key</sub></td>+ </tr>+ <tr>+ <td align="center"><img src="docs/lab.png" width="390" alt="An imp's fireball over the slime"><br><sub>E1M5: Phobos Lab</sub></td>+ <td align="center"><img src="docs/automap.png" width="390" alt="The automap"><br><sub>The automap</sub></td>+ </tr>+ <tr>+ <td align="center"><img src="docs/intermission.png" width="390" alt="The intermission"><br><sub>Hangar finished</sub></td>+ <td align="center"><img src="docs/menu.png" width="390" alt="The main menu over the game"><br><sub>The main menu over the game</sub></td>+ </tr>+ <tr>+ <td align="center"><img src="docs/keys.png" width="390" alt="The calculator's keys, in Read This!"><br><sub>Read This!: the calculator's keys</sub></td>+ <td align="center"><img src="docs/ending.png" width="390" alt="The episode's ending"><br><sub>The end of Knee-Deep in the Dead</sub></td>+ </tr>+</table>++## How to play++Press a key on the title screen for the menu, then choose New Game, Knee-Deep in the Dead and a skill level. Find the exit of each level, shooting what gets in your way: keycards open the doors of their colour, and walls that look a little different may hide a secret. Back opens the menu (and pauses the game), where you can save, load, change the options or read the keys again.++## Controls++| Key | What it does |+| --- | --- |+| Up / Down | Walk forward / back |+| Left / Right | Turn |+| OK | Fire |+| ⌫ or EXE | Use: open doors, press switches |+| shift (held) | Strafe with Left and Right |+| x,n,t / var | Strafe left / right |+| alpha (held) | Run |+| 1 to 7 | Choose a weapon |+| Toolbox | Automap (+ and − zoom, × follows you, ÷ shows the grid, 0 shows the whole map) |+| √ | Brightness |+| Back | Menu and pause; back one menu |+| Home | Keep the moment and quit |++In menus, the arrows choose, OK or EXE confirms and Back goes back. When the game asks a question, OK says yes and Back says no. Read This! in the menu shows these keys, and the very first game starts with a word on them.++## Good to know++* **No sound:** the calculator has no speaker, so Doom plays in silence.+* **Saves:** a save takes a few KB of the calculator's 42 KB of files, and its copy in `doom_saves.py` as much again. If there is no room, the game says so: delete a slot or an old script.+* **Its own pace:** the game thinks 35 times a second, as Doom always did, and draws up to 35 frames a second. Where a room is too much for the calculator, it draws fewer frames, but monsters, doors and you keep their speed.+* **The odd black stripe:** a frame has room for 3,600 slices of wall and sprite, as in RP2040 Doom. In the very busiest views, a narrow black stripe can flash for a frame where they run out.+* **Only the shareware episode:** the registered episodes (The Shores of Hell and Inferno) are not part of the free shareware WAD.++## How it's made++The calculator gives an app about 130 KB of RAM: Doom on a PC asked for 4 MB. This port runs Graham Sanderson's [RP2040 Doom](https://github.com/kilograham/rp2040-doom), which made all of the shareware DOOM1.WAD playable on a 264 KB microcontroller: the WAD is packed into its WHD format (1.4 MB without the sounds and music, read in place from flash), the levels are never copied to RAM, and the game's objects are squeezed with 16-bit pointers.++The calculator has less RAM still, and no room for a frame buffer: the screen is drawn 40 rows at a time. Each frame the engine walks the level once and keeps every column of wall, floor and sprite it would draw; then each band of rows is drawn from those lists, its floors and ceilings first, then its walls and things, texture by texture, and pushed to the screen through Doom's palette.++`make` builds `output/doom.nwa` (needs `arm-none-eabi-gcc` and Node.js for nwlink). `make test` plays it on a computer with the sanitizers on. `python3 tools/fetch.py build/ref` downloads the shareware DOOM1.WAD and `make data WAD=build/ref/doom1.wad` packs it again into `src/doom1.whx`.++## Credits++Doom is id Software's game (1993). Not affiliated with id Software, ZeniMax or Bethesda.++* **[RP2040 Doom](https://github.com/kilograham/rp2040-doom)** by Graham Sanderson: the engine, the WHD format and its converter (`tools/whd_gen`), and the renderer this port draws in bands.+* **[Chocolate Doom](https://github.com/chocolate-doom/chocolate-doom)** by Simon Howard and its contributors, which RP2040 Doom is made from.+* **The Doom source code** released by id Software in 1997 under the GNU GPL.+* **The shareware DOOM1.WAD** (version 1.9), which id Software lets anyone copy: its levels, pictures and texts.+* **[ADPCM-XQ](https://github.com/dbry/adpcm-xq)** by David Bryant and **[LodePNG](https://github.com/lvandeve/lodepng)** by Lode Vandevenne, used by the converter.++Made by Mason Chen as part of NumPlay.++## License++The engine is licensed under the GNU General Public License, version 2 or later (`COPYING.md`); RP2040 Doom's own files under the BSD 3-Clause license, as they say at their top; the converter's libraries under their own licenses (`tools/whd_gen`). NumPlay's code is licensed under the GNU General Public License v3.0: see the `LICENSE` file at the root of the repository. The shareware DOOM1.WAD packed into `src/doom1.whx` is id Software's, copied under the terms that let anyone share it.diff --git a/games/doom/docs/automap.png b/games/doom/docs/automap.pngnew file mode 100644index 00000000..49ab5efbBinary files /dev/null and b/games/doom/docs/automap.png differdiff --git a/games/doom/docs/ending.png b/games/doom/docs/ending.pngnew file mode 100644index 00000000..5306ba7bBinary files /dev/null and b/games/doom/docs/ending.png differdiff --git a/games/doom/docs/fight.png b/games/doom/docs/fight.pngnew file mode 100644index 00000000..907e134eBinary files /dev/null and b/games/doom/docs/fight.png differdiff --git a/games/doom/docs/hangar.png b/games/doom/docs/hangar.pngnew file mode 100644index 00000000..1c2a0190Binary files /dev/null and b/games/doom/docs/hangar.png differdiff --git a/games/doom/docs/imps.png b/games/doom/docs/imps.pngnew file mode 100644index 00000000..268f330fBinary files /dev/null and b/games/doom/docs/imps.png differdiff --git a/games/doom/docs/intermission.png b/games/doom/docs/intermission.pngnew file mode 100644index 00000000..316ede9aBinary files /dev/null and b/games/doom/docs/intermission.png differdiff --git a/games/doom/docs/keys.png b/games/doom/docs/keys.pngnew file mode 100644index 00000000..15bcf77bBinary files /dev/null and b/games/doom/docs/keys.png differdiff --git a/games/doom/docs/lab.png b/games/doom/docs/lab.pngnew file mode 100644index 00000000..78b9e457Binary files /dev/null and b/games/doom/docs/lab.png differdiff --git a/games/doom/docs/menu.png b/games/doom/docs/menu.pngnew file mode 100644index 00000000..3271f86dBinary files /dev/null and b/games/doom/docs/menu.png differdiff --git a/games/doom/docs/title.png b/games/doom/docs/title.pngnew file mode 100644index 00000000..95d8603fBinary files /dev/null and b/games/doom/docs/title.png differdiff --git a/games/doom/src/doom/d_main.c b/games/doom/src/doom/d_main.cindex eedb9696..39c0d2fe 100644--- a/games/doom/src/doom/d_main.c+++ b/games/doom/src/doom/d_main.c@@ -2126,12 +2126,14 @@ void D_DoomMain (void)// the calculator's keys and settings; the moment kept by Home, if there is one, comes backnw_input_init();nw_settings_load();-#ifdef NW_WARP- autostart = true;- startepisode = NW_WARP / 10;- startmap = NW_WARP % 10;- startskill = sk_hard;-#endif+ if (nw_warp)+ {+ // (tests: straight into a level, on Ultra-Violence)+ autostart = true;+ startepisode = nw_warp / 10;+ startmap = nw_warp % 10;+ startskill = sk_hard;+ }if (nw_resume_ready()){g_load_slot = NW_RESUME_SLOT;diff --git a/games/doom/src/doom/g_game.c b/games/doom/src/doom/g_game.cindex 5f1f2bc2..48e27047 100644--- a/games/doom/src/doom/g_game.c+++ b/games/doom/src/doom/g_game.c@@ -773,7 +773,7 @@ void G_DoLoadLevel (void){players[consoleplayer].message = "Press escape to quit.";}-}+}#if !NO_USE_JOYSTICKstatic void SetJoyButtons(unsigned int buttons_mask)@@ -2026,8 +2026,15 @@ void G_DoNewGame(boolean net)fastparm = false;nomonsters = false;G_InitNew (d_skill, d_episode, d_map);- gameaction = ga_nothing;-}+ gameaction = ga_nothing;+#if NUMWORKS+ if (nw_first_start)+ {+ players[consoleplayer].message = "OK FIRES, EXE OPENS DOORS, BACK: MENU";+ nw_first_start = false;+ }+#endif+}voiddiff --git a/games/doom/src/doom/m_menu.c b/games/doom/src/doom/m_menu.cindex fc0e0cef..4571fd09 100644--- a/games/doom/src/doom/m_menu.c+++ b/games/doom/src/doom/m_menu.c@@ -989,13 +989,52 @@ void M_DrawReadThis1(void)return;}#endif+#if NUMWORKS+ inhelpscreens = 4; // the calculator's keys (M_DrawKeys)+#elseinhelpscreens = 2;+#endif#if !USE_WHDV_DrawPatchDirect(0, 0, W_CacheLumpName(DEH_String("HELP2"), PU_CACHE));#endif}+#if NUMWORKS+// the first page of Read This!: the calculator's keys, drawn by the renderer over a flat, band by band+static const char *const keys_page[][2] = {+ {"UP, DOWN", "WALK FORWARD, BACK"},+ {"LEFT, RIGHT", "TURN"},+ {"OK", "FIRE"},+ {"EXE, BACKSPACE", "USE: DOORS, SWITCHES"},+ {"HOLD SHIFT", "STRAFE WITH LEFT, RIGHT"},+ {"X,N,T VAR", "STRAFE LEFT, RIGHT"},+ {"HOLD ALPHA", "RUN"},+ {"1 TO 7", "WEAPONS"},+ {"TOOLBOX", "AUTOMAP"},+ {" + -", "ZOOM IN, OUT"},+ {" * / 0", "FOLLOW, GRID, WHOLE MAP"},+ {"SQUARE ROOT", "BRIGHTNESS"},+ {"BACK", "MENU AND PAUSE"},+ {"HOME", "KEEP THE MOMENT AND QUIT"},+};++void M_DrawKeys(void)+{+ static const char title[] = "THE CALCULATOR'S KEYS";+ static const char menus[] = "IN MENUS: ARROWS, OK AND BACK";+ int y = 22;++ M_WriteText((SCREENWIDTH - M_StringWidth(title)) / 2, 6, title);+ for (unsigned i = 0; i < sizeof(keys_page) / sizeof(keys_page[0]); i++, y += 11)+ {+ M_WriteText(20, y, keys_page[i][0]);+ M_WriteText(128, y, keys_page[i][1]);+ }+ M_WriteText(20, y + 6, menus);+}+#endif+//@@ -1009,7 +1048,11 @@ void M_DrawReadThis2(void)return;}#endif+#if NUMWORKS+ inhelpscreens = 2; // (the order page: HELP1's keys are a PC's)+#elseinhelpscreens = 1;+#endif// We only ever draw the second page if this is// gameversion == exe_doom_1_9 and gamemode == registereddiff --git a/games/doom/src/doom/m_menu.h b/games/doom/src/doom/m_menu.hindex 3fd3c43a..2dc64b5c 100644--- a/games/doom/src/doom/m_menu.h+++ b/games/doom/src/doom/m_menu.h@@ -59,6 +59,9 @@ void M_SaveGame(int choice);void M_ClearMenus (void);extern uint8_t inhelpscreens;+#if NUMWORKS+void M_DrawKeys(void); // (Read This!'s first page, inhelpscreens 4)+#endifextern isb_int8_t detailLevel;extern isb_int8_t screenblocks;diff --git a/games/doom/src/nw/doomconf.h b/games/doom/src/nw/doomconf.hindex 4317e7a3..74fc2548 100644--- a/games/doom/src/nw/doomconf.h+++ b/games/doom/src/nw/doomconf.h@@ -98,7 +98,9 @@/* the renderer (pd_render.cpp), with room for this many runs of pixels in the view each frame */#define PICODOOM_RENDER_NEWHOPE 1#define MERGE_DISTSCALE0_INTO_VIEWCOSSINANGLE 1-#define NW_RENDER_COL_MAX 3000+#ifndef NW_RENDER_COL_MAX+#define NW_RENDER_COL_MAX 3600+#endif/* the calculator: no speaker, one core, files in Epsilon's file system */#define NO_USE_SOUND 1diff --git a/games/doom/src/nw/i_video.c b/games/doom/src/nw/i_video.cindex 09d9064c..a4b6d4a7 100644--- a/games/doom/src/nw/i_video.c+++ b/games/doom/src/nw/i_video.c@@ -28,17 +28,12 @@ int mouse_threshold = 10;uint8_t next_video_type, next_frame_index, next_overlay_index;semaphore_t render_frame_ready, display_frame_freed;-#define BAND_H 40-static uint8_t __attribute__((aligned(8))) band[SCREENWIDTH * BAND_H];static uint16_t palette[256];static int8_t next_pal = 0; /* the palette to use from the next frame, -1 when it is the one in use */static int8_t last_gamma = -1;void pd_init(void);-void I_InitGraphics(void) {- nw_band = band;- pd_init();-}+void I_InitGraphics(void) { pd_init(); }void I_ShutdownGraphics(void) {}void I_StartFrame(void) {}void I_UpdateNoBlit(void) {}@@ -102,7 +97,7 @@ void nw_frame_end(void) { host_frame(); }void nw_frame_end(void) {}#endif-void nw_band_begin(int y0, int y1) {+void nw_band_begin(uint8_t *band, int y0, int y1) {nw_band = band;nw_band_y0 = y0;nw_band_y1 = y1;@@ -112,7 +107,7 @@ void nw_band_begin(int y0, int y1) {void nw_band_end(void) {uint16_t lines[SCREENWIDTH * 6];for (int y = nw_band_y0; y < nw_band_y1; y += 5) {- const uint8_t *src = band + (y - nw_band_y0) * SCREENWIDTH;+ const uint8_t *src = nw_band + (y - nw_band_y0) * SCREENWIDTH;uint16_t *d = lines;for (int j = 0; j < 5; j++) {for (int i = 0; i < SCREENWIDTH; i++) d[i] = palette[src[i]];diff --git a/games/doom/src/nw/main.c b/games/doom/src/nw/main.cindex d256afdb..b6f8be12 100644--- a/games/doom/src/nw/main.c+++ b/games/doom/src/nw/main.c@@ -10,6 +10,11 @@void D_DoomMain(void);+#ifndef NW_WARP+#define NW_WARP 0+#endif+int nw_warp = NW_WARP;+#if !defined(HOST)const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Doom";const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;diff --git a/games/doom/src/nw/nw.h b/games/doom/src/nw/nw.hindex a5c895cd..5c4e3ebd 100644--- a/games/doom/src/nw/nw.h+++ b/games/doom/src/nw/nw.h@@ -3,8 +3,12 @@#define DOOM_NW_H#include "doomtype.h"-/* the zone on a computer: as much as the calculator's own software leaves */-#define NW_HOST_ZONE (60 * 1024)+/* the zone on a computer: the calculator's (about 53 KB), larger as the computer's pointers are 64-bit where+ * the calculator's levels use 16-bit ones (its levels take 1.7 to 1.8 times as much) */+#define NW_HOST_ZONE (96 * 1024)++/* tests: the level to start in (15 for E1M5), or 0 for the title (built with NW_WARP=15, or play --warp) */+extern int nw_warp;/* i_system.c: Home, On/Off and Quit end the main loop; I_Error and I_Quit jump back to main* (__builtin_setjmp and __builtin_longjmp on nw_exit) */@@ -28,4 +32,5 @@ void nw_resume_save(void); /* the game as it is now, if there is one tovoid nw_resume_done(void); /* the moment was read back: it goes */void nw_settings_load(void);void nw_settings_save(void);+extern boolean nw_first_start; /* no settings yet: the first game starts with a word on the keys */#endifdiff --git a/games/doom/src/nw/saves.c b/games/doom/src/nw/saves.cindex 9c65065f..4d7a5e6a 100644--- a/games/doom/src/nw/saves.c+++ b/games/doom/src/nw/saves.c@@ -155,9 +155,12 @@ void nw_resume_done(void) {}/* ------------------------------------------------------------------ settings */+boolean nw_first_start;+void nw_settings_load(void) {uint32_t len;const uint8_t *d = plat_load(CFG_NAME, &len);+ nw_first_start = !d;if (!d || len < 4 || d[0] != 'D' || d[1] != 1) return;showMessages = d[2] ? 1 : 0;usegamma = d[3] <= 4 ? d[3] : 0;diff --git a/games/doom/src/pd_render.cpp b/games/doom/src/pd_render.cppindex 005facee..5082614d 100644--- a/games/doom/src/pd_render.cpp+++ b/games/doom/src/pd_render.cpp@@ -175,7 +175,7 @@ extern "C" {extern uint8_t *nw_band;extern int nw_band_y0, nw_band_y1;extern boolean nw_direct;-void nw_band_begin(int y0, int y1);+void nw_band_begin(uint8_t *band, int y0, int y1);void nw_band_end(void);void nw_frame_begin(void);void nw_frame_end(void);@@ -358,16 +358,19 @@ static flat_run nw_flat_runs[NW_FLAT_RUNS];static int16_t nw_flat_run_count;#define flat_runs nw_flat_runs// for each column of a band, the next of its framedrawable (the column lists' own links stay as they are,-// for the next band), and the framedrawable itself (its field holds the column's x)-static int16_t fd_next[RENDER_COL_MAX];-static uint8_t col_fd[RENDER_COL_MAX];+// for the next band), and the framedrawable itself (its field holds the column's x); both on the stack of+// pd_end_frame, which has room to spare where the zone has none+static int16_t *fd_next;+static uint8_t *col_fd;#else#define flat_runs ((flat_run *)list_buffer)#endifstatic int16_t render_col_free;#if NUMWORKS-extern "C" { uint32_t nw_col_overflows, nw_col_peak; } // (tests read these)+// (tests read these: the most columns a frame had, the columns that found no room, how many frames had+// 0-249 columns, 250-499...)+extern "C" { uint32_t nw_col_overflows, nw_col_peak, nw_col_frames[40]; }#endifstatic int16_t alloc_pd_column(int x) {if (render_col_free < 0) {@@ -3195,6 +3198,25 @@ static void nw_clear_uncovered(int y0, int y1) {}}+// a flat tiled over the band (behind the ending's text, and darker behind the keys page)+static void nw_tile_flat(const char *name, int y0, int y1, int light = 0) {+ int flatnum = W_GetNumForName(name) - firstflat;+ uint8_t *flat_data = nullptr;+ for (int slot = 0; slot < cached_flat_slots; slot++) {+ if (cached_flat_picnum[slot] == flatnum) flat_data = cached_flat0 - slot * 4096;+ }+ if (!flat_data) flat_data = decode_flat_to_slot(0, flatnum);+ uint8_t *dest = nw_band;+ for (int y = y0; y < y1; y++) {+ const uint8_t *src = flat_data + (y & 63);+ for (int i = 0; i < SCREENWIDTH; i++) *dest++ = src[(i & 63) * 64];+ }+ if (light) {+ const lighttable_t *map = xcolormaps + 256 * light;+ for (uint8_t *p = nw_band; p < dest; p++) *p = map[*p];+ }+}+// a full screen picture behind everything when there is no level to seestatic void nw_draw_background(int y0, int y1) {int patch_num = 0;@@ -3203,6 +3225,7 @@ static void nw_draw_background(int y0, int y1) {case 1: patch_num = W_GetNumForName("HELP1"); break;case 2: patch_num = W_GetNumForName("HELP2"); break;case 3: patch_num = W_GetNumForName("HELP"); break;+ case 4: nw_tile_flat("FLOOR4_8", y0, y1, 22); return;}} else {switch (gamestate) {@@ -3214,18 +3237,7 @@ static void nw_draw_background(int y0, int y1) {break;case GS_FINALE:if (finalestage == F_STAGE_TEXT) {- // the tiled flat behind the text- int flatnum = W_GetNumForName(finaleflat) - firstflat;- uint8_t *flat_data = nullptr;- for (int slot = 0; slot < cached_flat_slots; slot++) {- if (cached_flat_picnum[slot] == flatnum) flat_data = cached_flat0 - slot * 4096;- }- if (!flat_data) flat_data = decode_flat_to_slot(0, flatnum);- uint8_t *dest = nw_band;- for (int y = y0; y < y1; y++) {- const uint8_t *src = flat_data + (y & 63);- for (int i = 0; i < SCREENWIDTH; i++) *dest++ = src[(i & 63) * 64];- }+ nw_tile_flat(finaleflat, y0, y1); // (the tiled flat behind the text)return;} else if (finalestage == F_STAGE_ARTSCREEN) {const char *ln = F_ArtScreenLumpName();@@ -3263,7 +3275,14 @@ void pd_end_frame(int wipe_start) {if (new_cache_flat_slots < 1) new_cache_flat_slots = 1;for (int i = cached_flat_slots; i < new_cache_flat_slots; i++) cached_flat_picnum[i] = 0xff;cached_flat_slots = new_cache_flat_slots;- if (view) nw_freeze_columns();+ int16_t fd_next_here[RENDER_COL_MAX];+ uint8_t col_fd_here[RENDER_COL_MAX];+ fd_next = fd_next_here;+ col_fd = col_fd_here;+ if (view) {+ nw_col_frames[render_col_count / 250 < 40 ? render_col_count / 250 : 39]++;+ nw_freeze_columns();+ }// what is drawn over the picture, gathered oncenw_patches[0].header.max = count_of(nw_patches) - 1;@@ -3284,9 +3303,10 @@ void pd_end_frame(int wipe_start) {if (pre_wipe_state == PRE_WIPE_EXTRA_FRAME_NEEDED) pre_wipe_state = PRE_WIPE_EXTRA_FRAME_DONE;nw_frame_begin();+ uint8_t __aligned(8) band[SCREENWIDTH * NW_BAND_H];for (int y0 = 0; y0 < SCREENHEIGHT; y0 += NW_BAND_H) {int y1 = y0 + NW_BAND_H;- nw_band_begin(y0, y1);+ nw_band_begin(band, y0, y1);render_frame_buffer = nw_band - y0 * SCREENWIDTH;I_VideoBuffer = render_frame_buffer;if (view) {@@ -3315,6 +3335,10 @@ void pd_end_frame(int wipe_start) {nw_direct = true;F_TextWrite();nw_direct = false;+ } else if ((inhelpscreens & 127) == 4) {+ nw_direct = true;+ M_DrawKeys();+ nw_direct = false;}}V_DrawPatchListBand(nw_patches);diff --git a/games/doom/tests/check.py b/games/doom/tests/check.pynew file mode 100644index 00000000..438add48--- /dev/null+++ b/games/doom/tests/check.py@@ -0,0 +1,115 @@+#!/usr/bin/env python3+"""Checks of Doom on a computer (make test): the host build, with AddressSanitizer and UBSan, through the+title and its demos, the menus, every level of the episode, an intermission, the ending, the saves and the+moment kept on Home.++ python3 tests/check.py build/play"""+import os+import re+import shutil+import subprocess+import sys+import tempfile++PLAY = sys.argv[1] if len(sys.argv) > 1 else "build/play"+failures = []+ENV = dict(os.environ, ASAN_OPTIONS="detect_leaks=0", UBSAN_OPTIONS="halt_on_error=1:print_stacktrace=1")+GS_LEVEL, GS_INTERMISSION, GS_FINALE, GS_DEMOSCREEN = 0, 1, 2, 3+++def run(args, saves=None, what=""):+ """Plays (in a save folder, a new one if None); returns the end state and the folder's files."""+ own = saves is None+ if own:+ saves = tempfile.mkdtemp(prefix="doom_check_")+ shots = tempfile.mkdtemp(prefix="doom_shots_")+ p = subprocess.run([PLAY, "--saves", saves, "--out", shots, "--stats"] + args, capture_output=True, text=True,+ env=ENV, timeout=1800)+ shutil.rmtree(shots, ignore_errors=True)+ files = sorted(os.listdir(saves))+ if own:+ shutil.rmtree(saves, ignore_errors=True)+ if p.returncode or "runtime error" in p.stderr or "AddressSanitizer" in p.stderr or "I_Error" in p.stderr:+ failures.append(f"{what or args}: crashed, an error or a sanitizer error\n{p.stderr[-2000:]}")+ return None+ m = re.search(r"END time (\d+) quit (\d+) state (\d+) map E(\d+)M(\d+) leveltime (-?\d+) health (-?\d+) kills (\d+)",+ p.stdout)+ s = re.search(r"STATS zone_free (-?\d+) columns peak (\d+) overflows (\d+) zone peak (\d+)", p.stdout)+ if not m or not s:+ failures.append(f"{what}: no end state\n{p.stdout[-500:]}")+ return None+ end = dict(zip(("time", "quit", "state", "episode", "map", "leveltime", "health", "kills"), map(int, m.groups())))+ end.update(zone_free=int(s.group(1)), columns=int(s.group(2)), overflows=int(s.group(3)), zone=int(s.group(4)),+ files=files)+ return end+++def check(cond, what):+ if not cond:+ failures.append(what)+ print(("ok " if cond else "FAIL"), what, flush=True)+++# the title, the credits and the three demos, which must play as they were recorded (they end in their+# levels at the same moment as on a PC: the title loop comes back around)+e = run(["--ms", "120000"], what="the demos")+if e:+ check(e["quit"] == 1, "the title and the demos play for two minutes and quit on Home")++# every level, walking, turning and firing on Ultra-Violence+walk = ",".join(f"{t}-{t + 900}:up,{t + 900}-{t + 1300}:right,{t + 300}-{t + 400}:ok" for t in range(1500, 20000, 1500))+for m in range(1, 10):+ e = run(["--warp", f"1{m}", "--keys", walk, "--ms", "21000"], what=f"E1M{m}")+ if e:+ check(e["state"] == GS_LEVEL and e["map"] == m and e["leveltime"] > 500,+ f"E1M{m}: played for {e['leveltime']} tics, health {e['health']}, {e['kills']} kills, "+ f"{e['columns']} columns at most, {e['zone'] // 1024} KB of the zone")++# a level's exit: the intermission, then the next level+e = run(["--warp", "11", "--exit-at", "3000", "--keys", "9000:ok,11000:ok,13000:ok", "--ms", "20000"],+ what="E1M1's exit")+if e:+ check(e["state"] == GS_LEVEL and e["map"] == 2, "E1M1's exit: the intermission, then E1M2")++# the episode's end: E1M8's exit, the text, then the picture+e = run(["--warp", "18", "--exit-at", "3000", "--keys", "40000:ok,41000:ok", "--ms", "45000"], what="the ending")+if e:+ check(e["state"] == GS_FINALE, "E1M8's exit: the ending")++# a new game from the menus: title, menu, New Game, the episode, Hurt Me Plenty; then the menus and the automap+keys = "2000:ok,2700:ok,3400:ok,4100:ok,6000-8000:up,9000:toolbox,10000:plus,11000:toolbox,12000:back,12600:down," \+ "13000:down,13400:back,14000:back"+e = run(["--keys", keys, "--ms", "16000"], what="a new game")+if e:+ check(e["state"] == GS_LEVEL and e["map"] == 1, "a new game from the menus, the automap and the menus over it")++# saving in a slot from the menu, then loading it; Home keeps the moment, and the next start is back there+saves = tempfile.mkdtemp(prefix="doom_saves_")+# (the menu: Save Game is the fourth line; the first slot; its name is the level's: OK saves)+save = "2000:ok,2700:ok,3400:ok,4100:ok,6000-7000:up,8000:back,8500:down,8800:down,9100:down,9600:ok,10200:ok,10800:ok"+e = run(["--keys", save, "--ms", "13000"], saves=saves, what="a save in a slot")+if e:+ check("doomsav0.dsg" in e["files"] and "doomres.sav" in e["files"] and "doom_saves.py" in e["files"],+ "saved in the first slot, the moment kept on Home, both copied into doom_saves.py")+ first = e["leveltime"]+ e = run(["--ms", "4000"], saves=saves, what="the moment back")+ if e:+ check(e["state"] == GS_LEVEL and e["map"] == 1 and e["leveltime"] > first,+ "the next start is back in the level, where Home left it")+ # (the files gone, as when the app is installed again: they come back from doom_saves.py)+ for f in os.listdir(saves):+ if not f.endswith(".py"):+ os.remove(os.path.join(saves, f))+ load = "2000:ok,2700:down,3000:down,3400:ok,4000:ok" # the menu, Load Game, the first slot+ e = run(["--keys", load, "--ms", "7000"], saves=saves, what="loading the slot")+ if e:+ check(e["state"] == GS_LEVEL and e["map"] == 1 and "doomsav0.dsg" in e["files"],+ "after a reinstall, the slot comes back from doom_saves.py and loads")+shutil.rmtree(saves, ignore_errors=True)++if failures:+ print(f"\n{len(failures)} failed:")+ for f in failures:+ print(" ", f)+ sys.exit(1)+print("\nall good")diff --git a/games/doom/tests/play.c b/games/doom/tests/play.cindex ec91209f..5560a7a5 100644--- a/games/doom/tests/play.c+++ b/games/doom/tests/play.c@@ -15,6 +15,7 @@#include "doomtype.h"#include "z_zone.h"+#include "doom/doomstat.h"#include "nw.h"#include "plat.h"@@ -69,7 +70,14 @@ static void shot(uint32_t ms) {}/* the script, as time goes by (plat_host.c calls it) */+static uint32_t exit_at[16];+static int nexits, next_exit;+void G_ExitLevel(void);void host_tick(void) {+ if (next_exit < nexits && host_time >= exit_at[next_exit]) {+ next_exit++;+ G_ExitLevel(); /* (as if the exit switch was pressed) */+ }uint64_t k = 0;for (int i = 0; i < nholds; i++)if (host_time >= holds[i].a && host_time < holds[i].b) k |= (uint64_t)1 << holds[i].key;@@ -106,6 +114,13 @@ int main(int argc, char **argv) {else if (!strcmp(argv[i], "--out") && i + 1 < argc) snprintf(out, sizeof out, "%s", argv[++i]);else if (!strcmp(argv[i], "--saves") && i + 1 < argc) saves = argv[++i];else if (!strcmp(argv[i], "--stats")) stats = 1;+ else if (!strcmp(argv[i], "--warp") && i + 1 < argc) nw_warp = atoi(argv[++i]);+ else if (!strcmp(argv[i], "--exit-at") && i + 1 < argc) {+ for (char *s = argv[++i]; *s && nexits < 16;) {+ exit_at[nexits++] = (uint32_t)strtoul(s, &s, 10);+ if (*s == ',') s++;+ }+ }else {fprintf(stderr, "play: unknown option %s\n", argv[i]);return 2;@@ -115,7 +130,15 @@ int main(int argc, char **argv) {mkdir(saves, 0755);host_save_dir(saves);int r = nw_main();- if (stats) printf("STATS zone_free %d\n", Z_FreeMemory());- printf("END time %u quit %d\n", host_time, (int)nw_quit);+ if (stats) {+ extern uint32_t nw_col_overflows, nw_col_peak, nw_col_frames[40], nw_zone_peak, nw_zone_size;+ printf("STATS zone_free %d columns peak %u overflows %u zone peak %u of %u frames by 250 columns:",+ Z_FreeMemory(), nw_col_peak, nw_col_overflows, nw_zone_peak, nw_zone_size);+ for (int i = 0; i < 40; i++) printf(" %u", nw_col_frames[i]);+ printf("\n");+ }+ printf("END time %u quit %d state %d map E%dM%d leveltime %d health %d kills %d\n", host_time, (int)nw_quit,+ (int)gamestate, gameepisode, gamemap, leveltime, players[consoleplayer].health,+ players[consoleplayer].killcount);return r;}diff --git a/games/doom/tools/fetch.py b/games/doom/tools/fetch.pynew file mode 100644index 00000000..8a73f9cb--- /dev/null+++ b/games/doom/tools/fetch.py@@ -0,0 +1,63 @@+#!/usr/bin/env python3+"""Downloads the shareware DOOM1.WAD (version 1.9, which id Software lets anyone copy) from Ubuntu's+doom-wad-shareware package, checks it is the one, and writes it to OUT/doom1.wad. Then:++ make data WAD=OUT/doom1.wad++packs it into src/doom1.whx (RP2040 Doom's format, read in place by the game; no sound or music).+Needs dpkg-deb, or the zstd command, to open the package.++Usage: fetch.py OUT"""+import hashlib+import io+import os+import shutil+import subprocess+import sys+import tarfile+import tempfile+import urllib.request++URL = "http://archive.ubuntu.com/ubuntu/pool/multiverse/d/doom-wad-shareware/doom-wad-shareware_1.9.fixed-4_all.deb"+MD5 = "f0cefca49926d00903cf57551d901abe" # the 1.9 shareware DOOM1.WAD+INSIDE = "usr/share/games/doom/doom1.wad"+++def ar_members(data):+ """The files of a Debian package (an ar archive)."""+ assert data[:8] == b"!<arch>\n", "not a .deb"+ p, out = 8, {}+ while p + 60 <= len(data):+ name = data[p:p + 16].decode().strip().rstrip("/")+ size = int(data[p + 48:p + 58].decode().strip())+ out[name] = data[p + 60:p + 60 + size]+ p += 60 + size + (size & 1)+ return out+++def main():+ out = sys.argv[1] if len(sys.argv) > 1 else "build/ref"+ os.makedirs(out, exist_ok=True)+ deb = urllib.request.urlopen(URL).read()+ with tempfile.TemporaryDirectory() as d:+ path = os.path.join(d, "doom-wad-shareware.deb")+ open(path, "wb").write(deb)+ if shutil.which("dpkg-deb"):+ subprocess.run(["dpkg-deb", "-x", path, d], check=True)+ wad = open(os.path.join(d, INSIDE), "rb").read()+ else:+ members = ar_members(deb)+ name = next(n for n in members if n.startswith("data.tar"))+ raw = members[name]+ if name.endswith(".zst"):+ raw = subprocess.run(["zstd", "-d", "-c"], input=raw, capture_output=True, check=True).stdout+ with tarfile.open(fileobj=io.BytesIO(raw)) as t:+ wad = t.extractfile("./" + INSIDE).read()+ if hashlib.md5(wad).hexdigest() != MD5:+ raise SystemExit("fetch: this is not the shareware DOOM1.WAD 1.9")+ open(os.path.join(out, "doom1.wad"), "wb").write(wad)+ print(f"{out}/doom1.wad: {len(wad)} bytes")+++if __name__ == "__main__":+ main()diff --git a/games/doom/tools/media.py b/games/doom/tools/media.pynew file mode 100644index 00000000..141c430b--- /dev/null+++ b/games/doom/tools/media.py@@ -0,0 +1,92 @@+#!/usr/bin/env python3+"""Doom's pictures and animations, from the computer build (which draws exactly what the calculator does):+docs/*.png, and the repository's docs/media/doom.gif (640 x 480), docs/media/gallery/doom.gif (320 x 240)+and docs/media/thumb_doom.png (160 x 120).++ make build/play && python3 tools/media.py build/play++The fights are id Software's own: the first demo of the title screen, Phobos Lab, played by the engine."""+import os+import shutil+import subprocess+import sys+import tempfile++from PIL import Image++GAME = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+ROOT = os.path.dirname(os.path.dirname(GAME))+sys.path.insert(0, os.path.join(ROOT, "tools"))+from record import save_gif # noqa: E402 (the repository's GIF maker: one palette, gifsicle)++PLAY = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else os.path.join(GAME, "build/play"))+FRAME = 1000 // 35 # (a frame drawn moves the computer's clock on by this many ms)+ENV = dict(os.environ, ASAN_OPTIONS="detect_leaks=0")+++def play(args, shots, ms):+ """Plays (with settings already saved, so without the first game's word on the keys) and returns+ {ms: picture} for each shot asked."""+ saves, out = tempfile.mkdtemp(prefix="doom_media_"), tempfile.mkdtemp(prefix="doom_media_")+ with open(os.path.join(saves, "doom.cfg"), "wb") as f:+ f.write(b"D\x01\x01\x00")+ shots = sorted(set(shots))+ subprocess.run([PLAY, "--saves", saves, "--out", out, "--ms", str(ms), "--shots", ",".join(map(str, shots))]+ + args, check=True, capture_output=True, env=ENV)+ pics = {}+ for t in shots:+ with Image.open(os.path.join(out, f"shot_{t:06d}.ppm")) as im:+ pics[t] = im.convert("RGB")+ shutil.rmtree(saves)+ shutil.rmtree(out)+ return pics+++def frames(a, b, step=2):+ """the times of every step-th frame from a to b ms"""+ return list(range(a - a % FRAME, b, FRAME * step))+++def save_png(im, path):+ im.quantize(colors=256, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE).save(path, optimize=True)+ print(path, os.path.getsize(path) // 1024, "KB")+++docs = os.path.join(GAME, "docs")+media = os.path.join(ROOT, "docs", "media")+os.makedirs(docs, exist_ok=True)++# the title screen and the first demo, Phobos Lab: imps down a corridor, then zombiemen around the yellow key+IMPS, KEY = (9200, 12700), (35300, 38500)+title_shots = {"title": 2000, "imps": 10058, "fight": 36058, "lab": 57058}+gif_times = frames(*IMPS) + frames(*KEY)+pics = play([], list(title_shots.values()) + gif_times + [1000], 58000)+for name, t in title_shots.items():+ save_png(pics[t], os.path.join(docs, f"{name}.png"))++# the animations: the title, then the two fights+anim = [(0, pics[1000])] + [(1500 + i * 2 * FRAME, pics[t]) for i, t in enumerate(gif_times)]+save_gif(anim, os.path.join(media, "doom.gif"), 2, 18)+print("doom.gif", os.path.getsize(os.path.join(media, "doom.gif")) // 1024, "KB")+small = [(0, pics[1000])] + [(1500 + i * 4 * FRAME, pics[t]) for i, t in enumerate(gif_times[::2])]+save_gif(small, os.path.join(media, "gallery", "doom.gif"), 1, 9)+print("gallery/doom.gif", os.path.getsize(os.path.join(media, "gallery", "doom.gif")) // 1024, "KB")+thumb = pics[title_shots["fight"]].resize((160, 120), Image.LANCZOS)+save_png(thumb, os.path.join(media, "thumb_doom.png"))++# Hangar: through the courtyard, the automap, the menu over the game, then the exit and the intermission+walk = ("1500-2200:up,2200-2500:right,1700:ok,2700-3400:up,3400-3700:right,2900:ok,3900-4600:up,4600-4900:right,"+ "4100:ok,5100-5800:up,5800-6100:right,6300-7000:up,7000-7300:right,9000:toolbox,10500:toolbox,11500:back,"+ "13000:back,21000:ok")+hangar_shots = {"hangar": 5200, "automap": 9800, "menu": 12400, "intermission": 19600}+pics = play(["--warp", "11", "--exit-at", "14000", "--keys", walk], hangar_shots.values(), 20000)+for name, t in hangar_shots.items():+ save_png(pics[t], os.path.join(docs, f"{name}.png"))++# Read This!: the calculator's keys+pics = play(["--keys", "2000:ok,2600:down,2900:down,3200:down,3500:down,4000:ok"], [5000], 6000)+save_png(pics[5000], os.path.join(docs, "keys.png"))++# E1M8's exit: the episode's ending+pics = play(["--warp", "18", "--exit-at", "3000"], [44000], 45000)+save_png(pics[44000], os.path.join(docs, "ending.png"))