//*****************************************************************************
// Dynamic light shader
//*****************************************************************************
//-----------------------------------------------------------------------------
// Structures
//-----------------------------------------------------------------------------
struct ConnectData
{
   float4 texCoord        : TEXCOORD0;
   float4 position        : TEXCOORD1;
};


struct Fragout
{
   float4 col : COLOR0;
};


//-----------------------------------------------------------------------------
// Main
//-----------------------------------------------------------------------------
Fragout main( ConnectData IN,
              uniform sampler2D depthMap        : register(S0),
              uniform sampler2D shadowMap       : register(S1),
              uniform float4x4  invProj         : register(C0),
              uniform float4x4  shadowProj      : register(C4),
              uniform float4x4  invView         : register(C8),
              uniform float4    sunPlane        : register(C12)
)
{
   Fragout OUT;


   //reconstruct original view-space position
   float4 position;
//   position.xyz = mul( invProj, float3( IN.position.xy / IN.position.z, 1.0 ) ).xyz;
   position.xyz = mul( invProj, float3( IN.position.xy, 1.0 ) ).xyz;
   float  z = tex2Dproj(depthMap, IN.texCoord).r;
   position.xy *= z;    // solve parametrically - fire the ray!
   position.z = z;


   position.w = 1.0;    //  could get proper w by multiplying by projection matrix if necessary to test


//   float4 finalTexCoord = mul( shadowProj, position );
//   OUT.col = tex2Dproj( shadowMap, finalTexCoord );

//   float4 finalTexCoord = mul( shadowProj, position );
//   OUT.col = tex2D( shadowMap, finalTexCoord.xy / 100.0 );


   float3 posInShadow = mul( invView, position );
//   float distToSun = length( sunPlane.xyz - posInShadow );
   float distToSun = abs( dot( sunPlane.xyz, posInShadow ) + sunPlane.w );

/*
float3 dirToLight = normalize( sunPlane.xyz - posInShadow );
if( dot( dirToLight, float3( 0.0, 0.0, 1.0 ) ) > 0.92 )
{
   OUT.col = float4( 0.0, 0.0, 1.0, 1.0 );
}
else
{
   OUT.col = float4( 1.0, 1.0, 1.0, 1.0 );
}
return OUT;
*/

   float4 finalTexCoord = mul( shadowProj, position );
   float shadowDist = tex2Dproj( shadowMap, finalTexCoord ).r;

   if( (distToSun - shadowDist) > 1.5 )
   {
      OUT.col = float4( 0.4, 0.4, 0.4, 0.4 );
   }
   else
   {
      OUT.col = float4( 1.0, 1.0, 1.0, 1.0 );
   }


   return OUT;

}
