uniform sampler2D 	clouds;
varying vec2 		texcoord,
					texcoord1;
varying float 		depth;

uniform vec3		sundir;
varying vec3		pos;
uniform vec3 		sunpos;
uniform float 		inScatter;
//uniform float 	sunpower;
uniform float		density;
uniform float 		extintion;

varying vec3		suneyedir;
varying vec3		eyepos;

// costanti passate allo shader
uniform vec3  SUN; 	// = colore del sole
uniform vec3  cBr; 	// = RayLeigh
uniform vec3  cBm; 	// = Mie	
uniform	vec3  C0; 	// = cBr+cBm;	
uniform vec3  C1; 	// = 1.0/(cBr+cBm);

uniform float C4;	// = (1-g)^2
uniform float C5;	// = 1+g^2
uniform float C6;	// = 2*g
uniform float C7;	// = 3/2

uniform vec3		fogColor;
uniform vec3		zenithColor;
uniform vec3		horizonColor;

////////////////////////////
void main()
{
	//vec3 dir=normalize(-sunpos.xyz-pos);
	vec3 clouddir=normalize(pos);
	vec4 cloudcolor=texture2D(clouds,texcoord.st);
//	vec4 cloudcolor2=texture2D(clouds,texcoord1.st);
	vec3 normal=cloudcolor.xyz*2.0-1.0;
	vec3 N=normal;
	N.y=normal.z;
	N.x=-normal.y;
	N.z=-normal.x;
	clouddir=clouddir+N;
	float cos=clamp(dot(-sundir,normalize(N)),0.0,1.0);
	float cos2=pow(clamp(dot(-sundir,normalize(clouddir)),0.0,1.0),5.0)*10.0;
	float eyeCos=pow(clamp(dot(-suneyedir,normalize(-eyepos+clouddir)),0.0,1.0),20.0)*(1.0-cos2*0.1);
	
	float NLwrap=(cos+1.0)/2.0;
	float diffuse = max(NLwrap,0.0);
	float fScatter = smoothstep(0.0, 0.5, NLwrap) * smoothstep(1.0, 0.5,NLwrap);
	//float diffuse = max(cos,0.0);
	vec3 Lin = vec3(0.1, 0.1, 1.0)+vec3(diffuse); 
	
	float d=clamp(exp(-depth*0.01*extintion)-0.2,0.0,1.0);
	float oneOverDens=clamp(1.0/(1.0-density),0.0,2.0);
	float density2=clamp(cloudcolor.w-density,0.0,1.0)*oneOverDens;
	float invDens=pow(1.0-density2,5.0);
	float invDens2=pow(1.0-density2,15.0)*100.0;
	
//	float density2b=clamp(cloudcolor2.w-density,0.0,1.0)*oneOverDens;
//	float invDensb=pow(1.0-density2b,5.0);

	vec3 clouds0=(Lin+(invDens*cos2)+(invDens2*eyeCos))*cloudcolor.w*SUN;
//	vec3 clouds1=(Lin+(invDensb*cos2))*cloudcolor2.w*SUN;
	
	gl_FragData[0].xyz=max(/*(*/clouds0/*+clouds1)*0.5*/,0.0);
	gl_FragData[0].w=clamp((density2/*+density2b*/)*d,0.0,1.0);
	
	gl_FragData[1].xyz=vec3(0.0,0.0,0.0);
	gl_FragData[1].w=max(1.0-(density2*d),0.0);
}
