sampler2D RenderTex;
sampler2D DiffuseTex;
sampler2D MaterialTex;

sampler2D PosTex;
sampler2D NormalTex;
samplerCUBE ReflectionTex;
samplerCUBE RealtimeReflectionTex;

float3 Ambient;

float3 FogColor;
float4 LerpFogColor;

struct PS_INPUT{
	float2 Tex				: TEXCOORD0;
	float3 ViewDir			: TEXCOORD1;
};

struct PS_OUTPUT{
	float4 Color			: COLOR;
};

#if defined(REFLECTION) && defined(PS14)
#if !defined(ADDFOG) && !defined(LERPFOG)
#define ADDFOG
#endif
#endif

//#define REFLECTION

//#define ADDFOG;
//#define LERPFOG


#include "dcOutputPos.HLSL"

PS_OUTPUT main(const PS_INPUT Input){
	// Texture lookups
	float4 Render = tex2D(RenderTex, Input.Tex);
	float3 Color = tex2D(DiffuseTex, Input.Tex);
	Color += Ambient * Render.rgb;

	float4 Material = tex2D(MaterialTex, Input.Tex);
	float4 NormalData = tex2D(NormalTex, Input.Tex);
	
	// Split values
	float3 Normal = UnpackNormal(NormalData.xyz);

	// Color
#ifndef ALPHA
	Color = lerp(Render.rgb, Color, Render.a);
#else
	Color *= Render.a;
#endif
	
	// Fogging
	float Fogging = ComputeFog(NormalData.w);
	
#ifdef REFLECTION
	// Reflection
	float3 N = Normal;
	float3 V = Input.ViewDir;
	
	float3 R = 2 * dot(N, V) * N - V;

#ifdef PS14
	Color += texCUBE(RealtimeReflectionTex, R) * 1 * Material.xyz * Material.w;
#else
	float4 Reflection = texCUBE(RealtimeReflectionTex, R) * 2;

	Color += Reflection * Material.xyz * Material.w;
#endif

#endif

#ifdef ADDFOG
	Color += FogColor * Fogging * Render.a;
#endif

#ifdef LERPFOG
	Color = lerp(Color, LerpFogColor.rgb, clamp(Fogging * LerpFogColor.a * Render.a, 0, 1));
#endif

	// Output
	PS_OUTPUT Out;
	Out.Color.rgb = Color;
//#ifdef ALPHA
	Out.Color.a = Render.a;
//#else
	//Out.Color.a = 1;
//#endif
	
	//Out.Color.rgb = Fogging;

	return Out;
}
