uniform vec3		sundir;
uniform float 		inScatter;
uniform float 		sunpower;
uniform vec3		fogColor;
uniform float 		extintion;

// 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 float 	sunpower;
uniform vec3	zenithColor;
uniform vec3	horizonColor;

//uniform vec3  	cBr; 	// = RayLeigh
//uniform vec3  	cBm; 	// = Mie	

float 	h;
vec3	vPos;
vec3	cnormal;
vec3 	cC0;
vec3 	baseColor;

varying vec3  	skyColor;
varying vec3 	fFex;
varying vec3 	fLin;

uniform vec3  campos;
uniform float cHeightFallof;

float cVolFogHeightDensityAtViewer=exp( cHeightFallof * -campos.y);
//float cFarDistance=100000.0;

float ComputeVolumetricFog( vec3 cameraToWorldPos )
{
	float fogInt = length( cameraToWorldPos )*cVolFogHeightDensityAtViewer;
	if( abs(cameraToWorldPos.y ) > 0.01)
	{
		float t = cHeightFallof * cameraToWorldPos.y;
		fogInt *= ( 1.0-exp( -t ) ) / t;
	}
	return fogInt; //exp( -extintion*0.005 * fogInt);
}

void main()
{
	gl_Position = gl_ModelViewProjectionMatrix*gl_Vertex;//ftransform();
	vec3 npos=normalize(gl_Vertex.xyz*vec3(1.0,7.0,1.0));
	h=clamp(1.1-npos.y,0.0,1.0);
	
	vec4 vertex=gl_Vertex;
	vertex.xyz=normalize(gl_Vertex.xyz)*vec3(50000000.0,50000000.0,50000000.0);
	vertex.xyz*=vec3(1.0,0.1,1.0);
	vPos=vertex.xyz;
	cnormal.xyz=-gl_Vertex.xyz;
	
	float rf = h;
	float mf = h*0.1;
	vec3 	rd=cBr,
			md=cBm;
	if(abs(rf) > 0.01) rd *=  (1.0 - exp(-rf)) / rf;
	if(abs(mf) > 0.01) md *=  (1.0 - exp(-mf)) / mf;
	cC0=(rd*rf + md*mf);
	
	baseColor=mix(zenithColor,horizonColor,h);
	
	float cos=dot(-sundir,normalize(cnormal));
	float cos2=(1.0-step(-cos,0.9999))*16.0;
	
	// SKY //////////////////////////////////////////////////////
	float F1=(1.0 + cos*cos);
	float F2=(C4/pow(C5-C6*cos,C7));

	vec3 Br = cBr*F1;
	vec3 Bm = cBm*F2;

	vec3 Fex=exp(-cC0*5000000.0);
	vec3 LinMul=C1*(1.0-Fex);
	vec3 Lin = (Br+Bm)*LinMul*inScatter*0.005;
	vec3 scatterColor=baseColor + Lin;
	skyColor=(scatterColor + cos2*Lin);
	
	// FOG /////////////////////////////////////////////////////
	vec3 viewDir=vPos-campos;
	//float distance=length(viewDir);
	float delta=ComputeVolumetricFog(viewDir);
	fFex=exp(-C0*extintion*delta);
	float fF1=(1.0 + cos*cos*0.5);
	fLin=( (fF1*cBr) )*C1*(1.0-fFex)*inScatter*fogColor*0.005;
}