cmake_minimum_required(VERSION 3.20)

# Xbox Kernel Replacement Layer
# Replaces 147 Xbox kernel imports with Win32 equivalents.
# Memory layout, file I/O, threading, synchronization, crypto, HAL.

set(KERNEL_SOURCES
    kernel_path.c
    kernel_pool.c
    kernel_rtl.c
    kernel_memory.c
    kernel_file.c
    kernel_thread.c
    kernel_sync.c
    kernel_hal.c
    kernel_xbox.c
    kernel_ob.c
    kernel_io.c
    kernel_crypto.c
    kernel_thunks.c
    kernel_bridge.c
    xbox_memory_layout.c
    icall_feedback.c
    recomp_trace.c
    nv2a_pb_scan.c
    nv2a_pb_exec.c
    nv2a_d3d11.c
)

# DLSS through NVIDIA Streamline (nv2a_dlss.h). Only with the SDK's folder in
# RECOMP_STREAMLINE_DIR, and then the consuming project must have enabled CXX
# (enable_language at its top level): the Streamline headers are C++. Without
# it, a stub that says DLSS is not available.
if(RECOMP_STREAMLINE_DIR AND EXISTS "${RECOMP_STREAMLINE_DIR}/include/sl.h")
    list(APPEND KERNEL_SOURCES nv2a_dlss.cpp)
    set(XBOX_KERNEL_STREAMLINE ON)
else()
    list(APPEND KERNEL_SOURCES nv2a_dlss_stub.c)
    set(XBOX_KERNEL_STREAMLINE OFF)
endif()

add_library(xbox_kernel STATIC ${KERNEL_SOURCES})

if(XBOX_KERNEL_STREAMLINE)
    file(TO_NATIVE_PATH "${RECOMP_STREAMLINE_DIR}/bin/x64" _sl_bin)
    string(REPLACE "\\" "\\\\" _sl_bin "${_sl_bin}")
    target_include_directories(xbox_kernel PRIVATE "${RECOMP_STREAMLINE_DIR}/include")
    target_compile_definitions(xbox_kernel PRIVATE
        RECOMP_STREAMLINE=1
        "RECOMP_STREAMLINE_BIN_DEFAULT=L\"${_sl_bin}\"")
    message(STATUS "xbox_kernel: DLSS through Streamline, ${RECOMP_STREAMLINE_DIR}")
endif()

# See src/platform/CMakeLists.txt: resolve src/ relative to this file, not via
# CMAKE_SOURCE_DIR, which is the consuming project's root under add_subdirectory().
get_filename_component(XBOXRECOMP_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/.." ABSOLUTE)

target_include_directories(xbox_kernel PUBLIC
    ${CMAKE_CURRENT_SOURCE_DIR}
    ${XBOXRECOMP_SRC_DIR}
)

if(WIN32)
    # platform is an INTERFACE target on Windows: it contributes the src/
    # include path that "platform/xbox_winnt.h" resolves against.
    target_link_libraries(xbox_kernel PUBLIC platform kernel32 bcrypt winmm
                          d3d11 dxgi dxguid d3dcompiler windowscodecs ole32)
else()
    # Linux: platform layer (POSIX host primitives) + OpenSSL for crypto.
    find_package(OpenSSL REQUIRED)
    target_link_libraries(xbox_kernel PUBLIC platform OpenSSL::Crypto)
endif()

if(MSVC)
    target_compile_options(xbox_kernel PRIVATE /W4 /WX- /O2 /GS- /Gy)
    target_compile_definitions(xbox_kernel PRIVATE _CRT_SECURE_NO_WARNINGS)
else()
    target_compile_options(xbox_kernel PRIVATE -Wall -Wextra -Wno-unused-parameter -O2)
endif()

target_compile_definitions(xbox_kernel PRIVATE $<$<CONFIG:Debug>:_DEBUG>)
