#version 430 core

uniform sampler3D cloud;
uniform sampler2D gb_depth;
uniform vec2 viewport;

in vec3 ec_pos;
in vec3 uvw;
in vec3 lightDir;
in vec4 extinction;
in vec3 inscatter;

layout (location = 0) out vec4 frag_color;

#include <shading_model/atmosphere_include.frag>

#include <deferred/gbuffer_read_include.frag>

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

	d = texture(cloud, uvw).r;
	float o = 1.0;
	float s = 2.0/64.0;
	float r = s * 4.0;
	vec3 sampleOffs = normalize(lightDir) * s;
	vec3 samplePos = uvw;
	if( d > 0.01 )
	{
		while( o > 0.0 )
		{
			if ( samplePos.x < 0.0 || samplePos.x > 1.0 ) break;
			if ( samplePos.y < 0.0 || samplePos.y > 1.0 ) break;
			if ( samplePos.z < 0.0 || samplePos.z > 1.0 ) break;
			o -= texture(cloud, samplePos).r * r;
			samplePos += sampleOffs;
		}
	}
	float alpha = d * clamp((ec_pos.z - pos.z)/4.0, 0.0, 1.0);
	float intensity = mix(0.4, 1.0, o);
	vec4 color = vec4(intensity, intensity, intensity, alpha);
	lightGroundAtmosphere(color, extinction, inscatter);
	color.a = alpha;
	frag_color = color;
}
