///////////////////////////////////////////////////////////////////////////
// 
//	Asteroid .cpp
//	Jesse Doane
//  April 2000

#include "asteroid.h"

Asteroid::Asteroid( Vertex* h ){

heading = h;
}
////////////////////////////////////////////////////////////////////////////

void Asteroid::AddEdge( Edge* e ){

edges.PushFront( e, 0 );
}
///////////////////////////////////////////////////////////////////////////
// 
//  naive collision detection.
// 
//  checks each edge of this asteroid with each edge of the other for
//  intersection

bool Asteroid::Collision( Asteroid* a ){

Edge* me;
Edge* you;
int collision = 0;
bool c1 = true; 
bool c2 = true;

this->edges.SetCurRear();

// for each edge in this asteroid
while( c1 ){
	
	c1 = this->edges.Forward( &me );
	a->edges.SetCurRear(); 
	
	// for each edge in the other
	while( c2 ){

		c2 = a->edges.Forward( &you );
		// collision?
		if( me->bIntersection( you ) ){
			
			collision++;
		}
	}
	c2 = true;
}
if( collision ){

// here is my very bad physics simulation

	this->heading->x = -this->heading->x;
	this->heading->y = -this->heading->y;
	a->heading->x = -a->heading->x;
	a->heading->y = -a->heading->y;

//  "bounce" the asteroids
	this->Move();
	a->Move();
}
return collision;
}
///////////////////////////////////////////////////////////////////////////////
//
// translate each edge in the asteroid by the asteroid's heading
// and check for collision with the world boundary

void Asteroid::Move( void ){

Edge* me;
int cb = -1;
bool flip_y, flip_x;
bool c = true;
flip_y = flip_x = false;

edges.SetCurRear();

while( c ){
	
	c = edges.Forward( &me );
	me->Add( heading );
	if( !flip_y && !flip_x ){
		
		if( (cb = me->CheckBounds()) > -1 ){
		
			if( cb == HIT_BOTTOM || cb == HIT_TOP ) flip_y = true;
			if( cb == HIT_RIGHT || cb == HIT_LEFT ) flip_x = true;
		}
	}
}
if( flip_x ) heading->x *= -1;
if( flip_y ) heading->y *= -1;
}

///////////////////////////////////////////////////////////////////////////

void Asteroid::Draw( UCHAR* canvas ){
	
Edge* me;
bool c = true;

edges.SetCurRear();

while( c ){

	c = edges.Forward( &me );
	me->Draw( canvas );
}}
