uniform sampler2D tex0;
uniform sampler2D tex1;

uniform vec2 size;

uniform float distance;
uniform float dof;    
uniform float amount;

uniform float dp;

uint wang_hash(uint seed)
{
    seed = (seed ^ 61) ^ (seed >> 16);
    seed *= 9;
    seed = seed ^ (seed >> 4);
    seed *= 0x27d4eb2d;
    seed = seed ^ (seed >> 15);
    return seed;
}

float rand(uint value)
{
	return float(wang_hash(value)) * (1.0 / 4294967296.0);
}

void main(void)
{
  vec2 texCoord = gl_FragCoord.xy/size;
  
	vec4 _color = texture2D(tex0, texCoord);
	vec4 _depth = texture2D(tex1, texCoord);
  
  /*float f= 16.0;
  float n = 0.1;
  float z = (2 * n) / (f + n - _depth.r * (f - n));
  
  float depth = clamp(1.0 - (abs(z-distance) / dof) * 2.0, 0.0, 1.0);*/
  //float depth = clamp((1.0-texture2D(tex1, texCoord).r) * 100.0, 0.0, 1.0);
  
  float depth = texture2D(tex1, texCoord).r;
  depth = 1.0 - smoothstep(dp, 1.0, depth);


  vec4 sample;
  vec4 accum = 0.0;
  float sum = 0.0;
  
  vec2 offset = vec2(0,0);
  
  for (uint i = 0; i < 500; i++)
  {
    offset = (-1.0 + 2.0 * vec2(rand(81*i+0), rand(81*i+13))) * 0.012 * amount * (1.0 - depth);
    sample = texture2D(tex0, gl_TexCoord[0].st + offset);
    accum += sample;
    sum++;  
  }
  accum /= sum;
  
  //depth = z;

	//gl_FragColor = vec4(1.0, 0.0, 0.0, fog);
  //gl_FragColor = vec4(1,1,1,fog);
  gl_FragColor = vec4(vec3(accum.rgb), 1);
  //gl_FragColor = vec4(1,1,0,1);  
}
