#version 430

layout(binding=0) uniform sampler2D texWave;
layout(binding=1) uniform sampler2D texSpaceDirX;
layout(binding=2) uniform sampler2D texSpaceDirY;


in vec4 posG;
in vec4 posOrigG;
in vec3 normalG;
in vec3 normalWSG;
in vec2 uvG;
in vec3 tangentG;
in vec3 colorG;
in vec4 posW;
in float brightG;

in float triangleIdG;

layout(location = 0) out vec4 frag;
layout(location = 1) out vec4 frag2;


#define PI 3.1415926

uniform float g_time;

uniform float g_uvOfsX = 0.0;
uniform float g_uvScale = 1.0;
uniform float g_uvScaleY = 1.0;
uniform float g_uvOfsY = 0.0;

uniform float g_texBrightness = 1.0;
uniform float g_texAmbient = 0.0;
uniform float g_prevAmount = 0.0;
uniform float g_prevBlurAmount = 0.0;
uniform float g_bump = 0.0;

uniform vec4 g_color = vec4(1.0);


uniform mat4 modelViewMatrix;
uniform mat4 modelViewInvMatrix;
uniform mat4 viewInvMatrix;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
uniform mat4 projectionInvMatrix;

uniform float g_windowWidth = 1280.0;
uniform float g_windowHeight = 720.0;


layout(binding=0, rgba16f) uniform image2D texSpaceNormal;

uniform float g_texW = 1280;
uniform float g_texH = 720;
uniform float g_quadsPerRow = 128;

vec2 getTexCoord(vec2 c) {
    vec2 ct = vec2(c.x*g_texW, c.y*g_texH);
    return ct;
}


void main() {

  vec3 normal = normalG;
  vec2 uv = uvG;
  vec3 tangent = tangentG;
  vec3 color = colorG;

  ivec2 ct = ivec2(gl_FragCoord.xy);

  ivec2 tuv = ivec2(getTexCoord(uvG));


//  vec4 baseTex = texelFetch(texWave, tuv, 0);
  vec4 cx = texelFetch(texSpaceDirX, tuv, 0);
  vec4 cy = texelFetch(texSpaceDirY, tuv, 0);

 // ivec2 test0 = ivec2(getTexCoord(uv));
 // ivec2 test1 = ivec2(getTexCoord(uv+vec2(0.50/g_texW, 0.0)));
 // ivec2 test2 = ivec2(getTexCoord(uv+vec2(0.0, 0.50/g_texH)));

 // vec4 tx = getTexBi(texWave, uv+vec2(0.50/g_texW, 0.0));
 // vec4 ty = getTexBi(texWave, uv+vec2(0.0, 0.5/g_texH));
  vec4 tx = texelFetch(texWave, ivec2(cx.zw), 0);
  vec4 ty = texelFetch(texWave, ivec2(cy.xy), 0);


//  float bx = tx.r-baseTex.r;
//  float by = ty.r-baseTex.r;

  vec4 baseTexLeft = texelFetch(texWave, ivec2(cx.xy), 0);
  vec4 baseTexUp = texelFetch(texWave, ivec2(cy.zw), 0);
  float bx = tx.r-baseTexLeft.r;
  float by = ty.r-baseTexUp.r;

  vec3 normD = normalize(normal);
  tangent = normalize(tangent);
  vec3 bita = cross(normD, tangent);
  float bs = 16.0;
  normD = normD-tangent*bx*bs-bita*by*bs;


  imageStore(texSpaceNormal, ct, vec4(normD, 0.0));

  discard;
 return;


}

