// Copyright (C) 2014 NVIDIA Corporation.
// Copyright (C) 2019 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only

#ifndef SHADOW_MAPPING_GLSLLIB
#define SHADOW_MAPPING_GLSLLIB

#include "depthpass.glsllib"

float qt_sampleCubemap( in samplerCube shadowCube, in vec4 shadowControls, in mat4 shadowViewMat, in vec3 lightPos, in vec3 worldPos, in vec2 cameraProps )
{
    float dist = length(worldPos - lightPos);
    float shadowMapNear = cameraProps.x;
    float shadowMapFar = cameraProps.y;
    float shadowBias = shadowControls.x;
    float shadowFactor = shadowControls.y;
    float currentDepth = clamp((dist - shadowMapNear) / (shadowMapFar - shadowMapNear), 0.0, 1.0);
    vec3 smpCoord = worldPos - lightPos;

    // reverse Y if shadowControls.w == 1 (not enough on its own, also expects +Y and -Y swapped in shadowCube)
    smpCoord.y = mix(smpCoord.y, -smpCoord.y, shadowControls.w);

    float sampleDepth = texture( shadowCube, smpCoord ).x + shadowBias;
    return min(1.0, exp(shadowFactor * sampleDepth) / exp(shadowFactor * currentDepth));
}

float qt_sampleOrthographic( in sampler2D shadowMap, in vec4 shadowControls, in mat4 shadowMatrix, in vec3 worldPos, in vec2 cameraProps )
{
    vec4 projCoord = shadowMatrix * vec4( worldPos, 1.0 );
    vec3 smpCoord = projCoord.xyz / projCoord.w;
    smpCoord.y = mix(smpCoord.y, 1.0 - smpCoord.y, shadowControls.w);

    float shadowBias = shadowControls.x;
    float shadowFactor = shadowControls.y;
    float sampleDepth = texture( shadowMap, smpCoord.xy ).x + shadowBias;

    return min(1.0, exp(shadowFactor * sampleDepth) / exp(shadowFactor * smpCoord.z));
}

#endif
