# The port's own sources, compiled without the game's lift.
#
# work/port/CMakeLists.txt builds the game and needs work/src/recomp, the lift
# of the player's own disc, which never leaves their machine. This project
# compiles everything else the port is made of -- main.cpp, the native PPU
# stand-ins, the settings, the launcher UI, the hand-written SPU kernels, the
# co-op mod -- against a STAND-IN ppu_recomp.h: the lifter's own preamble
# (tools/make_smoke_elf.py writes it from ppu_lifter.py's HEADER_PREAMBLE)
# plus a declaration for every func_<address> those sources call. Nothing is
# linked into a game; the archives prove the sources compile on this host,
# and the tests run.
#
#   cmake -S work/port/liftless -B build-liftless -G Ninja \
#         -DPS3RECOMP_DIR=<patched toolkit> [-DINFAMOUS_COOP=ON]
#   cmake --build build-liftless && ctest --test-dir build-liftless
cmake_minimum_required(VERSION 3.20)
project(InfamousPortLiftless LANGUAGES C CXX)

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

get_filename_component(PORT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/.." ABSOLUTE)
if(NOT DEFINED PS3RECOMP_DIR)
    message(FATAL_ERROR "-DPS3RECOMP_DIR=<ps3recomp with work/patches/ps3recomp.patch applied>")
endif()
get_filename_component(PS3RECOMP_DIR "${PS3RECOMP_DIR}" ABSOLUTE)
option(INFAMOUS_COOP "Also compile the co-op / split-screen mod" OFF)

add_subdirectory("${PS3RECOMP_DIR}" "${CMAKE_BINARY_DIR}/ps3recomp_sdk" EXCLUDE_FROM_ALL)

# ---------------------------------------------------------------------------
# The stand-in ppu_recomp.h
# ---------------------------------------------------------------------------
find_package(Python3 COMPONENTS Interpreter REQUIRED)
set(STUB_DIR "${CMAKE_BINARY_DIR}/stub_lift")
file(MAKE_DIRECTORY "${STUB_DIR}")
execute_process(
    COMMAND "${Python3_EXECUTABLE}" "${PS3RECOMP_DIR}/tools/make_smoke_elf.py"
            --out "${STUB_DIR}/smoke.elf" --header "${STUB_DIR}/preamble.h"
    RESULT_VARIABLE _rc OUTPUT_QUIET)
if(NOT _rc EQUAL 0)
    message(FATAL_ERROR "tools/make_smoke_elf.py failed (${_rc})")
endif()
file(READ "${STUB_DIR}/preamble.h" _stub)
set(_names "")
foreach(src IN ITEMS main.cpp ppu_native.cpp)
    file(READ "${PORT_DIR}/${src}" _txt)
    string(REGEX MATCHALL "func_[0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F]" _found "${_txt}")
    list(APPEND _names ${_found})
endforeach()
list(REMOVE_DUPLICATES _names)
list(SORT _names)
string(APPEND _stub "\n/* liftless: the lifted functions the port's sources name */\n")
foreach(n IN LISTS _names)
    string(APPEND _stub "void ${n}(ppu_context* ctx);\n")
endforeach()
file(WRITE "${STUB_DIR}/ppu_recomp.h.new" "${_stub}")
configure_file("${STUB_DIR}/ppu_recomp.h.new" "${STUB_DIR}/ppu_recomp.h" COPYONLY)
list(LENGTH _names _n)
message(STATUS "Stand-in lift:   ${STUB_DIR}/ppu_recomp.h (${_n} lifted functions declared)")

set(PORT_INCLUDES
    "${STUB_DIR}"
    "${PS3RECOMP_DIR}/include"
    "${PS3RECOMP_DIR}/runtime/ppu"
    "${PS3RECOMP_DIR}/runtime/spu"
    "${PS3RECOMP_DIR}/runtime/memory"
    "${PS3RECOMP_DIR}/runtime/syscalls"
    "${PS3RECOMP_DIR}/runtime/prx"
    "${PS3RECOMP_DIR}/runtime/platform"
    "${PS3RECOMP_DIR}/libs/video"
    "${PORT_DIR}")
if(CMAKE_C_COMPILER_ID MATCHES "Clang|GNU")
    set(PORT_WARN -Wall -Wextra -Wno-unused-parameter -fno-strict-aliasing -fwrapv)
endif()

# ---------------------------------------------------------------------------
# The port's sources (as work/port/CMakeLists.txt lists them)
# ---------------------------------------------------------------------------
add_library(infamous_port STATIC
    "${PORT_DIR}/main.cpp"
    "${PORT_DIR}/settings.cpp"
    "${PORT_DIR}/modfmt.cpp"
    "${PORT_DIR}/modpatch.cpp"
    "${PORT_DIR}/modfmt_ui.cpp"
    "${PORT_DIR}/ui.cpp"
    "${PORT_DIR}/stubs.cpp"
    "${PORT_DIR}/port_cpu_check.c"
    "${PORT_DIR}/native_passes.c"
    "${PORT_DIR}/re_trace.c"
    "${PORT_DIR}/ppu_native.cpp")
target_include_directories(infamous_port PRIVATE ${PORT_INCLUDES})
target_link_libraries(infamous_port PRIVATE ps3recomp_runtime)   # its usage requirements
find_package(ZLIB REQUIRED)                                      # modfmt.cpp: the Mod Manager mods' zips
target_link_libraries(infamous_port PRIVATE ${ZLIB_LIBRARIES})
target_compile_options(infamous_port PRIVATE ${PORT_WARN})

# The hand-written SPU kernels: x86-64 only (SSE/AVX intrinsics), built the
# way the port builds them. job2025_kernels_native.c is left out: its bodies
# are generated from the lifted job module. x86-64-v4, scripts/build.sh's default:
# edge_kernels_native.c is AVX-512 only. Compiled, never run here.
set(SPU_NATIVE "")
if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$")
    foreach(src IN ITEMS ec5f_native.c job2025_native.c edge_kernels_native.c
                         jobbc11_native.c job207_native.c job220_native.c)
        list(APPEND SPU_NATIVE "${PORT_DIR}/${src}")
    endforeach()
    add_library(infamous_spu_native STATIC ${SPU_NATIVE})
    target_include_directories(infamous_spu_native PRIVATE ${PORT_INCLUDES})
    target_link_libraries(infamous_spu_native PRIVATE ps3recomp_runtime)
    target_compile_definitions(infamous_spu_native PRIVATE
        SPU_USE_DISPATCH_MT SPU_WRCH_INLINE SPU_LS_NO_DEBUG)
    target_compile_options(infamous_spu_native PRIVATE -O2 -march=x86-64-v4 ${PORT_WARN})
    message(STATUS "SPU kernels:     ${CMAKE_SYSTEM_PROCESSOR}, compiled")
else()
    message(STATUS "SPU kernels:     not on ${CMAKE_SYSTEM_PROCESSOR} (x86-64 intrinsics)")
endif()

# ---------------------------------------------------------------------------
# The temporal upscaler mod (mods/upscale, docs/UPSCALERS.md): compiled, never
# run here (its test, mods/upscale/tests/run_mv_test.sh, needs a GPU). The
# DLSS/XeSS paths are left out: they need the player's own SDKs.
# ---------------------------------------------------------------------------
option(INFAMOUS_MOD_UPSCALE "Also compile the temporal upscaler mod" OFF)
if(INFAMOUS_MOD_UPSCALE AND PS3RECOMP_RSX_VULKAN)
    set(_ups "${PORT_DIR}/mods/upscale")
    set(_ups_ffx "${_ups}/third_party/fsr2/ffx_fsr2.cpp" "${_ups}/third_party/fsr2/vk/ffx_fsr2_vk.cpp")
    add_library(infamous_upscale STATIC
        "${_ups}/upscale_mod.c" "${_ups}/upscale_vk.c" "${_ups}/upscale_xess.c"
        "${_ups}/upscale_fsr2.cpp" "${_ups}/upscale_dlss.cpp" "${_ups}/upscale_fsr4.cpp" ${_ups_ffx})
    file(STRINGS "${PORT_DIR}/settings.h" _ups_api REGEX "port_mod_opt_set")
    if(_ups_api)
        target_sources(infamous_upscale PRIVATE "${_ups}/upscale_ui.cpp")
        # Only in infamous_port (a static library, never linked here): the tests and
        # the JOIN client compile settings.cpp too and do not link the mod.
        set_property(SOURCE "${PORT_DIR}/settings.cpp" "${PORT_DIR}/ui.cpp" APPEND PROPERTY COMPILE_DEFINITIONS
                     "$<$<STREQUAL:$<TARGET_PROPERTY:NAME>,infamous_port>:INFAMOUS_MOD_UPSCALE=1>")
    endif()
    target_include_directories(infamous_upscale PRIVATE ${PORT_INCLUDES} "${_ups}" "${PS3RECOMP_VULKAN_INCLUDE_DIR}"
                               "${PS3RECOMP_DIR}/libs/thirdparty/imgui")
    target_link_libraries(infamous_upscale PRIVATE ps3recomp_runtime)
    set_property(SOURCE ${_ups_ffx} APPEND PROPERTY INCLUDE_DIRECTORIES
                 "${_ups}/third_party/fsr2" "${_ups}/third_party/fsr2/vk" "${_ups}/third_party/fsr2/vk/shaders")
    set_property(SOURCE ${_ups_ffx} "${_ups}/upscale_fsr2.cpp" APPEND PROPERTY COMPILE_OPTIONS
                 -include "${_ups}/upscale_fsr2_compat.h" -w)
    set(_ups_sdk "${_ups}/third_party/ffx_sdk/sdk")
    set(_ups_ffx3 "${_ups_sdk}/src/backends/vk/ffx_vk.cpp" "${_ups_sdk}/src/components/fsr3upscaler/ffx_fsr3upscaler.cpp"
                  "${_ups_sdk}/src/shared/ffx_message.cpp" "${_ups_sdk}/src/shared/ffx_object_management.cpp"
                  "${_ups_sdk}/src/shared/ffx_breadcrumbs_list.cpp")
    target_sources(infamous_upscale PRIVATE ${_ups_ffx3} "${_ups}/upscale_fsr3.cpp")
    set_property(SOURCE ${_ups_ffx3} "${_ups}/upscale_fsr3.cpp" APPEND PROPERTY INCLUDE_DIRECTORIES
                 "${_ups_sdk}/include" "${_ups_sdk}/src/shared" "${_ups_sdk}/src/components"
                 "${_ups_sdk}/src/backends/shared" "${_ups_sdk}/src/backends/vk")
    set_property(SOURCE ${_ups_ffx3} "${_ups}/upscale_fsr3.cpp" APPEND PROPERTY COMPILE_OPTIONS
                 -include "${_ups}/upscale_fsr3_compat.h" -w)
    set_property(SOURCE "${PORT_DIR}/main.cpp" APPEND PROPERTY COMPILE_DEFINITIONS INFAMOUS_MOD_UPSCALE=1)
    message(STATUS "Upscaler mod:    ON (FSR 2.2, FSR 3.1)")
elseif(INFAMOUS_MOD_UPSCALE)
    message(STATUS "Upscaler mod:    off (needs -DPS3RECOMP_RSX_VULKAN=ON)")
endif()

# ---------------------------------------------------------------------------
# The co-op mod
# ---------------------------------------------------------------------------
enable_testing()
find_package(Threads REQUIRED)
if(INFAMOUS_COOP)
    set(COOP_SOURCES "")
    foreach(src IN ITEMS coop.c coop_net.c coop_follow.c coop_netplay.c coop_video.c coop_session.c
                         coop_audio.c coop_auth.c coop_netui.cpp coop_join.cpp)
        if(EXISTS "${PORT_DIR}/${src}")
            list(APPEND COOP_SOURCES "${PORT_DIR}/${src}")
        endif()
    endforeach()
    # coop.c is POSIX-only until it goes through coop_compat.h
    # (docs/coop/MOD_BUILD.md). Off Linux, leave it out with a warning rather
    # than fail the rest of the mod; once it includes the header it is in.
    if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux")
        file(STRINGS "${PORT_DIR}/coop.c" _compat REGEX "#include \"coop_compat.h\"")
        if(NOT _compat)
            list(REMOVE_ITEM COOP_SOURCES "${PORT_DIR}/coop.c")
            message(WARNING "coop.c does not include coop_compat.h yet: not compiled on "
                            "${CMAKE_SYSTEM_NAME} (docs/coop/MOD_BUILD.md)")
        endif()
    endif()
    add_library(infamous_coop STATIC ${COOP_SOURCES})
    target_include_directories(infamous_coop PRIVATE ${PORT_INCLUDES})
    target_link_libraries(infamous_coop PRIVATE ps3recomp_runtime)
    target_compile_definitions(infamous_coop PRIVATE INFAMOUS_COOP=1)
    target_compile_options(infamous_coop PRIVATE ${PORT_WARN})
    # coop_video.c / coop_audio.c include <SDL2/SDL.h>; the toolkit links SDL2 PRIVATE off
    # Windows, so its include path (Homebrew's /opt/homebrew/include on macOS) is asked for here
    find_package(SDL2 QUIET)
    if(TARGET SDL2::SDL2)
        target_link_libraries(infamous_coop PRIVATE SDL2::SDL2)
        get_target_property(_sdl_inc SDL2::SDL2 INTERFACE_INCLUDE_DIRECTORIES)
    endif()
    foreach(_d IN LISTS _sdl_inc SDL2_INCLUDE_DIRS)   # .../include/SDL2 -> .../include for <SDL2/SDL.h>
        if(_d MATCHES "/SDL2/?$")
            get_filename_component(_d "${_d}" DIRECTORY)
            target_include_directories(infamous_coop PRIVATE "${_d}")
        endif()
    endforeach()
    set_property(SOURCE "${PORT_DIR}/main.cpp" "${PORT_DIR}/ui.cpp" APPEND PROPERTY
                 COMPILE_DEFINITIONS INFAMOUS_COOP=1)
    if(SPU_NATIVE)
        set_property(SOURCE "${PORT_DIR}/ec5f_native.c" APPEND PROPERTY
                     COMPILE_DEFINITIONS INFAMOUS_COOP=1)
    endif()
    list(LENGTH COOP_SOURCES _cn)
    message(STATUS "Co-op mod:       ON (${_cn} source(s))")

    # Online co-op video (coop_video.c): compiled with FFmpeg when pkg-config finds it, without
    # otherwise (it then only logs that there is no video); its loopback test needs FFmpeg.
    if("${PORT_DIR}/coop_video.c" IN_LIST COOP_SOURCES)
        target_compile_definitions(infamous_coop PRIVATE COOP_HAVE_VIDEO=1)
        set_property(SOURCE "${PORT_DIR}/ui.cpp" APPEND PROPERTY COMPILE_DEFINITIONS COOP_HAVE_VIDEO=1)
        find_package(PkgConfig QUIET)
        if(PKG_CONFIG_FOUND)
            pkg_check_modules(COOP_FFMPEG QUIET IMPORTED_TARGET libavcodec libavutil)
        endif()
        if(COOP_FFMPEG_FOUND)
            set_property(SOURCE "${PORT_DIR}/coop_video.c" APPEND PROPERTY COMPILE_DEFINITIONS COOP_HAVE_FFMPEG=1)
            target_link_libraries(infamous_coop PRIVATE PkgConfig::COOP_FFMPEG)
            add_executable(coop_video_test "${PORT_DIR}/tests/coop_video_test.c" "${PORT_DIR}/coop_video.c"
                           "${PORT_DIR}/coop_auth.c")
            target_compile_definitions(coop_video_test PRIVATE CV_STANDALONE CV_NO_PRESENTER COOP_HAVE_FFMPEG=1)
            target_include_directories(coop_video_test PRIVATE "${PORT_DIR}")
            target_compile_options(coop_video_test PRIVATE ${PORT_WARN})
            target_link_libraries(coop_video_test PRIVATE PkgConfig::COOP_FFMPEG Threads::Threads)
            if(WIN32)
                target_link_libraries(coop_video_test PRIVATE ws2_32)
            else()
                target_link_libraries(coop_video_test PRIVATE m)
            endif()
            add_test(NAME coop_video COMMAND coop_video_test)
            message(STATUS "Co-op video:     FFmpeg ${COOP_FFMPEG_libavcodec_VERSION}, loopback test built")
            # the friend's sound: jitter buffer, loss, lip sync on a virtual clock, then for real
            # over the video's socket
            if(PKG_CONFIG_FOUND)
                pkg_check_modules(COOP_OPUS QUIET IMPORTED_TARGET opus)
            endif()
            if(COOP_OPUS_FOUND)
                add_executable(coop_audio_test "${PORT_DIR}/tests/coop_audio_test.c" "${PORT_DIR}/coop_audio.c"
                               "${PORT_DIR}/coop_video.c" "${PORT_DIR}/coop_auth.c")
                target_compile_definitions(coop_audio_test PRIVATE CV_STANDALONE CV_NO_PRESENTER CA_NO_DEVICE CA_NO_TAP
                                           COOP_HAVE_FFMPEG=1 COOP_HAVE_OPUS=1)
                target_include_directories(coop_audio_test PRIVATE "${PORT_DIR}")
                target_compile_options(coop_audio_test PRIVATE ${PORT_WARN})
                target_link_libraries(coop_audio_test PRIVATE PkgConfig::COOP_FFMPEG PkgConfig::COOP_OPUS Threads::Threads)
                if(WIN32)
                    target_link_libraries(coop_audio_test PRIVATE ws2_32)
                else()
                    target_link_libraries(coop_audio_test PRIVATE m)
                endif()
                add_test(NAME coop_audio COMMAND coop_audio_test)
                message(STATUS "Co-op audio:     Opus ${COOP_OPUS_VERSION}, audio test built")
            endif()
        else()
            message(STATUS "Co-op video:     no FFmpeg: coop_video.c without video, no loopback test")
        endif()
    endif()

    # The remote session's own tests: handshake, refusals, ping, reconnect, input uplink, on
    # localhost (IPv6 skipped where there is no ::1). No game, no video.
    # the audio's mix tap is the toolkit's (libs/audio/audio_tap.h); Opus as the game build finds it
    if("${PORT_DIR}/coop_audio.c" IN_LIST COOP_SOURCES)
        target_compile_definitions(infamous_coop PRIVATE COOP_HAVE_AUDIO=1)
        set_property(SOURCE "${PORT_DIR}/coop_audio.c" APPEND PROPERTY INCLUDE_DIRECTORIES "${PS3RECOMP_DIR}/libs/audio")
        find_package(PkgConfig QUIET)
        if(PKG_CONFIG_FOUND)
            pkg_check_modules(COOP_OPUS_LIB QUIET IMPORTED_TARGET opus)
        endif()
        if(COOP_OPUS_LIB_FOUND)
            set_property(SOURCE "${PORT_DIR}/coop_audio.c" APPEND PROPERTY COMPILE_DEFINITIONS COOP_HAVE_OPUS=1)
            target_link_libraries(infamous_coop PRIVATE PkgConfig::COOP_OPUS_LIB)
        endif()
    endif()

    # The pure adaptive-rate controller (no sockets, no FFmpeg).
    add_executable(coop_abr_test "${PORT_DIR}/tests/coop_abr_test.c" "${PORT_DIR}/coop_video.c" "${PORT_DIR}/coop_auth.c")
    target_compile_definitions(coop_abr_test PRIVATE CV_STANDALONE CV_NO_PRESENTER)
    target_compile_options(coop_abr_test PRIVATE ${PORT_WARN})
    target_link_libraries(coop_abr_test PRIVATE Threads::Threads)
    if(COOP_FFMPEG_FOUND)   # coop_video.c carries COOP_HAVE_FFMPEG as a source property here
        target_link_libraries(coop_abr_test PRIVATE PkgConfig::COOP_FFMPEG)
    endif()
    if(WIN32)
        target_link_libraries(coop_abr_test PRIVATE ws2_32)
    else()
        target_link_libraries(coop_abr_test PRIVATE m)
    endif()
    add_test(NAME coop_abr COMMAND coop_abr_test)

    # The friend's JOIN-only client, and the proof it holds nothing of the game.
    include("${PORT_DIR}/join/join.cmake")
    infamous_add_join(PORT_DIR "${PORT_DIR}" IMGUI_DIR "${PS3RECOMP_DIR}/libs/thirdparty/imgui")
    if(TARGET infamous_join)
        add_test(NAME join_no_lift COMMAND "${CMAKE_COMMAND}" -DBIN=$<TARGET_FILE:infamous_join> "-DNM=${CMAKE_NM}"
                 -P "${PORT_DIR}/join/check_no_lift.cmake")
        add_test(NAME join_version COMMAND infamous_join --version)
    endif()

    add_executable(coop_session_test "${PORT_DIR}/tests/coop_session_test.c" "${PORT_DIR}/coop_session.c"
                   "${PORT_DIR}/coop_auth.c")
    target_compile_options(coop_session_test PRIVATE ${PORT_WARN})
    target_link_libraries(coop_session_test PRIVATE Threads::Threads)
    if(WIN32)
        target_link_libraries(coop_session_test PRIVATE ws2_32 winmm)
    endif()
    add_test(NAME coop_session COMMAND coop_session_test)

    # The network layer's own tests: loopback UDP, no game.
    set(_net_test "${PORT_DIR}/tests/coop_net_test.c" "${PORT_DIR}/coop_net.c")
    if(EXISTS "${PORT_DIR}/coop_follow.c")
        list(APPEND _net_test "${PORT_DIR}/coop_follow.c")
    endif()
    add_executable(coop_net_test ${_net_test})
    target_compile_definitions(coop_net_test PRIVATE COOP_NET_TEST)
    target_link_libraries(coop_net_test PRIVATE Threads::Threads)
    if(NOT WIN32)
        target_link_libraries(coop_net_test PRIVATE m)
    else()
        target_link_libraries(coop_net_test PRIVATE ws2_32 winmm)
    endif()
    add_test(NAME coop_net COMMAND coop_net_test)
else()
    message(STATUS "Co-op mod:       off")
endif()

# The settings file round trip (POSIX: the test makes its directory with mkdtemp).
if(UNIX)
    add_executable(settings_test "${PORT_DIR}/tests/settings_test.cpp" "${PORT_DIR}/settings.cpp")
    target_include_directories(settings_test PRIVATE "${PORT_DIR}")
    add_test(NAME settings COMMAND settings_test)
    # The Mod Manager format: mod.json/modular.json, picks, the zip checks and the install.
    find_package(ZLIB REQUIRED)
    add_executable(modfmt_test "${PORT_DIR}/tests/modfmt_test.cpp" "${PORT_DIR}/modfmt.cpp" "${PORT_DIR}/modpatch.cpp" "${PORT_DIR}/settings.cpp")
    target_include_directories(modfmt_test PRIVATE "${PORT_DIR}")
    target_link_libraries(modfmt_test PRIVATE ${ZLIB_LIBRARIES})
    add_test(NAME modfmt COMMAND modfmt_test)
    # Data patches of mods (modpatch.cpp) and the creator kit's rules.
    add_executable(modpatch_test "${PORT_DIR}/tests/modpatch_test.cpp" "${PORT_DIR}/modpatch.cpp" "${PORT_DIR}/settings.cpp")
    target_include_directories(modpatch_test PRIVATE "${PORT_DIR}")
    add_test(NAME modpatch COMMAND modpatch_test)
endif()
