//
// Combine scene FBO+velocity map to get motion blurred end result
// Needs renderer.motion_blur.method at 4 and fs_filter1=<this_file>
// RvG, 25-2-09
//

float2 MB_GetVelocity(sampler2D velocityMap,float2 tc0,float texWidth,float texHeight)
// Get a velocity sample.
// Decodes the 8-bit encoding to get a real screen velocity.
{
  float4 velMap=tex2D(velocityMap,tc0);
  float2 vel;
  
  // Get X velocity. Red contains positive velocity upto 255 (=1.0 in shader terms)
  // Add negative velocity as well (either R or G will be non-zero)
  vel.x=(velMap.r*255.0/texWidth-velMap.g*255.0/texWidth);

  // Vertical (Y) velocity (positive)
  vel.y=(velMap.b*255.0/texHeight-velMap.a*255.0/texHeight);

  return vel;
}

float4 MotionBlur(sampler2D sceneMap,sampler2D velocityMap,float2 tc0,float texWidth,float texHeight)
{
  //float4 baseColor=tex2D(sceneMap,tc0); 
  float2 vel;

  // Get raw velocity
  vel=MB_GetVelocity(velocityMap,tc0,texWidth,texHeight);

  // Scale down filtering to avoid overdoing blur
  const float maxVel=10.0f;
  float l;
  l=length(vel);
  if(l>maxVel)
    vel*=maxVel/l;

//color.r=length(vel);
//color.gb=0;
//return float4(color,1);

  float3 color;
  // Enough motion to filter?
  if(abs(vel.x)<1.0/texWidth&&abs(vel.y)<1.0/texHeight)
  {
    color=tex2D(sceneMap,tc0).rgb;
  } else
  {
    // Sample along line
    const int numSamples=6;
    int    i;
    float2 tc=tc0;
    vel/=float(numSamples);
    for(i=0;i<numSamples;i++)
    {
      // Keep texture coordinates within 0..1
      tc=saturate(tc+vel);
      color+=tex2D(sceneMap,tc).rgb;
    }
    color/=numSamples;
  }

  // End color (average)
  return float4(color,1);
} 


float4 MotionBlur2(sampler2D sceneMap,sampler2D velocityMap,float2 tc0,float texWidth,float texHeight)
// Weighted to account for null-velocity samples
// Used to counter the echo effect on cars near fast-moving objects (road for example)
{
  float2 vel;

  float3 color;
  // Color when no blur is used
  float3 nonMBcolor;
  
  // Get unblurred sample
  nonMBcolor=tex2D(sceneMap,tc0).rgb;
    
  // Sample along line
  const int numSamples=8;
  const float oneOverSamples=1.0/float(numSamples);
  int    i;
  float2 tc=tc0;
  for(i=0;i<numSamples;i++)
  {
    vel=MB_GetVelocity(velocityMap,tc,texWidth,texHeight);
    if(abs(vel.x)+abs(vel.y)<0.005f)
    {
      // Don't blur in this signal
      //color=tex2D(sceneMap,tc0).rgb*(i+1);
      color+=nonMBcolor;
      // Reset color entirely
//        color=nonMBcolor*(i+1);
    } else
    {
      color+=tex2D(sceneMap,tc).rgb;
      // Keep texture coordinates within 0..1
      tc=saturate(tc+vel*oneOverSamples);
    }
  }
  color/=numSamples;

  // End color (average)
  return float4(color,1);
} 
