# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Andrew Sun <adsun701@gmail.com>

_realname=irrlicht
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.8.5
pkgrel=3
pkgdesc="An open source high performance realtime 3D graphics engine (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://irrlicht.sourceforge.io/"
license=("custom")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             $([[ ${CARCH} == aarch64 ]] && echo "git"))
depends=("${MINGW_PACKAGE_PREFIX}-cc-libs")
source=("https://downloads.sourceforge.net/irrlicht/irrlicht-${pkgver}.zip"
        "001-compile-fixes.patch"
        "002-aarch64.patch")
sha256sums=('effb7beed3985099ce2315a959c639b4973aac8210f61e354475a84105944f3d'
            'd8693950e4caa0199a57b84c9d1dcbec6186158372595db84b45522a38c57412'
            '67805e208400d834f87ba8857fabfb1622fdce5b2a74c162aec40967bb1e9323')

# Bring back NEON optimized code that matches the version being used
_pngver="1.6.37" # From source/Irrlicht/libpng/png.h
if [[ ${MSYSTEM} == CLANGARM64 ]]; then
  source+=("png::git+https://github.com/pnggroup/libpng.git#tag=v${_pngver}")
  sha256sums+=('2f502df9c7230e2706095386afb0f876cc9b8d688e5f07ded7c4d169d7a96bdf')
fi

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"

  apply_patch_with_msg \
    001-compile-fixes.patch \
    002-aarch64.patch

  if [[ ${MSYSTEM} == CLANGARM64 ]]; then
    mv "${srcdir}/png/arm" "${srcdir}/${_realname}-${pkgver}/source/Irrlicht/libpng"
  fi

  cd "${srcdir}"
  cp -rf "${_realname}-${pkgver}" "build-${MSYSTEM}-shared"
  cp -rf "${_realname}-${pkgver}" "build-${MSYSTEM}-static"
}

build() {
  CXXFLAGS+=" -std=gnu++11"

  msg "Build for ${MSYSTEM}-shared"
  cd "${srcdir}/build-${MSYSTEM}-shared/source/Irrlicht"
  CXX=${CXX} CC=${CC} AR=ar \
  make NDEBUG=1 sharedlib_win32

  msg "Build for ${MSYSTEM}-static"
  cd "${srcdir}/build-${MSYSTEM}-static/source/Irrlicht"
  CXX=${CXX} CC=${CC} AR=ar \
  make NDEBUG=1 staticlib_win32
}

package() {
  cd "${srcdir}/build-${MSYSTEM}-static"
  install -Dm644 "lib/Win32-gcc/libIrrlicht.a" "${pkgdir}${MINGW_PREFIX}/lib/libirrlicht.a"

  cd "${srcdir}/build-${MSYSTEM}-shared"
  install -Dm755 "bin/Win32-gcc/Irrlicht.dll" "${pkgdir}${MINGW_PREFIX}/bin/irrlicht.dll"
  install -Dm644 "lib/Win32-gcc/libIrrlicht.a" "${pkgdir}${MINGW_PREFIX}/lib/libirrlicht.dll.a"

  mkdir -p "${pkgdir}${MINGW_PREFIX}/include/irrlicht"
  cp -p include/*.h "${pkgdir}${MINGW_PREFIX}/include/irrlicht"
}
