/***************************
Diffuse/ambient/specular lighting + diffuse texture, envMap and fresnel term
Per-fragment lighting
****************************/
void main (
  // From Vertex
  float2 tc0    : TEXCOORD0,
  float3 normal : TEXCOORD1,
  float3 inPosW : TEXCOORD2,
  //Textures
  uniform sampler2D   baseMap: TEXUNIT0,
  uniform samplerCUBE envMap : TEXUNIT1,
  // Out
  out float4 outColor : COLOR,
  //From Program
  uniform float3 lightDirection,
  uniform float3 eyePosW,
  uniform float3 lightColor
  )

{
  const float Ka = 0.68; 0.2;
  const float Kd = 0.8; 0.8;
  const float Ks = 1.0;
  const float shininess = 1250 ;800;
  
  float4 baseCol=tex2D(baseMap,tc0);
  
  float3 N=normalize(normal);
  
  // Compute the incident, reflected, and refracted vectors for fresnel
  float3 II;
  II=inPosW-eyePosW;
  II=normalize(II);
  
  // Compute the specular term
  float3 L=lightDirection;
  float3 V=normalize(eyePosW-inPosW);
  float3 H=normalize(L+V);
  

  // Envmap
  float3 R=reflect(-V,N);

  
  float3 reflectedColor=texCUBE(envMap,R.xyz);
  
  // Compute diffuse term
  float diffuseLight=max(dot(N,L),0);
  float3 diffuse=(Kd*diffuseLight+Ka)*baseCol.rgb;			// Ambient+diffuse

  float specularLight;
  if (diffuseLight <= 0)
    specularLight=0;
  else
    specularLight=pow(max(dot(N,H),0),shininess);

  float3 specular=Ks*specularLight*lightColor;

  // Compute reflection factor according to Fresnel
  float fresnelBias = 0.05; //0.05;
  float fresnelScale = 2.0;
  float fresnelPower = 8.0;
  float3 reflectionFactor=min(fresnelBias+fresnelScale*pow(1+dot(II,N),fresnelPower)+baseCol.a,1);

  // Output total color
  //outColor.rgb=brightNess;
  outColor.rgb=lerp(diffuse,reflectedColor,reflectionFactor)+specular;//*brightNess;
  outColor.a=1.0;
}