uniform sampler2D 	posTex,
					causticsTex,
					colorTex;

varying vec2 		texcoord;
varying vec2		VPOS;
uniform float		waterY;
uniform mat4		eyeToWorldTM;
uniform vec3		SUN;
uniform vec2 		scale;

uniform vec3 		moonlightcolor;

uniform vec4		LTM0,
					LTM1,
					LTM3;
					
// ------------ ATMOSPHERE ------------------------------

uniform float 		length_unit;
uniform vec3 		earth_center;
uniform vec3 		sundir;

vec3 GetSunIrradiance(vec3 p, vec3 sun_direction);

// -------------------------------------------------------

void main()
{
	vec3 outcolor=vec3(0.0,0.0,0.0);
	vec4 color = texture2D(colorTex,texcoord.st);
	color.rgb=pow(color.rgb,vec3(2.2));
	
	vec4 pos;
	pos.z = texture2D(posTex,texcoord.st).r;
	if(-pos.z<400000)
	{
		pos.xy=VPOS*-pos.z;
		pos.w=1.0;	
		vec4 Wpos=eyeToWorldTM*pos;

		if(Wpos.y>waterY)
			discard;

		vec4	XYproj;	
		vec3 	projcoords;
		
		// COMPUTE LIGHT TEXTURE PROJECTION + ATTENUATION
		XYproj.x = dot(pos,LTM0);
		XYproj.y = dot(pos,LTM1);
		XYproj.w = dot(pos,LTM3);
		projcoords.xy=(XYproj.xy/XYproj.w);
		vec2 coords0=projcoords.xy;
		
		vec3 rwp=(Wpos.xyz*length_unit)-earth_center.xyz;
		rwp.y=max(rwp.y,-earth_center.y);
		vec3 sunLightColor = GetSunIrradiance(rwp, sundir)*SUN + moonlightcolor;
		
		vec3 c0;
		c0=texture2D(causticsTex,coords0.xy*scale).rgb;
		vec3 CR=sunLightColor*c0*color.xyz;
		outcolor=mix(vec3(0.0,0.0,0.0),CR,clamp( (waterY-Wpos.y)*0.001 ,0.0,1.0));
	}
	
	gl_FragColor.rgb=outcolor;
	gl_FragColor.a=1.0;
}
