/*
 * World.cpp
 *
 *  Created on: 2009-07-10
 *      Author: wasyl
 */

#include "World.h"

#include <algorithm>
#include <set>

#include "../Common.h"

/************************************************/

void World::add(Entity *e)
{
	mToAdd.push_back(e);
}

/************************************************/

void World::remove(Entity *e)
{
	mToRemove.push_back(e);
}

/************************************************/

void World::reindex()
{
	std::set<int> touched;

	// remove
	FOREACH(vector,Entity*,e,mToRemove)
	{
		int *id = (*e)->indices();
		while (*id)
		{
			touched.insert(*id);
			remove_element(index(*id),*e);
			id++;
		}
		delete *e;
	}

	// add
	FOREACH(vector,Entity*,e,mToAdd)
	{
		int *id = (*e)->indices();
		while (*id)
		{
			touched.insert(*id);
			index(*id).push_back(*e);
			(*e)->setWorld(this);
			id++;
		}
	}

	// clear lists
	mToAdd.clear();
	mToRemove.clear();

	// reindex
	FOREACH(set,int,id,touched)
	{
		if ((*id == ID("rndr")) || (*id == ID("entt")))
		{
			std::vector<Entity*> &ind = index(*id);
			std::stable_sort(ind.begin(), ind.end(), EntityCompare(*id));
		}
	}
}
