// Copyright 2009 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

#pragma once

#include "OSPConfig.h"
#include "common/FeatureFlagsEnum.h"
#include "common/World.ih"
#include "rkcommon/math/vec.ih"

OSPRAY_BEGIN_ISPC_NAMESPACE

SYCL_EXTERNAL float computeAO(const Renderer *uniform,
    const World *uniform,
    const varying DifferentialGeometry &,
    const uniform int sampleCnt,
    const uniform float aoRadius,
    const varying vec3i &sampleID,
    const uniform FeatureFlagsHandler &ff);

// TODO should use PDEP
inline uniform uint32 partitionZOrder(uniform uint32 n)
{
  n &= 0x0000FFFF;
  n = (n | (n << 8)) & 0x00FF00FF;
  n = (n | (n << 4)) & 0x0F0F0F0F;
  n = (n | (n << 2)) & 0x33333333;
  n = (n | (n << 1)) & 0x55555555;
  return n;
}

inline uint32 partitionZOrder8(uint32 n)
{
  n &= 0x000000FF;
  n = (n | (n << 4)) & 0x0F0F0F0F;
  n = (n | (n << 2)) & 0x33333333;
  n = (n | (n << 1)) & 0x55555555;
  return n;
}

// TODO should use PEXT
inline uniform uint32 unpartitionZOrder(uniform uint32 n)
{
  n &= 0x55555555;
  n = (n ^ (n >> 1)) & 0x33333333;
  n = (n ^ (n >> 2)) & 0x0F0F0F0F;
  n = (n ^ (n >> 4)) & 0x00FF00FF;
  n = (n ^ (n >> 8)) & 0x0000FFFF;
  return n;
}

inline uniform uint32 interleaveZOrder(uniform uint32 x, uniform uint32 y)
{
  return partitionZOrder(x) | (partitionZOrder(y) << 1);
}

inline uint32 interleaveZOrder16(uint32 x, uint32 y)
{
  return partitionZOrder8(x) | (partitionZOrder8(y) << 1);
}

inline void deinterleaveZOrder(
    uniform uint32 z, uniform uint32 *uniform x, uniform uint32 *uniform y)
{
  assert(x);
  assert(y);
  *x = *y = 0;
  *x = unpartitionZOrder(z);
  *y = unpartitionZOrder(z >> 1);
}

OSPRAY_END_ISPC_NAMESPACE
