# Builds priv/static/doom/: the engine as a standalone WASM program.
# The WAD is fetched at page load (never preloaded, never committed);
# the corresponding source ships next to the binary as src.tar.gz.

ENGINE := build/engine/doomgeneric
OUT := ../../priv/static/doom

# Upstream's own emscripten file list (Makefile.emscripten), as sources.
NAMES := dummy am_map doomdef doomstat dstrings d_event d_items d_iwad \
  d_loop d_main d_mode d_net f_finale f_wipe g_game hu_lib hu_stuff info \
  i_cdmus i_endoom i_joystick i_scale i_sound i_system i_timer memio \
  m_argv m_bbox m_cheat m_config m_controls m_fixed m_menu m_misc \
  m_random p_ceilng p_doors p_enemy p_floor p_inter p_lights p_map \
  p_maputl p_mobj p_plats p_pspr p_saveg p_setup p_sight p_spec p_switch \
  p_telept p_tick p_user r_bsp r_data r_draw r_main r_plane r_segs r_sky \
  r_things sha1 sounds statdump st_lib st_stuff s_sound tables v_video \
  wi_stuff w_checksum w_file w_main w_wad z_zone w_file_stdc i_input \
  i_video doomgeneric doomgeneric_emscripten mus2mid i_sdlmusic i_sdlsound

SRCS := $(addprefix $(ENGINE)/, $(addsuffix .c, $(NAMES)))

CFLAGS := -O2 -DFEATURE_SOUND -sUSE_SDL=2 -sUSE_SDL_MIXER=2
LDFLAGS := -sMODULARIZE=1 -sEXPORT_NAME=createDoom \
  -sEXPORTED_RUNTIME_METHODS=FS,callMain -sALLOW_MEMORY_GROWTH=1 \
  -sSDL2_MIXER_FORMATS='["mid"]' -lm

all: $(OUT)/doom.js $(OUT)/src.tar.gz

engine:
	./fetch-engine.sh

$(OUT)/doom.js: engine
	emcc $(CFLAGS) $(LDFLAGS) $(SRCS) -o $(OUT)/doom.js

# GPLv2 §3: the source that corresponds to the binary above — the
# pinned engine plus everything in this directory.
$(OUT)/src.tar.gz: engine
	tar czf $(OUT)/src.tar.gz \
	  --exclude doom-web/build/engine/.git \
	  -C .. doom-web/build/engine doom-web/Makefile doom-web/README.md \
	  doom-web/fetch-engine.sh doom-web/fetch-wad.sh \
	  -C ../priv/static doom/index.html doom/play.js

clean:
	rm -f $(OUT)/doom.js $(OUT)/doom.wasm $(OUT)/src.tar.gz

.PHONY: all engine clean
