//varying vec3 ViewPos;
//varying vec3 up;
varying vec3 WorldNormal;
varying vec4 projPos;
varying vec3 Nscreen;

uniform sampler2D Color0; // celshadey
uniform sampler2D Color1; // ground
uniform sampler2D Height; // mix

uniform sampler2D SceneLight;
uniform sampler2D SceneNormal;

uniform vec3 GrassColorScale;
uniform vec3 GrassColorBias;

const float scale = 0.02;
const float bias  = -0.02;

void main()
{
  //vec3 e = -normalize( ViewPos );

  // compute normal for cel-shading like
  vec2 texScene = projPos.xy / projPos.w * .5 + .5;
  vec4 buff = texture2D( SceneNormal, texScene );
  vec3 norm = 2.0 * buff.xyz - 1.0;
  vec4 light = texture2D( SceneLight, texScene );

  //float dist = buff.a;

  //vec2 xprojscale = 0.112233 * gl_TexCoord[1].xy;
  //vec2 yprojscale = 0.112233 * gl_TexCoord[2].xy;
  //vec2 zprojscale = 0.112233 * gl_TexCoord[3].xy;

  
  // arbitrary offset
  //float arbscale = 0.0;

  //if( dist < 100.0 ) {
  //  // Parallax
  //  vec3 h;
  //  h.x = 1.0 - texture2D( Height, gl_TexCoord[1].xy ).x * Nscreen.x;
  //  h.y = 1.0 - texture2D( Height, gl_TexCoord[2].xy ).x * Nscreen.y;
  //  h.z = 1.0 - texture2D( Height, gl_TexCoord[3].xy ).x * Nscreen.z;
  //  h *= scale;
  //  h += bias;
  //  
  //  vec2 offsetx = h.x * e.yz;//vec2( 0.0 );//
  //  vec2 offsety = h.y * e.xz;//vec2( 0.0 );//
  //  vec2 offsetz = h.z * e.yx;//vec2( 0.0 );//

  //  xprojscale += offsetx;
  //  yprojscale += offsety;
  //  zprojscale += offsetz;

  //  arbscale += h.x + h.y + h.z;
  //}
  
  // blend projected textures
  float grasschance = WorldNormal.y ;//+ arbscale;// + t.x - t.y;
  grasschance -= 0.3;
  grasschance = clamp( grasschance, 0.0, 0.5);//.0 );

  vec3 color = texture2D( Color1, gl_TexCoord[1].xy ).rgb * Nscreen.x +
               texture2D( Color1, gl_TexCoord[3].xy ).rgb * Nscreen.z;
  
  vec3 gcolor = ( 1.0 - grasschance ) * texture2D( Color1, gl_TexCoord[2].xy ).rgb + 
                (grasschance * grasschance) * GrassColorScale + 
                grasschance * GrassColorBias;

  color.rg = color.gr;
color += gcolor;
  
  //float colormod = mix( 1.0, arbscale/scale, ViewPos.z / 2000.0 );
  //color *= colormod;
  
  // weird lighting thing
  //vec2 texCoord;
  //vec3 e = -normalize( ViewPos.xyz );
  // v coord is normal dot up for a lighting like effect
  //texCoord.y = max( dot( norm.xyz, up ), 0.0 ) * 0.45 + 0.5;
  // u coord is normal dot eye for cel-shading like effect
  //texCoord.x = abs( dot( norm, e ) ) * 0.81 + 0.19;//max( dot( norm.xyz, e ), 0.0 ) * 0.81 + 0.19;//0.9+ 0.1;
  //texCoord.y = 1.0;//texCoord.x * 0.45 + 0.5;//
 
  // modulate with texture color
  //color *= texture2D( Color0, texCoord ).rgb;
  
  //float p = 1.0; // plasticity
  //light.a *= 2.54;
  vec3 lightColor = light.rgb + light.a;// * (( 1.0 - p ) * light.rgb + vec3( p, p, p ));
  //color = vec3(0.4, 0.4, 0.4);
  color *= lightColor;

  gl_FragColor = vec4( color, 1.0 );//vec4( ViewPos, 1.0 );//vec4( shadow, shadow, shadow, 1.0 );//
}