//
// Image Distortion
// Original code Shirley Carter
// Modified for rvfx - jrb
//

#version 330

#include "alpha.h"

uniform sampler2DRect inputTex;
uniform sampler2DRect maskTex;
uniform float scale;
uniform float uLocalTime;
uniform float uBlendValue=1.0;

in vec2 fsTexture;
in vec2 fsMaskTexture;
in vec2 fsPosition;
in vec2 fsTextureSize;
in vec2 fsNormalizedUV;

out vec4 outColor;

void main(void)
{
    //    float textureWidth = textureRect.z;
    //    float textureHeight = textureRect.w;
    //
    //    // This pixel location
    //    vec3 pCoord = gl_FragCoord.xyz;
    //    // Transform back to render traget coord space
    //    pCoord /= vec3(drawingScale, 1);
    //    pCoord += vec3(drawingOffset, 0);
    //
    //    vec2 drawingBoundsOrigin = drawingBoundsRect.xy;
    //    float drawingBoundsWidth =  drawingBoundsRect.z;
    //    float drawingBoundsHeight = drawingBoundsRect.w;
    //
    //    float deltaX = 0.0;//-0.75;//0.0;//sin( t )/2.0;//-.75;
    //    float deltaY = 0.0;//-0.5;//0.0;//sin( t )/2.0;//-.5;//1.0;
    //
    //    //First transform image coords i, j into x, y from -1 to 1
    //
    //    float x = -1.0+2.0/drawingBoundsWidth*(pCoord.x-drawingBoundsOrigin.x);
    //    float y = -1.0+2.0/drawingBoundsHeight*(pCoord.y-drawingBoundsOrigin.y);
    float x=fsPosition.x;
    float y=fsPosition.y;

    //Then transform to polar coordinates
    float ratio = min(fsTextureSize.x/fsTextureSize.y, fsTextureSize.y/fsTextureSize.x);
    float r = ratio*sqrt(x*x + y*y);
    float phi = atan(y,x);//equivalent to atan2

    float t = 90.0;//mod( float( time ), 30000.0 ) / 1000.0; //0 - 30 seconds
    float fac =  abs( sin( t ) )*scale + .125;//+1.5;/// 2.0 + 1.5;
    r = pow( r, fac );//fac );//magnifier

    //Map from polar to x, y
    x = r*cos( phi );
    y = r*sin( phi );

    //    //Map from x,y back to i , j texture coordinates
    //    float i = (x + 1.0 + deltaX)*drawingBoundsWidth*.5+drawingBoundsOrigin.x;
    //    float j = (y + 1.0 + deltaY)*drawingBoundsHeight*.5+drawingBoundsOrigin.y;
    //
    //    vec2 uv = gUV +(vec2(i,j)-pCoord.xy)/vec2(drawingBoundsWidth, drawingBoundsHeight)*vec2(textureRect.x+textureRect.z,textureRect.y+textureRect.w);
    //
    //    gl_FragColor = modulateColor*texture2DRect( texUnit, uv );
    //    gl_FragColor =(InBound(uv.x, textureRect.x, textureRect.x+textureRect.z) && InBound(uv.y, textureRect.y, textureRect.y+textureRect.w))?  gl_FragColor:vec4(0,0,0,0);

    vec2 uv;
    uv.x=x;
    uv.y=y;
    uv+=vec2(1.0,1.0);
    uv*=vec2(.5,.5f);
    uv=clamp(uv,vec2(0.0,0.0),vec2(1.0,1.0));
    uv*=fsTextureSize;
    vec4 texel=texture(inputTex,fsTexture);
    outColor=texture(inputTex,uv);
    float blendValue=uBlendValue;
#ifdef USE_MASK
    blendValue*=texture(maskTex,fsMaskTexture).a;
#endif
    mixColor(outColor, texel, outColor, blendValue);
}

