// K-3D
// Copyright (c) 1995-2004, Timothy M. Shead
//
// Contact: tshead@k-3d.com
//
// 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  USA

/** \file
		\author Romain Behar (romainbehar@yahoo.com)
*/

#include <k3dsdk/basic_math.h>
#include <k3dsdk/object.h>
#include <k3dsdk/persistence.h>
#include <k3dsdk/measurement.h>
#include <k3dsdk/mesh_filter.h>
#include <k3dsdk/module.h>
#include <k3dsdk/plugins.h>
#include <k3dsdk/utility.h>

namespace libk3dmesh
{

/////////////////////////////////////////////////////////////////////////////
// merge_faces_implementation

class merge_faces_implementation :
	public k3d::mesh_filter<k3d::persistent<k3d::object> >
{
	typedef k3d::mesh_filter<k3d::persistent<k3d::object> > base;

public:
	merge_faces_implementation(k3d::idocument& Document) :
		base(Document)
	{
		m_input_mesh.changed_signal().connect(SigC::slot(*this, &merge_faces_implementation::on_reset_geometry));
		m_output_mesh.need_data_signal().connect(SigC::slot(*this, &merge_faces_implementation::on_create_geometry));
	}

	void on_reset_geometry()
	{
		m_output_mesh.reset();
	}

	/// Returns true iff the given object is selected
	struct is_selected
	{
		bool operator()(k3d::face* const Face)
		{
			return Face->selected;
		}
	};

	/// Returns true iff the edge companion exists and is not selected
	inline bool is_exterior(k3d::split_edge* const Edge)
	{
		return !(Edge->companion && Edge->companion->is_selected());
	}

	k3d::mesh* on_create_geometry()
	{
		// Get the input geometry ...
		k3d::mesh* const input = m_input_mesh.property_value();
		if(!input)
			return 0;

		// Create output geometry ...
		k3d::mesh* const output = new k3d::mesh();
		k3d::deep_copy(*input, *output);

		// For each polyhedron ...
		for(k3d::mesh::polyhedra_t::iterator polyhedron = output->polyhedra.begin(); polyhedron != output->polyhedra.end(); ++polyhedron)
			{
				// Get the set of all selected faces ...
				k3d::polyhedron::faces_t selected_faces;
				k3d::copy_if((*polyhedron)->faces.begin(), (*polyhedron)->faces.end(), std::inserter(selected_faces, selected_faces.end()), is_selected());

				if(selected_faces.empty())
					selected_faces = (*polyhedron)->faces;

				// Save exterior edges ...
				typedef std::set<k3d::split_edge*> edge_set_t;
				edge_set_t exterior_edges;
				for(k3d::polyhedron::faces_t::iterator selected_face = selected_faces.begin(); selected_face != selected_faces.end(); ++selected_face)
					{
						k3d::face& face = **selected_face;
						k3d::split_edge* edge = face.first_edge;
						do
							{
								if(is_exterior(edge))
									exterior_edges.insert(edge);

								edge = edge->face_clockwise;
							}
						while(edge != face.first_edge);
					}

				// Make paths through exterior edges ...
				// TODO: handle created holes
				typedef std::vector<k3d::point*> face_t;
				typedef std::vector<k3d::split_edge*> edges_t;
				std::vector<face_t> new_faces;
				std::vector<edges_t> face_companions;
				while(exterior_edges.size())
					{
						face_t face;
						edges_t edges;

						edge_set_t::iterator first_edge_i = exterior_edges.begin();
						k3d::split_edge* first_edge = *first_edge_i;
						face.push_back(first_edge->vertex);
						edges.push_back(first_edge->companion);
						exterior_edges.erase(first_edge_i);

						k3d::split_edge* current_edge = first_edge->face_clockwise;
						do
							{
								if(!is_exterior(current_edge))
									{
										// Turn around vertex which is the next exterior egde
										k3d::split_edge* next_edge = current_edge;
										do
											{
												assert_warning(current_edge->companion);
												next_edge = next_edge->companion->face_clockwise;
												return_val_if_fail(next_edge != current_edge, 0);
											}
										while(!is_exterior(next_edge));

										current_edge = next_edge;
									}

								// Edge is an exterior, save it
								face.push_back(current_edge->vertex);
								edges.push_back(current_edge->companion);

								// Remove it from edge set
								edge_set_t::iterator edge_i = exterior_edges.find(current_edge);
								return_val_if_fail(edge_i != exterior_edges.end(), 0);
								exterior_edges.erase(edge_i);

								// Move on ...
								current_edge = current_edge->face_clockwise;
							}
						while(current_edge != first_edge);

						new_faces.push_back(face);
						face_companions.push_back(edges);
					}

				// Delete selected faces and their edges
				std::set<k3d::split_edge*> edges;
				for(k3d::polyhedron::faces_t::iterator f = selected_faces.begin(); f != selected_faces.end(); ++f)
					{
						k3d::face* face = *f;
						for(k3d::split_edge* edge = face->first_edge; edge; edge = edge->face_clockwise)
							{
								if(edge->companion)
									edge->companion->companion = 0;

								(*polyhedron)->edges.erase(std::remove((*polyhedron)->edges.begin(), (*polyhedron)->edges.end(), edge), (*polyhedron)->edges.end());
								edges.insert(edge);

								if(edge->face_clockwise == face->first_edge)
									break;
							}

						for(k3d::face::holes_t::iterator hole = face->holes.begin(); hole != face->holes.end(); ++hole)
							{
								for(k3d::split_edge* edge = *hole; edge; edge = edge->face_clockwise)
									{
										if(edge->companion)
											edge->companion->companion = 0;

										(*polyhedron)->edges.erase(std::remove((*polyhedron)->edges.begin(), (*polyhedron)->edges.end(), edge), (*polyhedron)->edges.end());
										edges.insert(edge);

										if(edge->face_clockwise == *hole)
											break;
									}
							}

						(*polyhedron)->faces.erase(std::remove((*polyhedron)->faces.begin(), (*polyhedron)->faces.end(), face), (*polyhedron)->faces.end());
					}

				std::for_each(edges.begin(), edges.end(), k3d::delete_object());
				std::for_each(selected_faces.begin(), selected_faces.end(), k3d::delete_object());

				// TODO: delete orphaned points

				// Create resulting faces
				std::vector<face_t>::const_iterator new_face = new_faces.begin();
				std::vector<edges_t>::const_iterator companion_list = face_companions.begin();
				for(; new_face != new_faces.end(); ++new_face, ++companion_list)
					{
						const face_t& face = *new_face;
						const edges_t& companions = *companion_list;

						std::vector<k3d::split_edge*> new_edges;
						face_t::const_iterator point = face.begin();
						edges_t::const_iterator companion = companions.begin();
						for(; point != face.end(); ++point, ++companion)
							{
								k3d::split_edge* const new_edge = new k3d::split_edge(*point);
								if(*companion)
									k3d::join_edges(*new_edge, *(*companion));
								new_edges.push_back(new_edge);
							}

						k3d::loop_edges(new_edges.begin(), new_edges.end());
						(*polyhedron)->edges.insert((*polyhedron)->edges.end(), new_edges.begin(), new_edges.end());
						(*polyhedron)->faces.push_back(new k3d::face(new_edges.front()));
					}

				assert_warning(is_valid(**polyhedron));
			}

		return output;
	}

	k3d::iplugin_factory& factory()
	{
		return get_factory();
	}

	static k3d::iplugin_factory& get_factory()
	{
		static k3d::plugin_factory<
			k3d::document_plugin<merge_faces_implementation>,
				k3d::interface_list<k3d::imesh_source,
				k3d::interface_list<k3d::imesh_sink > > > factory(
				k3d::uuid(0xfc611edf, 0xa16f4c45, 0x9a3d89d3, 0xd7125c5d),
				"MergeFaces",
				"Merges adjacent selected faces into a single polygon",
				"Objects",
				k3d::iplugin_factory::EXPERIMENTAL);

		return factory;
	}
};

/////////////////////////////////////////////////////////////////////////////
// merge_faces_factory

k3d::iplugin_factory& merge_faces_factory()
{
	return merge_faces_implementation::get_factory();
}

} // namespace libk3dmesh


