// Particle spark shader (vertex)
// MVL 8-6-2010
// inspired by rain shader

// App to vertex
struct a2v
{
  float3 position     : POSITION;
  float4 color        : COLOR;      //optional
  float2 texcoords    : TEXCOORD0;
  float2 size         : TEXCOORD1;
  float3 velocity     : TEXCOORD2;  //optional
};

// Vertex to fragment shader
struct v2p
{
  float4 position     : POSITION;
  float2 uv           : TEXCOORD0;
  float  alpha        : TEXCOORD1;
};

v2p main
(
  // IN
  a2v IN,
  
  // Constants
  uniform float dt,
  uniform float4x4 modelView,
  uniform float4x4 modelViewProj,
  uniform float4x4 prevModelViewProj,
  uniform float3   eyePosW
)
{
  v2p OUT;

  const float vanishDistSquared=2.0;
  dt=dt<0.0001f?0.01f:dt;
	
	float3 worldPos=IN.position.xyz;
	float3 diff=float3(worldPos-eyePosW);
	float distSq=dot(diff, diff);
	if(distSq<vanishDistSquared)
	{
    // Too close - remove particle
    OUT.position.x=-2.0;
    OUT.position.y=-2.0;
    OUT.position.z=-2.0;
    OUT.position.w=1.0;
	}	else
	{
    // Far enough to render
    float4 newPos=mul(modelViewProj, float4(IN.position,1)); 
    float4 oldPos=mul(prevModelViewProj, float4(IN.position-(IN.velocity*dt),1));  
  
    oldPos=newPos+((oldPos-newPos)/(dt*50.0f));

    // are we new or old?
    OUT.position=lerp(oldPos, newPos, IN.texcoords.x);
  
    // offset vertexes
    OUT.position.xy+=(-0.5f+IN.texcoords)*IN.size.xy;
  }
  OUT.alpha=IN.color.a;
  OUT.uv = IN.texcoords;
  
  return OUT;
}
