#version 430

layout(binding=0) uniform sampler2D tex;
layout(location = 0) out vec4 frag;
layout(location = 1) out vec4 frag2;

uniform float g_time;

precision highp float;
in highp vec2 coordG;

uniform float g_destW;
uniform float g_destH;

uniform float g_windowWidth;
uniform float g_windowHeight;
float zn = 0.0;
float zf = 1.0;
uniform mat4 projectionMatrix;
uniform mat4 projectionInvMatrix;

uniform float g_maxZ = 10.0;
uniform float g_powZ = 4.0;
uniform vec4 g_gain = vec4(1.0);

vec4 CalcEyeFromWindow(in vec3 windowSpace) {
    vec3 ndcPos;
    vec4 viewport = vec4(0.0, 0.0, g_windowWidth, g_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 = projectionMatrix[3][2]/(ndcPos.z-(projectionMatrix[2][2]/projectionMatrix[2][3]));
    clipPos.xyz = ndcPos * clipPos.w;
    return projectionInvMatrix * clipPos;
}


void main() {
    vec4 result = vec4(0.0);
    vec2 k = vec2(g_windowWidth/g_destW*gl_FragCoord.x, g_windowHeight/g_destH*gl_FragCoord.y);
    float d = texelFetch(tex, ivec2(k.x, k.y), 0).x;

    vec4 pos3D = CalcEyeFromWindow(vec3(k, d));

    float de = -pos3D.z;

    if (de < g_maxZ && de > 0.0) {

        de = (g_maxZ-de)/g_maxZ;

        de = pow(de, g_powZ);

        pos3D = normalize(pos3D);

        pos3D.x *= g_gain.y;
        pos3D.y *= g_gain.z;
        pos3D.z *= g_gain.w;
        pos3D.z *= -1.0;
        result = pos3D*de*g_gain.x;
    } else {
        result.z = -1000000.0; // special marker for indicating that there is no real value
    }

  //  result.r = 1.0;

    //result.rg = k;

    frag = result;
}
