#version 430

in vec2 uv;

layout(location = 0) out vec4 frag;

uniform float g_time;
uniform float windowWidth = 1280.0;
uniform float windowHeight = 720.0;

layout(binding=0) uniform sampler2D texDepth;

float zn = 0.0;
float zf = 1.0;
uniform mat4 projSecond;
uniform mat4 projInvSecond;
uniform mat4 viewInvSecond;
vec4 CalcEyeFromWindow(in vec3 windowSpace) {
    vec3 ndcPos;
    vec4 viewport = vec4(0.0, 0.0, windowWidth, windowHeight);
    ndcPos.xy = ((2.0 * windowSpace.xy) - (2.0 * viewport.xy)) / (viewport.zw) - 1;
    ndcPos.z = (2.0 * windowSpace.z - zn - zf) / (zf - zn);
    vec4 clipPos;
    clipPos.w = projSecond[3][2]/(ndcPos.z-(projSecond[2][2]/projSecond[2][3]));
    clipPos.xyz = ndcPos * clipPos.w;
    return projInvSecond * clipPos;
}

void main() {
    vec2 tc = gl_FragCoord.xy;
    vec4 d = texelFetch(texDepth, ivec2(tc), 0);
    vec4 eye = CalcEyeFromWindow(vec3(tc, d.r));
    vec4 wp = viewInvSecond*eye;

//    wp /= wp.w;

    frag = vec4(wp.xyz, 1.0);
 //   frag.rgb = vec3(fract(wp.z*1.0));
//    frag.rgb = vec3(0.0, 1.0, 0.0);
}

