//
// Fresnel, diffuseMap (texture), cubeMap (env)
// Per-fragment lighting
// The fresnel calculation determines the amount of reflection mixing
// 17-09-08: Created (Ruud van Gaal)
//

void main(
	  float4 inPosition : POSITION,
	  float3 inNormal   : NORMAL,
	  float2 inTC0      : TEXCOORD0,

	  // Output
        out float4 outPosition      : POSITION,
	  out float2 outTC0           : TEXCOORD0,
	  out float3 outNormal        : TEXCOORD1,
	  out float3 outPosW          : TEXCOORD2,
	  out float  reflectionFactor : TEXCOORD3,
	  out float3 R                : TEXCOORD4,
  
  // Params
  uniform float4x4 modelViewProj,
  uniform float4x4 modelMatrix,
  uniform float3   eyePosW
)
{

  float fresnelBias=0.1;
  float fresnelScale=0.9;
  float fresnelPower=4.0;
  
  // Transform vertex
  outPosition = mul(modelViewProj,inPosition);
  outPosW = mul(modelMatrix,inPosition).xyz;			// Object space to eye space with model transform
  
  // Pass texcoords
  outTC0 = inTC0;

  // Transform normal with model transformation
  float3 N = mul((float3x3)modelMatrix, inNormal);
  N=normalize(N);
  outNormal=N;

  // Fresnel
  // 
  // Compute position and normal in world space
  float3 posW=mul(modelMatrix,inPosition).xyz;
  float3 Nwc=mul(float3x3(modelMatrix),inNormal);

  // Compute the incident, reflected, and refracted vectors
  float3 I;
  I=posW-eyePosW;
  R=reflect(I,Nwc);
  I=normalize(I);

  // Compute reflection factor according to Fresnel
  reflectionFactor=1.0-(fresnelBias+fresnelScale*pow(1+dot(I,Nwc),fresnelPower));
}