#include "common.sh"


sampler   normTex : register(s1);
sampler detailTex : register(s3);
sampler   foamTex : register(s4);


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

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


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*(0.3/1024);
  O.ftc=I.tc/32;

  O.stc=O.pos;
  O.dtc.xy=pos.xz/16;
  O.dtc.z=I.extra.y/256;

  return O;
}


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


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

  const float detScale=3;

  float statFactor=saturate(1-I.dtc.z*15);

  float foam1=tex2D(foamTex, I.ftc.xy).g;
  float foam2=tex2D(foamTex, I.ftc.zw).g;
  // foam1=max(foam1, tex2D(foamTex, I.ftc.xy*detScale).g);
  // foam2=max(foam2, tex2D(foamTex, I.ftc.zw*detScale).g);
  foam1+=tex2D(foamTex, I.ftc.xy*detScale).g*0.5-0.25;
  foam2+=tex2D(foamTex, I.ftc.zw*detScale).g*0.5-0.25;
  float foam=lerp(foam1, foam2, foamBlend);

  float foamS=tex2D(foamTex, I.dtc.xy).g;
  // foamS=max(foamS, tex2D(foamTex, I.dtc.xy*detScale).g);
  foamS+=tex2D(foamTex, I.dtc.xy*detScale).g*0.5-0.25;
  foam=lerp(foam, foamS, statFactor);

  float4 detail=tex2D(detailTex, I.ftc.xy);
  detail=lerp(detail, tex2D(detailTex, I.ftc.zw), foamBlend);
  detail=lerp(detail, tex2D(detailTex, I.dtc.xy), statFactor);

  float b=1-fastexp(I.tc.w);

  foam*=smoothstep(0.01, 0.15, b-detail.a*0.1);
  float4 color=float4(foam+0.5, foam*foam*0.5, 0, 1);
  color=lerp(
    float4(blend_surf(0.01, 0.04, detail.a, 0.5)*detail.rgb*2, 0),
    color,
    smoothstep(0.001, 0.09, b-detail.a*0.1));

  // foam*=smoothstep(0.01, 0.05, b*detail.a);
  // float4 color=float4(foam*4, foam*foam*0.5*0, 0, foam);
  // color+=float4(blend_surf(0.01, 0.04, detail.a, 0.4)*detail.rgb*2, 0);

  clip((1-detail.a)*b-0.01);

  return pack_gbuf(I.tc.z, norm, color.rgb, color.a, 0);
}
