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

#pragma once

#include "Geometry.ih"
#include "GeometryDispatch.ih"
#include "common/Data.ih"
#include "common/FeatureFlagsEnum.h"
#include "render/Renderer.ih"
#include "rkcommon/math/AffineSpace.ih"
// c++ shared
#include "GeometricModelShared.h"

OSPRAY_BEGIN_ISPC_NAMESPACE

#ifdef OSPRAY_TARGET_SYCL
using namespace ospray;
#endif

inline Material *GeometricModel_getMaterial(const GeometricModel *uniform self,
    const Renderer *uniform renderer,
    const int32 primID)
{
  if ((!self->material) && (!self->materialID))
    return NULL;

  uint32 idx = primID;
  if (valid(self->index)) {
    idx = get_uint8(self->index, min(idx, self->index.numItems - 1));
  }

  uniform uint32 lastMaterial = self->numMaterials - 1;
  Material **uniform mats = (Material * *uniform) self->material;
  if (!mats) {
    idx = self->materialID[min(idx, lastMaterial)];
    mats = renderer->material;
    lastMaterial = renderer->numMaterials - 1;
  }

  if (mats)
    return mats[min(idx, lastMaterial)];

  return NULL;
}

inline void GeometricModel_postIntersect(const GeometricModel *uniform self,
    const Renderer *uniform renderer,
    varying DifferentialGeometry &dg,
    const varying Ray &ray,
    uniform int64 flags,
    const uniform FeatureFlagsHandler &ffh)
{
  Geometry *uniform geom = self->geom;

  Geometry_dispatch_postIntersect(geom, dg, ray, flags, ffh);

  dg.areaPDF = self->areaPDF;
  dg.objID =
      (self->userID == RTC_INVALID_GEOMETRY_ID) ? ray.geomID : self->userID;

  if (flags & DG_COLOR && valid(self->color)) {
    uint32 idx = ray.primID;
    if (valid(self->index)) {
      idx = get_uint8(self->index, min(idx, self->index.numItems - 1));
    }
    dg.color = get_vec4f(self->color, min(idx, self->color.numItems - 1));
  }

  if (renderer) {
    dg.material = GeometricModel_getMaterial(self, renderer, ray.primID);
  }

  if (flags & DG_NS && self->invertedNormals)
    dg.Ns = neg(dg.Ns);
}

OSPRAY_END_ISPC_NAMESPACE
