/*
* This code is released under the GNU General Public License.  See COPYING for 
* details.  Copyright 2003 John Spray: spray_john@users.sourceforge.net
*/


#include <stdlib.h>
#include <math.h>
#include <string.h>

#include "Missile.h"
#include "Game.h"
#include "Particle.h"
#include "Arena.h"
#include "Visual.h"
#include "SoundCore.h"


Missile::Missile(){
	s=0.0f;
	v=0.0f;
	a=0.0f;
	res=1.0f;
	collided=0;
}

Missile::~Missile(){
}

void Missile::Physics()
{
	v*=pow(res,game->dtf);
	v+=(game->dtf * a);
	Collide();
	s+=(game->dtf * v);
}

void Missile::Explode()
{
	Particle newpart1,newpart2,newpart3;

	newpart1.s=s;
	newpart1.a=game->g;
	newpart1.rad=2;
	newpart1.life=200.0f;
	newpart1.blendmode=GL_ONE;
	strcpy(newpart1.texfile,"explosion1.png");
	for(int i=0;i<5;i++){
		newpart1.v=game->arena->GetLastQuad()->n*0.02;
		newpart1.v.x+=0.02*((float)rand()/(float)RAND_MAX)-0.01;
		newpart1.v.y+=0.02*((float)rand()/(float)RAND_MAX)-0.01;
		newpart1.v.z+=0.02*((float)rand()/(float)RAND_MAX)-0.01;
		game->visual->NewParticle(&newpart1);
	}
	newpart2.s=s;
	newpart2.a=game->g;
	newpart2.rad=0.25;
	newpart2.life=800.0f;
	newpart2.blendmode=GL_ONE;
	newpart2.collide=1;
	newpart2.bounce=PARTICLE_BOUNCE_ONE;
	strcpy(newpart2.texfile,"explosion1.png");
	for(int i=0;i<5;i++){
		newpart2.v=game->arena->GetLastQuad()->n*0.02;
		newpart2.v.x+=0.02*((float)rand()/(float)RAND_MAX)-0.01;
		newpart2.v.y+=0.02*((float)rand()/(float)RAND_MAX)-0.01;
		newpart2.v.z+=0.02*((float)rand()/(float)RAND_MAX)-0.01;
		game->visual->NewParticle(&newpart2);
	}

	newpart3.s=s;
	newpart3.a=game->g;
	newpart3.rad=3;
	newpart3.life=500.0f;
	newpart3.blendmode=GL_ONE_MINUS_SRC_ALPHA;
	strcpy(newpart3.texfile,"smoke1.png");
	for(int i=0;i<5;i++){
		newpart3.v=game->arena->GetLastQuad()->n*0.03;
		newpart3.v.x+=0.02*((float)rand()/(float)RAND_MAX)-0.01;
		newpart3.v.y+=0.02*((float)rand()/(float)RAND_MAX)-0.01;
		newpart3.v.z+=0.02*((float)rand()/(float)RAND_MAX)-0.01;
		game->visual->NewParticle(&newpart3);
	}

	game->sound->Play("boom.wav",0,s,v);

}

void Missile::Collide()
{
	for(int j=0;j<2;j++){
	if(game->arena->Collision(s,s+v*game->dtf)){
		if(v.Mag2()<0.01){
			s=game->arena->GetLastQuad()->PlaneIntersectionPoint(s,s+v*game->dtf);
			Explode();
			collided=1;
			return;
		}
		else
			v=game->arena->GetLastQuad()->BounceVector(v,0.6f);
	}
	}
}

