varying vec2 		texcoord;
varying float		dist;
uniform sampler2D 	tex;
//uniform vec4		ambientColor;	// ambient  * material color
varying vec4		diffuse;		// diffuse color * material color
varying vec4		fog;
varying float		alphaFade;
uniform vec4 		diffuseColor;	// material color * sun color * sun power

/*varying vec3 	Lin;
varying vec3 	Fex;
*/

uniform vec2 		earth_center;	// x=earth_center Y, y=length_unit
//uniform float 		length_unit;

uniform vec3  		campos;
uniform vec3		sundir;
uniform vec3		ldir;

uniform vec3 		SUN;	// sun color * sun power
varying vec3 		Wpos;
uniform vec3 		inScatterColor;
uniform vec3 		moonlightcolor;

uniform vec3		sunColor;

#ifdef _HEIGHTMAP_

	uniform sampler2D	cmask;	
	varying vec2 		texcoord2;

#else
	#ifndef BSET
		uniform sampler2D 	noiseTex;
	#endif
#endif

vec3 GetSolarRadiance();
vec3 GetSkyRadiance(vec3 camera, vec3 view_ray, float shadow_length,
    vec3 sun_direction, out vec3 transmittance);
vec3 GetSkyRadianceToPoint(vec3 camera, vec3 point, float shadow_length,
    vec3 sun_direction, out vec3 transmittance);
vec3 GetSunAndSkyIrradiance(
    vec3 p, vec3 normal, vec3 sun_direction, out vec3 sky_irradiance);
vec3 GetTrasmittanceTexture(vec2 uv);
vec3 GetScatteringTexture(vec3 uv);
vec3 GetSunIrradiance(vec3 p, vec3 sun_direction);

void main()
{
	vec4 color=texture2D(tex,texcoord.st);
	color.rgb=pow(color.rgb,vec3(2.2));
	
	vec3 	Lin=vec3(0.0,0.0,0.0);
	vec3 	Fex=vec3(0.0,0.0,0.0);
	
	#ifdef _HEIGHTMAP_
		
		vec3 one=vec3(1.0,1.0,1.0);
		vec4 maskColor=texture2D(cmask,texcoord2.st);
		maskColor.rgb=pow(maskColor.rgb,vec3(2.2));
		
		vec3 rmul=color.rgb*maskColor.rgb;
		vec3 rscr=one-((one-maskColor.rgb)*(one-color.rgb));
		color.rgb=(color.rgb*rscr+(one-color.rgb)*rmul)*maskColor.a;
		color.a=1.0;
		//color*=texture2D(cmask,texcoord2.st);
		
	#else
		#ifdef BSET
			color.a*=alphaFade;
		#else
			float alpha=texture2D(noiseTex,texcoord.st).r;
			if(alpha>alphaFade)
				discard;
		#endif
	#endif
	
	if(dist<=0.0)
	{
		discard;
	}
	else
	{
		// convert normal to eye space
		vec3 WposFromEarth=(Wpos.xyz*earth_center.y/*length_unit*/)-vec3(0.0,earth_center.x,0.0);
		vec3 camposFromEarth=(campos.xyz*earth_center.y/*length_unit*/)-vec3(0.0,earth_center.x,0.0);
		camposFromEarth.y=max(camposFromEarth.y,-earth_center.x);
		
		vec3 sunlight=GetSunIrradiance(WposFromEarth, sundir)*sunColor + moonlightcolor;
		Lin=GetSkyRadianceToPoint(camposFromEarth, WposFromEarth, 0.0, sundir, Fex)*inScatterColor;
		
		gl_FragColor.xyz=Lin+Fex*diffuse.xyz*color.xyz*sunlight.xyz;
		gl_FragColor.a=color.a+0.25;
	}
}
