varying vec4 ViewPos;
varying vec3 normal;
varying vec3 tangent;
varying vec3 binormal;
varying vec3 taneye;
varying vec3 up;

uniform sampler2D Color0; // celshadey
uniform sampler2D Normal; // normal map with bump!


//////////////////////////////////////////////////////////////////////////
// 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(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);
const vec4 bitMsk = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);

void main()
{
  vec4 color, norm, packpos;

  // want eye linear depth
  float pos = 1.0 - ViewPos.z / 10000.0;

  // normal is offset
  vec3 tangentspacenormal = texture2D( Normal, gl_TexCoord[0].st ).xyz;
  // unpack
  tangentspacenormal = tangentspacenormal * 2.0 - 1.0;
  // transform
  /* normalized ver */
  vec3 t1 = normalize( tangent );
  vec3 b1 = normalize( binormal );
  vec3 n1 = normalize( normal );
  norm.x = dot( vec3( t1.x, b1.x, n1.x ), tangentspacenormal );
  norm.y = dot( vec3( t1.y, b1.y, n1.y ), tangentspacenormal );
  norm.z = dot( vec3( t1.z, b1.z, n1.z ), tangentspacenormal );
  norm.w = 1.0;

  // weird lighting thing
  vec2 texCoord;
  vec3 e = normalize( ViewPos.xyz );
  // v coord is normal dot up for a lighting like effect
  texCoord.y = max( dot( norm.xyz, up ), 0.0 ) * 0.45 + 0.5;
  // u coord is normal dot eye for cel-shading like effect
  texCoord.x = max( dot( norm.xyz, -e ), 0.0 ) * texCoord.y * 0.9+ 0.1;
 
  // modulate with texture color
  color = texture2D( Color0, texCoord );

  // pack //////////////////////////////////////////////////////////////////////////////////////////
  packpos = fract( pos * bitSh );
  packpos -= packpos.xxyz * bitMsk;
  
  // write output //////////////////////////////////////////////////////////////////////////////////
  gl_FragData[0] = color;
  gl_FragData[1] = norm * .5 + .5;
  gl_FragData[2] = packpos;
}