#version 330

uniform sampler2DRect inputTex;
uniform sampler2DRect maskTex;
uniform float intensity=.2;
uniform float uGlobalTime;
uniform float frequency=1.;

layout (location=0) in vec3 vsPosition;
layout (location=1) in vec2 vsTexture;
layout (location=2) in vec2 vsTextureMask;

out vec2 fsTexture;
out vec2 fsTexture2;
out vec2 fsMaskTexture;

float hash(vec2 p)
{
    p  = 50.0*fract( p*0.3183099 + vec2(0.71,0.113));
    return -1.0+2.0*fract( p.x*p.y*(p.x+p.y) );
}

float noise(vec2 p )
{
    vec2 i = floor( p );
    vec2 f = fract( p );

    vec2 u = f*f*(3.0-2.0*f);

    return mix( mix( hash( i + vec2(0.0,0.0) ),
                    hash( i + vec2(1.0,0.0) ), u.x),
               mix( hash( i + vec2(0.0,1.0) ),
                   hash( i + vec2(1.0,1.0) ), u.x), u.y);
}

void main()
{
    gl_Position=vec4(vsPosition.x,vsPosition.y,vsPosition.z,1.0);
    ivec2 texSize=textureSize(inputTex);
    vec2 tmp = vsTexture/vec2(texSize); //0,0 -> 1,1
    fsTexture2=vsTexture;
    tmp-=.5;    //-.5,-.5 -> .5,.5
    tmp*=2.;    //-1,-1 -> 1,1
    tmp/=(intensity+1.);
    float dx=uGlobalTime*4.*(frequency+.1);

    tmp.x+=noise(vec2(dx,-dx))*(intensity*.5);
    tmp.y-=noise(vec2(-dx,dx))*(intensity*.5);

    tmp*=.5;
    tmp+=.5;
    fsTexture=tmp*vec2(texSize);
    fsMaskTexture = vsTextureMask;
}
