/*  Tools
 *  Copyright (C) Joakim Kolsjö and Anders Asplund 2005
 *	This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.

 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.

 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 
 */
 
#include "psys.h"
#include "random.h"
 
using namespace std;

namespace Tools
{
	Particle::Particle()
	{
		active = false;
		life = fade = r = g = b = sy = sx = sz = x = y = z
			= xd = yd = zd = xg = yg = zg = 0;
		
		for(int i = 0; i < 5; i++)
			oldx[i] = oldy[i] = oldz[i] = 0;
	}
	
	PSys::PSys()
	{
		m_nParticles = 0;
		m_nOld = 0;
	}
	
	void PSys::Update(bool xd, bool yd, bool zd, float move, float distance, float dlife)
	{
		for(int i = 0; i < m_nParticles; i++)
		{
			Particle* p = &m_pParticles[i];
			if(p->active)
			{
				// Translate
				for(int i = m_nOld-1; i > 0; i--)
				{
					p->oldx[i] = p->oldx[i-1];
					p->oldy[i] = p->oldy[i-1];
					p->oldz[i] = p->oldz[i-1];
				}
				p->oldx[0] = p->x;
				p->oldy[0] = p->y;
				p->oldz[0] = p->z;
				
				p->x += p->xd*distance*move;
				p->y += p->yd*distance*move;
				p->z += p->zd*distance*move;
				
				// Apply gravity
				p->xd -= p->xg*move;
				p->yd -= p->yg*move;
				p->zd -= p->zg*move;
								
				// Remove lifetime
				p->life -= p->fade*move;
				
				// Revive dead particle
				if(p->life < 0)
				{
					p->life = dlife;
					p->fade = Random()/10 + 0.03;
					if(xd)
						p->xd = URandom();
					if(yd)
						p->yd = URandom();
					if(zd)
						p->zd = URandom();
										
					// Reset position
					p->x = p->sx;
					p->y = p->sy;
					p->z = p->sz;
				}
			}
		}
	}
}
