uniform sampler2D Color0;   // diffuse color
uniform sampler2D Normal;   // eye space normal
uniform sampler2D Position; // eye space position

varying vec3 lightPos;
varying vec3 eyePos;
varying vec3 lightColor;
varying vec4 projPos;

varying float radius;
varying float extraParam;

//////////////////////////////////////////////////////////////////////////
// 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);

void main()
{
  vec2 texCoord = projPos.xy / projPos.w * .5 + .5;
  
  // normalize eye vector
  vec3 e = normalize( eyePos );
  
  // recover position from gbuffer
  float depth  = 10000.0 * ( dot( bitSh, texture2D( Position, texCoord ) ) );
  vec3 objPos = e * depth;
  
  // distance from light to geometry
  vec3 l = objPos - lightPos;
  float attenuation = length( l ) * radius;
  // discard if outside radius
  attenuation = 0.95 - attenuation;

  if( attenuation < 0.0 ) discard;

  //attenuation = max( attenuation, 0.0 );
  // quadric vs linear fall off
  attenuation *= attenuation;//
  
  // unpack normal
  vec3 n = texture2D( Normal, texCoord ).xyz;
  n = (255.0/128.0) * n - 1.0;
  
  // standard ndotl
  l = normalize( l );
  float ndotl = max( dot( n, -l ), 0.0 );

  vec3 h = -normalize( e + l );
  float ndoth = max( dot( n, h ), 0.0 );

  float spec = pow( ndoth, 32.0 );
  spec *= 0.33 * ndotl;

  // unpack color
  vec3 color = texture2D( Color0, texCoord ).xyz;
  
  // apply! factor of 2 to push the light
  color *= ( attenuation * ndotl ) * lightColor + spec;//vec3( spec, spec, spec );
  color *= 2.54;

  gl_FragColor =  vec4( color, 1.0 );//vec4( 1.0, 0.0, 1.0, 0.1 );//
}
