#include <system.psh>

sampler2D ColorMap;
sampler2D OverlayMap;
sampler2D NormalMap:register(s2);

//Light parameters
float3 LightColor;
float3 LightPosition;
float Intensity;

// Ambient light parameters
float4 AmbientColor;
float AmbientPower;

//Material parameters
float Exp;
float DiffusePower;
float SpecularPower;

// Object parameters
float2 ObjectSize;
float2 ObjPosition;


float4 ps_main(PS_IN In) : COLOR {

	float4 Light = float4(0,0,0,0);

	float4 InputColor = tex2D(ColorMap,In.Tex0.xy);
	float4 NormalColor = tex2D(NormalMap, In.Tex0.xy);
	
	// Calculating normals: Y axis is inverted
	float3 Normal = normalize(float3(NormalColor.x-0.5, -NormalColor.y+0.5, NormalColor.z-0.5));

	// Calculating pixel position in world space
	float3 PixelPos = float3(ObjPosition.x+In.Tex0.x*ObjectSize.x,ObjPosition.y+In.Tex0.y*ObjectSize.y,0.0);

	// Getting direction to light and to viewer
	float3 LightDir = normalize(LightPosition-PixelPos);
	float3 ViewDir=float3(0,0,1);

	float3 Half_Vector = normalize(LightDir + ViewDir);

	// Compute the angle between the half vector and normal
	float  HdotN = max( 0.0f, dot( Half_Vector, Normal ) );

	// Compute the specular colour
	float3 Specular =SpecularPower* LightColor * pow( HdotN, Exp);

	// Compute the diffuse colour
	float3 Diffuse = DiffusePower*LightColor * max( 0.0f, dot( Normal, LightDir ) );

	// Determine the final colour    
	Light = float4( Diffuse + Specular, 1.0f );
	
	// Compute final color. Adding ambient light too
	return InputColor*(Intensity*Light+AmbientColor*AmbientPower);
}
