//
// CSM Shadowmapping + Bloom + Motion blur
// HDR version
//

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

// AO tests - normally undefine this
//#define OUTPUT_NORMALS
// Show velocity instead of actual image?
//#define DEV_SHOW_VELOCITY
// Show normals instead of actual image?
//#define DEV_SHOW_NORMALS

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

struct FragOut
{
  float4 col : COLOR;
};

float BlurTexture(sampler2D tex, float2 vin, float blur, sampler2D depthMap)
// With Z sampling
{
  return tex2D(tex,vin).a;
}

FragOut main(
  VertOut vin,
  uniform sampler2D sceneMap    : TEXUNIT0,
  uniform sampler2D velocityMap : TEXUNIT1,
  /// Z in TEXUNIT5
  uniform sampler2D bloomMap1   : TEXUNIT2,
  uniform sampler2D bloomMap2   : TEXUNIT3,
  uniform sampler2D bloomMap3   : TEXUNIT4,
  uniform float  alpha,          // Motion blur blending
  uniform float2 resolution,
  uniform float  exposure
)
{
  FragOut fout;

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

  //color=tex2D(sceneMap,vin.tc0);
  color.rgb=MotionBlur3(sceneMap,velocityMap,vin.tc0,resolution.x,resolution.y);

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

// Show the 3 bloom stages and the end-result in 1 view
/*if(vin.tc0.y>0.5)
{
 if(vin.tc0.x>0.666)color=tex2D(bloomMap3,vin.tc0);
 else if(vin.tc0.x>0.333)color=tex2D(bloomMap2,vin.tc0);
 else color=tex2D(bloomMap1,vin.tc0);
}*/

  // HDR -> LDR tonemap
  //fout.col=Desaturate(ToneMapHDR(color,exposure),0.2);
  fout.col.rgb=ToneMapHDR(color.rgb,exposure);
  fout.col.a=alpha;

#ifdef OUTPUT_NORMALS
  fout.col.rgb=tex2D(velocityMap,vin.tc0);
#endif

#ifdef DEV_SHOW_VELOCITY
  // Visualize velocity
  float2 vel;
  vel=MB_GetVelocity_SingleChannel(velocityMap,vin.tc0,resolution.x,resolution.y);
  vel*=10;             // Enhance contrast
  fout.col.rg=vel;
  fout.col.b=0;
#endif

#ifdef DEV_SHOW_NORMALS
  // Visualize normals
  float3 N;
  N=MotionBlurGetNormal(velocityMap,vin.tc0);
  fout.col.rgb=N;
#endif

  return fout;
} 
