cmake_minimum_required(VERSION 3.20)
project(lindbergh_recomp_ports VERSION 0.1.0 LANGUAGES C)
if(APPLE)
    enable_language(OBJC)       # the runtime's macOS menu bar
endif()

# Sega Lindbergh games, statically recompiled: one folder per game under
# games/ (ghostsquadevolution, hotd4), all on the lindberghrecomp runtime.
#
# A game's target only exists once you have lifted its ELF into
# games/<game>/generated, because the runtime needs two headers generated
# from it. Without any this still configures and builds the toolkit's own
# self-check, so the repo is testable out of the box.
#
#   ./scripts/build-macos.sh <game> /path/to/the/game       (macOS)
#   py -3.11 -m tools recomp <elf> ..\games\<game>\generated  (Windows, see the README)
#   cmake -S . -B build -A Win32
#   cmake --build build --config Release
#
# LINDBERGH_GAMES=<game;...> builds only those (the Quest build makes one
# game per build tree: each is the app's libmain.so).

set(LINDBERGH_GAMES "" CACHE STRING "games to build (empty: every one with lifted code)")

# Native Vulkan by default on macOS and Android/Quest; -DLINDBERGH_RENDERER=OPENGL
# builds the OpenGL renderer. (lindberghrecomp keeps the same default when built
# on its own; defined here first because C++ must be enabled at this scope.)
if(APPLE OR ANDROID)
    set(LINDBERGH_RENDERER "VULKAN" CACHE STRING "Host renderer: OPENGL or VULKAN")
else()
    set(LINDBERGH_RENDERER "OPENGL" CACHE STRING "Host renderer: OPENGL or VULKAN")
endif()
if(LINDBERGH_RENDERER STREQUAL "VULKAN")
    enable_language(CXX)
endif()
add_subdirectory(lindberghrecomp)

function(lindbergh_game id)
    set(src "${CMAKE_CURRENT_SOURCE_DIR}/games/${id}/src")
    set(gen "${CMAKE_CURRENT_SOURCE_DIR}/games/${id}/generated")
    file(GLOB lifted "${gen}/recomp_funcs_*.c")
    if(NOT lifted OR NOT EXISTS "${gen}/recomp_imports.h")
        message(STATUS "${id}: no lifted code in ${gen} yet, not built. See the README.")
        return()
    endif()
    if(ANDROID)
        # Meta Quest: SDL's Java side loads libmain.so and calls SDL_main
        # (android_main.c), which runs host.c's main.
        add_library(${id} SHARED "${src}/host.c" "${src}/android_main.c" ${lifted})
        set_target_properties(${id} PROPERTIES OUTPUT_NAME main)
        set_source_files_properties("${src}/host.c" PROPERTIES COMPILE_DEFINITIONS main=game_main)
    else()
        add_executable(${id} "${src}/host.c" ${lifted})
    endif()
    if(NOT WIN32 OR CMAKE_SIZEOF_VOID_P EQUAL 8)
        # Typed GL thunks for a 64-bit host, generated from the host's GL
        # headers (lindberghrecomp/tools/gen_gl_thunks.py): on the Quest from
        # gl4es' when the game has its own set for them
        if(LINDBERGH_RENDERER STREQUAL "VULKAN")
            set(vk_thunks "${CMAKE_CURRENT_BINARY_DIR}/vulkan-thunks-${id}.c")
            execute_process(COMMAND "${LINDBERGH_VULKAN_PYTHON}"
                "${CMAKE_CURRENT_SOURCE_DIR}/lindberghrecomp/tools/gen_gl_thunks.py"
                "${gen}/recomp_imports.h" ${LINDBERGH_GL_HEADERS}
                OUTPUT_FILE "${vk_thunks}.tmp" COMMAND_ERROR_IS_FATAL ANY)
            execute_process(COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${vk_thunks}.tmp" "${vk_thunks}" COMMAND_ERROR_IS_FATAL ANY)
            file(REMOVE "${vk_thunks}.tmp")
            set(LINDBERGH_VULKAN_THUNKS_${id} "${vk_thunks}" CACHE INTERNAL "Vulkan guest thunks" FORCE)
            target_sources(${id} PRIVATE "${vk_thunks}")
        elseif(WIN32)
            target_sources(${id} PRIVATE "${gen}/recomp_gl_thunks_windows.c")
        elseif(ANDROID AND EXISTS "${gen}/recomp_gl_thunks_android.c")
            target_sources(${id} PRIVATE "${gen}/recomp_gl_thunks_android.c")
        else()
            target_sources(${id} PRIVATE "${gen}/recomp_gl_thunks.c")
        endif()
        # libraries the game dlopens, lifted by lindberghrecomp/tools/recomp/solib.py
        file(GLOB solib "${gen}/recomp_solib_*.c")
        target_sources(${id} PRIVATE ${solib})
    endif()
    # The local builder clears the toolchain's default release flags.
    # Optimize lifted gameplay code on Windows without requiring a newer CPU.
    if(id STREQUAL "hotd4" AND WIN32 AND CMAKE_C_COMPILER_ID STREQUAL "GNU")
        set_property(SOURCE ${lifted} APPEND PROPERTY
            COMPILE_OPTIONS "$<$<CONFIG:Release>:-O1>")
        # Sofdec/MPEG and ADX chunks need extra optimization for real-time playback.
        foreach(chunk IN ITEMS 0058 0059 0060 0062 0066)
            set_property(SOURCE "${gen}/recomp_funcs_${chunk}.c" APPEND PROPERTY
                COMPILE_OPTIONS "$<$<CONFIG:Release>:-O2>")
        endforeach()
        # The supported dump's lifted CRI decoder is in this translation unit.
        set_property(SOURCE "${gen}/recomp_funcs_0062.c" APPEND PROPERTY
            COMPILE_DEFINITIONS RECOMP_MMX_SSE2)
    endif()
    if(id STREQUAL "hotd4" AND WIN32 AND CMAKE_SIZEOF_VOID_P EQUAL 8 AND
       NOT LINDBERGH_OPENXR AND NOT LINDBERGH_RENDERER STREQUAL "VULKAN")
        target_sources(${id} PRIVATE "${src}/hotd4_lighting.c" "${src}/hotd4_hd_textures.c")
    endif()
    lindbergh_runtime(${id} "${gen}")
    if(ANDROID AND LINDBERGH_VULKAN_OFFSCREEN)
        add_executable(${id}_vulkan_offscreen "${CMAKE_CURRENT_SOURCE_DIR}/quest/vulkan_offscreen.c")
        target_link_libraries(${id}_vulkan_offscreen PRIVATE ${id} SDL2::SDL2)
    endif()
    message(STATUS "${id}: building against lifted code in ${gen}")
endfunction()

file(GLOB game_dirs LIST_DIRECTORIES true "${CMAKE_CURRENT_SOURCE_DIR}/games/*")
foreach(dir ${game_dirs})
    if(IS_DIRECTORY "${dir}" AND EXISTS "${dir}/src/host.c")
        get_filename_component(id "${dir}" NAME)
        if(NOT LINDBERGH_GAMES OR id IN_LIST LINDBERGH_GAMES)
            lindbergh_game(${id})
        endif()
    endif()
endforeach()
