#include <allegro.h>

#include "main.h"
#include "object.h"
#include "particle.h"
#include "util.h"
#include "world.h"

static void init_particle(Object* obj, Particle* p)
{
	float angle;
	float vel;
	ParticleBurst* burst;

	burst = (ParticleBurst*)obj->data;
	
	angle = rand_num(burst->angle - burst->width,
			burst->angle + burst->width);
	vel = rand_num(0.5, burst->vel);

	p->x = obj->x;
	p->y = obj->y;
	p->dx = cos(angle) * vel;
	p->dy = -sin(angle) * vel;
	p->age = rand_num(1, 31);
	p->size = rand_num(0, 2);
}

static void particleburst_logic(Object* obj)
{
	Particle* p;
	Particle* end;
	int mickey_x, mickey_y, dist;
	int quota;
	
	p = ((ParticleBurst*)obj->data)->particles;
	end = p + ((ParticleBurst*)obj->data)->max;

	quota = ((ParticleBurst*)obj->data)->rate;
	
	for (; p < end; p++) {
		if (p->age > 0) {
			p->x += p->dx;
			p->y += p->dy;
			p->age--;
		} else if (quota > 0) {
			init_particle(obj, p);
			quota--;
		}
	}
/* Cool stuff to play with here */

	get_mouse_mickeys(&mickey_x, &mickey_y);
	dist = sqrt(mickey_x * mickey_x + mickey_y * mickey_y);

/* Make angle sensitive to direction of mouse motion */
	if (dist > 0) ((ParticleBurst*)obj->data)->angle = M_PI -
			atan2(mickey_y, mickey_x);

/* Make angle spiral around */
/*	((ParticleBurst*)obj->data)->angle += M_PI / 16; */

/* Make position correspond to mouse */
	obj->x = mouse_x;
	obj->y = mouse_y;

/* Make velocity constant */
	((ParticleBurst*)obj->data)->vel = 1.5;

/* Make velocity correspond to mouse velocity */
/*	((ParticleBurst*)obj->data)->vel = dist; */

/* Make rate constant */
/*	((ParticleBurst*)obj->data)->rate = 256; */

/* Make rate correspond to mouse velocity */
	((ParticleBurst*)obj->data)->rate = dist * 32;
}

static void particleburst_render(Object* obj)
{
	Particle* p;
	Particle* end;
	int x, y;
	
	p = ((ParticleBurst*)obj->data)->particles;
	x = -obj->world->x;
	y = -obj->world->y;

	end = p + ((ParticleBurst*)obj->data)->max;

	for (; p < end; p++) {
		if (p->age > 0)	rectfill(buf, p->x + x, p->y + y, p->x + x +
				p->size, p->y + y + p->size, p->age);
	}
}

static void particleburst_free(Object* obj)
{
	free(((ParticleBurst*)obj->data)->particles);
}

Object* make_particleburst(World* world, int x, int y, int max, float angle,
		float width, float vel, int rate)
{
	Object* obj;
	ParticleBurst* burst;
	
	obj = malloc(sizeof(Object));
	burst = malloc(sizeof(ParticleBurst));
	
	obj->world = world;
	obj->data = burst;
	obj->x = x;
	obj->y = y;
	obj->logic = particleburst_logic;
	obj->render = particleburst_render;
	obj->free = particleburst_free;
	obj->next = NULL;
	
	burst->particles = malloc(sizeof(Particle) * max);
	burst->max = max;
	burst->angle = angle;
	burst->width = width;
	burst->vel = vel;
	burst->rate = rate;
	
	return obj;
}

