uniform float ptimer;
uniform sampler2D htex;

const float origin_z = 0.0;
const float plane_z = 4.0;
const float far_z = 24.0;

const float scale = 16.0;
const float landscale = 128.0;
const float heightscale = 16.0;
const float step = 0.00025;

const float disp = 0.01;

float time;


vec3 getNormal(vec2 tc)
{
	tc.x = tc.x - disp;
	float dx0 = texture2D(htex, tc).a;
	tc.x = tc.x + 2.0 * disp;
	float dx1 = texture2D(htex, tc).a;
	tc.x = tc.x - disp;
	float dx = dx1 - dx0;

	tc.y = tc.y - disp;
	float dz0 = texture2D(htex, tc).a;
	tc.y = tc.y + 2.0 * disp;
	float dz1 = texture2D(htex, tc).a;
	tc.y = tc.y - disp;
	float dz = dz1 - dz0;

	vec3 norm = normalize(vec3(dx, 0.1, dz));
	return norm;
}

void main()
{
	time = ptimer * 0.0005;

	float xt = (gl_TexCoord[0].x - 0.5) * scale;
	float yt = (gl_TexCoord[0].y - 0.75) * scale;

	if (yt > 0.5)
	{
		gl_FragColor = vec4(0.0, 0.0, (yt - 0.5) / 16.0, 1.0);
	}
	else
	{
		vec3 pos = vec3(xt, yt, plane_z);
		vec3 origin = vec3(0.0, 0.0, origin_z);

		vec3 dir = normalize(pos - origin);
		vec3 dirstep = dir * (step / dir.z);

		float ccc = 0.0;
		vec2 tc;
		do
		{
			float tx = mod(pos.x / scale + sin(time/2.0) * 4.0, 1.0);
			float tz = mod(pos.z / scale + time, 1.0);
			tc = vec2(tx, tz);
			vec4 hgfx = texture2D(htex, tc);

			float ty = pos.y + 8.0;
			if (ty < hgfx.a * (heightscale / ((far_z + pos.z + plane_z) * 0.125)))
			{
				ccc = 0.75;
				break;
			}

			pos = pos + dirstep;
			dirstep = dirstep * 1.025;
		}while(pos.z < far_z);

		vec3 n = getNormal(tc);
		vec3 l = vec3(0.0, 0.0, 1.0);

		float cc = n.x * l.x + n.y * l.y + n.z * l.z;
		cc = mix(cc, (far_z - pos.z) / (far_z - plane_z), 0.5);

		if (pos.z >= far_z) cc = 0.0;
		gl_FragColor = vec4(cc, cc / 4.0, cc / 16.0, cc);
	}
}
