/*************************************************************
GLSL Demo - Bump mapping fragment shader
(c) 2005 Antoine Bouthors, EVASION
*************************************************************/

uniform sampler2D Tex2D;
varying vec3 normal;
varying vec3 lightDir;
varying vec3 pos2;

void main()
{
	vec4 fragment = texture2D( Tex2D, gl_TexCoord[0].xy );
	float gradientX = length( dFdx( fragment ) )/abs( dFdx( pos2.x ) );
	float gradientY = length( dFdy( fragment ) )/abs( dFdy( pos2.y ) );
	vec3 NormalizedNormal = normalize( normal );
	vec3 nx = normalize( dFdx( NormalizedNormal ) );
	vec3 ny = normalize( dFdy( NormalizedNormal ) );
	
	vec3 Newnormal = normalize( NormalizedNormal + .05*( gradientX*nx + gradientY*ny ) );
	
	vec3 NlightDir = normalize( lightDir );
	vec3 ReflectedRay = reflect( NlightDir, Newnormal );
	
	vec3 color = vec3( clamp( pow( dot( ReflectedRay, vec3( 0., 0., -1. ) ), 10. ), 0., 1. ) );
	float dp = dot( NormalizedNormal, NlightDir );
	if( dp > 0. ) dp = dot( Newnormal, NlightDir );
	color += gl_LightSource[0].diffuse.xyz * clamp( dp, 0., 1. );

	gl_FragColor.xyz = .5*fragment.xyz + .5*color;
}
