#version 450 core
#extension GL_ARB_shading_language_include : require
#include "../../lib/lights.fs"

//foliage.fs

layout (location = 0) out vec4 accum;
layout (location = 1) out float reveal;


struct Material {
    sampler2D diffuse;
    sampler2D specular;
    float shininess;
}; 

in vec3 FragPos;
in vec3 ViewFragPos;
in vec3 Normal;
in vec2 TexCoord;
in vec4 FragPosLightSpace;
in vec4 instanceColor;


uniform dvec3 viewPos;
uniform Material material;
uniform mat4 view;


/**
The output
*/
out vec4 FragColor;

// function prototypes
float easeIn(float interpolator);
float easeOut(float interpolator);

void main(){
    vec3 viewDir = normalize(vec3(viewPos) - FragPos);
    
    //grab light intensity
    vec3 lightIntensity = vec3(calcLightIntensityTotal(Normal));

    //get color of base texture
    // vec3 textureColor = vec3((norm.x + 1) / 2.0, norm.y, 1.0 - (norm.x + 1) / 2.0);
    vec4 textureColor =  texture(material.diffuse,TexCoord) * instanceColor;
    // vec3 textureColor = vec3(0.17647,0.4,0.09411);//texture(material.diffuse, TexCoord).rgb;

    //shadow
    float shadow = ShadowCalculation(FragPosLightSpace, normalize(-directLight.direction), Normal);

    //
    //point light calculations
    uint clusterIndex = findCluster(ViewFragPos, zNear, zFar);
    uint pointLightCount = clusters[clusterIndex].count;
    for(int i = 0; i < pointLightCount; i++){
        uint pointLightIndex = clusters[clusterIndex].lightIndices[i];
        PointLight pointLight = pointLight[pointLightIndex];
        lightIntensity = lightIntensity + CalcPointLight(pointLight, Normal, FragPos, viewDir);
    }
    //error checking on light clusters
    if(pointLightCount > MAX_LIGHTS_PER_CLUSTER){
        accum = vec4(1.0f,0.0f,0.0f,1);
        reveal = textureColor.a;
        return;
    }

    //calculate final color
    vec4 finalColor = textureColor.rgba * vec4(lightIntensity,1.0);// * max(shadow,0.4);
    // vec3 lightAmount = CalcDirLight(norm, viewDir);
    // for(int i = 0; i < NR_POINT_LIGHTS; i++){
    //    lightAmount += CalcPointLight(i, norm, FragPos, viewDir);
    // }

    //calculate weight function
    float weight = clamp(pow(min(1.0, finalColor.a * 10.0) + 0.01, 3.0) * 1e3 * 
                        pow(1.0 - gl_FragCoord.z * 0.9, 3.0), 1e-2, 3e3);

    //emit colors
    accum = vec4(finalColor.rgb * finalColor.a, finalColor.a) * weight;
    // accum = finalColor * weight;
    reveal = finalColor.a;
}


float easeIn(float interpolator){
    return interpolator * interpolator;
}

float easeOut(float interpolator){
    return 1 - easeIn(1 - interpolator);
}