#version 110

varying vec4 ViewPos;
varying vec3 ViewPos3;

uniform sampler2D ColorTex;
uniform sampler2D NoiseTex;
uniform float TileRadius;

void main()
{
// vec3 color_tex = texture2D(ColorTex, TexCoord).rgb;
// vec3 noise_tex = texture2D(NoiseTex, TexCoordNoise).rgb;

 vec3 color_tex = texture2D(ColorTex, gl_TexCoord[0].xy).rgb;

/*
 vec3 n1 = 0.5   * texture2D(NoiseTex, 125    * gl_TexCoord[0].xy).rgb;
 vec3 n2 = 0.25  * texture2D(NoiseTex, 250    * gl_TexCoord[0].xy).rgb;
 vec3 n3 = 0.125 * texture2D(NoiseTex, 500.0  * gl_TexCoord[0].xy).rgb;
 vec3 n4 = 0.625 * texture2D(NoiseTex, 1000.0 * gl_TexCoord[0].xy).rgb;
 vec3 noise_tex = (n1 + n2 + n3 + n4 + 0.03125)*1.5;
*/
/*
 float n1 = texture2D(NoiseTex, 180.0  * gl_TexCoord[0].xy).r;
 float n2 = texture2D(NoiseTex, 311.0  * gl_TexCoord[0].xy).g;
 float n3 = texture2D(NoiseTex, 498.0  * gl_TexCoord[0].xy).b;
 float n4 = texture2D(NoiseTex, 943.0 * gl_TexCoord[0].xy).a;
 float noise_sum = (n1 + n2 + n3 + n4 + 0.03125)*1.5;
*/

// vec4 n = texture2D(NoiseTex, 250.0 * gl_TexCoord[1].xy);
 vec4 n = texture2D(NoiseTex, 0.0625*TileRadius * gl_TexCoord[1].xy);
 float noise_sum = (n.r + n.g + n.b + n.a + 0.03125)*1.5;

 float b = 0.7*clamp(1.0 - length(ViewPos)/300.0, 0.0, 1.0);
 noise_sum = 1.0 - b + noise_sum*b; 

 vec3 noise_tex = vec3(noise_sum, noise_sum, noise_sum);

// vec3 color = color_tex;
// vec3 color = 0.2*noise_tex +  0.8*color_tex;

 //
 // Calculate fog
 // (must clamp the z value to avoid overflow when squared).
 float coord = clamp(gl_FogFragCoord, 0.0, 300000.0);
 float fog = exp(-gl_Fog.density*gl_Fog.density*coord*coord);
 fog = clamp(fog, 0.0, 1.0);
 
 //
 // Calculate final color
 //
 vec3 color = noise_tex*color_tex;
 color = mix(vec3(gl_Fog.color), color, fog);
// color = mix(vec3(1.0, 0.0, 0.0), color, fog);
 
 gl_FragColor = vec4(color, 1.0);
} 
