uniform sampler2D s_tex0; 

uniform float exposure;
uniform float daytime;
uniform float dayfactor;
uniform float noise;
uniform float time;
uniform vec4 daycolor;

uniform vec4 u_blendcolor;

varying vec2 v_texcoord;

const float MIDDLE_GREY = 0.72;
const float FUDGE = 0.001;
const float L_WHITE = 1.5;
const float PI = 3.14159265358979323846264;

// from: http://www.koders.com/noncode/fidB134383CDA66ACFDDE1E2BB70579CB362DC28D24.aspx
/** Tone mapping function 
@note Only affects rgb, not a
@param inColour The HDR colour
@param lum The scene lumninence 
@returns Tone mapped colour
*/
vec4 toneMap(in vec4 inColour, in float lum)
{
	// From Reinhard et al
	// "Photographic Tone Reproduction for Digital Images"
	
	// Initial luminence scaling (equation 2)
    inColour.rgb *= MIDDLE_GREY / (FUDGE + lum);

	// Control white out (equation 4 nom)
    inColour.rgb *= (1.0 + inColour.rgb / L_WHITE);

	// Final mapping (equation 4 denom)
	inColour.rgb /= (1.0 + inColour.rgb);
	
	return inColour;

}

float rand(vec2 co){
    return fract(sin(dot(co.xy ,vec2(1.29898,.78233))) * 43758.5453);
}

vec4 tint(in vec4 color, in float factor)
{
	// time parameter is 24h compressed into 0..1 around midnight
	// 0.0  -> 00:00
	// 0.25 -> 06:00
	// 0.5  -> 12:00
	// 0.75 -> 18:00
	// a 15 hour daylight phase goes from 05:30 (.229166667) to 20:30 (.854166667)

	// tint according to time of the day
	// daycolor.r = sin((daytime-2.3)*2.0*PI)*0.3+0.3; //max(0.0, sin((daytime-0.14)*1.2*PI))*0.3;
	// daycolor.g = max(0.0, sin((daytime-0.2292)*1.6*PI))*0.61;
	// daycolor.b = sin((daytime-0.2292)*2.0*PI)/2.0+0.5;
	vec3 localDaycolor = daycolor.rgb * color.rgb; // need a new var - can't modify a uniform

	float daytimefactorfactor = dayfactor * factor;
	color.rgb = (1.-daytimefactorfactor) * color.rgb + daytimefactorfactor * localDaycolor.rgb;
	
	vec4 toneColor = toneMap(color, exposure);
	color.rgb = (1.-factor) * color.rgb + factor * toneColor.rgb;

	return color;
}

void main()
{	
	vec4 color = texture2D(s_tex0, v_texcoord) * u_blendcolor;

	float factor = abs(daytime - 0.5)*2.0;
	color.rgb += color.rgb * rand(v_texcoord.xy*time) * factor * noise;

	gl_FragColor = tint(color, factor);
} 
