// Expand a range-compressed vector
float3 expand(float3 v)
{
  return (v - 0.5) * 2;
}

// Expand a range-compressed vector
float2 expand2(float2 v)
{
  return (v - 0.5) * 2;
}

// define inputs from application
struct appin
{
  float4 vertexPos     : POSITION;
  float4 normal        : NORMAL;
  float4 diffuseCoords : TEXCOORD0;
};

// define outputs from vertex shader
struct vertout
{
  float4 HPosition         : POSITION;
  float4 diffuseMapCoords  : TEXCOORD0;
  float4 reflCoords        : TEXCOORD1;

  float4 vertexColor       : COLOR;
};

vertout vp_main(appin IN,
		uniform float4x4 MVPMatrix,
		uniform float tiling,
		uniform float4 color
		)
{
  vertout OUT;

  // transform vertex position into homogenous clip-space
  OUT.HPosition = mul(MVPMatrix, IN.vertexPos);
  OUT.diffuseMapCoords = IN.diffuseCoords*tiling;

  OUT.vertexColor = color;

  // Projective texture coordinates, adjust for mapping
  float4x4 scalemat = float4x4(0.5,   0,   0, 0.5, 
                               0,-0.5,   0, 0.5,
                               0,   0, 0.5, 0.5,
                               0,   0,   0,   1);

  OUT.reflCoords = mul(scalemat, OUT.HPosition);

  return OUT;
}

//////////////////

// define inputs from vertex program
struct in_fragment
{
  float4 color     : COLOR0;
  float4 texCoord0 : TEXCOORD0;
  float4 texCoord1 : TEXCOORD1;
};

// define outputs from fragment program
struct out_fragment
{
  float4 color : COLOR0;
};

// fragment program
out_fragment fp_main
(
 // varying parameters
 in_fragment f_in,
 
 // uniform samplers (textures)
 uniform sampler2D reflMap : TEXUNIT0,
 uniform sampler2D bumpMap : TEXUNIT1,
 
 // modulate value for the final color output
 uniform float uTime,
 uniform float distortFactor
 )
{
  out_fragment f_out;
  
  float2 final = f_in.texCoord1.xy / f_in.texCoord1.w;

  // apply distortion/ripple
  //f_in.texCoord0.x += uTime;// * 0.05;
  float3 normalTex  = tex2D(bumpMap, f_in.texCoord0.xy).xyz;
  float3 normal     = expand(normalTex);

  final.xy += (normal.xy*distortFactor);

  float4 reflColor = tex2D(reflMap, final);

  f_out.color = f_in.color;

  f_out.color   += reflColor*0.25;
  f_out.color.a  = f_in.color.a;

  return f_out;
}
