/*
   Merge Dithering and Pseudo Transparency Shader v2.8 - Pass 2
   by Sp00kyFox, 2014

   Eliminating isolated detections.

*/


#pragma parameter VL_LO "MDAPT VL LO Thresh" 1.25 0.0 10.0 0.05
#pragma parameter VL_HI "MDAPT VL HI Thresh" 1.75 0.0 10.0 0.05
#pragma parameter CB_LO "MDAPT CB LO Thresh" 5.25 0.0 25.0 0.05
#pragma parameter CB_HI "MDAPT CB HI Thresh" 5.75 0.0 25.0 0.05

#ifdef PARAMETER_UNIFORM
	uniform float VL_LO, VL_HI, CB_LO, CB_HI;
#else
	#define VL_LO 1.25
	#define VL_HI 1.75
	#define CB_LO 5.25
	#define CB_HI 5.75
#endif


#define TEX(dx,dy) tex2D(decal, VAR.texCoord+float2((dx),(dy))*VAR.t1)
#define and(x,y) min(x,y)
#define or(x,y)  max(x,y)

float2 sigmoid(float2 signal){
	return smoothstep(float2(VL_LO, CB_LO), float2(VL_HI, CB_HI), signal);
}


struct input
{
	float2 video_size;
	float2 texture_size;
	float2 output_size;
};

struct out_vertex {
        float4 position : POSITION;
        float2 texCoord : TEXCOORD0;
        float2 t1;
};


/*    VERTEX_SHADER    */
out_vertex main_vertex
(
	float4 position	: POSITION,
	float2 texCoord : TEXCOORD0,

   	uniform float4x4 modelViewProj,
	uniform input IN
)
{
        out_vertex OUT;

        OUT.position = mul(modelViewProj, position);

        OUT.texCoord = texCoord;
	OUT.t1       = 1.0/IN.texture_size;

        return OUT;
}


/*    FRAGMENT SHADER    */
float4 main_fragment(in out_vertex VAR, uniform sampler2D decal : TEXUNIT0, uniform input IN) : COLOR
{

	/*
		NW  UUL U2 UUR NE
		ULL UL  U1 UR  URR
		L2  L1  C  R1  R2
		DLL DL  D1 DR  DRR	
		SW  DDL D2 DDR SE
	*/

	float2 C = TEX( 0, 0).xy;
	

	float2 hits = float2(0.0);
	
	//phase 1
	float2 L1 = TEX(-1, 0).xy;
	float2 R1 = TEX( 1, 0).xy;
	float2 U1 = TEX( 0,-1).xy;
	float2 D1 = TEX( 0, 1).xy;

	//phase 2
	float2 L2 = and(TEX(-2, 0).xy, L1);
	float2 R2 = and(TEX( 2, 0).xy, R1);
	float2 U2 = and(TEX( 0,-2).xy, U1);
	float2 D2 = and(TEX( 0, 2).xy, D1);
	float2 UL = and(TEX(-1,-1).xy, or(L1, U1));
	float2 UR = and(TEX( 1,-1).xy, or(R1, U1));
	float2 DL = and(TEX(-1, 1).xy, or(L1, D1));
	float2 DR = and(TEX( 1, 1).xy, or(R1, D1));

	//phase 3
	float2 ULL = and(TEX(-2,-1).xy, or(L2, UL));
	float2 URR = and(TEX( 2,-1).xy, or(R2, UR));
	float2 DRR = and(TEX( 2, 1).xy, or(R2, DR));
	float2 DLL = and(TEX(-2, 1).xy, or(L2, DL));
	float2 UUL = and(TEX(-1,-2).xy, or(U2, UL));
	float2 UUR = and(TEX( 1,-2).xy, or(U2, UR));
	float2 DDR = and(TEX( 1, 2).xy, or(D2, DR));
	float2 DDL = and(TEX(-1, 2).xy, or(D2, DL));

	//phase 4
	hits += and(TEX(-2,-2).xy, or(UUL, ULL));
	hits += and(TEX( 2,-2).xy, or(UUR, URR));
	hits += and(TEX(-2, 2).xy, or(DDL, DLL));
	hits += and(TEX( 2, 2).xy, or(DDR, DRR));

	hits += (ULL + URR + DRR + DLL + L2 + R2) + float2(0.0, 1.0) * (C + U1 + U2 + D1 + D2 + L1 + R1 + UL + UR + DL + DR + UUL + UUR + DDR + DDL);


	return float4(C * sigmoid(hits), C);
}
