#include "example5.h"

using namespace std;

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

static void rain_left_world(rat_world *thisworld,rat_body *thisbody,void *userdata)
{
	RatPhysicsExample5 *phys=(RatPhysicsExample5 *)userdata;

	vector2 newpos={phys->bounds.x/2.0,phys->bounds.y*0.2};
	rat_hull_set_pos(thisbody->hull,newpos);
	vector2_set(&(thisbody->velocity),0,0);
}

bool RatPhysicsExample5::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,rain_left_world,this);

	rat_world_set_gravity(world,gravity);
	rat_world_set_damping(world,0.95);

	vector2 center={bounds.x*0.5,bounds.y*0.65};

	rat_world_add_body(world,
		rat_body_create(rat_hull_circle_create(center,130),
		0.5,1.0,0.0,0.0));

	rat_examples_create_circle_row(world,25,0,bounds.y*0.1,bounds.x/2.0,30,1);
	rat_examples_create_circle_row(world,25,0,bounds.y*0.15,bounds.x/2.0,30,1);

	vector2 boxsize={25,25};
	rat_examples_create_box_row(world,boxsize,0,bounds.y*0.2,bounds.x/2.0,30,2);
	rat_examples_create_box_row(world,boxsize,0,bounds.y*0.25,bounds.x/2.0,30,2);

	rat_world_add_collision_filter(world,1,2,0);

	return (bool)world;
}

bool RatPhysicsExample5::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 RatPhysicsExample5::UpdateVisuals()
{
	rat_draw_world(world,show_quadtree,show_arbiters,show_aabbs);
	return true;
}

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

	return true;
}
