uniform sampler2D 	heightmap,
					colormap,
					depthmap;

uniform mat4		eyeToWorld;
uniform vec3		campos;
					
uniform vec3 invTerrainDim;
uniform float terrainMaxHeight;
uniform float maxRadius;
uniform float occScale;
uniform float terrainNormOrg;

varying vec4	VPOS;
varying vec2 	texcoord;

void main()
{
/*	vec4 pos;
	pos.z = texture2D(depthmap,texcoord.st).r;
	*/
	// compute world position
	/*pos.xy=VPOS*-pos.z;
	pos.w=1.0;
	vec4 Wpos=eyeToWorld*pos;*/
	vec3 Wpos;
	Wpos=(VPOS.xyz*-texture2D(depthmap,texcoord.st).r)+campos;
	//Wpos.z=pos.z;
	//Wpos+=campos;
	
	// get distance from terrain
	vec2 heigthmapCoord = (Wpos.xz*invTerrainDim.xz)+vec2(0.5,0.5);
	float tHeight=(texture2D(heightmap,heigthmapCoord.st).x-terrainNormOrg)*terrainMaxHeight;
	float tDistance=Wpos.y-tHeight;
	
	// get terrain sky visibility value from terrain
	float skyVisibility=texture2D(colormap,heigthmapCoord.st).a;

	// compute ambient occlusion basing on distance
	float d=clamp(tDistance/maxRadius,0.0,1.0);
	float visibility=mix(skyVisibility,1.0,d*d);	//0 max occlusion, 1 - no occlusion
	
	gl_FragColor=vec4(min(visibility+occScale,1.0));
}
