/*  Sorting blitter
 *  Copyright (C) Joakim Kolsjö 2004
 *	This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 
 */

#include "gfx_sort.h"
#include <iostream>
#include <cmath>
#include <algorithm>

namespace gfx
{
	void Sort::init(xio::Manager *i)
	{
		xio = i;
	}
	
	void Sort::addObject(xio::surface *texture)
	{
		obdata tobj;
		tobj.texture = texture;
		tobj.x = 0;
		tobj.y = 0;
		tobj.draw = true;
		objects.push_back(tobj);
	}
	
	void Sort::changeObject(int id, int x, int y)
	{
		objects[id].x = x;
		objects[id].y = y;
	}
	
	void Sort::setDraw(int id, bool draw)
	{
		objects[id].draw = draw;
	}

	void Sort::blitObjects(xio::surface *target)
	{
		vector <obdata> outlist;
		int s = (int)objects.size();
			
		outlist.reserve(s);
		for(int i = 0; i < s; i++)
		{
			obdata tobj;
			tobj.texture = objects[i].texture;
			tobj.x = objects[i].x;
			tobj.y = objects[i].y;
			tobj.c = objects[i].y + objects[i].texture->h;
			tobj.draw = objects[i].draw;
			outlist.push_back(tobj);	
		}	
		
		sort(outlist.begin(), outlist.end(), compare);

		for(int i = 0; i < s; i++)
		{
			if(outlist[i].draw)
				xio->video->blit(outlist[i].texture, target, outlist[i].x, outlist[i].y, 0, 0, -1, false);
		}
	}	
}
