uniform sampler2D tex0;
uniform sampler2D tex1;
uniform sampler2D tex2;
varying vec3 eye,light;

void main(void)
{
  vec3 useColor = vec3(1.0, 0.2, 0.0);
  vec3 halfv;
  float ndotl;

	vec4 col, texel = texture2D(tex0, gl_TexCoord[0].st);
  
  vec4 depth = texture2D(tex2, gl_TexCoord[0].st);
  
  vec3 n;
  
  useColor = texture2D(tex1, gl_TexCoord[0].st);

  if (length(texel) < 1.01)
  {
    gl_FragColor = vec4(0,0,0,1);
    return;
  }
  
  gl_FragColor = texel;
  //return;

  n = normalize((texel.xyz - 0.5) * 2.0);


	halfv = normalize(eye+light);
	ndotl = min(max(dot(n,halfv),0.0), 1.0);

  
			
  //col = vec4(vec3(useColor.r+ndotl*0.2,useColor.g+ndotl*0.2,useColor.b+ndotl*0.2)*max(ndotl,0.25),1.0);
  
  col = vec4(useColor * max(ndotl,0.1),1.0);
      
	//col=mix(vec4(0.0,0.0,0.1,1),col,clamp(300*ao*ao*ao,0.3,1.));
      
	col=mix(col,vec4(1.0, 1.0, 0.8, 1.0),pow(ndotl,50.0));
    
  //col = vec4(vec3(ndotl), 1.0);
  
  
  vec4 avgD = vec4(0);
  float counter = 0.0;
  
  for (int i = -7; i <= 7; i+=2)
  {
    for (int j = -7; j <= 7; j+=2)
    {
        avgD += texture2D(tex2, gl_TexCoord[0].st + vec2(i, j) * 0.01);
        counter++;
    }
  }
  avgD /= counter;
  
  float ssao = 1.0 - /*abs*/(avgD - depth);
  
  ssao = min(1.0, max(0.0, ssao));

  //ssao = 1.0;
  
  ssao = pow(ssao, 2.0);

	gl_FragColor = vec4(vec3(col.rgb * ssao * min(1.0, pow(depth.r * 5.0, 1.0))), 1.0);
  
  //gl_FragColor = vec4(vec3(ssao), 1.0);
  
  //gl_FragColor = depth;
  //gl_FragColor = vec4(useColor, 1.0);
}
