cmake_minimum_required(VERSION 3.31)
cmake_policy(SET CMP0091 NEW)
cmake_policy(SET CMP0114 NEW)
if(POLICY CMP0135)
    cmake_policy(SET CMP0135 NEW)
endif()

file(READ "lib/tlRender/Core/Version.h" VERSION_H)
string(REGEX MATCH "VERSION_MAJOR ([0-9]*)" _ ${VERSION_H})
set(TLRENDER_VERSION_MAJOR ${CMAKE_MATCH_1})
string(REGEX MATCH "VERSION_MINOR ([0-9]*)" _ ${VERSION_H})
set(TLRENDER_VERSION_MINOR ${CMAKE_MATCH_1})
string(REGEX MATCH "VERSION_PATCH ([0-9]*)" _ ${VERSION_H})
set(TLRENDER_VERSION_PATCH ${CMAKE_MATCH_1})
string(REGEX MATCH "VERSION_DEV \"([0-9a-z.-]*)\"" _ ${VERSION_H})
set(TLRENDER_VERSION_DEV ${CMAKE_MATCH_1})
# Composed here rather than read: the header builds it from the macros
# above, so there is no literal in the file to match. Keep this in step
# with the way the header spells it.
set(TLRENDER_VERSION_FULL
    "${TLRENDER_VERSION_MAJOR}.${TLRENDER_VERSION_MINOR}.${TLRENDER_VERSION_PATCH}${TLRENDER_VERSION_DEV}")

project(
    tlRender
    VERSION ${TLRENDER_VERSION_MAJOR}.${TLRENDER_VERSION_MINOR}.${TLRENDER_VERSION_PATCH}
    DESCRIPTION "tlRender is an open source library for building playback and review applications for visual effects, film, and animation"
    HOMEPAGE_URL "https://github.com/grizzlypeak3d/tlRender"
    LANGUAGES CXX C)

# A Python wheel build: scikit-build-core sets SKBUILD. The wheel settings
# are read before the options below, the way "cmake -C" would read them, so
# they win; the dependencies are built here too, since pip runs one CMake
# project and nothing before it.
if(SKBUILD)
    include(etc/Config/wheel.cmake)
    include(etc/Python/tlWheelDeps.cmake)
endif()

#-------------------------------------------------------------------------------
# Build options

set(TLRENDER_OCIO ON CACHE BOOL "Enable support for OpenColorIO")
set(TLRENDER_EXR ON CACHE BOOL "Enable support for EXR I/O")
set(TLRENDER_FFMPEG ON CACHE BOOL "Enable support for FFmpeg (required for audio)")
set(TLRENDER_FFMPEG_PLUGIN ON CACHE BOOL "Enable support for FFmpeg I/O")
set(TLRENDER_OIIO ON CACHE BOOL "Enable support for OpenImageIO")
set(TLRENDER_SVG ON CACHE BOOL "Enable support for SVG I/O")
set(TLRENDER_USD OFF CACHE BOOL "Enable support for USD")
set(TLRENDER_PYTHON OFF CACHE BOOL "Enable support for Python")
# Where the tlrender package goes, relative to the install prefix. The
# default keeps "PYTHONPATH=<prefix>/lib" working; a wheel puts the
# package at its root instead.
set(TLRENDER_PYTHON_INSTALL_DIR "lib/tlrender" CACHE STRING "Python package install directory")
# feather-tk built as part of this project from deps/ftk, or an installed
# one found with find_package() -- which is what a wheel does, so that
# tlrender loads the libraries in the feather-tk wheel rather than copies.
set(TLRENDER_FTK_PACKAGE OFF CACHE BOOL "Use an installed feather-tk rather than deps/ftk")
# Where FFmpeg was installed; the super build puts it in the install prefix.
set(TLRENDER_FFMPEG_PREFIX "${CMAKE_INSTALL_PREFIX}" CACHE PATH "FFmpeg install prefix")
set(TLRENDER_PROGRAMS ON CACHE BOOL "Build programs")
set(TLRENDER_EXAMPLES ON CACHE BOOL "Build examples")
set(TLRENDER_TESTS ON CACHE BOOL "Build tests")
set(TLRENDER_TESTS_NO_GL OFF CACHE BOOL "Run only the tests that do not need OpenGL")
if(APPLE)
    set(TLRENDER_IGNORE_PREFIX_PATH_DEFAULT /opt/homebrew)
endif()
set(TLRENDER_IGNORE_PREFIX_PATH ${TLRENDER_IGNORE_PREFIX_PATH_DEFAULT} CACHE STRING "Ignore the given prefix path")
set(TLRENDER_GCOV OFF CACHE BOOL "Enable gcov code coverage")
set(TLRENDER_GPROF OFF CACHE BOOL "Enable gprof code profiling")
set(TLRENDER_SANITIZE "" CACHE STRING "Enable sanitizers (comma-separated, e.g. address,undefined)")

#-------------------------------------------------------------------------------
# Internal configuration

list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/Modules)

if(NOT CMAKE_CXX_STANDARD)
    set(CMAKE_CXX_STANDARD 20)
endif()

if(NOT BUILD_SHARED_LIBS)
    set(BUILD_SHARED_LIBS OFF)
endif()

if(NOT CMAKE_POSITION_INDEPENDENT_CODE)
    set(CMAKE_POSITION_INDEPENDENT_CODE ON)
endif()

if(TLRENDER_IGNORE_PREFIX_PATH)
    set(CMAKE_IGNORE_PREFIX_PATH ${TLRENDER_IGNORE_PREFIX_PATH})
endif()

if(TLRENDER_TESTS)
    set(CTEST_OUTPUT_ON_FAILURE ON)
    enable_testing()
endif()

if(TLRENDER_GPROF)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pg")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pg")
    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pg")
endif()
if(TLRENDER_SANITIZE)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=${TLRENDER_SANITIZE} -fno-omit-frame-pointer")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=${TLRENDER_SANITIZE} -fno-omit-frame-pointer")
    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=${TLRENDER_SANITIZE}")
    set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fsanitize=${TLRENDER_SANITIZE}")
endif()

if(TLRENDER_GCOV)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --coverage -fprofile-update=atomic")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --coverage -fprofile-update=atomic")
    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} --coverage -fprofile-update=atomic")
endif()

if(MSVC)
    set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded$<$<CONFIG:Debug>:Debug>DLL)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /MP")
endif()

if(APPLE)
    set(CMAKE_FIND_FRAMEWORK LAST)
endif()

if(WIN32)
elseif(APPLE)
    # @loader_path rather than @executable_path, so that the libraries have
    # an rpath of their own as well as the executables: the loading chain's
    # rpaths usually cover a library, but not one loaded by itself, and the
    # wheel repair tool checks each library that way.
    set(CMAKE_INSTALL_RPATH "@loader_path/../lib")
    # The freshly built libraries have to come before the installed
    # copies, or a binary run from the build tree quietly loads the
    # stale install -- so they are gathered into one directory that
    # leads the search path. The install prefix entry cannot simply be
    # dropped: CMake adds it back for the prebuilt dependencies, and
    # after the build tree's own directories only because they are
    # listed here first.
    set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
    set(CMAKE_BUILD_RPATH
        "${CMAKE_BINARY_DIR}/lib"
        "${CMAKE_INSTALL_PREFIX}/lib")
else()
    set(CMAKE_INSTALL_RPATH "$ORIGIN/../lib")
endif()
# The rest of an rpath, relative to <prefix>/lib: a wheel names feather-tk's
# libraries in the feather_tk package beside it.
if(TLRENDER_INSTALL_RPATH_EXTRA)
    if(APPLE)
        list(APPEND CMAKE_INSTALL_RPATH "@loader_path/${TLRENDER_INSTALL_RPATH_EXTRA}")
    elseif(UNIX)
        list(APPEND CMAKE_INSTALL_RPATH "$ORIGIN/${TLRENDER_INSTALL_RPATH_EXTRA}")
    endif()
endif()

set_property(GLOBAL PROPERTY USE_FOLDERS ON)

#-------------------------------------------------------------------------------
# Dependencies

# Base dependencies
find_package(ZLIB REQUIRED)
find_package(Imath REQUIRED)
find_package(nlohmann_json REQUIRED)
find_package(minizip-ng REQUIRED)
find_package(OpenTimelineIO REQUIRED)

# OpenColorIO dependencies
if(TLRENDER_OCIO)
    find_package(OpenColorIO REQUIRED)
endif()

# I/O dependencies
if(TLRENDER_EXR)
    find_package(OpenEXR REQUIRED)
endif()
if(TLRENDER_FFMPEG)
    if(WIN32)
        set(FFmpeg_FOUND TRUE)
        add_library(FFmpeg::avutil STATIC IMPORTED)
        set_property(TARGET FFmpeg::avutil PROPERTY
             IMPORTED_LOCATION "${TLRENDER_FFMPEG_PREFIX}/lib/avutil.lib")
        add_library(FFmpeg::avdevice STATIC IMPORTED)
        set_property(TARGET FFmpeg::avdevice PROPERTY
             IMPORTED_LOCATION "${TLRENDER_FFMPEG_PREFIX}/lib/avdevice.lib")
        add_library(FFmpeg::avformat STATIC IMPORTED)
        set_property(TARGET FFmpeg::avformat PROPERTY
             IMPORTED_LOCATION "${TLRENDER_FFMPEG_PREFIX}/lib/avformat.lib")
        add_library(FFmpeg::avcodec STATIC IMPORTED)
        set_property(TARGET FFmpeg::avcodec PROPERTY
             IMPORTED_LOCATION "${TLRENDER_FFMPEG_PREFIX}/lib/avcodec.lib")
        add_library(FFmpeg::swresample STATIC IMPORTED)
        set_property(TARGET FFmpeg::swresample PROPERTY
             IMPORTED_LOCATION "${TLRENDER_FFMPEG_PREFIX}/lib/swresample.lib")
        add_library(FFmpeg::swscale STATIC IMPORTED)
        set_property(TARGET FFmpeg::swscale PROPERTY
             IMPORTED_LOCATION "${TLRENDER_FFMPEG_PREFIX}/lib/swscale.lib")
        add_library(FFmpeg::FFmpeg INTERFACE IMPORTED)
        set_property(TARGET FFmpeg::FFmpeg PROPERTY
            INTERFACE_LINK_LIBRARIES
            FFmpeg::avdevice
            FFmpeg::avformat
            FFmpeg::avcodec
            FFmpeg::swresample
            FFmpeg::swscale
            FFmpeg::avutil)
    elseif(APPLE)
        set(FFmpeg_FOUND TRUE)
        add_library(FFmpeg::avdevice STATIC IMPORTED)
        set_property(TARGET FFmpeg::avdevice PROPERTY
             IMPORTED_LOCATION "${TLRENDER_FFMPEG_PREFIX}/lib/libavdevice.dylib")
        add_library(FFmpeg::avformat STATIC IMPORTED)
        set_property(TARGET FFmpeg::avformat PROPERTY
             IMPORTED_LOCATION "${TLRENDER_FFMPEG_PREFIX}/lib/libavformat.dylib")
        add_library(FFmpeg::avcodec STATIC IMPORTED)
        set_property(TARGET FFmpeg::avcodec PROPERTY
             IMPORTED_LOCATION "${TLRENDER_FFMPEG_PREFIX}/lib/libavcodec.dylib")
        add_library(FFmpeg::swresample STATIC IMPORTED)
        set_property(TARGET FFmpeg::swresample PROPERTY
             IMPORTED_LOCATION "${TLRENDER_FFMPEG_PREFIX}/lib/libswresample.dylib")
        add_library(FFmpeg::swscale STATIC IMPORTED)
        set_property(TARGET FFmpeg::swscale PROPERTY
             IMPORTED_LOCATION "${TLRENDER_FFMPEG_PREFIX}/lib/libswscale.dylib")
        add_library(FFmpeg::avutil STATIC IMPORTED)
        set_property(TARGET FFmpeg::avutil PROPERTY
             IMPORTED_LOCATION "${TLRENDER_FFMPEG_PREFIX}/lib/libavutil.dylib")
        add_library(FFmpeg::FFmpeg INTERFACE IMPORTED)
        set_property(TARGET FFmpeg::FFmpeg PROPERTY
            INTERFACE_LINK_LIBRARIES
            FFmpeg::avdevice
            FFmpeg::avformat
            FFmpeg::avcodec
            FFmpeg::swresample
            FFmpeg::swscale
            FFmpeg::avutil)
    elseif(EMSCRIPTEN)
        # Only the libraries Core uses: the I/O plugin is not built for
        # the web, and neither is the rest of FFmpeg.
        set(FFmpeg_FOUND TRUE)
        add_library(FFmpeg::avutil STATIC IMPORTED)
        set_property(TARGET FFmpeg::avutil PROPERTY
             IMPORTED_LOCATION "${TLRENDER_FFMPEG_PREFIX}/lib/libavutil.a")
        add_library(FFmpeg::swresample STATIC IMPORTED)
        set_property(TARGET FFmpeg::swresample PROPERTY
             IMPORTED_LOCATION "${TLRENDER_FFMPEG_PREFIX}/lib/libswresample.a")
        add_library(FFmpeg::swscale STATIC IMPORTED)
        set_property(TARGET FFmpeg::swscale PROPERTY
             IMPORTED_LOCATION "${TLRENDER_FFMPEG_PREFIX}/lib/libswscale.a")
    else()
        find_package(PkgConfig REQUIRED)
        pkg_check_modules(
            swresample REQUIRED IMPORTED_TARGET
            libswresample)
        pkg_check_modules(
            swscale REQUIRED IMPORTED_TARGET
            libswscale)
        pkg_check_modules(
            avutil REQUIRED IMPORTED_TARGET
            libavutil)
        pkg_check_modules(
            FFmpeg REQUIRED IMPORTED_TARGET
            libavdevice
            libavformat
            libavcodec
            libswresample
            libswscale
            libavutil)
        add_library(FFmpeg::FFmpeg ALIAS PkgConfig::FFmpeg)
        add_library(FFmpeg::swresample ALIAS PkgConfig::swresample)
        add_library(FFmpeg::swscale ALIAS PkgConfig::swscale)
        add_library(FFmpeg::avutil ALIAS PkgConfig::avutil)
    endif()
endif()
if(TLRENDER_FFMPEG_PLUGIN)
    # The command line reader's subprocess.h is a single header with no
    # CMake configuration: the super build copies it into the install
    # prefix, a system build into a prefix on the search path.
    find_path(subprocess_INCLUDE_DIR subprocess.h REQUIRED)
endif()
if(TLRENDER_OIIO)
    find_package(OpenImageIO)
endif()
if(TLRENDER_SVG)
    # Also a dependency of ftk, which is where it comes from.
    find_package(lunasvg REQUIRED)
endif()
if(TLRENDER_USD)
    find_package(OpenGL REQUIRED)
    find_package(pxr REQUIRED)
endif()

# A distribution's package can install a CMake configuration whose include
# directories are not there: Ubuntu puts OpenColorIO's where its relative
# prefix resolves to "/", so it asks for "/include", and OpenImageIO's names
# the OpenCV headers it was built with, which its development package does
# not bring. CMake refuses to generate with them, so the directories that do
# not exist are dropped; the headers themselves are in /usr/include, which
# the compiler searches anyway.
function(tlrender_prune_include_directories TARGET)
    if(TARGET ${TARGET})
        get_target_property(DIRS ${TARGET} INTERFACE_INCLUDE_DIRECTORIES)
        if(DIRS)
            set(KEPT)
            foreach(DIR ${DIRS})
                if(DIR MATCHES "\\$<" OR EXISTS "${DIR}")
                    list(APPEND KEPT "${DIR}")
                else()
                    message(STATUS "Dropping missing include directory ${DIR} from ${TARGET}")
                endif()
            endforeach()
            set_property(TARGET ${TARGET} PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${KEPT}")
        endif()
    endif()
endfunction()
tlrender_prune_include_directories(OpenColorIO::OpenColorIO)
tlrender_prune_include_directories(OpenImageIO::OpenImageIO)

# Python dependencies
#
# The tlrender module is built the way feather-tk's module is, the stable
# ABI or not and against the same nanobind library, since nanobind shares
# types only between modules built alike and the tlrender module takes its
# types from feather_tk. So this is feather-tk's own option, declared here too because
# feather-tk is not added until below.
set(ftk_PYTHON_STABLE_ABI ON CACHE BOOL "Build the Python module against the stable ABI")
if(TLRENDER_PYTHON)
    # Development.Module rather than Development, as feather-tk asks: an
    # extension module does not link libpython.
    set(TLRENDER_PYTHON_COMPONENTS Interpreter Development.Module)
    set(TLRENDER_PYTHON_VERSION 3.10)
    set(TLRENDER_NANOBIND_LIBRARY nanobind-static)
    if(ftk_PYTHON_STABLE_ABI)
        # nanobind supports the stable ABI from Python 3.12.
        list(APPEND TLRENDER_PYTHON_COMPONENTS Development.SABIModule)
        set(TLRENDER_PYTHON_VERSION 3.12)
        set(TLRENDER_NANOBIND_LIBRARY nanobind-static-abi3)
    endif()
    find_package(Python ${TLRENDER_PYTHON_VERSION} REQUIRED COMPONENTS ${TLRENDER_PYTHON_COMPONENTS})
    find_package(nanobind REQUIRED CONFIG)
endif()

#-------------------------------------------------------------------------------
# feather-tk

if(TLRENDER_FTK_PACKAGE)
    find_package(ftk REQUIRED)
    # The graphics API is feather-tk's option, which an installed package
    # does not carry; the wheels are OpenGL 4.1.
    if(NOT ftk_API)
        set(ftk_API "GL_4_1")
    endif()
    # The resource tool is the package's imported target; the name
    # ftk_icon_resources() falls back on is the one inside feather-tk's
    # own tree.
    set(ftk_RESOURCE_COMMAND ftk::ftk-resource)
    if(TLRENDER_PYTHON)
        # feather-tk builds this library when it is added below; an
        # installed one leaves it to us. Built the same way, since the
        # binding libraries are compiled into the module against it.
        nanobind_build_library(${TLRENDER_NANOBIND_LIBRARY})
        if(ftk_PYTHON_STABLE_ABI)
            target_compile_definitions(${TLRENDER_NANOBIND_LIBRARY} PUBLIC Py_LIMITED_API=0x030C0000)
        endif()
    endif()
else()
    find_package(Git REQUIRED)
    if(NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/deps/ftk/CMakeLists.txt")
        execute_process(
            COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive
            WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
            RESULT_VARIABLE GIT_SUBMODULE_RESULT)
        if(NOT GIT_SUBMODULE_RESULT EQUAL 0)
            message(FATAL_ERROR "git submodule update failed with ${GIT_SUBMODULE_RESULT}")
        endif()
    endif()

    add_subdirectory(deps/ftk)
    add_library(ftk::ftkResource ALIAS ftkResource)
    add_library(ftk::ftkCore ALIAS ftkCore)
    add_library(ftk::ftkGL ALIAS ftkGL)
    add_library(ftk::ftkUI ALIAS ftkUI)
    add_library(ftk::ftkTestLib ALIAS ftkTestLib)
endif()

#-------------------------------------------------------------------------------
# Sub-directories

add_subdirectory(lib/tlRender)
if(TLRENDER_PROGRAMS)
    add_subdirectory(bin)
endif()
if(TLRENDER_TESTS)
    add_subdirectory(tests)
endif()
if(TLRENDER_EXAMPLES)
    add_subdirectory(examples)
endif()
add_subdirectory(etc/Legal)

include(CMakePackageConfigHelpers)
set(INCLUDE_INSTALL_DIR include/tlRender)
configure_package_config_file(
    tlRenderConfig.cmake.in
    ${CMAKE_CURRENT_BINARY_DIR}/tlRenderConfig.cmake
    INSTALL_DESTINATION lib/cmake/tlRender
    PATH_VARS INCLUDE_INSTALL_DIR)
install(
    FILES ${CMAKE_CURRENT_BINARY_DIR}/tlRenderConfig.cmake
    DESTINATION lib/cmake/tlRender
    COMPONENT dev)
