//
// Motion blur pixel shader
// From: http://developer.nvidia.com/docs/IO/8230/GDC2003_OpenGLShaderTricks.pdf
// RvG, 28-11-2008
//

//#include "motion_blur_const.cg"

struct v2f {
  float4 P          : TEXCOORD0;
  float4 Pprev      : TEXCOORD1;
  float  scale      : TEXCOORD2;
  float  dt         : TEXCOORD3;
};

void main(
  v2f IN,
  
  // Out
  out float4 outColor : COLOR
)
{
  // Aliases
  float4 P=IN.P;
  float4 Pprev=IN.Pprev;
  
  // do divide by W -> NDC coordinates
  P.xyz/=P.w;
  Pprev.xyz/=Pprev.w;
  // Calculate window space velocity
  float2 vel;
  float2 halfWinSize=float2(1024.0/2.0,768.0/2.0);
  //vel=halfWinSize.xy*(P.xy-Pprev.xy);
  // Negated
  vel=halfWinSize.xy*(Pprev.xy-P.xy);

  vel*=IN.scale;
  
  // Velocity based on 60Hz vsync'd
  // We have 4 color values with 8 bits (0..255)
  // The pixel can move in a circle with radius 255. If it goes faster
  // than that, it is clamped to movement=127.
  // To make maximum use of the 2D movement, all 4 color channels are used.
  const float virtualShutterFrequency=24.0;			// Simulate film
  const float dbgCamera=1.0;        // >1.0 = visualize better
  const float cameraFactor=dbgCamera*(1.0/(IN.dt*virtualShutterFrequency));
  
  // Range of velocity being stored
  const float velScale=1.0;            // Normally 1, if >1, throw away precision
  const float divider=255.0*velScale;
  
  // In Red, put the positive X velocity, maxed out at 255 pixels movement
  // For a 60Hz screen emulating a 30Hz, scale the velocity the get motion blur
  // as if it was a 30Hz camera.
  outColor.r=cameraFactor*max(0,min(vel.x,255))/divider;
  // In green, put the negative velocity
  outColor.g=-cameraFactor*min(0,max(vel.x,-255))/divider;
  // In B and A, put the vertical velocity
  outColor.b=cameraFactor*max(0,min(vel.y,255))/divider;
  outColor.a=-cameraFactor*min(0,max(vel.y,-255))/divider;
  
  // Debug
  //outColor=float4(1,0,0,1);
}
