//==============================================================================
/*! \file
 * OpenMesh Toolkit for mesh analysis    \n
 * Copyright (c) 2010 by Rostislav Hulik     \n
 *
 * Author:  Rostislav Hulik, rosta.hulik@gmail.com  \n
 * Date:    2010/10/27                          \n
 *
 * This file is part of software developed for support of Rostislav Hulik's dissertation thesis at dcgm-robotics@FIT group.
 *
 * This file is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This file 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 Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this file.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Module description:
 * - Module loads a file from input channel
 * - Then, subdivides a mesh in specified number of iterations
 * - Result is written into output channel
 */

#include "SubdivideMesh.h"

#include <OMToolkit\IO\OMIO.h>
#include <OMToolkit\OMTypes.h>

#include <OpenMesh\Tools\Subdivider\Uniform\Sqrt3T.hh>
#include <OpenMesh\Tools\Subdivider\Uniform\LoopT.hh>
#include <OpenMesh\Tools\Subdivider\Uniform\CompositeLoopT.hh>
#include <OpenMesh\Tools\Subdivider\Uniform\CompositeSqrt3T.hh>

///////////////////////////////////////////////////////////////////////////////////////////////////
// Module constants
///////////////////////////////////////////////////////////////////////////////////////////////////

// Module description
const std::string MODULE_DESCRIPTION    = "Module that uniformly subdivides mesh data";

// Additional command line arguments
const std::string MODULE_ARGUMENTS      = "method:iterations";

// Additional arguments
const std::string MODULE_ARG_METHOD			= "method";
const std::string MODULE_ARG_ITERATIONS		= "iterations";

// Smoothing method possibilities
const std::string METHOD_LOOP				= "loop";
const std::string METHOD_SQRT3				= "sqrt3";
const std::string METHOD_DEFAULT			= METHOD_SQRT3;

// Iterations possibilities
const int DEFAULT_ITERATIONS				= 1;

// Mesh type
typedef OMToolkit::Types::ModuleMeshd			MeshT;

///////////////////////////////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////////////////////////////
OMSubdivideMesh::OMSubdivideMesh(const std::string& sDescription) : mds::mod::CModule(sDescription)
{
    allowArguments(MODULE_ARGUMENTS);
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// Destructor
///////////////////////////////////////////////////////////////////////////////////////////////////
OMSubdivideMesh::~OMSubdivideMesh()
{
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// Do on startup
///////////////////////////////////////////////////////////////////////////////////////////////////
bool OMSubdivideMesh::startup()
{
	// Disable OpenMesh logging
	omlog().disable();
	omerr().disable();
	omout().disable();
    
	// Note
    MDS_LOG_NOTE("Module startup");

    // Test of existence of input and output channel
    if( getNumOfInputs() != 1 || getNumOfOutputs() != 1 )
    {
        MDS_CERR('<' << m_sFilename << "> Wrong number of input and output channels" << std::endl);
        return false;
    }

	// Test existence of method specification (now, only one is allowed)
	m_method = METHOD_DEFAULT;
	m_Arguments.value(MODULE_ARG_METHOD, m_method);
	if (m_method != METHOD_LOOP && m_method != METHOD_SQRT3)
	{
		MDS_CERR('<' << m_sFilename << "> Bad parameter value (-method): type -h for help" << std::endl);
        printUsage();
        return false;
	}

	// Test existence of iterations specification
	m_iterations = DEFAULT_ITERATIONS;
	m_Arguments.value(MODULE_ARG_ITERATIONS, m_iterations);
	if (m_iterations <= 0)
	{
		MDS_CERR('<' << m_sFilename << "> Bad parameter value (-iterations): type -h for help" << std::endl);
        printUsage();
        return false;
	}

    // O.K.
    return true;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// Main module loop
///////////////////////////////////////////////////////////////////////////////////////////////////
bool OMSubdivideMesh::main()
{
    //// Note
    MDS_LOG_NOTE("Module main function");

    //// I/O channels
    mds::mod::CChannel *pIChannel = getInput(0);
    mds::mod::CChannel *pOChannel = getOutput(0);

	 // Is any input?
    if( !pIChannel->isConnected() )
    {
        return false;
    }

    // Wait for data
    if( pIChannel->wait(1000) )
    {
		// Mesh specification and read options
		MeshT mesh;
		OMToolkit::IO::Options opt = OMToolkit::IO::Options::Default;
	
		// Read and save mesh
		if (OMToolkit::IO::readMesh(mesh, *pIChannel, opt))
		{
			MDS_LOG_NOTE("Starting subdivision, number of mesh vertices: " << mesh.n_vertices());
			
			try
			{			
				if (m_method == METHOD_SQRT3)
				{
					OpenMesh::Subdivider::Uniform::Sqrt3T<MeshT, MeshT::Normal::value_type> subdivider;
					subdivider.attach(mesh);
					subdivider(m_iterations);
					subdivider.detach();
				}
				else if (m_method == METHOD_LOOP)
				{
					OpenMesh::Subdivider::Uniform::LoopT<MeshT, MeshT::Normal::value_type> subdivider;
					subdivider.attach(mesh);
					subdivider(m_iterations);
					subdivider.detach();
				}
			}
			catch ( ... )
			{
				MDS_CERR('<' << m_sFilename << "> ERROR during subdivision process" << std::endl);
				return false;
			}

			MDS_LOG_NOTE("Subdivision successfully ended, number of mesh vertices: " << mesh.n_vertices());

			if (!OMToolkit::IO::writeMesh(mesh, *pOChannel))
			{
				MDS_CERR('<' << m_sFilename << "> Failed to write output mesh data" << std::endl);
				return false;
			}
		}
		// Error on input
		else 
		{
			MDS_CERR('<' << m_sFilename << "> Failed to read input mesh data" << std::endl);
			return false;
		}

		return false;
	}
    else
    {
        MDS_LOG_NOTE("Wait timeout");
    }

    // Returning 'true' means to continue processing the input channel
    return true;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// On module shutdown
///////////////////////////////////////////////////////////////////////////////////////////////////
void OMSubdivideMesh::shutdown()
{
    // Note
    MDS_LOG_NOTE("Module shutdown");
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// Writes extended use of this module
///////////////////////////////////////////////////////////////////////////////////////////////////
void OMSubdivideMesh::writeExtendedUsage(std::ostream& Stream)
{
    MDS_CERR("Necessary arguments: [-method method] [-iterations no]" << std::endl);
    MDS_CERR("Options:" << std::endl);
	MDS_CERR("  -method Specifies subdivision method. Possibilities:" << std::endl);
	MDS_CERR("		sqrt3 : Sqrt(3) subdivision method" << std::endl);
	MDS_CERR("		loop : Loop subdivision method" << std::endl);
	MDS_CERR("		DEFAULT: sqrt3" << std::endl);
	MDS_CERR("  -iterations Specifies number of subdivision iterations [1..inf]. Possibilities:" << std::endl);
	MDS_CERR("		DEFAULT: 1" << std::endl);
	MDS_CERR(std::endl);
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// Main - executing a module
///////////////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
    // Creation of a module using smart pointer
    OMSubdivideMeshPtr spModule(new OMSubdivideMesh(MODULE_DESCRIPTION));

    // Initialize and execute the module
    if( spModule->init(argc, argv) )
    {
        spModule->run();
    }

    // Console application finished
    return 0;
}

