cmake_minimum_required(VERSION 3.20)

# ============================================================================
# Def Jam: Fight for NY (Xbox, EA-073) — static recompilation to native PC
#
# Layout:
#   tools/xboxrecomp/      the recompiler + runtime libraries (git submodule)
#   src/main.c             host entry point (loads default.xbe, boots guest)
#   src/recomp_manual.c    hand-written overrides / ICALL diagnostics
#   src/recomp/gen/*.c     lifted C (generated by scripts/recomp.ps1, gitignored)
#   src/hooks/*.c          HLE hooks (file IO redirection, mod overrides)
#   src/patches/*.c        gameplay patches (delta-time, framerate, input)
#
# Nothing from the game disc is in this tree. Put your own dump in ./game
# (a junction/symlink is fine) and run scripts/verify-dump.py first.
# ============================================================================

project(defjam_recomp VERSION 0.13.0 LANGUAGES C CXX)

set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)

if(WIN32)
    add_compile_definitions(WIN32_LEAN_AND_MEAN NOMINMAX)
endif()

set(XBOXRECOMP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/tools/xboxrecomp" CACHE PATH
    "Path to the xboxrecomp toolkit root directory")

if(NOT EXISTS "${XBOXRECOMP_DIR}/CMakeLists.txt")
    message(FATAL_ERROR "xboxrecomp submodule missing. Run: git submodule update --init --recursive")
endif()

# The toolkit hard-codes /O2 on its kernel library, which MSVC refuses to combine
# with the /RTC1 runtime checks CMake adds to Debug. Drop /RTC1 so Debug builds work.
if(MSVC)
    string(REPLACE "/RTC1" "" CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG}")
endif()

# Check that every lifted call preserves ebx/esi/edi and does not leave esp
# low, and name the callee that breaks it (recomp_types.h, RECOMP_ABI_CHECK).
# Directory-wide because the reporter lives in the runtime library. Slower;
# build it as its own preset (win-x64-abicheck) when a register seems to
# arrive somewhere with the wrong value.
option(DEFJAM_ABI_CHECK "Check callee-saved registers across every lifted call" OFF)
if(DEFJAM_ABI_CHECK)
    add_compile_definitions(RECOMP_ABI_CHECK=1)
endif()

# Gamepads through SDL3 (DualSense, Switch Pro, DirectInput and XInput pads
# under one set of names; zlib licence). The toolkit fetches a pinned release
# and builds it statically, so configuring needs network access once. Turn it
# off to read pads through XInput only.
option(DEFJAM_SDL3 "Read gamepads through SDL3" ON)
set(XBOXRECOMP_SDL3 ${DEFJAM_SDL3} CACHE BOOL "Read gamepads through SDL3 (fetched and built statically)" FORCE)

# Builds all runtime libraries and provides the 'xboxrecomp' umbrella target.
add_subdirectory(${XBOXRECOMP_DIR} ${CMAKE_BINARY_DIR}/xboxrecomp)

# ── Game executable (only when lifted code is present) ──────────────────
file(GLOB RECOMP_GEN_SOURCES CONFIGURE_DEPENDS "src/recomp/gen/*.c")
file(GLOB HOOK_SOURCES       CONFIGURE_DEPENDS "src/hooks/*.c" "src/hooks/*.cpp")
file(GLOB PATCH_SOURCES      CONFIGURE_DEPENDS "src/patches/*.c")

option(DEFJAM_BUILD_GAME "Build the game executable (requires src/recomp/gen from scripts/recomp.ps1)" ON)

if(DEFJAM_BUILD_GAME AND NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/src/recomp/gen/recomp_dispatch.c")
    message(WARNING "src/recomp/gen is empty — run scripts/recomp.ps1. Building runtime libraries only.")
    set(DEFJAM_BUILD_GAME OFF)
endif()

if(DEFJAM_BUILD_GAME)
    # Dear ImGui (MIT): the launcher and the in-game overlay. Fetched at a pinned hash.
    list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
    if(WIN32)
        set(HOST_SOURCES "")
        list(FILTER HOOK_SOURCES EXCLUDE REGEX "/pc_launcher_sdl\\.cpp$")
        include(imgui)
        # The shield icon and the file properties (branding/icon/defjam.ico).
        enable_language(RC)
        include(windows_resource)
        defjam_windows_resource(DEFJAM_RC NAME defjam_recomp VERSION ${PROJECT_VERSION}
                                DESCRIPTION "Def Jam: Fight for NY - Recompiled")
        set(HOST_SOURCES ${DEFJAM_RC})
    else()
        # The Win32 window and the debug-register watchpoints have no place
        # here; src/host_posix.c has the SDL window and stands in for the rest.
        # The launcher (SDL's renderer in a window of its own) and the overlay
        # (Vulkan, in the game's window) are the same screen as on Windows,
        # in pc_ui.cpp; pc_launcher.cpp is the Direct3D 11 one.
        list(FILTER HOOK_SOURCES EXCLUDE REGEX "/(watchpoint\\.c|pc_launcher\\.cpp)$")
        set(HOST_SOURCES src/host_posix.c)
        if(APPLE)
            enable_language(OBJC)
            list(APPEND HOST_SOURCES src/host_macos.m)
        endif()
        find_package(SDL3 REQUIRED CONFIG)
        find_package(Vulkan REQUIRED)
        include(imgui)
        include(app_icon)
    endif()
    add_executable(${PROJECT_NAME} WIN32
        src/main.c
        src/recomp_manual.c
        ${HOST_SOURCES}
        ${HOOK_SOURCES}
        ${PATCH_SOURCES}
        ${RECOMP_GEN_SOURCES}
    )
    target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_17)
    if(WIN32)
        target_link_libraries(${PROJECT_NAME} PRIVATE xboxrecomp recomp_settings defjam_imgui d3d11 dxgi dxguid xinput winmm dbghelp shell32 comdlg32)
    else()
        # One SDL for the window, the sound and the pads: SDL3, the system's.
        defjam_app_icon(${PROJECT_NAME})
        target_link_libraries(${PROJECT_NAME} PRIVATE xboxrecomp recomp_settings defjam_imgui
                              SDL3::SDL3 Vulkan::Vulkan ${CMAKE_DL_LIBS} m)
        if(APPLE)
            # Shift held at start-up (src/host_posix.c) is read from the window server.
            target_link_libraries(${PROJECT_NAME} PRIVATE "-framework ApplicationServices" "-framework AppKit")
            # SDL opens the Vulkan loader by name, and macOS's search does not
            # reach a package manager's prefix; tell it where this build's is.
            # Not on Linux: there the game is often built in a container whose
            # /lib is not the player's (on Fedora it holds 32-bit libraries),
            # and SDL's own libvulkan.so.1 is found by the system's loader.
            target_compile_definitions(${PROJECT_NAME} PRIVATE
                DEFJAM_VULKAN_LIBRARY="${Vulkan_LIBRARY}")
        endif()
        # The lifted code was written against a compiler that does none of
        # these: it reads memory through casts of every width, relies on
        # wrapping arithmetic, and must not have a multiply and an add fused
        # into one rounding (arm64 does that by default, and the game's
        # simulation would then differ from the Windows build's).
        target_compile_options(${PROJECT_NAME} PRIVATE
            -fno-strict-aliasing -fwrapv -ffp-contract=off -g)
        if(APPLE)
            # One named section for the title's code (src/recomp/guest_section.h).
            set_source_files_properties(${RECOMP_GEN_SOURCES} PROPERTIES COMPILE_OPTIONS
                "-include;${CMAKE_CURRENT_SOURCE_DIR}/src/recomp/guest_section.h")
        endif()
        # Keep every lifted function's name in the dynamic symbol table, so
        # the crash report can name the one that faulted.
        set_target_properties(${PROJECT_NAME} PROPERTIES ENABLE_EXPORTS ON)
    endif()
    target_compile_definitions(${PROJECT_NAME} PRIVATE DEFJAM_VERSION=\"${PROJECT_VERSION}\")
    target_compile_definitions(${PROJECT_NAME} PRIVATE DEFJAM_MOD_SOURCE_DIR=\"${CMAKE_CURRENT_SOURCE_DIR}\")
    file(READ "${XBOXRECOMP_DIR}/src/nv2a/texture_pack.c" _mod_texture_loader)
    string(FIND "${_mod_texture_loader}" "texture_pack_wide_slabs" _mod_has_wide)
    if(NOT _mod_has_wide EQUAL -1)
        target_compile_definitions(${PROJECT_NAME} PRIVATE DEFJAM_MOD_WIDE=1)
    endif()
    target_include_directories(${PROJECT_NAME} PRIVATE
        ${CMAKE_CURRENT_SOURCE_DIR}/src
        ${CMAKE_CURRENT_SOURCE_DIR}/src/recomp
        ${XBOXRECOMP_DIR}/include
        # src/hooks/ac97_bm.c reuses the runtime's mmio_decode.h, the same
        # faulting-instruction decoder its USB controller model uses, so our
        # device models only have to describe register behaviour.
        ${XBOXRECOMP_DIR}/src/platform
        # src/hooks/d3d11_translator.c stands up a D3D11 device for the
        # push-buffer translator, so it needs the runtime's D3D8 and NV2A
        # headers. The libraries themselves come in through the umbrella.
        ${XBOXRECOMP_DIR}/src/d3d
        ${XBOXRECOMP_DIR}/src/nv2a
    )
    if(MSVC)
        target_link_options(${PROJECT_NAME} PRIVATE /LARGEADDRESSAWARE)
        # Generated chunks are huge; also keep debug info even in Release so the
        # VEH handler can name guest functions from the PDB.
        target_compile_options(${PROJECT_NAME} PRIVATE /bigobj /Zi)
        # Linker map lets scripts/sample-threads.py and tools/symbolize.py name guest functions from a host RIP.
        # /DYNAMICBASE:NO loads the image at the map's preferred address, so a RIP in a crash report is the
        # map address with no rebasing, and is the same across runs. /OPT:NOICF stops the linker folding
        # identical function bodies together, which it otherwise does freely here: thousands of lifted
        # functions translate to byte-identical code, and folding makes a crash report name whichever of
        # them won the merge rather than the one that ran.
        # /INCREMENTAL:NO: CMake gives RelWithDebInfo "/debug /INCREMENTAL", and link.exe's incremental
        # linker can crash on an image this large (LNK1000, internal error during IncrCalcPtrs, access
        # violation). The setup builds from scratch, so an incremental link has nothing to reuse.
        target_link_options(${PROJECT_NAME} PRIVATE /DEBUG /INCREMENTAL:NO /MAP:${CMAKE_BINARY_DIR}/defjam_recomp.map
                            /DYNAMICBASE:NO /OPT:NOICF)
    endif()
    # Debug-only diagnostics (toggle from the preset or command line)
    option(DEFJAM_ICALL_TRACE "Trace indirect calls (slow, verbose)" OFF)
    option(DEFJAM_VERBOSE_KERNEL "Log every kernel call" OFF)
    if(DEFJAM_ICALL_TRACE)
        target_compile_definitions(${PROJECT_NAME} PRIVATE ENABLE_ICALL_TRACE=1)
    endif()
    if(DEFJAM_VERBOSE_KERNEL)
        target_compile_definitions(${PROJECT_NAME} PRIVATE VERBOSE_KERNEL_LOG=1)
    endif()
endif()
