float fTime;			  // Time parameter. This keeps increasing

texture Texture;

float4x4 mWorld : WORLD;
float4x4 mWorldViewProj : WORLDVIEWPROJECTION;
float4x4 mViewProj : VIEWPROJECTION;

static const int MAX_MATRICES = 8;
float4x4    mWorldMatrixArray[MAX_MATRICES] : WORLDMATRIXARRAY;
int         NumBones;

sampler2D textureSampler = sampler_state 
{
    Texture = (Texture);
	AddressU = Wrap;
    AddressV = Wrap;
};


// Vertex shader program input
struct VS_INPUT
{
	float4 Position : POSITION;
	float4 Diffuse  : COLOR0;
	float2 Texture  : TEXCOORD0;
	float3 Normal : NORMAL;
	float4 BlendWeights    : BLENDWEIGHT;
    int4   BlendIndices    : BLENDINDICES;
};


struct VS_OUTPUT
{
    float4 Position   : POSITION;   // vertex position 
    float4 Diffuse    : COLOR0;     // vertex diffuse color
    float2 Texture    : TEXCOORD0;
	float3 Normal : TEXCOORD1;
	float4 Data   : TEXCOORD2;
};

// Vertex Shader Program

VS_OUTPUT ShadowVS(VS_INPUT input)
{
   VS_OUTPUT output = (VS_OUTPUT)0;
 
	float3      Pos = 0.0f;
	float3      Normal = 0.0f;   
    float       LastWeight = 0.0f;
	float4 original = input.Position;
	float4 normal =   mul( input.Normal, mWorld );
   
    float BlendWeightsArray[4] = (float[4])input.BlendWeights;
    int   IndexArray[4]        = (int[4])input.BlendIndices;
 
	if(NumBones == 0)
	{
		Pos = mul( input.Position, mWorld );
		original = float4(Pos.xyz, 1.0f);
		Normal.xyz = normal.xyz;
	}
	else
	{
		for (int iBone = 0; iBone < NumBones-1; iBone++)
		{
			LastWeight = LastWeight + BlendWeightsArray[iBone];
       
			Pos += mul(input.Position, mWorldMatrixArray[iBone]) * BlendWeightsArray[iBone];
			Normal += mul(input.Normal, mWorldMatrixArray[iBone]) * BlendWeightsArray[iBone];
		}
		LastWeight = 1.0f - LastWeight;

		Pos += (mul(input.Position, mWorldMatrixArray[NumBones - 1]) * LastWeight);
		Normal += (mul(input.Normal, mWorldMatrixArray[NumBones - 1]) * LastWeight);
	
		original = float4(Pos.xyz, 1.0f);
	}
	output.Position = mul(original, mViewProj);

	output.Texture = input.Texture;
	output.Normal = Normal;
	output.Diffuse = input.Diffuse;
	output.Data =  original;
	
	return output;
}


float4 ShadowPS( VS_OUTPUT p ) : COLOR
{
	float4 Output = float4(1.0f,1.0f,1.0f,1.0f);
	float4 original = p.Data;
	float4 pos = mul(original, mViewProj);
	//float4 diffuse = tex2D(textureSampler, p.Texture);
	//Output = diffuse;
	//Output = pos.z / pos.w;
	Output = pos.z / 4096.0f;
	return Output;
}

technique ShadowMapEffect
{
    pass pass0
    {
		VertexShader = compile vs_3_0 ShadowVS();
   		PixelShader  = compile ps_3_0 ShadowPS();

		Lighting = false;
    }
}