uniform sampler shadowmap;
uniform sampler diffusemap;	//for alpha map
uniform float4	invTexSize;
uniform float	hasAlpha ;

static const float SHADOW_FACTOR = 0.5f;

struct PS_INPUT
{
	float4 uv		: TEXCOORD0;
	float4 shadowUV	: TEXCOORD1;
};

float4 main_ps( PS_INPUT input ) : COLOR0
{
	float4 outColor = float4(1, 1, 1, 1 );
	float visibility = 1;
	
	//assuming shadowmap is square
	float texelOffset = invTexSize.x;

	// scaling shadowUV.z also by shadowUV.w is a hack, because DX9's issues with clearing the depth buffer
	// see http://www.stevestreeting.com/2009/01/04/depth-shadow-mapping-dx9-depth-range-gotchas/
	float3 scoord = input.shadowUV.xyz / input.shadowUV.w;
	float zCenter = tex2D( shadowmap, scoord.xy ).x;
	
	//=== PCF =========================================================================
	float4 zSamples = float4(
						tex2D( shadowmap, scoord.xy + float2(-texelOffset,0) ).x,
						tex2D( shadowmap, scoord.xy + float2(texelOffset, 0) ).x,
						tex2D( shadowmap, scoord.xy + float2(0,-texelOffset) ).x,
						tex2D( shadowmap, scoord.xy + float2(0, texelOffset) ).x	);
	
	visibility = ( zCenter < scoord.z ) ? SHADOW_FACTOR : 1.0;
	
	 visibility += ( zSamples.x < scoord.z ) ? SHADOW_FACTOR : 1.0;
	 visibility += ( zSamples.y < scoord.z ) ? SHADOW_FACTOR : 1.0;
	 visibility += ( zSamples.z < scoord.z ) ? SHADOW_FACTOR : 1.0;
	 visibility += ( zSamples.w < scoord.z ) ? SHADOW_FACTOR : 1.0;
	 
	 visibility /= 5.0;
	 //==================================================================================

	if (hasAlpha == 1.0)
	{
		float fAlpha  = saturate (tex2D( diffusemap, input.uv ).a ) ;
		visibility = lerp(visibility, 1  , 1-fAlpha );
	}

	outColor.rgb *= visibility;

	return saturate( outColor );
}
