#version 330 core

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

in vec4 light_plane;
in vec3 light_pos;
in vec3 light_coeff; // size, length, intensity
in vec3 light_color;

layout (location = 0) out vec4 frag_color;

#include <deferred/gbuffer_read_include.frag>

#if 0
#include <shading_model/blinn_phong_model_include.frag>
#endif

#include <shading_model/strauss_model_include.frag>


float point_plane_intersection( in vec3 pos )
{
	float dist = dot(light_plane.xyz, pos) + light_plane.w;
	if ( dist < 0.0 )
	{
		return -1.0;
	}
	else
	{
		vec3 isect = pos - light_plane.xyz*dist;
		vec3 pn = light_pos - isect;
		float s = min( length( light_pos - isect ), light_coeff.x ) / light_coeff.x;
		float l = min( dist, light_coeff.y ) / light_coeff.y;
		return (1.0 - pow(s, 8.0)) * (1.0 - pow(l, 8.0));
	}
}

void main()
{
	vec2 uv_pos = gl_FragCoord.xy * viewport;
	vec4 ds = texture2D(diffuse_specular, uv_pos);
	vec4 nd = texture2D(normal_depth, uv_pos);

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

	float atten = point_plane_intersection(pos);
	if ( atten < 0.0 ) discard;

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

	//vec3 terms = calculate_blinn_phong_model(n, ld, ed, 8.0) * atten;
	vec3 terms = calculate_strauss_model(n, ld, ed, 0.1, 0.9, 0.0) * atten;

	frag_color.xyz = ds.xyz*light_color*terms.x + light_color*ds.w*terms.y;
	frag_color.w = terms.x;
}
