// define inputs from application
struct appin
{
  float4 position : POSITION;
  float3 normal   : NORMAL;
  float2 uv       : TEXCOORD0;
  float2 uv2      : TEXCOORD1;
  float4 blendIdx : BLENDINDICES;
  float4 blendWgt : BLENDWEIGHT;
};

// define outputs from vertex program
struct vertout
{
  float4 position : POSITION;
  float2 uv       : TEXCOORD0;
  float2 uv2      : TEXCOORD1;
  float4 color    : COLOR;
};

/* 
  Four-weight-per-vertex hardware skinning, one (directed) light
  The number of bones supported for this is program is 24 (vs_1_1)
*/ 
vertout main
( 
 appin v_in,
 
 // Support up to 24 bones of float3x4 
 uniform float3x4 worldMatrix3x4Array[24],
 //uniform float4x4 worldMatrix,
 uniform float4x4 viewProjectionMatrix, 
 uniform float4   lightPos, // is interpreted as directional
 uniform float4   lightDiffuseColour,
 uniform float4   ambient,
 uniform float4   diffuse) 
{ 
  vertout v_out;

  // transform by indexed matrix 
  float4 blendPos = float4(0,0,0,0); 
  int i; 

  /*float weight = 0;
  for(i=0;i<4;++i) {
    weight += v_in.blendWgt[i];
    }*/

  for(i=0;i<3;++i) { 
    blendPos += 
      float4(mul(worldMatrix3x4Array[v_in.blendIdx[i]], v_in.position).xyz, 1.0) * 
      v_in.blendWgt[i]; 
  } 

  // view / projection 
  v_out.position = mul(viewProjectionMatrix, blendPos); 

  // transform normal 
  float3 norm = float3(0,0,0); 

  for(i=0;i<4;++i) { 
    norm += mul((float3x3)worldMatrix3x4Array[v_in.blendIdx[i]], v_in.normal) * 
      v_in.blendWgt[i]; 
  } 
  norm = normalize(norm); 

  // directed light
  //float3 lightDir0 = mul(worldMatrix, lightPos).xyz;
  float3 lightDir0 = lightPos.xyz;
  // point light would be:
  //float3 lightDir0 = normalize(lightPos - blendPos);
  
  v_out.uv = v_in.uv;
  v_out.uv2 = v_in.uv2;
  ambient = 0.3.xxxx;
  v_out.color = ambient + 
    (saturate(dot(lightDir0, norm)) * lightDiffuseColour);

  //v_out.color = diffuse;
  //v_out.color = 1.0.xxxx;

  return v_out;
}    


