/*=============================================================================
	ModShadowProjectionPixelShader.usf: Pixel shader for projecting a shadow depth buffer onto the scene.
	Copyright © 2006 Epic Games, Inc. All Rights Reserved.
=============================================================================*/

#include "Common.usf"
#include "ModShadowCommon.usf"

float4x4 ScreenToShadowMatrix;
sampler2D ShadowDepthTexture;
float4 SampleOffsets[NUM_SAMPLE_CHUNKS * 2];

void Main(
	in float4 ScreenPosition : TEXCOORD0,
	out float4 OutColor : COLOR0
	)
{
	half SceneW = PreviousDepth(ScreenPosition);

	float4 ShadowPosition = MulMatrix(ScreenToShadowMatrix,float4(ScreenPosition.xy / ScreenPosition.w * SceneW,SceneW,1));
	ShadowPosition.xy /= ShadowPosition.w;
	ShadowPosition.z = min(ShadowPosition.z,0.999);

	half ShadowDepth = texDepth2D(ShadowDepthTexture,ShadowPosition.xy).r;

	half Shadow = 0;
	for(int ChunkIndex = 0;ChunkIndex < NUM_SAMPLE_CHUNKS;ChunkIndex++)
	{
		float4	ShadowDepths;

		ShadowDepths.r = texDepth2D(ShadowDepthTexture,ShadowPosition.xy + SampleOffsets[ChunkIndex * 2 + 0].xy).r;
		ShadowDepths.g = texDepth2D(ShadowDepthTexture,ShadowPosition.xy + SampleOffsets[ChunkIndex * 2 + 0].wz).r;
		ShadowDepths.b = texDepth2D(ShadowDepthTexture,ShadowPosition.xy + SampleOffsets[ChunkIndex * 2 + 1].xy).r;
		ShadowDepths.a = texDepth2D(ShadowDepthTexture,ShadowPosition.xy + SampleOffsets[ChunkIndex * 2 + 1].wz).r;

		Shadow += dot(ShadowPosition.z < ShadowDepths ? half4(1,1,1,1) : half4(0,0,0,0), 1.0 / (4.0 * NUM_SAMPLE_CHUNKS));
	}
	
#if MODSHADOW_LIGHTTYPE_DIRECTIONAL
	// no attenuation necessary for directional lights
	half ShadowAtt = 1;
#else
	// attenuate between shadow color and white based on distance
	half ShadowAtt = ShadowAttenuation(ScreenPosition,SceneW);
#endif

	// add modulated/attenuated shadow color to shadow
	float4 ShadowedColor = lerp(float4(1,1,1,1),ShadowModulateColor,ShadowAtt);
	float4 UnshadowedColor = float4(1,1,1,1);

	// RETURN_COLOR not needed unless writing to SceneColor;
	//nse vbunny--
	//we don't need to worry about the mult, because the mult happens later in the full pass modualtion shader(gulp)
	//#if SUPPORTS_FP_BLENDING
		OutColor = lerp(ShadowedColor,UnshadowedColor,Square(Shadow));
	//#else
	//	OutColor = OpaqueBlendModulate( ScreenPosition, lerp(ShadowedColor,UnshadowedColor,Square(Shadow) ) );
	//#endif
	//--nse vbunny
}
