#define _RangeCorrection	1.8
varying vec4 ProjCoords, NormalCoords;
varying vec3 position, LightDir;
varying float Depth, DisDepth;

uniform float Base, WaveHeight, FarClip;
uniform vec3 n00, n01, n11, n10, f00, f01, f11, f10;
uniform vec3 cameraPos;
uniform mat4 CamAlignedProj;

#ifdef _VertexTexture
uniform sampler2D VertexTexture;
#endif

vec4 MixVert(in vec4 v)
{
	vec3 n = mix(mix(n00, n01, v.y), mix(n10, n11, v.y), v.x);
	vec3 f = mix(mix(f00, f01, v.y), mix(f10, f11, v.y), v.x);
	vec3 dir = n.xyz - f.xyz;
	vec4 ret; 
	ret.xyz = ((-(n.z - Base)/dir.z) * dir) + n.xyz;
	ret.w = 1.0;
	return ret; 
}

void main()
{
	vec4 v = MixVert(gl_Vertex);

	v.z = Base;
	NormalCoords = CamAlignedProj * v;
	NormalCoords.w *= _RangeCorrection;


#ifdef _VertexTexture
	v.z = Base + (texture2DLod(VertexTexture, gl_Vertex.xy, 0.0).x - 0.5) * WaveHeight;
#else
	v.z = Base + ((gl_Color.r)-0.5) * WaveHeight;
#endif

	LightDir = (gl_LightSource[0].position * gl_ModelViewMatrix).xyz;

	position = v.xyz;
	Depth = min(1.0, length(v.xyz-cameraPos) / FarClip);
	DisDepth = max(0.1, 1.0-min(length(v.xyz-cameraPos) / 200.0, 1.0));
	gl_Position = gl_ModelViewProjectionMatrix * v; // ViewCoords
	ProjCoords = gl_Position;
}
