uniform sampler2D ReflectionTex;
uniform sampler2D RefractionTex;
uniform float u_WaveTime;

varying vec3 v_Pos;
varying vec3 v_ScreenPos;

varying vec3 v_ViewVecInView;
varying vec3 v_NormalInView;
varying vec3 v_NormalInWorld;
varying vec3 v_TangentInWorld;

void main()
{  
	//variable initialization:
	vec3 NormalInView=normalize(v_NormalInView);  
	vec3 ViewVecInView=normalize(v_ViewVecInView);
	
	vec3 NormalInWorld=normalize(v_NormalInWorld);
	vec3 TangentInWorld=normalize(v_TangentInWorld);
	vec3 BitangentInWorld=cross(NormalInWorld, TangentInWorld);
	mat3 NormalTransform=mat3(TangentInWorld, BitangentInWorld, NormalInWorld);
	
	//small waves:
	vec2  D0=normalize(vec2(-3, 3)-v_Pos.xy);
	float A0=0.005;
	float w0=8;
	float S0=6;
	
	vec2  D1=normalize(vec2(3, 4)-v_Pos.xy);
	float A1=0.003;
	float w1=7;
	float S1=7;
	
	vec2  D2=normalize(vec2(0, 10)-v_Pos.xy);
	float A2=0.006;
	float w2=9;
	float S2=5;
	
	vec2  D3=normalize(vec2(-8, 0)-v_Pos.xy);
	float A3=0.008;
	float w3=3;
	float S3=10;
	
	vec3 WaveNormal=normalize(vec3(
			-w0*D0.x*A0*cos(dot(D0, vec2(v_Pos.x, v_Pos.y))*w0+u_WaveTime*S0)+
			-w1*D1.x*A1*cos(dot(D1, vec2(v_Pos.x, v_Pos.y))*w1+u_WaveTime*S1)+
			-w2*D2.x*A2*cos(dot(D2, vec2(v_Pos.x, v_Pos.y))*w2+u_WaveTime*S2)+
			-w3*D3.x*A3*cos(dot(D2, vec2(v_Pos.x, v_Pos.y))*w3+u_WaveTime*S3),
			
			-w0*D0.y*A0*cos(dot(D0, vec2(v_Pos.x, v_Pos.y))*w0+u_WaveTime*S0)+
			-w1*D1.y*A1*cos(dot(D1, vec2(v_Pos.x, v_Pos.y))*w1+u_WaveTime*S1)+
			-w2*D2.y*A2*cos(dot(D2, vec2(v_Pos.x, v_Pos.y))*w2+u_WaveTime*S2)+
			-w3*D3.y*A3*cos(dot(D3, vec2(v_Pos.x, v_Pos.y))*w3+u_WaveTime*S3),
			
			1));
	
	//TODO transform with normal transform
	vec3 Normal=NormalTransform*WaveNormal;
	
	//distortion
	vec2 dist=vec2(cos(v_Pos.x*10.0+u_WaveTime)*sin(v_Pos.y*10.0-u_WaveTime),
					sin(v_Pos.y*10.0-u_WaveTime)+cos(v_Pos.x*10.0+u_WaveTime))/20.0;
	dist=vec2(0, 0);
	
	dist+=vec2(Normal.x, Normal.y)*2;
	
	vec2 TexCoordDist=(v_ScreenPos.xy+dist)/v_ScreenPos.z;  
	TexCoordDist=(TexCoordDist+1.0)/2.0;
	
	
	//specular highlights
	vec3 LightInView=gl_NormalMatrix*normalize(vec3(3, 7, 4));
	vec3 reflLight=reflect(LightInView, v_NormalInView);
	float SpecIntensity=max(pow(dot(reflLight, ViewVecInView), 120), 0.0);
	
	//Refraction
	float RefractionFactor=dot(NormalInView, -ViewVecInView);
	
	vec4 ReflRefr=vec4(	texture2D(ReflectionTex, TexCoordDist).xyz*(1-RefractionFactor)+
						texture2D(RefractionTex, TexCoordDist).xyz*(  RefractionFactor)
						, 1.0);
	
	//Putting it together
	gl_FragColor=ReflRefr+SpecIntensity*vec4(1, 1, 1, 1)/3;
}