#version 430 core

uniform sampler2D gb_diffuse;
uniform sampler2D gb_specular;
uniform sampler2D gb_normal;
uniform sampler2D gb_depth;
uniform vec2 viewport;
uniform mat4 ProjectionMatrix;

in vec4 light_pos;
in vec3 color;

layout (location = 0) out vec4 frag_color;

#include <deferred/gbuffer_read_include.frag>

#if 0

#include <shading_model/blinn_phong_model_include.frag>

#else

#include <shading_model/material_model_include.frag>

#endif

#include <shading_model/light_equation.frag>

void main()
{
	vec2 uv = gl_FragCoord.xy * viewport;
	vec4 diff = texture(gb_diffuse, uv);
	vec4 spec = texture(gb_specular, uv);
	vec4 norm = texture(gb_normal, uv);
	float dpt = (texture(gb_depth, uv).x - 0.5)*2.0;
	//vec3 pos = calc_position(uv, nd.w);
	vec3 pos = calc_position(uv, dpt);

	vec3 ld = light_pos.xyz - pos;
	float len = length(ld);
	if ( len > light_pos.w ) discard;

	ld = normalize(ld);
	vec3 n = normalize(norm.xyz);
	vec3 ed = normalize(-pos);

	//float atten = (1.0 - pow(len / light_pos.w, 2.0));
	float atten = 1.0 - (len / light_pos.w);

	//vec3 terms = calculate_blinn_phong_model(n, ld, ed, 16.0) * atten;
	vec3 terms = calculate_material_model(n, ld, ed, spec.a) * atten;

	frag_color.rgb = lightEquation(diff.rgb*color, spec.rgb*color, diff.rgb*color, terms);
	frag_color.a = terms.x;
}
