#version 430 core

uniform mat4 TextureMatrix;
uniform sampler2D gb_diffuse;
uniform sampler2D gb_specular;
uniform sampler2D gb_normal;
uniform sampler2D gb_depth;
uniform samplerCube cubemap;
uniform vec2 viewport;

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>
#endif

#include <shading_model/strauss_model_include.frag>

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

	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);

	vec3 cn = normalize( vec3(TextureMatrix * vec4(pos, 1.0)) );
	cn.y = -cn.y;
	vec3 cubecolor = textureLod(cubemap, cn, 0.0).rgb*color;
	//vec3 cubecolor = texture(cubemap, cn).rgb*color;

	float atten = 1.0 - (len / light_pos.w);
	//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.rgb = cubecolor*diff.rgb*terms.x + cubecolor*spec.rgb*terms.y;
	frag_color.a = terms.x;
}
