#include "postfx_common.sh"

POSTFX_VSH_1_TEX


sampler sceneTex   : register(s0);

float4 pixelOfs    : register(c0);
float4 frameColor  : register(c1);


#define SAMPLE(ofs) tex2D(sceneTex, I.tc+ofs*pixelOfs.xy).rgb


#define s2(a, b)        temp = a; a = min(a, b); b = max(temp, b);

#define mn3(a, b, c)      s2(a, b); s2(a, c);
#define mx3(a, b, c)      s2(b, c); s2(a, c);

#define mnmx3(a, b, c)      mx3(a, b, c); s2(a, b);                                   // 3 exchanges
#define mnmx4(a, b, c, d)   s2(a, b); s2(c, d); s2(a, c); s2(b, d);                   // 4 exchanges
#define mnmx5(a, b, c, d, e)  s2(a, b); s2(c, d); mn3(a, c, e); mx3(b, d, e);           // 6 exchanges
#define mnmx6(a, b, c, d, e, f) s2(a, d); s2(b, e); s2(c, f); mn3(a, b, c); mx3(d, e, f); // 7 exchanges


float4 psh(VsOutput I) : COLOR
{
  float3 v[9], temp;

  v[0]=SAMPLE(float2( 0,  0));
  v[1]=SAMPLE(float2(+1,  0));
  v[2]=SAMPLE(float2(-1,  0));
  v[3]=SAMPLE(float2( 0, +1));
  v[4]=SAMPLE(float2( 0, -1));
  v[5]=SAMPLE(float2( 0, +2));
  v[6]=SAMPLE(float2( 0, -2));
  v[7]=SAMPLE(float2( 0, +3));
  v[8]=SAMPLE(float2( 0, -3));

  mnmx6(v[0], v[1], v[2], v[3], v[4], v[5]);
  mnmx5(v[1], v[2], v[3], v[4], v[6]);
  mnmx4(v[2], v[3], v[4], v[7]);
  mnmx3(v[3], v[4], v[8]);

  float4 res=float4(v[4], 0);

  float2 dp=I.tc*2-1;
  float f=saturate(dot(dp, dp));
  res=lerp(res, frameColor, frameColor.a*f);

  return res;
}
