//
// Standard: dynamic model with diffuse map, plus specularity control in diffuse map's alpha channel
//

#include "atmosphere.cg"
#include "lighting.cg"
#include "fresnel.cg"
#include "shadowmapping.cg"

// Vertex to pixel shader structure
struct v2p
{
  float  extinction     : TEXCOORD6;
  float2 tc0            : TEXCOORD0;
  float3 Direction      : TEXCOORD1;
  float4 RayleighColor  : TEXCOORD2;
  float4 MieColor       : TEXCOORD3;
  float4 Position       : TEXCOORD4;    // For fragment shader
  float3 normal         : TEXCOORD5;
};

void main(
  // In
  in v2p IN,

  // Out
  out float4 out0 : COLOR0,
#ifdef CSM_MRT
  out float4 out1 : COLOR1,
#endif
  
  // Constants
  uniform sampler2D   baseMap : TEXUNIT0,
  uniform float3    lightDirection,
  uniform float3    lightColor,
  uniform float3    lightAmbient,
  uniform float3    eyePosW,
  uniform float     atmosRayleigh,
  uniform float     atmosMie,
  uniform float3    Ke,
  uniform float3    Ka,
  uniform float3    Kd,
  uniform float3    Ks,
  uniform float     Kr,
  uniform float     shininess,
#ifdef CSM
  uniform sampler2D shadowArray  : TEXUNIT7,
  uniform float4x4  smTexMatArray[SM_MAX_SPLITS],  
  uniform float     smSplits, 
#endif
  uniform float     sunny,
  uniform float     exposure
)
{
  float3 skyColor;
  
  float3 N=normalize(IN.normal);

#ifdef CSM
  // Output shadowing
  float shadow = GetShadowFactor(IN.Position, IN.normal,shadowArray, smTexMatArray, smSplits, lightDirection)*sunny;
  //outShadow.rgb = N;
#else
  const float shadow=1;
#endif

  // Get sky gradient color
  skyColor.rgb=GetSkyColor(lightDirection,IN.Direction,IN.RayleighColor,IN.MieColor,atmosRayleigh,atmosMie,lightColor,lightAmbient);

  // Get base texture color
  float4 baseCol=tex2D(baseMap,IN.tc0);

  // Lighting
  float3 ambient,diffuse,specular;
  LightingSun(Ke,Ka,Kd,Ks,shininess,lightDirection,lightColor,lightAmbient,IN.Position,N,eyePosW,
    ambient,diffuse,specular);
	
  // Note that specularity is controlled through the first texture's alpha channel
  float3 litColor=baseCol*diffuse+specular*baseCol.a;
  float3 shadowColor=baseCol*(ambient+Ke);
  
#ifdef CSM_MRT
  // Mix sky with texture color based on atmospheric influence
  out0.rgb=lerp(skyColor,shadowColor,IN.extinction);
  //outShadow.rgb=lerp(skyColor,litColor,IN.extinction);
  out1.rgb=litColor*IN.extinction;

  out1.a=shadow;
  
  // Blending?
  out0.a=1; //baseCol.a;
#else
  // Mix sky with texture color based on atmospheric influence
  out0.rgb=lerp(skyColor,shadowColor+litColor*shadow,IN.extinction);
  // Blending
  out0.a=baseCol.a;
#endif
}
