uniform sampler2D myRGBAMask;
uniform sampler2D myDepthMask;
uniform sampler2D myDepthInput;
uniform vec4 cUVMax;
uniform vec2 cNearFar;
uniform float rPerspectiveness;

float ReadZ(float rZ)
{
  float 
    dist = gl_TexCoord[2].z / (rZ - gl_TexCoord[2].y);

  float 
    distOrtho = mix(cNearFar.x, cNearFar.y, rZ);

  return mix(distOrtho, dist, rPerspectiveness);
}

void main(void)
{
  vec4
    cRGBAMax = vec4(0.0);

  for (int iY = -1; iY <= 1; iY++)
  {
    for (int iX = -1; iX <= 1; iX++)
    {
      vec2
        cVec = vec2(float(iX),float(iY)) + vec2(1.0 / 3.0);

      vec4
        cUV = gl_TexCoord[0] + gl_TexCoord[1] * cVec.xyxy;

      // Border check
      if (cUV.x < cUVMax.x &&
          cUV.y < cUVMax.y &&
          cUV.z < cUVMax.z &&
          cUV.w < cUVMax.w)
      {
        float
          rZMask = ReadZ(texture2D(myDepthMask, cUV.xy).r),
          rZInput = ReadZ(texture2D(myDepthInput, cUV.zw).r);

        float
          rZDiff = rZMask - rZInput;

        float
          rBlurScale = mix(1.0, gl_TexCoord[2].x, clamp(rZDiff * gl_TexCoord[2].w, 0.0, 1.0));

        vec4
          cSample = vec4(rBlurScale) * texture2D(myRGBAMask, gl_TexCoord[0].xy + gl_TexCoord[1].xy * cVec);

        cRGBAMax = max(cRGBAMax, cSample);
      }
    }
  }
  gl_FragColor = min(vec4(1.0), cRGBAMax);
}

