//Copyright (C) 2007 SiegeLord
//See ReadMe.txt and License.txt for copying information

#include "thruster.h"

SThrusterParticleHolder* CreateThrusterParticleHolder(SObject* parent, SObject* target_object, SBitmap* bmp, zColor color)
{
	SThrusterParticleHolder* hold = new SThrusterParticleHolder(50);

	InitParticleHolder(hold, parent);

	hold->bmp = bmp;
	hold->restart = true;

	hold->dampening = 0.75;
	hold->random_vel_x = 5.0f;
	hold->random_vel_y = 65.0f;
	hold->max_life = 1.0f;
	hold->min_life = 0.5f;
	hold->acceleration = 40;
	hold->throttle = 150;
	hold->color = color;
	hold->target_object = target_object;

	hold->CreateBuffers();

	return hold;
}

int SThrusterParticleHolder::Handle()
{
	int num_reset = 0;

	if(target_object)//is our target still alive?
	{
		net_transform = local_transform;
		target_object->net_transform.TransformTransform(&net_transform);
	}

	FOR1(num_particles)
	{
		SParticle* part = &(particles[ii]);
		if(part->life <= 0 && num_reset < throttle * g_fDelta && target_object)//we reset it
		{
			num_reset++;
			part->life = Rand(min_life, max_life);

			part->position = GetGlobalPosition();
			vector2d new_vel(random_vel_y, Rand(-random_vel_x, random_vel_x));

			net_transform.RotateVector(&new_vel);

			part->velocity.y = new_vel.y;
			part->velocity.x = new_vel.x;
		}
		else
		{
			part->life -= g_fDelta;
			//part->velocity.y += acceleration * g_fDelta;
			part->velocity.y *= powf(dampening, g_fDelta);
			part->velocity.x *= powf(dampening, g_fDelta);

			part->position = part->position + part->velocity * g_fDelta;
		}

		float factor = part->life / max_life;
		if(factor < 0)
			factor = 0;

		factor = 1 - factor;

		if(factor < 0.75)
			part->color = BlendColors(0xffffffff, color, factor / 0.75);
		else
			part->color = BlendColors(color, 0x00000000, (factor - 0.75) / 0.25);
	}


	UpdateBuffers();

	if(!target_object && num_alive_particles == 0)
		dead = true;

	return 1;
}

void SThrusterParticleHolder::Draw()
{
	if(num_alive_particles > 0)
	{
		DrawModeAdd();

		DrawQuadBuffer(bmp, num_alive_particles, vertices, tcoords, colors);

		DrawModeSolid();
	}
}
