cmake_minimum_required(VERSION 3.25)
project(uc LANGUAGES C CXX)   # C for the third-party mod runtimes (miniz, Lua, QuickJS)
if(WIN32)
  enable_language(RC)
endif()
# The Linux (Steam Deck) cross build: cmake --toolchain cmake/toolchains/linux-sniper.cmake, see scripts/linux/build.ps1.
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
  set(UC_LINUX ON)
endif()
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Compiler cache: the 108 generated game files take about 25 CPU minutes, and a revert, a switch between two states or a clean tree finds them in the cache.
# Used when ccache is installed (winget install Ccache.Ccache); -DUC_CCACHE=OFF turns it off. MSVC-style /Zi debug info (a shared PDB) cannot be cached: the build then compiles as before.
option(UC_CCACHE "use ccache as the compiler launcher when it is installed" ON)
if(UC_CCACHE)
  file(GLOB uc_ccache_hints "$ENV{LOCALAPPDATA}/Microsoft/WinGet/Packages/Ccache.Ccache_*/ccache-*")   # where winget unpacks it: a shell started before the install does not have it on PATH
  find_program(UC_CCACHE_PROGRAM ccache HINTS ${uc_ccache_hints} "$ENV{LOCALAPPDATA}/Microsoft/WinGet/Links")
  if(UC_CCACHE_PROGRAM)
    # pch_defines,time_macros: lets ccache use the precompiled headers of the game/runtime targets (without it it reports "could not use precompiled header" and compiles those files uncached).
    # The settings go with the call, so a shell that does not have the user's ccache configuration (PowerShell and Git Bash read different ones) behaves the same.
    set(CMAKE_C_COMPILER_LAUNCHER "${CMAKE_COMMAND}" -E env CCACHE_SLOPPINESS=pch_defines,time_macros "${UC_CCACHE_PROGRAM}")
    set(CMAKE_CXX_COMPILER_LAUNCHER "${CMAKE_COMMAND}" -E env CCACHE_SLOPPINESS=pch_defines,time_macros "${UC_CCACHE_PROGRAM}")
    message(STATUS "ccache: ${UC_CCACHE_PROGRAM}")
  endif()
endif()
if(WIN32 AND CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
  add_compile_options(/clang:-march=x86-64-v3)
endif()
if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
  add_compile_options(-Wno-deprecated-declarations)   # "unsafe CRT function" (getenv, fopen), winsock and std::filesystem::u8path notes in the tools and third-party code are noise
endif()
# Guest memory access tracer (runtime/mem_trace.h): records the loads and stores of selected translated functions to find work that can run in parallel. Diagnostics only,
# 20x slower; build it in its own folder (the leaf functions then run as translated code, so every access is seen).
option(UC_TRACE_MEM "record guest memory accesses of the functions in UC_TRACE_MEM_FUNCS" OFF)
if(UC_TRACE_MEM)
  add_compile_definitions(UC_TRACE_MEM=1)
endif()
# Profile-guided optimization: ~8% more frames in gameplay. `python scripts/pgo.py` records project/pgo/uc.profdata from a harness run of an
# instrumented build; while that file exists every build uses it (stale parts are ignored silently, re-record after big changes).
option(UC_PGO_GENERATE "build an instrumented uc.exe that records a profile (scripts/pgo.py)" OFF)
set(UC_PGO_PROFILE "${CMAKE_SOURCE_DIR}/project/pgo/uc.profdata" CACHE FILEPATH "profile for the optimizer; used when the file exists")
if(WIN32 AND CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
  if(UC_PGO_GENERATE)
    add_compile_options($<$<COMPILE_LANGUAGE:CXX>:/clang:-fprofile-instr-generate>)
    get_filename_component(uc_llvm_bin "${CMAKE_CXX_COMPILER}" DIRECTORY)
    file(GLOB uc_profile_runtime "${uc_llvm_bin}/../lib/clang/*/lib/windows/clang_rt.profile-x86_64.lib")
    if(NOT uc_profile_runtime)
      message(FATAL_ERROR "clang_rt.profile-x86_64.lib not found next to ${CMAKE_CXX_COMPILER}")
    endif()
    add_link_options("${uc_profile_runtime}")
  elseif(EXISTS "${UC_PGO_PROFILE}")
    # A new profile must rebuild every object; mixed ThinLTO profile summaries cannot link.
    file(SHA256 "${UC_PGO_PROFILE}" uc_pgo_hash)
    set(uc_pgo_input "${CMAKE_BINARY_DIR}/pgo/${uc_pgo_hash}.profdata")
    configure_file("${UC_PGO_PROFILE}" "${uc_pgo_input}" COPYONLY)
    add_compile_options($<$<COMPILE_LANGUAGE:CXX>:/clang:-fprofile-instr-use=${uc_pgo_input}> -Wno-profile-instr-unprofiled -Wno-profile-instr-missing -Wno-profile-instr-out-of-date)
    message(STATUS "PGO profile: ${UC_PGO_PROFILE}")
  endif()
endif()
# ThinLTO across the translated game, runtime and renderer (lets the small native helpers be inlined into generated code); the link is slow.
option(UC_THINLTO "build with ThinLTO (build.bat and scripts/dev.bat turn it on)" OFF)
if(UC_THINLTO AND WIN32 AND CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
  add_compile_options($<$<COMPILE_LANGUAGE:CXX>:/clang:-flto=thin>)
  add_link_options("/lldltocache:${CMAKE_BINARY_DIR}/lto-cache")
endif()
if(UC_LINUX AND CMAKE_CXX_COMPILER_ID STREQUAL "Clang")   # the Steam Deck build: scripts/linux/pgo.py records project/pgo/uc-linux.profdata (names differ from the Windows profile)
  set(UC_PGO_LINUX_PROFILE "${CMAKE_SOURCE_DIR}/project/pgo/uc-linux.profdata" CACHE FILEPATH "profile for the Linux optimizer; used when the file exists")
  if(UC_PGO_GENERATE)
    get_filename_component(uc_llvm_bin "${CMAKE_CXX_COMPILER}" DIRECTORY)
    file(GLOB uc_profile_include "${uc_llvm_bin}/../lib/clang/*/include")
    add_library(uc_profile_rt STATIC runtime/linux_profile_rt.c)   # the sysroot's runtime is LLVM 11's: this one writes the compiler's own raw format (see the file)
    target_include_directories(uc_profile_rt PRIVATE ${uc_profile_include})
    add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-fprofile-instr-generate> "SHELL:$<$<COMPILE_LANGUAGE:CXX>:-mllvm -enable-value-profiling=false>")
    # linked by the game only (game/CMakeLists.txt): a global link_libraries would reach third-party targets with export sets
  elseif(EXISTS "${UC_PGO_LINUX_PROFILE}")
    file(SHA256 "${UC_PGO_LINUX_PROFILE}" uc_pgo_hash)
    set(uc_pgo_input "${CMAKE_BINARY_DIR}/pgo/${uc_pgo_hash}.profdata")
    configure_file("${UC_PGO_LINUX_PROFILE}" "${uc_pgo_input}" COPYONLY)
    add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-fprofile-instr-use=${uc_pgo_input}> -Wno-profile-instr-unprofiled -Wno-profile-instr-missing -Wno-profile-instr-out-of-date)
    message(STATUS "PGO profile: ${UC_PGO_LINUX_PROFILE}")
  endif()
endif()
if(UC_THINLTO AND UC_LINUX)   # the Linux (Steam Deck) build: scripts/linux/build.ps1 -ThinLTO (own build folder)
  add_compile_options(-flto=thin)
  add_link_options(-flto=thin "-Wl,--thinlto-cache-dir=${CMAKE_BINARY_DIR}/lto-cache")
endif()
enable_testing()
if(UC_LINUX)
  # Only what already builds for Linux; each platform-port task adds its libraries here (docs/superpowers/plans/2026-10-30-linux-port-bringup.md).
  add_subdirectory(common)
  add_subdirectory(runtime)
  add_subdirectory(renderer)
  add_subdirectory(modding)
  add_subdirectory(updater)    # the POSIX update stack (updater/posix) for the Deck launcher
  add_subdirectory(launcher)   # only the pieces the game shares (settings UI, bindings editor); the launcher program itself is Windows-only
  add_subdirectory(game)
  add_subdirectory(tests/linux)
  return()
endif()
# Every test runs on a desktop of its own (tools/hidden_run): the windows the tests open never appear over what the user is doing and never take the focus, however ctest is
# started. Set before any test program is created (CMake copies it into each program's TEST_LAUNCHER). UC_TESTS_VISIBLE=1 shows them.
add_subdirectory(tools/hidden_run)
set(CMAKE_TEST_LAUNCHER "$<TARGET_FILE:uc_hidden_run>")   # the tests that are programs of this build
# The tests that are a script (python, cmake -P) can start programs with windows too (test_update_end_to_end runs the launcher and the updater): add_test puts the launcher
# in front of their command as well. (The original command stays reachable as _add_test; a program of this build already has the launcher.)
function(add_test)
  if(NOT ARGV0 STREQUAL "NAME")
    _add_test(${ARGV})
    return()
  endif()
  set(arguments ${ARGN})
  list(FIND arguments "COMMAND" at)
  if(at GREATER_EQUAL 0)
    math(EXPR first "${at}+1")
    list(GET arguments ${first} program)
    if(NOT TARGET "${program}")
      list(INSERT arguments ${first} "$<TARGET_FILE:uc_hidden_run>")
    endif()
  endif()
  _add_test(${arguments})
endfunction()
add_subdirectory(common)
add_subdirectory(runtime)
add_subdirectory(renderer)
add_subdirectory(modding)
add_subdirectory(updater)
add_subdirectory(tools/s1_scan)
add_subdirectory(tools/dol_coverage)
add_subdirectory(tools/translator)
add_subdirectory(tools/opcheck_gen)
add_subdirectory(tools/sigmatch)
add_subdirectory(tools/xref)
add_subdirectory(tools/texture_extract)
add_subdirectory(tools/dump_text)
add_subdirectory(tools/arc_tool)
add_subdirectory(tools/sfd_tool)
add_subdirectory(tools/texture_convert)
add_subdirectory(tools/fifo_replay)
add_subdirectory(tests)
add_subdirectory(game)
add_subdirectory(launcher)
add_subdirectory(mods-examples/hello_native)   # after the launcher: it fetches the ImGui source the example DLL builds against
# Staged into dist: the example mods (not their sources), the header native mods build against, and the modding documentation.
install(DIRECTORY mods-examples/ DESTINATION mods-examples PATTERN "CMakeLists.txt" EXCLUDE PATTERN "src" EXCLUDE)
install(FILES modding/uc_mod.h DESTINATION sdk)
install(DIRECTORY docs/modding/ DESTINATION docs/modding)
# Portable clients and the isolated updater need the compiler's redistributable runtime.
set(CMAKE_INSTALL_SYSTEM_RUNTIME_DESTINATION .)
include(InstallRequiredSystemLibraries)
set(uc_helper_runtime_names "uc_updater.exe\n")
set(uc_helper_runtime_sources "$<TARGET_FILE:uc_updater>\n")
foreach(uc_runtime_file IN LISTS CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS)
  get_filename_component(uc_runtime_name "${uc_runtime_file}" NAME)
  string(APPEND uc_helper_runtime_names "${uc_runtime_name}\n")
  string(APPEND uc_helper_runtime_sources "${uc_runtime_file}\n")
endforeach()
file(GENERATE OUTPUT "${CMAKE_BINARY_DIR}/updater-runtime-files.txt" CONTENT "${uc_helper_runtime_names}")
file(GENERATE OUTPUT "${CMAKE_BINARY_DIR}/updater-runtime-sources.txt" CONTENT "${uc_helper_runtime_sources}")
