//#extension GL_ARB_texture_rectangle : enable

//uniform sampler2DRect dynamicRingsMap;
uniform vec2 texWH;
//varying vec4 proj_tc;


//uniform sampler2DRect dynamicRingsMap;
uniform sampler2D dynamicRingsMap;
uniform vec2 dynamicRingsMapWH;
uniform float ripple_scale;

uniform sampler2D noiseMap;

uniform sampler3D wave3D;

uniform float slice_nr;



uniform vec2 texLookupScale;

uniform float waveScale;
uniform float waveOff;



uniform vec4 isect_mm;
uniform vec4 isect_pm;
uniform vec4 isect_pp;
uniform vec4 isect_mp;



//void main_projgrid()
void main(void)
{

  //bilinearly interpolate current worldspace position
  //in homogeneous coordinates
  vec4 hPos =
  mix(mix(isect_mm, isect_mp, gl_TexCoord[0].y), 
      mix(isect_pm, isect_pp, gl_TexCoord[0].y), gl_TexCoord[0].x);

  //perform perspective divide
  // => yields the worldspace position in real coordinates
  vec3 worldPos = hPos.xyz / hPos.w;

  //map intersection coordinates to texture coordinates
  vec2 texCoords = texLookupScale.st*worldPos.xz;

  //perform heightmap lookup and displace vertex along
  //the baseplane normal (y-axis)
  //  worldPos.y = texture3D(wave3D, vec3(texCoords.xy, 12.0*(slice_nr/16.0))).r * waveScale + waveOff;
  //  worldPos.y = texture3D(wave3D, vec3(texCoords.xy, 12.0*(slice_nr/16.0)), -0.5).r * waveScale + waveOff;

  worldPos.y = texture3D(wave3D, vec3(texCoords.xy, 12.0*(slice_nr/16.0)), -1.25).r * waveScale + waveOff;

  worldPos.y *= 0.75;
  worldPos.y += (texture3D(wave3D, vec3(texCoords.xy, 12.0*(slice_nr/16.0))).r * waveScale + waveOff)*0.25;


  
  //add any offsets present in the "dynamic rings" map
  //do this through projective texturing!

  //  worldPos.y += texture2DRect(dynamicRingsMap, gl_TexCoord[0].xy*texWH).g;

  //  worldPos.y += texture2DRect(dynamicRingsMap, gl_TexCoord[0].xy*dynamicRingsMapWH).g;

  //NOW height is stored in ALPHA-channel
  //  worldPos.y += texture2DRect(dynamicRingsMap, gl_TexCoord[0].xy*dynamicRingsMapWH).a;


  //  float z = texture2DRect(dynamicRingsMap, gl_TexCoord[0].xy*dynamicRingsMapWH).a;
  float z = texture2D(dynamicRingsMap, gl_TexCoord[0].xy).a;

  //for unsigned tex
  //
  z*=2.0*ripple_scale;
  //  z*=ripple_scale;
  //
  z-=ripple_scale;
  //  z-=ripple_scale*0.5;

  //  z*=0.75; //???
  
  ///
  worldPos.y += z;


  //  worldPos.y = texture2DRect(dynamicRingsMap, (gl_TexCoord[1].st/gl_TexCoord[1].q)*texWH).g;


  //correct, but not necessary
  //due to projective grid <=> tex-coord is already correct!
  //  worldPos.y += texture2DRect(dynamicRingsMap, (proj_tc.st/proj_tc.q)*texWH).g;


  //worldPos.y += texture2DRect(dynamicRingsMap, (proj_tc.st/proj_tc.q)*dynamicRingsMapWH).xyz*2.0-1.0;

  //worldPos.y += texture2DRect(dynamicRingsMap, (proj_tc.st/proj_tc.q)*dynamicRingsMapWH).g;




  gl_FragColor = vec4(worldPos, 1.0);
}


