#include "example3.h"

#define NUM_CIRCLES 8
#define CIRCLE_RADIUS 25
#define LINE_Y_POS 150
#define LINE_START_X 100
#define LINE_END_X SCENE_WIDTH-100

using namespace std;

RatPhysicsExample3::RatPhysicsExample3(string name): RatPhysicsExample(name) {}
RatPhysicsExample3::RatPhysicsExample3(const char *name): RatPhysicsExample(name) {}
RatPhysicsExample3::RatPhysicsExample3(char *name): RatPhysicsExample(name) {}

bool RatPhysicsExample3::InitWorld()
{
	SDL_WM_SetCaption(title.c_str(),NULL);

	aabb space={{0,0},{bounds.x,bounds.y}};
	vector2 cell_size={150,150};
	vector2 gravity={0,12};

	world=rat_world_create(space,rat_integrator_euler,10,
		rat_body_manager_type_quad_tree,&cell_size);

	rat_world_set_body_left_world_callback(world,&rat_examples_leave_world_callback,NULL);

	rat_world_set_gravity(world,gravity);
	rat_examples_create_walls(world);

	const rat_real circle_mass=rat_area_circle(CIRCLE_RADIUS);
	const rat_real line_interval=LINE_END_X-LINE_START_X;

	for (unsigned int i=0; i<NUM_CIRCLES+1; i++)
	{
		rat_real line_completion=(rat_real)i/(rat_real)NUM_CIRCLES;
		vector2 center={LINE_START_X+line_completion*line_interval,LINE_Y_POS};
		rat_world_add_body(world,rat_body_create(rat_hull_circle_create(center,CIRCLE_RADIUS),
			line_completion,1.0,circle_mass,rat_moi_circle(circle_mass,CIRCLE_RADIUS)));
	}

	return (bool)world;
}

bool RatPhysicsExample3::UpdateWorld(rat_real timestep)
{
	timestep=timestep>2.0?2.0:timestep;
	rat_world_update(world,timestep*0.05,timestep<=1.0?1:0);

	return true;
}

bool RatPhysicsExample3::UpdateVisuals()
{
	rat_draw_world(world,show_quadtree,show_arbiters,show_aabbs);
	return true;
}

bool RatPhysicsExample3::FreeWorld()
{
	rat_world_free_entities(world);
	rat_world_destroy(world);

	return true;
}

