//
// 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,
#ifdef CSM_MRT
  out float4 outShadow: COLOR1,
#endif
  
  // Constants
  uniform sampler2D dayMap   : TEXUNIT0,
  uniform sampler2D nightMap : TEXUNIT1,
  uniform float3    eyePosW,
  uniform float3    lightDirection,
  uniform float3    lightColor,
  uniform float3    lightAmbient,
  uniform float     atmosRayleigh,
  uniform float     atmosMie,
  uniform float     exposure,
  uniform float     clouds,
  uniform float     sunny,
  uniform float     night
)
{
  float3 skyColor;

  skyColor=GetSkyColorAtm(lightDirection,IN.Direction,IN.RayleighColor,IN.MieColor,atmosRayleigh,atmosMie,lightColor,lightAmbient,sunny);

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

  // Cloud cover modifies alpha
  dayCol.a=CloudCoverAlpha(dayCol.a,clouds);
  //dayCol*=CloudCoverAlpha(dayCol.a,clouds)*float4(lightAmbient,1);
  // Star cover as well
  //nightCol*=CloudCoverAlpha(nightCol.a,clouds);

  // Atmosphere outside
  float3 atmosColor=skyColor;
  // Clouds are much closer than the outer atmosphere
  float3 cloudColor=dayCol.rgb;

  // General light
  //cloudColor*=lightAmbient;
  cloudColor*=(lightColor+lightAmbient);
  cloudColor*=clouds;

  // Night color - note these are stars, thus far away and part of the outer atmosphere!
  nightCol.rgb*=lightAmbient.rgb;
  //nightCol.rgb*=10;
  atmosColor+=nightCol*night;
  
  // Mix of inner & outer atmosphere
  float3 mixColor;
  float  mixClouds,mixAtmos;

  // Determine mix of atmosphere and inner ring of objects (clouds)
  mixClouds=dayCol.a;
  mixAtmos=max(1.0-mixClouds,0);
  mixColor=mixClouds*cloudColor+mixAtmos*atmosColor;

#ifdef CSM_MRT
  outShadow.rgba=float4(0,0,0,0);
#endif
  // Night & day texture
  //outColor.rgb=(1.0-night)*(skyColor.rgb+dayCol.rgb*dayCol.a) +       // Daylight
  //             night*(skyColor.rgb+nightCol.rgb*nightCol.a);          // Nighttime
  outColor.rgb=mixColor;

  // No blending normally
  outColor.a=dayCol.a;
}
