#version 330 core

uniform sampler2D diffuse_specular;
uniform sampler2D normal_depth;
uniform vec2 viewport;

in vec3 spot_pos;
in vec3 spot_dir;
in vec3 spot_params; //cone_angle, cone_cutoff_angle, radius
in vec3 color;       // rgb*intensity

layout (location = 0) out vec4 frag_color;

#include <gbuffer_include.frag>

void main()
{
	const float SPECULAR_POWER = 8.0;

	vec2 uv_pos = gl_FragCoord.xy * viewport;
	vec4 ds = texture(diffuse_specular, uv_pos);
	vec4 nd = texture(normal_depth, uv_pos);

	vec3 pos = calc_position(uv_pos, nd.w);

	vec3 light_dir = spot_pos - pos;
	float len = length(light_dir);
	if ( len > spot_params.z ) discard;

	light_dir = normalize(light_dir);

	vec3 normal = normalize(nd.xyz);
	float NdotL = dot(normal, light_dir);
	if ( NdotL <= 0.0 ) discard;

	float atten = 1.0 - (len / spot_params.z);
	atten *= clamp( (dot(-light_dir, spot_dir) - spot_params.x) / (spot_params.y - spot_params.x), 0.0, 1.0 );
	vec3 half_vector = reflect(normalize(pos), light_dir);
	float NdotHV = max(dot(normal, half_vector), 0.0)*NdotL;

	//frag_color.rgb = color*ds.rgb*NdotL*atten + vec3(color*atten)*pow(NdotHV, ds.w);
	frag_color.rgb = color*ds.rgb*NdotL*atten + vec3(color*ds.w*atten)*pow(NdotHV, SPECULAR_POWER);
	frag_color.a = NdotL*atten;
}
