//
// Diffuse+specular lighting+texture
// Uses parameter 'night' (set by Racer based on time-of-day) to determine mix
// of day and night textures.
//

#include "atmosphere.cg"

// Vertex to pixel shader structure
struct v2p
{
	float4 Position			: POSITION;
	//float3 Color 			: COLOR;
	float4 RayleighColor	: TEXCOORD2;
	float4 MieColor			: TEXCOORD3;
	float3 tc0              : TEXCOORD0;
	float3 Direction		: TEXCOORD1;
};

void main(
  // In
  in v2p IN,

  // Out
  out float4 outColor : COLOR,
  
  // Constants
  uniform sampler2D dayMap   : TEXUNIT0,
  uniform sampler2D nightMap : TEXUNIT1,
  uniform float3    eyePosW,
  uniform float3    lightDirection,
  uniform float3    lightColor,
  uniform float     atmosRayleigh,
  uniform float     atmosMie,
  uniform float     exposure,
  uniform float     clouds
)
{
  float3 skyColor;

  const float night=0.5;
  
  skyColor=GetSkyColor(lightDirection,IN.Direction,IN.RayleighColor,IN.MieColor,atmosRayleigh,atmosMie,lightColor);

  // Add textures
  float4 dayCol=tex2D(dayMap,IN.tc0);
  float4 nightCol=tex2D(nightMap,IN.tc0);

  // Cloud cover
  float factor=CloudCoverAlpha(dayCol.a,clouds);
  dayCol*=factor;
  // Star cover as well
  nightCol*=factor;
  
  //float3 finalColor=skyColor;

  // HDR toning of sky (should be done later for HDR FBO's)
  //skyColor=1.0-exp(-exposure*skyColor.rgb);
  
  //outColor.rgb=1.0-exp(-exposure*finalColor.rgb+(1.0-night)*dayCol.rgb-night*nightCol.rgb);
  //outColor.rgb=1.0-exp(-exposure*finalColor.rgb-night*nightCol.rgb)+(1.0-night)*dayCol.rgb*dayCol.a;
  //outColor.rgb=1.0-exp(-exposure*finalColor.rgb-night*nightCol.rgb-(1.0-night)*dayCol.rgb*dayCol.a);
  // Night & day texture
  //outColor.rgb=1.0-exp(-exposure*finalColor.rgb)+night*nightCol.rgb*nightCol.a+max(1.0-night*3,0)*dayCol.rgb*dayCol.a;
  //outColor.rgb=1.0-exp(-exposure*finalColor.rgb)+night*nightCol.rgb*nightCol.a+(1.0-night)*dayCol.rgb*dayCol.a;
  outColor.rgb=1.0-exp(-exposure*skyColor.rgb)+night*nightCol.rgb*nightCol.a+(1.0-night)*dayCol.rgb*dayCol.a;
  outColor.rgb=skyColor.rgb+night*nightCol.rgb*nightCol.a+(1.0-night)*dayCol.rgb*dayCol.a;
  // Day texture only
  //outColor.rgb=1.0-exp(-exposure*finalColor.rgb)+dayCol.rgb*dayCol.a;

  // Ignore textures
  //outColor.rgb=1.0-exp(-exposure*finalColor.rgb);
  //outColor.rgb=finalColor.rgb;
  // No blending
  outColor.a=1;
}
