attribute vec4 pos;
attribute vec2 tex; 

varying vec2 tc;
varying float visibility; 
varying float unique; 

uniform vec3 eyePos; 
uniform mat4 viewproj; 
uniform mat4 view; 
uniform mat4 tview;
uniform mat4 world;
uniform vec3 dynLightPos;

uniform float time; 
uniform int flip=0; 

float rand( vec2 n ) {
   return fract(sin(dot(n.xy, vec2(12.9898, 78.233)))* 43758.5453);
}

vec2 rotZ(vec2 p, float rad)
{
   mat2 r; 
   r[0] = vec2(cos(rad), -sin(rad));
   r[1] = vec2(sin(rad), cos(rad));
   return p*r;
}   

float farPlane = 120.0;
float focalPoint = 00.0;
float exponent = 1.0; 

float d(vec3 p) {
	float l = (abs(length(p-eyePos)-focalPoint))/farPlane;
	return clamp(1.0, 0.0, pow(l, exponent));
}

float fog_mul = 1.0;
float fogf(vec3 p) {
	float l = (abs(length(p-eyePos)))/farPlane;
	return clamp(1.0, 0.0, fog_mul*(1.0-.3*pow(l, exponent)));
}


void main()
{	
	/* Calculate Billboard */
	vec4 center = vec4((pos.xy-.50)*2.0, 0.0, 1.0); 
	vec4 bboard = 5.0*(center.x*tview[0]+center.y*tview[1]);

	/* Compute Position */
	float s = pos.z;//+floor(time); 
	unique = s; 										// unique identifier
	float x = 3000.0*rand(vec2(s, s))-1500;
	float y = 200+400*rand(vec2(s, s*232.3+3.2));
	float z = rand(vec2(s+2.32, 43.3))+time*.5;
	float adjZ = z-floor(z);
	adjZ = (adjZ-.5f)*4000.0;
	vec4 uPos = vec4(x,y,adjZ, 1.0);

	vec4 particlePos = uPos+bboard;
	gl_Position = viewproj*world*vec4(particlePos.xyz, 1.0);

	/* Compute TexCoords */ 
	tc = tex;
	float type = (pos.z/4.0-floor(pos.z/4.0))*4.0;
	tc = vec2(tex.x, tex.y/4.0+type*.25);

	/* Fog */
	float fog = 1.0-min(1.0, pow(length(uPos-eyePos)/2500.0, .1275));
	float verticalGrad = min(1.0, pow(uPos.y/100.0, 1.20));
	float blinc = .5+.5*sin(s+time*.01);
	visibility	= blinc*fog*verticalGrad*1.0*rand(vec2(s, s)); 
	//visibility = rand(vec2(s*23.32+2.3, s));
}	

//FRAGMENT
uniform sampler2D Texture0; 
uniform sampler1D Texture2;
uniform float time;
uniform float amplifier; 
float rand( vec2 n ) {
   return fract(sin(dot(n.xy, vec2(12.9898, 78.233)))* 43758.5453);
}


void main()
{  
	gl_FragColor = vec4(tc, 0, 1.0);
	gl_FragColor = texture2D(Texture0, tc);
	gl_FragColor.rgb = vec3(3.0);
	gl_FragColor.a *= visibility;
	gl_FragColor.a *= amplifier;
	//gl_FragColor.a *= 1.0+4.0*pow(clamp((amplifier-11000.0)/600.0, 0.0, 1.0), 30.0);
	
	gl_FragColor.a *= texture1D(Texture2, unique/20.0)*1.40;
	return; 

	float density = max(0.0, 1.0-min(sqrt(2.0), .5*length(tc-.5)));///sqrt(1.0); //Normalize 0-1
	float light = pow(max(0.0, density), 25.);
	float l2 = pow(max(0.0, density), 1.);
 	light = light*.95+.05*rand(vec2(tc+vec2(time*.01)));
 	gl_FragColor = vec4(light*l2);
	return;
}

