#version 430 core

uniform sampler2D clouds;
uniform sampler2D cloudsdetail;
uniform sampler2D gb_depth;
uniform vec2 viewport;
uniform vec2 cloudOffset;

in vec3 ec_pos;
in vec2 uv_offset;
in vec4 extinction;
in vec3 inscatter;
in float fade;

layout (location = 0) out vec4 frag_color;

#include <deferred/gbuffer_read_include.frag>

#include <shading_model/atmosphere_include.frag>

#include <deferred/cascaded_shadow_include.frag>

void main(void)
{
	vec2 uv_pos = gl_FragCoord.xy * viewport;
	float viewDepth = texture(gb_depth, uv_pos).x;
	vec3 pos = calc_position(uv_pos, (viewDepth - 0.5)*2.0);
	if ( pos.z > ec_pos.z ) discard;

	vec3 ppos = calc_position(uv_pos, gl_FragCoord.z*2.0 - 1.0);

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

	vec2 uv = uv_offset + gl_PointCoord.xy * 0.25;
	vec4 color = texture(clouds, uv).rrrr * (0.75 + 0.25*texture(cloudsdetail, uv_pos + cloudOffset).r);
	color.rgb *= shadow_term;
	float alpha = color.a * fade;
	lightGroundAtmosphere(color, extinction, inscatter);
	//lightCloudAtmosphere(color, extinction, inscatter);
	color.a = alpha * clamp((ec_pos.z - pos.z)/32.0, 0.0, 1.0) * 0.9;
	frag_color = color;
}
