#include "Common.hlsl"

float4x4 View;
float4x4 Projection;

Texture2D ViewNormalMap;
Texture2D DepthMap;
Texture2D ColorMap;

float2 Resolution;

float3 WorldLightPosition;
float3 ViewLightPosition;
float3 LightColor;
float LightSize;

float3 ViewDirBL, ViewDirDX, ViewDirDY;

struct VSInput
{
	float3 Position: POSITION;
};

struct VSOutput
{
	float4 Position: SV_Position;
	float4 ClipCoord: PIXELCOORD;
};

VSOutput vsMain(VSInput Input)
{
	VSOutput Output;
	float4 viewPosition = mul(View, float4(Input.Position*LightSize + WorldLightPosition, 1));
	Output.Position = mul(Projection, viewPosition);
	Output.ClipCoord = Output.Position;
	return Output;
}



float4 psMain(VSOutput Input): SV_Target
{
	float2 pixel = (Input.ClipCoord.xy / Input.ClipCoord.w) * 0.5 + 0.5;
	pixel.y = 1 - pixel.y;

	int3 pixelCoord = int3(pixel * Resolution, 0);
	float3 viewNormal = ViewNormalMap.Load(pixelCoord).xyz;

	// Reconstruct view position
	float3 viewDir = normalize( ViewDirBL + ViewDirDX * pixel.x + ViewDirDY * (1-pixel.y) );
	float depth = DepthMap.Load(pixelCoord).x;
	float3 viewPosition = viewDir * depth; 

	float3 lightDir = ViewLightPosition-viewPosition.xyz;
	float lightDist = length(lightDir);
	float3 normLightDir = lightDir / lightDist;
	float3 refViewDir = reflect(viewDir, viewNormal);

	float diffuseAttenuation = max(0, LightSize-lightDist) / LightSize;
	float diffuse = max(0, dot(viewNormal, normLightDir)) * diffuseAttenuation ;
	
	float4 diffuseColor = ColorMap.Load(pixelCoord);

	float specular = pow(max(0, dot(refViewDir, normLightDir)), 20 - diffuseColor.w*10) * diffuseAttenuation * diffuseColor.w;

	float3 color = (diffuse*diffuseColor.xyz + specular) * LightColor * 5;
	return float4(color,1.0);
}