//Tutorial source: http://coding-experiments.blogspot.co.at/2010/06/edge-detection.html
#version 330 core

#define WIDTH 1800.0
#define HEIGHT 1000.0

#define INTENSITY 5.0

in vec2 texCoords;

uniform sampler2D depthTex;

layout(location = 0) out vec4 fragColor;

float threshold (in float lowerBound, in float upperBound , in float value) {
    if (value < lowerBound) {
        return 0.0;
    }
	if (value > upperBound) {
        return 1.0;
    }

	return value;

}


// gets avg-Pixel intensity value.
float avgIntensity (in vec4 pix) {

    return (pix.r + pix.g + pix.b) / 3.0;

}


// returns pixerl
vec4 getPixel (in vec2 coords, in float dx, in float dy) {

    vec4 color = texture2D(depthTex, coords + vec2(dx, dy));
	color = vec4(pow(color.x, 50), pow(color.y, 50), pow(color.z, 50), 1.0);
	return color;

}


// returns pixelColor
float checkForEdge (in vec2 coords) {

    float dxTex = 1.0 / WIDTH;
    float dyTex = 1.0 / HEIGHT;

    float pixels[9];
    int k = -1;
    float delta;
	
	//checks the neighbours for their intensity. Formular given in the source.
	for (int i = -1; i < 2; i++) {
        for(int j = -1; j < 2; j++) {
            k++;
            pixels[k] = avgIntensity(getPixel(coords, float(i) * dxTex, float(j) * dyTex));
		}
	}

	delta = (abs(pixels[1] - pixels[7]) + abs(pixels[5] - pixels[3]) + abs(pixels[0] - pixels[8]) + abs(pixels[2] - pixels[6])) * INTENSITY;
    return threshold(0.4, 0.5, clamp(1.8 * delta, 0.0, 1.0));

}


void main() {
	
	// this check is neccessary so you don't get an outline around the window.
	if (texCoords.x < 0.001 || texCoords.x > 0.999 || texCoords.y < 0.001 || texCoords.y > 0.999) {
		
		fragColor = vec4(0.0, 0.0, 0.0, 1.0);

	} else {
	
		fragColor = vec4(0.0, 0.0, 0.0, 1.0);
		float edgeColor = checkForEdge(texCoords);

		fragColor.r = edgeColor;
		fragColor.g = edgeColor;
		fragColor.b = edgeColor;

	}

}