#version 330 core

uniform mat4 TextureMatrix;
uniform sampler2D diffuse_specular;
uniform sampler2D normal_depth;
uniform samplerCube cubemap;
uniform vec2 viewport;

in vec4 light_pos;
in vec3 color;

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 = light_pos.xyz - pos;
	float len = length(light_dir);
	if ( len > light_pos.w ) discard;

	light_dir = normalize(light_dir);

	vec3 normal = normalize(nd.xyz);
	float NdotL = dot(normal, light_dir);// > 0.0 ? 1.0 : -1.0;
	if ( NdotL <= 0.0 ) discard;

	float atten = 1.0 - (len / light_pos.w);
	vec3 half_vector = normalize(reflect(normalize(pos), light_dir));
	float NdotHV = max(dot(normal, half_vector), 0.0)*NdotL;
#if 0
	vec3 cn = vec3(TextureMatrix * vec4(light_dir, 0.0));
	cn.y = -cn.y;
#else
	vec3 cn = normalize( vec3(TextureMatrix * vec4(pos, 1.0)) );
	cn.y = -cn.y;
#endif
	vec3 cubecolor = textureLod(cubemap, cn, 0.0).rgb*color;

	vec3 lit = cubecolor*ds.rgb*NdotL + cubecolor*ds.a*pow(NdotHV, SPECULAR_POWER);
	frag_color = vec4(lit*atten, NdotL*atten);
}
