// Copyright 2006-2010 (C) - Frictional Games
//
// This file is part of HPL1 Engine
//
// For conditions of distribution and use, see copyright notice in LICENSE-shaders
//

///////////////////////////////////////////////////////
/// REFRACTION FRAGMENT PROGRAM /////////////////
///////////////////////////////////////////////////////

in vec2 vUv; //in object space
in vec3 vNormal;
in vec3 vEyePos;
in vec4 vColor;

OUTPUT

uniform sampler2DRect tex0; //screenMap
uniform sampler2D tex1; //refractMap
uniform sampler2D tex2; //diffuseMap

uniform vec2 screenSize;
uniform float scale;
uniform float t;

void main()
{
	//t *= 1;
	vec2 uv_offset1 = vUv;
	uv_offset1.x += sin(t*0.8 + vUv.y*10.0)*0.04;
	uv_offset1.y += sin(t*0.8 + uv_offset1.x*10.0)*0.04;

	vec3 offset1 = ((texture(tex1, uv_offset1)*2.0) - vec4(1.0)).xyz;

	vec2 uv_offset2 = vUv;
	uv_offset2.x += sin(t*-2.6 + vUv.y*12.0)*0.03;
	uv_offset2.y += sin(t*-2.6 + uv_offset2.x*12.0)*0.03;

	vec3 offset2 = ((texture(tex1, uv_offset2)*2.0) - vec4(1.0)).xyz;
	offset2.xy = -offset2.xy;

	vec3 offset = normalize(offset1*0.7 + offset2*0.3);

	//float fresnel = saturate(dot(normalize(vEyePos), normalize(vNormal)));
	//fresnel = (fresnel + 0.2)*0.8;

	vec3 waterColor = texture(tex2, uv_offset1).xyz;

	vec4 screenColor = texture2DRect(tex0, gl_FragCoord.xy + offset.xy * -scale);
	if(screenColor.w < 0.5) screenColor = texture2DRect(tex0, gl_FragCoord.xy);

	outColor.xyz = screenColor.xyz * waterColor;

	//outColor.y = uv.y+1 + uv_offset1.y;
	outColor.xyz *= clamp(dot(vec3(1.0/3.0, 1.0/3.0, 1.0/3.0), offset), 0.0, 1.0)*0.5 + 0.5;
	outColor.xyz += pow(clamp(dot(vec3(1.0/3.0, 1.0/3.0, 1.0/3.0), offset), 0.0, 1.0), 8.0)*5.0;
}
