attribute vec4 pos;
attribute vec2 tex; 

varying vec2 tc;
varying vec4 color; 
varying float unique;  
varying float uniqueCycle;  

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 = 360.0*(center.x*tview[0]+center.y*tview[1]);

	/* Compute Position */
	vec4 uPos = vec4(dynLightPos, 0.0);
	vec4 particlePos = uPos+bboard;
	gl_Position = viewproj*vec4(particlePos.xyz, 1.0);

	tc = tex;
	unique = pos.z;
	color = fogf(uPos.xyz);
	color.r *= 2.0*rand(pos.z);
	color.g *= 2.0*rand(pos.z+.1);
	color.b *= 2.0*rand(pos.z+.3);
}	

//FRAGMENT
uniform float time;
uniform float sunMultiplier; 

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


void main()
{  
	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);
 	gl_FragColor.rgb *= sunMultiplier; 
	return;
}

