//#extension GL_ARB_texture_rectangle : enable

uniform sampler2D cMap;
//uniform sampler2DRect cMap;

uniform sampler2D noiseMap;

//uniform sampler2D wMap; //waterheight
uniform sampler3D wave3D;

//uniform sampler2D longlatEnvMap;

uniform float texW;
uniform float texH;

uniform float ctexW;
uniform float ctexH;

uniform float slice_nr;

uniform mat4 vMat;

uniform vec2 texLookupScale;

uniform vec4 trans;
uniform vec4 scale;

uniform float waveScale;
uniform float waveOff;

uniform vec4 cc_above;

//uniform float eps;

//
varying vec2 tc;
//varying vec2 tc_wavemodel;
//varying vec4 transformed_vertex;
//varying float vertex_height;

varying vec3 worldpos_vert;


varying vec4 shadow_tex_coord;
uniform sampler2DShadow shadowMap;

uniform float light_still_in_shadowed_region;

float water_height(vec2 pos2D)
{
  ///  vec2 texCoords = vec2(pos2D.x*texLookupScale.s, pos2D.y*texLookupScale.t);
  vec2 texCoords = pos2D.xy * texLookupScale.st;

  //maybe add some noise for the reflective part...
  //smaller performance-hit since FBO is quite small

  //  float z = (texture3D(wave3D, vec3(texCoords.xy, 12.0*(slice_nr/16.0))).r * waveScale + waveOff);

  //
  float z = -(texture3D(wave3D, vec3(texCoords.xy, 12.0*(slice_nr/16.0)), -0.9).r * waveScale + waveOff);


  
  return z;
}

void main() 
{
  vec4 color;

  //  float eps = (waveScale+abs(waveOff));

  float water_h = water_height(worldpos_vert.xz);

  float land_h = worldpos_vert.y;


  //  land_h -= 1.0/(water_h-land_h)*waveOff;

  //  if(land_h < water_h-0.75)
  //  if(land_h < water_h-eps)
  //
  if(land_h < water_h)
    {
      //      gl_FragColor.a = 0.0;

      //
      discard; //ORIGINAL

    }
  else
    {
      //approx color

color = vec4(0.925, 0.95, 0.975, 1.0)*texture2D(cMap, tc*vec2(4.0/ctexW, 4.0/ctexH));


   // SM stable!!!
   // 0 ... if the object is in shadow 
   // 1 ... if it is not in shadow
   if(shadow_tex_coord.q > 0.0)
     {
   float in_shadow = shadow2DProj(shadowMap, shadow_tex_coord).x;

   //   color.rgb *= max(in_shadow, 0.8); //will still be 80% of original color, if in shadow!!!

   color.rgb *= max(in_shadow, light_still_in_shadowed_region);
     }


      gl_FragColor = color;
      gl_FragColor.a = 1.0;
    }
}
