
#ifdef VS

void main
(
	float4 ipos : POSITION0,
	float2 itex0 : TEXCOORD0,
	float2 itex1 : TEXCOORD1,
	out float4 opos : POSITION0,
	out float2 otex : TEXCOORD0,
	out float2 ofpos : TEXCOORD1
)
{
	opos = ipos;
	otex = itex0;
	ofpos = itex1;
}

#elif defined(PS)

sampler2D texDEPTH : register(s0);
samplerCUBE texSKY : register(s4);

float4x4 mInvView : register(c0);
float3 cameraPos : register(c4);

float4 skyDATA : register(c11);
float4 fogRGBS : register(c12);
float4 fogDATA : register(c13);

float4 main( float2 itex : TEXCOORD0, float2 fpos : TEXCOORD1 ) : COLOR0
{
	float fogMinDist = fogDATA.w;
	float fogHeightFactor = fogRGBS.w;
	float fogDensity = fogDATA.x;
	float fogHeightStart = fogDATA.z;
	float fogHeightDensity = fogDATA.y;
	float3 fogColor = fogRGBS.rgb;
	
	float distance = tex2D( texDEPTH, itex ).r;
	
	float vdistance;
	float3 rayPos = cameraPos;
	float3 dir = mul( mInvView, float4( fpos, 1, 0 ) * distance ).xyz;
	float3 rayEnd = cameraPos + dir;
	float fogEntryZ = min( fogHeightStart, rayPos.z );
	if( rayEnd.z < fogEntryZ ) // ray going down
	{
		vdistance = fogEntryZ - rayEnd.z;
	}
	else // ray going up, possibly exiting fog halfspace
	{
		float fogExitZ = min( fogHeightStart, rayEnd.z );
		vdistance = max( 0, fogExitZ - fogEntryZ );
	}
	vdistance /= abs( rayEnd.z - rayPos.z );
	vdistance *= length( dir );
	
//	float totalFogDensity = fogDensity + max( 0, 1 - exp( -sqrt( vdistance ) * fogHeightDensity ) );
	float fogfactor = saturate( 1 - exp( -distance * fogDensity - pow( vdistance * fogHeightDensity, 2 ) ) );
	if( distance <= 0 )
	{
		float3 sbcoord = normalize( mul( mInvView, float4( fpos, 1, 0 ) ).xyz );
		sbcoord = sbcoord.xzy;
		float3 skycolor = texCUBElod( texSKY, float4( sbcoord, 0 ) ).rgb;
		fogColor = lerp( fogColor, skycolor, skyDATA.x );
		fogfactor = 1;
	}
	return float4( fogColor, fogfactor );
}

#endif
