#include "RootConstants.hlsl"

struct Input
{
    float4 Color         : TEXCOORD0;
    float3 WorldNormal   : TEXCOORD1;
    float3 WorldPosition : TEXCOORD2;
};

float4 main(Input input) : SV_Target0
{
    float3 normal = normalize(input.WorldNormal);

    // Initial ambient component
    float3 result = input.Color.rgb * GlobalLightColor * GlobalAmbientIntensity;

    // Directional light contribution
    float ndotl = max(dot(normal, -GlobalLightDirection), 0.0);
    result += input.Color.rgb * GlobalLightColor * ndotl;

    // Point lights
    if (ActiveLightCount > 0)
    {
        StructuredBuffer<PointLight> pointLights = ResourceDescriptorHeap[LightBufferIndex];
        
        for (uint i = 0; i < ActiveLightCount; ++i)
        {
            PointLight light = pointLights[i];

            float3 lightDir = light.Position - input.WorldPosition;
            float  dist     = length(lightDir);
            
            if (dist < light.Radius)
            {
                lightDir = normalize(lightDir);
                float attenuation = 1.0 - (dist / light.Radius);
                attenuation = max(attenuation, 0.0);

                float pndotl = max(dot(normal, lightDir), 0.0);
                result += light.Color * input.Color.rgb * pndotl * attenuation * light.Intensity;
            }
        }
    }

    return float4(result, input.Color.a);
}
