#version 120

uniform float sun_ymin, sun_ymax;
uniform sampler2D sun_shadowmap;

varying vec3 posVS, posWS, normalVS, normalWS;
varying vec4 sunUV;

float unpack(vec4 encodedValue) { return dot(encodedValue,vec4( 1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0 )); }

float calculateSunShadow() {
	float myLightZ = (posWS.y-sun_ymin)/(sun_ymax-sun_ymin);
	
	vec2 center = sunUV.xy / sunUV.w;
	
	float dott = max(0.0, normalize(normalWS).y);
	
	if (min(center.x, center.y)<0.0 || max(center.x, center.y)>1.0) {
		return dott;
	}
	
	vec2 uv = center;

	float sampleZ = unpack(texture2D(sun_shadowmap, uv));
	float shadowSum = step(sampleZ, myLightZ);
	
	return shadowSum * dott;
}

void main(void)
{
	float sunShadow = calculateSunShadow();
	vec3 sunColor  = vec3(0.8,0.8,0.65);
	
	gl_FragData[0] = gl_Color*(vec4(sunShadow * sunColor, 1.0));
	gl_FragData[1] = vec4(gl_Color.xyz, posVS.z);
}
