#include "testApp.h"

//--------------------------------------------------------------
void testApp::setup() {
	
	ofBackground(0, 0, 0);
	ofSetLogLevel(OF_LOG_NOTICE);
	ofSetVerticalSync(true);
	
	// Box2d
	box2d.init();
	box2d.checkBounds(true);
	box2d.setGravity(0, 8);
	box2d.createFloor();
	box2d.setFPS(30.0);
	box2d.disableGrabbing(); // be careful when grabbing something that is about to die
	spill = true;
	
	
}


//--------------------------------------------------------------
void testApp::update() {
	if(spill){	
		if((int)ofRandom(0, 5)==3) {
			for(int i=0; i<ofRandom(3, 4); i++) {
				ofxBox2dCircle p;
				p.setPhysics(1.0, 0.7, 0.3);
				p.setup(box2d.getWorld(), (ofGetWidth()/2)+ofRandom(-20, 20), 50, ofRandom(3, 15));
				particles.push_back(p);	
			}
		}
	}
	box2d.update();	
	
	float top		= 0;
	float bottom	= ofGetHeight();
	float right		= ofGetWidth();
	float left		= 0;
	
	for(int i=0; i<particles.size(); i++) {
		ofPoint p = particles[i].getPosition();
		if(p.y > bottom) {
			particles[i].destroyShape();
		}
		if(p.y < top) {
			particles[i].destroyShape();
		}
		if(p.x > right) {
			particles[i].destroyShape();
		}
		if(p.x < left) {
			particles[i].destroyShape();
		}
	}
	
	for(int i=particles.size()-1; i>=0; i--) {
		if(particles[i].dead) particles.erase(particles.begin() + i);
	}
	
}

//--------------------------------------------------------------
void testApp::draw() {
	
	
	for(int i=0; i<particles.size(); i++) particles[i].draw();
	
	string info = "FPS: "+ofToString(ofGetFrameRate());
	info += "\nPress s to spill particles";
	info += "\nBodies: "+ofToString(box2d.getBodyCount()-2);
	info += "\nvector: "+ofToString((int)particles.size());
	ofSetColor(255, 255, 0);
	ofDrawBitmapString(info, 20, 20);
}


//--------------------------------------------------------------
void testApp::keyPressed(int key) {
	
	spill = !spill;
}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ) {
}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button) {
	
	
}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button) {
	
}

//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button) {
	ofxBox2dCircle p;
	p.setPhysics(1.0, 0.5, 0.3);
	p.setup(box2d.getWorld(), x, y, ofRandom(3, 10));
	particles.push_back(p);	
}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h) {
}

