//-----------------------------------------------------------------------------
// Screen Space Ambient Occlusion for TGEA
// Copyright (C) Ubiq Visuals Inc.
// http://www.ubiqvisuals.com/
//-----------------------------------------------------------------------------


//-----------------------------------------------------------------------------
// Structures                                                                  
//-----------------------------------------------------------------------------
struct PS_INPUT
{
   float4 Position : POSITION0;
   float4 Texcoord : TEXCOORD0;
};

struct PS_OUTPUT
{
   float4 Color : COLOR0;
};


//-----------------------------------------------------------------------------
// Main
//-----------------------------------------------------------------------------
PS_OUTPUT main( PS_INPUT Input,
   uniform sampler2D SSAOMap : register(S0),
   uniform sampler2D DepthMap : register(S1),
   uniform float2 PTexOffset : register(C0) )
{
   PS_OUTPUT Output;
   
   float2 CenterTexcoord = Input.Texcoord.xy + PTexOffset.xy * 0.5f;
   
   float TotalWeight = 0.0125f;
   float4 OutputColor = tex2D(SSAOMap, CenterTexcoord) * TotalWeight;
   float CenterDepth = tex2D(DepthMap, CenterTexcoord).r;
   
   float2 SampleOffsets[4] =
   {
      float2( 1,-1),
      float2(-1,-1),
      float2( 1, 1),
      float2(-1, 1),
   };
   
   for(int i = 0; i < 4; i++)
   {
      float2 SampleTexcoord = CenterTexcoord + PTexOffset.xy * SampleOffsets[i];
      float SampleDepth = tex2D(DepthMap, SampleTexcoord).r;
      float DepthDiff = 8.0f * (1.0f - SampleDepth/CenterDepth);
      float SampleWeight = saturate(0.5f - 0.75f * abs(DepthDiff) - 0.25f * DepthDiff);
      OutputColor += tex2D(SSAOMap, SampleTexcoord) * SampleWeight;
      TotalWeight += SampleWeight;
   }
   
   OutputColor /= TotalWeight;   
   Output.Color = float4(OutputColor.rgb, 1);
   
   return Output;
}