uniform sampler2D Color0;
uniform sampler2D Position;
uniform sampler2D Falloff;

uniform mat4 MotionMatrix;
varying vec3 eyePos;

//////////////////////////////////////////////////////////////////////////
// method to pack a f32 into an rgba8 from gamedev.net forums
//
// http://www.gamedev.net/community/forums/topic.asp?topic_id=463075
//
//////////////////////////////////////////////////////////////////////////

const vec4 bitSh = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);//
uniform float Timer;

const float offsetMax = 4 / 1024.0;

void main()
{
  // recover position from gbuffer
  float depth = ( dot( bitSh, texture2D( Position, gl_TexCoord[0].st ) ) );//
  vec4 oldPos = vec4( gl_TexCoord[0].s * 2.0 - 1.0,
                      gl_TexCoord[0].t * 2.0 - 1.0,
                      depth,
                      1.0 );

  // transform position to previous
  oldPos  = MotionMatrix * oldPos;
  vec2 oldScreen = oldPos.xy / oldPos.w * 0.5 + 0.5;
  vec2 delta = oldScreen - gl_TexCoord[0].st;
  //delta = clamp( delta, -offsetMax, offsetMax );

  float mag = sqrt( dot( delta, delta ) );

  delta /= 64.0;

  vec2 texCoord = gl_TexCoord[0].st;

  float attenuation = 1.0 - texture2D( Falloff, texCoord ).r;

  vec3 color = texture2D( Color0, texCoord ).rgb;
  vec3 colorsharp = color;
  texCoord += delta;
  color +=  texture2D( Color0, texCoord ).rgb;
  texCoord += delta;
  color +=  texture2D( Color0, texCoord ).rgb;
  texCoord += delta;
  color +=  texture2D( Color0, texCoord ).rgb;
  texCoord += delta;
  color +=  texture2D( Color0, texCoord ).rgb;
  texCoord += delta;
  color +=  texture2D( Color0, texCoord ).rgb;
  texCoord += delta;
  color +=  texture2D( Color0, texCoord ).rgb;
  texCoord += delta;
  color +=  texture2D( Color0, texCoord ).rgb;
  texCoord += delta;
  color +=  texture2D( Color0, texCoord ).rgb;
  texCoord += delta;
  color +=  texture2D( Color0, texCoord ).rgb;
  texCoord += delta;
  color +=  texture2D( Color0, texCoord ).rgb;
  texCoord += delta;
  color +=  texture2D( Color0, texCoord ).rgb;
  texCoord += delta;
  color +=  texture2D( Color0, texCoord ).rgb;
  texCoord += delta;
  color +=  texture2D( Color0, texCoord ).rgb;
  texCoord += delta;
  color +=  texture2D( Color0, texCoord ).rgb;

  float luma = dot( vec3( .299, .587, .114 ), color );
  luma /= 15.0; // scale
  luma += 0.5;//luma = max( luma, 0.2 );

  mag = min( 15.0, mag );
  mag = 16.0 - mag;

  attenuation *= luma;

  color = mix( colorsharp, color / mag, mag );
  color += colorsharp;
  //color = mix( colorsharp, vec3( 0.0, 1.0, 0.0 ), attenuation );
  gl_FragColor = vec4( color, 1.0 );
}