varying vec2 	texcoord;

uniform sampler2D 	waveTexture;
uniform sampler2D 	waveTextureDetail;
uniform sampler2D 	foamTexture;
uniform float		invWavemapSize;
uniform vec2 		foamDecay;

float computeFOAM(sampler2D waveDisplace, vec2 texcoord)
{
	vec3 waves=	texture2D(waveDisplace,(texcoord.st)).xzy;	
	vec3 wavesX=texture2D(waveDisplace,(texcoord.st+vec2(invWavemapSize,0.0))).xzy;
	vec3 wavesZ=texture2D(waveDisplace,(texcoord.st+vec2(0.0,invWavemapSize))).xzy;
		
	vec2 slopeX=wavesX.xz-waves.xz;
	vec2 slopeZ=wavesZ.xz-waves.xz;
		
	float foamVal = 	max((waves.x-wavesX.x),0.0)+
						max((wavesX.z-waves.z),0.0)+
						max((waves.x-wavesZ.x),0.0)+
						max((wavesZ.z-waves.z),0.0);
	return foamVal*0.25;//clamp((foamAmount-1.0+min(foamDensityMultiplier,1.0))*2.0f,0.0,1.0);
}

void main()
{	
	vec2 accfoam=texture2D(foamTexture,(texcoord.st)).xy;	
	vec2 newfoam;
	
	newfoam.x=computeFOAM(waveTexture,texcoord);
	newfoam.y=computeFOAM(waveTextureDetail,texcoord);
		
	accfoam=mix(newfoam,accfoam,foamDecay/*1.0-0.03125*/);
				
	gl_FragColor.xy = accfoam;
	gl_FragColor.z = 0.0;
	gl_FragColor.a=1.0;
}