uniform sampler2D colorTexture;
uniform sampler2D depthTexture;
varying vec2 pos;

uniform int mode;
uniform float thickness;
uniform float strength;
uniform vec2 screensize;

void main(void)
{
	vec4 color = texture2D(colorTexture, gl_TexCoord[0].st);
  vec4 realDepth = texture2D(depthTexture, gl_TexCoord[0].st);

  vec2 size = screensize * 3.5;

	float factor = 1.0;
  
  //float thickness = realDepth.r;
  
  thickness = 2.0;

	float stepX = thickness / (size.x);
	float stepY = thickness / (size.y);

	vec2 offset[9];
	vec3 kernel[6];

	offset[0] = vec2(-stepX, -stepY); offset[1] = vec2(0.0, -stepY); offset[2] = vec2(stepX, -stepY);
	offset[3] = vec2(-stepX,    0.0); offset[4] = vec2(0.0,    0.0); offset[5] = vec2(stepX,    0.0);
	offset[6] = vec2(-stepX,  stepY); offset[7] = vec2(0.0,  stepY); offset[8] = vec2(stepX,  stepY);


	kernel[0] = vec3(-1.0, 0.0, +1.0);
	kernel[1] = vec3(-2.0, 0.0, +2.0);
	kernel[2] = vec3(-1.0, 0.0, +1.0);

	kernel[3] = vec3(-1.0, -2.0, -1.0);
	kernel[4] = vec3( 0.0,  0.0,  0.0);
	kernel[5] = vec3(+1.0, +2.0, +1.0);

	vec4 texel;

	vec3 sobel[2];
	sobel[0] = vec3(0.0);
	sobel[1] = vec3(0.0);

	for (int j = 0; j < 2; j++)
	{
		for (int i = 0; i < 9; i++)
		{
			texel = texture2D(depthTexture, gl_TexCoord[0].st + offset[i]);
      float v = 0.0;
      if (mode == 0)
      {
        v = texel.a;
      }
      else
      {
        v = texel.r;
      }
      
      sobel[j] += v * 200.0 * kernel[3 * j + i / 3][int(mod(float(i), 3.0))];
		}
	}

	vec3 sb = clamp(pow(
                        pow(sobel[0], vec3(2.0)) + pow(sobel[1], vec3(2.0)),
                          vec3(1.0))
                          , 0.0, 1.0);

  //texel = texture2D(depthTexture, gl_TexCoord[0].st);
  
	//gl_FragColor = vec4(mix(color, color * (1.0 - sb), 0.8), color.a);
  
  vec4 contourColor = vec4(0.0, 0.0, 0.0, 1.0);
  
  //float depth = pow(1.0 - realDepth.r, 0.1);
  float depth = 1.0;  
    
  gl_FragColor = vec4(mix(color.rgb, contourColor.rgb, contourColor.a * sb * depth * strength), color.a);
  
  //gl_FragColor = vec4(vec3(sb.rgb), 1.0);
  //gl_FragColor = vec4(mix(color.rgb, contourColor.rgb, sb.rgb), 1.0);
  //gl_FragColor = vec4(vec3(color.rgb), 1.0);


  //gl_FragColor = vec4(vec3(depth), 1.0);
  //gl_FragColor = vec4(sb.rgb, 1.0);
}
