#include "common.sh"


sampler   aperTex : register(s0);
sampler   normTex : register(s1);
sampler   baseTex : register(s2);
sampler   surfTex : register(s3);
sampler detailTex : register(s4);


struct VsInput
{
#if INST
  float2 dxz       : POSITION0;
  float2 oxz       : POSITION1;
  float4 ys        : POSITION2;
#else
  float2 xz        : POSITION0;
  float  y         : POSITION1;
#endif
};

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


float4 tcOfs : register(c16);


VsOutput vsh(VsInput I)
{
  VsOutput O;

  #if INST
    float2 uv=I.dxz;
    float4 ik=float4((1-uv.x)*(1-uv.y), uv.x*(1-uv.y), (1-uv.x)*uv.y, uv.x*uv.y);
    float y=dot(I.ys, ik);
    float4 pos=float4(I.oxz.x+uv.x, y, I.oxz.y+uv.y, 1);
  #else
    float4 pos=float4(I.xz.x, I.y, I.xz.y, 1);
  #endif

  O.pos=mul(globtm, pos);

  float2 tc=pos.xz*tcOfs.xy;
  O.tc.xy=tc+tcOfs.z;
  O.tc.zw=tc+tcOfs.w;

  O.dtc.xy=pos.xz/16;
  O.dtc.z=dot(pos, depth_proj);

  return O;
}


GBuffer psh(VsOutput I)
{
  float3 norm=unpack_land_normal(tex2D(normTex, I.tc.zw));
  norm.xyz=normalize(norm.xyz);

  float4 baseColor=tex2D(baseTex, I.tc.xy);
  float4 surfColor=tex2D(surfTex, I.tc.xy);
  float4 detail=tex2D(detailTex, I.dtc.xy);

  float3 color=blend_surf(baseColor.rgb, surfColor.rgb, detail.a, surfColor.a);

  color*=detail.rgb*2;

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