# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=embree3
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=3.13.5
pkgrel=2
pkgdesc="High Performance Ray Tracing Kernels Intel Corporation (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://www.embree.org/"
license=("spdx:Apache-2.0")
depends=("${MINGW_PACKAGE_PREFIX}-cc-libs"
         "${MINGW_PACKAGE_PREFIX}-tbb")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=(https://github.com/embree/embree/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz
        001-build-fixes.patch
        https://github.com/embree/embree/pull/412.patch
        002-arm64-no-mm-malloc.patch)
sha256sums=('b8c22d275d9128741265537c559d0ea73074adbf2f2b66b0a766ca52c52d665b'
            '5ee91fb07f373b3a83f26f9f9fa3ab80661a9f0b7e1c3f4a23eb572f631fa37f'
            '8bc0c0635ec0969eb60768fa9d0682096d96d17bf818eb995700f5f64601df14'
            'ef8f9f14ccb1c53eed144ae99d589ec8edd331bb5da8ca7e2d68a7cdc10822e0')
prepare() {
  cd "${srcdir}"/embree-${pkgver}
  patch -p1 -i "${srcdir}"/001-build-fixes.patch
  # Windows ARM64 support
  patch -p1 -i "${srcdir}"/412.patch
  # no _mm_malloc with clangarm64, so just use _aligned_malloc everywhere
  patch -p1 -i "${srcdir}"/002-arm64-no-mm-malloc.patch

  mv kernels/embree.rc{,.orig}
  iconv -f UTF-16LE -t UTF-8 kernels/embree.rc.orig > kernels/embree.rc
}

build() {
  mkdir -p build-${MSYSTEM} && cd build-${MSYSTEM}

  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  if [[ "${CARCH}" == "x86_64" ]]; then
    extra_config+=("-DEMBREE_ISA_AVX512=ON" "-DEMBREE_MAX_ISA=AVX512SKX")
  else
    extra_config+=("-DEMBREE_ISA_AVX512=OFF")
  fi

  if [[ "${CARCH}" == "aarch64" ]]; then
    extra_config+=("-DEMBREE_ARM=ON")
  else
    extra_config+=("-DEMBREE_ARM=OFF")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe -Wno-dev \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DEMBREE_STATIC_LIB=OFF \
    -DEMBREE_ISPC_SUPPORT=OFF \
    -DEMBREE_STACK_PROTECTOR=ON \
    -DEMBREE_TUTORIALS=OFF \
    -DBUILD_TESTING=OFF \
    ${extra_config[@]} \
    ../embree-${pkgver}

  ${MINGW_PREFIX}/bin/cmake --build .
}

package() {
  cd "${srcdir}"/build-${MSYSTEM}
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install .
  install -Dm644 "${srcdir}"/embree-${pkgver}/LICENSE.txt "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
