# Savage Wind build
# macOS: Homebrew clang/SDL3/FFmpeg, Metal 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

# B: build dir. MACOS_MIN: oldest macOS to run on (default: this one). DEPS: prefix with SDL3 / FFmpeg instead of
# Homebrew's (make deps). `make app` sets all three (build/mac15, 15.0, build/deps); plain `make` uses none.
B         ?= build
MACOS_MIN ?=
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
# RECOMP_LOCALS=1 (the default since Alpha 5): the generator keeps each function's most used registers and its flags in
# C locals (gen.py --locals, docs/RECOMP-LOCALS.md); RECOMP_LOCALS=0 builds the plain game code. It is part of
# GAMELIB_ID, so a library built one way is never loaded for the other.
RECOMP_LOCALS ?= 1
GENLOCALS := $(if $(filter 1,$(RECOMP_LOCALS)),--locals)
# The start screen's zig cc reads -O1 as its own "fast" mode (clang -O2 with the loop and SLP vectorizers) and adds
# debug info and frame pointers: these give it what clang -O1 builds here, in a third less time (runtime/gamebuild.c)
GENFLAGS_ZIG := -Xclang $(filter -O%,$(GENFLAGS)) -fno-vectorize -fno-slp-vectorize -g0 -fomit-frame-pointer

# 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)/layout.c, then a folder per module (main, subsdk*, sdk)
GEN_SRC  := $(wildcard $(GEN)/*.c) $(wildcard $(GEN)/*/*.c)
GEN_OBJ  := $(patsubst %.c,$(B)/obj/%.o,$(patsubst $(GEN)/%,%,$(GEN_SRC))) $(B)/obj/tools/gamelib_entry.o
RT_SRC   := $(filter-out runtime/control.c runtime/control_game.c,$(wildcard runtime/*.c)) \
            runtime/control.c runtime/control_game.c $(wildcard runtime/hle/*.c) $(wildcard runtime/services/*.c) \
            $(wildcard runtime/nvn/*.c) $(wildcard runtime/nvn/maxwell/*.c) runtime/platform/$(PLATFORM).c
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) \
            $(wildcard runtime/services/*.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)/savagewind
DEPINC   := -I$(SDL)/include -I$(FFMPEG)/include
LDFLAGS  := -L$(SDL)/lib -lSDL3 -Wl,-rpath,$(SDL)/lib -L$(FFMPEG)/lib -lavformat -lavcodec -lavutil -lswscale -Wl,-rpath,$(FFMPEG)/lib \
            -framework CoreFoundation -framework Foundation -framework Metal -framework MetalFX -framework QuartzCore -framework AppKit -framework ImageIO -framework CoreGraphics -framework UniformTypeIdentifiers
BACKEND_SRC := $(wildcard runtime/nvn/*.m)
BACKEND_OBJ := $(patsubst runtime/%.m,$(B)/rt/%.o,$(BACKEND_SRC))
IMGUI_OBJ += $(B)/imgui/imgui_impl_metal.o
UIFLAGS  := -fobjc-arc
GAMELIB  := $(B)/swgame.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),linux)
EXE      := $(B)/savagewind
DEPINC   := $(if $(DEPS),-I$(DEPS)/include,$(shell pkg-config --cflags libavformat 2>/dev/null))  # (openSUSE has them in /usr/include/ffmpeg)
ifeq ($(ARCH),x86_64)
GENARCH  ?= -march=x86-64-v3  # as on Windows: AVX2 + FMA for the lifted FP/SIMD code (checked at startup)
GENARCH_COMPAT ?= -march=x86-64-v2  # CPUs without them (GAMELIB_ID_COMPAT below)
endif
GENFLAGS += $(GENARCH) -fPIC
OSFLAGS  := -Wno-format  # (%llx for uint64_t, which is unsigned long here: the same size)
# shaderc is libshaderc.so on Debian / Ubuntu and libshaderc_shared.so on Fedora, Arch and a shaderc built from source:
# tools/linux/build_deps.sh builds only the shaderc_shared target, so a DEPS prefix has no libshaderc.so at all - -lshaderc
# there would silently fall through to the system path, where Arch's shaderc package has a static libshaderc.a that is
# only the C wrapper (undefined shaderc_util symbols at the real link). A DEPS prefix therefore links -lshaderc_shared.
# Elsewhere pkg-config knows the name. Without a .pc, the probe links an executable that calls shaderc and tries
# -lshaderc_shared before -lshaderc, so an incomplete static libshaderc.a is rejected at probe time too. A shared-only
# probe cannot do that: a shared link keeps undefined symbols and only the executable link or run fails.
SHADERC_TEST := extern void *shaderc_compiler_initialize(void); int main(void){return shaderc_compiler_initialize()==0;}
SHADERC  ?= $(if $(DEPS),-lshaderc_shared,$(or $(shell pkg-config --libs shaderc 2>/dev/null),\
             $(shell echo '$(SHADERC_TEST)' | $(CC) -x c - -lshaderc_shared -o /dev/null 2>/dev/null && echo -lshaderc_shared),\
             $(shell echo '$(SHADERC_TEST)' | $(CC) -x c - -lshaderc -o /dev/null 2>/dev/null && echo -lshaderc),-lshaderc))
# -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) -lz -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++ apart from __APPLE__ blocks
GAMELIB  := $(B)/swgame.so
GAMELIB_LDFLAGS := -shared -fuse-ld=lld  # (the runtime functions it calls: the app's own, -rdynamic)
GAMELIB_SHARED := -shared
else
EXE      := $(B)/savagewind.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)
GENARCH_COMPAT ?= -march=x86-64-v2  # CPUs without them (GAMELIB_ID_COMPAT below)
GENFLAGS += -D_FILE_OFFSET_BITS=64 $(GENARCH)
# --stack: every thread's default stack, reserved (committed as it grows): 256 MB, the guest threads' recursion runs on
# it (runtime/kernel.c thread_start)
LDFLAGS  := -fuse-ld=lld -Wl,--stack,268435456 $(if $(DEPS),-L$(DEPS)/lib) -lSDL3 -lavformat -lavcodec -lavutil -lswscale \
            -lvulkan-1 -lwinmm -lole32 -lshell32 -lcomdlg32 -luuid -lgdi32 -ladvapi32 -lshaderc_shared -lpdh -lws2_32 -lwinhttp -l:libz.a -lpthread \
            $(if $(RELEASE),-Wl$(comma)--subsystem$(comma)windows)  # release: no console window (log -> savagewind.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++ apart from __APPLE__ blocks
GAMELIB  := $(B)/swgame.dll
# the runtime functions it calls: exported by the .exe, linked through its import library
LDFLAGS  += -Wl,--export-all-symbols -Wl,--out-implib,$(B)/savagewind.dll.a
GAMELIB_LDFLAGS := -shared -fuse-ld=lld $(B)/savagewind.dll.a
GAMELIB_SHARED := -shared  # (+ the import library: runtime/gamebuild.c)
# "Savage Wind Configuration.exe" in the release: starts savagewind.exe --config (runtime/platform/windows_config.c)
CONFIG_EXE := $(B)/savagewind-config.exe
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.
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/regs.py tools/flags.py tools/gamelib_entry.c runtime/hle/hle_symbols.txt \
                runtime/cpu.h runtime/simd.h runtime/simd_fp.h runtime/simd_softfma.h runtime/gamelib.h
GAMELIB_SRCS += tools/layout.py tools/game_sites.py
GAMELIB_ID := $(shell (cat $(GAMELIB_SRCS); echo '$(strip $(GENFLAGS))'; echo '$(GENFLAGS_ZIG)'; echo 'gen $(GENLOCALS)') | (shasum -a 256 2>/dev/null || sha256sum) | cut -c1-16)
# The compatible target (#9): x86-64 CPUs without AVX2 / FMA / BMI2 get the game code built with GENARCH_COMPAT in
# place of GENARCH (no -mfma: simd.h's fma is runtime/simd_softfma.h, slower). The start screen builds the one the CPU
# runs (runtime/gamelib.h gamelib_compat); its id differs, so neither library is ever loaded in place of the other.
# `make` builds the GENARCH one.
ifneq ($(strip $(GENARCH)),)
ifneq ($(strip $(GENARCH_COMPAT)),)
GENFLAGS_COMPAT := $(subst $(strip $(GENARCH)),$(strip $(GENARCH_COMPAT)),$(GENFLAGS))
GAMELIB_ID_COMPAT := $(shell (cat $(GAMELIB_SRCS); echo '$(strip $(GENFLAGS_COMPAT))'; echo '$(GENFLAGS_ZIG)'; echo 'gen $(GENLOCALS)') | (shasum -a 256 2>/dev/null || sha256sum) | cut -c1-16)
GAMELIB_TARGETS := -DGAMELIB_ARCH='"$(strip $(GENARCH))"' -DGAMELIB_ARCH_COMPAT='"$(strip $(GENARCH_COMPAT))"' \
                   -DGAMELIB_ID_COMPAT='"$(GAMELIB_ID_COMPAT)"'
endif
endif

# TRANSLATOR_ID / SPIRV_ID: what translated shaders and their SPIR-V are made from: the Maxwell translator (its
# source and the header with the key and the output structures it fills), and the GLSL -> SPIR-V step. The shader
# caches (cache/xlate, cache/spirv, the pipeline list, the precompiled libraries) are kept while these stay the same,
# so builds and updates that do not touch those sources keep them; the device-dependent switches the translator reads
# at run time are not in here (runtime/nvn/maxwell/translate.c maxwell_translation_variant: a translation records
# them itself). Baked into the generated header $(B)/inc/shader_ids.h, rewritten only when a hash changes, which
# translate.o and spirv.o include ahead of their source (-include) and depend on.
TRANSLATOR_SRCS := runtime/nvn/maxwell/translate.c runtime/nvn/maxwell/shader.h
SPIRV_SRCS := runtime/nvn/vulkan/spirv.c
TRANSLATOR_ID := $(shell cat $(TRANSLATOR_SRCS) | (shasum -a 256 2>/dev/null || sha256sum) | cut -c1-16)
SPIRV_ID := $(shell cat $(SPIRV_SRCS) | (shasum -a 256 2>/dev/null || sha256sum) | cut -c1-16)
SHADER_IDS := $(B)/inc/shader_ids.h
# (compared with cat and test, not cmp: MSYS2 has no diffutils unless installed, and a rewrite at every make would
# recompile the translator each time)
$(shell mkdir -p $(B)/inc && printf '#define TRANSLATOR_ID "%s"\n#define SPIRV_ID "%s"\n' '$(TRANSLATOR_ID)' '$(SPIRV_ID)' > $(SHADER_IDS).new && \
        if [ "$$(cat $(SHADER_IDS) 2>/dev/null)" = "$$(cat $(SHADER_IDS).new)" ]; then rm -f $(SHADER_IDS).new; else mv -f $(SHADER_IDS).new $(SHADER_IDS); fi)

# SW_SOURCE: the source this build is made from, in the log's first line (runtime/main.c): its commit and tree, and
# "modified" when the runtime, the tools or this Makefile differ from them ("unknown" outside a git checkout). A
# commit published to test has the tree of the local commit it was made from. $(B)/source_id follows it, so main.o is
# rebuilt when it changes.
comma    := ,
SW_SOURCE := $(or $(shell git log -1 --format='commit %h, tree %t' 2>/dev/null),unknown)$(if $(shell git status --porcelain --untracked-files=no -- runtime tools Makefile 2>/dev/null),$(comma) modified)
$(shell mkdir -p $(B) && [ "$$(cat $(B)/source_id 2>/dev/null)" = '$(SW_SOURCE)' ] || echo '$(SW_SOURCE)' > $(B)/source_id)

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

# Optional runtime-only optimization. The generated game library keeps GENFLAGS and its build ID.
# Use a separate B for each mode; the stamp also rebuilds runtime objects when flags or profiles change.
# Profile-guided build of the runtime (not the game library). tools/pgo/runtime.profdata is a ready profile, so
#   make PGO=use B=build-pgo            optimized build, no training needed
# is all most people need. To make a new profile (a profile only fits the clang that wrote it, and goes stale as
# the runtime changes; see tools/pgo/README.md), each step with its own B:
#   make PGO=gen B=build-gen            instrumented savagewind.exe
#   run it (a scripted walk ending with SAVAGEWIND_EXIT_AT=<frame>, or by hand) with LLVM_PROFILE_FILE=<dir>/rt-%p.profraw
#   llvm-profdata merge -o tools/pgo/runtime.profdata <dir>/*.profraw
PGO ?=
LTO ?=
PGO_PROFILE ?= tools/pgo/runtime.profdata
ifneq ($(filter-out gen use,$(PGO)),)
$(error PGO must be empty, gen, or use)
endif
ifneq ($(filter-out thin,$(LTO)),)
$(error LTO must be empty or thin)
endif
RUNTIME_OPTFLAGS := $(if $(LTO),-flto=thin)
RUNTIME_LINKFLAGS := $(if $(LTO),-flto=thin)
ifeq ($(PGO),gen)
RUNTIME_OPTFLAGS += -fprofile-instr-generate -fprofile-update=atomic -mllvm -enable-value-profiling=false -DSW_PGO_GENERATE=1
RUNTIME_LINKFLAGS += -fprofile-instr-generate
endif
ifeq ($(PGO),use)
ifeq ($(wildcard $(PGO_PROFILE)),)
$(error PGO=use needs PGO_PROFILE pointing to a merged runtime profile)
endif
RUNTIME_OPTFLAGS += -fprofile-instr-use=$(PGO_PROFILE)
endif
LDFLAGS += $(RUNTIME_LINKFLAGS)
RUNTIME_CONFIG := $(strip $(RUNTIME_OPTFLAGS))
$(shell mkdir -p $(B) && [ -f $(B)/runtime_config ] && [ "$$(cat $(B)/runtime_config 2>/dev/null)" = '$(RUNTIME_CONFIG)' ] || echo '$(RUNTIME_CONFIG)' > $(B)/runtime_config)
$(RT_OBJ) $(filter $(B)/rt/%,$(BACKEND_OBJ)) $(UI_OBJ): $(B)/runtime_config $(if $(filter use,$(PGO)),$(PGO_PROFILE))

.DEFAULT_GOAL := all

# AMD FidelityFX SDK 1.1.4 (third_party/FidelityFX, MIT): FSR 3 frame interpolation and optical flow
# (runtime/nvn/vulkan/framegen.cpp) and the FSR 3 upscaler (runtime/nvn/vulkan/fsr3.cpp) on its Vulkan backend. Its
# sources unchanged, with ffx_compat.h for what MSVC's headers bring; the shaders are tools/ffx_shaders.py's
# (third_party/FidelityFX/spirv).
FFX      := third_party/FidelityFX
FFX_SRC  := $(FFX)/sdk/src/components/frameinterpolation/ffx_frameinterpolation.cpp \
            $(FFX)/sdk/src/components/opticalflow/ffx_opticalflow.cpp \
            $(FFX)/sdk/src/components/fsr3upscaler/ffx_fsr3upscaler.cpp $(FFX)/sdk/src/backends/vk/ffx_vk.cpp \
            $(wildcard $(FFX)/sdk/src/shared/*.cpp)
FFX_OBJ  := $(patsubst $(FFX)/sdk/src/%.cpp,$(B)/ffx/%.o,$(FFX_SRC))
FFX_INC  := -I$(FFX)/sdk/include -I$(FFX)/sdk/src/components -I$(FFX)/sdk/src/shared -I$(FFX)/sdk/src/backends/shared
ifneq ($(PLATFORM),macos)
BACKEND_OBJ += $(FFX_OBJ)
$(B)/rt/nvn/vulkan/fsr3.o: CXXFLAGS := -DSW_FSR3=1 -include $(FFX)/ffx_compat.h $(FFX_INC) $(CXXFLAGS)
endif
$(B)/ffx/%.o: $(FFX)/sdk/src/%.cpp $(FFX)/ffx_compat.h
	@mkdir -p $(dir $@)
	$(CXX) -O2 -g -std=c++17 -w -include $(FFX)/ffx_compat.h $(FFX_INC) -I$(FFX)/sdk/include/FidelityFX/gpu $(DEPINC) -c $< -o $@
# (the SDK's headers ahead of $(DEPINC)'s: another copy of them there, from a build of the SDK, has other context
# sizes, and a context smaller than the SDK's own code writes overran the next one in memory)
$(B)/rt/nvn/vulkan/framegen.o: CXXFLAGS := -include $(FFX)/ffx_compat.h $(FFX_INC) -I$(FFX)/spirv $(CXXFLAGS)
$(B)/rt/nvn/vulkan/framegen.o: $(FFX)/spirv/ffx_shaders_vk.h $(FFX)/spirv/ffx_fsr3upscaler_vk.h $(FFX)/ffx_compat.h

all: $(EXE) $(CONFIG_EXE) $(if $(strip $(GEN_SRC)),$(GAMELIB))  # (GEN_SRC is a space when there is no generated/)

$(B)/obj/%.o: $(GEN)/%.c runtime/cpu.h runtime/simd.h runtime/simd_fp.h runtime/simd_softfma.h  # (cpu.h includes them)
	@mkdir -p $(dir $@)
	@$(CC) $(GENFLAGS) -c $< -o $@
$(B)/obj/layout.o: runtime/gamelib.h

$(B)/obj/tools/gamelib_entry.o: tools/gamelib_entry.c $(GAMELIB_SRCS) Makefile  # (the id: the flags are in here too)
	@mkdir -p $(dir $@)
	$(CC) $(GENFLAGS) -DGAMELIB_ID='"$(GAMELIB_ID)"' -c $< -o $@
$(B)/rt/nvn/maxwell/translate.o $(B)/rt/nvn/vulkan/spirv.o: $(SHADER_IDS)
$(B)/rt/nvn/maxwell/translate.o $(B)/rt/nvn/vulkan/spirv.o: RTFLAGS += -include $(SHADER_IDS)
$(B)/rt/main.o: $(B)/source_id
$(B)/rt/main.o: RTFLAGS += -DSW_SOURCE='"$(SW_SOURCE)"'
$(B)/rt/gamelib.o: $(GAMELIB_SRCS) Makefile
$(B)/rt/gamelib.o: RTFLAGS += -DGAMELIB_ID='"$(GAMELIB_ID)"' $(GAMELIB_TARGETS)
# 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_CFLAGS='"$(strip $(filter-out -Iruntime,$(GENFLAGS)))"' \
                                $(if $(GENFLAGS_COMPAT),-DGAMELIB_CFLAGS_COMPAT='"$(strip $(filter-out -Iruntime,$(GENFLAGS_COMPAT)))"') \
                                -DGAMELIB_ZIGFLAGS='"$(GENFLAGS_ZIG)"' -DGAMELIB_SHARED='"$(GAMELIB_SHARED)"' -DGAMELIB_GENARGS='"$(GENLOCALS)"'

# The profiler's Windows sampler guards its stack walks with SEH (__try).
$(B)/rt/prof_sampler.o: RTFLAGS += -fms-extensions
# Windows guarded memory scans use SEH.
$(B)/rt/memscan_os.o: RTFLAGS += -fms-extensions

$(B)/rt/control_places.o: runtime/control_places_data.inc  # (the generated table of shrines, Koroks ...)

$(B)/rt/%.o: runtime/%.c $(RT_HDRS)
	@mkdir -p $(dir $@)
	$(CC) $(RTFLAGS) $(RUNTIME_OPTFLAGS) -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

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

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

# 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/i18n.o: $(wildcard runtime/ui/i18n/*.inc) runtime/ui/i18n.h
$(B)/rt/ui/%.o: runtime/ui/%.mm $(RT_HDRS)
	@mkdir -p $(dir $@)
	$(CXX) $(CXXFLAGS) $(RUNTIME_OPTFLAGS) $(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 $@

$(B)/imgui/imgui_impl_metal.o: $(IMGUI)/backends/imgui_impl_metal.mm
	@mkdir -p $(dir $@)
	$(CXX) $(CXXFLAGS) -fobjc-arc -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))

# GENARGS=--any-version: a game version not supported yet (tools/game_sites.py; docs/SAVAGE-WIND.md)
gen:  # every module of the exefs, at the addresses tools/layout.py gives them
	cd tools && ../$(PY) gen.py all ../extracted/exefs ../$(GEN) --hle ../runtime/hle/hle_symbols.txt $(GENSIMD) $(GENLOCALS) $(GENARGS)

gen-objs: $(GEN_OBJ)

# Discord Rich Presence's place names: the game's own text, written from your extracted/ and never committed
ifneq ($(wildcard extracted/romfs/Pack/Bootup.pack),)
PLACE_PY := $(firstword $(PY) python3)
runtime/game_place_table.inc: tools/gen_place_table.py
	$(PLACE_PY) tools/gen_place_table.py extracted/romfs/Pack $@
$(B)/rt/game_place.o: runtime/game_place_table.inc
endif

# 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 runtime/platform/windows.manifest docs/icon/icon.ico
	@mkdir -p $(dir $@)
	$(WINDRES) -I docs/icon -I runtime/platform -O coff $< -o $@

$(B)/rt/platform/windows_config.o: runtime/platform/windows_config.c
	@mkdir -p $(dir $@)
	$(CC) -O2 -Wall $(OSFLAGS) -c $< -o $@
$(B)/savagewind-config.exe: $(B)/rt/platform/windows_config.o $(B)/rt/platform/windows_rc.o
	$(CC) -o $@ $^ -fuse-ld=lld -Wl,--subsystem,windows

# "SW Update.exe" in the release (runtime/platform/windows_update.c): static, it replaces every DLL next to it
SW_UPDATE_LIBS := -static -fuse-ld=lld -municode -Wl,--subsystem,windows -lwinhttp -lbcrypt -lcomctl32 -lshell32 -luser32 -lgdi32
$(B)/rt/platform/sw_update_rc.o: runtime/platform/sw_update.rc runtime/platform/sw_update.manifest docs/icon/icon.ico
	@mkdir -p $(dir $@)
	$(WINDRES) -I docs/icon -I runtime/platform -O coff $< -o $@
$(B)/rt/platform/windows_update.o: runtime/platform/windows_update.c runtime/update_core.h runtime/platform/sw_update_key.h
	@mkdir -p $(dir $@)
	$(CC) -O2 -Wall -Ithird_party/stb -c $< -o $@
$(B)/rt/platform/sw_update_core.o: runtime/update_core.c runtime/update_core.h
	@mkdir -p $(dir $@)
	$(CC) -O2 -Wall -c $< -o $@
$(B)/sw-update.exe: $(B)/rt/platform/windows_update.o $(B)/rt/platform/sw_update_core.o $(B)/rt/platform/sw_update_rc.o
	$(CC) -o $@ $^ $(SW_UPDATE_LIBS)

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

# macOS: build/Savage Wind.app, runs on macOS $(APP_MIN)+: the game rebuilt for that in build/mac15 against build/deps
# (`make deps`: SDL3, LGPL FFmpeg, 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)/savagewind
	MACOS_MIN=$(APP_MIN) tools/bundle_macos.sh $(APP_B)/savagewind

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

# Windows: build/dist/SavageWind-<version>-windows.zip, top folder "Savage Wind/": 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 savagewind.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.
# Needs: Windows 10+ x64, a Vulkan 1.3 driver, an SSE4.2 CPU (GENARCH_COMPAT x86-64-v2; checked at startup).
DIST     := build/dist/Savage Wind
WIN_B    := build/win-release
# The release runtime is profile-guided with ThinLTO (tools/pgo/runtime.profdata: +19..33% fps at 1080p/1440p TAA on a
# 5700X3D + 3080 Ti, see tools/pgo/README.md). DIST_PGO= and DIST_LTO= (empty) build it plain, e.g. with a clang other
# than the one that wrote the profile.
DIST_PGO ?= use
DIST_LTO ?= thin
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/swgen ] || { echo "make gen-helper first (the game code generator)"; exit 1; }
	@! find tools -maxdepth 1 -name '*.py' -newer build/helper/swgen/swgen.exe | grep -q . || \
	    { echo "make gen-helper first: tools/*.py changed since build/helper/swgen was frozen"; exit 1; }
	@[ -x build/zig/zig.exe ] || { echo "tools/fetch_zig.sh first (the compiler)"; exit 1; }
	$(MAKE) B=$(WIN_B) DEPS=$(CURDIR)/build/deps-win RELEASE=1 PGO=$(DIST_PGO) LTO=$(DIST_LTO) $(WIN_B)/savagewind.exe $(WIN_B)/savagewind-config.exe $(WIN_B)/sw-update.exe
	! nm $(WIN_B)/savagewind.exe | grep ' f_70' >/dev/null  # (no game code inside)
	rm -rf build/dist && mkdir -p "$(DIST)/gamelib-src"
	cp $(WIN_B)/savagewind.exe $(WIN_B)/savagewind.dll.a "$(DIST)/"
	cp $(WIN_B)/savagewind-config.exe "$(DIST)/Savage Wind Configuration.exe"
	cp $(WIN_B)/sw-update.exe "$(DIST)/SW Update.exe"
	tools/zig_slim.sh $(strip $(filter-out -Iruntime,$(GENFLAGS))) \
	    $(if $(GENFLAGS_COMPAT),-- $(strip $(filter-out -Iruntime,$(GENFLAGS_COMPAT))))  # (zig, its runtime built ahead of time)
	cp -R build/helper/swgen "$(DIST)/"
	cp -R build/zig-slim "$(DIST)/zig"
	cp runtime/cpu.h runtime/simd.h runtime/simd_fp.h runtime/simd_softfma.h runtime/gamelib.h tools/gamelib_entry.c \
	    runtime/hle/hle_symbols.txt "$(DIST)/gamelib-src/"
	cp docs/icon/icon_1024.png "$(DIST)/icon.png"
	cp runtime/nvn/vulkan/vk_pipelines.seed "$(DIST)/"  # (the pipeline seed the precompilation reads: hashes and render state, nothing of the game)
	cp third_party/fonts/FiraSans/FiraSans-SemiBold.ttf third_party/fonts/FiraSans/FiraSans-Medium.ttf "$(DIST)/"  # (menus, OFL)
	cp third_party/fonts/FiraSans/OFL.txt "$(DIST)/FiraSans-OFL.txt"
	cp third_party/fonts/NotoSansThai/NotoSansThai-Medium.ttf "$(DIST)/"  # (Thai menus, OFL)
	cp third_party/fonts/NotoSansThai/OFL.txt "$(DIST)/NotoSansThai-OFL.txt"
	cp third_party/fonts/NotoSansHebrew/NotoSansHebrew-Medium.ttf "$(DIST)/"  # (Hebrew menus, OFL)
	cp third_party/fonts/NotoSansHebrew/OFL.txt "$(DIST)/NotoSansHebrew-OFL.txt"
	cp third_party/FidelityFX/LICENSE.txt "$(DIST)/FidelityFX-LICENSE.txt"  # (AMD FidelityFX SDK, MIT: README "License")
	if [ -f build/fsr-dlls/amd_fidelityfx_loader_vk.dll ]; then cp build/fsr-dlls/amd_fidelityfx_*_vk.dll \
	    build/fsr-dlls/AMD-FidelityFX-DLL-LICENSE.txt "$(DIST)/"; fi  # (AMD FSR 4: tools/fetch_fsr_dlls.py; AMD's licence allows binary redistribution with this notice)
	mkdir "$(DIST)/colour-luts" && cp third_party/luts/*.cube third_party/luts/README.md "$(DIST)/colour-luts/"  # (CC0: Video > Colour)
	cp README.md LICENSE "$(DIST)/"  # (licenses and source links of the bundled components: README "License")
	cp recomplauncher.json "$(DIST)/"  # (RecompLauncher reads it from the release to set the game up: next to the exe)
	PATH="$(CURDIR)/build/deps-win/bin:$$PATH" ldd $(WIN_B)/savagewind.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)
	! ls "$(DIST)" | grep -i splash  # (no start screen picture: the player's own, never shipped)
	python3 tools/make_update_manifest.py "$(DIST)" "$(VERSION)"  # (what SW Update checks and replaces: this list, nothing else)
	cd build/dist && if command -v zip >/dev/null; then zip -qr "SavageWind-$(VERSION)-windows.zip" "Savage Wind"; \
	    else /c/Windows/System32/tar.exe -a -cf "SavageWind-$(VERSION)-windows.zip" "Savage Wind"; fi
	@echo "build/dist/SavageWind-$(VERSION)-windows.zip"

# The game code generator as a standalone helper, so players need no Python: build/helper/swgen/ (swgen[.exe] +
# _internal/), frozen by PyInstaller from tools/swgen.spec in its own venv (build/gen-venv). Shipped as swgen/ next to
# the exe (Windows, Linux) or in "Savage Wind.app"/Contents/Resources. The start screen's setup runs it on the player's own
# game files (runtime/gamebuild.c). PyInstaller only builds for the OS it runs on.
# macOS arm64: the relocatable Python 3.12 from `make deps` (macOS 11+ / 15+: the helper runs where the app does);
#   without it Homebrew's python@3.12 (then only on the macOS it was built for).
# Windows x86-64: from the MSYS2 shell with a python.org CPython 3.12 (prebuilt unicorn / capstone wheels), e.g.
#   make gen-helper GEN_PY="/c/Users/<you>/AppData/Local/Programs/Python/Python312/python.exe"
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

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/swgen.spec
	$(if $(filter windows,$(PLATFORM)),$(GEN_VPY) tools/pe_no_cfg.py build/helper/swgen/swgen.exe)
	@du -sh build/helper/swgen

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/Savage_Wind-<version>-<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

build/test_shaders: tools/test_shaders.m runtime/nvn/maxwell/translate.c runtime/nvn/maxwell/shader.h
	clang -O1 -fobjc-arc -framework Metal -framework Foundation -o $@ tools/test_shaders.m runtime/nvn/maxwell/translate.c

build/test_romfs: tools/test_romfs.c runtime/romfs_build.c runtime/romfs_image.c runtime/romfs_build.h runtime/romfs_image.h
	clang -O1 -Iruntime -o $@ tools/test_romfs.c runtime/romfs_build.c runtime/romfs_image.c -lpthread

$(B)/test_bind_capture: tools/test_bind_capture.c runtime/hle/bindings.c runtime/input_bind.h
	@mkdir -p $(B)
	$(CC) -O1 -DSDL_STATIC_LIB $(OSFLAGS) $(DEPINC) -Iruntime -o $@ tools/test_bind_capture.c runtime/hle/bindings.c -lSDL3

test-bind-capture: $(B)/test_bind_capture
	$(B)/test_bind_capture

.PHONY: test-bind-capture

# Per-action bindings (docs/ACTIONS.md): the answers to the game's hold / pressed queries, menus, shared keys, capture and
# savagewind.ini, then the patch the hook is written with (no game files)
$(B)/test_actions: tools/test_actions.c runtime/hle/bindings.c runtime/input_bind.h
	@mkdir -p $(B)
	$(CC) -O1 -DSDL_STATIC_LIB $(OSFLAGS) $(DEPINC) -Iruntime -o $@ tools/test_actions.c runtime/hle/bindings.c -lSDL3

test-actions: $(B)/test_actions
	$(B)/test_actions
	python3 tools/test_act_site.py

.PHONY: test-actions

$(B)/test_pc_controls: tests/test_pc_controls.c runtime/hle/input.c runtime/hle/bindings.c runtime/settings.h
	@mkdir -p $(dir $@)
	$(CC) -O2 -ffunction-sections -fdata-sections -DSDL_STATIC_LIB $(OSFLAGS) $(DEPINC) -Iruntime -isystem third_party -o $@ $< -fuse-ld=lld -Wl,--gc-sections $(if $(filter windows,$(PLATFORM)),-Wl$(comma)--exclude-all-symbols) -lSDL3 -lm

$(B)/test_pc_settings: tests/test_pc_settings.c runtime/settings.c runtime/settings.h runtime/hle/bindings.c
	@mkdir -p $(dir $@)
	$(CC) -O1 -DSDL_STATIC_LIB $(OSFLAGS) $(DEPINC) -Iruntime -o $@ $< -lSDL3 -lm

$(B)/test_game_place: tests/test_game_place.c runtime/game_place.c runtime/game_place.h runtime/game_place_table.inc
	@mkdir -p $(dir $@)
	$(CC) -O1 -Iruntime -o $@ $<

$(B)/test_discord_rpc: tests/test_discord_rpc.c runtime/discord_rpc.c runtime/discord_rpc.h
	@mkdir -p $(dir $@)
	$(CC) -O1 -Iruntime -o $@ $<

$(B)/test_options_pointer: tests/test_options_pointer.c runtime/pc_cursor.c runtime/pc_cursor.h runtime/pc_cursor_math.h runtime/nvn/hud_scale.h
	@mkdir -p $(dir $@)
	$(CC) -O2 -ffunction-sections -fdata-sections -DSDL_STATIC_LIB $(OSFLAGS) $(DEPINC) -Iruntime -isystem third_party -o $@ $< -fuse-ld=lld -Wl,--gc-sections $(if $(filter windows,$(PLATFORM)),-Wl$(comma)--exclude-all-symbols) -lSDL3 -lm

test-pc-controls: $(B)/test_pc_controls $(B)/test_pc_settings $(B)/test_options_pointer
	$(B)/test_pc_controls
	$(B)/test_options_pointer
	@set -e; tmp=$$(mktemp); trap 'rm -f "$$tmp"' EXIT; \
	 printf 'settings_version = 3\npc_cursor = 1\n' > "$$tmp"; \
	 $(B)/test_pc_settings "$$tmp" 1 1 0 0; \
	 $(B)/test_pc_settings "$$tmp" 0 0 1 1; \
	 SAVAGEWIND_PC_CURSOR=0 $(B)/test_pc_settings "$$tmp" 0 1 2 2

.PHONY: test-pc-controls

$(B)/test_output_scale: tests/test_output_scale.c runtime/nvn/output_scale.c $(RT_HDRS)
	@mkdir -p $(B)
	$(CC) -O1 -ffunction-sections -fdata-sections $(OSFLAGS) $(DEPINC) -Iruntime -o $@ $< -fuse-ld=lld -Wl,--gc-sections -lpthread -lm

test-output-scale: $(B)/test_output_scale
	$(B)/test_output_scale

.PHONY: test-output-scale

$(B)/test_window_size: tests/test_window_size.c runtime/window_size.c $(RT_HDRS)
	@mkdir -p $(B)
	$(CC) -O1 -DSDL_STATIC_LIB $(OSFLAGS) $(DEPINC) -Iruntime -o $@ tests/test_window_size.c runtime/window_size.c -lSDL3 -lpthread -lm

test-window-size: $(B)/test_window_size
	$(B)/test_window_size

.PHONY: test-window-size

$(B)/test_vibration: tools/test_vibration.c runtime/hle/vibration.c runtime/vibration.h runtime/settings.h runtime/services/hid_set.c
	@mkdir -p $(B)
	$(CC) -O1 -DSDL_STATIC_LIB $(OSFLAGS) $(DEPINC) -Iruntime -o $@ tools/test_vibration.c -lpthread -lm

test-vibration: $(B)/test_vibration
	$(B)/test_vibration

.PHONY: test-vibration

$(B)/test_prof: tools/test_prof.c runtime/prof.c runtime/prof_sampler.c runtime/prof.h runtime/rt.h
	@mkdir -p $(B)
	$(CC) -O2 -std=gnu11 -Wall -Wextra -Werror $(OSFLAGS) -Iruntime -o $@ tools/test_prof.c runtime/prof.c runtime/prof_sampler.c -lpthread

# (POSIX only: mkdtemp, nanosleep)
$(B)/test_prof_lifecycle: tools/test_prof_lifecycle.c runtime/prof.c runtime/prof_sampler.c runtime/prof.h runtime/rt.h
	@mkdir -p $(B)
	$(CC) -O2 -std=gnu11 -Wall -Wextra -Werror $(OSFLAGS) -Iruntime -o $@ tools/test_prof_lifecycle.c runtime/prof.c runtime/prof_sampler.c -lpthread

test-prof: $(B)/test_prof $(B)/test_prof_lifecycle
	$(B)/test_prof
	python3 -m unittest tools.test_swprof
	SWPROF_TEST_BIN=$(B)/test_prof_lifecycle python3 -m unittest tools.test_prof_lifecycle

.PHONY: test-prof

# The input test includes input.c; discard its unused HLE functions and their runtime dependencies.
$(B)/test_input_focus: tools/test_input_focus.c tools/test_pointer_disabled.h runtime/hle/input.c $(RT_HDRS)
	@mkdir -p $(B)
	$(CC) -O1 -ffunction-sections -fdata-sections $(OSFLAGS) $(DEPINC) -Iruntime -o $@ tools/test_input_focus.c \
	    $(if $(filter macos,$(PLATFORM)),-Wl$(comma)-dead_strip,-Wl$(comma)--gc-sections) \
	    $(if $(filter macos,$(PLATFORM)),-L$(SDL)/lib,$(if $(DEPS),-L$(DEPS)/lib)) -lSDL3 -lm

test-input-focus: $(B)/test_input_focus
	$(B)/test_input_focus

.PHONY: test-input-focus

# The virtual gyro at a shrine apparatus (docs/VIRTUAL_GYRO.md): the gyro keys through input.c and the bindings, the
# two Controls switches saved and loaded, the turns (motion.c), the apparatus heartbeat, the drag (no game files)
TEST_LD := $(if $(filter macos,$(PLATFORM)),-Wl$(comma)-dead_strip,-Wl$(comma)--gc-sections) \
           $(if $(filter macos,$(PLATFORM)),-L$(SDL)/lib,$(if $(DEPS),-L$(DEPS)/lib))
$(B)/test_gyro_bindings: tools/test_gyro_bindings.c tools/test_pointer_disabled.h runtime/hle/input.c runtime/hle/bindings.c $(RT_HDRS)
	@mkdir -p $(B)
	$(CC) -O1 -ffunction-sections -fdata-sections $(OSFLAGS) $(DEPINC) -Iruntime -o $@ tools/test_gyro_bindings.c \
	    runtime/hle/bindings.c $(TEST_LD) -lSDL3 -lm

$(B)/test_gyro_settings: tools/test_gyro_settings.c runtime/settings.c runtime/hle/bindings.c $(RT_HDRS)
	@mkdir -p $(B)
	$(CC) -O1 -ffunction-sections -fdata-sections $(OSFLAGS) $(DEPINC) -Iruntime -o $@ tools/test_gyro_settings.c \
	    $(TEST_LD) -lSDL3 -lm

$(B)/test_motion_keyboard: tools/test_motion_keyboard.c runtime/hle/motion.c runtime/dsu.c $(RT_HDRS)
	@mkdir -p $(B)
	$(CC) -O1 -ffunction-sections -fdata-sections $(OSFLAGS) $(DEPINC) -Iruntime -o $@ tools/test_motion_keyboard.c \
	    runtime/dsu.c $(TEST_LD) -lSDL3 -lm $(if $(filter windows,$(PLATFORM)),-lws2_32)

$(B)/test_motion_sensors: tools/test_motion_sensors.c runtime/hle/motion.c runtime/dsu.c $(RT_HDRS)
	@mkdir -p $(B)
	$(CC) -O1 -ffunction-sections -fdata-sections $(OSFLAGS) $(DEPINC) -Iruntime -o $@ tools/test_motion_sensors.c \
	    runtime/dsu.c $(TEST_LD) -lSDL3 -lm $(if $(filter windows,$(PLATFORM)),-lws2_32)

$(B)/test_gyro_activation: tools/test_gyro_activation.c runtime/pc_gyro_scene.c $(RT_HDRS)
	@mkdir -p $(B)
	$(CC) -O1 -ffunction-sections -fdata-sections $(OSFLAGS) $(DEPINC) -Iruntime -o $@ tools/test_gyro_activation.c \
	    $(TEST_LD) -lm

$(B)/test_gyro_drag: tools/test_gyro_drag.cpp runtime/ui/gyro_drag.h $(B)/imgui/imgui.o $(B)/imgui/imgui_draw.o \
                     $(B)/imgui/imgui_tables.o $(B)/imgui/imgui_widgets.o
	@mkdir -p $(B)
	$(CXX) -O1 -std=c++17 $(OSFLAGS) -I$(IMGUI) -Iruntime -o $@ tools/test_gyro_drag.cpp $(filter %.o,$^)

test-gyro: $(B)/test_gyro_bindings $(B)/test_gyro_settings $(B)/test_motion_keyboard $(B)/test_motion_sensors \
           $(B)/test_gyro_activation $(B)/test_gyro_drag test-bind-capture
	$(B)/test_gyro_bindings
	@set -e; tmp=$$(mktemp); trap 'rm -f "$$tmp"' EXIT; \
	 printf 'settings_version = 3\npc_gyro = 0\ngyro_scene = 1\n' > "$$tmp"; \
	 $(B)/test_gyro_settings "$$tmp" 0 1; \
	 $(B)/test_gyro_settings "$$tmp" 1 0 saved; \
	 SAVAGEWIND_PC_GYRO=1 SAVAGEWIND_GYRO_SCENE=0 $(B)/test_gyro_settings "$$tmp" 1 0
	$(B)/test_motion_keyboard
	$(B)/test_motion_sensors
	$(B)/test_gyro_activation
	$(B)/test_gyro_drag
	python3 tools/test_gyro_site.py

.PHONY: test-gyro

$(B)/test_swkbd: tools/test_swkbd.c runtime/hle/swkbd.c $(RT_HDRS)
	@mkdir -p $(B)
	$(CC) -O1 -std=gnu11 -Wall -Wextra -Werror $(OSFLAGS) -Iruntime -o $@ tools/test_swkbd.c

test-swkbd: $(B)/test_swkbd
	$(B)/test_swkbd

.PHONY: test-swkbd

# The Wii U / Cemu save importer against tools/botw_save_convert.py: both convert synthetic saves and every output file
# is compared (no game files needed). With your own: python3 tools/test_save_convert.py --src <profile> --bootup <pack>
$(B)/test_save_convert: tools/test_save_convert.c runtime/services/save_convert.c runtime/services/save_convert.h runtime/services/archive.c runtime/services/archive.h
	@mkdir -p $(B)
	$(CC) -O1 -std=gnu11 -D_FILE_OFFSET_BITS=64 -Iruntime -o $@ tools/test_save_convert.c runtime/services/archive.c

test-save-convert: $(B)/test_save_convert
	python3 tools/test_save_convert.py --exe $(B)/test_save_convert

.PHONY: test-save-convert

# Save profiles (runtime/services/save_profiles.c): names, create / copy / rename / delete, the active profile and the
# legacy `save` folder, on tiny fake folders in a temporary directory (no game files, no real saves)
$(B)/test_save_profiles: tools/test_save_profiles.c runtime/services/save_profiles.c runtime/services/save_profiles.h runtime/services/save_convert.c runtime/services/save_convert.h runtime/services/archive.c runtime/services/archive.h
	@mkdir -p $(B)
	$(CC) -O1 -Wall -std=gnu11 -D_FILE_OFFSET_BITS=64 -Iruntime -o $@ tools/test_save_profiles.c runtime/services/save_profiles.c runtime/services/save_convert.c runtime/services/archive.c

test-save-profiles: $(B)/test_save_profiles
	$(B)/test_save_profiles

.PHONY: test-save-profiles

$(B)/test_game_file_size: tools/test_game_file_size.c runtime/game_file_size.c runtime/game_file_size.h runtime/game_files.h
	@mkdir -p $(B)
	$(CC) -O1 -Wall $(OSFLAGS) -Iruntime -o $@ tools/test_game_file_size.c runtime/game_file_size.c

test-game-file-size: $(B)/test_game_file_size
	$(B)/test_game_file_size

$(B)/test_file_size_cache: tools/test_file_size_cache.cpp runtime/ui/file_size_cache.mm runtime/ui/file_size_cache.h runtime/game_file_size.h
	@mkdir -p $(B)
	$(CXX) -O1 -Wall -std=c++17 $(OSFLAGS) -Iruntime -o $@ tools/test_file_size_cache.cpp -lpthread

test-file-size-cache: $(B)/test_file_size_cache
	$(B)/test_file_size_cache

$(B)/test_dlc_check: tools/test_dlc_check.c runtime/dlc_check.c runtime/dlc_check.h runtime/romfs_build.c runtime/romfs_build.h
	@mkdir -p $(B)
	$(CC) -O1 -std=gnu11 -Wall -Wextra -Werror $(OSFLAGS) -Iruntime -o $@ tools/test_dlc_check.c runtime/dlc_check.c runtime/romfs_build.c

test-dlc-check: $(B)/test_dlc_check
	$(B)/test_dlc_check

.PHONY: test-game-file-size test-file-size-cache test-dlc-check

# the command layer of the control endpoint (who may run what, the queue, the text)
$(B)/test_control: tools/test_control.c runtime/control.c runtime/control.h
	@mkdir -p $(B)
	$(CC) -O1 -g -Wall $(OSFLAGS) -Iruntime -o $@ tools/test_control.c runtime/control.c -lpthread -lm \
	    $(if $(filter windows,$(PLATFORM)),-lws2_32)

test-control: $(B)/test_control
	env -u SAVAGEWIND_CONTROL -u SAVAGEWIND_DEV $(B)/test_control
	env -u SAVAGEWIND_CONTROL SAVAGEWIND_DEV=1 $(B)/test_control dev

.PHONY: test-control

# the named places behind goto (shrine 5, korok H23, stable wetland ...)
$(B)/test_places: tools/test_places.c runtime/control_places.c runtime/control_places.h runtime/control_places_data.inc
	@mkdir -p $(B)
	$(CC) -O1 -g -Wall $(OSFLAGS) -Iruntime -o $@ tools/test_places.c runtime/control_places.c

test-places: $(B)/test_places
	$(B)/test_places

.PHONY: test-places

# the in-game console's lines, history and completion
$(B)/test_console_core: tools/test_console_core.c runtime/console_core.c runtime/console_core.h
	@mkdir -p $(B)
	$(CC) -O1 -g -Wall $(OSFLAGS) -Iruntime -o $@ tools/test_console_core.c runtime/console_core.c

test-console: $(B)/test_console_core
	$(B)/test_console_core

.PHONY: test-console

$(B)/test_hour: tools/test_hour.c runtime/services/test_warp.c runtime/game_sites.h
	@mkdir -p $(B)
	$(CC) -O1 -g -Wall -Wno-unused-function $(OSFLAGS) -Iruntime -o $@ tools/test_hour.c -lm

test-hour: $(B)/test_hour
	env -u SAVAGEWIND_TEST_TIME $(B)/test_hour
	env SAVAGEWIND_TEST_TIME=18 $(B)/test_hour env

.PHONY: test-hour

# The BC5 view format (NVN 0x4C, SAVAGEWIND_BC5_UNORM): vk_format is the only function the section GC keeps from
# textures.c, so no Vulkan device is needed. Run twice so both initial environment states cache the right format.
ifneq ($(PLATFORM),macos)
$(B)/test_textures_format: tests/test_textures_format.c runtime/nvn/vulkan/textures.c $(RT_HDRS)
	@mkdir -p $(dir $@)
	$(CC) -O2 -ffunction-sections -fdata-sections $(OSFLAGS) $(DEPINC) -Iruntime -Iruntime/nvn -isystem third_party -isystem third_party/stb \
	    -o $@ tests/test_textures_format.c runtime/nvn/vulkan/textures.c -fuse-ld=lld -Wl,--gc-sections \
	    $(if $(filter windows,$(PLATFORM)),-Wl$(comma)--exclude-all-symbols) -lpthread -lm

test-textures: $(B)/test_textures_format
	env -u SAVAGEWIND_BC5_UNORM $(B)/test_textures_format
	env SAVAGEWIND_BC5_UNORM=1 $(B)/test_textures_format

bench-textures: $(B)/test_textures_format
	$(B)/test_textures_format --bench

.PHONY: test-textures bench-textures
endif

# Real Options routing + binding capture, using synthetic guest rows rather than game assets.
$(B)/two_button_bindings.o: runtime/hle/bindings.c runtime/input_bind.h
	@mkdir -p $(B)
	$(CC) -O1 -ffunction-sections -fdata-sections -DSDL_STATIC_LIB $(OSFLAGS) $(DEPINC) -Iruntime -c $< -o $@

$(B)/test_two_button_rows: tools/test_two_button_rows.cpp runtime/ui/game_options.mm runtime/ui/binding_row_layout.h $(B)/two_button_bindings.o
	$(CXX) -std=c++17 -O1 -ffunction-sections -fdata-sections -DSDL_STATIC_LIB $(OSFLAGS) $(DEPINC) -Iruntime -Ithird_party -o $@ $< $(B)/two_button_bindings.o -fuse-ld=lld -Wl,--gc-sections $(if $(filter windows,$(PLATFORM)),-Wl$(comma)--exclude-all-symbols) -lSDL3 -lm

test-two-button-rows: $(B)/test_two_button_rows
	$(B)/test_two_button_rows
	python3 tools/test_two_button_sites.py

.PHONY: test-two-button-rows
# Guard shader-specific bloom scaling against unrelated scene, depth and UI targets.
$(B)/test_bloom_scale: tests/test_bloom_scale.c runtime/nvn/vulkan/bloom_scale.h
	@mkdir -p $(B)
	$(CC) -O1 -Wall -Wextra -Werror -o $@ $<

test-bloom-scale: $(B)/test_bloom_scale
	$(B)/test_bloom_scale

.PHONY: test-bloom-scale

$(B)/test_audio_mix: tests/test_audio_mix.c runtime/audio_mix.h runtime/settings.h
	@mkdir -p $(B)
	$(CC) -O1 -Wall -Wextra -Werror -o $@ $< -lm

test-audio-mix: $(B)/test_audio_mix
	$(B)/test_audio_mix

.PHONY: test-audio-mix

$(B)/test_movie_stop: tests/test_movie_stop.c runtime/hle/movie.c runtime/hle.h runtime/kernel.h runtime/settings.h
	@mkdir -p $(B)
	$(CC) -O1 -Wall -Wno-unused-function $(OSFLAGS) $(DEPINC) -Iruntime -o $@ $< $(if $(DEPS),-L$(DEPS)/lib) -lavformat -lavcodec -lavutil -lswscale -lpthread -lm

test-movie-stop: $(B)/test_movie_stop
	$(B)/test_movie_stop

.PHONY: test-movie-stop
# Launch options (docs/launch-options.md): the checks, the file, the environment and the suggestions (no game files), and
# the generated table of the flags the code reads (tools/gen_launch_flags.py --check fails when it is stale)
$(B)/test_launch_flags: tools/test_launch_flags.c runtime/launch_flags.c runtime/launch_flags_table.c runtime/launch_flags.h
	@mkdir -p $(B)
	$(CC) -O1 -g -Wall -Wextra $(OSFLAGS) -Iruntime -o $@ tools/test_launch_flags.c runtime/launch_flags.c runtime/launch_flags_table.c

test-update-core: $(B)/test_update_core
	$(B)/test_update_core
$(B)/test_update_core: tools/test_update_core.c runtime/update_core.c runtime/update_core.h runtime/update_crypto.c runtime/update_crypto.h
	@mkdir -p $(dir $@)
	$(CC) -O1 -Wall -c tools/test_update_core.c -o $@-t.o
	$(CC) -O1 -Wall -c runtime/update_core.c -o $@-c.o
	$(CC) -O1 -Wall -c runtime/update_crypto.c -o $@-x.o
	$(CC) -o $@ $@-t.o $@-c.o $@-x.o
# (Windows) every way an update can go wrong, against a local server: tools/test_sw_update.py
test-sw-update:
	python3 tools/test_sw_update.py
# (Linux) the same for an AppImage replacing itself: tools/test_update_appimage.py
test-update-appimage:
	python3 tools/test_update_appimage.py
# Steam's shortcuts.vdf read and written (runtime/steam_shortcuts.c); real files (copies) can be given: STEAM_VDF="a b"
test-steam-shortcuts: $(B)/test_steam_shortcuts
	$(B)/test_steam_shortcuts $(STEAM_VDF)
$(B)/test_steam_shortcuts: tools/test_steam_shortcuts.c runtime/steam_shortcuts.c runtime/steam_shortcuts.h
	@mkdir -p $(dir $@)
	$(CC) -O1 -Wall -c tools/test_steam_shortcuts.c -o $@-t.o
	$(CC) -O1 -Wall -DSTEAM_VDF_ONLY -c runtime/steam_shortcuts.c -o $@-s.o
	$(CC) -o $@ $@-t.o $@-s.o

test-launch-flags: $(B)/test_launch_flags
	$(B)/test_launch_flags
	python3 tools/gen_launch_flags.py --check

.PHONY: test-launch-flags

# Native quick-selector sorting: synthetic Linux guest memory, no game files.
ifeq ($(PLATFORM),linux)
$(B)/test_quick_inventory_sort: tools/test_quick_inventory_sort.c runtime/quick_inventory_sort.c $(RT_HDRS)
	@mkdir -p $(B)
	$(CC) -std=gnu11 -O1 -g $(OSFLAGS) $(DEPINC) -Iruntime -o $@ $<

$(B)/test_gamelib_sites: tools/test_gamelib_sites.c runtime/gamelib.c $(RT_HDRS)
	@mkdir -p $(B)
	$(CC) -std=gnu11 -O1 -g -ffunction-sections -fdata-sections $(OSFLAGS) -Iruntime -o $@ $< -Wl,--gc-sections -ldl

test-quick-inventory-sort: $(B)/test_quick_inventory_sort $(B)/test_gamelib_sites
	$(B)/test_quick_inventory_sort
	$(B)/test_gamelib_sites

.PHONY: test-quick-inventory-sort

$(B)/test_quick_hint_font: tools/test_quick_hint_font.cpp runtime/ui/quick_hint_font.mm runtime/ui/quick_hint_font.h \
                         $(B)/imgui/imgui.o $(B)/imgui/imgui_draw.o $(B)/imgui/imgui_tables.o $(B)/imgui/imgui_widgets.o \
                         $(B)/rt/services/archive.o $(B)/rt/nvn/tegra.o $(B)/rt/nvn/glyphs.o $(B)/rt/hle/bindings.o
	@mkdir -p $(B)
	$(CXX) $(CXXFLAGS) -o $@ $< $(filter %.o,$^) $(TEST_LD) -lSDL3 -lm

# The player supplies RomFS locally; no fonts or game fixtures are distributed.
test-quick-inventory-font: $(B)/test_quick_hint_font
	@test -n "$(ROMFS)" || { echo 'Set ROMFS to your own extracted game RomFS directory.'; exit 2; }
	$(B)/test_quick_hint_font "$(ROMFS)"

.PHONY: test-quick-inventory-font
endif

ifeq ($(PLATFORM),linux)
$(B)/test_quick_drop_action: tools/test_quick_drop_action.c runtime/quick_drop_action.c $(RT_HDRS)
	@mkdir -p $(B)
	$(CC) -std=gnu11 -O1 -g $(OSFLAGS) $(DEPINC) -Iruntime -o $@ $<

$(B)/test_quick_drop_input: tools/test_quick_drop_input.c runtime/quick_drop_action.c runtime/hle/input.c tools/test_freecam_disabled.h $(RT_HDRS)
	@mkdir -p $(B)
	$(CC) -std=gnu11 -O1 -g -ffunction-sections -fdata-sections $(OSFLAGS) $(DEPINC) -Iruntime -o $@ $< $(TEST_LD) -lm

$(B)/test_quick_drop_menu: tools/test_quick_drop_menu.c runtime/quick_drop.c $(RT_HDRS)
	@mkdir -p $(B)
	$(CC) -std=gnu11 -O1 -g $(OSFLAGS) $(DEPINC) -Iruntime -o $@ $<

test-quick-drop-native: $(B)/test_quick_drop_action $(B)/test_quick_drop_menu
	$(B)/test_quick_drop_action
	$(B)/test_quick_drop_menu

test-quick-drop: test-quick-drop-native $(B)/test_quick_drop_input
	$(B)/test_quick_drop_input

.PHONY: test-quick-drop test-quick-drop-native
endif

$(B)/test_ui_layout: tests/test_ui_layout.c runtime/ui_layout.c runtime/ui_layout.h runtime/nvn/cmdbuf.c runtime/nvn/nvn.h runtime/nvn/hud_scale.h
	@mkdir -p $(dir $@)
	$(CC) -O1 -ffunction-sections -fdata-sections $(DEPINC) -Iruntime -o $@ $< -fuse-ld=lld -Wl,--gc-sections -lpthread -lm

test-ui-layout: $(B)/test_ui_layout
	$(B)/test_ui_layout
.PHONY: test-ui-layout
