#define SAMPLE_RINGS 5
#define SAMPLES_PER_RING 8

uniform sampler2DRect tex0;
uniform sampler2D envmap;

vec4 getNormalAndDepth( vec2 screenpos )
{
  vec2 texcoord = gl_TexCoord[0].xy;
  vec4 src = texture2DRect( tex0, screenpos );
  vec3 col = src.xyz;

  vec4 normal = vec4( col.xy*2.0-1.0, 0.0, col.z );
  normal.z = sqrt(1.03- dot(normal.xy,normal.xy));


  if (src.w < 0.5)
    {
      normal.z = 0.0;
    }


  
  return normal;
}

void main(void)
{
  vec2 texcoord = gl_TexCoord[0].xy;
  vec4 src = texture2DRect( tex0, texcoord );
  vec3 col = src.xyz;
  float alpha = src.w;
  
  vec4 normalDepth = getNormalAndDepth( texcoord );
  
  float basedepth = normalDepth.w;

  vec3 normalsum = normalDepth.xyz;

  if (true)
    {
      float r = sqrt(1.0-basedepth)*1;

      for (int i = 0; i < SAMPLE_RINGS; ++i) {
	float phi = 0;
	for( int x=0;x<SAMPLES_PER_RING;x++)
	  {
	    float du = sin((x / (float) SAMPLES_PER_RING) * 2.0 * 3.1415926535 + phi);
	    float dv = cos((x / (float)SAMPLES_PER_RING) * 2.0 * 3.1415926535 + phi);
      
	    vec4 nd = getNormalAndDepth( texcoord + vec2(du,dv) * r );


	    if ( abs( nd.w - basedepth ) < 0.02)
	      {
		normalsum += nd.xyz;
	      }

	  }
	r += 1.4325;
	phi += 3.1415926535*1.54312;
      }


    }

  vec3 normal = normalize(normalsum);
  vec2 envcoords;
  envcoords.x = (normal.x+1.0)/2.0 + (texcoord.x/1440.0)-.5;
  envcoords.y = (normal.y+1.0)/2.0 + (texcoord.y/900.0)-.5;



  vec4 env = texture2D( envmap,  envcoords);	

  normal.x += (env.x-0.5)*.3;
  normal.y += (env.y-0.5)*.3;
  normal.z += (env.z-0.5)*.3;
  normal = normalize(normal);


  env = vec4(0,0,0,0);
  
  float l = dot(normal,vec3(0.3,-0.4,0.86)) ; 
  float specular=0.0; 
  float specular2=0.0; 
  if(l>0.0) { 
    specular=pow(l,110.0)*2.0;
  }; 



  //       vec4 env = texture2D( envmap,  envcoords);

  vec3 matcol = vec3(1.8,1.8,1.8)*normal.z + env.xyz * pow(normal.z,5.0); //vec3(cos(normal.x),sin(normal.y),1.5);
  vec3 lcol=vec3(l*matcol.x,l*matcol.y,l*matcol.z)+vec3(0.7,0.7,0.7)*specular;




  gl_FragDepth = basedepth;

  gl_FragColor = vec4( lcol * (1.0-basedepth), alpha );

}
