//Copyright (C) 2007 SiegeLord
//See ReadMe.txt and License.txt for copying information

#include "../include/engine/error.h"
#include "../include/engine/object.h"
#include "../include/engine/gfx.h"

void DrawObject(SObject* obj)
{
	obj->Draw();

	for(list<SObject*>::iterator it = obj->children.begin(); it != obj->children.end(); it++)
	{
		DrawObject(*it);
	}
}

//restrict because can't be a child of self, so the transformation (a parent's thing) can't occupy
//the same memory as the child
//obj is the child
//current_trans is the parent
//no overlap
void UpdateObjectPosition(SObject* obj, const transform2d* restrict current_trans)
{
	obj->net_transform = obj->local_transform;
	current_trans->TransformTransform(&obj->net_transform);

	for(list<SObject*>::iterator it = obj->children.begin(); it != obj->children.end(); it++)
	{
		UpdateObjectPosition(*it, &obj->net_transform);
	}
}

int HandleObject(SObject* obj)
{
	int ret = 0;
	obj->Handle();

	for(list<SObject*>::iterator it = obj->children.begin(); it != obj->children.end(); it++)
	{
		ret |= HandleObject(*it);
	}
	return ret;
}

int DoObjectLogic(SObject* obj)
{
	UpdateObjectPosition(obj, &g_trIdentity);//first we update all of the positions
	return HandleObject(obj);//and then we call each object's logic
}

void DestroyObject(SObject* obj)
{
	for(list<SObject*>::iterator it = obj->children.begin(); it != obj->children.end(); it++)
	{
		DestroyObject(*it);
	}

	delete obj;
}

////////////////////////////////////////////
//		Dummy Stuff
////////////////////////////////////////////

//void DummyDraw(SObject* obj)
//{
//	math::vector2d shape[3];
//	shape[0].Set(50, 0);
//	shape[1].Set(0, -10);
//	shape[2].Set(0, 10);
//
//	gfx::SetModelMatrix(&obj->net_transform);
//
//	gfx::DrawPolyLine(shape, -10, 3, 0xffff00ff, true);
//
//	gfx::SetModelMatrix(&math::g_trIdentity);
//}

SObject* InitObject(SObject* object, SObject* parent)
{
	_ASSERT(object != parent)
	object->parent = parent;
	object->rotation = 0;
	object->depth = -10;

	if(parent)
	{
		parent->children.push_back(object);
	}

	return object;
}
