cmake_minimum_required(VERSION 3.23)

# Oldest macOS the build runs on. 11.0 (Big Sur) is the first release with
# Apple Silicon, so nothing lower is possible for arm64. It has to be set
# before project(): project() creates an empty cache entry, and a later
# set(... CACHE) cannot replace it, so the compiler falls back to the SDK
# version and the binary refuses to start on anything older than the build
# machine. FORCE only fills an empty value, which build folders configured
# before this fix still hold; a -D on the command line still wins. Ignored
# off Apple.
if(NOT CMAKE_OSX_DEPLOYMENT_TARGET)
    set(CMAKE_OSX_DEPLOYMENT_TARGET "11.0" CACHE STRING
        "Minimum macOS version the build runs on" FORCE)
endif()

project(LBA2)

# Emit compile_commands.json so clang-tidy and other tooling can analyze the
# real build configuration. See .clang-tidy and scripts/ci/run-clang-tidy.sh.
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Option to enable x86 assembly (requires UASM). Default OFF since all ASM is ported to C++.
option(ENABLE_ASM "Enable x86 assembly (requires UASM assembler)" OFF)

if(ENABLE_ASM)
    # UASM assembly compiler setup (must happen before enable_language)
    set(CMAKE_ASM_MASM_COMPILER uasm)
    set(CMAKE_ASM_MASM_FLAGS_INIT "-D_WIN32 -Zm -c -Cx -Cp -W4 -nologo -Sg -Sa -Zd")
    if(WIN32)
        set(CMAKE_ASM_MASM_FLAGS_INIT ${CMAKE_ASM_MASM_FLAGS_INIT}" -coff")
    else()
        set(CMAKE_ASM_MASM_FLAGS_INIT ${CMAKE_ASM_MASM_FLAGS_INIT}" -elf -zcw")
    endif()
    enable_language(C CXX ASM_MASM)
else()
    enable_language(C CXX)
endif()

set(CMAKE_CXX_STANDARD 98)

# Compilation options
set(SOUND_BACKEND "sdl" CACHE STRING "Sound backend to be used")
set(MVIDEO_BACKEND "smacker" CACHE STRING "Motion Video backend to be used")
# Compilation options sanitization
## Sound backend
set(SOUND_BACKEND_OPTIONS null miles sdl xaudio2)
set_property(CACHE SOUND_BACKEND PROPERTY STRINGS ${SOUND_BACKEND_OPTIONS})
if (NOT SOUND_BACKEND IN_LIST SOUND_BACKEND_OPTIONS)
    message(SEND_ERROR "SOUND_BACKEND set with invalid option '${SOUND_BACKEND}'. Valid options are: ${SOUND_BACKEND_OPTIONS}")
endif ()
## Motion Video backend
set(MVIDEO_BACKEND_OPTIONS null smacker)
set_property(CACHE MVIDEO_BACKEND PROPERTY STRINGS ${MVIDEO_BACKEND_OPTIONS})
if (NOT MVIDEO_BACKEND IN_LIST MVIDEO_BACKEND_OPTIONS)
    message(SEND_ERROR "MVIDEO_BACKEND set with invalid option '${MVIDEO_BACKEND}'. Valid options are: ${MVIDEO_BACKEND_OPTIONS}")
endif ()

# Testing options
option(LBA2_BUILD_TESTS "Build test suites" OFF)
option(LBA2_BUILD_ASM_EQUIV_TESTS "Build ASM↔CPP equivalence tests (requires objcopy; use OFF for host-only discovery tests)" ON)
# On by default in a build with tests, so test_polyrec.sh runs without a second build; off in
# a player's build. Idle, it is a flag test per draw call: 2400 headless ticks took the same
# 4.6 s with it and without on an Apple Silicon Mac.
option(ENABLE_POLY_RECORDING "Enable polygon call recording for ASM-vs-CPP testing" ${LBA2_BUILD_TESTS})
option(LBA2_GAMEPAD_STICK_LAYOUT "Default to left-stick movement and east-button dodge (controllers without triggers or stick clicks)" OFF)
option(LBA2_VITA_DIAGNOSTICS "Capture early Vita boot/stdout/stderr locally and enable optional DEBUGNET" OFF)
if(LBA2_VITA_DIAGNOSTICS AND NOT VITA)
    message(FATAL_ERROR "LBA2_VITA_DIAGNOSTICS requires the Vita toolchain.")
endif()

# Debug tools (original Adeline developer debug features)
option(DEBUG_TOOLS "Enable developer debug tools (collision viz, benchmarks, bug saves)" OFF)
if(DEBUG_TOOLS)
    add_compile_definitions(DEBUG_TOOLS=1)
endif()

# Interactive control socket (--listen). Runs arbitrary console commands for
# whoever connects, so it stays out of any binary a player might run: OFF here,
# and off again at runtime unless --listen names a port. It binds loopback only.
# See SOURCES/CONTROL_SERVER.H for what it is and is not for.
option(LBA2_CONTROL_SERVER "Enable the --listen console command socket (debug builds only)" OFF)
if(LBA2_CONTROL_SERVER)
    add_compile_definitions(LBA2_CONTROL_SERVER=1)
endif()

# Build the Android target as a command-line executable rather than the .so the
# Java Activity loads. There is no Activity in that shape, so no argv comes from
# an intent and no stdout is swallowed: `adb shell` hands back real arguments,
# separated stdout and stderr, and a real exit code, which is what the
# automation suite reads. It is for measuring ARM behaviour on a device and is
# not a shippable artifact, and needs the null platform (see LIB386/PLATFORM).
# See scripts/dev/android-lba2cc.sh and docs/ANDROID.md.
option(LBA2_ANDROID_EXECUTABLE "Build the Android engine as a CLI executable for on-device automation" OFF)
if(LBA2_ANDROID_EXECUTABLE)
    if(NOT ANDROID)
        message(FATAL_ERROR "LBA2_ANDROID_EXECUTABLE only means anything in an Android build")
    endif()
endif()

# The 1997 playable demo. A separate SKU, not a mode: the demo build has three
# fixed save slots instead of free saves, chains them on cube exit, permanently
# overlays the title logo, and ships neither voices nor cutscenes. Its data set
# is a different install (one island), so a demo binary cannot run retail data
# or the reverse. See docs/GAME_DATA.md.
option(LBA2_BUILD_DEMO "Build the 1997 playable-demo SKU (needs demo game data)" OFF)
if(LBA2_BUILD_DEMO)
    add_compile_definitions(DEMO=1)
endif()

# Performance options
option(LBA2_NATIVE_ARCH "Use -march=native for host-optimized build (not portable)" OFF)

# Release packaging — static-link the selected SDL SDK and the GCC runtime so the binary
# has no DLL dependencies beyond OS libraries. Used by the Windows release
# workflow (single-exe portable ZIP). Default OFF; dev workflows keep the
# faster shared-link path.
option(LBA2_LINK_STATIC "Static-link the selected SDL SDK and the GCC C++ runtime (release packaging)" OFF)

# Release packaging: compile with debug info so scripts/packaging/split-symbols.sh
# can move it into a symbol file published beside the release, which turns a crash
# block's module+offset frames into file, line and inlined frames. -g does not
# change the generated code, and the shipped binary is stripped of it again.
option(LBA2_RELEASE_SYMBOLS "Compile with -g for split symbol files (release packaging)" OFF)
if(LBA2_RELEASE_SYMBOLS AND NOT MSVC)
    add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:-g>)
    # With LTO the code is generated at the link, and MinGW GCC then writes the
    # program's debug info only if the link has -g too; ELF targets carry it in
    # from the objects, which is why only Windows needed this.
    add_link_options(-g)
endif()

if(CMAKE_BUILD_TYPE STREQUAL "Release")
    include(CheckIPOSupported)
    check_ipo_supported(RESULT ipo_supported OUTPUT ipo_error)
    if(ipo_supported)
        set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
    else()
        message(STATUS "LTO not supported: ${ipo_error}")
    endif()
endif()

# The link lines repeat some static libraries because GNU ld resolves them in
# order (see SOURCES/CMakeLists.txt). Apple's linker resolves them in any order
# and warns about each repeat, so turn that one warning off there.
if(APPLE)
    include(CheckLinkerFlag)
    check_linker_flag(CXX "-Wl,-no_warn_duplicate_libraries" LBA2_LD_NO_WARN_DUPLICATE_LIBS)
    if(LBA2_LD_NO_WARN_DUPLICATE_LIBS)
        add_link_options(-Wl,-no_warn_duplicate_libraries)
    endif()
endif()

# Type-based alias analysis has to stay off. The 1997 sources read a struct
# field back through a pointer of another type to get at its packed halves --
# `*(U32 *)&current->V_MapU` in the polygon clipper, the same shape in the
# object renderer and the HQR loader. Watcom defined that; ISO C++ does not, so
# gcc and clang are entitled to reorder or fold those loads once optimisation is
# on, and Release builds here run at -O2 or above with LTO. Eleven sites do it,
# spread across the code least tolerant of a silent codegen change, so the build
# opts out rather than rewriting them one at a time. The flag costs almost
# nothing on this workload.
if(NOT MSVC)
    add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:-fno-strict-aliasing>)
endif()

# No fused multiply-add. Where long double is not the x87's, the float 3D
# routines round with an inline add of 1.5 * 2^52 (LIB386/H/3D/X87REAL.H), and
# GCC's default -ffp-contract=fast fuses a projection's multiply into that add:
# one rounding instead of two, which moves exact half-pixel ties. Clang only
# contracts inside one expression, but takes the same flag. It is set for every
# target, not only the 3D library, because GCC applies the caller's setting to
# code it inlines at the LTO link: with the flag on the library alone, a
# projection inlined into another file fused again.
if(NOT MSVC)
    add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:-ffp-contract=off>)
endif()

if(LBA2_NATIVE_ARCH)
    if(CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|amd64|AMD64|i[3-6]86")
        add_compile_options(-march=native)
    elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64|arm64|ARM64")
        add_compile_options(-mcpu=native)
    endif()
endif()

# The selected platform owns its SDK dependencies and entry point.
if(NINTENDO_SWITCH)
    if(NOT PLATFORM_BACKEND STREQUAL "sdl2" OR NOT LBA2_LINK_STATIC)
        message(FATAL_ERROR "Nintendo Switch requires PLATFORM_BACKEND=sdl2 and LBA2_LINK_STATIC=ON. Use the switch preset.")
    endif()
    if(ENABLE_ASM OR LBA2_NATIVE_ARCH OR LBA2_BUILD_TESTS OR LBA2_CONTROL_SERVER)
        message(FATAL_ERROR "Nintendo Switch does not support x86 ASM, native-host tuning, desktop test executables or the control server.")
    endif()
endif()
if(VITA)
    if(NOT PLATFORM_BACKEND STREQUAL "sdl2" OR NOT LBA2_LINK_STATIC)
        message(FATAL_ERROR "PlayStation Vita requires PLATFORM_BACKEND=sdl2 and LBA2_LINK_STATIC=ON. Use the vita preset.")
    endif()
    if(ENABLE_ASM OR LBA2_NATIVE_ARCH OR LBA2_BUILD_TESTS OR LBA2_CONTROL_SERVER)
        message(FATAL_ERROR "PlayStation Vita does not support x86 ASM, native-host tuning, desktop test executables or the control server.")
    endif()
endif()
add_subdirectory(LIB386/PLATFORM)

# Engine version string. Reads the canonical value from the VERSION file
# at the repo root and (optionally) appends -dirty when the working tree
# has uncommitted changes. Produces both ${CMAKE_BINARY_DIR}/VERSION.txt
# (plain text, for release pipelines) and ${CMAKE_BINARY_DIR}/VERSION_GENERATED.h
# (defines LBA2_VERSION_STRING for the binary).
include(${CMAKE_SOURCE_DIR}/cmake/git_version.cmake)

# Product metadata. Single source of truth for executable name, runtime window
# title, .desktop entry, and AppImage labels. Override any of these with -D...
# at configure time (see docs/RELEASING.md).
set(LBA2_EXECUTABLE_NAME    "lba2cc"                        CACHE STRING "Name of the built game executable")
set(LBA2_PRODUCT_NAME       "LBA2 Classic Community"        CACHE STRING "Display name (window title, .desktop Name, AppImage label)")
set(LBA2_PRODUCT_NAME_DEMO  "LBA2 Twinsen's Odyssey Demo"   CACHE STRING "Display name when the binary is built with -DDEMO")
set(LBA2_PRODUCT_DESCRIPTION "A community source port of Little Big Adventure 2"
                                                            CACHE STRING "One-line description (.desktop Comment, AppStream summary)")
set(LBA2_DESKTOP_ID         "lba2cc"                        CACHE STRING "Desktop file basename and icon ID")
# Wording follows the Copyright section of README.md. The macOS About box is
# the only consumer today; the Windows resource has no LegalCopyright entry.
set(LBA2_COPYRIGHT          "Copyright [2.21]. Originally developed by Adeline Software International. Engine source under GPL-2.0-only."
                                                            CACHE STRING "Copyright line shown in platform About boxes")
set(LBA2_BUNDLE_IDENTIFIER  "org.lbalab.lba2cc"             CACHE STRING "Reverse-DNS app identifier (macOS bundle ID, AppStream component ID)")

# Build info header (timestamp from compile, flags from configure,
# version macro from the include of VERSION_GENERATED.h inside BUILD_INFO.h.in).
set(BUILD_FLAGS_STR "PLATFORM_BACKEND=${PLATFORM_BACKEND} SOUND_BACKEND=${SOUND_BACKEND} MVIDEO_BACKEND=${MVIDEO_BACKEND} ENABLE_ASM=${ENABLE_ASM}")
configure_file(${CMAKE_SOURCE_DIR}/SOURCES/BUILD_INFO.h.in ${CMAKE_BINARY_DIR}/BUILD_INFO.h)

# Generate the .desktop entry, AppStream metainfo and AppImage env file from
# the product metadata above. Outputs land in ${CMAKE_BINARY_DIR}/packaging/,
# where make-appimage.sh picks them up.
#
# The metainfo filename must be the component ID, which is what AppStream
# tooling matches on; make-appimage.sh installs it to usr/share/metainfo/
# inside the AppDir.
configure_file(${CMAKE_SOURCE_DIR}/packaging/lba2cc.desktop.in
               ${CMAKE_BINARY_DIR}/packaging/${LBA2_DESKTOP_ID}.desktop @ONLY)
configure_file(${CMAKE_SOURCE_DIR}/packaging/lba2cc.metainfo.xml.in
               ${CMAKE_BINARY_DIR}/packaging/${LBA2_BUNDLE_IDENTIFIER}.metainfo.xml @ONLY)
configure_file(${CMAKE_SOURCE_DIR}/packaging/appimage_env.sh.in
               ${CMAKE_BINARY_DIR}/packaging/appimage_env.sh @ONLY)

# Windows resource file: drives the .exe icon and Properties → Details
# (Product Name, File Description, Product Version, ...). Compiled into
# the binary on Windows builds via SOURCES/CMakeLists.txt; harmlessly
# generated and ignored on non-Windows.
#
# VERSION changes refresh configure-time package metadata automatically.
# Git dirty-state changes still need a reconfigure for this metadata.
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_SOURCE_DIR}/VERSION")
file(READ "${CMAKE_SOURCE_DIR}/VERSION" _LBA2_VER_RAW)
string(STRIP "${_LBA2_VER_RAW}" LBA2_VERSION_STRING_CONFIG)
if(GIT_EXECUTABLE AND EXISTS "${CMAKE_SOURCE_DIR}/.git"
                  AND NOT LBA2_VERSION_STRING_CONFIG MATCHES "-dirty$")
    execute_process(
        COMMAND ${GIT_EXECUTABLE} diff-index --quiet HEAD --
        WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
        RESULT_VARIABLE _LBA2_GIT_DIRTY
        OUTPUT_QUIET ERROR_QUIET)
    if(_LBA2_GIT_DIRTY EQUAL 1)
        set(LBA2_VERSION_STRING_CONFIG "${LBA2_VERSION_STRING_CONFIG}-dirty")
    endif()
endif()
# 4-tuple of integers for VERSIONINFO FILEVERSION / PRODUCTVERSION:
# strip pre-release/dirty suffix, split on '.', right-pad zeros to 4 parts.
string(REGEX MATCH "^[0-9]+(\\.[0-9]+)*" _LBA2_VER_NUM "${LBA2_VERSION_STRING_CONFIG}")
string(REPLACE "." ";" _LBA2_VER_PARTS "${_LBA2_VER_NUM}")
list(LENGTH _LBA2_VER_PARTS _LBA2_VER_N)
while(_LBA2_VER_N LESS 4)
    list(APPEND _LBA2_VER_PARTS 0)
    math(EXPR _LBA2_VER_N "${_LBA2_VER_N} + 1")
endwhile()
list(JOIN _LBA2_VER_PARTS "," LBA2_VERSION_TUPLE)
# VS_FF_PRERELEASE (0x2) for any non-pure-numeric version (covers -dev, -dirty,
# -rc1, etc.). Pure x.y.z → clean release (0x0).
if(LBA2_VERSION_STRING_CONFIG MATCHES "[a-zA-Z]")
    set(LBA2_VERSIONINFO_FLAGS "0x2L")
else()
    set(LBA2_VERSIONINFO_FLAGS "0x0L")
endif()
configure_file(${CMAKE_SOURCE_DIR}/packaging/lba2cc.rc.in
               ${CMAKE_BINARY_DIR}/packaging/lba2cc.rc @ONLY)

# macOS .app bundle metadata (Info.plist) + .icns icon generation.
# Only meaningful when building on macOS — gated to avoid generating
# stray files on other platforms.
if(APPLE)
    # LSMinimumSystemVersion comes from CMAKE_OSX_DEPLOYMENT_TARGET, set at
    # the top of this file.
    configure_file(${CMAKE_SOURCE_DIR}/packaging/Info.plist.in
                   ${CMAKE_BINARY_DIR}/packaging/Info.plist @ONLY)

    # Generate <id>.icns from <id>.png at build time using macOS native
    # tools (sips for resampling, iconutil for the multi-resolution
    # container). Both ship with Xcode CLI tools — no extra deps. The
    # .icns is consumed by the .app bundle via CFBundleIconFile in the
    # Info.plist (set to LBA2_DESKTOP_ID, with the .icns extension implied).
    set(_LBA2_ICNS_PNG     "${CMAKE_SOURCE_DIR}/packaging/${LBA2_DESKTOP_ID}.png")
    set(_LBA2_ICNS_OUT     "${CMAKE_BINARY_DIR}/packaging/${LBA2_DESKTOP_ID}.icns")
    set(_LBA2_ICNS_ICONSET "${CMAKE_BINARY_DIR}/packaging/${LBA2_DESKTOP_ID}.iconset")
    add_custom_command(
        OUTPUT ${_LBA2_ICNS_OUT}
        COMMAND ${CMAKE_COMMAND} -E make_directory ${_LBA2_ICNS_ICONSET}
        COMMAND sips -z 16 16     ${_LBA2_ICNS_PNG} --out ${_LBA2_ICNS_ICONSET}/icon_16x16.png       > /dev/null
        COMMAND sips -z 32 32     ${_LBA2_ICNS_PNG} --out ${_LBA2_ICNS_ICONSET}/icon_16x16@2x.png    > /dev/null
        COMMAND sips -z 32 32     ${_LBA2_ICNS_PNG} --out ${_LBA2_ICNS_ICONSET}/icon_32x32.png       > /dev/null
        COMMAND sips -z 64 64     ${_LBA2_ICNS_PNG} --out ${_LBA2_ICNS_ICONSET}/icon_32x32@2x.png    > /dev/null
        COMMAND sips -z 128 128   ${_LBA2_ICNS_PNG} --out ${_LBA2_ICNS_ICONSET}/icon_128x128.png     > /dev/null
        COMMAND sips -z 256 256   ${_LBA2_ICNS_PNG} --out ${_LBA2_ICNS_ICONSET}/icon_128x128@2x.png  > /dev/null
        COMMAND sips -z 256 256   ${_LBA2_ICNS_PNG} --out ${_LBA2_ICNS_ICONSET}/icon_256x256.png     > /dev/null
        COMMAND sips -z 512 512   ${_LBA2_ICNS_PNG} --out ${_LBA2_ICNS_ICONSET}/icon_256x256@2x.png  > /dev/null
        COMMAND sips -z 512 512   ${_LBA2_ICNS_PNG} --out ${_LBA2_ICNS_ICONSET}/icon_512x512.png     > /dev/null
        COMMAND sips -z 1024 1024 ${_LBA2_ICNS_PNG} --out ${_LBA2_ICNS_ICONSET}/icon_512x512@2x.png  > /dev/null
        COMMAND iconutil --convert icns ${_LBA2_ICNS_ICONSET} --output ${_LBA2_ICNS_OUT}
        DEPENDS ${_LBA2_ICNS_PNG}
        COMMENT "Generating ${LBA2_DESKTOP_ID}.icns from ${LBA2_DESKTOP_ID}.png"
        VERBATIM)
    add_custom_target(lba2_icns ALL DEPENDS ${_LBA2_ICNS_OUT})
endif()

# Process the targets
add_subdirectory(LIB386)
add_subdirectory(SOURCES)
add_subdirectory(tools)

if(LBA2_BUILD_TESTS)
    enable_testing()
    add_subdirectory(tests)
endif()
