float noise(vec2 pos,int seed);
float cosInterpolate(vec2 a, float x);
float smooth_2d_noise(vec2 pos,int seed);

float noise(vec2 pos,int seed) {
	float ret = fract(sin(seed+dot(pos,vec2(12.9898,78.233)))*43758.5453)*2.0-0.8;
	return ret;
}

float smooth_2d_noise(vec2 pos,int seed) {
	vec3 a = vec3(0,0,0);
	float ret;
	a.x = (noise(vec2(pos.x-1,pos.y-1),seed) + noise(vec2(pos.x+1,pos.y-1),seed) + noise(vec2(pos.x-1,pos.y+1),seed) + noise(vec2(pos.x+1,pos.y+1),seed)) / 16;
	a.y = (noise(vec2(pos.x-1,pos.y),seed) + noise(vec2(pos.x+1,pos.y),seed) + noise(vec2(pos.x,pos.y-1),seed) + noise(vec2(pos.x,pos.y+1),seed) ) / 8;
	a.z = noise(pos,seed)/4;
	ret = a.x + a.y + a.z;
	return ret;
}

float cosInterpolate(vec2 a, float x) {
	float ft,f,ret;
	float PI = 3.14159265358979323846264;
	ft = (x*PI);
	f = ((1-cos(ft)) * 0.5);
	ret = a.x*(1-f)+a.y*f;
	return ret;
}


float cos_2d_noise(vec2 pos, int seed) {
	vec2 int_pos = floor(pos);
	vec2 frac_pos = pos - int_pos;//fract(pos);
	float ret;
	vec4 v;
	vec2 i;
	
	v.x = smooth_2d_noise(int_pos,seed);	
	v.y = smooth_2d_noise(vec2(int_pos.x+1.0,int_pos.y),seed);
	v.z = smooth_2d_noise(vec2(int_pos.x,int_pos.y+1),seed);
	v.a = smooth_2d_noise(vec2(int_pos.x+1.0,int_pos.y+1.0),seed);
	
	i.x = cosInterpolate(vec2(v.x,v.y),frac_pos.x);
	i.y = cosInterpolate(vec2(v.z,v.a),frac_pos.x);
	
	ret = cosInterpolate(i,frac_pos.y);
	
	return ret;
}


float perlinNoise(vec2 pos,int seed) {
	int i;
	float ret = 0.0;
	float freq,amp;
	int p = 3;
	int n = 3;
	
	for(i=0;i<n;i++) {
		freq = pow(2,i);
		amp = pow(p,i);
		ret += cos_2d_noise(vec2(pos.x*freq,pos.y*freq),seed) *amp;
		ret += 0.1;
	}
	
	return ret;
}






uniform float timer;

varying vec3 position;
varying vec4 diffuse,ambientGlobal, ambient,normal;
varying vec3 lightDir,halfVector;
varying float dist; 

uniform sampler2D tex0,tex1,tex2;


void main() {
	vec4 t0 = texture2D(tex0,gl_TexCoord[0].st);
	vec4 t1 = texture2D(tex1,gl_TexCoord[0].st);
	vec4 t2 = texture2D(tex2,gl_TexCoord[0].st);
	vec3 bump;
	vec2 scale = vec2(500,500);
	
	bump.x = (cos_2d_noise(gl_TexCoord[0].st*scale,25))*0.1;
	bump.y = (cos_2d_noise(gl_TexCoord[0].st*scale,2500))*0.1;
	bump.z = (cos_2d_noise(gl_TexCoord[0].st*scale,236))*0.1;

	vec3 n,halfV,viewV,ldir;
	float NdotL,NdotHV;
	vec4 color = vec4(0.01,0.01,0.01,1);
	float att;
	vec4 fog=vec4(1,1,1,1);


	fog *= (normal.a*0.4);



	n = normalize(normal.xyz);
	n+=bump;

	NdotL = max(dot(n,normalize(lightDir)),0.0);
		att = 1.0 / (gl_LightSource[0].constantAttenuation +
				gl_LightSource[0].linearAttenuation * dist +
				gl_LightSource[0].quadraticAttenuation * dist * dist);
		color += att * (diffuse * NdotL + ambient);
		halfV = normalize(halfVector);

		NdotHV = max(dot(n,halfV),0.0);
		color += att * gl_FrontMaterial.specular * gl_LightSource[0].specular * pow(NdotHV,10.0/*gl_FrontMaterial.shininess*/);


	gl_FragData[0]=color;
	gl_FragData[0].a=1.0;
	gl_FragData[1] = normal;
	//gl_FragData[1].a = 0.0;
}
