uniform sampler2D s_tex0;
uniform float intensity;
uniform float roughness;
uniform float darkness;
uniform float time;

varying vec4 v_color;
varying vec4 v_texCoord;

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

void main()
{
	vec4 color = v_color * texture2D(tex, v_texCoord.xy);
	
	// bloom effect inspired by http://kstudios.de/postprocessing2_3.php
	vec3 origColor = color.rgb;
	color.rgb = color.rgb*color.rgb;

	// average is darkened via factor
	float avg = (color.r+color.g+color.b)/3.0;
	avg = avg * (1.0-roughness) + avg * rand(v_texCoord.xy*time)*roughness;
	avg /= 1.+darkness;
	color.rgb = vec3(avg,avg,avg);
	color.rgb += origColor.rgb;

	// feed it back according to http://kstudios.de/postprocessing2_3.php
	color.rgb = mix(origColor,color.rgb, intensity);

	gl_FragColor = color;
}
