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

   Backpropagation and checkerboard smoothing.

*/

/* COMPATIBILITY 
   - HLSL compilers
   - Cg   compilers
   - FX11 compilers
*/

#define TEX(dx,dy)   COMPAT_Sample(decal, texCoord+float2((dx),(dy))*t1)
#define TEXt0(dx,dy) COMPAT_Sample(PASSPREV4, texCoord+float2((dx),(dy))*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)));
}

#include "../../../../compat_includes.inc"
uniform COMPAT_Texture2D(decal) : TEXUNIT0;
INITIALIZE_PASSPREV(4, 1)
uniform float4x4 modelViewProj;

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

out_vertex main_vertex(COMPAT_IN_VERTEX)
{
#ifdef HLSL_4
	float4 position = VIN.position;
	float2 texCoord = VIN.texCoord;
#endif
	out_vertex OUT;
	OUT.position = mul(modelViewProj, position);
	OUT.texCoord = texCoord;
	OUT.t1 = 1.0 / COMPAT_texture_size;
	
	return OUT;
}

/*    FRAGMENT SHADER    */
float4 mdapt_pass3(float2 texCoord, float2 t1, COMPAT_Texture2D(decal), COMPAT_Texture2D(PASSPREV4))
{
	/*
		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;
}

float4 main_fragment(prev PASSPREV4 : TEXUNIT1, COMPAT_IN_FRAGMENT) : COMPAT_Output
{
	return mdapt_pass3(VOUT.texCoord, VOUT.t1, decal, PASSPREV_texture(4));
}
COMPAT_END