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

   Backpropagation and checkerboard smoothing.

*/


#define TEX(dx,dy)   tex2D(decal, VAR.texCoord+float2((dx),(dy))*VAR.t1)
#define TEXt0(dx,dy) tex2D(PASSPREV4.texture, VAR.texCoord+float2((dx),(dy))*VAR.t1)

bool eq(float3 A, float3 B){
	return all(A == B);
}

float and(float a, float b){
	return min(a,b);
}

float or(float a, float b, float c, float d, float e, float f, float g, float h, float i){
	return max(a, max(b, max(c, max(d, max(e, max(f, max(g, max(h,i))))))));
}

float2 and(float2 a, float2 b){
	return min(a,b);
}

float2 or(float2 a, float2 b){
	return max(a,b);
}

float2 or(float2 a, float2 b, float2 c, float2 d){
	return max(a, max(b, max(c,d)));
}


struct prev
{
	float2 video_size;
	float2 texture_size;
	sampler2D texture;
};

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, prev PASSPREV4, uniform input IN) : COLOR
{

	/*
		UL U UR
		L  C R
		DL D DR
	*/

	float4 C  = TEX( 0, 0);		float3 c  = TEXt0( 0, 0).xyz;
	float2 L  = TEX(-1, 0).xy;	float3 l  = TEXt0(-1, 0).xyz;
	float2 R  = TEX( 1, 0).xy;	float3 r  = TEXt0( 1, 0).xyz;
	float2 U  = TEX( 0,-1).xy;	float3 u  = TEXt0( 0,-1).xyz;
	float2 D  = TEX( 0, 1).xy;	float3 d  = TEXt0( 0, 1).xyz;
	float2 UL = TEX(-1,-1).y;	float3 ul = TEXt0(-1,-1).xyz;
	float2 UR = TEX( 1,-1).y;	float3 ur = TEXt0( 1,-1).xyz;
	float2 DL = TEX(-1, 1).y;	float3 dl = TEXt0(-1, 1).xyz;
	float2 DR = TEX( 1, 1).y;	float3 dr = TEXt0( 1, 1).xyz;

	// Backpropagation
	C.xy = or(C.xy, and(C.zw, or(L, R, U, D)));

	// Checkerboard Smoothing
	C.y = or(C.y, and(U.y, eq(c,u)), and(D.y, eq(c,d)), and(L.y, eq(c,l)), and(R.y, eq(c,r)), and(UL, eq(c,ul)), and(UR, eq(c,ur)), and(DL, eq(c,dl)), and(DR, eq(c,dr)));

	return C;
}
