#define SAMPLE_RINGS 3
#define SAMPLES_PER_RING 8

uniform sampler2DRect backTex;
uniform sampler2DRect frontTex;

vec4 getBackNormalAndDepth(vec2 screenpos) {
  vec2 texcoord = gl_TexCoord[0].xy;
  vec4 src = texture2DRect( backTex, 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;
}

vec4 getNormalAndDepth( vec2 screenpos )
{
  vec2 texcoord = gl_TexCoord[0].xy;
  vec4 src = texture2DRect( frontTex, 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( frontTex, texcoord );
  vec3 col = src.xyz;
  float alpha = src.w;
  
  vec4 normalDepth = getNormalAndDepth( texcoord );
  vec4 backNormalDepth =getBackNormalAndDepth(texcoord);
  float backDepth = backNormalDepth.w;
  float backBaseDepth = backNormalDepth.w;
  float basedepth = normalDepth.w;
  float depth = normalDepth.w;

  vec3 normalsum = normalDepth.xyz;
  vec3 backnormalsum = backNormalDepth.xyz;

  if (true)
    {
      float r = sqrt(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 );
	    vec4 bnd = getBackNormalAndDepth(texcoord + vec2(du,dv) *r);

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

		if (abs(bnd.w - backBaseDepth) < 0.02) {
			backnormalsum+=bnd.xyz;
		}

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


    }
  backDepth /= (float)(SAMPLE_RINGS*SAMPLES_PER_RING);
  depth /=(float)(SAMPLE_RINGS*SAMPLES_PER_RING);
  vec3 normal = normalize(normalsum);
  vec3 backnormal = normalize(backnormalsum);

  float d= (abs(depth - backDepth));
  d = min(d, 1.0);
  d = max(d, 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,100.0);
  }; 
  backnormal.z*=-1;
  float fdb = pow(dot(backnormal, normal),0.2);
  fdb = max(0.0,fdb);
  
  vec3 backGlow =  vec3(1,1,1)*(-d*2);
  
  vec3 extraglow = vec3(1,1,1)*(1.0/(d*800.0));
  vec3 matcol = vec3(.0,.2,.3);//-vec3(1,1,1)*(basedepth*.5);
  l=.9+l*.1*d;
  vec3 lcol= vec3(l*matcol.x,l*matcol.y,l*matcol.z)+vec3(0.3,0.3,0.3)*specular + backGlow+extraglow;
  gl_FragDepth = basedepth;

  gl_FragColor = vec4( lcol*(1.4-pow(basedepth,3.2)) , alpha );

}
