# 3DWorldRecomp build
# macOS: clang, SDL3 / FFmpeg / the Vulkan loader + MoltenVK + shaderc from `make deps` (or Homebrew), Vulkan renderer.
# Windows: MSYS2 UCRT64 shell (see docs/BUILD-windows.md), clang + Vulkan renderer.
# Linux: clang + Vulkan renderer, x86-64 or aarch64 (see docs/linux.md).
UNAME := $(shell uname -s)
comma := ,
ifneq ($(filter MINGW% MSYS% CYGWIN% Windows_NT,$(UNAME) $(OS)),)
PLATFORM := windows
else ifeq ($(UNAME),Linux)
PLATFORM := linux
else
PLATFORM := macos
endif

# Linux: ARCH (x86_64 / aarch64, default this machine's) picks the target, separately from PLATFORM. The generated code
# differs per arch (AArch64 hosts run the guest's FP/SIMD as inline asm, others use the portable C of simd.h), so a
# cross build has its own generated-<arch>/ and build/<arch>/; SYSROOT is the target's root filesystem (headers, libs).
GEN      ?= generated
ifeq ($(PLATFORM),linux)
HOSTARCH := $(patsubst arm64,aarch64,$(shell uname -m))
ARCH     ?= $(HOSTARCH)
ifneq ($(ARCH),$(HOSTARCH))
CROSS    := --target=$(ARCH)-linux-gnu $(if $(SYSROOT),--sysroot=$(SYSROOT))
GEN      := generated-$(ARCH)
B        ?= build/$(ARCH)
endif
GENSIMD  := --simd $(if $(filter aarch64,$(ARCH)),asm,c)
endif
# Android (arm64-v8a): `make PLATFORM=android` (MSYS2 shell on Windows, or Linux / macOS), with the SDK, NDK and
# libraries of tools/android/build_deps.sh under build/android. AArch64 code generation as on Linux aarch64.
ifeq ($(PLATFORM),android)
GEN      := generated-android
B        ?= build/android/build
GENSIMD  := --simd asm
GUEST_WINDOW ?= 0x1000000000
endif
# The guest's address window (runtime/rt.h GUEST_WINDOW, which says why Android's differs): the game code is generated
# for it. GUEST_WINDOW=<address> builds another one (with its own B and GEN), a test of that on a computer.
GUEST_WINDOW ?= 0x7000000000
SDK_BASE := $(shell printf '0x%x' $$(( $(GUEST_WINDOW) + 0x6000000 )))
GENPY    := gen.py
ifneq ($(GUEST_WINDOW),0x7000000000)
WINDOWFLAG := -DGUEST_WINDOW=$(GUEST_WINDOW)ull
# (gen.py's patches are keyed by their addresses in the computers' window: it moves them)
GENPY    := gen_window.py
endif

# B: build dir. MACOS_MIN: oldest macOS to run on (default: this one). DEPS: prefix with SDL3 / FFmpeg / the Vulkan
# stack instead of Homebrew's (make deps). `make app` sets all three (build/mac15, 15.0, build/deps); plain `make` on
# macOS uses build/deps once `make deps` has made it (Homebrew has no Vulkan Memory Allocator), Homebrew before that.
B         ?= build
MACOS_MIN ?=
ifeq ($(PLATFORM),macos)
DEPS      ?= $(if $(wildcard build/deps/lib/libvulkan.1.dylib),$(CURDIR)/build/deps)
endif
DEPS      ?=
MINFLAG  := $(if $(MACOS_MIN),-mmacosx-version-min=$(MACOS_MIN))
CC       := clang $(MINFLAG) $(CROSS)
CXX      := clang++ $(MINFLAG) $(CROSS)
IMGUI    := third_party/imgui
GENFLAGS := -O1 -fno-strict-aliasing -Wno-return-type -Wno-unused-label -fvisibility=hidden -Iruntime

# The game code (made by `make gen` from your own game files) is its own library next to the app (runtime/gamelib.h);
# the app itself holds none of it
GEN_SRC  := $(wildcard $(GEN)/main/*.c) $(wildcard $(GEN)/sdk/*.c)
GEN_OBJ  := $(patsubst %.c,$(B)/obj/%.o,$(patsubst $(GEN)/%,%,$(GEN_SRC))) $(B)/obj/tools/gamelib_entry.o
PLATSRC  := $(if $(filter android,$(PLATFORM)),linux,$(PLATFORM))  # (Android: the Linux layer, with its #ifdefs)
RT_SRC   := $(wildcard runtime/*.c) $(wildcard runtime/hle/*.c) $(wildcard runtime/services/*.c) \
            $(wildcard runtime/nvn/*.c) $(wildcard runtime/nvn/maxwell/*.c) runtime/platform/$(strip $(PLATSRC)).c \
            $(if $(filter windows,$(PLATFORM)),,runtime/platform/posix.c)  # (what macOS and Linux share)
RT_HDRS  := $(wildcard runtime/*.h) $(wildcard runtime/platform/*.h) $(wildcard runtime/nvn/*.h) \
            $(wildcard runtime/nvn/maxwell/*.h) $(wildcard runtime/nvn/vulkan/*.h) $(wildcard runtime/ui/*.h)
UI_SRC   := $(wildcard runtime/ui/*.mm)
UI_OBJ   := $(patsubst runtime/%.mm,$(B)/rt/%.o,$(UI_SRC))
IMGUI_OBJ := $(B)/imgui/imgui.o $(B)/imgui/imgui_draw.o $(B)/imgui/imgui_tables.o $(B)/imgui/imgui_widgets.o \
             $(B)/imgui/imgui_impl_sdl3.o

ifeq ($(PLATFORM),macos)
SDL      := $(or $(DEPS),/opt/homebrew/opt/sdl3)
FFMPEG   := $(or $(DEPS),/opt/homebrew/opt/ffmpeg)
EXE      := $(B)/3dworldrecomp
DEPINC   := -I$(SDL)/include -I$(FFMPEG)/include
LDFLAGS  := $(addprefix -L,$(sort $(SDL)/lib $(FFMPEG)/lib)) $(addprefix -Wl$(comma)-rpath$(comma),$(sort $(SDL)/lib $(FFMPEG)/lib)) \
            -lSDL3 -lavformat -lavcodec -lavutil -lswscale
# the Vulkan renderer, as on Windows and Linux, on MoltenVK (Vulkan on Metal) through the Vulkan loader; shaderc
# compiles the translated GLSL (runtime/nvn/vulkan)
VULKAN   := $(or $(DEPS),/opt/homebrew)
OSFLAGS  := -Wno-nullability-completeness  # (Vulkan Memory Allocator's header with Apple clang)
DEPINC   += -I$(VULKAN)/include
LDFLAGS  += $(if $(filter $(VULKAN)/lib,$(SDL)/lib $(FFMPEG)/lib),,-L$(VULKAN)/lib -Wl$(comma)-rpath$(comma)$(VULKAN)/lib) \
            -lvulkan -lshaderc_shared
BACKEND_SRC := $(wildcard runtime/nvn/vulkan/*.c) $(wildcard runtime/nvn/vulkan/*.cpp)
BACKEND_OBJ := $(patsubst runtime/%.cpp,$(B)/rt/%.o,$(patsubst runtime/%.c,$(B)/rt/%.o,$(BACKEND_SRC)))
IMGUI_OBJ += $(B)/imgui/imgui_impl_vulkan.o
UIFLAGS  := -x c++ $(OSFLAGS)  # the .mm UI sources are plain C++
GAMELIB  := $(B)/3dwgame.dylib
GAMELIB_LDFLAGS := -dynamiclib -undefined dynamic_lookup  # (the runtime functions it calls: the app's own)
GAMELIB_SHARED := -shared -Wl,-undefined,dynamic_lookup  # (the same, for the start screen's build: zig cc)
else ifeq ($(PLATFORM),android)
# The runtime is libmain.so, which SDL's Java activity loads and calls SDL_main in (tools/android/apk.sh packages
# it); the game code library links against it for the runtime functions it calls (the Linux build's -rdynamic).
ANDROID_API ?= 30  # (Android 11: memfd_create)
# (the newest NDK in the SDK tools/android/env.sh picks: $ANDROID_HOME, setup_sdk.sh's, else Android Studio's)
NDK      ?= $(lastword $(sort $(wildcard $(firstword $(wildcard $(ANDROID_HOME) build/android/sdk \
                $(HOME)/Library/Android/sdk $(HOME)/Android/Sdk $(subst \,/,$(LOCALAPPDATA))/Android/Sdk))/ndk/*)))
NDKHOST  := $(if $(filter MINGW% MSYS%,$(UNAME)),windows-x86_64,$(if $(filter Darwin,$(UNAME)),darwin-x86_64,linux-x86_64))
CC       := $(NDK)/toolchains/llvm/prebuilt/$(NDKHOST)/bin/clang --target=aarch64-linux-android$(strip $(ANDROID_API)) -fPIC
CXX      := $(NDK)/toolchains/llvm/prebuilt/$(NDKHOST)/bin/clang++ --target=aarch64-linux-android$(strip $(ANDROID_API)) -fPIC
EXE      := $(B)/libmain.so
DEPINC   := -Ibuild/android/deps/include
OSFLAGS  := -Wno-format -Wno-nullability-completeness  # (%llx for uint64_t: unsigned long here, the same size; VMA)
# (--no-undefined: a missing symbol fails here, not as a dlopen error on the device. Vulkan: the API 33 stub, the
# first with the 1.3 functions the renderer calls - the manifest requires Vulkan 1.3, which only Android 13+ reports)
LDFLAGS  := -shared -fuse-ld=lld -Wl,-soname,libmain.so -Wl,--no-undefined -Lbuild/android/deps/lib -lSDL3 -lavformat -lavcodec -lavutil \
            -lswscale -lshaderc_shared -llog -landroid -lm -ldl \
            $(NDK)/toolchains/llvm/prebuilt/$(NDKHOST)/sysroot/usr/lib/aarch64-linux-android/33/libvulkan.so
BACKEND_SRC := $(wildcard runtime/nvn/vulkan/*.c) $(wildcard runtime/nvn/vulkan/*.cpp)
BACKEND_OBJ := $(patsubst runtime/%.cpp,$(B)/rt/%.o,$(patsubst runtime/%.c,$(B)/rt/%.o,$(BACKEND_SRC)))
IMGUI_OBJ += $(B)/imgui/imgui_impl_vulkan.o
UIFLAGS  := -x c++ $(OSFLAGS)  # the .mm UI sources are plain C++
GAMELIB  := $(B)/3dwgame.so
GAMELIB_LDFLAGS := -shared -fuse-ld=lld $(EXE)
GAMELIB_SHARED := -shared
else ifeq ($(PLATFORM),linux)
EXE      := $(B)/3dworldrecomp
DEPINC   := $(if $(DEPS),-I$(DEPS)/include)
ifeq ($(ARCH),x86_64)
GENARCH  ?= -march=x86-64-v3  # as on Windows: AVX2 + FMA for the lifted FP/SIMD code (checked at startup)
endif
GENFLAGS += $(GENARCH) -fPIC
OSFLAGS  := -Wno-format  # (%llx for uint64_t, which is unsigned long here: the same size)
SHADERC  ?= -lshaderc  # (Debian / Ubuntu's libshaderc.so; a shaderc built from source: -lshaderc_shared)
# -rdynamic: crash backtraces name host functions (runtime/platform/linux.c)
LDFLAGS  := -fuse-ld=lld -rdynamic $(if $(DEPS),-L$(DEPS)/lib) -lSDL3 -lavformat -lavcodec -lavutil -lswscale \
            -lvulkan $(SHADERC) -lpthread -ldl -lm
BACKEND_SRC := $(wildcard runtime/nvn/vulkan/*.c) $(wildcard runtime/nvn/vulkan/*.cpp)
BACKEND_OBJ := $(patsubst runtime/%.cpp,$(B)/rt/%.o,$(patsubst runtime/%.c,$(B)/rt/%.o,$(BACKEND_SRC)))
IMGUI_OBJ += $(B)/imgui/imgui_impl_vulkan.o
UIFLAGS  := -x c++  # the .mm UI sources are plain C++
GAMELIB  := $(B)/3dwgame.so
GAMELIB_LDFLAGS := -shared -fuse-ld=lld  # (the runtime functions it calls: the app's own, -rdynamic)
GAMELIB_SHARED := -shared
else
EXE      := $(B)/3dworldrecomp.exe
DEPINC   := $(if $(DEPS),-I$(DEPS)/include)
OSFLAGS  := -D_FILE_OFFSET_BITS=64 -D_POSIX_THREAD_SAFE_FUNCTIONS -D_CRT_RAND_S -DWIN32_LEAN_AND_MEAN -DNOMINMAX
GENARCH  ?= -march=x86-64-v3  # AVX2 + FMA for the lifted FP/SIMD code (simd.h); x86-64-v2 at setup without them
GENFLAGS += -D_FILE_OFFSET_BITS=64 $(GENARCH)
LDFLAGS  := -fuse-ld=lld -Wl,--stack,16777216 $(if $(DEPS),-L$(DEPS)/lib) -lSDL3 -lavformat -lavcodec -lavutil -lswscale \
            -lvulkan-1 -lwinmm -lole32 -lshell32 -lcomdlg32 -luuid -lshaderc_shared -lcfgmgr32 -lws2_32 \
            $(if $(RELEASE),-Wl$(comma)--subsystem$(comma)windows)  # release: no console window (log -> 3dworldrecomp.log)
BACKEND_SRC := $(wildcard runtime/nvn/vulkan/*.c) $(wildcard runtime/nvn/vulkan/*.cpp)
BACKEND_OBJ := $(patsubst runtime/%.cpp,$(B)/rt/%.o,$(patsubst runtime/%.c,$(B)/rt/%.o,$(BACKEND_SRC)))
BACKEND_OBJ += $(B)/rt/platform/windows_rc.o  # the .exe's icon (Explorer, taskbar)
WINDRES  ?= windres
IMGUI_OBJ += $(B)/imgui/imgui_impl_vulkan.o
UIFLAGS  := -x c++ $(OSFLAGS)  # the .mm UI sources are plain C++
GAMELIB  := $(B)/3dwgame.dll
# the runtime functions it calls: exported by the .exe, linked through its import library
LDFLAGS  += -Wl,--export-all-symbols -Wl,--out-implib,$(B)/3dworldrecomp.dll.a
GAMELIB_LDFLAGS := -shared -fuse-ld=lld $(B)/3dworldrecomp.dll.a
GAMELIB_SHARED := -shared  # (+ the import library: runtime/gamebuild.c)
endif

# GAMELIB_ID: what the game code library is built from (the generator, the headers it is compiled against, the
# flags). A library with another id is rebuilt by the start screen, never loaded. Their text is hashed: any edit to
# these files, a comment too, has every player recompile the game (minutes; longer on a Steam Deck) after updating.
GAMELIB_SRCS := tools/gen.py tools/lifter.py tools/analyze.py tools/nso.py tools/passes.py tools/patches.py \
                tools/simd_c.py tools/gamelib_entry.c runtime/hle/hle_symbols.txt \
                runtime/cpu.h runtime/simd.h runtime/simd_fp.h runtime/gamelib.h
ifneq ($(WINDOWFLAG),)
# (another guest window: libraries for different windows get different ids)
GAMELIB_SRCS += tools/gen_window.py
GENFLAGS += $(WINDOWFLAG)
endif
GAMELIB_ID := $(shell (cat $(GAMELIB_SRCS); echo '$(GENFLAGS)') | (shasum -a 256 2>/dev/null || sha256sum) | cut -c1-16)

RT_OBJ   := $(patsubst runtime/%.c,$(B)/rt/%.o,$(RT_SRC))
RTFLAGS  := -O2 -g -fno-strict-aliasing -Wall -Wno-unused-function -Iruntime -Iruntime/nvn $(DEPINC) $(OSFLAGS) $(WINDOWFLAG)
CXXFLAGS := -O2 -g -std=c++17 -I$(IMGUI) -I$(IMGUI)/backends -Iruntime -Iruntime/nvn $(DEPINC) $(WINDOWFLAG)

all: $(EXE) $(if $(GEN_SRC),$(GAMELIB))

$(B)/obj/%.o: $(GEN)/%.c runtime/cpu.h
	@mkdir -p $(dir $@)
	@$(CC) $(GENFLAGS) -c $< -o $@

$(B)/obj/tools/gamelib_entry.o: tools/gamelib_entry.c $(GAMELIB_SRCS)
	@mkdir -p $(dir $@)
	$(CC) $(GENFLAGS) -DGAMELIB_ID='"$(GAMELIB_ID)"' -c $< -o $@
$(B)/rt/gamelib.o: $(GAMELIB_SRCS)
$(B)/rt/gamelib.o: RTFLAGS += -DGAMELIB_ID='"$(GAMELIB_ID)"'
# the start screen's build of it (runtime/gamebuild.c) uses the same flags
$(B)/rt/gamebuild.o: $(GAMELIB_SRCS) Makefile
$(B)/rt/gamebuild.o: RTFLAGS += -DGAMELIB_ID='"$(GAMELIB_ID)"' -DGAMELIB_CFLAGS='"$(strip $(filter-out -Iruntime,$(GENFLAGS)))"' \
                                -DGAMELIB_SHARED='"$(GAMELIB_SHARED)"'

$(B)/rt/%.o: runtime/%.c $(RT_HDRS)
	@mkdir -p $(dir $@)
	$(CC) $(RTFLAGS) -c $< -o $@

# SMAA (third_party/smaa, MIT): the reference shader as a C string for runtime/nvn/smaa_data.c (both backends build
# their passes from it); the non-ASCII bytes in its comments become '?', and its CRLF line ends plain LF (a CR left in
# the string literals ends them early on macOS clang)
$(B)/inc/smaa_hlsl.inc: third_party/smaa/SMAA.hlsl
	@mkdir -p $(dir $@)
	LC_ALL=C tr -d '\r' < $< | LC_ALL=C tr '\200-\377' '?' | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/^/"/' -e 's/$$/\\n"/' > $@
$(B)/rt/nvn/smaa_data.o: $(B)/inc/smaa_hlsl.inc
$(B)/rt/nvn/smaa_data.o: RTFLAGS += -I$(B)/inc -Ithird_party/smaa/Textures
# the shipped shader list (tools/shader_list.py) is in exec.c; the inflater (miniz's tinfl, third_party/miniz) in inflate.c
$(B)/rt/nvn/vulkan/exec.o: runtime/nvn/shader_list.inc
$(B)/rt/nvn/inflate.o: $(wildcard third_party/miniz/*.h) third_party/miniz/miniz_tinfl.c

$(B)/rt/%.o: runtime/%.cpp $(RT_HDRS)
	@mkdir -p $(dir $@)
	$(CXX) $(CXXFLAGS) $(OSFLAGS) -c $< -o $@

# NVIDIA DLSS (runtime/nvn/dlss.h). NVIDIA's SDK has its own license: it is not in this repository and not shipped.
# Linux: make NGX_SDK=<a clone of github.com/NVIDIA/DLSS> links it in. Windows: the executable needs nothing at build
# time; tools/build_ngx_bridge_windows.bat builds 3dworldrecomp_ngx.dll (MSVC) from the same SDK, for next to the exe.
NGX_SDK ?=
ifneq ($(NGX_SDK),)
ifeq ($(PLATFORM),linux)
$(B)/rt/nvn/vulkan/dlss.o: CXXFLAGS += -DHAVE_DLSS -I$(NGX_SDK)/include
$(B)/rt/nvn/vulkan/dlss.o: runtime/nvn/ngx/dlss_ngx.cpp
LDFLAGS += $(NGX_SDK)/lib/Linux_x86_64/libnvsdk_ngx.a
endif
endif

# linked to a temp file, then renamed over: a copy of the game still running keeps its (old) file - relinking in
# place gets running copies killed by macOS (code signature of the changed pages). The temp file keeps the real name
# (in a folder of its own): on Windows the import library records the name the game code library loads it by.
$(EXE): $(RT_OBJ) $(BACKEND_OBJ) $(UI_OBJ) $(IMGUI_OBJ)
	@mkdir -p $(dir $@)link
	$(CXX) -o $(dir $@)link/$(notdir $@) $^ $(LDFLAGS)
	mv -f $(dir $@)link/$(notdir $@) $@

# its id file (<library>.id) says what it was built from without loading it (runtime/gamelib.c)
$(GAMELIB): $(GEN_OBJ) | $(EXE)
	$(CC) $(GAMELIB_LDFLAGS) -o $@.tmp $^
	mv -f $@.tmp $@
	echo $(GAMELIB_ID) > $@.id

$(B)/rt/ui/%.o: runtime/ui/%.mm $(RT_HDRS)
	@mkdir -p $(dir $@)
	$(CXX) $(CXXFLAGS) $(UIFLAGS) -c $< -o $@

$(B)/imgui/%.o: $(IMGUI)/%.cpp
	@mkdir -p $(dir $@)
	$(CXX) $(CXXFLAGS) -c $< -o $@

$(B)/imgui/imgui_impl_%.o: $(IMGUI)/backends/imgui_impl_%.cpp
	@mkdir -p $(dir $@)
	$(CXX) $(CXXFLAGS) -c $< -o $@

# Python: tools/venv (macOS, Linux: bin/python, Windows: Scripts/python.exe)
PY := $(firstword $(wildcard tools/venv/bin/python) $(wildcard tools/venv/Scripts/python.exe))

gen:
	cd tools && ../$(PY) $(GENPY) sdk ../extracted/exefs/sdk $(SDK_BASE) ../$(GEN)/sdk --hle ../runtime/hle/hle_symbols.txt $(GENSIMD)
	cd tools && ../$(PY) $(GENPY) main ../extracted/exefs/main $(GUEST_WINDOW) ../$(GEN)/main $(GENSIMD)

gen-objs: $(GEN_OBJ)

# Runtime objects only (no generated code, no link): quick compile check
runtime-objs: $(RT_OBJ) $(BACKEND_OBJ) $(UI_OBJ)

$(B)/rt/platform/windows_rc.o: runtime/platform/windows.rc docs/icon/icon.ico runtime/platform/windows.manifest
	@mkdir -p $(dir $@)
	$(WINDRES) -I docs/icon -I runtime/platform -O coff $< -o $@

VERSION  := $(shell sed -n 's/^\#define LARECOMP_VERSION "\(.*\)"/\1/p' runtime/ui/launcher.mm)

# macOS: build/3DWorldRecomp.app, runs on macOS $(APP_MIN)+: the game rebuilt for that in build/mac15 against build/deps
# (`make deps`: SDL3, LGPL FFmpeg, the Vulkan loader, MoltenVK, shaderc, Python, from pinned sources), the generator
# helper when built (`make gen-helper` after `make deps`), packaged by tools/bundle_macos.sh. No game files or fonts.
APP_MIN  := 15.0
APP_B    := build/mac15
deps:
	MACOS_MIN=$(APP_MIN) tools/build_deps_macos.sh
app:
	@[ -f build/deps/lib/libSDL3.0.dylib ] || { echo "make deps first"; exit 1; }
	$(MAKE) B=$(APP_B) MACOS_MIN=$(APP_MIN) DEPS=$(CURDIR)/build/deps $(APP_B)/3dworldrecomp
	MACOS_MIN=$(APP_MIN) tools/bundle_macos.sh $(APP_B)/3dworldrecomp

# macOS release disk image (the .app + an Applications shortcut to drag it onto): build/dist/3DWorldRecomp-<v>-macOS.dmg
dmg: app
	tools/make_dmg.sh

# Windows: build/dist/3DWorldRecomp-<version>-windows.zip, top folder "3DWorldRecomp/": the exe, what the start screen
# builds the game code with on the player's machine (make gen-helper,
# tools/fetch_zig.sh slimmed by tools/zig_slim.sh: its runtime built ahead of time, gamelib-src/, the exe's import library)
# and the DLLs they load (runs without MSYS2). No game code. The exe is a release build in $(WIN_B):
# linked against the LGPL FFmpeg from `make deps-windows` (MSYS2's is a GPLv3 build) and without a console window
# (RELEASE=1: the log goes to 3dworldrecomp.log next to the exe, fatal errors show a message box). Its DLLs are looked up
# with build/deps-win/bin first (the FFmpeg DLL names are the same as MSYS2's GPL ones). vulkan-1.dll is left
# out: every Vulkan driver installs the loader in System32. Saves and game files go next to the exe at run time.
# The zip's exe is stripped (strip -s: no DWARF or COFF symbol table - 12 MB down to 3 MB, and no data appended after
# its sections, which virus scanners' heuristics flag as an "overlay"); code, data, exports and relocations stay
# byte for byte, so the game code's import library and a crash log's 3dworldrecomp+<offset> still match. The unstripped
# exe is kept as build/symbols/3dworldrecomp-<version>-windows.exe to read those offsets with:
# addr2line -fpe build/symbols/3dworldrecomp-<version>-windows.exe 0x<0x140000000 + offset>
# Needs: Windows 10+ x64, a Vulkan 1.3 driver, an SSE4.2 CPU (checked at startup; GENARCH x86-64-v3, built as
# x86-64-v2 on the player's PC without AVX2: runtime/gamebuild.c gamebuild_x86_level).
DIST     := build/dist/3DWorldRecomp
WIN_B    := build/win-release
deps-windows:
	tools/build_deps_windows.sh
dist:
	@[ -f build/deps-win/lib/libavcodec.dll.a ] || { echo "make deps-windows first (LGPL FFmpeg)"; exit 1; }
	@[ -d build/helper/3dwgen ] || { echo "make gen-helper first (the game code generator)"; exit 1; }
	@[ -x build/zig/zig.exe ] || { echo "tools/fetch_zig.sh first (the compiler)"; exit 1; }
	@[ -f build/ffx/amd_fidelityfx_upscaler_vk.dll ] || { echo "tools/fetch_ffx.sh first (AMD FSR 3 / 4)"; exit 1; }
	$(MAKE) B=$(WIN_B) DEPS=$(CURDIR)/build/deps-win RELEASE=1 $(WIN_B)/3dworldrecomp.exe
	! nm $(WIN_B)/3dworldrecomp.exe | grep ' f_70' >/dev/null  # (no game code inside)
	rm -rf build/dist && mkdir -p "$(DIST)/gamelib-src"
	strip -s -o "$(DIST)/3dworldrecomp.exe" $(WIN_B)/3dworldrecomp.exe  # (no debug info or symbols: see above)
	mkdir -p build/symbols && cp $(WIN_B)/3dworldrecomp.exe build/symbols/3dworldrecomp-$(VERSION)-windows.exe
	cp $(WIN_B)/3dworldrecomp.dll.a "$(DIST)/"
	tools/zig_slim.sh $(strip $(filter-out -Iruntime,$(GENFLAGS)))  # (zig with its runtime built ahead of time)
	cp -R build/helper/3dwgen "$(DIST)/"
	cp -R build/zig-slim "$(DIST)/zig"
	cp runtime/cpu.h runtime/simd.h runtime/simd_fp.h runtime/gamelib.h tools/gamelib_entry.c runtime/hle/hle_symbols.txt \
	    "$(DIST)/gamelib-src/"
	cp third_party/fonts/Baloo2/Baloo2-SemiBold.ttf "$(DIST)/"  # (start screen font, OFL)
	cp third_party/fonts/Baloo2/OFL.txt "$(DIST)/Baloo2-OFL.txt"
	[ ! -f recomplauncher.json ] || cp recomplauncher.json "$(DIST)/"  # (RecompLauncher's profile, when there is one)
	cp README.md LICENSE "$(DIST)/"  # (licenses and source links of the bundled components: README "License")
	cp build/ffx/amd_fidelityfx_loader_vk.dll build/ffx/amd_fidelityfx_upscaler_vk.dll build/ffx/AMD-FSR-LICENSE.md "$(DIST)/"  # (FSR 3 / 4)
	PATH="$(CURDIR)/build/deps-win/bin:$$PATH" ldd $(WIN_B)/3dworldrecomp.exe | awk '(/ucrt64/ || /deps-win/) && !/vulkan-1/ {print $$3}' | sort -u | \
	    xargs -I{} cp -u {} "$(DIST)/"
	! ls "$(DIST)" | grep -iE 'x264|x265|xvid|postproc'  # (no GPL codec libraries in the release)
	cd build/dist && if command -v zip >/dev/null; then zip -qr "3DWorldRecomp-$(VERSION)-windows.zip" "3DWorldRecomp"; \
	    else /c/Windows/System32/tar.exe -a -cf "3DWorldRecomp-$(VERSION)-windows.zip" "3DWorldRecomp"; fi
	@echo "build/dist/3DWorldRecomp-$(VERSION)-windows.zip"

# The generator's helper is frozen by PyInstaller in its own venv (build/gen-venv). PyInstaller only builds for the
# OS it runs on. Windows: a python.org CPython 3.12, e.g. make gen-helper GEN_PY="py -3.12".
ifeq ($(PLATFORM),macos)
GEN_PY  ?= $(firstword $(wildcard build/deps/python/bin/python3.12) python3.12)
GEN_VPY := build/gen-venv/bin/python
else
GEN_PY  ?= py -3.12
GEN_VPY := build/gen-venv/Scripts/python.exe
endif

# The game code generator, the same way (tools/3dwgen.spec): build/helper/3dwgen/, shipped as 3dwgen/ next to the exe or
# in Contents/Resources. The start screen's setup runs it on the player's own game files (runtime/gamebuild.c).
gen-helper: build/gen-venv/.ok
	$(if $(filter windows,$(PLATFORM)),USERPROFILE="$$(cygpath -w ~ 2>/dev/null || echo $$HOME)") \
	$(GEN_VPY) -m PyInstaller --noconfirm --clean --log-level WARN --distpath build/helper --workpath build/pyinstaller \
	    tools/3dwgen.spec
	$(if $(filter windows,$(PLATFORM)),$(GEN_VPY) tools/pe_no_cfg.py build/helper/3dwgen/3dwgen.exe)
	@du -sh build/helper/3dwgen

build/gen-venv/.ok:
	$(GEN_PY) -m venv build/gen-venv
	$(GEN_VPY) -m pip install -q capstone==5.0.9 unicorn==2.1.4 lz4==4.4.5 pyinstaller==6.22.3
	touch $@

# Linux: build/dist/3DWorldRecomp-<version>-linux-<arch>.AppImage, built in Ubuntu 22.04 containers (podman) with SDL3, LGPL
# FFmpeg, shaderc and the game code generator helper inside; the Vulkan loader and GPU drivers are the system's.
# `make appimage` (ARCH: this machine's, or aarch64 cross-compiled), `make appimages` both. See docs/linux.md.
appimage:
	tools/linux/appimage.sh $(ARCH)
appimages:
	tools/linux/appimage.sh x86_64
	tools/linux/appimage.sh aarch64

.PHONY: dmg all gen gen-helper gen-objs runtime-objs deps deps-windows app dist appimage appimages
