//
// Fresnel, diffuseMap (texture), cubeMap (env), hemisphere, bumpmap
// Per-fragment lighting
// Expects diffuseMap in first layer (TEXUNIT0) and envmap (cubemap) in TEXUNIT1 (2nd layer in Racer shader)
//

float3 expand(float3 v) { return (v-0.5)*2.0; }

void main(
  // In
  float3 inPosition         : POSITION,
  float2 tc0                : TEXCOORD0,
  float3 inNormal	        : TEXCOORD1,
  //float3 inPosW             : TEXCOORD2,
  float  inReflectionFactor : TEXCOORD3,
  float3 R                  : TEXCOORD4,
  float3 lightDirTS         : TEXCOORD5,          // Modified light direction in tangent space
  //float3 normalOrg          : COLOR,
  //float3 inEyePosW          : COLOR,
  float3 inEyeDir           : TEXCOORD6,          // Varying over polygon
  // Out
  out float4 outColor : COLOR,
  uniform sampler2D   baseMap   : TEXUNIT0,
  uniform samplerCUBE envMap    : TEXUNIT1,
  uniform sampler2D   normalMap : TEXUNIT2,
  uniform float3 lightDirection,
  uniform float3 lightColor
  //uniform float3 eyePosW
)
{
  const float Ka=0.25;
  const float Kd=0.85;
  const float Ks=1.0;
  const float shininess=80.0;
 
  // Diffuse map
  float3 baseCol=tex2D(baseMap,tc0).rgb;
  //baseCol=1;

  // Bumpmap (delta from original normal)
  // Assume its normalized
  float3 N=expand(tex2D(normalMap,tc0).xyz);

  // Compute diffuse term (in tangent space)
  float3 L=lightDirTS;
  float  diffuseLight=max(dot(N,L),0);
  float3 diffuse=(Kd*diffuseLight+Ka)*baseCol*lightColor;			// Ambient+diffuse

  // Compute the specular term (in tangent space!)
  float3 V=normalize(inEyeDir);
  float3 H=normalize(lightDirTS+V);		// Use world light dir
  
  float specularLight;
  if (diffuseLight<=0)
    specularLight=0;
  else
    specularLight=pow(max(dot(N,H),0),shininess);

  float3 specular=Ks*lightColor*specularLight;

  // Envmap
  //float3 R=reflect(inEyeDir,N);
  float3 envColor=texCUBE(envMap,R).rgb;

/*
  // Hemisphere lighting
  float cosTheta=dot(N,lightDirN);
  float a=0.5+0.5*cosTheta;
  const float3 groundColor=float3(0.2,0.17,0.14);
  const float3 skyColor=float3(0.7,0.83,0.95);
  float3 hemiColor=lerp(groundColor,skyColor,a);
  diffuse*=hemiColor*1.5;
*/

/*
  // Image-based lighting; use envmap to colorize diffuse
  // Currently too sharp
  float3 imgColor=texCUBE(envMap,N);
  diffuse*=imgColor; //+0.5;
*/

  // Output total color
  //outColor.rgb=diffuse+specular;
  //outColor.rgb=specular;
  //outColor.rgb=inReflectionFactor;
  //outColor.rgb=envColor;
  outColor.rgb=lerp(envColor,diffuse+specular,inReflectionFactor);
  //outColor.rgb=inEyeDir; //imgColor;
  outColor.a=1.0;
}
