#include "common.sh"


sampler   aperTex : register(s0);
sampler   normTex : register(s1);
sampler   foamTex : register(s4);


struct VsInput
{
  float2 xz        : POSITION0;
  float  y         : POSITION1;
  float4 tc        : TEXCOORD0;
  float2 extra     : TEXCOORD1; // foam, speed
};

struct VsOutput
{
  float4 pos       : POSITION;
  float4 tc        : TEXCOORD0; // depth in Z, foam in W
  float4 stc       : TEXCOORD1;
  float4 ftc       : TEXCOORD2;
};


float4 tcOfs : register(c16);


VsOutput vsh(VsInput I)
{
  VsOutput O;

  float4 pos=float4(I.xz.x, I.y, I.xz.y, 1);

  O.pos=mul(globtm, pos);

  O.tc.xy=pos.xz*tcOfs.xy+tcOfs.z;
  O.tc.z=dot(pos, depth_proj);
  O.tc.w=I.extra.x/256;
  O.ftc=I.tc/32;

  O.stc=O.pos;

  return O;
}


float  foamBlend   : register(c12);
float4 screenScale : register(c13);


struct GBufferWater
{
  float4 o0 : COLOR0;
  float4 o1 : COLOR1;
};


GBufferWater psh(VsOutput I)
{
  float2 stc=I.stc.xy/I.stc.w*screenScale.xy+screenScale.zw;
  float depth=unpack_from_8x3(tex2D(gbuf0_tex, stc).xyz);

  float3 norm=unpack_land_normal(tex2D(normTex, I.tc.xy-3.0/(8*256)));
  norm.xyz=normalize(norm.xyz);

  float foam1=tex2D(foamTex, I.ftc.xy).g;
  float foam2=tex2D(foamTex, I.ftc.zw).g;
  foam1=max(foam1, tex2D(foamTex, I.ftc.xy*10).g);
  foam2=max(foam2, tex2D(foamTex, I.ftc.zw*10).g);
  float foam=lerp(foam1, foam2, foamBlend);

  float fk=I.tc.w;
  //fk=1-(1-fk)*(1-fk);
  foam=lerp(foam*fk, 1, fk*fk*0.7);

  GBuffer gb=pack_gbuf(I.tc.z, norm, 0, 0, foam, 1-fastexp((depth-I.tc.z)*100));
  GBufferWater gbw;
  gbw.o0=gb.o0;
  gbw.o1=gb.o1;
  return gbw;
}
