#include "common.sh"


struct VsOutput
{
  float4 pos  : POSITION;
  float2 tc   : TEXCOORD0;
};


float4 texsz : register(c16);
float4 texofs : register(c20);


VsOutput vsh(float2 pos: POSITION)
{
  VsOutput O;
  O.pos=float4(pos, 1, 1);
  O.tc.xy=pos.xy*texsz.xy+0.5+texofs.xy*0.5;
  return O;
}


float4 blurStep : register(c18);


float4 psh(VsOutput I) : COLOR
{
  float depth =unpack_from_8x3(tex2D(gbuf0_tex, I.tc.xy            ).xyz);
  float depth1=unpack_from_8x3(tex2D(gbuf0_tex, I.tc.xy+blurStep.xy).xyz);
  float depth2=unpack_from_8x3(tex2D(gbuf0_tex, I.tc.xy-blurStep.xy).xyz);
  float depth3=unpack_from_8x3(tex2D(gbuf0_tex, I.tc.xy+blurStep.zw).xyz);
  float depth4=unpack_from_8x3(tex2D(gbuf0_tex, I.tc.xy-blurStep.zw).xyz);

  float3 norm =normalize(tex2D(gbuf1_tex, I.tc.xy            ).xyz*2-1);
  float3 norm1=normalize(tex2D(gbuf1_tex, I.tc.xy+blurStep.xy).xyz*2-1);
  float3 norm2=normalize(tex2D(gbuf1_tex, I.tc.xy-blurStep.xy).xyz*2-1);
  float3 norm3=normalize(tex2D(gbuf1_tex, I.tc.xy+blurStep.zw).xyz*2-1);
  float3 norm4=normalize(tex2D(gbuf1_tex, I.tc.xy-blurStep.zw).xyz*2-1);

  float eps=0.1;

  float w0=0.3750/eps;
  float w1=0.2500/(abs(depth1-depth)+eps);
  float w2=0.2500/(abs(depth2-depth)+eps);
  float w3=0.0625/(abs(depth3-depth)+eps);
  float w4=0.0625/(abs(depth4-depth)+eps);

  w1*=pow(saturate(dot(norm, norm1)), 32);
  w2*=pow(saturate(dot(norm, norm2)), 32);
  w3*=pow(saturate(dot(norm, norm3)), 32);
  w4*=pow(saturate(dot(norm, norm4)), 32);

  float4 res;
  res =tex2D(light_tex, I.tc.xy       )*w0;
  res+=tex2D(light_tex, I.tc.xy+blurStep.xy)*w1;
  res+=tex2D(light_tex, I.tc.xy-blurStep.xy)*w2;
  res+=tex2D(light_tex, I.tc.xy+blurStep.zw)*w3;
  res+=tex2D(light_tex, I.tc.xy-blurStep.zw)*w4;
  res/=w0+w1+w2+w3+w4;

  // return tex2D(light_tex, I.tc.xy); //==

  return res;
}
