## Copyright 2009-2021 Intel Corporation
## SPDX-License-Identifier: Apache-2.0

CMAKE_MINIMUM_REQUIRED(VERSION 3.5)

SET(EMBREE_VERSION_MAJOR 4)
SET(EMBREE_VERSION_MINOR 3)
SET(EMBREE_VERSION_PATCH 3)
SET(EMBREE_VERSION_NOTE "")

SET(EMBREE_VERSION ${EMBREE_VERSION_MAJOR}.${EMBREE_VERSION_MINOR}.${EMBREE_VERSION_PATCH})
MATH(EXPR EMBREE_VERSION_NUMBER "10000*${EMBREE_VERSION_MAJOR} + 100*${EMBREE_VERSION_MINOR} + ${EMBREE_VERSION_PATCH}")
SET(CPACK_RPM_PACKAGE_RELEASE 1)

PROJECT(embree${EMBREE_VERSION_MAJOR})
SET(EMBREE_PROJECT_COMPILATION ON)

include(CMakeDependentOption)

# We use our own strip tool on macOS to sign during install. This is required as CMake modifies RPATH of the binary during install.
IF (APPLE AND EMBREE_SIGN_FILE)
  SET(EMBREE_STRIP ${CMAKE_STRIP})
  SET(CMAKE_STRIP "${PROJECT_BINARY_DIR}/post_install_target.sh")
  CONFIGURE_FILE(scripts/post_install_target.sh.in "${PROJECT_BINARY_DIR}/post_install_target.sh" @ONLY)
ENDIF()

MACRO (SIGN_TARGET target)
  IF (EMBREE_SIGN_FILE)
    IF (WIN32)
      # on Windows we sign and do not strip as debug symbols not included in binary
      ADD_CUSTOM_COMMAND(TARGET ${target} POST_BUILD
        COMMAND ${EMBREE_SIGN_FILE} $<TARGET_FILE:${target}>)
    ELSEIF (APPLE)
      # on MacOSX we strip and sign here for testing purposes but also during install, as CMake modifies binary during install
      ADD_CUSTOM_COMMAND(TARGET ${target} POST_BUILD
        COMMAND ${EMBREE_STRIP} -x $<TARGET_FILE:${target}>
        COMMAND ${EMBREE_SIGN_FILE} -o runtime -e "${CMAKE_SOURCE_DIR}/common/cmake/embree.entitlements" $<TARGET_FILE:${target}>)
    ELSE()
      # on Linux signing of binaries is not supported and stripping is done during install
    ENDIF()
  ENDIF()
ENDMACRO()

# find git version
IF(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.git")
  FIND_PACKAGE(Git)
  IF(GIT_FOUND)
    EXECUTE_PROCESS(
      COMMAND ${GIT_EXECUTABLE} rev-parse HEAD
      WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
      OUTPUT_VARIABLE "EMBREE_HASH"
      ERROR_QUIET
      OUTPUT_STRIP_TRAILING_WHITESPACE)
  ELSE()
    SET(EMBREE_HASH 0)
  ENDIF()
ENDIF()

IF(COMMAND cmake_policy)
  if (POLICY CMP0003)
    cmake_policy(SET CMP0003 NEW)
  endif()
  if (POLICY CMP0042)
    cmake_policy(SET CMP0042 NEW)
  endif()
  if(POLICY CMP0072)
    cmake_policy(SET CMP0072 NEW)
  endif()
  if(POLICY CMP0022)
    cmake_policy(SET CMP0022 NEW)
  endif()
  if(POLICY CMP0074)
    cmake_policy(SET CMP0074 NEW)
  endif()
  if(POLICY CMP0135)
    cmake_policy(SET CMP0135 NEW)
  endif()
  if(POLICY CMP0057)
    cmake_policy(SET CMP0057 NEW)
  endif()
ENDIF()

MARK_AS_ADVANCED(CMAKE_BACKWARDS_COMPATIBILITY)
MARK_AS_ADVANCED(EXECUTABLE_OUTPUT_PATH)
MARK_AS_ADVANCED(LIBRARY_OUTPUT_PATH)

MARK_AS_ADVANCED(CMAKE_OSX_ARCHITECTURES)
MARK_AS_ADVANCED(CMAKE_OSX_DEPLOYMENT_TARGET)
MARK_AS_ADVANCED(CMAKE_OSX_SYSROOT)
MARK_AS_ADVANCED(CLEAR CMAKE_CXX_COMPILER)

SET(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/common/cmake" ${CMAKE_MODULE_PATH})

INCLUDE(test)

set(BUILD_DOC OFF CACHE INTERNAL "build documentation (internal only)")
IF (BUILD_DOC)
  ADD_SUBDIRECTORY(doc)
ENDIF()

OPTION(EMBREE_TUTORIALS    "Enable to build Embree tutorials" ON)

##############################################################
# Embree configuration
##############################################################

GET_PROPERTY(SHARED_LIBS_SUPPORTED GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS)
IF(SHARED_LIBS_SUPPORTED)
  OPTION(EMBREE_STATIC_LIB "Build Embree as a static library.")
  MARK_AS_ADVANCED(CLEAR EMBREE_STATIC_LIB)
ELSE()
  SET(EMBREE_STATIC_LIB ON CACHE BOOL "Build Embree as a static library." FORCE)
  MARK_AS_ADVANCED(EMBREE_STATIC_LIB)
ENDIF()
IF (EMBREE_STATIC_LIB)
  SET(EMBREE_LIB_TYPE STATIC)
  ADD_DEFINITIONS(-DEMBREE_STATIC_LIB)
ELSE()
  SET(EMBREE_LIB_TYPE SHARED)
ENDIF()

OPTION(EMBREE_ISPC_SUPPORT "Build Embree with support for ISPC applications." OFF)
IF (EMSCRIPTEN)
  SET(EMBREE_ISPC_SUPPORT OFF CACHE BOOL "Build Embree with support for ISPC applications." FORCE)
ENDIF()

SET(EMBREE_API_NAMESPACE "" CACHE STRING "C++ namespace to put API symbols into.")
SET(EMBREE_LIBRARY_NAME  "embree${EMBREE_VERSION_MAJOR}" CACHE STRING "Name of the embree library file (default is embree${EMBREE_VERSION_MAJOR})")

IF (EMBREE_API_NAMESPACE AND EMBREE_ISPC_SUPPORT)
   MESSAGE(FATAL_ERROR "You cannot enable ISPC when EMBREE_API_NAMESPACE is used.")
ENDIF()

##############################################################################
# Configurations (add configurations also to common/cmake/embree-config.cmake)

OPTION(EMBREE_ZIP_MODE "Create Embree ZIP package" ON)
MARK_AS_ADVANCED(EMBREE_ZIP_MODE)

OPTION(EMBREE_INSTALL_DEPENDENCIES "Install Embree dependencies in binary packages and install" OFF)
MARK_AS_ADVANCED(EMBREE_INSTALL_DEPENDENCIES)

OPTION(EMBREE_STAT_COUNTERS "Enables statistic counters.")
OPTION(EMBREE_STACK_PROTECTOR "When enabled Embree compiles with stack protection against return address overrides." OFF)

IF (NOT APPLE)
  OPTION(EMBREE_SYCL_SUPPORT "Enables SYCL GPU support." OFF)
ENDIF()
CMAKE_DEPENDENT_OPTION(EMBREE_SYCL_LARGEGRF "Enables SYCL large GRF support." OFF "EMBREE_SYCL_SUPPORT" OFF)
CMAKE_DEPENDENT_OPTION(EMBREE_SYCL_DBG "Enables DPC++ debug info." OFF "EMBREE_SYCL_SUPPORT" OFF)
CMAKE_DEPENDENT_OPTION(EMBREE_SYCL_GEOMETRY_CALLBACK  "Enabled geometry callbacks which are disabled by default for SYCL." OFF  "EMBREE_SYCL_SUPPORT" OFF)

MARK_AS_ADVANCED(EMBREE_SYCL_LARGEGRF)
MARK_AS_ADVANCED(EMBREE_SYCL_DBG)
MARK_AS_ADVANCED(EMBREE_SYCL_GEOMETRY_CALLBACK)

IF (EMBREE_SYCL_GEOMETRY_CALLBACK)
  message(WARNING "Enabling EMBREE_SYCL_GEOMETRY_CALLBACK is experimental and may result in poor performance.")
ENDIF()

IF (EMBREE_SYCL_SUPPORT)
  ADD_DEFINITIONS("-DEMBREE_SYCL_SUPPORT")  # FIXME: only use define from rtcore_config.h
ENDIF()

CMAKE_DEPENDENT_OPTION(EMBREE_SYCL_RT_SIMULATION "Using hardware simulation" OFF "EMBREE_SYCL_SUPPORT" OFF)
MARK_AS_ADVANCED(EMBREE_SYCL_RT_SIMULATION)
IF (EMBREE_SYCL_RT_SIMULATION AND NOT EMBREE_SYCL_RT_VALIDATION_API AND EMBREE_SYCL_IMPLICIT_DISPATCH_GLOBALS)
  MESSAGE(FATAL_ERROR "Using EMBREE_SYCL_RT_SIMULATION requires EMBREE_SYCL_RT_VALIDATION_API=ON and EMBREE_SYCL_IMPLICIT_DISPATCH_GLOBALS=OFF")
ENDIF()
IF (EMBREE_SYCL_RT_SIMULATION)
  ADD_DEFINITIONS("-DEMBREE_SYCL_RT_SIMULATION")
ENDIF()

CMAKE_DEPENDENT_OPTION(EMBREE_SYCL_RT_VALIDATION_API "Use rt_validation API instead of IGC provided rt_production API" OFF "EMBREE_SYCL_SUPPORT" OFF)
IF (EMBREE_SYCL_RT_VALIDATION_API)
  ADD_DEFINITIONS("-DEMBREE_SYCL_RT_VALIDATION_API")
ENDIF()

CMAKE_DEPENDENT_OPTION(EMBREE_SYCL_IMPLICIT_DISPATCH_GLOBALS "Using L0 allocated Dispatch Globals" ON "EMBREE_SYCL_RT_VALIDATION_API" OFF)
IF (EMBREE_SYCL_RT_VALIDATION_API AND NOT EMBREE_SYCL_IMPLICIT_DISPATCH_GLOBALS)
  ADD_DEFINITIONS("-DEMBREE_SYCL_ALLOC_DISPATCH_GLOBALS")
ENDIF()

MARK_AS_ADVANCED(EMBREE_SYCL_RT_VALIDATION_API)
MARK_AS_ADVANCED(EMBREE_SYCL_IMPLICIT_DISPATCH_GLOBALS)

IF (EMBREE_SYCL_SUPPORT)
  SET(EMBREE_SYCL_AOT_DEVICES "none" CACHE STRING "SYCL devices to use for AOT compilation")
  SET_PROPERTY(CACHE EMBREE_SYCL_AOT_DEVICES PROPERTY STRINGS none dg2 pvc XE_HPG_CORE XE_HPC_CORE)
  
  SET(EMBREE_SYCL_AOT_DEVICE_REVISION 0)
  IF (EMBREE_SYCL_AOT_DEVICES STREQUAL "dg2")
    SET(EMBREE_SYCL_AOT_DEVICE_REVISION 4)  # FIXME: bug workaround should get removed
  ENDIF()
ENDIF()

CMAKE_DEPENDENT_OPTION(EMBREE_SYCL_L0_RTAS_BUILDER "Enable Level Zero RTAS builder" ON "EMBREE_SYCL_SUPPORT" OFF)
IF (EMBREE_SYCL_L0_RTAS_BUILDER)
  ADD_DEFINITIONS("-DEMBREE_SYCL_L0_RTAS_BUILDER")
ENDIF()

OPTION(EMBREE_RAY_MASK "Enables ray mask support." ON)
OPTION(EMBREE_BACKFACE_CULLING "Enables backface culling.")
OPTION(EMBREE_BACKFACE_CULLING_CURVES "Enables backface culling for curve primitives." OFF)
OPTION(EMBREE_BACKFACE_CULLING_SPHERES "Enables backface culling for sphere primitives." OFF)

OPTION(EMBREE_FILTER_FUNCTION "Enables filter functions." ON)
OPTION(EMBREE_IGNORE_INVALID_RAYS "Ignores invalid rays." OFF) # FIXME: enable by default?
OPTION(EMBREE_COMPACT_POLYS "Enables double indexed poly layout." OFF)
OPTION(EMBREE_GEOMETRY_TRIANGLE "Enables support for triangle geometries." ON)
OPTION(EMBREE_GEOMETRY_QUAD "Enables support for quad geometries." ON)
OPTION(EMBREE_GEOMETRY_CURVE "Enables support for curve geometries." ON)
OPTION(EMBREE_GEOMETRY_SUBDIVISION "Enables support for subdiv geometries." ON)
OPTION(EMBREE_GEOMETRY_USER "Enables support for user geometries." ON)
OPTION(EMBREE_GEOMETRY_INSTANCE "Enables support for instances." ON)
OPTION(EMBREE_GEOMETRY_INSTANCE_ARRAY "Enables support for instance arrays." ON)
SET(EMBREE_MAX_INSTANCE_LEVEL_COUNT 1 CACHE STRING "Maximum number of instance levels.")

IF (NOT EMBREE_GEOMETRY_INSTANCE AND NOT EMBREE_GEOMETRY_INSTANCE_ARRAY AND NOT EMBREE_MAX_INSTANCE_LEVEL_COUNT EQUAL 1)
  message(FATAL_ERROR "EMBREE_MAX_INSTANCE_LEVEL_COUNT must be 1 when EMBREE_GEOMETRY_INSTANCE and EMBREE_GEOMETRY_INSTANCE_ARRAY are disabled")
ENDIF()

OPTION(EMBREE_GEOMETRY_GRID "Enables support for grid geometries." ON)
OPTION(EMBREE_GEOMETRY_POINT "Enables support for point geometries." ON)

OPTION(EMBREE_RAY_PACKETS "Enabled support for ray packets." ON)


SET(EMBREE_CURVE_SELF_INTERSECTION_AVOIDANCE_FACTOR 2.0 CACHE STRING "Self intersection avoidance factor for flat curves. Specify floating point value in range 0 to inf.")
OPTION(EMBREE_DISC_POINT_SELF_INTERSECTION_AVOIDANCE "Enables self intersection avoidance for ray oriented discs." ON)
OPTION(EMBREE_MIN_WIDTH "Enables min-width feature to enlarge curve and point thickness to pixel width." OFF)

##############################################################
# Platform detection and defaults
##############################################################

# detect ARM compilation
IF (APPLE AND CMAKE_SYSTEM_NAME STREQUAL "Darwin" AND (CMAKE_SYSTEM_PROCESSOR STREQUAL "arm64" AND CMAKE_OSX_ARCHITECTURES STREQUAL "") OR ("arm64" IN_LIST CMAKE_OSX_ARCHITECTURES))
  MESSAGE(STATUS "Building for Apple silicon")
  SET(EMBREE_ARM ON)
ELSEIF(CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64" OR CMAKE_SYSTEM_PROCESSOR STREQUAL "ARM64")
  MESSAGE(STATUS "Building for AArch64")
  SET(EMBREE_ARM ON)
ENDIF()

SET(EMBREE_TASKING_SYSTEM "TBB" CACHE STRING "Selects tasking system")
SET(EMBREE_TBB_COMPONENT "tbb" CACHE STRING "The TBB component/library name.")

IF (WIN32)
  SET_PROPERTY(CACHE EMBREE_TASKING_SYSTEM PROPERTY STRINGS TBB INTERNAL PPL)
ELSE()
  SET_PROPERTY(CACHE EMBREE_TASKING_SYSTEM PROPERTY STRINGS TBB INTERNAL)
ENDIF()

IF (EMBREE_TASKING_SYSTEM STREQUAL "TBB")
  SET(TASKING_TBB      ON )
  SET(TASKING_INTERNAL OFF)
  SET(TASKING_PPL      OFF )
  ADD_DEFINITIONS(-DTASKING_TBB)
  LIST(APPEND ISPC_DEFINITIONS -DTASKING_TBB)
ELSEIF (EMBREE_TASKING_SYSTEM STREQUAL "PPL")
  SET(TASKING_PPL      ON )
  SET(TASKING_TBB      OFF )
  SET(TASKING_INTERNAL OFF)
  ADD_DEFINITIONS(-DTASKING_PPL)
  LIST(APPEND ISPC_DEFINITIONS -DTASKING_PPL)
ELSE()
  SET(TASKING_INTERNAL ON )
  SET(TASKING_TBB      OFF)
  SET(TASKING_PPL      OFF )
  ADD_DEFINITIONS(-DTASKING_INTERNAL)
  LIST(APPEND ISPC_DEFINITIONS -DTASKING_INTERNAL)
ENDIF()

##############################################################
# Compiler
##############################################################
# TODO: fixme, define relwithassert also for icc, msvc, ... or remove when debug build with dpcpp is useable
IF(EMBREE_SYCL_SUPPORT)
  SET(CONFIGURATION_TYPES "Debug;Release;RelWithDebInfo;RelWithAssert")
ELSE()
SET(CONFIGURATION_TYPES "Debug;Release;RelWithDebInfo")
ENDIF()

# Validate build type
IF (CMAKE_BUILD_TYPE)
  string(FIND "${CONFIGURATION_TYPES}" "${CMAKE_BUILD_TYPE}" MATCHED_CONFIG)
  IF (${MATCHED_CONFIG} EQUAL -1)
    message(FATAL_ERROR "CMAKE_BUILD_TYPE (${CMAKE_BUILD_TYPE}) allows only the following values: ${CONFIGURATION_TYPES}")
  ENDIF()
ENDIF()

message(DEBUG "CMAKE_GENERATOR_TOOLSET: ${CMAKE_GENERATOR_TOOLSET}")
message(DEBUG "CMAKE_CXX_COMPILER_ID: ${CMAKE_CXX_COMPILER_ID}")
message(DEBUG "CMAKE_CXX_COMPILER: ${CMAKE_CXX_COMPILER}")

include(CheckCXXCompilerFlag)
check_cxx_compiler_flag(-fsycl COMPILER_HAS_SYCL_SUPPORT)

IF (WIN32)
  IF (NOT DEFAULT_CMAKE_CONFIGURATION_TYPES_SET)
    SET(CMAKE_CONFIGURATION_TYPES "${CONFIGURATION_TYPES}" CACHE STRING "List of generated configurations." FORCE)
    SET(DEFAULT_CMAKE_CONFIGURATION_TYPES_SET ON CACHE INTERNAL "Default CMake configuration types set.")
  ENDIF()
  SET_PROPERTY(GLOBAL PROPERTY USE_FOLDERS ON)

  IF ((${CMAKE_CXX_COMPILER_ID} MATCHES "IntelLLVM") OR
      (${CMAKE_CXX_COMPILER_ID} MATCHES "Clang" AND COMPILER_HAS_SYCL_SUPPORT))
    MESSAGE("-- DPCPP compiler detected")
    INCLUDE(dpcpp)
  ELSEIF(${CMAKE_GENERATOR_TOOLSET} MATCHES "^LLVM")
    set(EMBREE_SYCL_SUPPORT OFF)
    MESSAGE("-- CLANG compiler detected")
    INCLUDE(clang)
  ELSEIF(${CMAKE_GENERATOR_TOOLSET} MATCHES "^Intel")
    set(EMBREE_SYCL_SUPPORT OFF)
    MESSAGE("-- Intel compiler detected")
    INCLUDE (intel)
  ELSEIF(${CMAKE_CXX_COMPILER_FRONTEND_VARIANT} MATCHES "GNU")
    set(EMBREE_SYCL_SUPPORT OFF)
    MESSAGE("-- GNU-like compiler detected")
    INCLUDE(gnu)
  ELSE()
    set(EMBREE_SYCL_SUPPORT OFF)
    IF (EMBREE_ISA_AVX512)
      MESSAGE(FATAL_ERROR "Microsoft Visual C++ Compiler does not support AVX512. Please use Intel Compiler or Clang.")
    ENDIF()
    MESSAGE("-- MSVC detected")
    INCLUDE (msvc)
  ENDIF()

ELSE (WIN32)
  IF(CMAKE_CXX_COMPILER_WRAPPER STREQUAL "CrayPrgEnv")
    INCLUDE (crayprgenv)
  ELSE()
    GET_FILENAME_COMPONENT(CXX_COMPILER_NAME ${CMAKE_CXX_COMPILER} NAME)
    
    STRING(TOLOWER "${CMAKE_CXX_COMPILER_ID}" _LOWER_CXX_COMPILER_ID)
    STRING(REPLACE "appleclang" "clang" _LOWER_CXX_COMPILER_ID ${_LOWER_CXX_COMPILER_ID})
    STRING(REPLACE "intelllvm" "dpcpp" _LOWER_CXX_COMPILER_ID ${_LOWER_CXX_COMPILER_ID})
    IF(${_LOWER_CXX_COMPILER_ID} MATCHES "clang" AND ${CXX_COMPILER_NAME} MATCHES "icpx")
      STRING(REPLACE "clang" "dpcpp" _LOWER_CXX_COMPILER_ID ${_LOWER_CXX_COMPILER_ID})
    ENDIF()
    IF(${_LOWER_CXX_COMPILER_ID} MATCHES "clang" AND ${CXX_COMPILER_NAME} MATCHES "dpcpp")
      STRING(REPLACE "clang" "dpcpp" _LOWER_CXX_COMPILER_ID ${_LOWER_CXX_COMPILER_ID})
    ENDIF()
    IF (EMBREE_SYCL_SUPPORT)
      SET(_LOWER_CXX_COMPILER_ID "dpcpp")
    ENDIF()
    STRING(TOUPPER "${_LOWER_CXX_COMPILER_ID}" _UPPER_CXX_COMPILER_ID)
    MESSAGE("-- ${_UPPER_CXX_COMPILER_ID} detected")
    INCLUDE(${_LOWER_CXX_COMPILER_ID} OPTIONAL RESULT_VARIABLE COMPILER_FOUND)
    IF (NOT COMPILER_FOUND)
      MESSAGE(FATAL_ERROR "Unsupported compiler: " ${CMAKE_CXX_COMPILER_ID})
    ENDIF ()
  ENDIF ()

  IF(NOT CMAKE_BUILD_TYPE)
    SET(CMAKE_BUILD_TYPE "Release" CACHE STRING "Specifies the build type." FORCE)
    SET_PROPERTY(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS ${CONFIGURATION_TYPES})
  ENDIF(NOT CMAKE_BUILD_TYPE)

  OPTION(CMAKE_VERBOSE_MAKEFILE "Enables verbose mode.")
  MARK_AS_ADVANCED(CLEAR CMAKE_VERBOSE_MAKEFILE)

ENDIF (WIN32)

##############################################################
# ISA configuration
##############################################################

# just for compatibility with old naming
IF(DEFINED EMBREE_ISA_AVX512SKX)
  UNSET(EMBREE_ISA_AVX512 CACHE)
  SET(EMBREE_ISA_AVX512 ${EMBREE_ISA_AVX512SKX} CACHE BOOL "")
ENDIF()

IF (CMAKE_CXX_COMPILER_WRAPPER STREQUAL "CrayPrgEnv")
  SET(EMBREE_MAX_ISA "DEFAULT" CACHE STRING "Selects highest ISA to support.")
ELSEIF (EMSCRIPTEN)
  SET(EMBREE_MAX_ISA "SSE2" CACHE STRING "Selects highest ISA to support.")
ELSE()
  SET(EMBREE_MAX_ISA "NONE" CACHE STRING "Selects highest ISA to support.")
ENDIF()

IF (EMBREE_ARM)
  SET_PROPERTY(CACHE EMBREE_MAX_ISA PROPERTY STRINGS NONE NEON NEON2X)
ELSE()  
  SET_PROPERTY(CACHE EMBREE_MAX_ISA PROPERTY STRINGS NONE SSE2 SSE4.2 AVX AVX2 AVX512 DEFAULT)
ENDIF()

IF (EMBREE_MAX_ISA STREQUAL "NONE")
  
  IF (EMBREE_ARM)
    IF (APPLE)
      OPTION(EMBREE_ISA_NEON   "Enables NEON ISA." OFF)
      OPTION(EMBREE_ISA_NEON2X "Enables NEON ISA double pumped." ON)
    ELSE()
      OPTION(EMBREE_ISA_NEON   "Enables NEON ISA." ON)
      OPTION(EMBREE_ISA_NEON2X "Enables NEON ISA double pumped." OFF)
    ENDIF()
  ELSE()
    TRY_COMPILE(COMPILER_SUPPORTS_AVX    "${CMAKE_BINARY_DIR}" "${PROJECT_SOURCE_DIR}/common/cmake/check_isa.cpp" COMPILE_DEFINITIONS ${FLAGS_AVX})
    TRY_COMPILE(COMPILER_SUPPORTS_AVX2   "${CMAKE_BINARY_DIR}" "${PROJECT_SOURCE_DIR}/common/cmake/check_isa.cpp" COMPILE_DEFINITIONS ${FLAGS_AVX2})
    TRY_COMPILE(COMPILER_SUPPORTS_AVX512 "${CMAKE_BINARY_DIR}" "${PROJECT_SOURCE_DIR}/common/cmake/check_isa.cpp" COMPILE_DEFINITIONS ${FLAGS_AVX512})
  
    OPTION(EMBREE_ISA_SSE2 "Enables SSE2 ISA." ON)
    OPTION(EMBREE_ISA_SSE42 "Enables SSE4.2 ISA." ON)
    OPTION(EMBREE_ISA_AVX "Enables AVX ISA." ${COMPILER_SUPPORTS_AVX})
    OPTION(EMBREE_ISA_AVX2 "Enables AVX2 ISA." ${COMPILER_SUPPORTS_AVX2})
    IF (WIN32 OR APPLE)
      OPTION(EMBREE_ISA_AVX512 "Enables AVX512 ISA." OFF)
    ELSE()
      OPTION(EMBREE_ISA_AVX512 "Enables AVX512 ISA." ${COMPILER_SUPPORTS_AVX512})
    ENDIF()
    # Don't use OPTION, but still set them to OFF, so that embree-config.cmake is consisten with its definitions
    SET(EMBREE_ISA_NEON   OFF)
    SET(EMBREE_ISA_NEON2X OFF)
  ENDIF()

ELSEIF (EMBREE_MAX_ISA STREQUAL "DEFAULT")
  UNSET(EMBREE_ISA_NEON CACHE)
  UNSET(EMBREE_ISA_NEON2X CACHE)
  UNSET(EMBREE_ISA_SSE2 CACHE)
  UNSET(EMBREE_ISA_SSE42 CACHE)
  UNSET(EMBREE_ISA_AVX CACHE)
  UNSET(EMBREE_ISA_AVX2 CACHE)
  UNSET(EMBREE_ISA_AVX512 CACHE)
  SET(EMBREE_ISA_NEON OFF)
  SET(EMBREE_ISA_NEON2X OFF)
  SET(EMBREE_ISA_SSE2 OFF)
  SET(EMBREE_ISA_SSE42 OFF)
  SET(EMBREE_ISA_AVX OFF)
  SET(EMBREE_ISA_AVX2 OFF)
  SET(EMBREE_ISA_AVX512 OFF)
  MESSAGE(STATUS "Detecting default ISA...")
  INCLUDE(check_isa_default)
  CHECK_ISA_DEFAULT(EMBREE_ISA_DEFAULT)
  MESSAGE(STATUS "Detected default ISA: ${EMBREE_ISA_DEFAULT}")
  SET(EMBREE_ISA_${EMBREE_ISA_DEFAULT} ON)

ELSE()
  UNSET(EMBREE_ISA_NEON CACHE)
  UNSET(EMBREE_ISA_NEON2X CACHE)
  UNSET(EMBREE_ISA_SSE2 CACHE)
  UNSET(EMBREE_ISA_SSE42 CACHE)
  UNSET(EMBREE_ISA_AVX CACHE)
  UNSET(EMBREE_ISA_AVX2 CACHE)
  UNSET(EMBREE_ISA_AVX512 CACHE)
 
  IF(EMBREE_MAX_ISA STREQUAL "NEON")
    SET(ISA  1)
  ELSEIF(EMBREE_MAX_ISA STREQUAL "NEON2X")
    SET(ISA  2)
  ELSEIF(EMBREE_MAX_ISA STREQUAL "SSE2")
    SET(ISA  1)
  ELSEIF(EMBREE_MAX_ISA STREQUAL "SSE4.2")
    SET(ISA  2)
  ELSEIF(EMBREE_MAX_ISA STREQUAL "AVX")
    SET(ISA  3)
  ELSEIF(EMBREE_MAX_ISA STREQUAL "AVX2")
    SET(ISA  4)
  ELSEIF(EMBREE_MAX_ISA STREQUAL "AVX512")
    SET(ISA 5)
  ELSEIF(EMBREE_MAX_ISA STREQUAL "AVX512SKX")  # just for compatibility
    SET(ISA 5)
  ELSE()
    MESSAGE(FATAL_ERROR "Unsupported ISA specified: " ${EMBREE_MAX_ISA})
  ENDIF()

  SET(EMBREE_ISA_NEON OFF)
  SET(EMBREE_ISA_NEON2X OFF)
  SET(EMBREE_ISA_SSE2 OFF)
  SET(EMBREE_ISA_SSE42 OFF)
  SET(EMBREE_ISA_AVX OFF)
  SET(EMBREE_ISA_AVX2 OFF)
  SET(EMBREE_ISA_AVX512 OFF)

  IF (EMBREE_ARM)
    IF (ISA GREATER 0)
      SET(EMBREE_ISA_NEON ON)
    ENDIF ()
    IF (ISA GREATER 1)
      SET(EMBREE_ISA_NEON2X ON)
    ENDIF ()
  ELSE()
    IF (ISA GREATER 0)
      SET(EMBREE_ISA_SSE2  ON)
    ENDIF ()
    IF (ISA GREATER 1)
      SET(EMBREE_ISA_SSE42  ON)
    ENDIF ()
    IF (ISA GREATER 2)
      SET(EMBREE_ISA_AVX  ON)
    ENDIF ()
    IF (ISA GREATER 3)
      SET(EMBREE_ISA_AVX2  ON)
    ENDIF ()
    IF (ISA GREATER 4)
      SET(EMBREE_ISA_AVX512  ON)
    ENDIF ()
  ENDIF()
ENDIF()

IF(CMAKE_CXX_COMPILER_WRAPPER STREQUAL "CrayPrgEnv")
  SET(EMBREE_ISA_SSE42 OFF)
ENDIF()

IF (APPLE AND EMBREE_STATIC_LIB)

  # count number of set ISAs
  SET(NUMISA 0)
  IF (EMBREE_ISA_NEON)
    MATH(EXPR NUMISA "${NUMISA}+1")
  ENDIF()
  IF (EMBREE_ISA_NEON2X)
    MATH(EXPR NUMISA "${NUMISA}+1")
  ENDIF()
  IF (EMBREE_ISA_SSE2)
    MATH(EXPR NUMISA "${NUMISA}+1")
  ENDIF()
  IF (EMBREE_ISA_SSE42)
    MATH(EXPR NUMISA "${NUMISA}+1")
  ENDIF()
  IF (EMBREE_ISA_AVX)
    MATH(EXPR NUMISA "${NUMISA}+1")
  ENDIF()
  IF (EMBREE_ISA_AVX2)
    MATH(EXPR NUMISA "${NUMISA}+1")
  ENDIF()
  IF (EMBREE_ISA_AVX512)
    MATH(EXPR NUMISA "${NUMISA}+1")
  ENDIF()

  IF (NUMISA GREATER 1)
    IF (${CMAKE_CXX_COMPILER_ID} MATCHES "Clang")
      IF (${CMAKE_CXX_COMPILER_VERSION} VERSION_GREATER "9.0.0" OR ${CMAKE_CXX_COMPILER_VERSION} VERSION_EQUAL "9.0.0")
        MESSAGE(FATAL_ERROR "Using Embree as static library is not supported with AppleClang >= 9.0 when multiple ISAs are selected. Please either build a shared library or enable only one ISA.")
      ENDIF()
    ENDIF()
  ENDIF()
ENDIF()

##############################################################
# ISA configuration continued
##############################################################

SET(SSE2 0)
SET(SSE42 1)
SET(AVX 2)
SET(AVX2 3)
SET(AVX512 4)

UNSET(FLAGS_LOWEST)
SET(ISA_LOWEST -1)
SET(ISA_LOWEST_AVX 2)

IF (EMBREE_ARM)
  IF (EMBREE_ISA_NEON2X)
    LIST(APPEND ISPC_TARGETS "neon-i32x8")
  ELSEIF (EMBREE_ISA_NEON)
    LIST(APPEND ISPC_TARGETS "neon-i32x4")
  ENDIF()
ENDIF()

IF (EMBREE_ISA_NEON)
  SET(EMBREE_ISA_SSE2 ON)
ENDIF()

IF (EMBREE_ISA_NEON2X)
  SET(EMBREE_ISA_SSE2 OFF)
  SET(EMBREE_ISA_SSE42 OFF)
  SET(EMBREE_ISA_AVX OFF)
  SET(EMBREE_ISA_AVX2 ON)
ENDIF()

IF (EMBREE_ISA_SSE2)
  ADD_DEFINITIONS(-DEMBREE_TARGET_SSE2)
  IF (NOT EMBREE_ARM)
    LIST(APPEND ISPC_TARGETS "sse2")
  ENDIF()
  IF(NOT FLAGS_LOWEST)
    SET(ISA_LOWEST ${SSE2})
    SET(FLAGS_LOWEST ${FLAGS_SSE2})
  ENDIF()
ENDIF()

IF (EMBREE_ISA_SSE42)
  ADD_DEFINITIONS(-DEMBREE_TARGET_SSE42)
  IF (NOT EMBREE_ARM)
    LIST(APPEND ISPC_TARGETS "sse4")
  ENDIF()
  IF(NOT FLAGS_LOWEST)
    SET(ISA_LOWEST ${SSE42})
    SET(FLAGS_LOWEST ${FLAGS_SSE42})
  ENDIF()
ENDIF ()

IF (EMBREE_ISA_AVX)
  ADD_DEFINITIONS(-DEMBREE_TARGET_AVX)
  IF (NOT EMBREE_ARM)
    LIST(APPEND ISPC_TARGETS "avx")
  ENDIF()
  IF(NOT FLAGS_LOWEST)
    SET(ISA_LOWEST ${AVX})
    SET(ISA_LOWEST_AVX ${AVX})
    SET(FLAGS_LOWEST ${FLAGS_AVX})
  ENDIF()
ENDIF ()

IF (EMBREE_ISA_AVX2)
  ADD_DEFINITIONS(-DEMBREE_TARGET_AVX2)
  IF (NOT EMBREE_ARM)
    LIST(APPEND ISPC_TARGETS "avx2")
  ENDIF()
  IF(NOT FLAGS_LOWEST)
    SET(ISA_LOWEST ${AVX2})
    SET(ISA_LOWEST_AVX ${AVX2})
    SET(FLAGS_LOWEST ${FLAGS_AVX2})
  ENDIF()
ENDIF ()

IF (EMBREE_ISA_AVX512)
  ADD_DEFINITIONS(-DEMBREE_TARGET_AVX512)
  IF (NOT EMBREE_ARM)
    LIST(APPEND ISPC_TARGETS "avx512skx-i32x16")
  ENDIF()
  IF(NOT FLAGS_LOWEST)
    SET(ISA_LOWEST ${AVX512})
    SET(ISA_LOWEST_AVX ${AVX512})
    SET(FLAGS_LOWEST ${FLAGS_AVX512})
  ENDIF()
ENDIF ()

IF (ISA_LOWEST EQUAL -1)
  MESSAGE(FATAL_ERROR "You have to enable at least one ISA!")
ENDIF()

INCLUDE (ispc)

##############################################################
# Create Binary Packages (uses above config options)
##############################################################
include(package)

##############################################################
# Create Config files
##############################################################

CONFIGURE_FILE(
  "${PROJECT_SOURCE_DIR}/kernels/config.h.in"
  "${PROJECT_SOURCE_DIR}/kernels/config.h"
  )

INCLUDE_DIRECTORIES(${PROJECT_BINARY_DIR})

CONFIGURE_FILE(
  "${PROJECT_SOURCE_DIR}/kernels/rtcore_config.h.in"
  "${PROJECT_SOURCE_DIR}/include/embree4/rtcore_config.h"
)

CONFIGURE_FILE(
  "${PROJECT_SOURCE_DIR}/kernels/hash.h.in"
  "${PROJECT_SOURCE_DIR}/kernels/hash.h"
)
CONFIGURE_FILE(
  "${PROJECT_SOURCE_DIR}/kernels/export.linux.map.in"
  "${PROJECT_SOURCE_DIR}/kernels/export.linux.map"
)
CONFIGURE_FILE(
  "${PROJECT_SOURCE_DIR}/kernels/export.macosx.map.in"
  "${PROJECT_SOURCE_DIR}/kernels/export.macosx.map"
)


##############################################################
# Output paths
##############################################################
SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}")
SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}")
SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}")

##############################################################
# Directories to compile
##############################################################

ADD_SUBDIRECTORY(common)
ADD_SUBDIRECTORY(kernels)
ADD_SUBDIRECTORY(tests)

IF (EMBREE_TUTORIALS)
  ADD_SUBDIRECTORY(tutorials)
ENDIF()

##############################################################
# Uninstall
##############################################################

IF (NOT TARGET uninstall)
  configure_file(
      "${CMAKE_CURRENT_SOURCE_DIR}/common/cmake/uninstall.cmake.in"
      "${CMAKE_CURRENT_BINARY_DIR}/uninstall.cmake"
      IMMEDIATE @ONLY)

  add_custom_target(uninstall
      COMMAND ${CMAKE_COMMAND} -P "${CMAKE_CURRENT_BINARY_DIR}/uninstall.cmake")

  SET_PROPERTY(TARGET uninstall PROPERTY FOLDER CMakePredefinedTargets)
ENDIF()

##############################################################
# Has to be last
##############################################################

INCLUDE(CPack)
