/*

  2xSaL Smart shader 

           - Copyright (C) 2007 guest(r) - guest.r@gmail.com

           - License: GNU-GPL  
		   
	2013-04-03 - Overlay + Dots, Flashlight edition. // KrossX
*/


uniform sampler2D OGL2TMU1;
uniform sampler2D OGL2Texture;
uniform vec4 OGL2Param;

//Comment the line below to disable the dots
//#define DOTTY

#ifdef DOTTY
	//The higher, the stronger the dots and the overall darkness will be.
	#define DOTTY_MIX (0.2)
#endif

float overlay(float base, float blend)
{
	float result = 0.0;
	
	if( base < 0.5 ) 
		result = 2.0 * base * blend;
	else   
		result = 1.0 - (1.0 - 2.0*(base-0.5)) * (1.0-blend);
		
	return result;
}

#ifdef DOTTY
vec3 dotty(vec3 color)
{
	float rest = fract(gl_FragCoord.x*0.25);	
	
	if (rest < 0.25)
	{    		
		color.g = 0.0;
		color.b = 0.0;
	}
	else if (rest > 0.50 && rest < 0.75)
	{    
		color.r = 0.0;
		color.g = 0.0;	
	}
	else if (rest < 0.75)
	{    
		color.r = 0.0;		
		color.b = 0.0;
	}
	else	
		color *= 0.5;	

	rest = fract(gl_FragCoord.y*0.5);		
	if(rest > 0.5) color *= 0.5;

	return color;
}
#endif

const vec3 dt = vec3(1.4,1.4,1.4);

void main()
{

    // Calculating texel coordinates
	
    vec2 size     = vec2(2048.0,1024.0);
    vec2 inv_size = vec2(1.0/2048.0, 1.0/1024.0);

    vec2 OGL2Pos = gl_TexCoord[0].xy*size;
    vec2 fp  = fract(OGL2Pos);
    vec2 dx  = vec2(inv_size.x,0.0);
    vec2 dy  = vec2(0.0,inv_size.y);
    vec2 g1  = vec2( inv_size.x,inv_size.y);
    vec2 g2  = vec2(-inv_size.x,inv_size.y);

    vec2 pC4 = floor(OGL2Pos)*inv_size;
   

    // Reading the texels

    vec3 C0 = texture2D(OGL2Texture,pC4-g1).xyz; 
    vec3 C1 = texture2D(OGL2Texture,pC4-dy).xyz;
    vec3 C2 = texture2D(OGL2Texture,pC4-g2).xyz;
    vec3 C3 = texture2D(OGL2Texture,pC4-dx).xyz;
    vec3 C4 = texture2D(OGL2Texture,pC4   ).xyz;
    vec3 C5 = texture2D(OGL2Texture,pC4+dx).xyz;
    vec3 C6 = texture2D(OGL2Texture,pC4+g2).xyz;
    vec3 C7 = texture2D(OGL2Texture,pC4+dy).xyz;
    vec3 C8 = texture2D(OGL2Texture,pC4+g1).xyz;

    vec3 ul,ur,dl,dr; float m1,m2;

    m1=dot(abs(C0-C4),dt)+0.001;
    m2=dot(abs(C1-C3),dt)+0.001;
    ul=(m2*(C0+C4)+m1*(C1+C3))/(m1+m2);

    m1=dot(abs(C1-C5),dt)+0.001;
    m2=dot(abs(C2-C4),dt)+0.001;
    ur=(m2*(C1+C5)+m1*(C2+C4))/(m1+m2);

    m1=dot(abs(C3-C7),dt)+0.001;
    m2=dot(abs(C6-C4),dt)+0.001;
    dl=(m2*(C3+C7)+m1*(C6+C4))/(m1+m2);

    m1=dot(abs(C4-C8),dt)+0.001;
    m2=dot(abs(C5-C7),dt)+0.001;
    dr=(m2*(C4+C8)+m1*(C5+C7))/(m1+m2);
    
    vec3 color = 0.5*((dr*fp.x+dl*(1-fp.x))*fp.y+(ur*fp.x+ul*(1-fp.x))*(1-fp.y));
	
	
	vec3 result = vec3(	overlay(color.r, color.r), 
						overlay(color.g, color.g), 
						overlay(color.b, color.b));
				
#ifdef DOTTY	
	color = mix(color, dotty(color), DOTTY_MIX);
	result = mix(result, dotty(result), DOTTY_MIX);
#endif

	vec3 blackthingy = texture2D(OGL2TMU1, gl_TexCoord[1].xy).rgb;
	
	float param = (OGL2Param.z + 1.0) * 0.20;			
	gl_FragColor.rgb = mix(color, result, param) * blackthingy;	
}

