#version 430 core

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

layout (location = 0) out vec4 frag_color;

#include <deferred/gbuffer_read_include.frag>

#include <shading_model/atmosphere_include.frag>

#include <shading_model/material_model_include.frag>

#include <shading_model/light_equation.frag>

#include <deferred/cascaded_shadow_include.frag>

void main()
{
	vec2 uv = gl_FragCoord.xy * viewport;
	vec4 diff = texture(gb_diffuse, uv);
	vec4 spec = texture(gb_specular, uv);
	vec3 n = normalize( texture(gb_normal, uv).xyz );
	float viewDepth = texture(gb_depth, uv).x;
	vec3 pos = calc_position(uv, (viewDepth - 0.5)*2.0);

	float shadow_term = calculate_cascaded_shadow(viewDepth, pos)*shadowParams.x + shadowParams.y;

	vec3 ld = normalize(SunDirection);
	vec3 ed = normalize(-pos);

	vec4 extinction;
	vec3 inscatter;
	calculateGroundAtmosphere(pos, n, extinction, inscatter);

	vec3 terms = calculate_material_model(n, ld, ed, spec.a) * shadow_term;

	vec4 color;
	//color.rgb = diff.rgb*terms.x + spec.rgb*terms.y + diff.rgb*vec3(0.2, 0.5, 1.0)*terms.z;
	color.rgb = lightEquation(diff.rgb, spec.rgb, diff.rgb, terms);
	color.a = 1.0;
	lightGroundAtmosphere(color, extinction, inscatter);

	float isSky = float(viewDepth < 1.0 ? 1.0 : 0.0);
	frag_color.rgb = color.rgb * isSky;
	frag_color.a = terms.x * isSky;
}
