/**
 *  Triangles
 *  Copyright (C) 2016 POSITIVE MENTAL ATTITUDE
 *
 *  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, version 3 of the License.
 *
 *  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, see <http://www.gnu.org/licenses/>.
 */

#include "Collidable.hpp"

Collidable::~Collidable()
{
	_cmap.clear();
	_cbanned.clear();
}

void Collidable::genCollisionBox(std::string file, sf::Vector2f size)
{
	sf::Image img;
	img.loadFromFile(file);
	_cmap.reserve((img.getSize().x * img.getSize().y) / 10);
	_cbanned.reserve((img.getSize().x * img.getSize().y) / 2);
	for(unsigned int i = 0; i < img.getSize().x; ++i)
		for(unsigned int j = 0; j < img.getSize().y; ++j)
			if(img.getPixel(i, j).r == 255)
				_cmap.push_back(sf::Vector2f(int(i - size.x), int(j - size.y)));
}

void Collidable::setPointCount(unsigned pointCount)
{
	_pointCount = pointCount;
}

void Collidable::updateTransform(sf::Transform transform)
{
	_transform = transform;
}

int Collidable::pixelPerfect(Foreground& foreground)
{
	unsigned tileSize = foreground.getTileSize();

	for(unsigned k = 0; k < _cmap.size(); ++k)
	{
		sf::Vector2i vec = (sf::Vector2i)_transform.transformPoint(_cmap[k]);
		if(vec.x < 0) vec.x = 0;
		if(vec.y < 0) vec.y = 0;
		if(vec.x >= (signed int)foreground.getSize().x) vec.x = foreground.getSize().x - 1;
		if(vec.y >= (signed int)foreground.getSize().y) vec.y = foreground.getSize().y - 1;
		if(foreground.tileAlpha(vec.x / tileSize, vec.y / tileSize, vec.x % tileSize, vec.y % tileSize) > 0)
			return k;
	}
	return -1;
}
