# Super Odyssey PC Recomp build
# Windows: MSYS2 UCRT64 (see docs/BUILD-windows.md), clang + Vulkan renderer: `make gen`, then `make -j16`.
# Linux: clang + Vulkan renderer; macOS: Homebrew clang/SDL3/FFmpeg, Metal renderer (both untested with Odyssey).
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 the
# system's.
B         ?= build
MACOS_MIN ?=
DEPS      ?=
MINFLAG  := $(if $(MACOS_MIN),-mmacosx-version-min=$(MACOS_MIN))
# Windows (MSYS2 UCRT64): clang.exe, clang++.exe, clang-cl.exe and clang-cpp.exe in /ucrt64/bin are one hard-linked file,
# and on Windows the name clang comes up as can be another link's: the driver takes its mode from that name (clang++'s
# C++), and a C build then stops at "error: invalid argument '-std=c11' not allowed with 'C++'" (CI run 46704930641). Say
# the mode instead; an explicit --driver-mode wins over the program name (clang's Driver::ParseDriverMode). Linux, macOS
# and the Linux -> Windows cross build pass no flag: their command lines are the same as before.
CLANG    := clang$(if $(filter windows,$(PLATFORM)), --driver-mode=gcc)
CLANGXX  := clang++$(if $(filter windows,$(PLATFORM)), --driver-mode=g++)
CC       := $(CLANG) $(MINFLAG) $(CROSS)
CXX      := $(CLANGXX) $(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)/subsdk0/*.c) $(wildcard $(GEN)/sdk/*.c)
GEN_OBJ  := $(patsubst %.c,$(B)/obj/%.o,$(patsubst $(GEN)/%,%,$(GEN_SRC))) $(B)/obj/tools/gamelib_entry.o
# the modules made by `make gen`, in load order: their tables go into the library (tools/gamelib_entry.c). A code mod's
# subsdk4 is not one of them: it is $(GEN)/subsdk4, and goes into the mod's own library (below), never into the vanilla one.
GEN_MODS := $(foreach m,main subsdk0 sdk,$(if $(wildcard $(GEN)/$(m)/*.c),$(m)))

# The runtime's HLE_FUNC names a code mod's sdk takes (tools/hle_funcs.py's mod_call_names), hashed: the modded library's
# id carries it (runtime/codemod.h HLE_FUNCS_HASH: sha256 of the sorted names, one per line, 16 hex digits). A runtime
# that adds or removes one of those names makes another library for the mod; the objects that use the hash depend on
# what it is made from (HLE_FUNCS_SRCS), so `make` compiles them again.
# Python 3 for it: the checkout's tools/venv (setup_windows.ps1), the generator's build/gen-venv (make gen-helper), else
# PATH's python3 (the Windows CI job's setup-python): tools/hle_funcs.py needs only the standard library.
HLE_FUNCS_PY   := $(firstword $(wildcard tools/venv/bin/python) $(wildcard tools/venv/Scripts/python.exe) \
                    $(wildcard build/gen-venv/bin/python) $(wildcard build/gen-venv/Scripts/python.exe) python3)
HLE_FUNCS_HASH := $(shell $(HLE_FUNCS_PY) tools/hle_funcs.py --hash runtime 2>/dev/null)
HLE_FUNCS_SRCS := tools/hle_funcs.py $(wildcard runtime/*.c runtime/*/*.c runtime/*/*/*.c)

# Code mods (runtime/codemod.h): `make gen CODEMOD=<the mod's exefs/subsdk4> [SITES=<its manifest>]` generates the mod's
# code too, and `make codemod-libs` (the same CODEMOD= SITES=) links it as ONE library next to the vanilla one. All of
# it in one command: `make codemod CODEMOD=... SITES=...` (the vanilla app and library too, then both).
# - $(GEN)/subsdk4: the mod itself, at its base between subsdk0 and sdk (the NSOs' headers: tools/codemod_base.py,
#   runtime/codemod.c's subsdk4_base), lifted with --br-all (its clang-built code has compressed jump tables) and no HLE;
# - $(GEN)/main-modded and $(GEN)/sdk-modded: main and sdk as the vanilla ones (the same HLE), plus the manifest's live
#   sites (--sites), which is what differs from the vanilla code.
# The modded library (odyssey_game-<first 8 hex digits of the mod's sha256>.<ext>) holds all four modules in load order -
# main-modded, subsdk0 (the vanilla subsdk0: the mod leaves it alone), subsdk4, sdk-modded - and its own id (its .id file,
# and the id it reports: tools/gamelib_entry.c). That id is codemod.h codemod_lib_id's, byte for byte (CODEMOD_LIB_ID,
# below). Switching the mod on and off rebuilds neither library. Without CODEMOD, `make gen` and `make` are what they
# were: subsdk4 is not in the vanilla library, and nothing of the mod's is.
CODEMOD   ?=
SITES     ?=
CODEMOD_A := $(abspath $(CODEMOD))
SITES_A   := $(if $(SITES),$(abspath $(SITES)),)
# the mod's sha256 (tools/codemod_hash.py), and its manifest's part of the id (16 hex digits: tools/codemod_hash_manifest.py
# hashes the manifest as runtime/codemod.c manifest_hash does with gamebuild.c's hash2, then folds in HLE_FUNCS_HASH as
# codemod_lib_id does)
CODEMOD_SHA := $(if $(CODEMOD_A),$(shell python3 tools/codemod_hash.py "$(CODEMOD_A)" 2>/dev/null))
CODEMOD_MANIFEST := $(if $(SITES_A),$(shell test -f "$(SITES_A)" && $(HLE_FUNCS_PY) tools/codemod_hash_manifest.py "$(SITES_A)" "$(HLE_FUNCS_HASH)" 2>/dev/null))
SITES_ARG := $(if $(SITES_A),--sites $(SITES_A))
# subsdk4's base (0x7003800000 on 1.0.0): the command, run once with CODEMOD set (make gen, codemod-libs: they need
# extracted/exefs/ and the mod): "" without CODEMOD, so nothing runs
CODEMOD_BASE := $(if $(CODEMOD_A),$(shell python3 tools/codemod_base.py extracted/exefs "$(CODEMOD_A)" 2>/dev/null))
# gamelib_id's CPU level (runtime/gamelib.c), which the library's id carries: -avx, -v2, -x64 on an x86-64 CPU without
# AVX2 + FMA + BMI2, the build's own level (x86-64-v3) with them, and none off x86-64 (not x86: the build's target).
# ODYSSEY_CPU_LEVEL=avx / v2 / x64 forces one, as the runtime's (v3, or anything it doesn't know: the build's own).
# Plain shell: the library's id must be the one codemod_lib_id computes when the game starts on this machine.
CODEMOD_CPU_SH := if [ "$(ARCH)" = x86_64 ] && [ -r /proc/cpuinfo ]; then \
    if ! (grep -qw avx2 /proc/cpuinfo && grep -qw fma /proc/cpuinfo && grep -qw bmi2 /proc/cpuinfo); then \
      if grep -qw avx /proc/cpuinfo && grep -qw sse4_2 /proc/cpuinfo && grep -qw popcnt /proc/cpuinfo; then echo avx; \
      elif grep -qw sse4_2 /proc/cpuinfo && grep -qw popcnt /proc/cpuinfo && grep -qw ssse3 /proc/cpuinfo; then echo v2; \
      else echo x64; fi; \
    fi; \
  fi
CODEMOD_CPU := $(if $(filter avx v2 x64,$(ODYSSEY_CPU_LEVEL)),$(ODYSSEY_CPU_LEVEL),$(shell $(CODEMOD_CPU_SH)))
# the code mod's generated code: its own objects, apart from the vanilla ones ($(B)/obj/<module>/), under
# $(B)/obj/codemod/<module>/ (the rules below: each file's name has a dash, which the vanilla objects' rule
# ($(B)/obj/%.o: $(GEN)/%.c) would map to the wrong module)
CODEMOD_SRC   := $(foreach m,main-modded subsdk4 sdk-modded,$(sort $(wildcard $(GEN)/$(m)/*.c)))
CODEMOD_OBJ   := $(patsubst %.c,$(B)/obj/codemod/%.o,$(subst $(GEN)/,,$(CODEMOD_SRC)))
# the library's modules in load order (tools/gamelib_entry.c's GAMELIB_MODULES): main, subsdk0 (if `make gen` made it:
# the vanilla objects, as the vanilla library's list), subsdk4, sdk
CODEMOD_MODS  := $(if $(wildcard $(GEN)/main-modded/*.c),main) $(if $(wildcard $(GEN)/subsdk0/*.c),subsdk0) \
                 $(if $(wildcard $(GEN)/subsdk4/*.c),subsdk4) $(if $(wildcard $(GEN)/sdk-modded/*.c),sdk)
# subsdk0's vanilla objects (the vanilla rules: the mod leaves subsdk0 alone); none if `make gen` made none. They are
# named as the vanilla objects are ($(B)/obj/subsdk0/...), not by GEN_OBJ's path.
CODEMOD_SUBSDK0 := $(patsubst %.c,$(B)/obj/%.o,$(patsubst $(GEN)/%,%,$(wildcard $(GEN)/subsdk0/*.c)))
CODEMOD_ENTRY   := $(B)/obj/codemod/gamelib_entry.o
RT_SRC   := $(wildcard runtime/*.c) $(wildcard runtime/hle/*.c) $(wildcard runtime/services/*.c) \
            $(wildcard runtime/nvn/*.c) $(wildcard runtime/nvn/maxwell/*.c) runtime/platform/$(PLATFORM).c \
            $(if $(filter windows,$(PLATFORM)),runtime/platform/windows_mem.c)
RT_HDRS  := $(wildcard runtime/*.h) $(wildcard runtime/hle/*.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)/SuperOdysseyRecomp
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)/odyssey_game.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 setup page's build: runtime/gamebuild.c)
else ifeq ($(PLATFORM),linux)
EXE      := $(B)/SuperOdysseyRecomp
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) -l:libzstd.a -lpthread -ldl -lm  # (zstd: the shader cache pack, nvn/vulkan/shaders.c)
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)/odyssey_game.so
GAMELIB_LDFLAGS := -shared -fuse-ld=lld  # (the runtime functions it calls: the app's own, -rdynamic)
GAMELIB_SHARED := -shared -fuse-ld=lld
else
EXE      := $(B)/SuperOdysseyRecomp.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); override for older CPUs
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 -lruntimeobject -lshell32 -lcomdlg32 -luuid -lshaderc_shared -l:libzstd.a -lpdh -lbcrypt -lwinhttp -lwintrust -lcrypt32 -lws2_32 \
            $(if $(CONSOLE),,-Wl$(comma)--subsystem$(comma)windows)  # no console window (log -> SuperOdysseyRecomp.log); CONSOLE=1: one
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)/odyssey_game.dll
# the runtime functions it calls: exported by the .exe, linked through its import library
LDFLAGS  += -Wl,--export-all-symbols -Wl,--out-implib,$(B)/SuperOdysseyRecomp.dll.a
GAMELIB_LDFLAGS := -shared -fuse-ld=lld $(B)/SuperOdysseyRecomp.dll.a
GAMELIB_SHARED := -shared -fuse-ld=lld  # (+ 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, and on Windows releases the compiler runtime it is linked with: tools/zig_slim.sh). A library with another id
# is never loaded (`make gen`, then `make` again; players' setup builds it again).
GAMELIB_SRCS := tools/gen.py tools/lifter.py tools/analyze.py tools/nso.py tools/passes.py tools/odyssey_patches.py \
                tools/simd_c.py tools/gamelib_entry.c runtime/hle/hle_symbols.txt runtime/hle/hot_functions.txt \
                runtime/cpu.h runtime/simd.h runtime/simd_fp.h runtime/gamelib.h
# (the compiler runtime's script only where it is used: its change for #87 made every Linux / Steam Deck player's
# game code rebuild too - about 25 minutes on a Deck - for a library that was the same. runtime/gamelib.c same_as
# keeps the Linux libraries built before this.)
ifeq ($(PLATFORM),windows)
GAMELIB_SRCS += tools/zig_slim.sh
endif
# (line endings don't count: a Windows checkout with CRLF and GitHub's LF one make the same library)
GAMELIB_ID := $(shell (cat $(GAMELIB_SRCS); echo '$(GENFLAGS)') | tr -d '\015' | (shasum -a 256 2>/dev/null || sha256sum) | cut -c1-16)

# The code mod's library (GAMELIB's own extension: .so, .dylib, .dll) and its id - codemod.h codemod_lib_id's, byte for
# byte: this build's id for gamelib_id (GAMELIB_ID, then the CPU level as runtime/gamelib.c gives it: CODEMOD_CPU),
# "-", the mod's sha256 (64 hex digits), "-", the manifest's part (16: its hash xor HLE_FUNCS_HASH). runtime/codemod.c
# makes the same at run time (tools/codemod_hash.py and tools/codemod_hash_manifest.py are its two hashes, and the
# runtime has the HLE_FUNCS_HASH compiled in), so the mod loads this library. Without a manifest the part is the list's
# hash alone (codemod_lib_id's 0 xor it); 0 only if no python3 made it, which a code mod's build needs anyway.
CODEMOD_LIB    := $(B)/odyssey_game-$(strip $(shell echo '$(CODEMOD_SHA)' | cut -c1-8))$(suffix $(notdir $(GAMELIB)))
CODEMOD_LIB_ID := $(GAMELIB_ID)$(if $(CODEMOD_CPU),-$(CODEMOD_CPU))-$(CODEMOD_SHA)-$(if $(CODEMOD_MANIFEST),$(CODEMOD_MANIFEST),$(if $(HLE_FUNCS_HASH),$(HLE_FUNCS_HASH),0000000000000000))
# the paths, one word each (a mod or manifest under a folder with a space), for `make gen`'s sub-make
CODEMOD_SUBMAKE_ARGS := CODEMOD="$(CODEMOD_A)" SITES="$(SITES_A)"

RT_OBJ   := $(patsubst runtime/%.c,$(B)/rt/%.o,$(RT_SRC))
# (Windows: library headers' own paths, e.g. an assert's __FILE__ in vk_mem_alloc.h, name MSYS2's folder - which can be
# in the builder's user folder: written as /msys64 instead; tools/dist_check_paths.sh checks the release)
PREFIX_MAP := $(if $(filter windows,$(PLATFORM)),-ffile-prefix-map=$(shell cygpath -m / 2>/dev/null)=/msys64)
RTFLAGS  := -O2 -g -fno-strict-aliasing -Wall -Wno-unused-function -Iruntime -Iruntime/nvn $(DEPINC) $(OSFLAGS) $(PREFIX_MAP)
CXXFLAGS := -O2 -g -std=c++17 -I$(IMGUI) -I$(IMGUI)/backends -Iruntime -Iruntime/nvn $(DEPINC) $(PREFIX_MAP)

all: $(EXE) $(if $(strip $(GEN_SRC)),$(GAMELIB))  # (strip: with no game code yet GEN_SRC is " ", which $(if) counts as set)

# The C compiler's command line as the build runs it (the CI's guard: a Windows host's clang must come up in C mode -
# see CLANG above; .github/workflows/build.yml compiles a C file with exactly this, before anything else is built)
print-cc:
	@echo $(CC)

$(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) $(wildcard $(GEN)/*/*_table.c)
	@mkdir -p $(dir $@)
	$(CC) $(GENFLAGS) -DGAMELIB_ID='"$(GAMELIB_ID)"' -DGAMELIB_MODULES='$(foreach m,$(GEN_MODS),X($(m)))' -c $< -o $@
$(B)/rt/gamelib.o: $(GAMELIB_SRCS) Makefile  # (GAMELIB_ID is computed there)
# PREP_ID: what a prepared shader cache is made by - the shader translator, the SPIR-V compile and its pack, and the
# list of shaders prepared (runtime/nvn/vulkan/device.c prep_identity, with its own PREP_REV). The preparation was
# due again after every update (the version number): ~1 minute on a fast PC, ~8 on a Steam Deck, mostly for nothing.
PREP_SRCS := runtime/nvn/maxwell/translate.c runtime/nvn/maxwell/shader.h runtime/nvn/vulkan/shaders.c \
             runtime/nvn/vulkan/known_programs.txt
PREP_ID := $(shell cat $(PREP_SRCS) | tr -d '\015' | (shasum -a 256 2>/dev/null || sha256sum) | cut -c1-12)
$(B)/rt/nvn/vulkan/device.o: $(PREP_SRCS)
$(B)/rt/nvn/vulkan/device.o: RTFLAGS += -DPREP_ID='"$(PREP_ID)"'
# (the same hash labels the game's saved translations - maxwell_translator_stamp: a build's own date and time made every
# release's players translate thousands of shaders again in their first kingdom, setup not being due)
$(B)/rt/nvn/maxwell/translate.o: $(PREP_SRCS)
$(B)/rt/nvn/maxwell/translate.o: RTFLAGS += -DTRANSLATOR_ID='"$(PREP_ID)"'
$(B)/rt/gamelib.o: RTFLAGS += -DGAMELIB_ID='"$(GAMELIB_ID)"'
# the setup page's build of it on the player's machine (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)"'
# runtime/codemod.c's modded library id carries the runtime's HLE_FUNC list's hash (HLE_FUNCS_HASH, above): it is made
# from runtime/'s sources, so a changed one compiles codemod.c again. (An explicit rule rather than a target-specific
# RTFLAGS +=: RTFLAGS is simple, so that would compute the hash while parsing every make, even one that builds no code.)
$(B)/rt/codemod.o: runtime/codemod.c $(RT_HDRS) $(HLE_FUNCS_SRCS) Makefile
	@mkdir -p $(dir $@)
	$(CC) $(RTFLAGS) -DHLE_FUNCS_HASH=0x$(if $(strip $(HLE_FUNCS_HASH)),$(HLE_FUNCS_HASH),$(error HLE_FUNCS_HASH: $(HLE_FUNCS_PY) tools/hle_funcs.py --hash runtime printed nothing (a Python 3: tools/venv, build/gen-venv or PATH)))ull -c $< -o $@

$(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
$(B)/rt/nvn/vulkan/fsr3_sdk.o: $(wildcard third_party/fsr3_sdk/api/include/*.h) \
    $(wildcard third_party/fsr3_sdk/api/include/vk/*.h) $(wildcard third_party/fsr3_sdk/upscalers/include/*.h)
$(B)/rt/nvn/vulkan/xess_sdk.o: $(wildcard third_party/xess/include/*.h)

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

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

$(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))

gen:
	cd tools && ../$(PY) gen.py sdk ../extracted/exefs/sdk 0x7004000000 ../$(GEN)/sdk --hle ../runtime/hle/hle_symbols.txt $(GENSIMD)
	cd tools && ../$(PY) gen.py main ../extracted/exefs/main 0x7000000000 ../$(GEN)/main --hle ../runtime/hle/hle_symbols.txt $(GENSIMD)
	$(if $(wildcard extracted/exefs/subsdk0),cd tools && ../$(PY) gen.py subsdk0 ../extracted/exefs/subsdk0 0x7003000000 ../$(GEN)/subsdk0 $(GENSIMD))  # (Odyssey's multimedia library)
	$(if $(CODEMOD),$(MAKE) $(CODEMOD_SUBMAKE_ARGS) gen-codemod)  # (the mod's code too)

# `make gen CODEMOD=<the mod's exefs/subsdk4> [SITES=<its manifest>]`: the code mod's code too (runtime/codemod.h).
# subsdk4 at its base, lifted with --br-all (the mod's clang code has compressed jump tables: gen.py's rule for a
# clang-built module) and no HLE (it is the game's code, not the SDK's). main and sdk as the vanilla ones (the same
# --hle), plus the manifest's sites (--sites, when there is one), into $(GEN)/main-modded and $(GEN)/sdk-modded. And
# subsdk0 (vanilla: the mod doesn't patch it) when this GEN has none yet, as the library links it.
gen-codemod:
	@test -n "$(CODEMOD)" || { echo 'make gen CODEMOD=<the code mod'"'"'s exefs/subsdk4> [SITES=<its manifest>]'; exit 1; }
	@test -n "$(CODEMOD_SHA)" || { echo "$(CODEMOD): can't be read (its sha256: the library's name and id)"; exit 1; }
	@test -n "$(CODEMOD_BASE)" || { echo "$(CODEMOD): not a readable NSO, or extracted/exefs/ with main and sdk missing (subsdk4's base)"; exit 1; }
	@echo "code mod: $(CODEMOD) (sha256 $(CODEMOD_SHA)) at $(CODEMOD_BASE)"
	cd tools && ../$(PY) gen.py subsdk4 "$(CODEMOD_A)" $(CODEMOD_BASE) ../$(GEN)/subsdk4 $(GENSIMD) --br-all
	cd tools && ../$(PY) gen.py sdk ../extracted/exefs/sdk 0x7004000000 ../$(GEN)/sdk-modded --hle ../runtime/hle/hle_symbols.txt $(SITES_ARG) $(GENSIMD)
	cd tools && ../$(PY) gen.py main ../extracted/exefs/main 0x7000000000 ../$(GEN)/main-modded --hle ../runtime/hle/hle_symbols.txt $(SITES_ARG) $(GENSIMD)
	$(if $(wildcard extracted/exefs/subsdk0),test -d $(GEN)/subsdk0 || (cd tools && ../$(PY) gen.py subsdk0 ../extracted/exefs/subsdk0 0x7003000000 ../$(GEN)/subsdk0 $(GENSIMD)))  # (the library's vanilla subsdk0, once: `make codemod` in a new GEN has no `make gen` of its own)

# main-modded's, subsdk4's and sdk-modded's own objects: the vanilla flags (so the same code), kept apart from the
# vanilla ones ($(B)/obj/main-modded/ would be main's rule's, $(B)/obj/main/-modded/...: the dash). Their table symbols
# are their module's (main-modded's table is main's: main_fn_*).
$(B)/obj/codemod/main-modded/%.o: $(GEN)/main-modded/%.c runtime/cpu.h $(wildcard $(GEN)/*/*_table.c)
	@mkdir -p $(dir $@)
	$(CC) $(GENFLAGS) -DGAMELIB_ID='"$(GAMELIB_ID)"' -c $< -o $@
$(B)/obj/codemod/subsdk4/%.o: $(GEN)/subsdk4/%.c runtime/cpu.h $(wildcard $(GEN)/*/*_table.c)
	@mkdir -p $(dir $@)
	$(CC) $(GENFLAGS) -DGAMELIB_ID='"$(GAMELIB_ID)"' -c $< -o $@
$(B)/obj/codemod/sdk-modded/%.o: $(GEN)/sdk-modded/%.c runtime/cpu.h $(wildcard $(GEN)/*/*_table.c)
	@mkdir -p $(dir $@)
	$(CC) $(GENFLAGS) -DGAMELIB_ID='"$(GAMELIB_ID)"' -c $< -o $@

# The library's entry: the modules in load order, and the library's id - the one its .id file holds (tools/gamelib_entry.c
# reports -DCODEMOD_LIB_ID as the library's id: runtime/gamelib.c gamelib_codemods splits it)
$(CODEMOD_ENTRY): tools/gamelib_entry.c $(GAMELIB_SRCS) $(wildcard $(GEN)/*/*_table.c)
	@mkdir -p $(dir $@)
	$(CC) $(GENFLAGS) -DGAMELIB_ID='"$(GAMELIB_ID)"' -DCODEMOD_LIB_ID='"$(CODEMOD_LIB_ID)"' \
		-DGAMELIB_MODULES='$(foreach m,$(CODEMOD_MODS),X($(m)))' -c $< -o $@

# The code mod's library: one library, all four modules, beside the vanilla one (whose file and id it leaves alone).
# subsdk0's objects are the vanilla ones (the vanilla flags), when `make gen` made them.
$(CODEMOD_LIB): $(CODEMOD_OBJ) $(CODEMOD_SUBSDK0) $(CODEMOD_ENTRY)
	$(CXX) $(GAMELIB_LDFLAGS) -o $@.tmp $^
	mv -f $@.tmp $@
	echo '$(CODEMOD_LIB_ID)' > $@.id

# With a code mod: the mod's code (`make gen CODEMOD=... SITES=...`) and then its library. `codemod-libs` alone links
# what `make gen CODEMOD=` generated (the vanilla app and library are `make`'s, or run first: the library links nothing
# of the app, but the app is what loads it).
codemod-libs: $(if $(CODEMOD_SRC),$(CODEMOD_LIB))
# (sub-makes: codemod-libs' files are the ones gen-codemod makes, which a prerequisite list read before it ran wouldn't have)
codemod: $(EXE) $(if $(strip $(GEN_SRC)),$(GAMELIB))
	$(MAKE) $(CODEMOD_SUBMAKE_ARGS) gen-codemod
	$(MAKE) $(CODEMOD_SUBMAKE_ARGS) codemod-libs
gen-objs: $(GEN_OBJ)

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

$(B)/ptbr-test-main.o: runtime/main.c $(RT_HDRS)
	$(CC) $(RTFLAGS) -Dmain=ptbr_runtime_main -c $< -o $@

$(B)/ptbr-test.o: tools/test_ptbr_install.c runtime/ptbr_install.h
	$(CC) $(RTFLAGS) -c $< -o $@

PTBR_TEST := $(B)/test_ptbr_install$(if $(filter windows,$(PLATFORM)),.exe)
$(PTBR_TEST): $(filter-out $(B)/rt/main.o,$(RT_OBJ)) $(BACKEND_OBJ) $(UI_OBJ) $(IMGUI_OBJ) $(B)/ptbr-test-main.o $(B)/ptbr-test.o
	$(CXX) -o $@ $^ $(filter-out -Wl$(comma)--out-implib% -Wl$(comma)--subsystem%,$(LDFLAGS))

.PHONY: test-ptbr-installer
test-ptbr-installer: $(PTBR_TEST)
	$(PY) tools/test_ptbr_install.py $(PTBR_TEST)

# The BSD (bsd:u / bsd:s) and sfdnsres services on host sockets: tests/bsd_test.c drives the handlers directly against
# an in-process TCP and UDP echo server (the kernel is linked for g_rt_unwind, no guest threads). No game files needed.
BSD_TEST_SRC := tests/bsd_test.c tests/bsd_test_stubs.c runtime/services/bsd.c runtime/services/sfdnsres.c runtime/kernel.c
BSD_TEST := $(B)/test_bsd$(if $(filter windows,$(PLATFORM)),.exe)
$(BSD_TEST): $(BSD_TEST_SRC) runtime/hle.h runtime/ipc.h runtime/kernel.h runtime/cpu.h runtime/rt.h runtime/platform.h \
		runtime/settings.h runtime/services/sfdnsres.h tests/host_netdb.h
	@mkdir -p $(dir $@)
	$(CC) -O2 -g -fno-strict-aliasing -Wall -Wno-unused-function -Wno-format -DBSD_TEST_NO_HOST_NETDB -Itests -Iruntime -Iruntime/nvn $(OSFLAGS) \
		-o $@ $(BSD_TEST_SRC) $(if $(filter windows,$(PLATFORM)),-lws2_32,) -lpthread

.PHONY: test-bsd
test-bsd: $(BSD_TEST)
	$(BSD_TEST)
# The smoo.it server list (runtime/smooit.c): tests/smooit_test.c - the tolerant JSON parser (made-up *.example hosts
# and documentation IPs: online / offline / settings-string states, escaped quotes, missing fields, more than 64
# entries, garbage) and the online mod's keyboard prefill (each prompt, a non-mod header, host:port). No network, no
# game files: download_https_file is stubbed.
SMOOIT_TEST := $(B)/test_smooit$(if $(filter windows,$(PLATFORM)),.exe)
$(SMOOIT_TEST): tests/smooit_test.c runtime/smooit.c runtime/smooit.h runtime/download.h runtime/paths.h \
		runtime/settings.h runtime/rt.h
	@mkdir -p $(dir $@)
	$(CC) -O2 -g -fno-strict-aliasing -Wall -Wno-unused-function -Wno-format -Iruntime -Iruntime/nvn $(OSFLAGS) \
		-o $@ tests/smooit_test.c runtime/smooit.c -lpthread

.PHONY: test-smooit
test-smooit: $(SMOOIT_TEST)
	$(SMOOIT_TEST)


# ssl's IPC trace (runtime/services/ssl.c, ODYSSEY_SSL_TRACE): tests/ssl_trace_test.c drives ISslService, ISslContext
# and ISslConnection directly - the objects, what the commands set, the trace stub's handshake error, and (in a forked
# child, because the switch is read once) the generic stub's answer with the trace off. No game files, no network.
SSL_TRACE_TEST := $(B)/test_ssl_trace$(if $(filter windows,$(PLATFORM)),.exe)
$(SSL_TRACE_TEST): tests/ssl_trace_test.c runtime/services/ssl.c runtime/ipc.c runtime/nxcrypto.c runtime/ipc.h \
		runtime/kernel.h runtime/hle.h runtime/rt.h runtime/cpu.h runtime/platform.h runtime/nxcrypto.h
	@mkdir -p $(dir $@)
	$(CC) -O2 -g -fno-strict-aliasing -Wall -Wno-unused-function -Wno-format -Iruntime -Iruntime/nvn $(OSFLAGS) \
		-o $@ tests/ssl_trace_test.c runtime/services/ssl.c runtime/ipc.c runtime/nxcrypto.c -lpthread

.PHONY: test-ssl-trace
test-ssl-trace: $(SSL_TRACE_TEST)
	$(SSL_TRACE_TEST)

# The host-folder filesystem (runtime/services/fs.c: fsp-srv's IFile / IDirectory on the SD card and save data):
# tests/fs_hostfs_test.c drives service_lookup's fsp-srv entry on a temporary folder - an object's last guest reference
# (runtime/ipc.c service_release -> on_close) must close its host fd / DIR, or Windows can't delete a file still open
# (one the game read once) and a session leaks one fd per file it opens. POSIX host (/proc/self/fd, fcntl); no game
# files.
.PHONY: test-fs-hostfs
ifeq ($(PLATFORM),windows)
test-fs-hostfs:
	@echo "test-fs-hostfs: a POSIX host (a temporary folder, /proc/self/fd)"; exit 2
else
FS_HOSTFS_TEST := $(B)/test_fs_hostfs
$(FS_HOSTFS_TEST): tests/fs_hostfs_test.c runtime/services/fs.c runtime/ipc.c runtime/ipc.h runtime/kernel.h \
		runtime/hle.h runtime/rt.h runtime/cpu.h runtime/platform.h runtime/mods.h runtime/paths.h runtime/romfs_read.h
	@mkdir -p $(dir $@)
	$(CC) -O2 -g -fno-strict-aliasing -Wall -Wno-unused-function -Wno-format -Iruntime -Iruntime/nvn $(OSFLAGS) \
		-o $@ tests/fs_hostfs_test.c runtime/services/fs.c runtime/ipc.c -lpthread

test-fs-hostfs: $(FS_HOSTFS_TEST)
	$(FS_HOSTFS_TEST)
endif

# The account nickname setting (runtime/settings.c settings_player_name; the menu's Mods tab, Player name):
# tests/settings_player_name_test.c includes settings.c itself (its read-once values started over between checks) -
# the 32-byte UTF-8 cut, ODYSSEY_PLAYER_NAME > the setting > Link, the ini line's round trip. Writes in a temporary folder.
SETTINGS_NAME_TEST := $(B)/test_settings_player_name$(if $(filter windows,$(PLATFORM)),.exe)
$(SETTINGS_NAME_TEST): tests/settings_player_name_test.c runtime/settings.c runtime/settings.h runtime/input_bind.h runtime/platform.h
	@mkdir -p $(dir $@)
	$(CC) -O2 -g -fno-strict-aliasing -Wall -Wno-unused-function -Wno-format -Iruntime -Iruntime/nvn $(DEPINC) $(OSFLAGS) \
		-o $@ tests/settings_player_name_test.c -lSDL3 -lm

.PHONY: test-settings-player-name
test-settings-player-name: $(SETTINGS_NAME_TEST)
	$(SETTINGS_NAME_TEST)

# The Windows runtime's own tests: plain console programs over the real runtime files (no game, no SDL), each printing
# ok/FAIL and exiting non-zero on a FAIL. `make test-win-native` builds and runs all four: on a Windows host with the
# build's own compiler (the CI's windows-2022 runner: MSYS2 UCRT64 clang), on a Linux host with clang's MinGW target
# under Wine (WINE=... for Proton-GE's, WIN_PREFIX=<a throwaway prefix>).
#   1. tests/win_alias_test.c       the guest window: placeholders, a section at a module's address and again as a code
#                                   mod's RW alias, the reboot's reset (runtime/platform/windows_mem.c)
#   2. tests/win_bsd_reboot_test.c  bsd:u / bsd:s: a blocking Recv and a blocking Accept return when a reboot's stop
#                                   runs (bsd_reboot_stop), as tests/bsd_test.c's reboot section does on Linux
#   3. tests/win_fs_test.c          fsp-srv: a file / folder opened through it can be deleted once the guest closes it,
#                                   and after a reboot (tests/fs_hostfs_test.c's Windows counterpart)
#   4. tests/win_wine_test.c        Wine detection is off on real Windows (runtime/gamebuild.c's zig_clang); under Wine
#                                   the check is skipped, with a note
WINE       ?= wine
WIN_PREFIX ?= $(CURDIR)/build/wineprefix
ifeq ($(PLATFORM),windows)
WIN_CC        ?= $(CC) $(OSFLAGS)
WIN_TEST_RUN  :=
WIN_TEST_LIBS := -lws2_32 -lpthread
else
# clang's MinGW target: runtime/cpu.h uses clang's builtins (__builtin_bitreverse64, simd_fp.h's vector vocabulary),
# which mingw-w64's GCC has not. libwinpthread linked in, so Wine needs no libwinpthread-1.dll beside the program.
WIN_CC        ?= clang --target=x86_64-w64-mingw32 -D_FILE_OFFSET_BITS=64 -D_POSIX_THREAD_SAFE_FUNCTIONS -D_CRT_RAND_S \
	-DWIN32_LEAN_AND_MEAN -DNOMINMAX
WIN_TEST_RUN  := WINEPREFIX="$(WIN_PREFIX)" WINEDEBUG=-all "$(WINE)"
WIN_TEST_LIBS := -lws2_32 -Wl,-Bstatic -lwinpthread -Wl,-Bdynamic
endif

WIN_ALIAS_TEST := $(B)/win_alias_test.exe
$(WIN_ALIAS_TEST): tests/win_alias_test.c runtime/platform/windows_mem.c runtime/platform.h
	@mkdir -p $(dir $@)
	$(WIN_CC) -O1 -g -std=c11 -Iruntime -Iruntime/nvn -o $@ tests/win_alias_test.c runtime/platform/windows_mem.c

WIN_BSD_TEST := $(B)/win_bsd_reboot_test.exe
$(WIN_BSD_TEST): tests/win_bsd_reboot_test.c tests/bsd_test_stubs.c runtime/services/bsd.c runtime/services/sfdnsres.c \
		runtime/kernel.c runtime/hle.h runtime/ipc.h runtime/kernel.h runtime/cpu.h runtime/rt.h runtime/platform.h \
		runtime/settings.h runtime/services/sfdnsres.h
	@mkdir -p $(dir $@)
	$(WIN_CC) -O2 -g -fno-strict-aliasing -Wall -Wno-unused-function -Wno-format -Itests -Iruntime -Iruntime/nvn \
		-o $@ tests/win_bsd_reboot_test.c tests/bsd_test_stubs.c runtime/services/bsd.c runtime/services/sfdnsres.c \
		runtime/kernel.c $(WIN_TEST_LIBS)

WIN_FS_TEST := $(B)/win_fs_test.exe
$(WIN_FS_TEST): tests/win_fs_test.c runtime/services/fs.c runtime/ipc.c runtime/ipc.h runtime/kernel.h runtime/hle.h \
		runtime/rt.h runtime/cpu.h runtime/platform.h runtime/mods.h runtime/paths.h runtime/romfs_read.h
	@mkdir -p $(dir $@)
	$(WIN_CC) -O2 -g -fno-strict-aliasing -Wall -Wno-unused-function -Wno-format -Iruntime -Iruntime/nvn \
		-o $@ tests/win_fs_test.c runtime/services/fs.c runtime/ipc.c $(WIN_TEST_LIBS)

WIN_WINE_TEST := $(B)/win_wine_test.exe
$(WIN_WINE_TEST): tests/win_wine_test.c
	@mkdir -p $(dir $@)
	$(WIN_CC) -O2 -g -Wall -o $@ tests/win_wine_test.c

ifeq ($(PLATFORM),macos)
.PHONY: test-win-native test-win-alias
test-win-native test-win-alias:
	@echo "test-win-native: a Windows host, or a Linux host with clang's MinGW target and Wine"; exit 2
else
.PHONY: test-win-native
test-win-native: $(WIN_ALIAS_TEST) $(WIN_BSD_TEST) $(WIN_FS_TEST) $(WIN_WINE_TEST)
	@mkdir -p "$(WIN_PREFIX)"  # (Wine refuses a prefix folder that isn't there; it fills it on the first run)
	$(WIN_TEST_RUN) $(WIN_ALIAS_TEST)
	$(WIN_TEST_RUN) $(WIN_BSD_TEST)
	$(WIN_TEST_RUN) $(WIN_FS_TEST)
	$(WIN_TEST_RUN) $(WIN_WINE_TEST)

.PHONY: test-win-alias
test-win-alias: $(WIN_ALIAS_TEST)
	$(WIN_TEST_RUN) $(WIN_ALIAS_TEST)
endif

# The macOS runtime's own test: plain console program over the real memory code (no game, no SDL), printing ok/FAIL and
# exiting non-zero on a FAIL - the guest window and the code mod's rtld slot below it, plat_share, plat_alias at a
# page-congruent address, the refusal of one that isn't, plat_unalias and the reboot's reset (runtime/platform/macos.c;
# tests/mac_alias_test.c). A macOS host only
# (Apple Silicon: 16 KB pages; Intel Macs: 4 KB).
MAC_ALIAS_TEST := $(B)/mac_alias_test
$(MAC_ALIAS_TEST): tests/mac_alias_test.c runtime/platform/macos.c runtime/platform.h runtime/rt.h
	@mkdir -p $(dir $@)
	$(CC) -O1 -g -std=gnu11 -Wall -Wno-unused-function -Iruntime -Iruntime/nvn $(OSFLAGS) -o $@ tests/mac_alias_test.c \
		runtime/platform/macos.c

ifeq ($(PLATFORM),macos)
.PHONY: test-mac-native
test-mac-native: $(MAC_ALIAS_TEST)
	$(MAC_ALIAS_TEST)
else
.PHONY: test-mac-native
test-mac-native:
	@echo "test-mac-native: a macOS host (platform/macos.c's Mach VM pages and aliases)"; exit 2
endif

# Code mods' live sites (runtime/codemod_sites.c; docs/smoo-plus.md): tests/codemod_sites_test.c - the
# words a mod writes, each checked (registers against Unicorn, an emulator; a CMP's flags against the encoding; the jumps
# and x30; an entry site's switch between its body and the mod's word, a mid site's original and its nop), and the fatal
# path. No game files. Linked with the generator's Unicorn (the venv's static library).
# tools/test_codemod_sites_gen.sh then compiles a generated module as the game code is (-fvisibility=hidden), links it,
# and reads nm for the entry sites' bodies: with CODEGEN_SITES=<a game generated with --sites: its main/ or sdk/>, that;
# else the test's own little module (the generator's shapes, tools/test_codemod_sites_shapes.py).
CODEGEN_SITES ?=
UNICORN_DIR := $(firstword $(wildcard tools/venv/lib/python3*/site-packages/unicorn))
CODEMOD_SITES_TEST := $(B)/test_codemod_sites$(if $(filter windows,$(PLATFORM)),.exe)
$(CODEMOD_SITES_TEST): tests/codemod_sites_test.c runtime/codemod_sites.c runtime/codemod_sites.h runtime/cpu.h \
		runtime/rt.h runtime/gamelib.h
	@mkdir -p $(dir $@)
	$(CC) -O2 -g -fno-strict-aliasing -Wall -Wno-unused-function -Wno-format -Iruntime -I$(UNICORN_DIR)/include \
		$(OSFLAGS) -o $@ tests/codemod_sites_test.c runtime/codemod_sites.c \
		-L$(UNICORN_DIR)/lib -l:libunicorn.a -lm -lpthread

.PHONY: test-codemod-sites
ifeq ($(PLATFORM),linux)
test-codemod-sites: $(CODEMOD_SITES_TEST) tools/test_codemod_sites_gen.sh tools/test_codemod_sites_shapes.py
	$(CODEMOD_SITES_TEST)
	CC="$(CC)" sh tools/test_codemod_sites_gen.sh "$(CODEGEN_SITES)"
else
test-codemod-sites: $(CODEMOD_SITES_TEST)
	$(CODEMOD_SITES_TEST)
endif

# A code mod's sdk needs the runtime's HLE_FUNC bodies (tools/hle_funcs.py): a package has no runtime/ next
# to its generator, so it ships the names as gamelib-src/hle_funcs.txt and gen.py reads them (--hle-funcs).
# The check: the script's list is gen.py's walk, and gen.py on the real sdk with --sites, run from a copy of
# tools/ that has no ../runtime, writes the mod's nvnBootstrapLoader body as the runtime's - and refuses
# without the file instead of writing a library whose SDK bodies are the console's.
.PHONY: test-hle-funcs
test-hle-funcs:
	$(PY) tools/test_hle_funcs.py

# A code mod's OS edges (runtime/rtld.c's module list and nodes, runtime/platform/linux.c's shared pages and their RW
# aliases, runtime/kernel.c's GetInfo 65001 and svc 0x74/0x75, runtime/dispatch.c's trampoline resolver:
# docs/smoo-plus.md). tests/codemod_os_test.c runs them on real NSOs, read-only - the release's
# subsdk4 (SMOO_RELEASE, or CODEMOD_RELEASE in the environment) and exefs/{main,sdk} of a game (CODEGAME, default
# extracted/; without one, the checks that need it say so and skip) - the nodes against LibHakkun's own offsets
# (tests/codemod_os_ro_proof.c's aarch64 static_asserts, compiled first), sdk's "nvnBootstrapLoader" through its DT_HASH,
# a write through an alias seen at the original and back, and svc 0x74/0x75 with every module's aliases. No game run.
CODEMOD_OS_TEST := $(B)/test_codemod_os$(if $(filter windows,$(PLATFORM)),.exe)
CODEGAME ?= extracted
# (rtld.c, the kernel and the platform compiled in: the console is the test's, and without a frame pointer, so FATAL's
# rt_fatal_trace ends the check there. -lSDL3: platform/linux.c's error window.)
$(CODEMOD_OS_TEST): tests/codemod_os_test.c runtime/rtld.c runtime/dispatch.c runtime/codemod_sites.c \
		runtime/loader_hostdata.c runtime/platform/$(PLATFORM).c runtime/kernel.c runtime/cpu.h runtime/kernel.h \
		runtime/rt.h runtime/platform.h runtime/hle.h runtime/codemod.h runtime/gamelib.h tests/codemod_os_ro_proof.c
	@mkdir -p $(dir $@)
	$(CLANG) --target=aarch64-none-elf -fsyntax-only -std=c11 tests/codemod_os_ro_proof.c
	$(CC) -O2 -g -fno-strict-aliasing -fomit-frame-pointer -Wall -Wno-unused-function -Wno-format -DRTLD_TEST -Iruntime $(OSFLAGS) \
		-o $@ tests/codemod_os_test.c tests/codemod_os_words.c runtime/rtld.c runtime/dispatch.c runtime/codemod_sites.c \
		runtime/loader_hostdata.c runtime/platform/$(PLATFORM).c runtime/kernel.c -lpthread $(if $(filter linux,$(PLATFORM)),-lSDL3)

# Linux: the real thing (shared pages, mremap aliases). Elsewhere: the parts that are the same everywhere.
ifeq ($(PLATFORM),linux)
.PHONY: test-codemod-os
test-codemod-os: $(CODEMOD_OS_TEST)
	CODEMOD_RELEASE="$${CODEMOD_RELEASE:-$(SMOO_RELEASE)}" CODEGAME="$${CODEGAME:-$(CODEGAME)}" $(CODEMOD_OS_TEST)
else
.PHONY: test-codemod-os
test-codemod-os:
	@echo "test-codemod-os: Linux only (platform/linux.c's shared pages and aliases)"; exit 2
endif

# Code mods (runtime/codemod.h): tests/codemod_test.c finds a mod's folder in mods/ in both layouts, matches its sha256 to
# the known one, computes subsdk4's base (and the ones it can't have: 1.0.0's images give 0x7003800000), and runs the
# single-mod rule - with the real runtime/codemod.c, codemod_modules.c and mods.c (the app's parts they ask for are
# in the test).
# modules it makes - no game files. With SMOO_RELEASE=<the SMOO-Plus release's folder (SMOO-Plus/ of the Emulator zip,
# with exefs/ and romfs/)>, the real release; without, the temporary copy the test makes from it has to exist already
# (CODEMOD_TEST_RELEASE).
SMOO_RELEASE ?=
CODEMOD_TEST_SRC := tests/codemod_test.c
CODEMOD_TEST_LIBS := runtime/codemod.c runtime/codemod_modules.c runtime/mods.c
CODEMOD_TEST := $(B)/test_codemod$(if $(filter windows,$(PLATFORM)),.exe)
$(CODEMOD_TEST): $(CODEMOD_TEST_SRC) $(CODEMOD_TEST_LIBS) runtime/codemod.h runtime/mods.h runtime/rt.h \
		runtime/gamelib.h runtime/paths.h runtime/platform.h runtime/settings.h $(HLE_FUNCS_SRCS) Makefile
	@mkdir -p $(dir $@)
	$(CC) -O2 -g -fno-strict-aliasing -Wall -Wno-unused-function -Wno-format -Wno-unused-result -Iruntime -Iruntime/nvn $(OSFLAGS) \
		-DHLE_FUNCS_HASH=0x$(if $(strip $(HLE_FUNCS_HASH)),$(HLE_FUNCS_HASH),$(error HLE_FUNCS_HASH: $(HLE_FUNCS_PY) tools/hle_funcs.py --hash runtime printed nothing))ull \
		-o $@ $(CODEMOD_TEST_SRC) $(CODEMOD_TEST_LIBS) -lpthread

# Linux only (macOS' and Windows' platforms aren't part of the app's parts the test stands in for)
ifeq ($(PLATFORM),linux)
.PHONY: test-codemod
test-codemod: $(CODEMOD_TEST)
	@test -n "$(SMOO_RELEASE)" || test -n "$$CODEMOD_RELEASE" || { echo "test-codemod: SMOO_RELEASE=<the SMOO-Plus release folder (SMOO-Plus/ of the Emulator zip)>"; exit 2; }
	CODEMOD_RELEASE="$${CODEMOD_RELEASE:-$(SMOO_RELEASE)}" $(CODEMOD_TEST)
else
.PHONY: test-codemod
test-codemod:
	@echo "test-codemod: Linux only (macOS' and Windows' platforms aren't part of the test's stand-ins)"; exit 2
endif

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

# Windows: Super Odyssey Configuration.exe - the settings without the game (runtime/platform/configure_launcher.c starts
# the exe with --configure). Built as SuperOdysseyConfiguration.exe (make and spaces), shipped under its real name.
$(B)/rt/platform/configure_rc.o: runtime/platform/configure.rc runtime/platform/app.manifest docs/icon/icon.ico
	@mkdir -p $(dir $@)
	$(WINDRES) -I docs/icon -O coff $< -o $@
$(B)/SuperOdysseyConfiguration.exe: runtime/platform/configure_launcher.c $(B)/rt/platform/configure_rc.o
	$(CC) -O2 -municode -mwindows -fuse-ld=lld -o $@ $^
configure-exe: $(B)/SuperOdysseyConfiguration.exe

# Windows: the DLLs the exe loads (MSYS2 UCRT64's SDL3, FFmpeg, shaderc and what they pull in) copied next to it, so
# SuperOdysseyRecomp.exe starts from Explorer or a shortcut without MSYS2 on the PATH. vulkan-1.dll is the system's.
dlls: $(EXE)
	ldd $(EXE) | awk '/ucrt64/ && !/vulkan-1/ {print $$3}' | sort -u | xargs -I{} cp -u {} $(dir $(EXE))

# ---------------------------------------------------------------- release (Windows)
# build/dist/Super Odyssey PC Recomp-<version>-windows.zip, top folder "Super Odyssey PC Recomp/": the exe and the DLLs it loads (runs
# without MSYS2), what the setup page builds the game code with on the player's machine (runtime/gamebuild.c) - the
# generator (make gen-helper), zig (tools/fetch_zig.sh, slimmed by tools/zig_slim.sh: its runtime built ahead of time),
# gamelib-src/ and the exe's import library - the shader list, the menu font, README and LICENSE. No game code and no
# game files: the setup page (runtime/ui/setup.mm) builds them from the player's own. The exe is built in $(WIN_B)
# against the LGPL FFmpeg from `make deps-windows` (MSYS2's is a GPLv3 build); vulkan-1.dll is the system's.
# Also the vendors' upscaler runtimes (tools/fetch_upscalers.sh: DLSS, FSR 3.1 / 4, XeSS) and the pipeline seed.
# Order: make deps-windows; make gen-helper; tools/fetch_zig.sh; tools/fetch_upscalers.sh; make dist
# (all from a clean checkout: .github/workflows/build.yml does exactly this).
VERSION  := $(shell grep 'APP_VERSION' runtime/version.h | cut -d'"' -f2)
RC_VERSION := $(shell grep 'ProductVersion' runtime/platform/windows.rc | cut -d'"' -f4)
DIST     := build/dist/Super Odyssey PC Recomp
WIN_B    := build/win-release
ifeq ($(PLATFORM),windows)
PY312    ?= py -3.12
GEN_VPY  := build/gen-venv/Scripts/python.exe
else  # (macOS: the relocatable Python from `make deps`, so the helper runs on the app's oldest macOS)
PY312    ?= $(firstword $(wildcard build/deps/python/bin/python3.12) python3.12)
GEN_VPY  := build/gen-venv/bin/python
endif
deps-windows:
	tools/build_deps_windows.sh

# The game code generator as a standalone helper (tools/odysseygen.spec, PyInstaller, its own venv build/gen-venv):
# build/helper/odysseygen/, shipped as odysseygen/ next to the exe (macOS: in the .app's Resources). PyInstaller only
# builds for the OS it runs on (Linux: tools/linux/gen_helper.sh in the AppImage's build container).
# Windows: Python's own signed interpreter with the generator's sources and packages (tools/pyembed.py: a PyInstaller
# bundle was taken for a trojan by Windows Defender); macOS, Linux: frozen with PyInstaller (tools/odysseygen.spec).
ifeq ($(PLATFORM),windows)
gen-helper: build/gen-venv/.ok
	$(GEN_VPY) tools/pyembed.py build/helper/odysseygen
	@du -sh build/helper/odysseygen
else
gen-helper: build/gen-venv/.ok
	$(GEN_VPY) -m PyInstaller --noconfirm --clean --log-level WARN --distpath build/helper --workpath build/pyinstaller \
	    tools/odysseygen.spec
	@du -sh build/helper/odysseygen
endif
build/gen-venv/.ok:
	$(PY312) -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 $@

# ---------------------------------------------------------------- release (macOS, Linux)
# macOS: make deps (SDL3, LGPL FFmpeg, a relocatable Python - for macOS APP_MIN+), make gen-helper, tools/fetch_zig.sh,
# make dmg -> build/dist/Super Odyssey PC Recomp-<version>-macOS.dmg (Apple Silicon, ad-hoc signed).
# Linux: make appimage (podman, Ubuntu 22.04 containers: tools/linux/appimage.sh) -> build/dist/...-linux-x86_64.AppImage.
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)/SuperOdysseyRecomp
	MACOS_MIN=$(APP_MIN) tools/bundle_macos.sh $(APP_B)/SuperOdysseyRecomp
dmg: app
	tools/make_dmg.sh
appimage:
	tools/linux/appimage.sh $(or $(ARCH),x86_64)

dist:
	@[ "$(VERSION)" = "$(RC_VERSION)" ] || { echo "runtime/version.h ($(VERSION)) and windows.rc ($(RC_VERSION)) differ"; exit 1; }
	@[ -f build/deps-win/lib/libavcodec.dll.a ] || { echo "make deps-windows first (LGPL FFmpeg)"; exit 1; }
	@[ -d build/helper/odysseygen ] || { 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/upscalers/libxess.dll ] || { echo "tools/fetch_upscalers.sh first (DLSS, FSR, XeSS runtimes)"; exit 1; }
	$(MAKE) B=$(WIN_B) DEPS=$(CURDIR)/build/deps-win $(WIN_B)/SuperOdysseyRecomp.exe
	! nm $(WIN_B)/SuperOdysseyRecomp.exe | grep ' f_70' >/dev/null  # (no game code inside)
	$(GEN_VPY) tools/check_cpu_baseline.py $(WIN_B)/SuperOdysseyRecomp.exe --dispatched "$$($(CC) -print-file-name=libzstd.a)"  # (runs on AVX without AVX2: docs/CPU-BASELINE.md)
	rm -rf build/dist && mkdir -p "$(DIST)/gamelib-src"
	$(MAKE) B=$(WIN_B) $(WIN_B)/SuperOdysseyConfiguration.exe
	cp $(WIN_B)/SuperOdysseyRecomp.exe $(WIN_B)/SuperOdysseyRecomp.dll.a "$(DIST)/"
	cp $(WIN_B)/SuperOdysseyConfiguration.exe "$(DIST)/Super Odyssey Configuration.exe"
	strip --strip-debug "$(DIST)/SuperOdysseyRecomp.exe"  # (its debug info names the build folder; exports stay)
	tools/zig_slim.sh $(strip $(filter-out -Iruntime,$(GENFLAGS)))  # (zig with its runtime built ahead of time)
	cp -R build/helper/odysseygen "$(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 \
	    runtime/hle/hot_functions.txt "$(DIST)/gamelib-src/"
	$(GEN_VPY) tools/hle_funcs.py runtime "$(DIST)/gamelib-src/hle_funcs.txt"  # (gen.py --hle-funcs: a code mod's sdk bodies)
	cp runtime/nvn/vulkan/known_programs.txt third_party/imgui/misc/fonts/Roboto-Medium.ttf data/pipeline-seed.bin.zst data/shader-variants.bin data/shader-fills.bin data/prep-index.bin 	    README.md LICENSE recomplauncher.json "$(DIST)/"  # (recomplauncher.json: RecompLauncher's setup, next to the exe)
	mkdir -p "$(DIST)/lang" && cp runtime/ui/lang/*.txt "$(DIST)/lang/"  # (the menu's translations: runtime/ui/i18n.mm)
	mkdir -p "$(DIST)/data/mods/smoo-plus" && cp data/mods/smoo-plus/*.json "$(DIST)/data/mods/smoo-plus/"  # (the code mods' manifests: runtime/codemod.c codemod_manifest_path)
	mkdir -p "$(DIST)/fsr2" && cp third_party/fsr2/shaders/* third_party/fsr2/LICENSE.txt "$(DIST)/fsr2/"  # (FSR 2: runtime/nvn/vulkan/fsr2.c)
	cp build/upscalers/*.dll "$(DIST)/"  # (loaded only when chosen in the menu)
	tools/dist_licenses.sh "$(DIST)"  # (every shipped component's licence and source: licenses/README.txt)
	PATH="$(CURDIR)/build/deps-win/bin:$$PATH" ldd $(WIN_B)/SuperOdysseyRecomp.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)
	tools/dist_check_paths.sh "$(DIST)"  # (no path of this machine inside: debug info, caches, logs)
	cd build/dist && /c/Windows/System32/tar.exe -a -cf "Super Odyssey PC Recomp-$(VERSION)-windows.zip" "Super Odyssey PC Recomp"
	@echo "build/dist/Super Odyssey PC Recomp-$(VERSION)-windows.zip"

.PHONY: all gen gen-codemod codemod codemod-libs gen-objs runtime-objs dlls configure-exe deps-windows gen-helper dist deps app dmg appimage print-cc

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
