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


struct Fragout
{
   float4 col : COLOR0;
};


//-----------------------------------------------------------------------------
// Main
//-----------------------------------------------------------------------------
Fragout main( ConnectData IN,
              uniform sampler2D depthMap        : register(S0),
              uniform sampler2D normalMap       : register(S1),
              uniform float4x4  invProj         : register(C0)
)
{
   Fragout OUT;

   half3 norm = tex2Dproj(normalMap, IN.texCoord);
   norm = norm * 2.0f - 1.0f;
   norm = normalize(norm);  // normalize because it was low-res 8 bit components

OUT.col = float4( norm, 1.0f );


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


   float3 lightVec = float3( IN.centerAndRadius.xyz - position.xyz );
   float len = length( lightVec );
   float atten = max(1.0f - (len / IN.centerAndRadius.w), 0.0f);
   lightVec /= len;

   atten *= dot( lightVec, norm );


OUT.col = IN.color * atten;

//OUT.col.g += 0.05; OUT.col.a = 1.0;  // debug - see complete light


   return OUT;
}
