#version 150

in vec2 gDistance;
in vec3 gNormal;
in vec2 gTexcoord;
uniform sampler2D tex0;
uniform vec4 light_position;

const float Scale = 20.0;
const float Offset = -1.0;
const float Shininess = 42.0;
const vec3 AmbientMaterial = vec3(0.1, 0.1, 0.1);
const vec3 SpecularMaterial = vec3(0.5, 0.5, 0.5);
const vec3 FrontMaterial = vec3(1.0, 1.0, 0.5);
const vec3 BackMaterial = vec3(0.4, 0.4, 0.4);

out vec4 FragColor;


vec4 amplify(float d, vec3 color)
{
  d = Scale * d + Offset + gl_FragCoord.z;
  d = clamp(d, 0, 1);
  d = 1 - exp2(-2*d*d);
  return vec4(d*color, 1);
}

void main()
{
  vec3 N = normalize(gNormal);
  if (!gl_FrontFacing)
    N = -N;
    
  vec2 uv = gTexcoord.xy;
  uv.y *= -1.0;
  vec3 tex_color = texture(tex0, uv).rgb;
  
  vec3 L = normalize(light_position.xyz);
  vec3 Eye = vec3(0, 0, 1);
  vec3 H = normalize(L + Eye);
  float df = max(0.0, dot(N, L));
  float sf = max(0.0, dot(N, H));
  sf = pow(sf, Shininess);
  vec3 color = gl_FrontFacing ? FrontMaterial : BackMaterial;
  vec3 lighting = AmbientMaterial + df * color * tex_color;
  if (gl_FrontFacing)
  {
    lighting += sf * SpecularMaterial;
    float d = min(gDistance.x, gDistance.y);
    FragColor = amplify(d, lighting);    
  }
  else
    FragColor = vec4(lighting, 1);    
}
