varying vec2 	texcoord;

#ifdef PSYSTEM

uniform	vec4 	pparams[100];
uniform vec4	prevPParams[100];

vec4		tpos;
uniform vec4	data;
uniform vec3 	campos;
uniform vec3 	camdir;

//attribute vec4	index; // pparams.x=particle size pparams.w=particle index
varying float 	life;
uniform vec3	particleScale;

#endif

uniform vec2	tofs;
varying vec4 	curpos,
				prev;
uniform mat4	prevMVM,
				prevWTM/*,
				WTM*/;
uniform vec2	NF;
uniform vec2 	tscale0;


vec2 ComputeFrame(float dt)
{
	vec2 ofs=vec2(1.0,1.0)/NF;
	float frame=floor(dt*NF.x*NF.y);
	float row=floor(frame/NF.x);
	float col=floor(frame-NF.x*row);
	
	return vec2(ofs.x*col, 1.0-(ofs.y*row)-ofs.y);
}

void main()
{
	vec2 texOfs=tofs;
	
	#ifdef PSYSTEM

		vec4 ppos=pparams[int(/*index.x*/gl_Color.x)];
		life=ppos.w;
		float invLife=clamp(1.0-life,0.0,1.0);
		
		if(data.w==0.0)
		{
			float scale=data.x + (data.y*invLife);
			scale=clamp(scale,0.0,abs(scale))*0.5;
			scale+=scale*/*index.y*/gl_Color.y;	
			ppos.w=1.0;

			float angle=(/*index.y*/gl_Color.y*6.28)+(data.z*invLife*6.28);

			float cosa=cos(angle);
			float sina=sin(angle);

			tpos=gl_ModelViewMatrix * ppos;	

			vec3 tv=gl_Vertex.xyz;
			tv.x=(gl_Vertex.x*cosa)-(gl_Vertex.y*sina);
			tv.y=(gl_Vertex.x*sina)+(gl_Vertex.y*cosa);
			tpos.xyz=(tv.xyz*particleScale*scale + tpos.xyz);
		}
		else
		{
			vec4 prevpos=prevPParams[int(/*index.x*/gl_Color.x)];
			prevpos.w=1.0;
						
			mat3 rTM;
			//vec3 cam=campos;
			//cam.y=ppos.y;
			
			vec3 vel=ppos.xyz-prevpos.xyz;
			vec3 dir;//=normalize(ppos.xyz-cam);
			vec3 vdir=normalize(vel);
			vec3 rgt=normalize(cross(vdir,camdir));
			dir=cross(vdir,rgt);
			rTM[2]=dir;
			rTM[0]=rgt;
			rTM[1]=vdir;

			float scale=length(vel);
			vec4 rpos;
			rpos.xyz=gl_Vertex.xyz*data.x;
			rpos.y+=(gl_Vertex.y*particleScale.y*scale);
			rpos.xyz=(/*wtm*/rTM*rpos.xyz) + ppos.xyz;
			rpos.w=1.0;
			tpos=gl_ModelViewMatrix*rpos;
		}
		
		gl_Position=gl_ProjectionMatrix*tpos;			
		texOfs=ComputeFrame(invLife);
		
	#else

		gl_Position = (gl_ModelViewProjectionMatrix)*gl_Vertex;//ftransform();

	#endif

	texcoord = gl_MultiTexCoord0.st*tscale0 + texOfs;
}