#include "gravityModule.h"

//-------------------------------------------------
gravityModule::gravityModule(){
	ofSeedRandom();
	bgColor.set(0,0,0);
	
}

//-------------------------------------------------	
void gravityModule::setup(){
	reset();
}

//-------------------------------------------------
void gravityModule::reset(){
	
	pct 			= 0;
	framecount 		= 0;
	radius			= 8;
	
	
	whichSide = rand()%3;	
	
	
	vel.set( cos(0) * 10, sin(0) * 8, 0);

	//pos.set( 0, 120, 0);				//works fine
	pos.set( 0, 120 + rand()%240, 0); //doesn't work - hmmm
	startPos = pos;
			
	switch(whichSide){
		
		case 0:
			dst.set(160 + rand()%320, -radius * 4, 0);
		break;
		
		case 1:
			dst.set(640 + radius*4,  rand()%480, 0);
		break;
		
		case 2:		
			dst.set(160 + rand()%320, 480 + radius*4, 0);
		break;
	
		default:
		
		break;
	}
	
	
}

//-------------------------------------------------
void gravityModule::update(){
	
	//record our trail
	trail[framecount] = pos;
	
	angle			= dst - pos;
	ofVec3f tmpVel 	= angle;
	float dist 		= tmpVel.length();
	
	tmpVel.normalize();
	
	//lets make it easier to find its
	//target as it gets closer
	if(dist > 4*radius){
		tmpVel *= 0.2;
	}
	else{
		tmpVel *= 0.8;
	}
	
	vel *= 0.955;
	vel += tmpVel;
	pos += vel;
	
	
	//detect when we ave gone off the screen
	if( 
	    (whichSide == 2 && pos.y > 480 + radius*2) ||
	    (whichSide == 0 && pos.y < -radius*2) 	   ||
	    (whichSide == 1 && pos.x > 640 + radius*2) ){
		
		pct = 1.1;	
	}
	
	if (framecount % 5 == 0) addPoint(pos);
	framecount++;
}

//-------------------------------------------------
void gravityModule::draw(){
	
	ofSetColor(0xff00ff);
	
	//draw trail
	glBegin(GL_LINE_STRIP);
	for(int i = 0; i < framecount; i++){
		glVertex2f(trail[i].x, trail[i].y);
	}
	glEnd();
	
	//draw angle vector to goal
	glPushMatrix();
		glTranslatef(pos.x, pos.y, 0);
		glRotatef( (180*( atan2f(angle.y, angle.x))/PI), 0, 0, 1);
		
		glBegin(GL_LINES);
			glVertex2f(0, 0);
			glVertex2f(100, 0);
		glEnd();
		
	glPopMatrix();
	
	ofSetColor(0xffffff);
	
	//draw starting angle
	glPushMatrix();
		glTranslatef(startPos.x, startPos.y, 0);
		glRotatef( (180*(endAngle)/PI), 0, 0, 1);
		
		glBegin(GL_LINES);
			glVertex2f(0, 0);
			glVertex2f(100, 0);
		glEnd();
		
	glPopMatrix();	
	
	
	//draw current angle
	glPushMatrix();
		glTranslatef(pos.x, pos.y, 0);
		glRotatef( (180*( atan2f(vel.y, vel.x))/PI), 0, 0, 1);
		
		glBegin(GL_LINES);
			glVertex2f(0, 0);
			glVertex2f(100, 0);
		glEnd();
		
	glPopMatrix();	
	
	//draw particle
	ofCircle(pos.x, pos.y, radius);
}

//-------------------------------------------------
bool gravityModule::bAmIdone(){
	return pct > 1 ? true : false;
}

//-------------------------------------------------
ofVec3f gravityModule::getStartPosition(){
	
	return startPos;
}

//-------------------------------------------------
float gravityModule::getStartAngle(){
	return 0;
}
		
		