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

//texture defines
#define ATLAS_ELEMENT_DIM 256.0
#define ATLAS_DIM 8192.0
#define ATLAS_EL_PER_ROW 32
#define ATLAS_NORMALIZED_ELEMENT_WIDTH 0.031 //within the single texture within the atlas, we use this so we never go over the end of the texture
#define ATLAS_NORMALIZED_ELEMENT_WIDTH_FULL 0.03125 //used to properly shift from texture to texture in the atlas


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

in vec3 FragPos;
in vec3 ViewFragPos;
in vec3 Normal;
in vec2 uv;
in vec4 FragPosLightSpace;
in flat int samplerIndexVec; //the indices in the atlas of textures to sample


uniform vec3 viewPos;
uniform Material material;

/**
Used for light cluster calculation
*/
uniform mat4 view;

/**
The output
*/
out vec4 FragColor;


// function prototypes
vec3 getColor(vec2 uv, vec3 normal, int samplerIndexVec, Material material);

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

    //get color of base texture
    vec3 textureColor = getColor(uv, norm, samplerIndexVec, material);

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

    //
    //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, norm, FragPos, viewDir);
    }
    //error checking on light clusters
    if(pointLightCount > MAX_LIGHTS_PER_CLUSTER){
        FragColor = vec4(1.0f,0.0f,0.0f,1);
        return;
    }

    //calculate final color
    vec3 finalColor = textureColor * lightIntensity * max(shadow,0.4);

    //this final calculation is for transparency
    FragColor = vec4(finalColor, 1);
}


/**
 * The function that gets the texture color based on the triplanar texture mapping and the voxel type at each point along the vert.
 * See the triplanar mapping wiki article for an explanation of math involved.
 */
vec3 getColor(vec2 uv, vec3 normal, int samplerIndexVec, Material material){

    //the uv of the texture clamped within the atlas
    vec2 actualUv = vec2(
        (fract(uv.x) * ATLAS_NORMALIZED_ELEMENT_WIDTH) + (mod(samplerIndexVec,ATLAS_EL_PER_ROW) * ATLAS_NORMALIZED_ELEMENT_WIDTH_FULL),
        (fract(uv.y) * ATLAS_NORMALIZED_ELEMENT_WIDTH) + (round(samplerIndexVec / ATLAS_EL_PER_ROW) * ATLAS_NORMALIZED_ELEMENT_WIDTH_FULL)
    );
    //albedo for the X texture
    vec3 color = texture(material.diffuse, actualUv).rgb;
    

    return color;
}