#include "../include/zf.h"

#define BOMB_LIFESPAN 300
#define BOMB_RADIUS_RANGE 8.0f

int age;
float radius;
CLvertex position;
bool activated;


static ZfSmartPointer smart_pointer; 

static bool
is_valid(void* dun_care)
{
    return true;
}

static void
reference(void* meh)
{
}

static void
release(void* meh2)
{
}

static bool
query_collision(void* there_is_no_fork,
		const CLUsphere* sphere,
		const CLnormal* force,
		ZfType collider_type,
		CLvertex* collision_position,
		CLnormal* collision_force_perp,
		CLnormal* collision_force_tan)
{
    if(activated)
    {
	float dist;
	
	dist = cluVertexDistance(&sphere->origin,
				 &position);
	if(dist < (sphere->radius + radius))
	    return true;
    }
    return false;
}

static void
step(void* meh4)
{
    if(activated)
    {
	age++;
	radius+=0.1f;
	zf_ship_query_position(&position);
	if(age >= BOMB_LIFESPAN)
	    activated = false;
    }
}

static void
render(void* meh5)
{
    if(activated) 
    {
	float t;

	glPushAttrib(GL_ALL_ATTRIB_BITS);

	glDisable(GL_LIGHTING);
	glDisable(GL_TEXTURE_2D);
	glEnable(GL_DEPTH_TEST);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	t = 1.0f - (float)age/BOMB_LIFESPAN;

	glColor4f(0.8f + 0.2f * t, 
		  0.2f,
		  0.5f + 0.3f * t,
		  t*0.6f);
	
	/*glColor3f(0.0f, 0.5f*t, 0.5f*t);*/
	glPushMatrix();
	glTranslatef(position.x,
		     position.y,
		     position.z);

	glutSolidSphere(radius, 8, 8); 

	glColor4f(0.5f,
		  0.2f,
		  0.8f, 
		  t);
	glutWireSphere(radius, 8, 8); 

	glPopMatrix();

	glPopAttrib();
    }
}

void
zf_bomb_init(void)
{
    age = 0;
    activated = false;

    smart_pointer.is_valid = (ZfIsValid*) is_valid;
    smart_pointer.reference = (ZfReference*) reference;
    smart_pointer.release = (ZfRelease*) release;

    /* only one instance of bomb is needed */
    zf_animation_system_add(0,
			    &smart_pointer,
			    (ZfAnimate*)step);
    
    zf_render_system_add_translucent(0,
				     &smart_pointer,
				     (ZfRender*)render);

    /* has to be static, because the radius of the collider changes!*/
    zf_collision_system_add_static(0,
				   &smart_pointer,
				   query_collision,
				   ZF_BOMB);
}

void
zf_bomb_close(void)
{
    /* nothing atm - texture later? */
}

void
zf_bomb_new(CLvertex* ship_pos)
{
    if(!activated)
    {
	age = 0;
	radius = 0.1f; /* starting value */
       	activated = true;
	
	clCopyVertex(&position, ship_pos);
    }
}
