
struct VsOutput
{
  float4 pos: POSITION;
  float4 tc : TEXCOORD0;
  float3 tc2: TEXCOORD1;
};

float4 textm : register(c16);
float4 texsz : register(c17);

VsOutput vsh(float2 pos: POSITION)
{
  VsOutput O;
  O.pos=float4(pos, 1, 1);

  float2 t=pos.xy*textm.xy+textm.zw;
  O.tc =t.xyyy+float4(0, 0, texsz.y, -texsz.y);
  O.tc2=t.xyy +float3(0, texsz.w, -texsz.w);

  return O;
}


sampler edgeTex : register(s0);
sampler prevTex : register(s1);

float4 offset   : register(c0);


float4 psh(VsOutput I) : COLOR
{
  clip(tex2D(edgeTex, I.tc.xy).r-0.5);

  float4 res;

  #if FIRST

    res.xz=( (tex2D(edgeTex, I.tc2.xy).r >= 0.5)
      ? float2(offset.x, 0)
      : float2(0, 1)
    );

    res.yw=( (tex2D(edgeTex, I.tc2.xz).r >= 0.5)
      ? float2(offset.x, 0)
      : float2(0, 1)
    );

  #else

    float4 prev=tex2D(prevTex, I.tc.xy);

    res.xz=( ((1-prev.z) * tex2D(edgeTex, I.tc2.xy).r * (1-tex2D(prevTex, I.tc.xz).z) >= 0.5)
      ? float2(tex2D(prevTex, I.tc2.xy).x+offset.x, 0)
      : float2(prev.x, 1)
    );

    res.yw=( ((1-prev.w) * tex2D(edgeTex, I.tc2.xz).r * (1-tex2D(prevTex, I.tc.xw).w) >= 0.5)
      ? float2(tex2D(prevTex, I.tc2.xz).y+offset.x, 0)
      : float2(prev.y, 1)
    );

  #endif

  #if FINAL
    res.zw=res.xy;
  #endif

  return res;
}
