cmake_minimum_required(VERSION 3.20)
project(joyride C)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)   # build/compile_commands.json, for clangd

# The lifted game code is generated from the user's own executable by
# tools/lift.sh and never committed; the build needs it to exist.
set(JOYRIDE_GEN_DIR "${CMAKE_SOURCE_DIR}/gen/wino/recomp" CACHE PATH
    "Directory with the C generated by tools/lift.sh")
# JOYRIDE_RUNTIME_ONLY: joyride without the game, its runtime library alone
# (what the AppImage carries; the player's machine adds the generated code)
option(JOYRIDE_RUNTIME_ONLY "Build only joyride's runtime library, no generated code" OFF)
# JOYRIDE_RELEASE: a build for players (the AppImage, the Windows bundle):
# without the debugging aids (debug.c: L4's report, L5's weapons and cars)
option(JOYRIDE_RELEASE "A release: no debugging aids" OFF)
file(GLOB JOYRIDE_GEN_SOURCES "${JOYRIDE_GEN_DIR}/*.c")
if(NOT JOYRIDE_GEN_SOURCES AND NOT JOYRIDE_RUNTIME_ONLY)
    message(FATAL_ERROR "No generated code in ${JOYRIDE_GEN_DIR}. Run tools/lift.sh first.")
endif()

set(PCRECOMP "${CMAKE_SOURCE_DIR}/external/pcrecomp")
if(NOT EXISTS "${PCRECOMP}/runtime/win32hle/win32hle.h")
    message(FATAL_ERROR "pcrecomp submodule missing: git submodule update --init")
endif()

if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8)
    message(FATAL_ERROR "joyride builds 64-bit: the guest's 4 GB is one mapping at a fixed host address")
endif()

if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE RelWithDebInfo)
endif()

# SDL3 for the window, input, audio and SDL_GPU presenting; SDL3_ttf for the
# TrueType text win32hle's GDI draws.
find_package(SDL3 REQUIRED CONFIG)
find_package(SDL3_ttf REQUIRED CONFIG)
find_package(Threads REQUIRED)

# ffmpeg decodes the intro movie (Smacker). Optional: without it the game
# skips the movie.
option(JOYRIDE_WITH_FFMPEG "Play the intro movie through ffmpeg" ON)
if(JOYRIDE_WITH_FFMPEG)
    find_package(PkgConfig)
    if(PkgConfig_FOUND)
        pkg_check_modules(FFMPEG IMPORTED_TARGET libavformat libavcodec libavutil)
    endif()
    if(NOT FFMPEG_FOUND)
        message(WARNING "ffmpeg (libavformat, libavcodec, libavutil) not found: the intro movie will be skipped")
        set(JOYRIDE_WITH_FFMPEG OFF)
    endif()
endif()

# Guest memory: one 4 GB block at this host address; ADDR(va) adds it as a constant.
set(JOYRIDE_DEFS RECOMP_MEM_BASE=0x100000000000ull)
if(WIN32)
    # recomp_types.h defines its shared globals in every file, weakly, for the
    # linker to keep one: ELF does, PE/COFF keeps every file's own (50 copies:
    # the lifted loops' yield hook was set in one and NULL in the rest, and the
    # game waited for a timer tick forever). On Windows they are link-once
    # instead, selectany when initialised and common when not, in the game
    # and the runtime alike
    set(JOYRIDE_ONCE_FLAGS -Dweak=selectany -fcommon)
endif()

# --- the lifted game: huge, machine-made; build it fast and quietly ---------
# (tools/link-game.sh compiles it with these same flags on a player's machine)
if(NOT JOYRIDE_RUNTIME_ONLY)
    add_library(joyride_gen OBJECT ${JOYRIDE_GEN_SOURCES})
    target_include_directories(joyride_gen PRIVATE "${PCRECOMP}/runtime/recomp32" "${JOYRIDE_GEN_DIR}")
    target_compile_definitions(joyride_gen PRIVATE ${JOYRIDE_DEFS})
    target_compile_options(joyride_gen PRIVATE -O1 -w "SHELL:-include ${JOYRIDE_GEN_DIR}/recomp_funcs.h"
        "SHELL:-include ${CMAKE_SOURCE_DIR}/src/hle/texfilter_inline.h")   # the filter's per-pixel part, inlined
    target_compile_options(joyride_gen PRIVATE ${JOYRIDE_ONCE_FLAGS})
endif()

# --- pcrecomp's Win32 layer, minus its selftests and the four files that use
# SDL2: screen.c and present.c are replaced by joyride's SDL3/SDL_GPU screen,
# gdidc.c and dsound.c by SDL3 ports of themselves (src/platform/).
file(GLOB WIN32HLE_SOURCES "${PCRECOMP}/runtime/win32hle/*.c")
list(FILTER WIN32HLE_SOURCES EXCLUDE REGEX "(_selftest|/screen|/present|/gdidc|/dsound)\\.c$")
if(WIN32)
    # joyride on Windows (cmake/mingw-w64.cmake): what the runtime takes from
    # POSIX, kept here (src/compat/win/); no guest Winsock (GTA's network play
    # is DirectPlay, joyride's own)
    list(FILTER WIN32HLE_SOURCES EXCLUDE REGEX "/wsock32\\.c$")
    add_library(joyride_compat STATIC src/compat/win/compat_win.c)
    enable_language(RC)
    add_library(joyride_icon OBJECT src/compat/win/joyride.rc)            # joyride.exe's icon
    target_include_directories(joyride_compat PRIVATE src/compat/win)
    set(JOYRIDE_COMPAT_FLAGS "SHELL:-include ${CMAKE_SOURCE_DIR}/src/compat/win/posix_win.h")
endif()
add_library(win32hle STATIC ${WIN32HLE_SOURCES}
    src/platform/screen_sdl3.c
    src/platform/gdidc_sdl3.c
    src/platform/dsound_sdl3.c)
target_include_directories(win32hle PRIVATE src/hle)
if(WIN32)
    target_sources(win32hle PRIVATE src/compat/win/wsock32_none.c)
    target_include_directories(win32hle BEFORE PUBLIC src/compat/win)
    target_compile_options(win32hle PUBLIC ${JOYRIDE_COMPAT_FLAGS} ${JOYRIDE_ONCE_FLAGS})
    target_link_libraries(win32hle PUBLIC joyride_compat ws2_32 winmm)
endif()
# the window's icon (art/joyride-128.png, joyride's own), in the program
file(READ "${CMAKE_SOURCE_DIR}/art/joyride-128.png" JOYRIDE_ICON HEX)
string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," JOYRIDE_ICON "${JOYRIDE_ICON}")
file(WRITE "${CMAKE_BINARY_DIR}/icon/joyride_icon.h" "static const unsigned char joyride_icon_png[] = { ${JOYRIDE_ICON} };\n")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_SOURCE_DIR}/art/joyride-128.png")
target_include_directories(win32hle PRIVATE "${CMAKE_BINARY_DIR}/icon")
target_include_directories(win32hle PUBLIC "${PCRECOMP}/runtime/win32hle" "${PCRECOMP}/runtime/recomp32")
target_compile_definitions(win32hle PUBLIC ${JOYRIDE_DEFS})
target_compile_options(win32hle PRIVATE -w)
target_link_libraries(win32hle PUBLIC SDL3::SDL3 SDL3_ttf::SDL3_ttf Threads::Threads m)

# --- shaders: GLSL -> SPIR-V at build time (glslc, from shaderc), embedded
# as C arrays. Without glslc the texture filter runs on the CPU only.
find_program(GLSLC glslc)
set(JOYRIDE_PREBUILT_SHADERS "" CACHE PATH "The shaders as C headers, compiled elsewhere (where there is no glslc)")
if(GLSLC)
    set(JOYRIDE_SHADER_DIR "${CMAKE_BINARY_DIR}/shaders")
    set(JOYRIDE_SHADER_HEADERS)
    foreach(shader fullscreen.vert texfilter.frag hwquad.vert hwquad.frag composite.frag map.frag)
        set(out "${JOYRIDE_SHADER_DIR}/${shader}.h")
        add_custom_command(OUTPUT "${out}"
            COMMAND ${CMAKE_COMMAND} -E make_directory "${JOYRIDE_SHADER_DIR}"
            COMMAND ${GLSLC} -O -mfmt=c -o "${out}" "${CMAKE_SOURCE_DIR}/shaders/${shader}"
            DEPENDS "${CMAKE_SOURCE_DIR}/shaders/${shader}"
            COMMENT "glslc ${shader}")
        list(APPEND JOYRIDE_SHADER_HEADERS "${out}")
    endforeach()
    add_custom_target(joyride_shaders DEPENDS ${JOYRIDE_SHADER_HEADERS})
    add_dependencies(win32hle joyride_shaders)
    target_include_directories(win32hle PRIVATE "${JOYRIDE_SHADER_DIR}")
    target_compile_definitions(win32hle PRIVATE JOYRIDE_GPU_FILTER)
elseif(JOYRIDE_PREBUILT_SHADERS)
    # compiled elsewhere (glslc -O -mfmt=c, the same headers): a build where
    # glslc is not, as the release's (tools/release-linux)
    set(JOYRIDE_SHADER_DIR "${JOYRIDE_PREBUILT_SHADERS}")
    target_include_directories(win32hle PRIVATE "${JOYRIDE_SHADER_DIR}")
    target_compile_definitions(win32hle PRIVATE JOYRIDE_GPU_FILTER)
else()
    message(STATUS "glslc not found: texture filtering on the CPU only")
endif()

# --- joyride itself: its runtime, then the game linked to it ------------------
add_library(joyride_runtime STATIC
    src/host/main.c
    src/hle/mss.c
    src/hle/smack.c
    src/hle/ddraw_extra.c
    src/hle/dplay.c
    src/hle/texfilter.c
    src/hle/display.c
    src/hle/smooth.c
    src/hle/hwrender.c
    src/platform/overlay.c
    src/platform/pad.c
    src/platform/map.c
    src/platform/debug.c
    src/platform/backdrop.c
    src/platform/driveby.c
    src/platform/savegame.c)
target_include_directories(joyride_runtime PRIVATE src/hle)
if(JOYRIDE_RELEASE)
    target_compile_definitions(joyride_runtime PRIVATE JOYRIDE_RELEASE)
endif()
target_compile_options(joyride_runtime PRIVATE -Wall -Wextra -Wno-unused-parameter -Wno-format-truncation)
target_link_libraries(joyride_runtime PUBLIC win32hle)
if(JOYRIDE_WITH_FFMPEG)
    target_compile_definitions(joyride_runtime PRIVATE JOYRIDE_WITH_FFMPEG)
    target_link_libraries(joyride_runtime PUBLIC PkgConfig::FFMPEG)
endif()
if(NOT JOYRIDE_RUNTIME_ONLY)
    add_executable(joyride $<TARGET_OBJECTS:joyride_gen> $<$<BOOL:${WIN32}>:$<TARGET_OBJECTS:joyride_icon>>)
    set_target_properties(joyride PROPERTIES LINKER_LANGUAGE C)
    target_link_libraries(joyride PRIVATE joyride_runtime)
endif()
