#include "common.sh"


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


struct VsInput
{
  float2 dxz       : POSITION0;
  float2 tc        : TEXCOORD0;
  float2 oxz       : POSITION10;
  float4 ys        : POSITION11;
  float4 flip      : POSITION12;
};

struct VsOutput
{
  float4 pos       : POSITION;
  float4 fog       : COLOR0;
  float4 tc        : TEXCOORD0;
  float2 dtc       : TEXCOORD1;
};


float4 tcOfs : register(c16);


VsOutput vsh(VsInput I)
{
  VsOutput O;

  float2 uv=I.dxz;
  if (I.flip.r>0.5) uv.x=1-uv.x;
  if (I.flip.g>0.5) uv.y=1-uv.y;
  if (I.flip.b>0.5) uv=uv.yx;

  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);

  O.pos=mul(globtm, pos);

  float2 tc=pos.xz*tcOfs.xy;
  O.tc.xy=tc+tcOfs.z;
  O.tc.zw=tc+tcOfs.w;
  O.fog=vs_calc_fog_color(pos.xyz);

  O.dtc.xy=I.tc;

  return O;
}


float4 psh(VsOutput I) : COLOR
{
  float3 res;

  float4 norm=tex2D(normTex, I.tc.zw);
  norm.xyz=norm.xyz*2-1;
  norm.xyz=normalize(norm.xyz);
  float ao=norm.w;

  float4 color=tex2D(houseTex, I.dtc.xy);

  // light
  float3 light=calc_simple_light(norm.xyz, ao);

  // result
  res=light*color.rgb;

  // fog
  res=lerp(res, I.fog.rgb, I.fog.a);

  return pack_color(res, 1);
}
