cmake_minimum_required(VERSION 3.20)
project(gt5
    VERSION 0.1.0
    LANGUAGES C CXX
    DESCRIPTION "Gran Turismo 5 static recompilation"
)

set(CMAKE_C_STANDARD 17)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

set(PS3RECOMP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../ps3recomp" CACHE PATH "ps3recomp checkout")
get_filename_component(PS3RECOMP_DIR "${PS3RECOMP_DIR}" ABSOLUTE)

set(RECOMP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/generated")
set(SPU_DIR "${CMAKE_CURRENT_SOURCE_DIR}/spu")

if(NOT EXISTS "${RECOMP_DIR}/ppu_recomp.h")
    message(FATAL_ERROR "No ppu_recomp.h in ${RECOMP_DIR}. Run scripts/relift.ps1 first.")
endif()

file(GLOB RECOMP_SOURCES CONFIGURE_DEPENDS "${RECOMP_DIR}/*.cpp")
list(LENGTH RECOMP_SOURCES RECOMP_SOURCE_COUNT)
message(STATUS "Lifted sources:  ${RECOMP_SOURCE_COUNT} file(s)")

# Movies decode through FFmpeg, loaded at run time; only its headers are needed to build. get-ffmpeg.ps1 (setup.ps1,
# update.ps1) puts it in this folder. It is optional: without it the game builds and runs, and only its movies don't
# play; get-ffmpeg.ps1 makes the build folder configure again when it arrives later.
set(GT5_FFMPEG_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../ffmpeg/ffmpeg-n9.0-latest-win64-lgpl-shared-9.0")
if(EXISTS "${GT5_FFMPEG_DIR}/include/libavcodec/avcodec.h")
    set(PS3RECOMP_FFMPEG_RUNTIME ON CACHE BOOL "" FORCE)
    set(PS3RECOMP_FFMPEG_INCLUDE_DIR "${GT5_FFMPEG_DIR}/include" CACHE PATH "" FORCE)
else()
    message(STATUS "GT5: no FFmpeg in ${GT5_FFMPEG_DIR}: this build plays no movies")
    set(PS3RECOMP_FFMPEG_RUNTIME OFF CACHE BOOL "" FORCE)
endif()
# Vulkan as a second renderer (the launcher's Display > Renderer; DirectX 12 stays the default).
# scripts\add_vulkan.ps1 builds SDL2 and glslang into deps\vulkan and turns it on; a build folder set up
# again later finds them there by itself.
set(GT5_VULKAN_PREFIX "${CMAKE_CURRENT_SOURCE_DIR}/deps/vulkan/prefix")
if(EXISTS "${GT5_VULKAN_PREFIX}/include/vulkan/vulkan.h")
    if(NOT DEFINED PS3RECOMP_RSX_VULKAN)
        set(PS3RECOMP_RSX_VULKAN ON CACHE BOOL "Build the Vulkan RSX backend (Linux, Android; Windows for testing)")
    endif()
    list(APPEND CMAKE_PREFIX_PATH "${GT5_VULKAN_PREFIX}")
endif()
# Every SPU program GT5 runs is converted to PC code at setup (scripts/spu_jobs_from_eboot.py finds them all,
# lift_spu_jobs.py converts them, each with an any-address form). The SPU interpreter stays in as the last
# resort, as before: an address no lift covers (code reached only through a table or a computed branch that
# neither the converter nor a game run has named) runs there, the game goes on, and SPU_TARGET_LOG names the
# address for scripts/spu_static_entries.txt. -DGT5_SPU_NO_INTERP_TEST=ON (testing builds only) leaves the
# interpreter out: such an address then ends its job ("[spu-static] no converted code"), which can hang the
# game. (static2_spu 4c: Europe 2.11 hung so, at a bytecode handler the old build ran in the interpreter. The
# option's old name, GT5_SPU_NO_INTERP, was ON by default and stays in older build folders' caches unread.)
option(GT5_SPU_NO_INTERP_TEST "GT5 without the SPU interpreter (testing builds only)" OFF)
set(PS3RECOMP_SPU_NO_INTERP ${GT5_SPU_NO_INTERP_TEST} CACHE BOOL "Build without the SPU interpreter (every SPU program converted)" FORCE)
add_subdirectory("${PS3RECOMP_DIR}" "${CMAKE_BINARY_DIR}/ps3recomp_sdk" EXCLUDE_FROM_ALL)

# The HLE NID table comes from the toolkit under build, regenerated by relift.ps1:
# one built against another revision can reference handlers this one lacks.
set(HLE_NID_TABLE "${CMAKE_CURRENT_SOURCE_DIR}/src/gen/ppu_hle_nids.cpp")

# The shared boot harness rather than a port main.cpp: it is the only entry point
# that turns on the live NV4097 -> D3D12 engine (RSX_LIVE_DRAW=1).
set(PS3RECOMP_SCAFFOLD
    "${PS3RECOMP_DIR}/runtime/ppu/tests/boot_main.cpp"
    "${PS3RECOMP_DIR}/runtime/ppu/ppu_loader.cpp"
    "${PS3RECOMP_DIR}/runtime/ppu/ppu_hle.cpp"
    "${PS3RECOMP_DIR}/runtime/ppu/ppu_fs.cpp"
    "${PS3RECOMP_DIR}/runtime/ppu/ppu_sysprx.cpp"
)

# Lifted SPU images, registered with the runtime by content fingerprint. Only the
# ones build_spu_workloads.py registered: the other images it lifted carry shuffle
# tables inside their code ranges and run in the SPU interpreter for now.
set(SPU_SOURCES "")
if(EXISTS "${SPU_DIR}/sources.cmake")
    include("${SPU_DIR}/sources.cmake")
    list(LENGTH SPU_GENERATED_SOURCES SPU_SOURCE_COUNT)
    message(STATUS "Lifted SPU:      ${SPU_SOURCE_COUNT} file(s)")
    # The musttail indirect-branch fast path has to be built here, by clang.
    list(APPEND SPU_SOURCES ${SPU_GENERATED_SOURCES} "${PS3RECOMP_DIR}/runtime/spu/spu_dispatch_mt.c")
endif()

# Raw SPU images captured from a run; see scripts/lift_spu_jobs.py.
file(GLOB SPU_JOB_SOURCES CONFIGURE_DEPENDS "${SPU_DIR}/jobs/*/spu_recomp.c")
if(SPU_JOB_SOURCES)
    list(LENGTH SPU_JOB_SOURCES SPU_JOB_COUNT)
    message(STATUS "Lifted SPU jobs: ${SPU_JOB_COUNT} image(s)")
    list(APPEND SPU_SOURCES ${SPU_JOB_SOURCES} "${CMAKE_CURRENT_SOURCE_DIR}/src/gen/spu_jobs.c")
endif()
# Each image's any-address form (spu_lifter.py --any-address, n_static 22 Nov 2026): every instruction address
# enterable, so the runtime never interprets an address of a known image. Compiled as the image's own file is.
file(GLOB SPU_ANY_SOURCES CONFIGURE_DEPENDS "${SPU_DIR}/jobs/*/spu_anyaddr.c")
if(SPU_ANY_SOURCES)
    list(APPEND SPU_SOURCES ${SPU_ANY_SOURCES})
endif()

add_executable(gt5
    src/gt5_longjmp.cpp
    src/gt5_debug.cpp
    src/gt5_widescreen.cpp
    src/gt5_cockpit.cpp
    src/gt5_ticks.cpp
    src/gt5_carlod.cpp
    src/gt5_freecam.cpp
    src/gt5_padmap.cpp
    src/gt5_threadstats.cpp
    src/gt5_framerate.cpp
    src/gt5_volread.cpp
    src/gt5_glyphs.cpp
    src/gt5_glyph_art.c
    ${PS3RECOMP_SCAFFOLD}
    ${HLE_NID_TABLE}
    ${RECOMP_SOURCES}
    ${SPU_SOURCES}
)

# The in-game settings menu (F1): Dear ImGui 1.93.0 (third_party/imgui, MIT, unmodified) on the D3D12 renderer,
# and on the Vulkan one when the build has it (gt5_menu_vk.cpp, imgui_impl_vulkan). Input, sizes and pages are
# shared (gt5_menu.cpp, gt5_menu_ui.cpp); each renderer has a file of its own for the drawing.
# The runtime calls it through runtime/settings/gt5_menu.h and gt5_menu_vk.h; a build without these sources
# links the runtime's empty stand-ins (gt5_menu_stub.c) instead.
set(GT5_IMGUI_DIR "${CMAKE_CURRENT_SOURCE_DIR}/third_party/imgui")
if(WIN32 AND EXISTS "${GT5_IMGUI_DIR}/imgui.cpp" AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/src/menu/gt5_menu.cpp")
    set(GT5_MENU_SOURCES
        src/menu/gt5_menu.cpp
        src/menu/gt5_menu_ui.cpp
        src/menu/gt5_menu_dx12.cpp
        src/menu/gt5_binds.c)
    set(GT5_IMGUI_SOURCES
        "${GT5_IMGUI_DIR}/imgui.cpp" "${GT5_IMGUI_DIR}/imgui_draw.cpp" "${GT5_IMGUI_DIR}/imgui_tables.cpp"
        "${GT5_IMGUI_DIR}/imgui_widgets.cpp" "${GT5_IMGUI_DIR}/backends/imgui_impl_dx12.cpp")
    target_sources(gt5 PRIVATE ${GT5_MENU_SOURCES} ${GT5_IMGUI_SOURCES})
    set(_menu_inc "${GT5_IMGUI_DIR};${GT5_IMGUI_DIR}/backends;${PS3RECOMP_DIR}/runtime/settings")
    set(_menu_defs "IMGUI_DISABLE_DEMO_WINDOWS;IMGUI_DISABLE_DEBUG_TOOLS;IMGUI_DISABLE_OBSOLETE_FUNCTIONS")
    set_source_files_properties(${GT5_MENU_SOURCES} ${GT5_IMGUI_SOURCES} PROPERTIES
        INCLUDE_DIRECTORIES "${_menu_inc}" COMPILE_DEFINITIONS "${_menu_defs}")
    set_source_files_properties(${GT5_IMGUI_SOURCES} PROPERTIES COMPILE_OPTIONS "/w")
    # The Vulkan renderer's drawing: its functions come from the runtime's loader (VK_NO_PROTOTYPES), so
    # nothing links to vulkan-1.dll; the headers are the ones the Vulkan build uses.
    if(PS3RECOMP_RSX_VULKAN AND EXISTS "${GT5_IMGUI_DIR}/backends/imgui_impl_vulkan.cpp" AND PS3RECOMP_VULKAN_INCLUDE_DIR)
        set(GT5_MENU_VK_SOURCES src/menu/gt5_menu_vk.cpp "${GT5_IMGUI_DIR}/backends/imgui_impl_vulkan.cpp")
        target_sources(gt5 PRIVATE ${GT5_MENU_VK_SOURCES})
        set_source_files_properties(${GT5_MENU_VK_SOURCES} PROPERTIES
            INCLUDE_DIRECTORIES "${_menu_inc};${PS3RECOMP_VULKAN_INCLUDE_DIR}" COMPILE_DEFINITIONS "${_menu_defs};VK_NO_PROTOTYPES")
        set_source_files_properties("${GT5_IMGUI_DIR}/backends/imgui_impl_vulkan.cpp" PROPERTIES COMPILE_OPTIONS "/w")
        message(STATUS "In-game menu:    on (Dear ImGui), DirectX 12 and Vulkan")
    else()
        message(STATUS "In-game menu:    on (Dear ImGui)")
    endif()
    target_link_libraries(gt5 PRIVATE d3dcompiler shell32)
endif()

# SMAA 1x (third_party/smaa, MIT, unmodified), the game's own anti-aliasing (LD_AA=smaa) on the D3D12 renderer:
# src/aa/gt5_smaa.cpp, the third back end behind the renderer's upscaler interface (gt5_upscale.h). The runtime
# calls gt5_smaa_get(); a build without this file links the runtime's stand-in (libs/video/rsx_smaa_none.c).
# SMAA.hlsl goes into the executable as bytes (gen_smaa/smaa_hlsl.h, rewritten only when it changes).
set(GT5_SMAA_DIR "${CMAKE_CURRENT_SOURCE_DIR}/third_party/smaa")
if(WIN32 AND EXISTS "${GT5_SMAA_DIR}/SMAA.hlsl" AND EXISTS "${GT5_SMAA_DIR}/AreaTex.h" AND EXISTS "${GT5_SMAA_DIR}/SearchTex.h")
    file(READ "${GT5_SMAA_DIR}/SMAA.hlsl" _smaa_hex HEX)
    string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," _smaa_bytes "${_smaa_hex}")
    file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/gen_smaa/smaa_hlsl.h.new"
        "/* SMAA.hlsl (third_party/smaa), written by GT5/CMakeLists.txt */\nstatic const unsigned char k_smaa_hlsl[] = {${_smaa_bytes}0x00};\n")
    configure_file("${CMAKE_CURRENT_BINARY_DIR}/gen_smaa/smaa_hlsl.h.new" "${CMAKE_CURRENT_BINARY_DIR}/gen_smaa/smaa_hlsl.h" COPYONLY)
    set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${GT5_SMAA_DIR}/SMAA.hlsl")
    target_sources(gt5 PRIVATE src/aa/gt5_smaa.cpp)
    set_source_files_properties(src/aa/gt5_smaa.cpp PROPERTIES
        INCLUDE_DIRECTORIES "${GT5_SMAA_DIR};${CMAKE_CURRENT_BINARY_DIR}/gen_smaa;${PS3RECOMP_DIR}/libs/video")
    message(STATUS "Anti-aliasing:   SMAA built in (DirectX 12)")
endif()

# Game-code mods (scripts/mods.py, MODDING.md): the start-up switch of each mod that applies to
# this EBOOT. The file only exists when one does.
file(GLOB GT5_MOD_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/gen/mods.cpp")
if(GT5_MOD_SOURCES)
    target_sources(gt5 PRIVATE ${GT5_MOD_SOURCES})
    # The Frame rate setting (60 / 30) switches the half-rate mod's pacer while the game runs
    # (src/gt5_framerate.cpp): only when the mod applies to this EBOOT, so that its switch exists.
    # A re-lift rewrites mods.cpp: configure again then, so this follows it.
    set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${GT5_MOD_SOURCES}")
    file(STRINGS "${GT5_MOD_SOURCES}" _half_rate REGEX "int g_mod_half_rate")
    if(_half_rate)
        set_property(SOURCE src/gt5_framerate.cpp APPEND PROPERTY COMPILE_DEFINITIONS GT5_HAVE_HALF_RATE=1)
        message(STATUS "Frame rate:      60 and 30 (the half-rate mod's switch)")
    else()
        message(STATUS "Frame rate:      60 only (no half-rate mod for this EBOOT)")
    endif()
endif()

# The processor the game code is built for: GT5_CPU, which scripts\build.cmd sets from this PC's processor
# (scripts\cpu_level.ps1 asks the compiler what it has; the environment variable GT5_CPU overrides that).
# Every level runs the same game code with the same results; only the instructions differ, and a lower
# level runs slower.
#   avx2     (the default) AVX2 with FMA, BMI1/2, MOVBE, LZCNT: Intel Haswell (2013) and later Core, AMD
#            Excavator, Zen and later. The flags as always.
#   avx-fma  AVX with FMA3, no AVX2: AMD FX Piledriver / Steamroller (FX-4300/6300/8350, A8/A10 APUs).
#   avx      AVX, no FMA: Intel Sandy / Ivy Bridge (2nd and 3rd generation Core), AMD FX Bulldozer.
#   sse42    SSE4.2 and POPCNT, no AVX: Intel Pentium / Celeron before 2020, Atom, 1st generation Core.
# Below avx2 the natives written with AVX2 instructions (GT5_NATIVE_AVX2_ONLY) are left out and their jobs
# run as lifted code, as GT5_NATIVE_GEO=0 / GT5_CULLX=0 / GT5_CAD00_NATIVE=0 run them; the sound natives
# (src/native/native_fma.h) and the generated ones stay.
set(GT5_CPU "avx2" CACHE STRING "Processor level of the game code: avx2 (default), avx-fma, avx, sse42")
set_property(CACHE GT5_CPU PROPERTY STRINGS avx2 avx-fma avx sse42)
set(GT5_CPU_LEVELS_ALL sse42 avx avx-fma avx2)   # in order; the guard gets the index
# Below avx-fma there is no FMA instruction, so the game code's fma() / fmaf() (the PPU's fmadd family, the SPU's
# double fma, vmx_fmaf, native_fma.h) are the C library's, whose software path gives +0 where the instruction gives
# -0 and goes its own way under DAZ / FTZ. src/gt5_fma_fix.h, force-included at those two levels only (the generated
# files can't change), gives them the instruction's results; avx2 and avx-fma never see it.
set(GT5_FMA_FIX "/FI${CMAKE_CURRENT_SOURCE_DIR}/src/gt5_fma_fix.h")
if(GT5_CPU STREQUAL "avx2")
    set(GT5_CPU_SPU_FLAGS "-mavx2;-mfma")
    set(GT5_CPU_PPU_FLAGS "-mavx2;-mfma;-mbmi;-mbmi2;-mmovbe;-mlzcnt;-mpopcnt")
elseif(GT5_CPU STREQUAL "avx-fma")
    set(GT5_CPU_SPU_FLAGS "-mavx;-mfma;-mpopcnt")
    set(GT5_CPU_PPU_FLAGS "-mavx;-mfma;-mpopcnt")
elseif(GT5_CPU STREQUAL "avx")
    set(GT5_CPU_SPU_FLAGS "-mavx;-mpopcnt;${GT5_FMA_FIX}")
    set(GT5_CPU_PPU_FLAGS "-mavx;-mpopcnt;${GT5_FMA_FIX}")
elseif(GT5_CPU STREQUAL "sse42")
    set(GT5_CPU_SPU_FLAGS "-msse4.2;-mpopcnt;${GT5_FMA_FIX}")
    set(GT5_CPU_PPU_FLAGS "-msse4.2;-mpopcnt;${GT5_FMA_FIX}")
else()
    message(FATAL_ERROR "GT5_CPU=${GT5_CPU}: it is avx2, avx-fma, avx or sse42.")
endif()
set(GT5_NATIVE_AVX2_ONLY native_w018CAD00.c native_cad00.c native_w01606C00.c native_w0163C080.c)
message(STATUS "Processor level: ${GT5_CPU}")
# The SPU interpreter (the runtime's one file with guest fused multiply-adds: spu__dfmx) gets the same fix.
if(GT5_CPU STREQUAL "avx" OR GT5_CPU STREQUAL "sse42")
    set_property(SOURCE "${PS3RECOMP_DIR}/runtime/spu/spu_interp.c" TARGET_DIRECTORY ps3recomp_runtime
                 APPEND PROPERTY COMPILE_OPTIONS "${GT5_FMA_FIX}")
endif()
# The start-up check that this processor (and its system) has what the level needs: src/gt5_cpuguard.c, a plain
# message and exit code 22 instead of an "illegal instruction" crash. It runs before every constructor of the game
# code (a .CRT$XIY initializer on Windows, constructor priority 101 on Linux), so it is built with the target's own
# flags -- the baseline, never the level's; only the level's number reaches it (sse42 0, avx 1, avx-fma 2, avx2 3).
list(FIND GT5_CPU_LEVELS_ALL "${GT5_CPU}" GT5_CPU_LEVEL_N)
target_sources(gt5 PRIVATE src/gt5_cpuguard.c)
set_source_files_properties(src/gt5_cpuguard.c PROPERTIES COMPILE_DEFINITIONS "GT5_CPU_LEVEL=${GT5_CPU_LEVEL_N}")

# Scoped so the huge PPU TUs keep their cached compile commands. /GS-: no stack-cookie check in
# every lifted SPU function (most are a basic block long; their locals hold no guest-sized buffers).
if(SPU_SOURCES)
    set_source_files_properties(${SPU_SOURCES} PROPERTIES
        INCLUDE_DIRECTORIES "${PS3RECOMP_DIR}/runtime/spu"
        COMPILE_DEFINITIONS SPU_USE_DISPATCH_MT
        COMPILE_OPTIONS "-O2;/w;/GS-;${GT5_CPU_SPU_FLAGS};-ffp-contract=off;-DSPU_X86_RZ_ALWAYS=1")
endif()
# GT5's sound job: its numbers are samples, and it was about 10% short of real time with a full grid.
# jD58063CD is the disc's; game update 2.17 replaces it with jCB9BD024 (spu_jobs_from_eboot.py, UPDATED).
# Only the mixer: the downmix module (jFDFFAAC1) filled the mix with NaN under these rules (15 Nov),
# since the SPU reads exponent-255 words as large numbers where the host sees infinity or NaN.
foreach(_sound_job jD58063CD jCB9BD024)
    set_source_files_properties("${SPU_DIR}/jobs/${_sound_job}/spu_recomp.c" "${SPU_DIR}/jobs/${_sound_job}/spu_anyaddr.c" PROPERTIES
        COMPILE_OPTIONS "-O2;/w;/GS-;${GT5_CPU_SPU_FLAGS};-ffp-contract=off;-DSPU_X86_RZ_ALWAYS=1;-DSPU_X86_FAST_FLOAT=1")
endforeach()
# The EQ module (socepdideq: jEB79FDFC on the disc, jE3FDDA10 from 2.01) does its FFT's phase steps in
# double precision, three ops per pass, and switching the rounding mode around each one costs ten
# times the op: its doubles round toward zero instead (SPU_X86_FAST_DOUBLE, spu_helpers.h).
foreach(_eq_job jEB79FDFC jE3FDDA10)
    set_source_files_properties("${SPU_DIR}/jobs/${_eq_job}/spu_recomp.c" "${SPU_DIR}/jobs/${_eq_job}/spu_anyaddr.c" PROPERTIES
        COMPILE_OPTIONS "-O2;/w;/GS-;${GT5_CPU_SPU_FLAGS};-ffp-contract=off;-DSPU_X86_RZ_ALWAYS=1;-DSPU_X86_FAST_DOUBLE=1")
endforeach()

# Native replacements of hot SPU functions (src/native/natives.txt: image, address, symbol, source).
# The lifted job file is compiled from a patched copy in which the listed function is renamed and a
# switch with its old name picks native or lifted at run time (scripts/spu_native_patch.py), so no
# re-lift is needed and every caller is unchanged. GT5_SPU_NATIVE=0 runs the lifted code as before.
set(GT5_NATIVE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/src/native")
# Direct branches (scripts/spu_native_patch.py --direct-bi, src/native/gt5_direct_bi.c): in the lifted code of
# every WWS job and of the WWS job manager, a branch or call to a register holding one of the image's own
# entries goes there without the runtime's dispatcher wherever the dispatcher would choose the same (the
# rest is unchanged). GT5_DIRECT_BI=0 at run time: as before; 2: each one checked against the dispatcher;
# GT5_DIRECT_BI_OFF=<image,...>: those images as before. Off here: none of it is built.
option(GT5_SPU_DIRECT_BI "direct branches in the lifted SPU job images" ON)
set(_dbi_args "")
set(_dbi_deps "")
if(GT5_SPU_DIRECT_BI AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/src/gen/spu_jobs.c")
    set(_dbi_args --direct-bi "${CMAKE_CURRENT_SOURCE_DIR}/src/gen/spu_jobs.c")
    set(_dbi_deps "${CMAKE_CURRENT_SOURCE_DIR}/src/gen/spu_jobs.c")
endif()
if(EXISTS "${GT5_NATIVE_DIR}/natives.txt" AND SPU_JOB_SOURCES)
    find_program(GT5_PYTHON NAMES python python3
                 HINTS "${CMAKE_CURRENT_SOURCE_DIR}/../venv/Scripts" "${CMAKE_CURRENT_SOURCE_DIR}/../venv/bin")
    set(_nat_list "${GT5_NATIVE_DIR}/natives.txt")
    if(NOT GT5_CPU STREQUAL "avx2")
        # Below avx2: a copy of the list with the lines of the natives written in AVX2 made comments, so their
        # functions stay lifted (wgen_gen.py reads natives.txt itself and calls those functions by name either way).
        set(_nat_list "${CMAKE_BINARY_DIR}/natives_${GT5_CPU}.txt")
        set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${GT5_NATIVE_DIR}/natives.txt")
        file(READ "${GT5_NATIVE_DIR}/natives.txt" _nat_text)
        # A newline at both ends, so the first and the last line match like the others; \r: the list has CRLF
        # line ends, and a line ending right after the source name would not have matched (its native then
        # compiled below avx2: #error, or AVX2 instructions in the game).
        set(_nat_text "\n${_nat_text}\n")
        set(_nat_prev "")
        while(NOT _nat_prev STREQUAL _nat_text)
            set(_nat_prev "${_nat_text}")
            foreach(_src ${GT5_NATIVE_AVX2_ONLY})
                string(REPLACE "." "\\." _re "${_src}")
                string(REGEX REPLACE "\n([A-Za-z0-9]+[ \t]+[0-9A-Fa-f]+[ \t]+[^ \t\r\n]+[ \t]+${_re}[ \t\r\n])" "\n#\\1" _nat_text "${_nat_text}")
            endforeach()
        endwhile()
        string(SUBSTRING "${_nat_text}" 1 -1 _nat_text)
        file(WRITE "${_nat_list}.tmp" "${_nat_text}")
        configure_file("${_nat_list}.tmp" "${_nat_list}" COPYONLY)
        string(REPLACE ";" ", " _nat_avx2 "${GT5_NATIVE_AVX2_ONLY}")
        message(STATUS "Native SPU:      ${GT5_CPU} build: ${_nat_avx2} left out (AVX2), their functions lifted")
    endif()
    file(STRINGS "${_nat_list}" _nat_lines REGEX "^[A-Za-z0-9]")
    # Three-field lines say something about an image and are read first:
    #   <image> lift-sha1 <hex>   its native functions were written against exactly this lifted file;
    #                               with any other (another release, another lifter) the image stays lifted
    #   <image> generate <script>   src/native/<script> <lifted file> <build folder> writes files the
    #                               native source includes (statements cut from this copy's own lift)
    set(_nat_skip "")
    foreach(_l ${_nat_lines})
        separate_arguments(_f UNIX_COMMAND "${_l}")
        list(LENGTH _f _fn)
        if(NOT _fn EQUAL 3)
            continue()
        endif()
        list(GET _f 0 _img)
        list(GET _f 1 _kind)
        list(GET _f 2 _val)
        set(_in "${SPU_DIR}/jobs/${_img}/spu_recomp.c")
        if(NOT EXISTS "${_in}")
            continue()
        endif()
        if(_kind STREQUAL "lift-sha1")
            set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_in}")
            file(SHA1 "${_in}" _sha)
            if(NOT _sha STREQUAL _val AND NOT _img IN_LIST _nat_skip)
                list(APPEND _nat_skip ${_img})
                message(STATUS "Native SPU:      ${_img} stays lifted (its lifted code is not the one the native functions were written for)")
            endif()
        elseif(_kind STREQUAL "generate")
            list(APPEND _nat_gen_${_img} "${_val}")
        endif()
    endforeach()
    # -DGT5_CULL_PROF=ON (testing builds only): the w018CAD00 job profiler -- src/native/natives_prof.txt's
    # hooks and the profiler code in native_w018CAD00.c (GT5_CULL_PROF=1 at run time prints "[cull-prof]").
    # Off (the default, every player build): none of its hooks is in the game.
    option(GT5_CULL_PROF "w018CAD00 job profiler hooks (testing builds only)" OFF)
    set(_nat_lists "${_nat_list}")
    if(GT5_CULL_PROF AND EXISTS "${GT5_NATIVE_DIR}/natives_prof.txt")
        if(GT5_CPU STREQUAL "avx2")
            list(APPEND _nat_lists "${GT5_NATIVE_DIR}/natives_prof.txt")
        else()
            message(STATUS "Native SPU:      GT5_CULL_PROF needs native_w018CAD00.c, which a ${GT5_CPU} build leaves out")
        endif()
    endif()
    # -DGT5_NATIVE_STATS=ON (testing): the geometry natives count what they do and print it every 5 s.
    set(_nat_stats "")
    if(GT5_NATIVE_STATS AND NOT GT5_CPU STREQUAL "avx2")
        # native_geo_switch.c's NATIVE_STATS part reads the counters of native_w01606C00.c / native_w0163C080.c,
        # which a build below avx2 leaves out: the link would fail on them.
        message(STATUS "Native SPU:      GT5_NATIVE_STATS needs the AVX2 geometry natives, which a ${GT5_CPU} build leaves out")
    elseif(GT5_NATIVE_STATS)
        set(_nat_stats ";NATIVE_STATS")
    endif()
    set(_nat_any OFF)
    set(_nat_done "")
    foreach(_l ${_nat_lines})
        separate_arguments(_f UNIX_COMMAND "${_l}")
        list(LENGTH _f _fn)
        if(_fn LESS 4)
            continue()
        endif()
        list(GET _f 0 _img)
        list(GET _f 3 _src)
        set(_in "${SPU_DIR}/jobs/${_img}/spu_recomp.c")
        if(NOT EXISTS "${_in}" OR NOT GT5_PYTHON OR _img IN_LIST _nat_skip)
            continue()   # this copy of the game has no such job (another release): nothing to replace
        endif()
        get_source_file_property(_opts "${_in}" COMPILE_OPTIONS)
        set(_incs "${PS3RECOMP_DIR}/runtime/spu;${SPU_DIR}/jobs/${_img};${GT5_NATIVE_DIR};${CMAKE_BINARY_DIR}/spu_native/${_img}")
        set(_stamp "")
        if(DEFINED _nat_gen_${_img})
            set(_stamp "${CMAKE_BINARY_DIR}/spu_native/${_img}/generated.stamp")
        endif()
        if(_stamp AND NOT _img IN_LIST _nat_done)
            set(_gen_cmds "")
            set(_gen_deps "${_in}")
            foreach(_g ${_nat_gen_${_img}})
                list(APPEND _gen_cmds COMMAND "${GT5_PYTHON}" "${GT5_NATIVE_DIR}/${_g}" "${_in}" "${CMAKE_BINARY_DIR}/spu_native/${_img}")
                list(APPEND _gen_deps "${GT5_NATIVE_DIR}/${_g}")
            endforeach()
            add_custom_command(OUTPUT "${_stamp}"
                ${_gen_cmds}
                COMMAND "${CMAKE_COMMAND}" -E touch "${_stamp}"
                DEPENDS ${_gen_deps}
                COMMENT "Native SPU: statements of ${_img} for its native functions" VERBATIM)
            target_sources(gt5 PRIVATE "${_stamp}")
        endif()
        if(NOT _img IN_LIST _nat_done)
            list(APPEND _nat_done ${_img})
            set(_out "${CMAKE_BINARY_DIR}/spu_native/${_img}/spu_recomp.c")
            add_custom_command(OUTPUT "${_out}"
                COMMAND "${GT5_PYTHON}" "${CMAKE_CURRENT_SOURCE_DIR}/scripts/spu_native_patch.py" "${_in}" "${_out}" ${_img} ${_nat_lists} ${_dbi_args}
                DEPENDS "${_in}" ${_nat_lists} ${_dbi_deps} "${CMAKE_CURRENT_SOURCE_DIR}/scripts/spu_native_patch.py"
                COMMENT "Native SPU functions for ${_img}" VERBATIM)
            file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/spu_native/${_img}")
            set_source_files_properties("${_in}" PROPERTIES HEADER_FILE_ONLY ON)
            target_sources(gt5 PRIVATE "${_out}")
            set_source_files_properties("${_out}" PROPERTIES
                INCLUDE_DIRECTORIES "${_incs}" COMPILE_DEFINITIONS SPU_USE_DISPATCH_MT COMPILE_OPTIONS "${_opts}")
        endif()
        get_source_file_property(_have "${GT5_NATIVE_DIR}/${_src}" COMPILE_OPTIONS)
        if(NOT _have)
            target_sources(gt5 PRIVATE "${GT5_NATIVE_DIR}/${_src}")
            set(_nat_defs "SPU_USE_DISPATCH_MT;NATIVE_HOOKED")
            if(_src MATCHES "^native_w")   # the geometry natives; the sound ones keep their counters for the harness
                string(APPEND _nat_defs "${_nat_stats}")
            endif()
            if(GT5_CULL_PROF AND _src STREQUAL "native_w018CAD00.c")
                string(APPEND _nat_defs ";GT5_CULL_PROF_HOOKS")
            endif()
            set_source_files_properties("${GT5_NATIVE_DIR}/${_src}" PROPERTIES
                INCLUDE_DIRECTORIES "${_incs}" COMPILE_DEFINITIONS "${_nat_defs}" COMPILE_OPTIONS "${_opts}")
            if(_stamp)
                set_source_files_properties("${GT5_NATIVE_DIR}/${_src}" PROPERTIES OBJECT_DEPENDS "${_stamp}")
            endif()
        endif()
        set(_nat_any ON)
    endforeach()
    if(_nat_any)
        target_sources(gt5 PRIVATE "${GT5_NATIVE_DIR}/spu_native.c")
        set_source_files_properties("${GT5_NATIVE_DIR}/spu_native.c" PROPERTIES
            INCLUDE_DIRECTORIES "${PS3RECOMP_DIR}/runtime/spu"
            COMPILE_OPTIONS "-O2;/w;/GS-;${GT5_CPU_SPU_FLAGS}")
        if(EXISTS "${GT5_NATIVE_DIR}/native_snd.c")
            target_sources(gt5 PRIVATE "${GT5_NATIVE_DIR}/native_snd.c")
            set_source_files_properties("${GT5_NATIVE_DIR}/native_snd.c" PROPERTIES
                INCLUDE_DIRECTORIES "${PS3RECOMP_DIR}/runtime/spu" COMPILE_OPTIONS "-O2;/w;/GS-;${GT5_CPU_SPU_FLAGS}")
        endif()
        if(EXISTS "${GT5_NATIVE_DIR}/native_geo_switch.c")
            target_sources(gt5 PRIVATE "${GT5_NATIVE_DIR}/native_geo_switch.c")
            set_source_files_properties("${GT5_NATIVE_DIR}/native_geo_switch.c" PROPERTIES
                INCLUDE_DIRECTORIES "${PS3RECOMP_DIR}/runtime/spu;${GT5_NATIVE_DIR}" COMPILE_DEFINITIONS "NATIVE_GEO_SWITCH${_nat_stats}" COMPILE_OPTIONS "-O2;/w;/GS-;${GT5_CPU_SPU_FLAGS}")
        endif()
        list(LENGTH _nat_done _nat_n)
        message(STATUS "Native SPU:      ${_nat_n} image(s) with native functions")
    endif()
endif()
if(SPU_JOB_SOURCES AND EXISTS "${GT5_NATIVE_DIR}/gt5_direct_bi.c")
    # the run-time half (also what the natives' in-run A/B calls), with or without the option
    target_sources(gt5 PRIVATE "${GT5_NATIVE_DIR}/gt5_direct_bi.c")
    set_source_files_properties("${GT5_NATIVE_DIR}/gt5_direct_bi.c" PROPERTIES
        INCLUDE_DIRECTORIES "${PS3RECOMP_DIR}/runtime/spu;${GT5_NATIVE_DIR}" COMPILE_OPTIONS "-O2;/w;/GS-;${GT5_CPU_SPU_FLAGS}")
endif()
if(_dbi_args AND SPU_JOB_SOURCES)
    find_program(GT5_PYTHON NAMES python python3
                 HINTS "${CMAKE_CURRENT_SOURCE_DIR}/../venv/Scripts" "${CMAKE_CURRENT_SOURCE_DIR}/../venv/bin")
    if(GT5_PYTHON)
        # The images with native functions got theirs in the natives patch above; every other job image is
        # compiled from a copy made here (the script copies an image that takes no direct branches unchanged).
        set(_dbi_n 0)
        foreach(_in ${SPU_JOB_SOURCES})
            get_filename_component(_dir "${_in}" DIRECTORY)
            get_filename_component(_img "${_dir}" NAME)
            if(_img IN_LIST _nat_done)
                continue()
            endif()
            set(_out "${CMAKE_BINARY_DIR}/spu_dbi/${_img}/spu_recomp.c")
            add_custom_command(OUTPUT "${_out}"
                COMMAND "${GT5_PYTHON}" "${CMAKE_CURRENT_SOURCE_DIR}/scripts/spu_native_patch.py" "${_in}" "${_out}" ${_img} ${_dbi_args}
                DEPENDS "${_in}" ${_dbi_deps} "${CMAKE_CURRENT_SOURCE_DIR}/scripts/spu_native_patch.py"
                COMMENT "Direct branches for ${_img}" VERBATIM)
            file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/spu_dbi/${_img}")
            get_source_file_property(_opts "${_in}" COMPILE_OPTIONS)
            set_source_files_properties("${_in}" PROPERTIES HEADER_FILE_ONLY ON)
            target_sources(gt5 PRIVATE "${_out}")
            set_source_files_properties("${_out}" PROPERTIES
                INCLUDE_DIRECTORIES "${PS3RECOMP_DIR}/runtime/spu;${_dir};${GT5_NATIVE_DIR}"
                COMPILE_DEFINITIONS SPU_USE_DISPATCH_MT COMPILE_OPTIONS "${_opts}")
            math(EXPR _dbi_n "${_dbi_n} + 1")
        endforeach()
        message(STATUS "Direct branches: on (the WWS jobs' code and job manager; ${_dbi_n} job file(s) copied for it)")
    endif()
endif()

target_include_directories(gt5 PRIVATE
    "${RECOMP_DIR}"
    "${PS3RECOMP_DIR}/include"
    "${PS3RECOMP_DIR}/runtime/ppu"
    "${PS3RECOMP_DIR}/runtime/spu"
    "${PS3RECOMP_DIR}/runtime/memory"
    "${PS3RECOMP_DIR}/runtime/syscalls"
    "${PS3RECOMP_DIR}/runtime/platform"
    "${PS3RECOMP_DIR}/libs/video"
    "${CMAKE_CURRENT_SOURCE_DIR}"
)

target_link_libraries(gt5 PRIVATE ps3recomp_runtime dbghelp user32 gdi32 winmm)
# Line numbers for the runtime too, so a profile names the RSX thread's hot lines (used to be a hand edit
# of build.ninja that every CMake regeneration lost).
target_compile_options(ps3recomp_runtime PRIVATE /Z7)
# The DLLs the runtime opens sit next to the exe.
if(PS3RECOMP_FFMPEG_RUNTIME)
    add_custom_command(TARGET gt5 POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different
        "${GT5_FFMPEG_DIR}/bin/avcodec-63.dll" "${GT5_FFMPEG_DIR}/bin/avutil-61.dll" "${GT5_FFMPEG_DIR}/bin/swresample-7.dll"
        "$<TARGET_FILE_DIR:gt5>")
endif()
if(PS3RECOMP_RSX_VULKAN)
    # The runtime keeps the definition to itself (so the generated code isn't rebuilt); the boot harness
    # picks the Vulkan backend on it when RSX_LIVE_DRAW is off.
    set_property(SOURCE "${PS3RECOMP_DIR}/runtime/ppu/tests/boot_main.cpp" APPEND PROPERTY COMPILE_DEFINITIONS PS3RECOMP_RSX_VULKAN)
    # SDL2 loads only when Vulkan runs, so DirectX 12 starts even without SDL2.dll.
    target_link_options(gt5 PRIVATE /DELAYLOAD:SDL2.dll)
    target_link_libraries(gt5 PRIVATE delayimp)
    find_file(GT5_SDL2_DLL SDL2.dll PATH_SUFFIXES bin REQUIRED)
    add_custom_command(TARGET gt5 POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${GT5_SDL2_DLL}" "$<TARGET_FILE_DIR:gt5>")
else()
    # SDL2.dll next to gt5.exe tells the launcher and play.bat the exe has Vulkan: not this one.
    add_custom_command(TARGET gt5 POST_BUILD COMMAND ${CMAKE_COMMAND} -E rm -f "$<TARGET_FILE_DIR:gt5>/SDL2.dll")
endif()
set_target_properties(gt5 PROPERTIES LINKER_LANGUAGE CXX)

target_compile_options(gt5 PRIVATE /W3 /wd4100 /wd4244 /wd4267 /Zc:__cplusplus -fno-strict-aliasing -fwrapv)
target_compile_definitions(gt5 PRIVATE _CRT_SECURE_NO_WARNINGS)

# Machine-generated: warnings off, and /bigobj because one TU passes the default
# object format's section limit. -O1 keeps these TUs' build time and memory sane;
# the last -O on the line wins, so this overrides Release's /O2 for them alone.
# -O2 with this CPU's instructions (2026-11-05): the largest chunk builds in 71 s against 67 s at -O1, under 1 GB.
# MOVBE folds the byte swap of every big-endian guest load and store into the access itself.
# No FMA contraction, so floating-point results match the -O1 build. -mfma lets ppu_vmx.h do
# vmaddfp/vnmsubfp four lanes at once with the same results (every AVX2 CPU has FMA; contraction
# stays off, so nothing else changes).
set(GT5_RECOMP_OPTIONS "/w;/bigobj;-O2;${GT5_CPU_PPU_FLAGS};-ffp-contract=off")
set_source_files_properties(${RECOMP_SOURCES} PROPERTIES COMPILE_OPTIONS "${GT5_RECOMP_OPTIONS}")

# Native PPU functions (src/native/ppu_natives.txt, scripts/ppu_native_patch.py, src/native/gen_ppu_leaf.py): a
# lifted file that holds a listed function is compiled from a copy in which that function is renamed
# func_<ADDR>_lifted and a switch with the old name picks the native form or the lifted one at run time
# (GT5_PPU_NATIVE: 1 native, the default; 0 lifted, as before; 2 compare both, differences logged). The native
# form is made at build time from this lift's own text of the function, and only where that text is the one it
# was proven on (its SHA-1 in the list): every other function, and another release or update of the game, keeps
# its lifted code. No re-lift; every caller and the function table keep the old name. -DGT5_PPU_NATIVE=OFF: none
# of it is built.
option(GT5_PPU_NATIVE "native PPU functions (src/native/ppu_natives.txt)" ON)
set(_ppu_nat_list "${GT5_NATIVE_DIR}/ppu_natives.txt")
if(GT5_PPU_NATIVE AND EXISTS "${_ppu_nat_list}")
    find_program(GT5_PYTHON NAMES python python3
                 HINTS "${CMAKE_CURRENT_SOURCE_DIR}/../venv/Scripts" "${CMAKE_CURRENT_SOURCE_DIR}/../venv/bin")
    set(_ppu_nat_files "")
    if(GT5_PYTHON)
        set(_ppu_nat_script "${CMAKE_CURRENT_SOURCE_DIR}/scripts/ppu_native_patch.py")
        set(_ppu_nat_gen "${GT5_NATIVE_DIR}/gen_ppu_leaf.py")
        # The lifted files holding a listed function with the proven text; a re-lift rewrites ppu_recomp.h, so
        # configuring again then looks again.
        set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
            "${_ppu_nat_list}" "${RECOMP_DIR}/ppu_recomp.h" "${_ppu_nat_script}" "${_ppu_nat_gen}")
        execute_process(COMMAND "${GT5_PYTHON}" "${_ppu_nat_script}" --where "${_ppu_nat_list}" "${RECOMP_DIR}"
                        OUTPUT_VARIABLE _ppu_nat_files RESULT_VARIABLE _ppu_nat_rc OUTPUT_STRIP_TRAILING_WHITESPACE)
        if(NOT _ppu_nat_rc EQUAL 0)
            set(_ppu_nat_files "")
        endif()
    endif()
    foreach(_f ${_ppu_nat_files})
        set(_in "${RECOMP_DIR}/${_f}")
        set(_out "${CMAKE_BINARY_DIR}/ppu_native/${_f}")
        add_custom_command(OUTPUT "${_out}"
            COMMAND "${GT5_PYTHON}" "${_ppu_nat_script}" "${_in}" "${_out}" "${_ppu_nat_list}"
            DEPENDS "${_in}" "${_ppu_nat_list}" "${_ppu_nat_script}" "${_ppu_nat_gen}"
            COMMENT "Native PPU functions in ${_f}" VERBATIM)
        set_source_files_properties("${_in}" PROPERTIES HEADER_FILE_ONLY ON)
        target_sources(gt5 PRIVATE "${_out}")
        set_source_files_properties("${_out}" PROPERTIES
            INCLUDE_DIRECTORIES "${GT5_NATIVE_DIR}" COMPILE_OPTIONS "${GT5_RECOMP_OPTIONS}")
    endforeach()
    if(_ppu_nat_files)
        file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/ppu_native")
        target_sources(gt5 PRIVATE "${GT5_NATIVE_DIR}/ppu_native.cpp")
        list(LENGTH _ppu_nat_files _ppu_nat_n)
        message(STATUS "Native PPU:      functions in ${_ppu_nat_n} lifted file(s) (GT5_PPU_NATIVE=0 at run time: as before)")
    else()
        message(STATUS "Native PPU:      none for this copy of the game")
    endif()
endif()

# Keep symbols so crash RVAs can be symbolized.
target_compile_options(gt5 PRIVATE /Z7)
target_link_options(gt5 PRIVATE /DEBUG /INCREMENTAL:NO)
