// simple fragment shader

// 'time' contains seconds since the program was linked.

varying vec3 nor;
varying vec3 poz;
uniform sampler2D colMap;
uniform sampler2D norMap;
uniform sampler2D transpMap;
uniform float scaleTex;
uniform float tex_tran_y;
uniform float tex_tran_x;
uniform float tecCoordGen;
uniform float distort;
uniform float norMapStrength;
uniform float lightAmount;
uniform float reflAmount;

varying vec3 vertex;
varying vec3 position;
bool eyeAtOrigin = true;
vec4 getTexture(sampler2D tex)
{
		vec4 col;
		vec2 sc=vec2(scaleTex);
		vec2 tran=vec2(tex_tran_x,tex_tran_y) ;
		if(tecCoordGen==1)
		{
			
	   		col =  texture2D(tex,(vertex.xz+ tran)*sc)*(nor.y*nor.y);
	    	col += texture2D(tex,(vertex.xy+ tran)*sc)*(nor.z*nor.z);
	   	 	col += texture2D(tex,(vertex.yz+ tran)*sc)*(nor.x*nor.x);


		}
		else
			col = texture2D(tex,(gl_TexCoord[0].xy+ tran) * sc );

		return col;
}

vec4 lightSource( vec3 N, vec3 V, gl_LightSourceParameters light )
{
	vec3  H;
	float d = length( light.position.xyz - V );
	vec3  L = normalize( light.position.xyz - V );

	if(eyeAtOrigin)
	H = normalize( L + vec3( 0.0, 0.0, 1.0 ) );
	else	
	H = normalize( L );

	float NdotL = max( 0.0, dot( N,L ) );
	float NdotH = max( 0.0, dot( N,H ) );

	float Idiff = NdotL;
	float Ispec = pow( NdotH, gl_FrontMaterial.shininess );


	// 'real' shading
	return 
		gl_FrontMaterial.ambient  * light.ambient +
		gl_FrontMaterial.diffuse  * light.diffuse  * Idiff +
		gl_FrontMaterial.specular * light.specular * Ispec;
}
vec3 getNormal()
{
	
	vec3 N = normalize( nor + getTexture(norMap).xyz-vec3(0.5) );
	return N;
}

float getTransp()
{
	vec3 t = getTexture(transpMap).xyz;
	float rez = (t.x+t.y+t.z)/3.0f;
	return rez;
}
//
// computes light of all light sources and the scene.
//
vec4 lighting( void )
{

	//vec3 N = normalize( normal + getTexture(norMap).xyz-vec3(0.5) );
	vec3 N = getNormal();
	return
		gl_FrontMaterial.emission +
		gl_FrontMaterial.ambient * gl_LightModel.ambient +
		(lightSource( N, poz, gl_LightSource[0] )+
		lightSource( N, poz, gl_LightSource[1] ) );
}

void main()
{
	vec2 uv = gl_TexCoord[0].xy;
	vec2 uv2 = poz.xy / vec2(poz.z);
	uv2.y=-uv2.y;
	uv2 = uv2/vec2(2)+vec2(.5);

	vec2 uv3= uv2;
	uv3 += (nor.xy+vec2(nor.z)+(getNormal().xy-vec3(.5))*norMapStrength)*vec2(distort);

	vec4 col = texture2D(colMap,uv3)*reflAmount +lighting()*lightAmount;
	gl_FragColor = gl_Color* col;
	gl_FragColor = col;
}
