/**
 *
 * Diplomova prace
 * Stinove techniky na dnesnim hardware a jejich porovnani
 *
 * Michal Toth
 *
 * Fakulta informacnich technologii
 * Vysoke uceni technicke v Brne
 *
 * 2013/2014
 *
 */

/**
 * Screen space ambient occlusion - vypocet osvetleni
 * osvetlovaci model s vyuzitim vypocitaneho ambient occlusion faktoru
 * moznost nastavit rozmazani
 */

#version 420

in vec2 tc;

uniform sampler2D texSSAO;
uniform sampler2D texNormal;
uniform sampler2D texDepth;
uniform sampler2D texMaterial;

uniform vec3 La;
uniform vec3 Ld;
uniform vec3 Ls;

uniform mat4 imvp;

uniform vec3 cameraPos;
uniform vec3 lightPos;

uniform float shininess=32;

uniform int blurSize=3;
uniform bool colored=true;

out vec4 fragColor;

void main() {
    float ssao =0;
    int d= blurSize/2;
    for(int y=-d;y<=d;y++){
	for(int x=-d;x<=d;x++){
	    ssao+= textureOffset(texSSAO,tc,ivec2(x,y)).x;
	}
    }
    ssao/=blurSize*blurSize;


    vec3 color;
    if(colored){
	vec3 col = texture(texMaterial,tc).rgb;

	vec3 N = normalize(texture(texNormal,tc).xyz);
	float depth = texture(texDepth,tc).x;
	if(depth>=1.0){
	    fragColor=vec4(0);
	    return;
	}
	vec4 pos = imvp*vec4(tc*2-1,depth*2-1,1);
	vec3 position = pos.xyz/pos.w;

	vec3 L = normalize(lightPos-position);

	//vec3 A = (max(vec3(0),La-(1-ssao)))*col;
	vec3 A = La*ssao*col;
	//vec3 A = La*col;
	vec3 D = Ld*max(dot(L,N),0)*col;

	vec3 S = vec3(0,0,0);
	if(shininess>0){
	    vec3 V = normalize(cameraPos-position);
	    vec3 R = reflect(-L,N);
	    float spec = max(0,pow(dot(R,V),shininess));
	    S = spec*Ls;
	}

	color = A+D+S;
    }else{
	color=vec3(ssao);
    }


    fragColor = vec4(color,1);
}
