// CSM Shadowmapping, no bloom
// HDR version

#include "../common/constants.cg"
#include "../common/hdr.cg"
#include "bloom.cg"

struct VertOut
{
  float4 pos : POSITION;
  float4 col : COLOR0;
  float2 tc0 : TEXCOORD0;
};

struct FragOut
{
  float4 col : COLOR;
};

float BlurTexture(sampler2D tex, float2 vin, float blur)
{
  float sum=0;
  const float blurT2=2.0*blur;
  const float blurT3=3.0*blur;
  const float blurT4=4.0*blur;
 
  // blur in y (vertical)
  // take nine samples, with the distance blur between them
  sum += tex2D(tex, float2(vin.x - blurT4, vin.y)).a * 0.05;
  sum += tex2D(tex, float2(vin.x - blurT3, vin.y)).a * 0.09;
  sum += tex2D(tex, float2(vin.x - blurT2, vin.y)).a * 0.12;
  sum += tex2D(tex, float2(vin.x - blur, vin.y)).a * 0.15;
  sum += tex2D(tex, float2(vin.x, vin.y)).a * 0.16 * 2.0f;
  sum += tex2D(tex, float2(vin.x + blur, vin.y)).a * 0.15;
  sum += tex2D(tex, float2(vin.x + blurT2, vin.y)).a * 0.12;
  sum += tex2D(tex, float2(vin.x + blurT3, vin.y)).a * 0.09;
  sum += tex2D(tex, float2(vin.x + blurT4, vin.y)).a * 0.05;
  
  sum += tex2D(tex, float2(vin.x, vin.y - blurT4)).a * 0.05;
  sum += tex2D(tex, float2(vin.x, vin.y - blurT3)).a * 0.09;
  sum += tex2D(tex, float2(vin.x, vin.y - blurT2)).a * 0.12;
  sum += tex2D(tex, float2(vin.x, vin.y - blur)).a * 0.15;
  //sum += tex2D(tex, float2(vin.x, vin.y)).a * 0.16;
  sum += tex2D(tex, float2(vin.x, vin.y + blur)).a * 0.15;
  sum += tex2D(tex, float2(vin.x, vin.y + blurT2)).a * 0.12;
  sum += tex2D(tex, float2(vin.x, vin.y + blurT3)).a * 0.09;
  sum += tex2D(tex, float2(vin.x, vin.y + blurT4)).a * 0.05;
  
  return sum*0.5f;
}

float BlurTexture0(sampler2D tex, float2 vin, float blur)
// Does not smooth
{
  // blur in y (vertical)
  // take nine samples, with the distance blur between them
  return tex2D(tex, float2(vin.x, vin.y)).a;
}

FragOut main(
  VertOut vin,
  uniform sampler2D tex0 : TEXUNIT0,
  // Z in TEXUNIT5
  //uniform sampler2D bloomMap1   : TEXUNIT2,
  //uniform sampler2D bloomMap2   : TEXUNIT3,
  //uniform sampler2D bloomMap3   : TEXUNIT4,
  uniform sampler2D shadowMap   : TEXUNIT3,
  //uniform float smblurAmount,
  uniform float exposure
)
{
  FragOut fout;

  float4 ambientColor,
         sdColor,                 // Specular+diffuse
         color;

  // Original color
  ambientColor=tex2D(tex0,vin.tc0);
  sdColor=tex2D(shadowMap,vin.tc0);
  
  float shadowAmount=BlurTexture(shadowMap, vin.tc0, smBlurAmount);
  color=ambientColor+shadowAmount*sdColor;

/*  
  // Bloom
  float4 bloomColor=BloomCombineMaps3(bloomMap1,bloomMap2,bloomMap3,vin.tc0);
  color=BloomMix(color,bloomColor);
*/

  // HDR -> LDR tonemap
  fout.col=ToneMapHDR(color,exposure);

  return fout;
} 
