// FRAGMENT SHADER :  TEXTURE + BUMP

uniform sampler2D diffMap2D;
uniform sampler2D normalMap2D;

uniform float textureScale;
uniform vec4 matColor;

varying vec3 vLight0;
varying vec3 vHalfAngleVec0;
varying vec3 vLight1;
varying vec3 vVertex;
varying vec3 vNormal;

vec2 tGetAutomaticTexCoords(vec3 pos, vec3 normal)
{
      float dotX = dot(normal,vec3(1.0,0.0,0.0));
      float dotY = dot(normal,vec3(0.0,1.0,0.0));
      float dotZ = dot(normal,vec3(0.0,0.0,1.0));
      float adotX = abs(dotX);
      float adotY = abs(dotY);
      float adotZ = abs(dotZ);
      
      vec3 npos = pos - vec3(0,0,0);
      vec2 texCoordOut = npos.xy;
      if(dotZ > 0.0)
      {
            texCoordOut = npos.xy;
      }
      else
      {
            texCoordOut = vec2(npos.x,-npos.y);
      }
      if(adotX > adotY)
      {
            if(adotX > adotZ)
            {
                  if(dotX > 0.0)
                  {
                        texCoordOut = npos.yz;
                  }
                  else
                  {
                        texCoordOut = vec2(-npos.y,npos.z);
                  }
            }
      }
      else if(adotY > adotZ)
      {
            if(dotY > 0.0)
            {
                  texCoordOut = vec2(-npos.x, npos.z);
            }
            else
            {
                  texCoordOut = vec2(npos.x,npos.z);
            }
      }
      return texCoordOut;
}

void main()
{
	vec2 localTexCoord = tGetAutomaticTexCoords(vVertex.xyz, vNormal.xyz);

	// Fetch bump normal
	vec3 bumpNormal = vec3(texture2D(normalMap2D, localTexCoord.xy*textureScale, 0.0)) - vec3(0.5);

	// Fetch texture color
	vec4 color = texture2D(diffMap2D, localTexCoord.xy*textureScale, 0.0);

	vec4 illumination = vec4(0.0);
	vec4 spec = vec4(0.0);

	// Calc light0 products
	float LdotB = clamp(dot(vLight0.xyz, bumpNormal), 0.0, 1.0);

	// Look up illumination
//	illumination = LdotB * gl_LightSource[0].diffuse;
	illumination = LdotB * vec4(matColor.xyz, 1.0);

	float ndoth = dot(bumpNormal, vHalfAngleVec0);
	ndoth = clamp(ndoth, 0.0, 1.0);
	ndoth = pow(ndoth, gl_FrontMaterial.shininess); // specular exponent in w
//	spec += ndoth * gl_FrontMaterial.specular * gl_LightSource[0].specular;
	spec += ndoth * vec4(0.2, 0.2, 0.2, 1.0);

	// Combine all
//	gl_FragColor = clamp(spec + (illumination * color) + gl_FrontLightModelProduct.sceneColor*color, 0.0, 1.0);
	gl_FragColor = clamp(spec + (illumination * color), 0.0, 1.0);

//	gl_FragColor = vec4(vLight0.xyz, 1.0);
}
