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
Five Nights at Freddy's: the office, the cameras and the nights
Mason363c9d5dba09685
diff --git a/games/fnaf/.gitignore b/games/fnaf/.gitignorenew file mode 100644index 00000000..2bb66cc0--- /dev/null+++ b/games/fnaf/.gitignore@@ -0,0 +1,3 @@+output/+build/+ref/diff --git a/games/fnaf/Makefile b/games/fnaf/Makefilenew file mode 100644index 00000000..ad93c724--- /dev/null+++ b/games/fnaf/Makefile@@ -0,0 +1,82 @@+# Five Nights at Freddy's on the NumWorks calculator.+# make output/fnaf.nwa+# make check link it like the calculator does (output/fnaf.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 data src/data.bin and src/data.h from the pictures tools/fetch.py gathers+# (REF=its folder, Python + Pillow + NumPy)+Q ?= @+# the ARM toolchain on the PATH, or in TOOLCHAIN=<its bin folder>+TOOLCHAIN ?=+BIN = $(if $(TOOLCHAIN),$(TOOLCHAIN)/)+CC = $(BIN)arm-none-eabi-gcc+NWLINK ?= npx --yes -- [email protected]+STRIP ?= $(BIN)arm-none-eabi-strip --strip-unneeded+SIZE = $(BIN)arm-none-eabi-size+BUILD_DIR = output+REF ?=++# the pictures are decoded and drawn every frame at -O2; the rest is small at -Os+HOT = src/pic.c src/gfx.c+COLD = $(filter-out $(HOT) src/plat_host.c src/plat_eadk.c,$(wildcard src/*.c))+COLD_OBJ = $(patsubst src/%.c,$(BUILD_DIR)/cold/%.o,$(COLD))+HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h++CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DDATA_BIN='"src/data.bin"'+CFLAGS += -O2 -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal+CFLAGS += -ffunction-sections -fdata-sections $(EXTRA)+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel++.PHONY: build check clean host test data+build: $(BUILD_DIR)/fnaf.nwa++# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones)+check: $(BUILD_DIR)/fnaf.nwa+ $(Q) $(NWLINK) nwa-bin --ram-length 133652 $< $(BUILD_DIR)/fnaf.bin+ @echo "BIN $(BUILD_DIR)/fnaf.bin: $$(wc -c < $(BUILD_DIR)/fnaf.bin) bytes"++$(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)+ @mkdir -p $(@D)+ $(Q) $(CC) $(CFLAGS) -Os -c $< -o $@++$(BUILD_DIR)/fnaf.nwa: $(HOT) src/plat_eadk.c $(COLD_OBJ) $(HEADERS) $(BUILD_DIR)/icon.o $(BUILD_DIR)/data.o+ @echo "LD $@"+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(HOT) src/plat_eadk.c $(COLD_OBJ) $(BUILD_DIR)/data.o $(BUILD_DIR)/icon.o -lm -o $@+ $(Q) $(STRIP) $@+ $(Q) $(SIZE) $@++$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)+ @echo "ICON $<"+ $(Q) $(NWLINK) png-icon-o $< $@++$(BUILD_DIR):+ $(Q) mkdir -p $@++# on a computer: tests/play.c plays it with scripted keys and saves screenshots+HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -Isrc -DHOST -DDATA_BIN='"src/data.bin"'+HOST_SAN = -fsanitize=address,undefined -fno-sanitize-recover=undefined+HOST_SRC = $(filter-out src/plat_eadk.c src/main.c,$(wildcard src/*.c))+host: build/play build/pictures+build/play: $(HOST_SRC) tests/play.c src/data.S src/data.bin $(HEADERS)+ $(Q) mkdir -p $(dir $@)+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) $(HOST_SRC) tests/play.c src/data.S -lm -o $@+ @echo "HOST $@"+build/pictures: src/pic.c src/gfx.c src/plat_host.c tests/pics.c src/data.S src/data.bin $(HEADERS)+ $(Q) mkdir -p $(dir $@)+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) src/pic.c src/gfx.c src/plat_host.c tests/pics.c src/data.S -lm -o $@++test: host+ python3 tests/check.py build/play build/pictures++data:+ @test -n "$(REF)" || { echo "make data REF=<the folder tools/fetch.py filled>"; exit 1; }+ python3 -I tools/pack.py $(REF)++clean:+ $(Q) rm -rf $(BUILD_DIR) builddiff --git a/games/fnaf/src/calls.c b/games/fnaf/src/calls.cnew file mode 100644index 00000000..e5dece59--- /dev/null+++ b/games/fnaf/src/calls.c@@ -0,0 +1,173 @@+/* The phone calls of nights 1 to 5, as subtitles: the calculator has no sound, so the Phone Guy's+ * messages are read, each line from the second it is said in the recording. */+#include <stddef.h>+#include "game.h"++typedef struct {+ float at;+ const char *s;+} Line;++static const Line night1[] = {+ {3.4f, "*phone ringing*"},+ {18.9f, "Hello? Hello, hello?"},+ {21.7f, "Uh, I wanted to record a message for you"},+ {24.7f, "to help you get settled in on your first night."},+ {27.5f, "Um, I actually worked in that office before you."},+ {31.1f, "I'm finishing up my last week now, as a matter of fact."},+ {34.2f, "So, I know it can be a bit overwhelming,"},+ {37.8f, "but I'm here to tell you there's nothing to worry about."},+ {40.7f, "Uh, you'll do fine."},+ {42.4f, "So, let's just focus on getting you through your first week."},+ {46.5f, "Okay?"},+ {47.3f, "Uh, let's see, first there's an introductory greeting"},+ {50.0f, "from the company that I'm supposed to read."},+ {53.1f, "Uh, it's kind of a legal thing, you know."},+ {55.8f, "Um, \"Welcome to Freddy Fazbear's Pizza."},+ {58.9f, "A magical place for kids and grown-ups alike,"},+ {61.9f, "where fantasy and fun come to life."},+ {64.6f, "Fazbear Entertainment is not responsible for damage to property or person."},+ {69.1f, "Upon discovering that damage or death has occurred,"},+ {71.5f, "a missing person report will be filed within 90 days,"},+ {74.4f, "or as soon property and premises have been thoroughly cleaned and bleached,"},+ {78.3f, "and the carpets have been replaced.\" Blah blah blah."},+ {81.3f, "Now that might sound bad, I know,"},+ {83.6f, "but there's really nothing to worry about."},+ {86.4f, "Uh, the animatronic characters here do get a bit quirky at night,"},+ {90.9f, "but do I blame them? No."},+ {92.9f, "If I were forced to sing those same stupid songs for twenty years"},+ {96.3f, "and I never got a bath?"},+ {98.5f, "I'd probably be a bit irritable at night too."},+ {101.1f, "So, remember, these characters hold a special place in the hearts of children"},+ {105.2f, "and we need to show them a little respect, right? Okay."},+ {109.1f, "So, just be aware, the characters do tend to wander a bit."},+ {114.0f, "Uh, they're left in some kind of free roaming mode at night."},+ {117.9f, "Uh... Something about their servos locking up"},+ {120.5f, "if they get turned off for too long."},+ {122.6f, "Uh, they used to be allowed to walk around during the day too."},+ {125.5f, "But then there was The Bite of '87. Yeah."},+ {129.8f, "I-It's amazing that the human body can live without the frontal lobe,"},+ {133.5f, "you know?"},+ {134.4f, "Uh, now concerning your safety, the only real risk to you as a night watchman here,"},+ {140.7f, "if any, is the fact that these characters, uh, if they happen to see you after hours"},+ {148.9f, "probably won't recognize you as a person."},+ {150.4f, "They'll p-most likely see you as a metal endoskeleton without its costume on."},+ {155.6f, "Now since that's against the rules here at Freddy Fazbear's Pizza,"},+ {159.4f, "they'll probably try to... forcefully stuff you inside a Freddy Fazbear suit."},+ {163.6f, "Um, now, that wouldn't be so bad if the suits themselves weren't filled with"},+ {168.6f, "crossbeams, wires, and animatronic devices, especially around the facial area."},+ {174.5f, "So, you could imagine how having your head forcefully pressed inside one of those"},+ {178.3f, "could cause a bit of discomfort... and death."},+ {182.4f, "Uh, the only parts of you that would likely see the light of day again"},+ {185.1f, "would be your eyeballs and teeth when they pop out the front of the mask, heh."},+ {189.3f, "Y-Yeah, they don't tell you these things when you sign up."},+ {192.4f, "But hey, first day should be a breeze."},+ {194.4f, "I'll chat with you tomorrow."},+ {195.9f, "Uh, check those cameras, and remember to close the doors only if absolutely necessary."},+ {201.0f, "Gotta conserve power."},+ {202.7f, "Alright, good night."},+ {204.2f, NULL},+};++static const Line night2[] = {+ {3.6f, "*phone ringing*"},+ {18.7f, "Uhh, hello, hello?"},+ {21.0f, "Uh, well if you're hearing this and you made it to day two, uh, congrats!"},+ {25.7f, "I-I won't talk quite as long this time"},+ {28.6f, "since Freddy and his friends tend to become more active as the week progresses."},+ {32.9f, "Uhh, it might be a good idea to peek at those cameras while I talk"},+ {36.7f, "just to make sure everyone's in their proper place, you know."},+ {40.1f, "Uh, interestingly enough, Freddy himself doesn't come off stage very often."},+ {45.1f, "I heard he becomes a lot more active in the dark, though,"},+ {49.5f, "so, hey, I guess that's one more reason not to run out of power, right?"},+ {53.0f, "I-I also want to emphasize the importance of using your door lights."},+ {57.5f, "There are blind spots in your camera views,"},+ {60.8f, "and those blind spots happen to be right outside of your doors."},+ {64.8f, "So if-if you can't find something, or someone, on your cameras,"},+ {69.0f, "be sure to check the door lights."},+ {71.7f, "Uh, you might only have a few seconds to react..."},+ {74.8f, "Uh, not that you would be in any danger, of course. I'm not implying that."},+ {80.3f, "Also, check on the curtain in Pirate Cove from time to time."},+ {85.4f, "The character in there seems unique in that he becomes more active"},+ {88.3f, "if the cameras remain off for long periods of time."},+ {92.4f, "I guess he doesn't like being watched. I don't know."},+ {95.5f, "Anyway, I'm sure you have everything under control."},+ {98.7f, "Uh, talk to you soon."},+ {100.4f, NULL},+};++static const Line night3[] = {+ {5.2f, "*phone ringing*"},+ {19.7f, "Hello, hello?"},+ {21.0f, "Hey, you're doing great! Most people don't last this long."},+ {25.1f, "I mean, you know, they usually move on to other things by now."},+ {29.4f, "I'm not implying that they died. Th-That's not what I meant."},+ {34.0f, "Uh anyway, I better not take up too much of your time."},+ {37.4f, "Things start getting real tonight."},+ {39.7f, "Uh, hey, listen, I had an idea:"},+ {42.7f, "if you happen to get caught and want to avoid getting stuffed into a Freddy Fazbear suit,"},+ {47.7f, "uh, try playing dead! You know, go limp."},+ {51.3f, "Then there's a chance that, uh, maybe they'll think that you're an empty costume instead."},+ {56.3f, "Then again if they think you're an empty costume,"},+ {59.8f, "they-they might try to... stuff a metal endoskeleton through you."},+ {62.3f, "Wonder how that would work."},+ {64.0f, "Uh, yeah, never mind, scratch that. It's best just not to get caught."},+ {68.4f, "Uh, okay, I'll leave you to it."},+ {71.4f, "See you on the flip side."},+ {72.5f, NULL},+};++static const Line night4[] = {+ {3.3f, "*phone ringing*"},+ {17.6f, "Hello, hello? Hey!"},+ {19.4f, "Hey, wow, day four. I knew you could do it."},+ {23.3f, "Uh, hey, listen, I may not be around to send you a message tomorrow."},+ {26.7f, "*banging* It's been a bad night here for me."},+ {30.5f, "Um, I-I'm kinda glad that I recorded my messages for you, uh, when I did."},+ {36.3f, "Uh, hey, do me a favor. Maybe sometime, uh,"},+ {39.9f, "you could check inside those suits in the back room?"},+ {43.7f, "I'm gonna try to hold out until someone checks. Maybe it won't be so bad."},+ {49.1f, "Uh, I-I-I always wondered what was in all those empty heads back there. You know..."},+ {52.7f, "*a music box* Oh, no..."},+ {55.1f, "*moaning*"},+ {56.4f, "Oh, no..."},+ {57.3f, "*banging*"},+ {58.3f, "*an animatronic screams*"},+ {58.8f, "*static*"},+ {60.4f, "*the line goes dead*"},+ {62.0f, NULL},+};++static const Line night5[] = {+ {3.9f, "*phone ringing*"},+ {17.3f, "*static*"},+ {18.8f, "*garbled, deep voices*"},+ {26.7f, "*a scream*"},+ {27.0f, "*garbled, deep voices*"},+ {30.0f, "*a scream*"},+ {30.3f, "*garbled, deep voices*"},+ {33.3f, "*a scream*"},+ {33.6f, "*garbled, deep voices*"},+ {34.6f, "*a high scream*"},+ {35.5f, "*the line goes dead*"},+ {36.3f, NULL},+};++static const Line *const calls[5] = {night1, night2, night3, night4, night5};++const char *call_line(int night, float t) {+ if (night < 1 || night > 5) return NULL;+ const char *s = NULL;+ for (const Line *l = calls[night - 1]; l->at <= t; l++) {+ s = l->s;+ if (!s) break;+ }+ return s;+}++float call_end(int night) {+ if (night < 1 || night > 5) return 0;+ const Line *l = calls[night - 1];+ while (l->s) l++;+ return l->at;+}diff --git a/games/fnaf/src/data.S b/games/fnaf/src/data.Snew file mode 100644index 00000000..70fb2e75--- /dev/null+++ b/games/fnaf/src/data.S@@ -0,0 +1,19 @@+/* data.bin (tools/pack.py) in the app's read-only data */+#ifdef __APPLE__+ .const_data+ .p2align 2+ .globl _fnaf_data+_fnaf_data:+ .incbin DATA_BIN+ .p2align 2+#else+ .section .rodata.fnaf_data,"a"+ .balign 4+ .global fnaf_data+fnaf_data:+ .incbin DATA_BIN+ .balign 4+#endif+#ifdef __ELF__+ .section .note.GNU-stack,"",%progbits+#endifdiff --git a/games/fnaf/src/data.bin b/games/fnaf/src/data.binnew file mode 100644index 00000000..50c6b9b2Binary files /dev/null and b/games/fnaf/src/data.bin differdiff --git a/games/fnaf/src/data.h b/games/fnaf/src/data.hnew file mode 100644index 00000000..ac052aa1--- /dev/null+++ b/games/fnaf/src/data.h@@ -0,0 +1,240 @@+/* Made by tools/pack.py: what is in data.bin. */+#ifndef FNAF_DATA_H+#define FNAF_DATA_H++#define SEC_HUFF 0+#define SEC_QUANT 1+#define SEC_PICS 2+#define SEC_TABLE 3+#define SEC_BANK 4+#define SEC_FONTS 5+#define SEC_IMGS 6+#define SEC_MAP 7+#define PIC_OFFICE 0+#define PIC_OFFICE_LL 1+#define PIC_OFFICE_LLB 2+#define PIC_OFFICE_RL 3+#define PIC_OFFICE_RLC 4+#define PIC_DARK 5+#define PIC_DARK_FREDDY 6+#define PIC_DOOR_L 7+#define PIC_DOOR_R 8+#define PIC_PANEL_L0 9+#define PIC_PANEL_L1 10+#define PIC_PANEL_L2 11+#define PIC_PANEL_L3 12+#define PIC_PANEL_R0 13+#define PIC_PANEL_R1 14+#define PIC_PANEL_R2 15+#define PIC_PANEL_R3 16+#define PIC_FAN0 17+#define PIC_FAN1 18+#define PIC_FAN2 19+#define PIC_OFFICE_GOLD 20+#define PIC_CAM1A_EMPTY 21+#define PIC_CAM1A_F 22+#define PIC_CAM1A_BF 23+#define PIC_CAM1A_CF 24+#define PIC_CAM1A_BCF 25+#define PIC_CAM1B_EMPTY 26+#define PIC_CAM1B_B 27+#define PIC_CAM1B_C 28+#define PIC_CAM1B_F 29+#define PIC_CAM1B_BC 30+#define PIC_CAM1B_BF 31+#define PIC_CAM1B_CF 32+#define PIC_CAM1B_BCF 33+#define PIC_CAM2A_EMPTY 34+#define PIC_CAM2A_B 35+#define PIC_CAM2B_EMPTY 36+#define PIC_CAM2B_B 37+#define PIC_CAM3_EMPTY 38+#define PIC_CAM3_B 39+#define PIC_CAM4A_EMPTY 40+#define PIC_CAM4A_C 41+#define PIC_CAM4A_F 42+#define PIC_CAM4A_CF 43+#define PIC_CAM4B_EMPTY 44+#define PIC_CAM4B_C 45+#define PIC_CAM4B_F 46+#define PIC_CAM5_EMPTY 47+#define PIC_CAM5_B 48+#define PIC_CAM7_EMPTY 49+#define PIC_CAM7_C 50+#define PIC_CAM7_F 51+#define PIC_CAM7_CF 52+#define PIC_CAM1C_0 53+#define PIC_CAM1C_1 54+#define PIC_CAM1C_2 55+#define PIC_CAM1C_3 56+#define PIC_CAM2A_DARK 57+#define PIC_CAM2B_GOLD 58+#define PIC_BONNIE0 59+#define PIC_BONNIE1 60+#define PIC_BONNIE2 61+#define PIC_BONNIE3 62+#define PIC_BONNIE4 63+#define PIC_BONNIE5 64+#define PIC_BONNIE6 65+#define PIC_BONNIE7 66+#define PIC_BONNIE8 67+#define PIC_BONNIE9 68+#define PIC_CHICA0 69+#define PIC_CHICA1 70+#define PIC_CHICA2 71+#define PIC_CHICA3 72+#define PIC_CHICA4 73+#define PIC_CHICA5 74+#define PIC_CHICA6 75+#define PIC_CHICA7 76+#define PIC_CHICA8 77+#define PIC_CHICA9 78+#define PIC_CHICA10 79+#define PIC_CHICA11 80+#define PIC_CHICA12 81+#define PIC_CHICA13 82+#define PIC_CHICA14 83+#define PIC_FREDDY0 84+#define PIC_FREDDY1 85+#define PIC_FREDDY2 86+#define PIC_FREDDY3 87+#define PIC_FREDDY4 88+#define PIC_FREDDY5 89+#define PIC_FREDDY6 90+#define PIC_FREDDY7 91+#define PIC_FREDDY8 92+#define PIC_FREDDY9 93+#define PIC_FREDDY10 94+#define PIC_FREDDY11 95+#define PIC_FREDDY12 96+#define PIC_FREDDY13 97+#define PIC_FREDDY14 98+#define PIC_FREDDY15 99+#define PIC_FREDDY16 100+#define PIC_FREDDY17 101+#define PIC_FREDDY18 102+#define PIC_FREDDY19 103+#define PIC_FOXY0 104+#define PIC_FOXY1 105+#define PIC_FOXY2 106+#define PIC_FOXY3 107+#define PIC_FOXY4 108+#define PIC_FOXY5 109+#define PIC_FOXY6 110+#define PIC_FOXY7 111+#define PIC_FOXY8 112+#define PIC_FOXY9 113+#define PIC_FOXY10 114+#define PIC_FOXY11 115+#define PIC_FOXY12 116+#define PIC_FOXY13 117+#define PIC_FOXY14 118+#define PIC_FOXY15 119+#define PIC_FOXY16 120+#define PIC_FOXY17 121+#define PIC_FOXY18 122+#define PIC_FOXYRUN0 123+#define PIC_FOXYRUN1 124+#define PIC_FOXYRUN2 125+#define PIC_FOXYRUN3 126+#define PIC_FOXYRUN4 127+#define PIC_FOXYRUN5 128+#define PIC_FOXYRUN6 129+#define PIC_FOXYRUN7 130+#define PIC_FOXYRUN8 131+#define PIC_FOXYRUN9 132+#define PIC_FOXYRUN10 133+#define PIC_FOXYRUN11 134+#define PIC_FOXYRUN12 135+#define PIC_FOXYRUN13 136+#define PIC_FOXYRUN14 137+#define PIC_FOXYRUN15 138+#define PIC_FOXYRUN16 139+#define PIC_FOXYRUN17 140+#define PIC_POWEROUT0 141+#define PIC_POWEROUT1 142+#define PIC_POWEROUT2 143+#define PIC_POWEROUT3 144+#define PIC_POWEROUT4 145+#define PIC_POWEROUT5 146+#define PIC_POWEROUT6 147+#define PIC_POWEROUT7 148+#define PIC_POWEROUT8 149+#define PIC_POWEROUT9 150+#define PIC_POWEROUT10 151+#define PIC_POWEROUT11 152+#define PIC_POWEROUT12 153+#define PIC_POWEROUT13 154+#define PIC_POWEROUT14 155+#define PIC_POWEROUT15 156+#define PIC_POWEROUT16 157+#define PIC_POWEROUT17 158+#define PIC_POWEROUT18 159+#define PIC_POWEROUT19 160+#define PIC_POWEROUT20 161+#define PIC_FLIP0 162+#define PIC_FLIP1 163+#define PIC_FLIP2 164+#define PIC_FLIP3 165+#define PIC_FLIP4 166+#define PIC_FLIP5 167+#define PIC_FLIP6 168+#define PIC_FLIP7 169+#define PIC_FLIP8 170+#define PIC_FLIP9 171+#define PIC_FLIP10 172+#define PIC_GOLDEN 173+#define PIC_TITLE0 174+#define PIC_TITLE1 175+#define PIC_TITLE2 176+#define PIC_TITLE3 177+#define PIC_NEWSPAPER 178+#define PIC_FACE_FREDDY 179+#define PIC_FACE_BONNIE 180+#define PIC_FACE_CHICA 181+#define PIC_FACE_FOXY 182+#define PIC_PAYCHECK 183+#define PIC_OVERTIME 184+#define PIC_PINKSLIP 185+#define PIC_GAMEOVER 186+#define PIC_COUNT 187+#define FONT_HUD 0+#define FONT_BIG 1+#define FONT_TEXT 2+#define FONT_CLOCK 3+#define FONT_PIXEL 4+#define FONT_HUGE 5+#define DOOR_L_X 27+#define DOOR_L_W 70+#define DOOR_L_H 239+#define DOOR_R_X 434+#define DOOR_R_W 60+#define DOOR_R_H 239+#define PANEL_L_X 0+#define PANEL_R_X 496+#define PANEL_Y 96+#define FAN_X 256+#define FAN_Y 96+#define GOLD_X 176+#define GOLD_Y 128+#define GOLD_W 176+#define GOLD_H 112+#define BONNIE_N 10+#define BONNIE_X 106+#define CHICA_N 15+#define CHICA_X 95+#define FREDDY_N 20+#define FREDDY_X 180+#define FOXY_N 19+#define FOXY_X 0+#define FOXYRUN_N 18+#define FOXYRUN_X 213+#define POWEROUT_N 21+#define POWEROUT_X 53+#define FLIP_N 11+#define FLIP_X 53+#define IMG_TITLE 0+#define IMG_STAR 1+#define MAP_SIZE 133++#endifdiff --git a/games/fnaf/src/game.c b/games/fnaf/src/game.cnew file mode 100644index 00000000..90e592ce--- /dev/null+++ b/games/fnaf/src/game.c@@ -0,0 +1,404 @@+/* The scenes around the nights: the title, the newspaper, how to play, the night's card, 6 AM, the+ * paychecks and the pink slip, the game over, the custom night and Golden Freddy; keys and saves. */+#include <string.h>+#include "game.h"+#include "gfx.h"+#include "res.h"++Game g;+static uint32_t seed = 0x2C1B3C6Du;++uint32_t rnd(void) {+ seed ^= seed << 13, seed ^= seed >> 17, seed ^= seed << 5;+ return seed;+}+float rndf(void) { return (float)(rnd() >> 8) / 16777216.0f; }++static bool pressed(uint32_t k) { return (g.pressed & k) != 0; }++void caption(const char *s) {+ for (int i = 0; i < 4; i++)+ if (g.cap[i] == s && g.cap_t[i] > 1.2f) { /* (the same again: it stays up) */+ g.cap_t[i] = 3;+ return;+ }+ memmove(g.cap, g.cap + 1, 3 * sizeof g.cap[0]);+ memmove(g.cap_t, g.cap_t + 1, 3 * sizeof g.cap_t[0]);+ g.cap[3] = s;+ g.cap_t[3] = 3;+}++static void go(int scene) {+ g.scene = scene;+ g.t = 0;+ g.menu = 0;+}++void start_night(int night) {+ g.n.night = (uint8_t)night;+ memset(g.cap, 0, sizeof g.cap);+ go(SC_INTRO);+}++void game_init(void) {+ seed ^= plat_millis() * 2654435761u;+ g.running = true;+ g.held = 0xFFFFFFFFu; /* (the key that opened the app is not a press) */+ save_restore_copy();+ save_load();+ if (save_resume_load()) { /* Home left a night: back in it, paused */+ go(SC_NIGHT);+ g.paused = 1;+ } else+ go(SC_TITLE);+}++/* ------------------------------------------------------------------ the title */+enum { M_NEW, M_CONTINUE, M_SIXTH, M_CUSTOM };++static int face; /* the title: which of Freddy's faces, how bright */+static int face_light = 20;+static float face_t, light_t;++static void title_step(void) {+ /* Freddy's face twitches, and its light wavers */+ face_t += DT, light_t += DT;+ if (face_t >= 0.08f) face_t = 0, face = rnd() % 100 < 4 ? 1 + (int)(rnd() % 3) : 0;+ if (light_t >= 0.3f) light_t = 0, face_light = 14 + (int)(rnd() % 19);+ g.menu_n = (uint8_t)(2 + (g.stars & 1) + ((g.stars >> 1) & 1));+ if (pressed(K_UP | K_DIGIT(8))) g.menu = (uint8_t)((g.menu + g.menu_n - 1) % g.menu_n);+ if (pressed(K_DOWN | K_DIGIT(2))) g.menu = (uint8_t)((g.menu + 1) % g.menu_n);+ if (pressed(K_BACK)) g.running = false;+ if (!pressed(K_OK)) return;+ switch (g.menu) {+ case M_NEW:+ g.reached = 1;+ save_progress();+ g.n.night = 1;+ go(SC_NEWS);+ break;+ case M_CONTINUE: start_night(g.reached); break;+ case M_SIXTH: start_night(6); break;+ case M_CUSTOM: go(SC_CUSTOM); break;+ }+}++static void title_draw(void) {+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);+ pic_draw(PIC_TITLE0 + face, 0, 0);+ gfx_dim(0, gfx_y0, SCREEN_W, BAND_H, face_light);+ gfx_static(0, gfx_y0, SCREEN_W, BAND_H, 9, rnd());+ /* the slow white band going down, and lines that flash */+ int sy = (int)(g.t / 20 * (SCREEN_H + 10)) % (SCREEN_H + 10) - 10;+ gfx_blend(0, sy, SCREEN_W, 10, WHITE, 3);+ if ((int)(g.t * 10) % 7 == 0) gfx_blend(0, (int)(g.t * 997) % SCREEN_H, SCREEN_W, 2, WHITE, 8);+ gfx_img(IMG_TITLE, 20, 18, WHITE);+ for (int i = 0; i < 3; i++)+ if (g.stars >> i & 1) gfx_img(IMG_STAR, 20 + 27 * i, 132, WHITE);+ static const char *const items[] = {"New Game", "Continue", "6th Night", "Custom Night"};+ int y0 = g.stars ? 160 : 150;+ for (int i = 0; i < g.menu_n; i++) {+ int y = y0 + 18 * i;+ gfx_text(FONT_BIG, 44, y, items[i], WHITE);+ if (g.menu == i) gfx_text(FONT_BIG, 20, y, ">>", WHITE);+ }+ if (g.menu == M_CONTINUE) {+ char s[] = "Night 0";+ s[6] = (char)('0' + g.reached);+ gfx_text(FONT_HUD, 44, y0 + 18 * g.menu_n + 4, s, WHITE);+ }+}++/* ------------------------------------------------------------------ the newspaper, how to play, the card */+static int fade_in_out(float t, float in, float hold, float out) { /* 0 black to 32 */+ float a = t < in ? t / in : t < hold ? 1 : t < hold + out ? 1 - (t - hold) / out : 0;+ return (int)(a * 32);+}++static void news_draw(void) {+ pic_draw(PIC_NEWSPAPER, 0, 0);+ gfx_dim(0, gfx_y0, SCREEN_W, BAND_H, fade_in_out(g.t, 2, 7, 2));+}++static void news_step(void) {+ if (pressed(K_OK) && g.t > 2 && g.t < 7) g.t = 7;+ if (g.t >= 9) {+ if (!g.keys_seen) {+ go(SC_KEYS);+ g.after_keys = 0;+ } else+ start_night(1);+ }+}++static void keys_draw(void) {+ static const char *const rows[][2] = {+ {"In the office", NULL},+ {"4 6, < >", "look left and right"},+ {"7 1", "left door, left light"},+ {"9 3", "right door, right light"},+ {"OK, 8", "the monitor up and down"},+ {"0", "mute the call"},+ {"On the monitor", NULL},+ {"1 to 7", "a camera (again: 1B, 1C...)"},+ {"arrows", "around the map"},+ {"Back", "pause"},+ };+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);+ gfx_text_c(FONT_BIG, 160, 8, "How to survive", WHITE);+ int y = 34;+ for (unsigned i = 0; i < sizeof rows / sizeof rows[0]; i++) {+ if (!rows[i][1]) {+ gfx_text(FONT_HUD, 16, y + 2, rows[i][0], RGB(0x8FD18F));+ y += 17;+ continue;+ }+ gfx_text(FONT_HUD, 26, y, rows[i][0], WHITE);+ gfx_text(FONT_TEXT, 108, y, rows[i][1], RGB(0xC8C8C8));+ y += 15;+ }+ gfx_text_c(FONT_TEXT, 160, 196, "Watch the power: every door, light and", RGB(0xC8C8C8));+ gfx_text_c(FONT_TEXT, 160, 209, "camera drains it. Survive until 6 AM.", RGB(0xC8C8C8));+ if ((int)(g.t * 2) & 1) gfx_text_c(FONT_HUD, 160, 226, "OK", WHITE);+}++static void keys_step(void) {+ if (!pressed(K_OK | K_BACK) || g.t < 0.4f) return;+ if (!g.keys_seen) {+ g.keys_seen = 1;+ save_progress();+ }+ if (g.after_keys) {+ g.scene = SC_NIGHT;+ g.paused = 1;+ } else+ start_night(g.n.night ? g.n.night : 1);+}++static const char *const nth[] = {"", "1st Night", "2nd Night", "3rd Night", "4th Night", "5th Night", "6th Night",+ "7th Night"};++static void intro_draw(void) {+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);+ gfx_text_c(FONT_HUGE, 160, 92, "12:00 AM", WHITE);+ gfx_text_c(FONT_BIG, 160, 124, nth[g.n.night], WHITE);+ if (g.t < 0.15f) gfx_static(0, gfx_y0, SCREEN_W, BAND_H, 20, rnd());+ if (g.t > 1.2f) gfx_dim(0, gfx_y0, SCREEN_W, BAND_H, (int)((2.2f - g.t) * 32));+}++static void intro_step(void) {+ if (g.t < 2.2f) return;+ night_begin(g.n.night);+ go(SC_NIGHT);+}++/* ------------------------------------------------------------------ the night, paused */+static void night_scene_step(void) {+ if (g.paused) {+ if (g.confirm) {+ if (pressed(K_LEFT | K_RIGHT | K_UP | K_DOWN | K_DIGIT(4) | K_DIGIT(6))) g.pause_item ^= 1;+ if (pressed(K_BACK)) g.confirm = 0;+ if (pressed(K_OK)) {+ if (g.pause_item) go(SC_TITLE), g.paused = 0;+ g.confirm = 0, g.pause_item = 2;+ }+ return;+ }+ if (pressed(K_UP | K_DIGIT(8))) g.pause_item = (uint8_t)((g.pause_item + 2) % 3);+ if (pressed(K_DOWN | K_DIGIT(2))) g.pause_item = (uint8_t)((g.pause_item + 1) % 3);+ if (pressed(K_BACK)) g.paused = 0;+ if (pressed(K_OK)) {+ if (g.pause_item == 0) g.paused = 0;+ else if (g.pause_item == 1) go(SC_KEYS), g.after_keys = 1;+ else g.confirm = 1, g.pause_item = 0;+ }+ return;+ }+ if (pressed(K_BACK)) {+ g.paused = 1;+ g.pause_item = 0;+ return;+ }+ night_step();+}++static void pause_draw(void) {+ view_night();+ gfx_dim(0, gfx_y0, SCREEN_W, BAND_H, 9);+ if (g.confirm) {+ gfx_text_c(FONT_BIG, 160, 84, "Quit this night?", WHITE);+ gfx_text_c(FONT_TEXT, 160, 106, "It starts over next time.", RGB(0xB0B0B0));+ gfx_text(FONT_BIG, 104, 132, "No", WHITE);+ gfx_text(FONT_BIG, 190, 132, "Yes", WHITE);+ gfx_text(FONT_BIG, g.pause_item ? 168 : 82, 132, ">>", WHITE);+ return;+ }+ gfx_text_c(FONT_HUGE, 160, 62, "Paused", WHITE);+ static const char *const items[] = {"Resume", "How to play", "Quit night"};+ for (int i = 0; i < 3; i++) {+ gfx_text(FONT_BIG, 112, 104 + 20 * i, items[i], WHITE);+ if (g.pause_item == i) gfx_text(FONT_BIG, 88, 104 + 20 * i, ">>", WHITE);+ }+}++/* ------------------------------------------------------------------ 6 AM, the paychecks */+static void six_begin(void) {+ int n = g.n.night;+ if (n < 5 && g.reached < n + 1) g.reached = (uint8_t)(n + 1);+ if (n == 5) g.stars |= 1;+ if (n == 6) g.stars |= 2;+ if (n == 7 && g.n.ai[0] == 20 && g.n.ai[1] == 20 && g.n.ai[2] == 20 && g.n.ai[3] == 20) g.stars |= 4;+ save_progress();+ caption("*chimes*");+}++static void six_draw(void) {+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);+ /* 5 rolls up into 6 */+ float r = g.t < 1 ? 0 : g.t > 6 ? 1 : (g.t - 1) / 5;+ int cy = 104, dh = 30, off = (int)(r * dh);+ if (gfx_y0 + BAND_H > cy - 2 && gfx_y0 < cy + dh) {+ gfx_text(FONT_HUGE, 118, cy - off, "5", WHITE);+ gfx_text(FONT_HUGE, 118, cy + dh - off, "6", WHITE);+ gfx_fill(110, cy - dh, 30, dh, BLACK); /* (only the window between shows) */+ gfx_fill(110, cy + dh, 30, dh, BLACK);+ }+ gfx_text(FONT_HUGE, 148, cy, "AM", WHITE);+ if (g.t > 6.2f) gfx_text_c(FONT_TEXT, 160, 170, "*children cheering*", RGB(0xA0A0A0));+ gfx_dim(0, gfx_y0, SCREEN_W, BAND_H, fade_in_out(g.t, 1, 10.5f, 1));+}++static void six_step(void) {+ if (g.t < DT * 1.5f) six_begin();+ if (pressed(K_OK) && g.t > 6.5f && g.t < 10.5f) g.t = 10.5f;+ if (g.t < 11.5f) return;+ int n = g.n.night;+ if (n < 5) start_night(n + 1);+ else {+ g.paper = (uint8_t)(n - 5);+ go(SC_PAPER);+ }+}++static void paper_draw(void) {+ static const int pics[3] = {PIC_PAYCHECK, PIC_OVERTIME, PIC_PINKSLIP};+ pic_draw(pics[g.paper], 0, 0);+ gfx_dim(0, gfx_y0, SCREEN_W, BAND_H, fade_in_out(g.t, 2, 17, 2));+}++static void paper_step(void) {+ if (pressed(K_OK) && g.t > 2 && g.t < 17) g.t = 17;+ if (g.t >= 19) go(SC_TITLE);+}++/* ------------------------------------------------------------------ the end of a night */+static void over_draw(void) {+ if (g.t < 2.5f) {+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);+ gfx_static(0, gfx_y0, SCREEN_W, BAND_H, 30, rnd());+ return;+ }+ pic_draw(PIC_GAMEOVER, 0, 0);+ gfx_static(0, gfx_y0, SCREEN_W, BAND_H, g.t < 3 ? 26 : 6, rnd());+ gfx_text_r(FONT_HUGE, 306, 200, "Game Over", WHITE);+}++static void over_step(void) {+ if ((pressed(K_OK) && g.t > 3) || g.t > 13) go(SC_TITLE);+}++static void golden_draw(void) {+ pic_draw(PIC_GOLDEN, ((int)(g.t * 60) & 2) - 1, 0);+ gfx_static(0, gfx_y0, SCREEN_W, BAND_H, 6 + (int)(rnd() % 8), rnd());+}++static void golden_step(void) {+ if (g.t > 1.6f) g.running = false; /* and the game is gone, as it crashes on a computer */+}++/* ------------------------------------------------------------------ the custom night */+static const int faces[4] = {PIC_FACE_FREDDY, PIC_FACE_BONNIE, PIC_FACE_CHICA, PIC_FACE_FOXY};+static const char *const names[4] = {"Freddy", "Bonnie", "Chica", "Foxy"};++static void custom_draw(void) {+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);+ gfx_text_c(FONT_BIG, 160, 14, "Customize Night", WHITE);+ for (int i = 0; i < 4; i++) {+ int x = 12 + 76 * i, y = 52;+ pic_part(faces[i], x, y, 0, 0, 64, 64);+ gfx_frame_rect(x - 2, y - 2, 68, 68, g.custom_sel == i ? WHITE : RGB(0x404040));+ gfx_text_c(FONT_HUD, x + 32, y + 72, names[i], WHITE);+ gfx_text_c(FONT_TEXT, x + 32, y + 88, "A.I. Level", RGB(0xB0B0B0));+ char s[3] = {(char)('0' + g.custom[i] / 10), (char)('0' + g.custom[i] % 10), 0};+ gfx_text_c(FONT_HUGE, x + 32, y + 104, g.custom[i] >= 10 ? s : s + 1, WHITE);+ if (g.custom_sel == i) {+ gfx_text(FONT_BIG, x + 2, y + 106, "<", WHITE);+ gfx_text(FONT_BIG, x + 52, y + 106, ">", WHITE);+ }+ }+ gfx_text(FONT_TEXT, 12, 214, "< > pick up down: level", RGB(0x909090));+ gfx_text_r(FONT_BIG, 308, 208, "Ready", (int)(g.t * 2) & 1 ? WHITE : RGB(0xC0C0C0));+}++static void custom_step(void) {+ if (pressed(K_LEFT | K_DIGIT(4))) g.custom_sel = (uint8_t)((g.custom_sel + 3) % 4);+ if (pressed(K_RIGHT | K_DIGIT(6))) g.custom_sel = (uint8_t)((g.custom_sel + 1) % 4);+ int d = 0;+ uint32_t up = K_UP | K_DIGIT(8), down = K_DOWN | K_DIGIT(2);+ if (pressed(up)) d = 1, g.repeat = 0.35f;+ else if (pressed(down)) d = -1, g.repeat = 0.35f;+ else if (g.held & (up | down)) { /* held: faster */+ g.repeat -= DT;+ if (g.repeat <= 0) g.repeat = 0.06f, d = g.held & up ? 1 : -1;+ }+ int8_t *v = &g.custom[g.custom_sel];+ *v = (int8_t)(*v + d < 0 ? 0 : *v + d > 20 ? 20 : *v + d);+ if (pressed(K_BACK)) {+ save_progress();+ go(SC_TITLE);+ }+ if (pressed(K_OK)) {+ save_progress();+ if (g.custom[0] == 1 && g.custom[1] == 9 && g.custom[2] == 8 && g.custom[3] == 7) go(SC_GOLDEN);+ else start_night(7);+ }+}++/* ------------------------------------------------------------------ steps and drawing */+void game_step(uint32_t keys) {+ g.pressed = keys & ~g.held;+ g.held = keys;+ for (int i = 0; i < 4; i++)+ if (g.cap_t[i] > 0) g.cap_t[i] -= DT;+ if (g.blip > 0) g.blip -= DT;+ if (keys & K_HOME) { /* Home (or On/Off): a night is kept as it is */+ if (g.scene == SC_NIGHT) save_resume();+ g.running = false;+ return;+ }+ g.t += DT;+ switch (g.scene) {+ case SC_TITLE: title_step(); break;+ case SC_NEWS: news_step(); break;+ case SC_KEYS: keys_step(); break;+ case SC_INTRO: intro_step(); break;+ case SC_NIGHT: night_scene_step(); break;+ case SC_SCARE:+ g.scare_t += DT;+ if (g.scare_t > 0.95f) go(SC_OVER);+ break;+ case SC_SIX: six_step(); break;+ case SC_PAPER: paper_step(); break;+ case SC_OVER: over_step(); break;+ case SC_CUSTOM: custom_step(); break;+ case SC_GOLDEN: golden_step(); break;+ }+}++void game_draw(void) {+ static void (*const draws[])(void) = {+ [SC_TITLE] = title_draw, [SC_NEWS] = news_draw, [SC_KEYS] = keys_draw, [SC_INTRO] = intro_draw,+ [SC_NIGHT] = view_night, [SC_SCARE] = view_scare, [SC_SIX] = six_draw, [SC_PAPER] = paper_draw,+ [SC_OVER] = over_draw, [SC_CUSTOM] = custom_draw, [SC_GOLDEN] = golden_draw};+ gfx_frame(g.scene == SC_NIGHT && g.paused ? pause_draw : draws[g.scene]);+}diff --git a/games/fnaf/src/game.h b/games/fnaf/src/game.hnew file mode 100644index 00000000..1bb1f907--- /dev/null+++ b/games/fnaf/src/game.h@@ -0,0 +1,117 @@+/* Five Nights at Freddy's: the game's state and its parts.+ *+ * game.c: the scenes (title, newspaper, the night's card, 6 AM, paychecks, game over, custom night), keys and+ * saves. night.c: a night (time, power, the doors and lights, the cameras, the animatronics) as the game plays+ * it, 60 steps a second. view.c: drawing the office, the cameras and what is around them. calls.c: the phone+ * calls, as subtitles. */+#ifndef FNAF_GAME_H+#define FNAF_GAME_H+#include <stdbool.h>+#include <stdint.h>++#define DT (1.0f / 60) /* a step */+#define OFFICE_PAN 213 /* how far the office view turns (the office is 533 wide, the screen 320) */+#define CAM_PAN 213++enum { CAM_1A, CAM_1B, CAM_1C, CAM_2A, CAM_2B, CAM_3, CAM_4A, CAM_4B, CAM_5, CAM_6, CAM_7, CAM_COUNT };+enum { AT_DOOR = CAM_COUNT, IN_OFFICE }; /* where Freddy, Bonnie and Chica go past the cameras */+enum { FREDDY, BONNIE, CHICA, FOXY };+enum { LEFT, RIGHT };++/* scenes */+enum { SC_TITLE, SC_NEWS, SC_KEYS, SC_INTRO, SC_NIGHT, SC_SCARE, SC_SIX, SC_PAPER, SC_OVER, SC_CUSTOM, SC_GOLDEN };+/* jumpscares */+enum { SCARE_BONNIE, SCARE_CHICA, SCARE_FREDDY, SCARE_FOXY, SCARE_DARK };++/* A night, all of it: kept as it is when Home quits (save.c), so the next start goes on from there. */+typedef struct {+ uint8_t night; /* 1 to 7 (7: the custom night) */+ int8_t ai[4]; /* Freddy, Bonnie, Chica, Foxy: 0 to 20 */+ uint8_t hour; /* 0 (12 AM) to 6 */+ uint8_t usage; /* 1 to 5 bars */+ int16_t power; /* 999: 99.9 % */+ uint8_t door[2]; /* closed (or closing) */+ uint8_t light; /* 0, 1 + LEFT or 1 + RIGHT */+ uint8_t monitor; /* up, or going up */+ uint8_t cam; /* the camera picked */+ int8_t want; /* a door or light pressed while looking away: turning there first (-1 none) */+ uint8_t pos[3]; /* Freddy, Bonnie, Chica: a CAM_*, AT_DOOR or IN_OFFICE */+ uint8_t freddy_state; /* 0 waits, 1 counts down, 2 goes at the next chance */+ uint8_t foxy; /* 0 behind the curtain, 1 peeking, 2 out, 3 gone down the hall */+ uint8_t foxy_pounds; /* times he hit the closed door */+ uint8_t foxy_seen; /* seen running in 2A */+ uint8_t gold; /* Golden Freddy: 0 may come, 1 on 2B's poster, 2 seen there, 3 in the office, 4 gone */+ uint8_t call_muted;+ uint8_t dark; /* the power is out: 1 dark, 2 Freddy at the door, 3 all black */+ uint8_t pad[3];+ float t; /* seconds since 12 AM */+ float hour_t;+ float drain_t, penalty_t;+ float door_anim[2]; /* 0 open to 1 closed */+ float pan, pan_v; /* the office view's left edge */+ float flip; /* the monitor: 0 down to 1 up */+ float cam_t; /* the camera's slow turn: 14 seconds there and back */+ float glitch; /* seconds of disruption on the camera watched */+ float force_t; /* someone came in while the monitor was up: it comes down after 30 seconds */+ float move_t[4]; /* until the next movement opportunity */+ float freddy_count; /* Freddy's countdown, in frames */+ float freddy_try; /* in the office: a try a second */+ float foxy_stun; /* frames Foxy fails every opportunity (the monitor was up) */+ float foxy_wait; /* frames out of the cove */+ float foxy_run; /* frames since he was seen running, or -1 */+ float kitchen_t, circus_t, hum_t, gold_t, halluc, dark_t, dark_step;+} Night;++typedef struct {+ int scene;+ float t; /* seconds in the scene */+ uint32_t held, pressed;+ bool running;+ /* the save: the night reached (1 to 5), the stars and whether the keys were shown */+ uint8_t reached, stars, keys_seen;+ uint8_t menu, menu_n;+ uint8_t paused, confirm, pause_item;+ uint8_t custom_sel, paper;+ uint8_t scare, after_keys;+ int8_t custom[4]; /* the custom night's levels */+ float scare_t;+ float blip; /* the cameras' white flicker when switched */+ float repeat; /* a held key repeats */+ const char *cap[4]; /* what is heard, as captions (the newest last) */+ float cap_t[4];+ Night n;+} Game;++extern Game g;++/* game.c */+void game_init(void);+void game_step(uint32_t keys);+void game_draw(void);+uint32_t rnd(void);+float rndf(void);+void start_night(int night);+void caption(const char *s);++/* night.c */+void night_begin(int night);+void night_step(void);+bool night_power_out(void);++/* view.c */+void view_night(void);+void view_scare(void);+void view_captions(void);+void view_clock(void);++/* calls.c: the phone call's line at t seconds into the night, or NULL; and when it ends */+const char *call_line(int night, float t);+float call_end(int night);++/* save.c */+void save_restore_copy(void);+void save_progress(void);+void save_load(void);+void save_resume(void); /* the night as it is (Home) */+bool save_resume_load(void);+#endifdiff --git a/games/fnaf/src/gfx.c b/games/fnaf/src/gfx.cnew file mode 100644index 00000000..b65992ac--- /dev/null+++ b/games/fnaf/src/gfx.c@@ -0,0 +1,155 @@+/* Drawing (gfx.h): a band of 16 rows at a time, then pushed to the screen. */+#include "gfx.h"+#include "res.h"++uint16_t *gfx_band;+int gfx_y0;++void gfx_set_band_memory(uint16_t *m) { gfx_band = m; }++void gfx_frame(void (*draw)(void)) {+ for (gfx_y0 = 0; gfx_y0 < SCREEN_H; gfx_y0 += BAND_H) {+ draw();+ plat_push(0, gfx_y0, SCREEN_W, BAND_H, gfx_band);+ }+ gfx_y0 = 0;+}++uint16_t gfx_mix(uint16_t f, uint16_t b, int a) {+ uint32_t x = (f | (uint32_t)f << 16) & 0x07E0F81F, y = (b | (uint32_t)b << 16) & 0x07E0F81F;+ y = (y + ((x - y) * (uint32_t)a >> 5)) & 0x07E0F81F;+ return (uint16_t)(y | y >> 16);+}++/* the rectangle's part in this band: rows r0 to r1 of the band, columns x0 to x1 */+static bool clip(int x, int y, int w, int h, int *x0, int *x1, int *r0, int *r1) {+ *x0 = x > 0 ? x : 0, *x1 = x + w < SCREEN_W ? x + w : SCREEN_W;+ int y0 = y > gfx_y0 ? y : gfx_y0, y1 = y + h < gfx_y0 + BAND_H ? y + h : gfx_y0 + BAND_H;+ *r0 = y0 - gfx_y0, *r1 = y1 - gfx_y0;+ return *x0 < *x1 && *r0 < *r1;+}++void gfx_fill(int x, int y, int w, int h, uint16_t c) {+ int x0, x1, r0, r1;+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1)) return;+ for (int r = r0; r < r1; r++)+ for (uint16_t *p = gfx_band + r * SCREEN_W + x0, *e = gfx_band + r * SCREEN_W + x1; p < e; p++) *p = c;+}++void gfx_blend(int x, int y, int w, int h, uint16_t c, int a) {+ int x0, x1, r0, r1;+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1)) return;+ for (int r = r0; r < r1; r++)+ for (uint16_t *p = gfx_band + r * SCREEN_W + x0, *e = gfx_band + r * SCREEN_W + x1; p < e; p++)+ *p = gfx_mix(c, *p, a);+}++void gfx_frame_rect(int x, int y, int w, int h, uint16_t c) {+ gfx_fill(x, y, w, 1, c);+ gfx_fill(x, y + h - 1, w, 1, c);+ gfx_fill(x, y, 1, h, c);+ gfx_fill(x + w - 1, y, 1, h, c);+}++void gfx_static(int x, int y, int w, int h, int a, uint32_t seed) {+ int x0, x1, r0, r1;+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1) || a <= 0) return;+ for (int r = r0; r < r1; r++) {+ uint32_t s = seed ^ (uint32_t)(gfx_y0 + r) * 0x9E3779B1u;+ s ^= s >> 15, s *= 0x2C1B3C6Du, s ^= s >> 12;+ /* a line now and then is brighter, as the game's static has */+ int la = (s & 31) == 0 ? a + 6 : a;+ if (la > 32) la = 32;+ for (uint16_t *p = gfx_band + r * SCREEN_W + x0, *e = gfx_band + r * SCREEN_W + x1; p < e; p++) {+ s ^= s << 13, s ^= s >> 17, s ^= s << 5;+ uint32_t g = (s >> 24) * 3 / 4;+ uint16_t n = (uint16_t)((g & 0xF8) << 8 | (g & 0xFC) << 3 | g >> 3);+ *p = gfx_mix(n, *p, la);+ }+ }+}++void gfx_dim(int x, int y, int w, int h, int a) {+ int x0, x1, r0, r1;+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1)) return;+ for (int r = r0; r < r1; r++)+ for (uint16_t *p = gfx_band + r * SCREEN_W + x0, *e = gfx_band + r * SCREEN_W + x1; p < e; p++) {+ if (a <= 32) {+ *p = gfx_mix(*p, BLACK, 32 - a);+ } else { /* brighter: each channel times a / 32, up to 2 */+ uint32_t v = *p, R = (v >> 11) * (uint32_t)a >> 5, G = (v >> 5 & 63) * (uint32_t)a >> 5, B = (v & 31) * (uint32_t)a >> 5;+ *p = (uint16_t)((R > 31 ? 31 : R) << 11 | (G > 63 ? 63 : G) << 5 | (B > 31 ? 31 : B));+ }+ }+}++/* ------------------------------------------------------------------ text */+static const uint8_t *font_at(int font) {+ const uint8_t *s = section(SEC_FONTS);+ return s + rd32(s + 4 + 4 * font);+}++int gfx_line_h(int font) { return font_at(font)[0]; }++/* 4-bit alpha rows (the first pixel in the low half of a byte) in colour c */+static void alpha_rows(const uint8_t *rows, int w, int h, int x, int y, uint16_t c) {+ int x0, x1, r0, r1;+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1)) return;+ int stride = (w + 1) >> 1;+ for (int r = r0; r < r1; r++) {+ const uint8_t *src = rows + (gfx_y0 + r - y) * stride;+ uint16_t *d = gfx_band + r * SCREEN_W;+ for (int px = x0; px < x1; px++) {+ int i = px - x, a = src[i >> 1] >> ((i & 1) * 4) & 15;+ if (a) d[px] = a == 15 ? c : gfx_mix(c, d[px], a * 2 + (a >> 3));+ }+ }+}++int gfx_text_n(int font, int x, int y, const char *s, int n, uint16_t c) {+ const uint8_t *f = font_at(font);+ int x0 = x;+ bool here = y < gfx_y0 + BAND_H && y + f[0] > gfx_y0;+ for (; *s && n-- > 0; s++) {+ int ch = (uint8_t)*s;+ if (ch < 32 || ch > 126) ch = '?';+ const uint8_t *g = f + 4 + 12 * (ch - 32);+ if (here && g[1]) alpha_rows(f + rd32(g + 8), g[1], g[2], x + (int8_t)g[3], y + (int8_t)g[4], c);+ x += g[0];+ }+ return x - x0;+}++int gfx_text(int font, int x, int y, const char *s, uint16_t c) { return gfx_text_n(font, x, y, s, 1 << 30, c); }++int gfx_text_wn(int font, const char *s, int n) {+ const uint8_t *f = font_at(font);+ int w = 0;+ for (; *s && n-- > 0; s++) {+ int ch = (uint8_t)*s;+ if (ch < 32 || ch > 126) ch = '?';+ w += f[4 + 12 * (ch - 32)];+ }+ return w;+}+int gfx_text_w(int font, const char *s) { return gfx_text_wn(font, s, 1 << 30); }++void gfx_text_c(int font, int cx, int y, const char *s, uint16_t c) { gfx_text(font, cx - gfx_text_w(font, s) / 2, y, s, c); }+void gfx_text_r(int font, int rx, int y, const char *s, uint16_t c) { gfx_text(font, rx - gfx_text_w(font, s), y, s, c); }+void gfx_text_s(int font, int x, int y, const char *s, uint16_t c) {+ gfx_text(font, x + 1, y + 1, s, BLACK);+ gfx_text(font, x, y, s, c);+}++/* ------------------------------------------------------------------ small pictures */+static const uint8_t *img_at(int id) {+ const uint8_t *s = section(SEC_IMGS);+ return s + rd32(s + 4 + 4 * id);+}+int gfx_img_w(int id) { return (int)rd16(img_at(id)); }+int gfx_img_h(int id) { return (int)rd16(img_at(id) + 2); }++void gfx_img(int id, int x, int y, uint16_t c) {+ const uint8_t *p = img_at(id);+ alpha_rows(p + 8, (int)rd16(p), (int)rd16(p + 2), x, y, c);+}diff --git a/games/fnaf/src/gfx.h b/games/fnaf/src/gfx.hnew file mode 100644index 00000000..2e625107--- /dev/null+++ b/games/fnaf/src/gfx.h@@ -0,0 +1,53 @@+/* Five Nights at Freddy's: drawing, a band of 16 rows at a time.+ *+ * The screen is drawn in 15 bands of 320 x 16 pixels (one row of the pictures' 16 x 16 squares): for each+ * band the scene's whole drawing function runs, everything clipped to the band, then the band is pushed.+ * So the game needs no frame buffer (it would not fit in the RAM apps get), and a picture's squares are+ * decoded once each, as the band they fall in is drawn. */+#ifndef FNAF_GFX_H+#define FNAF_GFX_H+#include <stdbool.h>+#include <stdint.h>+#include "plat.h"++#define BAND_H 16+#define RGB(c) (uint16_t)((((c) >> 8) & 0xF800) | (((c) >> 5) & 0x07E0) | (((c) >> 3) & 0x1F))+#define WHITE 0xFFFF+#define BLACK 0x0000++extern uint16_t *gfx_band; /* SCREEN_W x BAND_H */+extern int gfx_y0; /* the band's top row */+void gfx_set_band_memory(uint16_t *m);+/* draws the frame: draw() once for each band */+void gfx_frame(void (*draw)(void));++uint16_t gfx_mix(uint16_t f, uint16_t b, int a); /* f over b, a from 0 (b) to 32 (f) */+void gfx_fill(int x, int y, int w, int h, uint16_t c);+void gfx_blend(int x, int y, int w, int h, uint16_t c, int a);+void gfx_frame_rect(int x, int y, int w, int h, uint16_t c);+/* video noise over a rectangle: a of 32 of the way to grey static; seed changes it each frame */+void gfx_static(int x, int y, int w, int h, int a, uint32_t seed);+/* the rectangle a of 32 of the way to black, or brighter (a > 32 up to 64) */+void gfx_dim(int x, int y, int w, int h, int a);++/* text in data.bin's fonts (FONT_*); returns the width */+int gfx_text(int font, int x, int y, const char *s, uint16_t c);+int gfx_text_w(int font, const char *s);+int gfx_text_n(int font, int x, int y, const char *s, int n, uint16_t c); /* the first n letters */+int gfx_text_wn(int font, const char *s, int n);+int gfx_line_h(int font);+void gfx_text_c(int font, int cx, int y, const char *s, uint16_t c); /* centred on cx */+void gfx_text_r(int font, int rx, int y, const char *s, uint16_t c); /* ending at rx */+/* with a 1-pixel dark shadow, for words over pictures */+void gfx_text_s(int font, int x, int y, const char *s, uint16_t c);+/* data.bin's small pictures (IMG_*): white (or grey) with alpha, in colour c */+void gfx_img(int id, int x, int y, uint16_t c);+int gfx_img_w(int id);+int gfx_img_h(int id);++/* pictures (pic.c): the whole of one at (x, y), or the part (sx, sy, w, h) of it */+void pic_draw(int id, int x, int y);+void pic_part(int id, int x, int y, int sx, int sy, int w, int h);+int pic_w(int id); /* (in squares of 16 pixels, times 16) */+int pic_h(int id);+#endifdiff --git a/games/fnaf/src/icon.png b/games/fnaf/src/icon.pngnew file mode 100644index 00000000..51065bcfBinary files /dev/null and b/games/fnaf/src/icon.png differdiff --git a/games/fnaf/src/main.c b/games/fnaf/src/main.cnew file mode 100644index 00000000..6751bf02--- /dev/null+++ b/games/fnaf/src/main.c@@ -0,0 +1,46 @@+/* Five Nights at Freddy's for the NumWorks calculator.+ *+ * Inspired by Five Nights at Freddy's by Scott Cawthon, not affiliated with him.+ * Made by Mason Chen as part of NumPlay. */+#include "game.h"+#include "gfx.h"+#include "plat.h"+#include "res.h"++#ifndef HOST+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "FNAF";+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;+extern const uint8_t fnaf_data[];+const uint8_t *fnaf_bin;++uint32_t perf_frames __attribute__((used)); /* read by tools/emu.py */+uint32_t perf_updates __attribute__((used));++int main(void) {+ uint16_t band[SCREEN_W * BAND_H]; /* (here: on the stack, out of the RAM apps get) */+ gfx_set_band_memory(band);+ plat_begin();+ fnaf_bin = fnaf_data;+ game_init();+ uint32_t next = plat_millis() * 3; /* in thirds of a millisecond: 50 a step, 60 steps a second */+ while (g.running) {+ /* the game's steps: drawn when caught up (at most 4 steps for a drawing) */+ int n = 0;+ uint32_t now = plat_millis() * 3;+ while ((int32_t)(now - next) >= 0 && n < 4 && g.running) {+ game_step(plat_keys());+ perf_updates++;+ next += 50;+ n++;+ }+ if (!g.running) break;+ if ((int32_t)(now - next) > 600) next = now; /* far behind: do not rush */+ if (n) {+ game_draw();+ perf_frames++;+ } else+ plat_sleep(1);+ }+ return plat_end();+}+#endifdiff --git a/games/fnaf/src/night.c b/games/fnaf/src/night.cnew file mode 100644index 00000000..24027015--- /dev/null+++ b/games/fnaf/src/night.c@@ -0,0 +1,472 @@+/* A night of Five Nights at Freddy's, 60 steps a second, as the game plays it.+ *+ * Every few seconds each animatronic has a movement opportunity (Freddy every 3.02, Bonnie 4.97, Chica 4.98,+ * Foxy 5.01): a number from 1 to 20, and it moves if its AI level (0 to 20, by night, rising at 2, 3 and 4 AM)+ * is that number or more. Bonnie and Chica wander their sides of the building to the doors; at a closed door+ * they go back, at an open one they come in, and get you when the monitor next comes down. Freddy goes his+ * one way to the right door, only while the monitor is down (but for his last step, which he takes while you+ * watch another camera), and waits a while after each chance, longer when you watch him. Foxy comes out of+ * Pirate Cove when the cameras stay down, then runs for the left door. The power drains a point (of 999)+ * a second for each bar of usage, and a point every few seconds more from the second night on; when it is+ * gone, the doors open, the lights die, and Freddy comes. */+#include <string.h>+#include "game.h"+#include "plat.h"++#define N g.n++static const int8_t AI[6][4] = { /* Freddy, Bonnie, Chica, Foxy at 12 AM, nights 1 to 6 */+ {0, 0, 0, 0}, {0, 3, 1, 1}, {1, 0, 5, 2}, {1, 2, 4, 6}, {3, 5, 7, 5}, {4, 10, 12, 16}};+static const float OPPORTUNITY[4] = {3.02f, 4.97f, 4.98f, 5.01f};+static const float PENALTY[8] = {0, 0, 6, 5, 4, 3, 3, 3}; /* seconds between the extra points, by night */+static const uint8_t BONNIE_GOES[CAM_COUNT][2] = {+ [CAM_1A] = {CAM_5, CAM_1B}, [CAM_1B] = {CAM_5, CAM_2A}, [CAM_5] = {CAM_1B, CAM_2A},+ [CAM_2A] = {CAM_3, CAM_2B}, [CAM_3] = {AT_DOOR, CAM_2A}, [CAM_2B] = {CAM_3, AT_DOOR}};+static const uint8_t CHICA_GOES[CAM_COUNT][2] = {+ [CAM_1A] = {CAM_1B, CAM_1B}, [CAM_1B] = {CAM_7, CAM_6}, [CAM_7] = {CAM_6, CAM_4A},+ [CAM_6] = {CAM_7, CAM_4A}, [CAM_4A] = {CAM_1B, CAM_4B}, [CAM_4B] = {CAM_4A, AT_DOOR}};+static const uint8_t FREDDY_GOES[CAM_COUNT] = {+ [CAM_1A] = CAM_1B, [CAM_1B] = CAM_7, [CAM_7] = CAM_6, [CAM_6] = CAM_4A, [CAM_4A] = CAM_4B, [CAM_4B] = AT_DOOR};+/* the cameras around each on the map: left, right, up, down */+static const int8_t NEXT_CAM[CAM_COUNT][4] = {+ [CAM_1A] = {-1, -1, -1, CAM_1B}, [CAM_1B] = {CAM_5, CAM_7, CAM_1A, CAM_1C}, [CAM_1C] = {CAM_5, CAM_7, CAM_1B, CAM_3},+ [CAM_2A] = {CAM_3, CAM_4A, CAM_1C, CAM_2B}, [CAM_2B] = {CAM_3, CAM_4B, CAM_2A, -1}, [CAM_3] = {-1, CAM_2A, CAM_1C, -1},+ [CAM_4A] = {CAM_2A, CAM_6, -1, CAM_4B}, [CAM_4B] = {CAM_2B, -1, CAM_4A, -1}, [CAM_5] = {-1, CAM_1B, -1, CAM_1C},+ [CAM_6] = {CAM_4A, -1, CAM_7, -1}, [CAM_7] = {CAM_1B, -1, -1, CAM_6}};++static int roll(void) { return 1 + (int)(rnd() % 20); }+static bool watching(void) { return N.flip >= 1; }+static bool pressed(uint32_t k) { return (g.pressed & k) != 0; }+static bool held(uint32_t k) { return (g.held & k) != 0; }++void night_begin(int night) {+ memset(&N, 0, sizeof N);+ N.night = (uint8_t)night;+ if (night < 7) {+ memcpy(N.ai, AI[night - 1], sizeof N.ai);+ if (night == 4) N.ai[FREDDY] = (int8_t)(1 + (rnd() & 1));+ } else+ memcpy(N.ai, g.custom, sizeof N.ai);+ N.power = 999;+ N.usage = 1;+ N.pan = OFFICE_PAN / 2;+ N.want = -1;+ N.cam = CAM_1A;+ N.pos[FREDDY] = N.pos[BONNIE] = N.pos[CHICA] = CAM_1A;+ for (int k = 0; k < 4; k++) N.move_t[k] = OPPORTUNITY[k];+ N.foxy_run = -1;+}++/* ------------------------------------------------------------------ things that end the night */+static void scare(int who) {+ g.scene = SC_SCARE;+ g.scare = (uint8_t)who;+ g.scare_t = 0;+ N.monitor = 0;+ N.flip = 0;+}++static void six_am(void) {+ g.scene = SC_SIX;+ g.t = 0;+}++static void power_out(void) {+ N.power = 0;+ N.dark = 1;+ N.dark_t = N.dark_step = 0;+ N.door[LEFT] = N.door[RIGHT] = 0;+ N.light = 0;+ N.monitor = 0;+ N.want = -1;+ caption("*the power goes out*");+}++bool night_power_out(void) { return N.dark != 0; }++/* ------------------------------------------------------------------ the office */+static bool side_in_view(int side) { return side == LEFT ? N.pan <= 24 : N.pan >= OFFICE_PAN - 24; }++/* a door or light button: k 0 the door, 1 the light */+static void button(int side, int k) {+ if (N.pos[side == LEFT ? BONNIE : CHICA] == IN_OFFICE) {+ caption("*click* ...it won't work");+ return;+ }+ if (k == 0) {+ float a = N.door_anim[side];+ if (a <= 0 || a >= 1) N.door[side] ^= 1;+ } else+ N.light = N.light == 1 + side ? 0 : (uint8_t)(1 + side);+}++static void office_keys(void) {+ static const uint32_t keys[2][2] = {{K_DIGIT(7), K_DIGIT(1)}, {K_DIGIT(9), K_DIGIT(3)}};+ for (int side = 0; side < 2; side++)+ for (int k = 0; k < 2; k++)+ if (pressed(keys[side][k])) {+ if (side_in_view(side)) {+ button(side, k);+ N.want = -1;+ } else+ N.want = (int8_t)(side * 2 + k);+ }+ /* turning: held, or toward a button pressed */+ float target = 0;+ if (held(K_LEFT | K_DIGIT(4))) target = -380, N.want = -1;+ else if (held(K_RIGHT | K_DIGIT(6))) target = 380, N.want = -1;+ if (N.want >= 0) {+ int side = N.want >> 1;+ if (side_in_view(side)) {+ button(side, N.want & 1);+ N.want = -1;+ } else+ target = side == LEFT ? -720 : 720;+ }+ float dv = target - N.pan_v, step = 4200 * DT;+ N.pan_v += dv > step ? step : dv < -step ? -step : dv;+ N.pan += N.pan_v * DT;+ if (N.pan < 0) N.pan = 0, N.pan_v = 0;+ if (N.pan > OFFICE_PAN) N.pan = OFFICE_PAN, N.pan_v = 0;+ if (pressed(K_DIGIT(5)) && N.pan > 40 && N.pan < 190) caption("*honk*"); /* Freddy's nose, on the poster */+}++static void monitor_keys(void) {+ if (N.flip < 1) return;+ /* (Golden Freddy holds the camera on 2B) */+ if (N.cam == CAM_2B && (N.gold == 1 || N.gold == 2)) return;+ int to = -1;+ static const uint32_t arrows[4] = {K_LEFT, K_RIGHT, K_UP, K_DOWN};+ for (int d = 0; d < 4; d++)+ if (pressed(arrows[d]) && NEXT_CAM[N.cam][d] >= 0) to = NEXT_CAM[N.cam][d];+ if (pressed(K_DIGIT(1))) to = N.cam == CAM_1A ? CAM_1B : N.cam == CAM_1B ? CAM_1C : CAM_1A;+ if (pressed(K_DIGIT(2))) to = N.cam == CAM_2A ? CAM_2B : CAM_2A;+ if (pressed(K_DIGIT(3))) to = CAM_3;+ if (pressed(K_DIGIT(4))) to = N.cam == CAM_4A ? CAM_4B : CAM_4A;+ if (pressed(K_DIGIT(5))) to = CAM_5;+ if (pressed(K_DIGIT(6))) to = CAM_6;+ if (pressed(K_DIGIT(7))) to = CAM_7;+ if (to >= 0 && to != N.cam) {+ N.cam = (uint8_t)to;+ N.glitch = 0;+ g.blip = 0.12f;+ }+}++static void monitor_flip(void) {+ bool was = watching();+ if (N.dark) N.monitor = 0;+ N.flip += (N.monitor ? 1 : -1) * DT / 0.22f;+ if (N.flip < 0) N.flip = 0;+ if (N.flip > 1) N.flip = 1;+ if (!was && watching()) { /* up */+ N.light = 0;+ g.blip = 0.12f;+ if (N.pos[BONNIE] == IN_OFFICE || N.pos[CHICA] == IN_OFFICE) N.force_t = 0;+ }+ if (was && !watching()) { /* down: whoever came in is here */+ N.glitch = 0;+ if (N.pos[BONNIE] == IN_OFFICE) scare(SCARE_BONNIE);+ else if (N.pos[CHICA] == IN_OFFICE) scare(SCARE_CHICA);+ else if (N.gold == 2) {+ N.gold = 3;+ N.gold_t = 0;+ N.halluc = 1.66f;+ }+ }+}++static void keys(void) {+ if (pressed(K_DIGIT(0) | K_DEL) && N.night <= 5 && !N.call_muted && N.t < call_end(N.night)) N.call_muted = 1;+ if (N.dark) { /* no power: only looking around */+ float target = held(K_LEFT | K_DIGIT(4)) ? -380 : held(K_RIGHT | K_DIGIT(6)) ? 380 : 0;+ N.pan += target * DT;+ N.pan = N.pan < 0 ? 0 : N.pan > OFFICE_PAN ? OFFICE_PAN : N.pan;+ return;+ }+ bool toggle = pressed(K_OK | K_DIGIT(8)) || (N.flip <= 0 && pressed(K_UP));+ if (toggle && (N.flip <= 0 || N.flip >= 1)) {+ N.monitor ^= 1;+ N.want = -1;+ }+ if (N.flip <= 0 && !N.monitor) office_keys();+ else monitor_keys();+}++/* ------------------------------------------------------------------ time and power */+static void time_passes(void) {+ N.t += DT;+ N.hour_t += DT;+ if (N.hour_t < (N.hour == 0 ? 90 : 89)) return;+ N.hour_t -= N.hour == 0 ? 90 : 89;+ N.hour++;+ if (N.hour >= 2 && N.hour <= 4) N.ai[BONNIE]++;+ if (N.hour == 3 || N.hour == 4) N.ai[CHICA]++, N.ai[FOXY]++;+ for (int k = 0; k < 4; k++)+ if (N.ai[k] > 20) N.ai[k] = 20;+ if (N.hour >= 6) six_am();+}++static void drain(int points) {+ N.power = (int16_t)(N.power > points ? N.power - points : 0);+}++static void power(void) {+ N.usage = (uint8_t)(1 + watching() + N.door[LEFT] + N.door[RIGHT] + (N.light != 0));+ N.drain_t += DT;+ if (N.drain_t >= 1) {+ N.drain_t -= 1;+ drain(N.usage);+ }+ if (PENALTY[N.night] > 0) {+ N.penalty_t += DT;+ if (N.penalty_t >= PENALTY[N.night]) {+ N.penalty_t -= PENALTY[N.night];+ drain(1);+ }+ }+ if (N.power <= 0) power_out();+}++/* ------------------------------------------------------------------ the animatronics */+/* what a move sounds like from the office (the game's footsteps, by where they go) */+static void footsteps(int to, int who) {+ static const uint8_t loud[2][CAM_COUNT] = { /* Bonnie, Chica: 0 none, 1 faint, 2, 3 close */+ {[CAM_1B] = 1, [CAM_2A] = 2, [CAM_2B] = 3, [CAM_3] = 2},+ {[CAM_7] = 1, [CAM_6] = 1, [CAM_4A] = 2, [CAM_4B] = 2}};+ int l = to < CAM_COUNT ? loud[who - BONNIE][to] : 3;+ static const char *const say[4] = {NULL, "*faint footsteps*", "*footsteps*", "*footsteps, close by*"};+ if (say[l]) caption(say[l]);+}++static bool opportunity(int who) {+ N.move_t[who] -= DT;+ if (N.move_t[who] > 0) return false;+ N.move_t[who] += OPPORTUNITY[who];+ return roll() <= N.ai[who];+}++/* Bonnie and Chica: who 1 or 2 */+static void wanderer(int who) {+ int side = who == BONNIE ? LEFT : RIGHT;+ uint8_t *pos = &N.pos[who];+ if (*pos == IN_OFFICE) {+ if (watching()) {+ N.force_t += DT;+ if (N.force_t >= 30) N.monitor = 0; /* (it comes down by itself) */+ }+ return;+ }+ if (!opportunity(who)) return;+ int from = *pos, to;+ if (from == AT_DOOR) {+ to = N.door[side] ? (who == BONNIE ? CAM_1B : CAM_4A) : IN_OFFICE;+ if (to == IN_OFFICE && watching()) caption("*something is breathing*");+ } else+ to = (who == BONNIE ? BONNIE_GOES : CHICA_GOES)[from][rnd() & 1];+ *pos = (uint8_t)to;+ if (to != from) {+ footsteps(to, who);+ if (watching() && N.cam != CAM_6 && (N.cam == from || N.cam == to)) N.glitch = 5;+ }+ if ((to == AT_DOOR) != (from == AT_DOOR)) {+ if (N.light == 1 + side) N.light = 0;+ }+}++static void freddy(void) {+ uint8_t *pos = &N.pos[FREDDY];+ if (*pos == IN_OFFICE) { /* a try every second, 1 in 4 */+ N.freddy_try += DT;+ if (N.freddy_try >= 1) {+ N.freddy_try -= 1;+ if (rnd() % 4 == 0) scare(SCARE_FREDDY);+ }+ return;+ }+ if (N.freddy_state == 1) N.freddy_count += 1;+ N.move_t[FREDDY] -= DT;+ bool chance = N.move_t[FREDDY] <= 0;+ if (chance) N.move_t[FREDDY] += OPPORTUNITY[FREDDY];+ if (watching() && *pos != CAM_4B) { /* he waits while the monitor is up, longer if he is watched */+ if (N.cam == *pos) N.freddy_count = 0;+ return;+ }+ if (N.freddy_state == 1 && N.freddy_count >= 1000 - 100 * N.ai[FREDDY]) {+ N.freddy_count = 0;+ N.freddy_state = 2;+ }+ if (chance && N.freddy_state == 0 && roll() <= N.ai[FREDDY]) {+ N.freddy_state = 1;+ return;+ }+ if (N.freddy_state != 2) return;+ if (*pos == CAM_4B && (!watching() || N.cam == CAM_4B)) {+ N.freddy_count = 0;+ return;+ }+ if (*pos == CAM_1A && (N.pos[BONNIE] == CAM_1A || N.pos[CHICA] == CAM_1A)) return;+ int to = FREDDY_GOES[*pos];+ if (to == AT_DOOR) to = N.door[RIGHT] ? CAM_4A : IN_OFFICE;+ N.freddy_state = 0;+ *pos = (uint8_t)to;+ static const char *const laugh[] = {"*a deep laugh, far away*", "*a deep laugh*", "*a deep laugh, close by*"};+ caption(laugh[to == CAM_1B || to == CAM_7 ? 0 : to == CAM_6 || to == CAM_4A ? 1 : 2]);+ if (to == CAM_6) caption("*a music box plays*");+}++static void foxy_reaches_door(void) {+ if (N.door[LEFT]) {+ caption("*BANG BANG BANG*");+ drain(10 + 50 * N.foxy_pounds);+ if (N.foxy_pounds < 40) N.foxy_pounds++;+ N.foxy = (uint8_t)(rnd() & 1);+ N.foxy_wait = 0;+ N.foxy_run = -1;+ N.move_t[FOXY] = OPPORTUNITY[FOXY];+ if (N.power <= 0) power_out();+ } else+ scare(SCARE_FOXY);+}++static void foxy(void) {+ if (watching()) N.foxy_stun = 50 + (float)(rnd() % 1000); /* the cameras up: he can't come out */+ else if (N.foxy_stun > 0) N.foxy_stun -= 1;+ if (N.foxy == 3) {+ if (watching() && N.cam == CAM_2A && N.foxy_run < 0) {+ N.foxy_run = 0;+ caption("*running footsteps*");+ }+ if (N.foxy_run >= 0) {+ N.foxy_run += 1;+ if (N.foxy_run >= 100) foxy_reaches_door();+ return;+ }+ N.foxy_wait += 1;+ if (N.foxy_wait >= 1500) {+ caption("*running footsteps*");+ foxy_reaches_door();+ }+ return;+ }+ N.move_t[FOXY] -= DT;+ if (N.move_t[FOXY] > 0) return;+ N.move_t[FOXY] += OPPORTUNITY[FOXY];+ if (N.foxy_stun > 0 || roll() > N.ai[FOXY]) return;+ if (++N.foxy == 3) N.foxy_wait = 0, N.foxy_run = -1;+}++/* ------------------------------------------------------------------ the rest */+static void golden(void) {+ switch (N.gold) {+ case 0:+ N.gold_t += DT;+ if (N.gold_t >= 1) {+ N.gold_t -= 1;+ if (rnd() % 32768 == 0) N.gold = 1;+ }+ break;+ case 1:+ if (watching() && N.cam == CAM_2B && N.pos[BONNIE] != CAM_2B) {+ N.gold = 2;+ caption("*a little girl giggles*");+ }+ break;+ case 3:+ if (watching()) {+ N.gold = 4;+ break;+ }+ N.gold_t += DT;+ if (N.gold_t >= 5) {+ g.scene = SC_GOLDEN;+ g.t = 0;+ }+ break;+ }+}++static void sounds(void) {+ /* the kitchen (no picture, only its sound): Chica's pots and pans, Freddy's music box */+ N.kitchen_t += DT;+ if (N.kitchen_t >= 4) {+ N.kitchen_t -= 4;+ bool near = watching() && N.cam == CAM_6;+ if (N.pos[CHICA] == CAM_6 && rnd() % 10 < 5) caption(near ? "*pots and pans clatter*" : "*pots and pans, far away*");+ if (N.pos[FREDDY] == CAM_6 && near) caption("*a music box plays*");+ }+ N.circus_t += DT;+ if (N.circus_t >= 5) {+ N.circus_t -= 5;+ if (rnd() % 30 == 0) caption("*circus music, far away*");+ }+ N.hum_t += DT;+ if (N.hum_t >= 4) {+ N.hum_t -= 4;+ if (N.foxy == 0 && rnd() % 30 == 0) caption("*humming from Pirate Cove*");+ /* from the fourth night: voices on the corners' cameras */+ if (N.night >= 4 && watching() && ((N.cam == CAM_2B && N.pos[BONNIE] == CAM_2B) ||+ (N.cam == CAM_4B && N.pos[CHICA] == CAM_4B)))+ caption("*a garbled voice*");+ }+ if (N.halluc > 0) N.halluc -= DT;+ else if ((int)(N.t * 60) % 60 == 0 && rnd() % 1000 == 0) N.halluc = 1.66f;+}++/* no power: Freddy at the left door, his song, then the dark */+static void dark(void) {+ N.door_anim[LEFT] -= DT / 0.3f;+ N.door_anim[RIGHT] -= DT / 0.3f;+ for (int s = 0; s < 2; s++)+ if (N.door_anim[s] < 0) N.door_anim[s] = 0;+ N.flip -= DT / 0.22f;+ if (N.flip < 0) N.flip = 0;+ N.dark_t += DT;+ N.dark_step += DT;+ switch (N.dark) {+ case 1:+ if ((N.dark_step >= 5 && (N.dark_step -= 5, rnd() % 5 == 0)) || N.dark_t >= 20) {+ N.dark = 2;+ N.dark_t = N.dark_step = 0;+ caption("*a music box: the Toreador March*");+ }+ break;+ case 2:+ if ((N.dark_step >= 5 && (N.dark_step -= 5, rnd() % 5 == 0)) || N.dark_t >= 20) {+ N.dark = 3;+ N.dark_t = N.dark_step = 0;+ caption("*silence*");+ }+ break;+ case 3:+ if ((N.dark_step >= 2 && (N.dark_step -= 2, rnd() & 1)) || N.dark_t >= 20) scare(SCARE_DARK);+ break;+ }+}++void night_step(void) {+ time_passes();+ if (g.scene != SC_NIGHT) return;+ keys();+ if (N.dark) {+ dark();+ return;+ }+ for (int s = 0; s < 2; s++) {+ N.door_anim[s] += (N.door[s] ? 1 : -1) * DT / 0.3f;+ N.door_anim[s] = N.door_anim[s] < 0 ? 0 : N.door_anim[s] > 1 ? 1 : N.door_anim[s];+ }+ monitor_flip();+ if (g.scene != SC_NIGHT) return;+ power();+ if (N.dark) return;+ if (N.glitch > 0) N.glitch -= DT;+ N.cam_t += DT;+ if (N.cam_t >= 14) N.cam_t -= 14;+ wanderer(BONNIE);+ wanderer(CHICA);+ freddy();+ if (g.scene == SC_NIGHT) foxy();+ if (g.scene == SC_NIGHT) golden();+ if (g.scene == SC_NIGHT) sounds();+}diff --git a/games/fnaf/src/pic.c b/games/fnaf/src/pic.cnew file mode 100644index 00000000..7e98403a--- /dev/null+++ b/games/fnaf/src/pic.c@@ -0,0 +1,248 @@+/* The pictures (tools/codec.py): 16 x 16 squares coded as JPEG codes them, decoded as the bands are drawn.+ *+ * A square: four 8 x 8 blocks of Y, one of Cb and one of Cr (at half resolution), each a Huffman-coded+ * list of quantized cosine coefficients. The inverse transform is libjpeg's "ifast" one (the AAN algorithm,+ * its scales folded into the quantization tables by tools/pack.py), with a shortcut for the many blocks+ * that are one flat colour in these dark rooms. Colours are dithered on the way to 16 bits, or the dark+ * gradients would band. */+#include "gfx.h"+#include "res.h"++typedef struct {+ const uint16_t *lut; /* 9 bits ahead: length << 8 | symbol, 0 when the code is longer */+ const int32_t *maxcode; /* JPEG's, by length (1 to 17) */+ const int32_t *valoff;+ const uint8_t *vals;+} Huff;++static const uint8_t zigzag[64 + 16] = {+ 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7,+ 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46,+ 53, 60, 61, 54, 47, 55, 62, 63,+ 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63 /* (a corrupt run lands here) */+};++static Huff huff_tab(int k) {+ const uint8_t *p = section(SEC_HUFF) + 1424 * k;+ return (Huff){(const uint16_t *)(const void *)p, (const int32_t *)(const void *)(p + 1024),+ (const int32_t *)(const void *)(p + 1096), p + 1168};+}++/* ------------------------------------------------------------------ bits */+typedef struct {+ const uint8_t *p;+ uint32_t buf; /* the next bits, from the top */+ int n;+} Bits;++static inline void fill(Bits *b) {+ while (b->n <= 24) {+ b->buf |= (uint32_t)*b->p++ << (24 - b->n);+ b->n += 8;+ }+}+static inline uint32_t take(Bits *b, int k) {+ uint32_t v = b->buf >> (32 - k);+ b->buf <<= k;+ b->n -= k;+ return v;+}+static inline int decode(Bits *b, const Huff *h) {+ fill(b);+ uint32_t e = h->lut[b->buf >> 23];+ if (e) {+ b->buf <<= e >> 8;+ b->n -= (int)(e >> 8);+ return (int)(e & 0xFF);+ }+ for (int l = 10; l <= 16; l++) {+ int32_t code = (int32_t)(b->buf >> (32 - l));+ if (code <= h->maxcode[l]) {+ b->buf <<= l;+ b->n -= l;+ return h->vals[(code + h->valoff[l]) & 0xFF];+ }+ }+ b->buf <<= 16; /* (corrupt: give up on this block) */+ b->n -= 16;+ return 0;+}+/* JPEG's extension of s bits to a signed value */+static inline int value(Bits *b, int s) {+ if (!s) return 0;+ fill(b);+ int v = (int)take(b, s);+ return v < 1 << (s - 1) ? v - (1 << s) + 1 : v;+}++/* ------------------------------------------------------------------ one block */+#define CONST_BITS 8+#define MUL(v, c) (((v) * (c)) >> CONST_BITS)+#define FIX_1_082392200 277+#define FIX_1_414213562 362+#define FIX_1_847759065 473+#define FIX_2_613125930 669++static inline uint8_t clamp8(int v) { return (uint8_t)(v < 0 ? 0 : v > 255 ? 255 : v); }++/* decodes a block into out (8 x 8 bytes, stride 8); *pred: the DC before it */+static void block(Bits *b, const Huff *dc, const Huff *ac, int *pred, const uint16_t *q, uint8_t *out) {+ int32_t c[64];+ uint64_t cols = 0; /* which coefficients are not 0, a bit each */+ int s = decode(b, dc);+ *pred += value(b, s);+ int dcv = *pred * q[0];+ for (int k = 1; k < 64;) {+ int rs = decode(b, ac), r = rs >> 4;+ s = rs & 15;+ if (!s) {+ if (r != 15) break;+ k += 16;+ continue;+ }+ k += r;+ if (k > 63) break;+ int z = zigzag[k++];+ cols |= (uint64_t)1 << z;+ c[z] = value(b, s) * q[z];+ }+ if (!cols) { /* one colour */+ uint8_t v = clamp8(((dcv + 16) >> 5) + 128);+ uint32_t w = v * 0x01010101u;+ for (int i = 0; i < 16; i++) ((uint32_t *)(void *)out)[i] = w;+ return;+ }+ c[0] = dcv;+ int32_t ws[64];+ for (int x = 0; x < 8; x++) { /* columns */+ int32_t *in = c + x, *o = ws + x;+#define IN(k) ((cols >> (x + 8 * (k)) & 1) ? in[8 * (k)] : 0)+ if (!(cols >> 8 & (0x01010101010101ull << x))) {+ int32_t d = x ? IN(0) : dcv;+ for (int k = 0; k < 8; k++) o[8 * k] = d;+ continue;+ }+ int32_t t0 = x ? IN(0) : dcv, t1 = IN(2), t2 = IN(4), t3 = IN(6);+ int32_t t10 = t0 + t2, t11 = t0 - t2, t13 = t1 + t3, t12 = MUL(t1 - t3, FIX_1_414213562) - t13;+ t0 = t10 + t13, t3 = t10 - t13, t1 = t11 + t12, t2 = t11 - t12;+ int32_t t4 = IN(1), t5 = IN(3), t6 = IN(5), t7 = IN(7);+#undef IN+ int32_t z13 = t6 + t5, z10 = t6 - t5, z11 = t4 + t7, z12 = t4 - t7;+ t7 = z11 + z13;+ t11 = MUL(z11 - z13, FIX_1_414213562);+ int32_t z5 = MUL(z10 + z12, FIX_1_847759065);+ t10 = MUL(z12, FIX_1_082392200) - z5;+ t12 = MUL(z10, -FIX_2_613125930) + z5;+ t6 = t12 - t7, t5 = t11 - t6, t4 = t10 + t5;+ o[0] = t0 + t7, o[56] = t0 - t7, o[8] = t1 + t6, o[48] = t1 - t6;+ o[16] = t2 + t5, o[40] = t2 - t5, o[32] = t3 + t4, o[24] = t3 - t4;+ }+ for (int y = 0; y < 8; y++) { /* rows: +128 and rounding folded into the first */+ int32_t *w = ws + 8 * y;+ uint8_t *o = out + 8 * y;+ int32_t w0 = w[0] + (128 << 5) + 16;+ int32_t t10 = w0 + w[4], t11 = w0 - w[4], t13 = w[2] + w[6], t12 = MUL(w[2] - w[6], FIX_1_414213562) - t13;+ int32_t t0 = t10 + t13, t3 = t10 - t13, t1 = t11 + t12, t2 = t11 - t12;+ int32_t z13 = w[5] + w[3], z10 = w[5] - w[3], z11 = w[1] + w[7], z12 = w[1] - w[7];+ int32_t t7 = z11 + z13, t11b = MUL(z11 - z13, FIX_1_414213562), z5 = MUL(z10 + z12, FIX_1_847759065);+ int32_t t10b = MUL(z12, FIX_1_082392200) - z5, t12b = MUL(z10, -FIX_2_613125930) + z5;+ int32_t t6 = t12b - t7, t5 = t11b - t6, t4 = t10b + t5;+ o[0] = clamp8((t0 + t7) >> 5), o[7] = clamp8((t0 - t7) >> 5);+ o[1] = clamp8((t1 + t6) >> 5), o[6] = clamp8((t1 - t6) >> 5);+ o[2] = clamp8((t2 + t5) >> 5), o[5] = clamp8((t2 - t5) >> 5);+ o[4] = clamp8((t3 + t4) >> 5), o[3] = clamp8((t3 - t4) >> 5);+ }+}++/* ------------------------------------------------------------------ one square */+static const uint8_t bayer[16] = {0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5};++/* decodes the square at data into px (16 x 16, stride 16) */+static void square(const uint8_t *data, int qset, uint16_t *px) {+ static Huff h[4];+ static const uint8_t *loaded;+ if (loaded != fnaf_bin) {+ for (int k = 0; k < 4; k++) h[k] = huff_tab(k);+ loaded = fnaf_bin;+ }+ const uint16_t *qy = (const uint16_t *)(const void *)(section(SEC_QUANT) + 256 * qset), *qc = qy + 64;+ uint8_t y[4][64] __attribute__((aligned(4))), cb[64] __attribute__((aligned(4))), cr[64] __attribute__((aligned(4)));+ Bits b = {data, 0, 0};+ int pred = 0;+ for (int k = 0; k < 4; k++) block(&b, &h[0], &h[1], &pred, qy, y[k]);+ pred = 0;+ block(&b, &h[2], &h[3], &pred, qc, cb);+ pred = 0;+ block(&b, &h[2], &h[3], &pred, qc, cr);+ for (int r = 0; r < 16; r += 2)+ for (int c = 0; c < 16; c += 2) {+ int ci = (r >> 1) * 8 + (c >> 1), u = cb[ci] - 128, v = cr[ci] - 128;+ int dr = (91881 * v + 32768) >> 16, dg = (-22554 * u - 46802 * v + 32768) >> 16, db = (116130 * u + 32768) >> 16;+ for (int i = 0; i < 2; i++)+ for (int j = 0; j < 2; j++) {+ int rr = r + i, cc = c + j;+ int l = y[(rr >> 3) * 2 + (cc >> 3)][(rr & 7) * 8 + (cc & 7)];+ int d = bayer[(rr & 3) * 4 + (cc & 3)];+ int R = l + dr + (d >> 1), G = l + dg + (d >> 2), B = l + db + (d >> 1);+ R = R < 0 ? 0 : R > 255 ? 255 : R;+ G = G < 0 ? 0 : G > 255 ? 255 : G;+ B = B < 0 ? 0 : B > 255 ? 255 : B;+ px[rr * 16 + cc] = (uint16_t)((R & 0xF8) << 8 | (G & 0xFC) << 3 | B >> 3);+ }+ }+}++/* ------------------------------------------------------------------ pictures */+typedef struct {+ int mw, mh, q;+ const uint8_t *table, *base_table; /* base_table: the picture whose squares it shares, or NULL */+ int count; /* its own squares then */+} Info;++static Info info(int id) {+ const uint8_t *p = section(SEC_PICS) + 12 * id, *t = section(SEC_TABLE);+ Info i = {p[0], p[1], p[2], t + rd32(p + 8), NULL, (int)rd16(p + 6)};+ uint32_t base = rd16(p + 4);+ if (base != 0xFFFF) i.base_table = t + rd32(section(SEC_PICS) + 12 * base + 8);+ return i;+}++static uint32_t square_at(const Info *i, int k) {+ if (!i->base_table) return rd24(i->table + 3 * k);+ int lo = 0, hi = i->count - 1;+ while (lo <= hi) {+ int mid = (lo + hi) >> 1, mk = (int)rd16(i->table + 5 * mid);+ if (mk == k) return rd24(i->table + 5 * mid + 2);+ if (mk < k) lo = mid + 1;+ else hi = mid - 1;+ }+ return rd24(i->base_table + 3 * k);+}++int pic_w(int id) { return 16 * section(SEC_PICS)[12 * id]; }+int pic_h(int id) { return 16 * section(SEC_PICS)[12 * id + 1]; }++void pic_part(int id, int x, int y, int sx, int sy, int w, int h) {+ Info in = info(id);+ /* clip to the screen, the band and the picture */+ int x0 = x > 0 ? x : 0, x1 = x + w < SCREEN_W ? x + w : SCREEN_W;+ int y0 = y > gfx_y0 ? y : gfx_y0, y1 = y + h < gfx_y0 + BAND_H ? y + h : gfx_y0 + BAND_H;+ if (x0 >= x1 || y0 >= y1) return;+ const uint8_t *bank = section(SEC_BANK);+ uint16_t px[256];+ /* in the picture: rows y0 - y + sy to y1 - y + sy, columns likewise */+ int pr0 = y0 - y + sy, pr1 = y1 - y + sy, pc0 = x0 - x + sx, pc1 = x1 - x + sx;+ for (int my = pr0 >> 4; my <= (pr1 - 1) >> 4 && my < in.mh; my++)+ for (int mx = pc0 >> 4; mx <= (pc1 - 1) >> 4 && mx < in.mw; mx++) {+ square(bank + square_at(&in, my * in.mw + mx), in.q, px);+ int r0 = my * 16 > pr0 ? my * 16 : pr0, r1 = my * 16 + 16 < pr1 ? my * 16 + 16 : pr1;+ int c0 = mx * 16 > pc0 ? mx * 16 : pc0, c1 = mx * 16 + 16 < pc1 ? mx * 16 + 16 : pc1;+ for (int r = r0; r < r1; r++) {+ uint16_t *d = gfx_band + (r - sy + y - gfx_y0) * SCREEN_W + (c0 - sx + x);+ const uint16_t *s = px + (r - my * 16) * 16 + (c0 - mx * 16);+ for (int c = c0; c < c1; c++) *d++ = *s++;+ }+ }+}++void pic_draw(int id, int x, int y) { pic_part(id, x, y, 0, 0, pic_w(id), pic_h(id)); }diff --git a/games/fnaf/src/plat.h b/games/fnaf/src/plat.hnew file mode 100644index 00000000..8685bc62--- /dev/null+++ b/games/fnaf/src/plat.h@@ -0,0 +1,41 @@+/* Five Nights at Freddy's: the platform (the calculator, or a computer for tests).+ *+ * plat_eadk.c: the calculator's EADK display, keyboard, time and files.+ * plat_host.c: a frame buffer that tests save as images, scripted keys and+ * simulated time (tests/play.c). */+#ifndef FNAF_PLAT_H+#define FNAF_PLAT_H+#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>++#define SCREEN_W 320+#define SCREEN_H 240++/* keys held now, as bits */+enum {+ K_LEFT = 1 << 0, K_RIGHT = 1 << 1, K_UP = 1 << 2, K_DOWN = 1 << 3,+ K_OK = 1 << 4, /* OK, EXE */+ K_BACK = 1 << 5, /* Back: pause */+ K_HOME = 1 << 6, /* Home, On/Off: keep the moment and quit */+ K_DEL = 1 << 7, /* backspace: mute the call */+ K_0 = 1 << 8, /* the digits: K_0 << n */+ K_ANY = 1 << 18+};+#define K_DIGIT(n) (K_0 << (n))+uint32_t plat_keys(void);+uint32_t plat_millis(void);+void plat_sleep(uint32_t ms);+void plat_push(int x, int y, int w, int h, const uint16_t *px);+bool plat_save(const char *name, const void *data, uint32_t len);+const uint8_t *plat_load(const char *name, uint32_t *len); /* NULL if absent */+/* a file of len bytes to write in place (the calculator's storage is RAM): plat_reserve gives its+ * bytes, plat_reserved says they are written; NULL if there is no room */+uint8_t *plat_reserve(const char *name, uint32_t len);+void plat_reserved(const char *name, uint32_t len);+bool plat_remove(const char *name);+void plat_begin(void);+int plat_end(void);+/* an N0110 or N0115 (216 MHz, the N0120 has 550) */+bool plat_slow(void);+#endifdiff --git a/games/fnaf/src/plat_eadk.c b/games/fnaf/src/plat_eadk.cnew file mode 100644index 00000000..d94b80d6--- /dev/null+++ b/games/fnaf/src/plat_eadk.c@@ -0,0 +1,43 @@+/* The calculator: EADK display, keyboard, time and files. */+#include <eadk.h>+#include "../../common/epsilon_app.h"+#include "../../common/epsilon_files.h"+#include "plat.h"++#define KEY(k) ((uint64_t)1 << (k))++uint32_t plat_keys(void) {+ static const uint8_t digits[10] = {eadk_key_zero, eadk_key_one, eadk_key_two, eadk_key_three, eadk_key_four,+ eadk_key_five, eadk_key_six, eadk_key_seven, eadk_key_eight, eadk_key_nine};+ uint64_t k = eadk_keyboard_scan();+ uint32_t r = 0;+ if (k & KEY(eadk_key_left)) r |= K_LEFT;+ if (k & KEY(eadk_key_right)) r |= K_RIGHT;+ if (k & KEY(eadk_key_up)) r |= K_UP;+ if (k & KEY(eadk_key_down)) r |= K_DOWN;+ if (k & (KEY(eadk_key_ok) | KEY(eadk_key_exe))) r |= K_OK;+ if (k & KEY(eadk_key_back)) r |= K_BACK;+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) r |= K_HOME;+ if (k & KEY(eadk_key_backspace)) r |= K_DEL;+ for (int i = 0; i < 10; i++)+ if (k & KEY(digits[i])) r |= K_DIGIT(i);+ if (k) r |= K_ANY;+ return r;+}++uint32_t plat_millis(void) { return (uint32_t)eadk_timing_millis(); }+void plat_sleep(uint32_t ms) { eadk_timing_msleep(ms); }+void plat_push(int x, int y, int w, int h, const uint16_t *px) {+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);+}+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); }+uint8_t *plat_reserve(const char *name, uint32_t len) {+ uint32_t n;+ return ef_write(name, NULL, len) ? (uint8_t *)(uintptr_t)ef_read(name, &n) : NULL; /* (the storage is RAM) */+}+void plat_reserved(const char *name, uint32_t len) { (void)name, (void)len; }+bool plat_remove(const char *name) { return ef_remove(name); }+void plat_begin(void) { np_app_begin(); }+int plat_end(void) { return np_app_end(); }+bool plat_slow(void) { return epsilon_slow_model(); }diff --git a/games/fnaf/src/plat_host.c b/games/fnaf/src/plat_host.cnew file mode 100644index 00000000..f3f5a8c5--- /dev/null+++ b/games/fnaf/src/plat_host.c@@ -0,0 +1,71 @@+/* A computer: the screen goes to a frame buffer that tests save as images,+ * keys come from a script, time is simulated. */+#include <stdio.h>+#include <stdlib.h>+#include "plat.h"++uint16_t host_fb[SCREEN_W * SCREEN_H];+uint32_t host_time; /* ms */+uint32_t host_keys;++uint32_t plat_keys(void) { return host_keys; }+uint32_t plat_millis(void) { return host_time; }+void plat_sleep(uint32_t ms) { host_time += ms; }+void plat_push(int x, int y, int w, int h, const uint16_t *px) {+ for (int r = 0; r < h; r++)+ for (int c = 0; c < w; c++)+ if ((unsigned)(x + c) < SCREEN_W && (unsigned)(y + r) < SCREEN_H) host_fb[(y + r) * SCREEN_W + x + c] = px[r * w + c];+}++static char save_dir[256] = "build/host-saves";+void host_save_dir(const char *d) { snprintf(save_dir, sizeof save_dir, "%s", d); }+bool plat_save(const char *name, const void *data, uint32_t len) {+ char p[512];+ snprintf(p, sizeof p, "%s/%s", save_dir, name);+ FILE *f = fopen(p, "wb");+ if (!f) return false;+ bool ok = fwrite(data, 1, len, f) == len;+ fclose(f);+ return ok;+}+/* (each file read gets its own buffer: callers may hold two at once) */+static uint8_t loaded[4][1 << 16];+static int next_load;+const uint8_t *plat_load(const char *name, uint32_t *len) {+ char p[512];+ snprintf(p, sizeof p, "%s/%s", save_dir, name);+ FILE *f = fopen(p, "rb");+ if (!f) return NULL;+ uint8_t *b = loaded[next_load++ & 3];+ *len = (uint32_t)fread(b, 1, sizeof loaded[0], f);+ fclose(f);+ return b;+}+static uint8_t reserved[1 << 16];+bool host_storage_full; /* tests: no room for any file */+uint8_t *plat_reserve(const char *name, uint32_t len) {+ (void)name;+ return len <= sizeof reserved && !host_storage_full ? reserved : NULL;+}+void plat_reserved(const char *name, uint32_t len) { plat_save(name, reserved, len); }+bool plat_remove(const char *name) {+ char p[512];+ snprintf(p, sizeof p, "%s/%s", save_dir, name);+ return remove(p) == 0;+}+void plat_begin(void) {}+int plat_end(void) { return 0; }+bool plat_slow(void) { return false; }++/* writes the screen as a PPM image */+void host_shot(const char *path) {+ FILE *f = fopen(path, "wb");+ if (!f) return;+ fprintf(f, "P6\n%d %d\n255\n", SCREEN_W, SCREEN_H);+ for (int i = 0; i < SCREEN_W * SCREEN_H; i++) {+ uint16_t c = host_fb[i];+ uint8_t rgb[3] = {(uint8_t)((c >> 11) * 255 / 31), (uint8_t)(((c >> 5) & 63) * 255 / 63), (uint8_t)((c & 31) * 255 / 31)};+ fwrite(rgb, 1, 3, f);+ }+ fclose(f);+}diff --git a/games/fnaf/src/res.h b/games/fnaf/src/res.hnew file mode 100644index 00000000..800c7c40--- /dev/null+++ b/games/fnaf/src/res.h@@ -0,0 +1,15 @@+/* Five Nights at Freddy's: data.bin (tools/pack.py), read where it lies in flash. */+#ifndef FNAF_RES_H+#define FNAF_RES_H+#include <stdint.h>+#include "data.h"++extern const uint8_t *fnaf_bin;++/* (byte by byte: the data is not always aligned) */+static inline uint32_t rd16(const uint8_t *p) { return (uint32_t)(p[0] | p[1] << 8); }+static inline int32_t rds16(const uint8_t *p) { return (int16_t)(p[0] | p[1] << 8); }+static inline uint32_t rd24(const uint8_t *p) { return (uint32_t)(p[0] | p[1] << 8 | p[2] << 16); }+static inline uint32_t rd32(const uint8_t *p) { return (uint32_t)(p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24); }+static inline const uint8_t *section(int s) { return fnaf_bin + rd32(fnaf_bin + 8 + 4 * s); }+#endifdiff --git a/games/fnaf/src/save.c b/games/fnaf/src/save.cnew file mode 100644index 00000000..62bc04b5--- /dev/null+++ b/games/fnaf/src/save.c@@ -0,0 +1,163 @@+/* Saves: the progress (fnaf.sav: the night reached, the stars), the night as it was when Home quit+ * (fnafres.sav, read once on the next start), and a copy of both in a Python script: installing apps from the+ * NumWorks website keeps only Python scripts, so the saves come back from it when the files themselves are+ * gone. Each is a comment line "#>name:base64" (the way NumPlay and its big games keep theirs). */+#include <string.h>+#include "game.h"+#include "plat.h"++#define SAVE_NAME "fnaf.sav"+#define RESUME_NAME "fnafres.sav"+#define COPY_NAME "fnaf_saves.py"+#define MAGIC 0x46414E46u /* "FNAF" */+#define VERSION 1++typedef struct {+ uint32_t magic;+ uint8_t version, reached, stars, keys_seen;+ int8_t custom[4]; /* the custom night's last levels */+} Progress;++typedef struct {+ uint32_t magic;+ uint32_t size;+ Night n;+} Resume;++static const char *const kept[] = {SAVE_NAME, RESUME_NAME};+#define NKEPT (int)(sizeof kept / sizeof kept[0])+static const char copy_head[] =+ "# Five Nights at Freddy's keeps a copy of your nights\n"+ "# and stars here, so that reinstalling it doesn't erase\n"+ "# them. If you delete this file, the game writes it again.\n";+static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";++static void copy_write(void) {+ uint32_t total = 1 + (sizeof copy_head - 1) + 1, len;+ int n = 0;+ for (int k = 0; k < NKEPT; k++)+ if (plat_load(kept[k], &len) && len) total += 2 + (uint32_t)strlen(kept[k]) + 1 + (len + 2) / 3 * 4 + 1, n++;+ plat_remove(COPY_NAME);+ if (!n) return;+ uint8_t *o = plat_reserve(COPY_NAME, total), *p = o;+ if (!o) return;+ *p++ = 0; /* (the script's status byte: not imported) */+ memcpy(p, copy_head, sizeof copy_head - 1), p += sizeof copy_head - 1;+ for (int k = 0; k < NKEPT; k++) {+ const uint8_t *d = plat_load(kept[k], &len);+ if (!d || !len) continue;+ uint32_t nl = (uint32_t)strlen(kept[k]);+ *p++ = '#', *p++ = '>';+ memcpy(p, kept[k], nl), p += nl;+ *p++ = ':';+ for (uint32_t i = 0; i < len; i += 3, p += 4) {+ /* (written out: GCC 15.2 for the calculator got a loop over the four wrong, see NumPlay's+ * launcher/src/storage.c) */+ uint32_t left = len - i, v = (uint32_t)d[i] << 16 | (left > 1 ? d[i + 1] << 8 : 0) | (left > 2 ? d[i + 2] : 0);+ p[0] = (uint8_t)b64[v >> 18 & 63];+ p[1] = (uint8_t)b64[v >> 12 & 63];+ p[2] = left > 1 ? (uint8_t)b64[v >> 6 & 63] : '=';+ p[3] = left > 2 ? (uint8_t)b64[v & 63] : '=';+ }+ *p++ = '\n';+ }+ *p++ = 0;+ plat_reserved(COPY_NAME, (uint32_t)(p - o));+}++static int b64_value(uint8_t c) {+ for (int i = 0; i < 64; i++)+ if ((uint8_t)b64[i] == c) return i;+ return -1;+}++static const uint8_t *copy_line(int k, uint32_t *len) {+ uint32_t n, nl = (uint32_t)strlen(kept[k]);+ const uint8_t *c = plat_load(COPY_NAME, &n);+ if (!c) return NULL;+ for (uint32_t i = 0; i + nl + 3 <= n; i++)+ if (c[i] == '#' && c[i + 1] == '>' && !memcmp(c + i + 2, kept[k], nl) && c[i + 2 + nl] == ':') {+ const uint8_t *l = c + i + 3 + nl;+ uint32_t m = 0;+ while (l + m < c + n && l[m] != '\n' && l[m]) m++;+ *len = m;+ return l;+ }+ return NULL;+}++void save_restore_copy(void) {+ for (int k = 0; k < NKEPT; k++) {+ uint32_t have, len;+ if (plat_load(kept[k], &have)) continue;+ const uint8_t *l = copy_line(k, &len);+ if (!l || !len || len % 4) continue;+ uint32_t size = len / 4 * 3 - (l[len - 1] == '=') - (l[len - 2] == '=');+ uint8_t *out = plat_reserve(kept[k], size);+ if (!out) continue;+ l = copy_line(k, &len);+ bool ok = l != NULL && len / 4 * 3 - (l[len - 1] == '=') - (l[len - 2] == '=') == size;+ uint32_t o = 0;+ for (uint32_t i = 0; ok && i < len; i += 4) {+ int v0 = l[i] == '=' ? 0 : b64_value(l[i]), v1 = l[i + 1] == '=' ? 0 : b64_value(l[i + 1]);+ int v2 = l[i + 2] == '=' ? 0 : b64_value(l[i + 2]), v3 = l[i + 3] == '=' ? 0 : b64_value(l[i + 3]);+ if (v0 < 0 || v1 < 0 || v2 < 0 || v3 < 0) ok = false;+ uint32_t wd = (uint32_t)(v0 << 18 | v1 << 12 | v2 << 6 | v3);+ if (o < size) out[o++] = (uint8_t)(wd >> 16);+ if (o < size) out[o++] = (uint8_t)(wd >> 8);+ if (o < size) out[o++] = (uint8_t)wd;+ }+ if (ok && o == size) plat_reserved(kept[k], size);+ else plat_remove(kept[k]);+ }+}++void save_progress(void) {+ Progress p;+ memset(&p, 0, sizeof p);+ p.magic = MAGIC, p.version = VERSION;+ p.reached = g.reached, p.stars = g.stars, p.keys_seen = g.keys_seen;+ memcpy(p.custom, g.custom, sizeof p.custom);+ plat_save(SAVE_NAME, &p, sizeof p);+ copy_write();+}++void save_load(void) {+ uint32_t len;+ const uint8_t *d = plat_load(SAVE_NAME, &len);+ g.reached = 1;+ if (!d || len != sizeof(Progress)) return;+ Progress p;+ memcpy(&p, d, sizeof p);+ if (p.magic != MAGIC || p.version != VERSION) return;+ g.reached = p.reached >= 1 && p.reached <= 5 ? p.reached : 1;+ g.stars = p.stars & 7;+ g.keys_seen = p.keys_seen;+ for (int k = 0; k < 4; k++) g.custom[k] = p.custom[k] >= 0 && p.custom[k] <= 20 ? p.custom[k] : 0;+}++void save_resume(void) {+ Resume r;+ memset(&r, 0, sizeof r);+ r.magic = MAGIC, r.size = sizeof(Night), r.n = g.n;+ plat_save(RESUME_NAME, &r, sizeof r);+ copy_write();+}++bool save_resume_load(void) {+ uint32_t len;+ const uint8_t *d = plat_load(RESUME_NAME, &len);+ if (!d) return false;+ bool ok = false;+ if (len == sizeof(Resume)) {+ Resume r;+ memcpy(&r, d, sizeof r);+ if (r.magic == MAGIC && r.size == sizeof(Night) && r.n.night >= 1 && r.n.night <= 7) {+ g.n = r.n;+ ok = true;+ }+ }+ plat_remove(RESUME_NAME);+ copy_write();+ return ok;+}diff --git a/games/fnaf/src/view.c b/games/fnaf/src/view.cnew file mode 100644index 00000000..4726581b--- /dev/null+++ b/games/fnaf/src/view.c@@ -0,0 +1,299 @@+/* Drawing a night: the office (turning, its lights, doors, buttons and fan), the monitor and its cameras+ * (the feed's slow turn, its static, the map), and around them the clock, the power, the call's subtitles+ * and the captions of what can be heard. */+#include <stddef.h>+#include "game.h"+#include "gfx.h"+#include "res.h"++#define N g.n+#define GREY RGB(0xB8B8B8)++/* chosen once a frame (the bands of a frame must agree) */+static struct {+ bool light_off; /* the door light flickers */+ bool hall_lit; /* 2A's light flickers on */+ int fan;+ int halluc; /* 0, or what flashes: 1 Golden Freddy, 2 the endoskeleton, 3 IT'S ME */+ int freddy_face; /* in the dark */+ int noise, shake;+ uint32_t seed;+} f;++static void prepare(void) {+ f.light_off = rnd() % 10 <= 1;+ f.hall_lit = rnd() % 10 < 3;+ f.fan = (int)(N.t * 30) % 3;+ f.halluc = N.halluc > 0 && rnd() % 10 == 0 ? 1 + (int)(rnd() % 3) : 0;+ f.freddy_face = rnd() % 4 == 0;+ f.noise = 4 + (int)(rnd() % 4) + (rnd() % 16 == 0 ? 6 : 0);+ f.shake = (int)(rnd() % 7) - 3;+ f.seed = rnd();+}++/* ------------------------------------------------------------------ text helpers */+static void small_digits(int font, int x, int y, int v, uint16_t c) {+ char s[4];+ int n = 0;+ if (v >= 100) s[n++] = (char)('0' + v / 100);+ if (v >= 10) s[n++] = (char)('0' + v / 10 % 10);+ s[n++] = (char)('0' + v % 10);+ s[n] = 0;+ gfx_text(font, x, y, s, c);+}++/* a 3 x 5 font for the map's buttons: 1 to 7, A, B, C */+static const uint16_t tiny[10] = {0x2C97, 0x73E7, 0x73CF, 0x5BC9, 0x79CF, 0x79EF, 0x7249, 0x2BED, 0x6BAE, 0x3923};+static void tiny_text(int x, int y, const char *s, uint16_t c) {+ for (; *s; s++, x += 4) {+ int k = *s >= '1' && *s <= '7' ? *s - '1' : *s - 'A' + 7;+ uint16_t b = tiny[k];+ for (int r = 0; r < 5; r++)+ for (int col = 0; col < 3; col++)+ if (b >> (14 - r * 3 - col) & 1) gfx_fill(x + col, y + r, 1, 1, c);+ }+}++/* wraps s to lines of at most w pixels: the start and length of line k, false past the last */+static bool wrap(int font, const char *s, int w, int k, const char **start, int *len) {+ for (;;) {+ while (*s == ' ') s++;+ if (!*s) return false;+ int n = 0, last_space = -1;+ while (s[n] && gfx_text_wn(font, s, n + 1) <= w) {+ if (s[n] == ' ') last_space = n;+ n++;+ }+ if (s[n] && last_space > 0) n = last_space;+ if (!k--) {+ *start = s, *len = n;+ return true;+ }+ s += n;+ }+}++/* ------------------------------------------------------------------ around the view */+static void clock_and_night(void) {+ int h = N.hour ? N.hour : 12;+ int w = gfx_text_w(FONT_BIG, " AM") + gfx_text_w(FONT_CLOCK, h >= 10 ? "12" : "1");+ int x = 310 - w;+ x += gfx_text(FONT_CLOCK, x, 6, h >= 10 ? (h == 12 ? "12" : "10") : (char[]){(char)('0' + h), 0}, WHITE);+ gfx_text(FONT_BIG, x, 8, " AM", WHITE);+ int nx = 310 - gfx_text_w(FONT_HUD, "Night ") - gfx_text_w(FONT_PIXEL, "0");+ nx += gfx_text(FONT_HUD, nx, 31, "Night ", WHITE);+ small_digits(FONT_PIXEL, nx, 30, N.night, WHITE);+}++static void power_hud(void) {+ int x = 8 + gfx_text(FONT_HUD, 8, 206, "Power left: ", WHITE);+ int p = N.power / 10;+ small_digits(FONT_PIXEL, x, 205, p, WHITE);+ gfx_text(FONT_HUD, x + gfx_text_w(FONT_PIXEL, p >= 10 ? "00" : "0") + 1, 206, "%", WHITE);+ x = 8 + gfx_text(FONT_HUD, 8, 222, "Usage: ", WHITE);+ static const uint32_t bars[5] = {0x00C000, 0x00C000, 0xE6E600, 0xE00000, 0xE00000};+ for (int i = 0; i < N.usage && i < 5; i++) {+ gfx_fill(x + 9 * i, 222, 7, 12, RGB(bars[i]));+ gfx_fill(x + 9 * i + 1, 223, 5, 2, gfx_mix(WHITE, RGB(bars[i]), 12));+ }+}++static void call_hud(void) {+ if (N.night > 5 || N.call_muted || N.t >= call_end(N.night)) return;+ if (N.t > 3) {+ gfx_blend(6, 6, 74, 15, RGB(0x202020), 22);+ gfx_frame_rect(6, 6, 74, 15, GREY);+ gfx_text(FONT_HUD, 12, 8, "MUTE CALL", WHITE);+ gfx_text(FONT_TEXT, 84, 8, "0", RGB(0x909090));+ }+ const char *s = call_line(N.night, N.t);+ if (!s) return;+ const char *line;+ int len, n = 0;+ while (n < 3 && wrap(FONT_TEXT, s, 300, n, &line, &len)) n++;+ int y = 52;+ gfx_blend(4, y - 2, 312, 14 * n + 4, BLACK, 18);+ for (int k = 0; k < n; k++) {+ wrap(FONT_TEXT, s, 300, k, &line, &len);+ int w = gfx_text_wn(FONT_TEXT, line, len);+ gfx_text_n(FONT_TEXT, 160 - w / 2 + 1, y + 14 * k + 1, line, len, BLACK);+ gfx_text_n(FONT_TEXT, 160 - w / 2, y + 14 * k, line, len, RGB(0xF2F2C8));+ }+}++void view_captions(void) {+ int y = 186;+ for (int i = 3; i >= 0; i--) {+ if (!g.cap[i] || g.cap_t[i] <= 0) continue;+ int a = g.cap_t[i] > 0.5f ? 32 : (int)(g.cap_t[i] * 64);+ gfx_text(FONT_TEXT, 9, y + 1, g.cap[i], BLACK);+ gfx_text(FONT_TEXT, 8, y, g.cap[i], gfx_mix(RGB(0xD8E8FF), BLACK, a));+ y -= 13;+ }+}++/* the bar at the bottom to bring the monitor up or down */+static void flip_bar(void) {+ gfx_blend(118, 229, 84, 9, WHITE, 6);+ gfx_frame_rect(118, 229, 84, 9, gfx_mix(WHITE, BLACK, 14));+ for (int k = 0; k < 2; k++)+ for (int i = 0; i < 4; i++) {+ gfx_fill(152 + 9 * k + i, 235 - i, 1, 1, WHITE);+ gfx_fill(152 + 9 * k + 7 - i, 235 - i, 1, 1, WHITE);+ }+}++/* ------------------------------------------------------------------ the office */+static void office(void) {+ int px = (int)N.pan;+ if (N.dark) {+ if (N.dark == 3 && (N.dark_t > 0.35f || (int)(N.dark_t * 30) & 1)) {+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);+ return;+ }+ pic_part(N.dark == 2 && f.freddy_face ? PIC_DARK_FREDDY : PIC_DARK, 0, 0, px, 0, SCREEN_W, SCREEN_H);+ return;+ }+ int base = PIC_OFFICE;+ if (N.light == 1 + LEFT && !f.light_off) base = N.pos[BONNIE] == AT_DOOR ? PIC_OFFICE_LLB : PIC_OFFICE_LL;+ if (N.light == 1 + RIGHT && !f.light_off) base = N.pos[CHICA] == AT_DOOR ? PIC_OFFICE_RLC : PIC_OFFICE_RL;+ pic_part(base, 0, 0, px, 0, SCREEN_W, SCREEN_H);+ pic_draw(PIC_FAN0 + f.fan, FAN_X - px, FAN_Y);+ pic_part(PIC_PANEL_L0 + (N.door[LEFT] | (N.light == 1 + LEFT) << 1), PANEL_L_X - px, PANEL_Y, 0, 0, 26, 80);+ pic_draw(PIC_PANEL_R0 + (N.door[RIGHT] | (N.light == 1 + RIGHT) << 1), PANEL_R_X - px, PANEL_Y);+ static const int doors[2][4] = {{PIC_DOOR_L, DOOR_L_X, DOOR_L_W, DOOR_L_H}, {PIC_DOOR_R, DOOR_R_X, DOOR_R_W, DOOR_R_H}};+ for (int s = 0; s < 2; s++) {+ int vis = (int)(N.door_anim[s] * doors[s][3] + 0.5f);+ if (vis > 0) pic_part(doors[s][0], doors[s][1] - px, 0, 0, doors[s][3] - vis, doors[s][2], vis);+ }+ if (N.gold == 3) pic_part(PIC_OFFICE_GOLD, GOLD_X - px, GOLD_Y, 0, 0, GOLD_W, GOLD_H);+}++/* ------------------------------------------------------------------ the cameras */+static const char *const cam_names[CAM_COUNT] = {"Show Stage", "Dining Area", "Pirate Cove", "West Hall",+ "W. Hall Corner", "Supply Closet", "East Hall", "E. Hall Corner",+ "Backstage", "Kitchen", "Restrooms"};+static const char *const cam_labels[CAM_COUNT] = {"1A", "1B", "1C", "2A", "2B", "3", "4A", "4B", "5", "6", "7"};++static bool here(int who, int cam) { return N.pos[who] == cam; }++static int cam_picture(void) {+ bool b = here(BONNIE, N.cam), c = here(CHICA, N.cam), fr = here(FREDDY, N.cam);+ switch (N.cam) {+ case CAM_1A:+ if (!fr) return PIC_CAM1A_EMPTY;+ return b && c ? PIC_CAM1A_BCF : b ? PIC_CAM1A_BF : c ? PIC_CAM1A_CF : PIC_CAM1A_F;+ case CAM_1B: return PIC_CAM1B_EMPTY + (b && c && fr ? 7 : b && c ? 4 : b && fr ? 5 : c && fr ? 6 : b ? 1 : c ? 2 : fr ? 3 : 0);+ case CAM_1C: return PIC_CAM1C_0 + (N.foxy < 3 ? N.foxy : 3);+ case CAM_2A: return !f.hall_lit ? PIC_CAM2A_DARK : b ? PIC_CAM2A_B : PIC_CAM2A_EMPTY;+ case CAM_2B: return (N.gold == 1 || N.gold == 2) && !b ? PIC_CAM2B_GOLD : b ? PIC_CAM2B_B : PIC_CAM2B_EMPTY;+ case CAM_3: return b ? PIC_CAM3_B : PIC_CAM3_EMPTY;+ case CAM_4A: return c && fr ? PIC_CAM4A_CF : c ? PIC_CAM4A_C : fr ? PIC_CAM4A_F : PIC_CAM4A_EMPTY;+ case CAM_4B: return c ? PIC_CAM4B_C : fr ? PIC_CAM4B_F : PIC_CAM4B_EMPTY;+ case CAM_5: return b ? PIC_CAM5_B : PIC_CAM5_EMPTY;+ case CAM_7: return c && fr ? PIC_CAM7_CF : c ? PIC_CAM7_C : fr ? PIC_CAM7_F : PIC_CAM7_EMPTY;+ }+ return -1;+}++static void camera_map(void) {+ const uint8_t *m = section(SEC_MAP);+ int size = (int)rd16(m), stride = (size + 7) >> 3;+ int mx = SCREEN_W - size - 4, my = SCREEN_H - size - 12;+ for (int r = 0; r < size; r++) {+ int y = my + r;+ if (y < gfx_y0 || y >= gfx_y0 + BAND_H) continue;+ const uint8_t *row = m + 4 + r * stride;+ uint16_t *d = gfx_band + (y - gfx_y0) * SCREEN_W + mx;+ for (int c = 0; c < size; c++)+ if (row[c >> 3] >> (c & 7) & 1) d[c] = WHITE;+ }+ const uint8_t *centres = m + 4 + size * stride;+ bool blink = (int)(g.t * 3) & 1 ? false : true;+ for (int k = 0; k < CAM_COUNT; k++) {+ int cx = mx + (int)rd16(centres + 4 * k), cy = my + (int)rd16(centres + 4 * k + 2);+ bool sel = k == N.cam;+ gfx_fill(cx - 8, cy - 5, 17, 11, sel && blink ? RGB(0x8BC34A) : RGB(0x424242));+ gfx_frame_rect(cx - 8, cy - 5, 17, 11, RGB(0xD0D0D0));+ tiny_text(cx - (cam_labels[k][1] ? 3 : 1), cy - 2, cam_labels[k], WHITE);+ }+ gfx_text(FONT_HUD, mx - 2, my - 18, cam_names[N.cam], WHITE);+}++static void cameras(void) {+ float c = N.cam_t; /* 5 seconds there, 2 still, 5 back, 2 still */+ float a = c < 5 ? c / 5 : c < 7 ? 1 : c < 12 ? 1 - (c - 7) / 5 : 0;+ int px = (int)(a * CAM_PAN);+ if (N.glitch > 0) {+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);+ gfx_static(0, gfx_y0, SCREEN_W, BAND_H, 16, f.seed);+ } else if (N.cam == CAM_6) {+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);+ gfx_static(0, gfx_y0, SCREEN_W, BAND_H, 7, f.seed);+ gfx_text_c(FONT_BIG, 100, 64, "CAMERA DISABLED", WHITE);+ gfx_text_c(FONT_BIG, 100, 86, "-AUDIO ONLY-", WHITE);+ } else if (N.cam == CAM_2A && N.foxy_run >= 0 && N.foxy_run < 35) {+ pic_draw(PIC_FOXYRUN0 + (int)(N.foxy_run / 35 * FOXYRUN_N), 0, 0);+ gfx_static(0, gfx_y0, SCREEN_W, BAND_H, f.noise, f.seed);+ } else {+ pic_part(cam_picture(), 0, 0, px, 0, SCREEN_W, SCREEN_H);+ gfx_static(0, gfx_y0, SCREEN_W, BAND_H, f.noise, f.seed);+ }+ if (g.blip > 0) gfx_blend(0, gfx_y0, SCREEN_W, BAND_H, WHITE, (int)(g.blip * 120));+ gfx_frame_rect(5, 5, 310, 230, gfx_mix(WHITE, BLACK, 20));+ if ((int)(g.t * 1.5f) & 1) { /* the recording dot */+ static const uint8_t dot[7] = {2, 1, 0, 0, 0, 1, 2};+ for (int r = 0; r < 7; r++) gfx_fill(14 + dot[r], 26 + r, 7 - 2 * dot[r], 1, RGB(0xE02020));+ }+ camera_map();+}++/* ------------------------------------------------------------------ the night */+static void hallucination(void) {+ if (!f.halluc) return;+ if (f.halluc == 1) pic_draw(PIC_GOLDEN, 0, 0);+ else if (f.halluc == 2) pic_draw(PIC_TITLE3, 0, 0);+ else {+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);+ gfx_text_c(FONT_HUGE, 160, 104, "IT'S ME", WHITE);+ }+}++static void night_draw(void) {+ bool cams = N.flip >= 1 && !N.dark;+ if (cams) cameras();+ else {+ office();+ if (N.flip > 0) { /* the monitor coming up, or down */+ int k = (int)(N.flip * FLIP_N);+ pic_draw(PIC_FLIP0 + (k < FLIP_N ? k : FLIP_N - 1), 0, 0);+ }+ }+ hallucination();+ if (!N.dark) {+ clock_and_night();+ power_hud();+ call_hud();+ if (!cams || N.flip >= 1) flip_bar();+ }+ view_captions();+}++void view_night(void) {+ if (gfx_y0 == 0) prepare();+ night_draw();+}++/* ------------------------------------------------------------------ jumpscares */+void view_scare(void) {+ static const int first[5] = {PIC_BONNIE0, PIC_CHICA0, PIC_FREDDY0, PIC_FOXY0, PIC_POWEROUT0};+ static const int count[5] = {BONNIE_N, CHICA_N, FREDDY_N, FOXY_N, POWEROUT_N};+ static const float fps[5] = {30, 30, 25, 25, 30};+ static const bool loops[5] = {true, true, false, false, false};+ if (gfx_y0 == 0) prepare();+ int w = g.scare, k = (int)(g.scare_t * fps[w]);+ k = loops[w] ? k % count[w] : k < count[w] ? k : count[w] - 1;+ int dx = g.scare_t > 0.1f ? f.shake : 0;+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);+ pic_draw(first[w] + k, dx, 0);+}diff --git a/games/fnaf/tests/pics.c b/games/fnaf/tests/pics.cnew file mode 100644index 00000000..6a81cb79--- /dev/null+++ b/games/fnaf/tests/pics.c@@ -0,0 +1,30 @@+/* Draws every picture of data.bin on a computer (build/pics/<id>.ppm), to check the codec:+ * tests/check.py compares them with what tools/pack.py was given. */+#include <stdio.h>+#include "../src/gfx.h"+#include "../src/res.h"++extern const uint8_t fnaf_data[];+const uint8_t *fnaf_bin;+void host_shot(const char *path);++static int cur, offx;+static void draw(void) {+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);+ pic_draw(cur, -offx, 0);+}++int main(int argc, char **argv) {+ static uint16_t band[SCREEN_W * BAND_H];+ gfx_set_band_memory(band);+ fnaf_bin = fnaf_data;+ const char *dir = argc > 1 ? argv[1] : "build/pics";+ for (cur = 0; cur < PIC_COUNT; cur++)+ for (offx = 0; offx < pic_w(cur); offx += SCREEN_W) {+ gfx_frame(draw);+ char path[256];+ snprintf(path, sizeof path, "%s/%d_%d.ppm", dir, cur, offx);+ host_shot(path);+ }+ return 0;+}diff --git a/games/fnaf/tests/play.c b/games/fnaf/tests/play.cnew file mode 100644index 00000000..21f43163--- /dev/null+++ b/games/fnaf/tests/play.c@@ -0,0 +1,162 @@+/* Plays Five Nights at Freddy's on a computer, with scripted keys (or a player of its own), and saves frames.+ *+ * play [--frames N] [--keys "10-40:left,50:ok,..."] [--shots 30,60|all|every:N] [--out DIR] [--saves DIR]+ * [--night N] [--ai F,B,C,X] [--power P] [--hour H] [--seed S] [--bot] [--resume]+ *+ * Keys: left right up down ok back home del 0 to 9. "a-b:key" holds the key from frame (step) a to b, "a:key" for+ * one step. --night starts that night (its card first); --ai, --power and --hour then set its AI levels, power+ * and hour. --bot plays the night itself (it knows where everyone is): doors when someone is at them, a look+ * at Pirate Cove now and then. Frames are steps (60 a second); the screen is drawn every second step.+ * Screenshots are DIR/shot_<frame>.ppm. At the end it prints the state: "END scene ... night ... hour ...". */+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include "../src/game.h"+#include "../src/gfx.h"+#include "../src/res.h"++extern uint32_t host_keys, host_time;+extern uint16_t host_fb[SCREEN_W * SCREEN_H];+void host_shot(const char *path);+void host_save_dir(const char *d);+extern const uint8_t fnaf_data[];+const uint8_t *fnaf_bin;++typedef struct { int a, b; uint32_t k; } Hold;+static Hold holds[4096];+static int nholds;++static uint32_t key_of(const char *s) {+ static const struct { const char *n; uint32_t k; } names[] = {+ {"left", K_LEFT}, {"right", K_RIGHT}, {"up", K_UP}, {"down", K_DOWN}, {"ok", K_OK}, {"back", K_BACK},+ {"home", K_HOME}, {"del", K_DEL}};+ for (unsigned i = 0; i < sizeof names / sizeof names[0]; i++)+ if (!strcmp(s, names[i].n)) return names[i].k;+ if (s[0] >= '0' && s[0] <= '9' && !s[1]) return K_DIGIT(s[0] - '0');+ fprintf(stderr, "unknown key %s\n", s);+ exit(2);+}++static void parse_keys(char *s) {+ for (char *t = strtok(s, ","); t; t = strtok(NULL, ",")) {+ char *colon = strchr(t, ':');+ if (!colon) continue;+ *colon = 0;+ int a = atoi(t), b = a;+ char *dash = strchr(t, '-');+ if (dash) b = atoi(dash + 1);+ holds[nholds++] = (Hold){a, b, key_of(colon + 1)};+ }+}++/* ------------------------------------------------------------------ a player */+static uint32_t bot(int f) {+ Night *n = &g.n;+ if (g.scene != SC_NIGHT || g.paused) return 0;+ uint32_t k = 0;+ static int next_look, look_until;+ bool up = n->flip >= 1;+ bool bonnie = n->pos[BONNIE] == AT_DOOR, chica = n->pos[CHICA] == AT_DOOR;+ bool foxy = n->foxy >= 2, freddy = n->pos[FREDDY] == CAM_4B || n->pos[FREDDY] == CAM_4A;+ bool want_l = bonnie || foxy, want_r = chica || freddy;+ if (n->monitor) { /* on the cameras: look at Pirate Cove, then come down */+ if (up && n->cam != CAM_1C && !(f & 1)) return K_DIGIT(1);+ if (up && f >= look_until && !(f & 1)) return K_OK;+ return 0;+ }+ if (n->flip > 0 || (f & 1)) return 0;+ if (n->door[LEFT] != want_l) return K_DIGIT(7);+ if (n->door[RIGHT] != want_r) return K_DIGIT(9);+ if (f >= next_look && !n->dark) {+ next_look = f + 300 + (int)(rnd() % 400);+ look_until = f + 70;+ return K_OK;+ }+ return k;+}++int main(int argc, char **argv) {+ int frames = 600, night = 0, power = -1, hour = -1, ai[4] = {-1, -1, -1, -1};+ bool use_bot = false, all = false;+ int every = 0;+ const char *out = "build/shots", *saves = "build/host-saves";+ static int shots[4096];+ int nshots = 0;+ for (int i = 1; i < argc; i++) {+ const char *a = argv[i];+ if (!strcmp(a, "--frames")) frames = atoi(argv[++i]);+ else if (!strcmp(a, "--keys")) parse_keys(argv[++i]);+ else if (!strcmp(a, "--shots")) {+ char *s = argv[++i];+ if (!strcmp(s, "all")) all = true;+ else if (!strncmp(s, "every:", 6)) every = atoi(s + 6);+ else+ for (char *t = strtok(s, ","); t && nshots < 4096; t = strtok(NULL, ",")) shots[nshots++] = atoi(t);+ } else if (!strcmp(a, "--out")) out = argv[++i];+ else if (!strcmp(a, "--saves")) saves = argv[++i];+ else if (!strcmp(a, "--night")) night = atoi(argv[++i]);+ else if (!strcmp(a, "--power")) power = atoi(argv[++i]);+ else if (!strcmp(a, "--hour")) hour = atoi(argv[++i]);+ else if (!strcmp(a, "--ai")) sscanf(argv[++i], "%d,%d,%d,%d", &ai[0], &ai[1], &ai[2], &ai[3]);+ else if (!strcmp(a, "--seed")) {+ unsigned s = (unsigned)atoi(argv[++i]);+ for (unsigned k = 0; k < s % 1000; k++) rnd();+ } else if (!strcmp(a, "--bot")) use_bot = true;+ else {+ fprintf(stderr, "unknown argument %s\n", a);+ return 2;+ }+ }+ mkdir(out, 0755);+ mkdir(saves, 0755);+ host_save_dir(saves);+ static uint16_t band[SCREEN_W * BAND_H];+ gfx_set_band_memory(band);+ fnaf_bin = fnaf_data;+ host_time = 1000;+ game_init();+ if (night) {+ if (night == 7)+ for (int k = 0; k < 4; k++) g.custom[k] = (int8_t)(ai[k] >= 0 ? ai[k] : 0);+ start_night(night);+ }+ bool set = false;+ int f;+ for (f = 0; f < frames && g.running; f++) {+ if (!set && g.scene == SC_NIGHT) { /* the night's levels, power and hour, as asked */+ set = true;+ for (int k = 0; k < 4; k++)+ if (ai[k] >= 0) g.n.ai[k] = (int8_t)ai[k];+ if (power >= 0) g.n.power = (int16_t)power;+ if (hour >= 0) g.n.hour = (uint8_t)hour, g.n.t = hour * 89.0f + 1;+ }+ uint32_t k = 0;+ for (int i = 0; i < nholds; i++)+ if (f >= holds[i].a && f <= holds[i].b) k |= holds[i].k;+ if (use_bot && !k) k = bot(f);+ host_keys = k;+ int was = g.scene;+ game_step(k);+ if (g.scene != was && (g.scene == SC_SIX || g.scene == SC_SCARE || g.scene == SC_GOLDEN))+ printf("EVENT %s night %d hour %d power %d t %.1f who %d foxy_pounds %d\n",+ g.scene == SC_SIX ? "six" : g.scene == SC_SCARE ? "scare" : "golden", g.n.night, g.n.hour, g.n.power,+ g.n.t, g.scare, g.n.foxy_pounds);+ host_time += (f % 3 == 2) ? 17 : 16;+ bool shot = all || (every && f % every == 0);+ for (int i = 0; i < nshots; i++) shot |= shots[i] == f;+ if (g.running && (shot || !(f & 1))) {+ game_draw();+ if (shot) {+ char p[512];+ snprintf(p, sizeof p, "%s/shot_%05d.ppm", out, f);+ host_shot(p);+ }+ }+ }+ printf("END scene %d night %d hour %d power %d t %.1f frames %d running %d paused %d reached %d stars %d "+ "pos %d,%d,%d foxy %d gold %d dark %d\n",+ g.scene, g.n.night, g.n.hour, g.n.power, g.n.t, f, g.running, g.paused, g.reached, g.stars, g.n.pos[0],+ g.n.pos[1], g.n.pos[2], g.n.foxy, g.n.gold, g.n.dark);+ return 0;+}diff --git a/games/fnaf/tools/codec.py b/games/fnaf/tools/codec.pynew file mode 100644index 00000000..cd60b260--- /dev/null+++ b/games/fnaf/tools/codec.py@@ -0,0 +1,249 @@+"""Five Nights at Freddy's: the pictures' codec (src/pic.c decodes it).++The game's pictures are dark, grainy renders: what keeps them small is what JPEG does, so this is JPEG's+baseline coding without its file format. A picture is a grid of 16 x 16 squares (MCUs): YCbCr, the colours at+half resolution (4:2:0), each 8 x 8 block cosine-transformed, quantized and Huffman-coded (JPEG's run/size+symbols and tables, one set for the whole game). Every square stands alone, starting on a byte, with no DC+prediction from the one before it (only between the four Y blocks of a square), so the game decodes only the+squares on screen, and pictures share squares: a camera with Bonnie in it is the empty camera's squares but+where he stands, the frames of a jumpscare share what doesn't move, and squares that come out the same anywhere+are stored once."""+import heapq++import numpy as np++ZIGZAG = [0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7,+ 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46,+ 53, 60, 61, 54, 47, 55, 62, 63]+STD_LUMA = [16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56,+ 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92,+ 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99]+STD_CHROMA = [17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99,+ 47, 66, 99, 99, 99, 99, 99, 99] + [99] * 32+# libjpeg's "ifast" IDCT folds these scales into the quantization table (src/pic.c)+AANSCALES = [16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, 22725, 31521, 29692, 26722, 22725, 17855, 12299,+ 6270, 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906, 19266, 26722, 25172, 22654, 19266, 15137,+ 10426, 5315, 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, 12873, 17855, 16819, 15137, 12873,+ 10114, 6967, 3552, 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446, 4520, 6270, 5906, 5315, 4520,+ 3552, 2446, 1247]+LUT_BITS = 9+++def qtable(base, quality):+ s = 5000 / quality if quality < 50 else 200 - 2 * quality+ return np.array([min(255, max(1, int((b * s + 50) // 100))) for b in base], dtype=np.float64)+++def dct_matrix():+ c = np.zeros((8, 8))+ for k in range(8):+ for n in range(8):+ c[k, n] = (np.sqrt(1 / 8) if k == 0 else np.sqrt(2 / 8)) * np.cos((2 * n + 1) * k * np.pi / 16)+ return c+++DCT = dct_matrix()+++def ycbcr(rgb):+ """an H x W x 3 picture (0-255) -> Y (H x W), Cb and Cr (H/2 x W/2), all level-shifted (-128)"""+ r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]+ y = 0.299 * r + 0.587 * g + 0.114 * b - 128+ cb = -0.168736 * r - 0.331264 * g + 0.5 * b+ cr = 0.5 * r - 0.418688 * g - 0.081312 * b+ h, w = y.shape+ cb = cb.reshape(h // 2, 2, w // 2, 2).mean(axis=(1, 3))+ cr = cr.reshape(h // 2, 2, w // 2, 2).mean(axis=(1, 3))+ return y, cb, cr+++def blocks_of(plane):+ """an H x W plane -> (H/8, W/8, 8, 8) of its DCT coefficients"""+ h, w = plane.shape+ b = plane.reshape(h // 8, 8, w // 8, 8).transpose(0, 2, 1, 3)+ return np.einsum("ij,abjk,lk->abil", DCT, b, DCT)+++def quantize(coef, q, deadzone):+ """coefficients (..., 8, 8) / a natural-order table, rounded toward 0 a little (deadzone) on the AC ones"""+ x = coef / q.reshape(8, 8)+ r = np.sign(x) * np.floor(np.abs(x) + 0.5 - deadzone)+ r[..., 0, 0] = np.round(x[..., 0, 0])+ return np.maximum(r, 0 * r - 2047).clip(-2047, 2047).astype(np.int32)+++def size_of(v):+ v = abs(int(v))+ n = 0+ while v:+ n += 1+ v >>= 1+ return n+++def bits_of(v, n):+ return v if v >= 0 else v + (1 << n) - 1+++def block_symbols(zz, pred):+ """one block's coefficients in zigzag order -> [(table: 0 DC 1 AC, symbol, extra bits value, extra bits count)]"""+ out = []+ d = int(zz[0]) - pred+ s = size_of(d)+ out.append((0, s, bits_of(d, s), s))+ run = 0+ last = 63+ while last > 0 and zz[last] == 0:+ last -= 1+ for k in range(1, last + 1):+ v = int(zz[k])+ if v == 0:+ run += 1+ continue+ while run > 15:+ out.append((1, 0xF0, 0, 0))+ run -= 16+ s = size_of(v)+ out.append((1, run << 4 | s, bits_of(v, s), s))+ run = 0+ if last < 63:+ out.append((1, 0x00, 0, 0))+ return out+++def mcu_symbols(yq, cbq, crq):+ """the quantized blocks of one square: 4 Y (8 x 8 each, natural order), Cb, Cr -> [(component class, ...)]"""+ syms = []+ pred = 0+ for b in yq:+ zz = b.reshape(64)[ZIGZAG]+ syms += [(0,) + s for s in block_symbols(zz, pred)]+ pred = int(zz[0])+ for b in (cbq, crq):+ zz = b.reshape(64)[ZIGZAG]+ syms += [(1,) + s for s in block_symbols(zz, 0)]+ return syms+++def huffman_lengths(freq):+ """symbol -> frequency, to code lengths of at most 16 bits (JPEG's Annex K.2 and K.3)"""+ # a symbol of its own takes the all-ones code, which JPEG never uses (the padding is ones)+ f = {s: float(c) for s, c in freq.items() if c > 0}+ f[256] = 0.5+ syms = list(f)+ heap = [(f[s], i, [s]) for i, s in enumerate(syms)]+ heapq.heapify(heap)+ length = {s: 0 for s in syms}+ n = len(syms)+ while len(heap) > 1:+ f1, _, a = heapq.heappop(heap)+ f2, _, b = heapq.heappop(heap)+ for s in a + b:+ length[s] += 1+ n += 1+ heapq.heappush(heap, (f1 + f2, n, a + b))+ bits = [0] * 64+ for s in syms:+ bits[length[s]] += 1+ i = 63+ while i > 16:+ while bits[i] > 0:+ j = i - 2+ while bits[j] == 0:+ j -= 1+ bits[i] -= 2+ bits[i - 1] += 1+ bits[j + 1] += 2+ bits[j] -= 1+ i -= 1+ while bits[i] == 0:+ i -= 1+ bits[i] -= 1 # (the reserved code goes)+ order = sorted(syms, key=lambda s: (length[s], s == 256, s))[:-1]+ out = {}+ k = 0+ for ln in range(1, 17):+ for _ in range(bits[ln]):+ out[order[k]] = ln+ k += 1+ return out+++def canonical(lengths):+ """symbol -> length to (symbol -> (code, length), BITS[1..16], HUFFVAL)"""+ order = sorted(lengths, key=lambda s: (lengths[s], s))+ bits = [0] * 17+ for s in order:+ bits[lengths[s]] += 1+ codes = {}+ code = 0+ k = 0+ for ln in range(1, 17):+ for _ in range(bits[ln]):+ codes[order[k]] = (code, ln)+ code += 1+ k += 1+ code <<= 1+ return codes, bits[1:], order+++def decode_tables(bits, vals):+ """BITS and HUFFVAL -> the decoder's tables: a LUT_BITS lookup (length << 8 | symbol, 0 when longer), then+ for the slow way JPEG's maxcode (17 int32, -1 when none) and valoffset (17 int32), then HUFFVAL (256 bytes)"""+ lut = [0] * (1 << LUT_BITS)+ maxcode = [-1] * 18+ valoff = [0] * 18+ code = 0+ k = 0+ for ln in range(1, 17):+ n = bits[ln - 1]+ if n:+ valoff[ln] = k - code+ for _ in range(n):+ if ln <= LUT_BITS:+ base = code << (LUT_BITS - ln)+ for j in range(1 << (LUT_BITS - ln)):+ lut[base + j] = ln << 8 | vals[k]+ code += 1+ k += 1+ maxcode[ln] = code - 1+ code <<= 1+ maxcode[17] = 0x7FFFFFFF+ out = b"".join(v.to_bytes(2, "little") for v in lut)+ out += b"".join(v.to_bytes(4, "little", signed=True) for v in maxcode)+ out += b"".join(v.to_bytes(4, "little", signed=True) for v in valoff)+ out += bytes(vals) + bytes(256 - len(vals))+ return out+++class BitWriter:+ def __init__(self):+ self.out = bytearray()+ self.acc = 0+ self.n = 0++ def put(self, v, n):+ if n == 0:+ return+ self.acc = self.acc << n | (v & ((1 << n) - 1))+ self.n += n+ while self.n >= 8:+ self.n -= 8+ self.out.append(self.acc >> self.n & 0xFF)+ self.acc &= (1 << self.n) - 1++ def flush(self):+ """pads with ones (like JPEG) to a byte"""+ if self.n:+ self.put((1 << (8 - self.n)) - 1, 8 - self.n)+ return bytes(self.out)+++def encode_mcu(syms, tables):+ """a square's symbols -> its bytes; tables[component class][0 DC, 1 AC][symbol] = (code, length)"""+ w = BitWriter()+ for comp, tab, sym, val, n in syms:+ code, ln = tables[comp][tab][sym]+ w.put(code, ln)+ w.put(val, n)+ return w.flush()diff --git a/games/fnaf/tools/fetch.py b/games/fnaf/tools/fetch.pynew file mode 100644index 00000000..5df4a9cc--- /dev/null+++ b/games/fnaf/tools/fetch.py@@ -0,0 +1,35 @@+#!/usr/bin/env python3+"""Five Nights at Freddy's: gathers the public material tools/pack.py turns into src/data.bin.++ python3 tools/fetch.py REF (then: make data REF=REF)++The game's own pictures, as two fan ports keep them in their repositories, at the commits used:+- wellsousaaa's Five Nights at Freddy's Web (github.com/souwell/Five-Nights-at-Freddys-Web): the office and its+ lights, the cameras, the jumpscares, Foxy's run, the custom night's faces and the camera map;+- BaranMuzu's HX-NAF (github.com/BaranMuzu/HX-NAF): the title's faces, words and star, and the newspaper.+Both are cloned with git into REF."""+import os+import subprocess+import sys++SOURCES = [+ ("web", "https://github.com/souwell/Five-Nights-at-Freddys-Web", "6573cf1679e3ea62f1aa5e779bb3caaa627c8491"),+ ("hxnaf", "https://github.com/BaranMuzu/HX-NAF", "85c6b74c45ef419564eea94ae381d25ecddd60ff"),+]+++def main():+ if len(sys.argv) != 2:+ raise SystemExit(__doc__)+ ref = sys.argv[1]+ os.makedirs(ref, exist_ok=True)+ for name, url, commit in SOURCES:+ d = os.path.join(ref, name)+ if not os.path.isdir(os.path.join(d, ".git")):+ subprocess.run(["git", "clone", "--quiet", url, d], check=True)+ subprocess.run(["git", "-C", d, "checkout", "--quiet", commit], check=True)+ print(f"{name}: {commit[:10]}")+++if __name__ == "__main__":+ main()diff --git a/games/fnaf/tools/pack.py b/games/fnaf/tools/pack.pynew file mode 100644index 00000000..3a1571fb--- /dev/null+++ b/games/fnaf/tools/pack.py@@ -0,0 +1,719 @@+#!/usr/bin/env python3+"""Five Nights at Freddy's: its pictures and fonts -> src/data.bin + src/data.h.++ python3 -I tools/pack.py REF (REF: the folder tools/fetch.py filled; Python + Pillow + NumPy)++data.bin: "FNF1", the number of sections, their offsets, then the sections (SEC_* in data.h):+- HUFF: the four Huffman tables (Y DC, Y AC, colour DC, colour AC), 1424 bytes each (tools/codec.py)+- QUANT: for each quality, the Y and colour tables (64 u16 each, natural order, scaled for the IDCT)+- PICS: 12 bytes a picture (PIC_*): its width and height in 16 x 16 squares, its quality, 0, the picture it+ shares squares with (u16, 0xFFFF none), how many squares it has of its own then (u16) and where its table+ starts (u32)+- TABLE: a whole picture's squares (3 bytes each: where in BANK), or a picture sharing another's: the squares+ that differ (u16 the square's index, then 3 bytes)+- BANK: the squares, each from a byte boundary+- FONTS: for each font (FONT_*) its line height, baseline and 95 glyphs (32 to 126): advance, width, height,+ x and y from the top of the line (s8), 0, the offset of its 4-bit alpha rows (u32, from the section)+- IMGS: small pictures with alpha (IMG_*): width, height (u16), then 4-bit alpha (or 4-bit grey and alpha)+- MAP: the camera map's walls, 1 bit a pixel, and where the camera buttons are (MAP_*)++The office and the cameras are the game's 1600 x 720 pictures at a third (533 x 240): the calculator shows 320+of it and turns, as the game turns its 1280. Doors, buttons and the fan are drawn over the office."""+import os+import struct+import sys++import numpy as np+from PIL import Image, ImageDraw, ImageFont++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import codec as C # noqa: E402++OUT_BIN = os.path.join(HERE, "..", "src", "data.bin")+OUT_H = os.path.join(HERE, "..", "src", "data.h")+ROOT = os.path.join(HERE, "..", "..", "..")+SECTIONS = ["HUFF", "QUANT", "PICS", "TABLE", "BANK", "FONTS", "IMGS", "MAP"]+QUALITY = {"scene": 80, "scare": 70, "paper": 84, "face": 76}+FONT_DIRS = ["/usr/share/fonts/truetype/dejavu", "/usr/share/fonts/TTF", "/usr/local/share/fonts",+ "/Library/Fonts", os.path.expanduser("~/Library/Fonts")]++OW, OH = 533, 240 # the office and the cameras on the calculator+REF = None+++def web(path):+ return os.path.join(REF, "web", "src", "media", "Textures", path)+++def hx(path):+ return os.path.join(REF, "hxnaf", "assets", "images", path)+++def rgb(path, frame=0):+ im = Image.open(path)+ if frame:+ im.seek(frame)+ return im.convert("RGB")+++def third(im, size=(OW, OH)):+ return np.asarray(im.resize(size, Image.LANCZOS)).astype(np.float64)+++def pad16(a):+ h, w = a.shape[:2]+ H, W = -(-h // 16) * 16, -(-w // 16) * 16+ return np.pad(a, ((0, H - h), (0, W - w), (0, 0)), mode="edge")+++# ------------------------------------------------------------------ pictures+class Pic:+ def __init__(self, name, a, quality, base=None, refs=()):+ self.name, self.q, self.base = name, quality, base+ self.w, self.h = a.shape[1], a.shape[0]+ self.a = pad16(a)+ self.refs = [r for r in ([base] if base else []) + list(refs) if r] # pictures to take squares from+ self.mw, self.mh = self.a.shape[1] // 16, self.a.shape[0] // 16+++PICS = []+++def pic(name, a, quality="scene", base=None, refs=()):+ p = Pic(name, np.clip(a, 0, 255), quality, base, refs)+ PICS.append(p)+ return p+++def same_square(a, b, strict):+ d = np.abs(a - b)+ return d.max() <= (6 if strict else 14) and d.mean() <= (1.2 if strict else 3.0)+++def encode_all():+ qt = {k: (C.qtable(C.STD_LUMA, v), C.qtable(C.STD_CHROMA, v)) for k, v in QUALITY.items()}+ qnames = list(QUALITY)+ # each picture's squares: its own symbols, or a square of a picture it shares with+ for p in PICS:+ y, cb, cr = C.ycbcr(p.a)+ ql, qc = qt[p.q]+ yq = C.quantize(C.blocks_of(y), ql, 0.18)+ cbq = C.quantize(C.blocks_of(cb), qc, 0.22)+ crq = C.quantize(C.blocks_of(cr), qc, 0.22)+ p.sq = []+ for my in range(p.mh):+ for mx in range(p.mw):+ src = None+ tile = p.a[my * 16:my * 16 + 16, mx * 16:mx * 16 + 16]+ for r in p.refs:+ if mx < r.mw and my < r.mh and r.q == p.q:+ if same_square(tile, r.a[my * 16:my * 16 + 16, mx * 16:mx * 16 + 16], r is not p.base):+ src = r.sq[my * r.mw + mx]+ break+ if src is None:+ blocks = [yq[2 * my + i, 2 * mx + j] for i in (0, 1) for j in (0, 1)]+ src = ("own", tuple(C.mcu_symbols(blocks, cbq[my, mx], crq[my, mx])))+ p.sq.append(src)+ # Huffman tables from every square of its own, once+ freq = [[{}, {}], [{}, {}]]+ seen = set()+ for p in PICS:+ for s in p.sq:+ if id(s) in seen:+ continue+ seen.add(id(s))+ for comp, tab, sym, _, _ in s[1]:+ f = freq[comp][tab]+ f[sym] = f.get(sym, 0) + 1+ tables, huff = [[None, None], [None, None]], b""+ for comp in (0, 1):+ for tab in (0, 1):+ codes, bits, vals = C.canonical(C.huffman_lengths(freq[comp][tab]))+ tables[comp][tab] = codes+ huff += C.decode_tables(bits, vals)+ bank, where = bytearray(), {}+ by_id = {}+ for p in PICS:+ p.off = []+ for s in p.sq:+ if id(s) not in by_id:+ data = C.encode_mcu(s[1], tables)+ if data not in where:+ where[data] = len(bank)+ bank += data+ by_id[id(s)] = where[data]+ p.off.append(by_id[id(s)])+ bank += bytes(8)+ assert len(bank) < 1 << 24+ quant = b""+ for k in qnames:+ for t in qt[k]:+ quant += b"".join(struct.pack("<H", (int(t[i]) * C.AANSCALES[i] + 2048) >> 12) for i in range(64))+ pics, table = b"", bytearray()+ for i, p in enumerate(PICS):+ diff = []+ if p.base:+ b = p.base+ assert (b.mw, b.mh) == (p.mw, p.mh) and not b.base+ diff = [k for k in range(len(p.off)) if p.off[k] != b.off[k]]+ if p.base and 5 * len(diff) < 3 * len(p.off): # (else a whole table is smaller)+ pics += struct.pack("<BBBBHHI", p.mw, p.mh, qnames.index(p.q), 0, PICS.index(b), len(diff), len(table))+ for k in diff:+ table += struct.pack("<H", k) + p.off[k].to_bytes(3, "little")+ else:+ pics += struct.pack("<BBBBHHI", p.mw, p.mh, qnames.index(p.q), 0, 0xFFFF, 0, len(table))+ for o in p.off:+ table += o.to_bytes(3, "little")+ print(f"pictures: {len(PICS)}, squares {len(bank)} bytes, tables {len(table)} bytes")+ return huff, quant, pics, bytes(table), bytes(bank)+++# ------------------------------------------------------------------ fonts and small pictures+def find_font(name):+ for d in FONT_DIRS:+ p = os.path.join(d, name)+ if os.path.exists(p):+ return p+ raise SystemExit(f"pack: {name} not found (the DejaVu fonts)")+++def nibbles(alpha):+ """an h x w array of 0-15 -> rows of 4-bit pixels, the first in the low half of each byte"""+ h, w = alpha.shape+ out = bytearray()+ for r in range(h):+ row = list(alpha[r]) + [0]+ for c in range(0, w, 2):+ out.append(int(row[c]) | int(row[c + 1]) << 4)+ return bytes(out)+++def to4(a):+ return np.clip(np.round(np.asarray(a, dtype=np.float64) / 255 * 15), 0, 15).astype(np.uint8)+++def ttf_font(path, size, line=None):+ font = ImageFont.truetype(path, size)+ asc, desc = font.getmetrics()+ line = line or asc + desc+ glyphs = []+ for c in range(32, 127):+ ch = chr(c)+ adv = int(round(font.getlength(ch)))+ box = font.getbbox(ch)+ if box[2] <= box[0] or ch == " ":+ glyphs.append((adv, 0, 0, 0, 0, b""))+ continue+ im = Image.new("L", (box[2] - box[0], box[3] - box[1]))+ ImageDraw.Draw(im).text((-box[0], -box[1]), ch, font=font, fill=255)+ glyphs.append((adv, im.width, im.height, box[0], box[1], nibbles(to4(np.asarray(im)))))+ return line, asc, glyphs+++def fnt_font(fnt, png, scale, extra_adv=0):+ """an AngelCode .fnt bitmap font (white glyphs), scaled down"""+ sheet = Image.open(png).convert("RGBA")+ a = np.asarray(sheet).astype(np.float64)+ alpha = a[..., 3] * a[..., :3].mean(axis=2) / 255 if a[..., 3].min() < 255 else a[..., :3].mean(axis=2)+ chars, line, base = {}, 0, 0+ for row in open(fnt):+ kv = dict(t.split("=", 1) for t in row.split() if "=" in t)+ if row.startswith("common"):+ line, base = int(kv["lineHeight"]), int(kv["base"])+ if row.startswith("char "):+ chars[int(kv["id"])] = {k: int(v) for k, v in kv.items() if k in+ ("x", "y", "width", "height", "xoffset", "yoffset", "xadvance")}+ glyphs = []+ for c in range(32, 127):+ g = chars.get(c)+ if not g or not g["width"]:+ adv = int(round((g["xadvance"] if g else line * 0.4) * scale)) + extra_adv+ glyphs.append((adv, 0, 0, 0, 0, b""))+ continue+ crop = Image.fromarray(alpha[g["y"]:g["y"] + g["height"], g["x"]:g["x"] + g["width"]].astype(np.uint8))+ x0, y0 = g["xoffset"] * scale, g["yoffset"] * scale+ w = max(1, int(np.ceil(x0 + g["width"] * scale)) - int(np.floor(x0)))+ h = max(1, int(np.ceil(y0 + g["height"] * scale)) - int(np.floor(y0)))+ # placed at its fraction of a pixel, then reduced+ big = Image.new("L", (w * 8, h * 8))+ big.paste(crop.resize((max(1, int(round(g["width"] * scale * 8))), max(1, int(round(g["height"] * scale * 8)))),+ Image.LANCZOS), (int(round((x0 - np.floor(x0)) * 8)), int(round((y0 - np.floor(y0)) * 8))))+ im = big.resize((w, h), Image.BOX)+ glyphs.append((int(round(g["xadvance"] * scale)) + extra_adv, w, h, int(np.floor(x0)), int(np.floor(y0)),+ nibbles(to4(np.asarray(im)))))+ return int(round(line * scale)), int(round(base * scale)), glyphs+++def pack_fonts(fonts):+ head, data = b"", b""+ base = 4 + 4 * len(fonts)+ blobs = []+ for line, asc, glyphs in fonts:+ b = struct.pack("<BBBB", line, asc, 32, 95)+ rows = b""+ offs = []+ for adv, w, h, x, y, r in glyphs:+ offs.append(len(rows))+ rows += r+ g0 = len(b) + 12 * 95+ for (adv, w, h, x, y, r), o in zip(glyphs, offs):+ b += struct.pack("<BBBbbBHI", adv, w, h, x, y, 0, 0, g0 + o)+ blobs.append(b + rows)+ out = struct.pack("<I", len(fonts))+ p = base+ for b in blobs:+ out += struct.pack("<I", p)+ p += len(b)+ return out + b"".join(blobs)+++# ------------------------------------------------------------------ the game's pictures+DEFINES = []+++def define(name, value):+ DEFINES.append((name, value))+++def office_pictures():+ o = lambda n: third(rgb(web(f"Office/{n}.webp"))) # noqa: E731+ office = pic("OFFICE", o("Default"))+ for n, src in (("OFFICE_LL", "LL"), ("OFFICE_LLB", "LL_BONNIE"), ("OFFICE_RL", "RL"), ("OFFICE_RLC", "RL_CHICA")):+ pic(n, o(src), base=office)+ dark = pic("DARK", o("304"))+ pic("DARK_FREDDY", o("305"), base=dark)+ # the doors: where they differ from the open office, closed+ default = np.asarray(rgb(web("Office/Default.webp"))).astype(int)+ for side, src in (("L", "LD"), ("R", "RD")):+ full = np.asarray(rgb(web(f"Office/{src}.webp"))).astype(int)+ d = np.abs(full - default).max(axis=2) > 24+ ys, xs = np.nonzero(d)+ x0, x1 = int(np.floor(xs.min() / 3)), int(np.ceil((xs.max() + 1) / 3))+ y1 = int(np.ceil((ys.max() + 1) / 3))+ closed = o(src)+ pic(f"DOOR_{side}", closed[0:y1, x0:x1])+ define(f"DOOR_{side}_X", x0)+ define(f"DOOR_{side}_W", x1 - x0)+ define(f"DOOR_{side}_H", y1)+ # the buttons: off as the game shows them; the door's lit green, the light's lit white+ for side, (x0, x1) in (("L", (0, 32)), ("R", (496, 544))):+ mx0, mx1, my0, my1 = x0 // 16, x1 // 16, 96 // 16, 176 // 16+ for state in range(4):+ base = o("LL" if side == "L" and state & 2 else "RL" if side == "R" and state & 2 else "Default")+ base = pad16(base)[my0 * 16:my1 * 16, mx0 * 16:mx1 * 16].copy()+ light_buttons(base, side, state)+ pic(f"PANEL_{side}{state}", base)+ define(f"PANEL_{side}_X", mx0 * 16)+ define("PANEL_Y", 96)+ # the fan: its blades turning, three frames+ fan_frames(o("Default"))+ golden_office(o("Default"))+++def golden_office(office):+ """Golden Freddy, slumped in front of the desk: Freddy as he comes at you in the dark (lit, on black),+ gold, his eyes empty, his head fallen to a side; a patch of the office around him"""+ im = Image.open(web("Freddy-Jumpscare1.gif"))+ im.seek(9)+ a = np.asarray(im.convert("RGB")).astype(np.float64)+ lum = a.mean(axis=2)+ eyes = (lum > 150) & (a.max(axis=2) - a.min(axis=2) < 60)+ alpha = np.clip((lum - 6) / 18, 0, 1)+ gold = np.stack([lum * 1.35, lum * 1.05, lum * 0.32], axis=2)+ gold[eyes] = 0+ rgba = np.dstack([np.clip(gold, 0, 255), alpha * 255]).astype(np.uint8)+ sprite = Image.fromarray(rgba, "RGBA").rotate(-24, resample=Image.BICUBIC, expand=True)+ box = sprite.getbbox()+ sprite = sprite.crop(box)+ h = 128+ sprite = sprite.resize((int(sprite.width * h / sprite.height), h), Image.LANCZOS)+ x0, y0 = 266 - sprite.width // 2, OH - h + 30+ base = Image.fromarray(office.astype(np.uint8))+ dim = sprite.copy()+ dim.putdata([(int(r * 0.55), int(g * 0.55), int(b * 0.55), al) for r, g, b, al in sprite.getdata()])+ base.paste(dim, (x0, y0), dim)+ gx0, gy0 = x0 // 16 * 16, y0 // 16 * 16+ gx1 = min(OW, -(-(x0 + sprite.width) // 16) * 16)+ patch = np.asarray(base).astype(np.float64)[gy0:OH, gx0:gx1]+ pic("OFFICE_GOLD", patch)+ define("GOLD_X", gx0)+ define("GOLD_Y", gy0)+ define("GOLD_W", gx1 - gx0)+ define("GOLD_H", OH - gy0)+++def light_buttons(a, side, state):+ """paints the lit buttons on a panel (16-pixel squares from the office at a third)"""+ r, g, b = a[..., 0], a[..., 1], a[..., 2]+ red = (r > 90) & (r > 2.2 * g) & (r > 2.2 * b)+ ys, xs = np.nonzero(red)+ if not len(ys):+ return+ top, bottom = ys.min(), ys.max()+ h = bottom - top + 1+ if state & 1: # the door's button goes green+ lum = r[red]+ a[red, 0] = lum * 0.25+ a[red, 1] = np.minimum(255, lum * 1.05 + 20)+ a[red, 2] = lum * 0.25+ if state & 2: # the light's button, just under it, lights up+ x0, x1 = xs.min(), xs.max() + 1+ ly0, ly1 = bottom + 1 + max(1, h // 6), min(a.shape[0], bottom + 1 + h + h // 3)+ box = a[ly0:ly1, x0:x1]+ lum = box.mean(axis=2, keepdims=True)+ lit = lum > 40+ box[:] = np.where(lit, np.minimum(255, lum * 1.9 + 60), box)+++def fan_frames(office):+ """the desk fan's blades, turning: the inside of its grille blurred around its centre at three angles"""+ cx, cy, rad = 285.0, 124.0, 17.0+ mx0, my0, mx1, my1 = int((cx - rad) // 16), int((cy - rad) // 16), int((cx + rad) // 16) + 1, int((cy + rad) // 16) + 1+ region = pad16(office)[my0 * 16:my1 * 16, mx0 * 16:mx1 * 16]+ img = Image.fromarray(region.astype(np.uint8))+ ccx, ccy = cx - mx0 * 16, cy - my0 * 16+ yy, xx = np.mgrid[0:region.shape[0], 0:region.shape[1]]+ rr = np.hypot(xx - ccx, yy - ccy)+ inside = (rr < rad * 0.86)[..., None]+ for k in range(3):+ acc = np.zeros_like(region)+ n = 8+ for i in range(n):+ ang = k * 40 + i * 60 / n+ acc += np.asarray(img.rotate(ang, resample=Image.BILINEAR, center=(ccx, ccy))).astype(np.float64)+ pic(f"FAN{k}", np.where(inside, acc / n, region))+ define("FAN_X", mx0 * 16)+ define("FAN_Y", my0 * 16)+++CAMS = { # the camera's pictures: who is there (b Bonnie, c Chica, f Freddy) -> the file+ "1A": [("", "Stage"), ("f", "Stage-f"), ("bf", "Stage-b-f"), ("cf", "Stage-c-f"), ("bcf", "Stage-b-c-f")],+ "1B": [("", "DinningArea"), ("b", "DinningArea-b"), ("c", "DinningArea-c"), ("f", "DinningArea-f"),+ ("bc", "DinningArea-b-c"), ("bf", "DinningArea-b-f"), ("cf", "DinningArea-c-f"),+ ("bcf", "DinningArea-b-c-f")],+ "2A": [("", "West_Hall"), ("b", "West_Hall-b")],+ "2B": [("", "WHallCorner"), ("b", "WHallCorner-b")],+ "3": [("", "SupplyRoom"), ("b", "SupplyRoom-b")],+ "4A": [("", "East_Hall"), ("c", "East_Hall-c"), ("f", "East_Hall-f"), ("cf", "East_Hall-c-f")],+ "4B": [("", "EHallCorner"), ("c", "EHallCorner-c"), ("f", "EHallCorner-f")],+ "5": [("", "Backstage"), ("b", "Backstage-b")],+ "7": [("", "Restrooms"), ("c", "Restrooms-c"), ("f", "Restrooms-f"), ("cf", "Restrooms-c-f")],+ "1C": [("0", "Pirate_Cove"), ("1", "Pirate_Cove-1"), ("2", "Pirate_Cove-2"), ("3", "Pirate_Cove-3")],+}+++def camera_pictures():+ for cam, states in CAMS.items():+ first = None+ for who, f in states:+ a = third(rgb(web(f"Cams/{f}.webp")))+ name = f"CAM{cam}_{who.upper() or 'EMPTY'}"+ if first is None:+ first = pic(name, a)+ else:+ pic(name, a, base=first)+ # 2A's hall is dark but when its light flickers on: the same hall, its lamp off+ hall = third(rgb(web("Cams/West_Hall.webp")))+ pic("CAM2A_DARK", dark_hall(hall), base=PICS[[p.name for p in PICS].index("CAM2A_EMPTY")])+ # 2B's poster, Golden Freddy's face for a while (the easter egg)+ corner = third(rgb(web("Cams/WHallCorner.webp")))+ gold = golden_poster(corner, rgb(web("golden_freddy.webp")))+ pic("CAM2B_GOLD", gold, base=PICS[[p.name for p in PICS].index("CAM2B_EMPTY")])+++def dark_hall(a):+ """West Hall with its light off: dim, and the far end (lit by the lamp) dark"""+ h, w = a.shape[:2]+ yy, xx = np.mgrid[0:h, 0:w]+ far = np.exp(-(((xx - 0.71 * w) / (0.09 * w)) ** 2 + ((yy - 0.42 * h) / (0.5 * h)) ** 2))+ return a * (0.42 - 0.3 * far)[..., None]+++def golden_poster(corner, face):+ """2B's poster (its corners at a third: on the wall, in perspective) with Golden Freddy's face in it"""+ quad = [(162, 8), (243, 6), (252, 98), (189, 125)] # top left, top right, bottom right, bottom left+ fw, fh = face.size+ src = [(fw * 0.1, 0), (fw * 0.9, 0), (fw * 0.9, fh), (fw * 0.1, fh)]+ # the perspective from the wall to the face: 8 unknowns from the 4 corners+ m, v = [], []+ for (x, y), (u, w) in zip(quad, src):+ m.append([x, y, 1, 0, 0, 0, -u * x, -u * y])+ m.append([0, 0, 0, x, y, 1, -w * x, -w * y])+ v += [u, w]+ coef = np.linalg.solve(np.array(m, dtype=np.float64), np.array(v, dtype=np.float64))+ warped = np.asarray(face.transform((OW, OH), Image.PERSPECTIVE, tuple(coef), Image.BICUBIC)).astype(np.float64)+ mask = Image.new("L", (OW, OH))+ ImageDraw.Draw(mask).polygon(quad, fill=255)+ mask = np.asarray(mask).astype(np.float64)[..., None] / 255+ region = corner[mask[..., 0] > 0.5]+ light = region.mean() / 255+ return corner * (1 - mask) + warped * (0.1 + light * 0.95) * mask+++def scare(name, path, frames, x0, size=(OW, OH), step=1):+ """a jumpscare's frames, 320 pixels wide from x0 (office coordinates at a third)"""+ im = Image.open(path)+ n = im.n_frames+ out = []+ prev = None+ first = None+ for i in range(0, min(n, frames), step):+ im.seek(i)+ a = np.asarray(im.convert("RGB").resize(size, Image.LANCZOS)).astype(np.float64)[:, x0:x0 + 320]+ p = pic(f"{name}{len(out)}", a, "scare", base=first, refs=[prev] if prev else [])+ first = first or p+ prev = p+ out.append(p)+ define(f"{name}_N", len(out))+ define(f"{name}_X", x0)+ return out+++def scare_pictures():+ scare("BONNIE", web("Bonnie-Jumpscare.webp"), 10, 106)+ scare("CHICA", web("Chica-Jumpscare.webp"), 15, 95)+ scare("FREDDY", web("Freddy-Jumpscare.webp"), 20, 180)+ scare("FOXY", web("Foxy-Jumpscare.gif"), 19, 0)+ scare("FOXYRUN", web("Foxy-Hallway.webp"), 18, 213)+ scare("POWEROUT", web("Freddy-Jumpscare1.gif"), 21, 53, size=(427, 240))+ scare("FLIP", web("Up.webp"), 11, 53, size=(427, 240)) # the monitor coming up+ g = rgb(web("golden_freddy.webp")).resize((427, 240), Image.LANCZOS)+ pic("GOLDEN", np.asarray(g).astype(np.float64)[:, 53:373], "scare")+++def menu_pictures():+ # the title's four faces of Freddy (the atlas has two of them turned)+ atlas = Image.open(hx("mainmenu/freddy.png")).convert("RGBA")+ first = None+ for i, (x, y, rot) in enumerate([(2, 2, False), (1286, 2, True), (2, 726, True), (726, 1286, False)]):+ w, h = (720, 1280) if rot else (1280, 720)+ f = atlas.crop((x, y, x + w, y + h))+ if rot:+ f = f.transpose(Image.Transpose.ROTATE_90)+ bg = Image.new("RGB", f.size)+ bg.paste(f, (0, 0), f)+ a = np.asarray(bg.resize((427, 240), Image.LANCZOS)).astype(np.float64)[:, 107:427]+ p = pic(f"TITLE{i}", a, "face", base=first)+ first = first or p+ news = Image.open(hx("mainmenu/newspaper.png")).convert("RGB").resize((427, 240), Image.LANCZOS)+ pic("NEWSPAPER", np.asarray(news).astype(np.float64)[:, 53:373], "paper")+ for n in ("freddy", "bonnie", "chica", "foxy"):+ f = Image.open(web(f"CustomNight/{n}.png")).convert("RGBA")+ bg = Image.new("RGB", f.size)+ bg.paste(f, (0, 0), f)+ pic(f"FACE_{n.upper()}", np.asarray(bg.resize((64, 64), Image.LANCZOS)).astype(np.float64), "face")+ for name, draw in (("PAYCHECK", paycheck), ("OVERTIME", overtime), ("PINKSLIP", pink_slip)):+ pic(name, np.asarray(draw()).astype(np.float64), "paper")+ # the game over: Backstage, where the empty suits are, darker+ back = third(rgb(web("Cams/Backstage.webp")))[:, 106:426] * 0.7+ pic("GAMEOVER", back, "scene")+++def paper(color):+ im = Image.new("RGB", (320, 240), (12, 12, 12))+ d = ImageDraw.Draw(im)+ rng = np.random.default_rng(7)+ d.rectangle((22, 30, 297, 210), fill=color)+ a = np.asarray(im).astype(np.float64)+ grain = rng.normal(0, 5, a.shape[:2])[..., None]+ a[30:211, 22:298] += grain[30:211, 22:298]+ return Image.fromarray(np.clip(a, 0, 255).astype(np.uint8))+++def text(d, xy, s, size, bold=False, serif=False, fill=(30, 30, 30), anchor="la"):+ name = ("DejaVuSerif" if serif else "DejaVuSans") + ("-Bold" if bold else "") + ".ttf"+ d.text(xy, s, font=ImageFont.truetype(find_font(name), size), fill=fill, anchor=anchor)+++def cheque(amount, words, memo):+ im = paper((222, 228, 214))+ d = ImageDraw.Draw(im)+ d.rectangle((26, 34, 293, 206), outline=(120, 140, 120))+ text(d, (34, 42), "Fazbear Entertainment, Inc.", 11, bold=True, serif=True)+ text(d, (34, 56), "Freddy Fazbear's Pizza", 9, serif=True, fill=(70, 70, 70))+ text(d, (286, 42), "No. 0451", 9, fill=(90, 90, 90), anchor="ra")+ text(d, (34, 88), "PAY TO THE", 8, fill=(80, 80, 80))+ text(d, (34, 98), "ORDER OF", 8, fill=(80, 80, 80))+ text(d, (92, 92), "Mike Schmidt", 14, serif=True, fill=(20, 30, 90))+ d.line((90, 110, 220, 110), fill=(80, 80, 80))+ d.rectangle((228, 86, 290, 106), outline=(80, 80, 80))+ text(d, (286, 96), amount, 13, bold=True, fill=(20, 30, 90), anchor="rm")+ text(d, (34, 124), words, 10, serif=True, fill=(20, 30, 90))+ d.line((34, 138, 286, 138), fill=(80, 80, 80))+ text(d, (34, 172), "MEMO", 8, fill=(80, 80, 80))+ text(d, (64, 168), memo, 11, serif=True, fill=(20, 30, 90))+ d.line((62, 184, 150, 184), fill=(80, 80, 80))+ d.line((180, 184, 286, 184), fill=(80, 80, 80))+ text(d, (233, 188), "Fazbear Entertainment", 7, fill=(80, 80, 80), anchor="ma")+ return im+++def paycheck():+ return cheque("$120.50", "One hundred twenty and 50/100 dollars", "One week's work")+++def overtime():+ return cheque("$0.50", "Zero and 50/100 dollars", "Overtime")+++def pink_slip():+ im = paper((236, 178, 190))+ d = ImageDraw.Draw(im)+ text(d, (160, 40), "NOTICE OF TERMINATION", 13, bold=True, serif=True, anchor="ma")+ text(d, (160, 58), "Freddy Fazbear's Pizza", 9, serif=True, fill=(80, 40, 50), anchor="ma")+ d.line((34, 74, 286, 74), fill=(120, 60, 70))+ rows = [("Employee:", "Mike Schmidt"), ("Position:", "Night security"), ("Reason:", "Tampering with the"),+ ("", "animatronics, general"), ("", "unprofessionalism, odor.")]+ y = 86+ for k, v in rows:+ text(d, (36, y), k, 10, bold=True, fill=(60, 20, 30))+ text(d, (110, y), v, 11, serif=True, fill=(30, 20, 20))+ y += 18+ text(d, (160, 186), "Please return your uniform.", 9, serif=True, fill=(80, 40, 50), anchor="ma")+ return im+++# ------------------------------------------------------------------ the map, the title's words, the star+def camera_map():+ im = np.asarray(Image.open(web("Cams/Complete_Map.png")).convert("RGBA")).astype(np.int32)+ a = im[..., 3]+ grey = (a > 128) & (im[..., 0] < 140) & (im[..., 0] > 40)+ # the CAM labels: grey boxes; where each is (the buttons go there), and none of them in the walls+ seen = np.zeros_like(grey)+ boxes = []+ H, W = grey.shape+ for y in range(H):+ for x in range(W):+ if grey[y, x] and not seen[y, x]:+ stack, pts = [(y, x)], []+ seen[y, x] = True+ while stack:+ cy, cx = stack.pop()+ pts.append((cy, cx))+ for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):+ ny, nx = cy + dy, cx + dx+ if 0 <= ny < H and 0 <= nx < W and grey[ny, nx] and not seen[ny, nx]:+ seen[ny, nx] = True+ stack.append((ny, nx))+ if len(pts) > 150:+ ys, xs = zip(*pts)+ boxes.append((min(xs), min(ys), max(xs), max(ys)))+ walls = (a > 100) & (im[..., 0] > 200)+ for x0, y0, x1, y1 in boxes:+ walls[max(0, y0 - 3):y1 + 4, max(0, x0 - 3):x1 + 4] = False+ expect = {"1A": (135, 38), "1B": (122, 100), "1C": (75, 178), "2A": (133, 300), "2B": (133, 338),+ "3": (60, 268), "4A": (225, 300), "4B": (225, 338), "5": (25, 128), "6": (345, 250), "7": (345, 112)}+ s = 1 / 3+ size = int(400 * s)+ small = Image.fromarray((walls * 255).astype(np.uint8)).resize((size, size), Image.BOX)+ bits = np.asarray(small) > 70+ out = struct.pack("<HH", size, size)+ stride = (size + 7) // 8+ for r in range(size):+ row = bytearray(stride)+ for c in range(size):+ if bits[r, c]:+ row[c >> 3] |= 1 << (c & 7)+ out += row+ centres = {}+ for cam, (ex, ey) in expect.items():+ best = min(boxes, key=lambda b: ((b[0] + b[2]) / 2 - ex) ** 2 + ((b[1] + b[3]) / 2 - ey) ** 2)+ centres[cam] = (int(round((best[0] + best[2]) / 2 * s)), int(round((best[1] + best[3]) / 2 * s)))+ for cam in ("1A", "1B", "1C", "2A", "2B", "3", "4A", "4B", "5", "6", "7"):+ out += struct.pack("<HH", *centres[cam])+ define("MAP_SIZE", size)+ return out+++IMGS = []+++def img(name, alpha, grey=None):+ """a small picture with alpha (and a grey level, when not white)"""+ a = to4(alpha)+ h, w = a.shape+ data = struct.pack("<HHBBH", w, h, 1 if grey is not None else 0, 0, 0) + nibbles(a)+ if grey is not None:+ data += nibbles(to4(grey))+ define(f"IMG_{name}", len(IMGS))+ IMGS.append(data)+++def small_pictures():+ t = Image.open(hx("mainmenu/texts/FIVE_GAME_TITLE.png")).convert("RGBA")+ t = t.resize((int(t.width * 0.5), int(t.height * 0.5)), Image.LANCZOS)+ a = np.asarray(t).astype(np.float64)+ img("TITLE", a[..., 3] * a[..., :3].mean(axis=2) / 255)+ s = Image.open(hx("mainmenu/STAR.png")).convert("RGBA").resize((22, 21), Image.LANCZOS)+ a = np.asarray(s).astype(np.float64)+ img("STAR", a[..., 3] * a[..., :3].mean(axis=2) / 255)+++def app_icon():+ """src/icon.png: Freddy's face as it comes out of the dark, with NumPlay's rounded corners"""+ sys.path.insert(0, os.path.join(ROOT, "tools"))+ from make_icon import corner_mask+ im = Image.open(web("Freddy-Jumpscare1.gif"))+ im.seek(7)+ f = im.convert("RGB")+ w, h = f.size+ s = 0.95 * h+ face = f.crop((int(w / 2 - s / 2), int(0.40 * h - s / 2), int(w / 2 + s / 2), int(0.40 * h + s / 2)))+ face = face.resize((55, 56), Image.LANCZOS).point(lambda v: min(255, int(v * 1.15)))+ face.putalpha(corner_mask(55, 56))+ face.save(os.path.join(HERE, "..", "src", "icon.png"), optimize=True)+++def pack_imgs():+ out = struct.pack("<I", len(IMGS))+ p = 4 + 4 * len(IMGS)+ for d in IMGS:+ out += struct.pack("<I", p)+ p += len(d) + (-len(d) % 4)+ return out + b"".join(d + bytes(-len(d) % 4) for d in IMGS)+++def main():+ global REF+ if len(sys.argv) != 2:+ raise SystemExit(__doc__)+ REF = sys.argv[1]+ office_pictures()+ camera_pictures()+ scare_pictures()+ menu_pictures()+ huff, quant, pics, table, bank = encode_all()+ fonts = [+ ttf_font(find_font("DejaVuSansMono-Bold.ttf"), 11), # FONT_HUD+ ttf_font(find_font("DejaVuSansMono.ttf"), 17), # FONT_BIG+ ttf_font(find_font("DejaVuSans.ttf"), 11), # FONT_TEXT+ fnt_font(hx("numbers/NUMBER.fnt"), hx("numbers/NUMBER.png"), 0.36), # FONT_CLOCK+ fnt_font(hx("numbers/PIXEL_NUMBER.fnt"), hx("numbers/PIXEL_NUMBER.png"), 0.36), # FONT_PIXEL+ ttf_font(find_font("DejaVuSansMono.ttf"), 24), # FONT_HUGE+ ]+ small_pictures()+ app_icon()+ sections = [huff, quant, pics, table, bank, pack_fonts(fonts), pack_imgs(), camera_map()]+ head = b"FNF1" + struct.pack("<I", len(sections))+ offs, p = [], len(head) + 4 * len(sections)+ for s in sections:+ offs.append(p)+ p += len(s) + (-len(s) % 4)+ out = head + b"".join(struct.pack("<I", o) for o in offs)+ for s in sections:+ out += s + bytes(-len(s) % 4)+ open(OUT_BIN, "wb").write(out)+ h = ["/* Made by tools/pack.py: what is in data.bin. */", "#ifndef FNAF_DATA_H", "#define FNAF_DATA_H", ""]+ h += [f"#define SEC_{n} {i}" for i, n in enumerate(SECTIONS)]+ h += [f"#define PIC_{p.name} {i}" for i, p in enumerate(PICS)]+ h += [f"#define PIC_COUNT {len(PICS)}"]+ h += [f"#define FONT_{n} {i}" for i, n in enumerate(["HUD", "BIG", "TEXT", "CLOCK", "PIXEL", "HUGE"])]+ h += [f"#define {n} {v}" for n, v in DEFINES]+ h += ["", "#endif", ""]+ open(OUT_H, "w").write("\n".join(h))+ print(f"data.bin: {len(out)} bytes")+++if __name__ == "__main__":+ main()