#version 330 core
out float FragColor;

in vec2 TexCoord;
in vec4 PosWrld;

uniform int pt_light;
uniform vec3 light_pos;
uniform float far_plane;
uniform float near_plane;

struct Material {
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
    vec3 roughness;

    sampler2D diffTex;
    sampler2D ambtTex;
    sampler2D specTex;
    sampler2D normTex;
    sampler2D dispTex;
    sampler2D rghnTex;
};

uniform Material mtrl[2];

// Note: The `location` qualifier specifies the output buffer (if you have multiple),
// and `component` specifies the channel within that buffer.

void main()
{
    if( texture( mtrl[0].diffTex, TexCoord ).a < 0.05 ){
        discard;
    } else {
        float lightDistance = length(PosWrld.xyz - light_pos);
        
        // map to [0;1] range by dividing by far_plane
        lightDistance = lightDistance / far_plane;
        
        // write this as modified depth
        FragColor = lightDistance;
        gl_FragDepth = lightDistance;
        //gl_FragDepth = sqrt( (2.0 * 0.1 ) / (far_plane + 0.1 - ( lightDistance  * 2.0 - 1.0 ) * (far_plane - 0.1)) );
        //float z     = lightDistance + lightDistance - 1.0; // back to NDC 
        //float depth = ( near_plane + near_plane ) / (far_plane + near_plane - z * (far_plane - near_plane));
    }
}

