//==============================================================================
/*! \file
 * OpenMesh Toolkit for mesh analysis    \n
 * Copyright (c) 2010 by Rostislav Hulik     \n
 *
 * Author:  Rostislav Hulik, rosta.hulik@gmail.com  \n
 * Date:    2010/11/21                          \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 rasterizes vertex neighbourhood on a tangent raster
 * - Result is sent to connected MDSTk channel
 */

#include "ComputeMatrices.h"

#include <OMToolkit\IO\OMIO.h>
#include <OMToolkit\OMProjector.h>
#include <OMToolkit\OMTypes.h>
#include <OpenMesh\Tools\Utils\Timer.hh>

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

// Module description
const std::string MODULE_DESCRIPTION    = "Module that rasterizes vertex neighbourhood on a tangent raster";

// Additional command line arguments
const std::string MODULE_ARGUMENTS      = "size:relative:resolution:xdir:zdir";

// Additional arguments
const std::string MODULE_ARG_SIZE		= "size";
const std::string MODULE_ARG_RES		= "resolution";
const std::string MODULE_ARG_XDIR		= "xdir";
const std::string MODULE_ARG_ZDIR		= "zdir";
const std::string MODULE_ARG_RELATIVE	= "relative";

const double SIZE_DEFAULT				= 16.0;
const double RES_DEFAULT				= 3.0;
const bool RELATIVE_DEFAULT				= false;

const std::string ZDIR_CURVATURE		= "curvature";
const std::string ZDIR_ZDIR				= "z";
const std::string ZDIR_NORMALS			= "normals";
const std::string ZDIR_DEFAULT			= ZDIR_ZDIR;

const std::string XDIR_CURVATURE		= "curvature";
const std::string XDIR_NONE				= "none";
const std::string XDIR_DEFAULT			= XDIR_NONE;

// Type of accepted mesh
typedef OMToolkit::Types::ModuleMeshd	MeshT;

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

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

///////////////////////////////////////////////////////////////////////////////////////////////////
// Do on startup
///////////////////////////////////////////////////////////////////////////////////////////////////
bool OMComputeMatrices::startup()
{
	// Disable all OpenMesh errorlogs (for not mix MDSTk log)
	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;
    }

	m_size = SIZE_DEFAULT;
	m_Arguments.value(MODULE_ARG_SIZE, m_size);

	m_resolution = RES_DEFAULT;
	m_Arguments.value(MODULE_ARG_RES, m_resolution);

	m_direction = XDIR_DEFAULT;
	m_Arguments.value(MODULE_ARG_XDIR, m_direction);

	m_relative = RELATIVE_DEFAULT;
	if (m_Arguments.exists(MODULE_ARG_RELATIVE)) m_relative = true;

	if (m_size <= 0.0 || m_resolution <= 0.0 || ((int)m_resolution)%2 == 0)
	{
		MDS_CERR('<' << m_sFilename << "> Wrong size or resolution of a tangent matrix" << std::endl);
		return false;
	}

	m_directionZ = ZDIR_ZDIR;
	m_Arguments.value(MODULE_ARG_ZDIR, m_directionZ);
	
    // O.K.
    return true;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// Main module loop
///////////////////////////////////////////////////////////////////////////////////////////////////
bool OMComputeMatrices::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 matrix computation... Model: " << mesh.n_vertices() << " vertices.");
			OpenMesh::Utils::Timer timer;
			OMToolkit::OMProjector<MeshT, MeshT::VertexMatrix> projector(&mesh, mesh.getMatrixHandle());

			// set X direction from argument
			int dirFlag;
			if (m_direction == XDIR_CURVATURE)
				dirFlag = OMToolkit::OMProjector<MeshT, MeshT::VertexMatrix>::XDIR_CURVATURE;
			else if (m_direction == XDIR_NONE)
				dirFlag = OMToolkit::OMProjector<MeshT, MeshT::VertexMatrix>::XDIR_DO_NOT_CHECK;
			else
			{
				MDS_CERR('<' << m_sFilename << "> Bad xdir argument..." << std::endl);
				return false;
			}

			int zCurv = OMToolkit::OMProjector<MeshT, MeshT::VertexMatrix>::ZDIR_Z;
			if (m_directionZ == ZDIR_ZDIR)
				zCurv = OMToolkit::OMProjector<MeshT, MeshT::VertexMatrix>::ZDIR_Z;
			else if (m_directionZ == ZDIR_CURVATURE)
				zCurv = OMToolkit::OMProjector<MeshT, MeshT::VertexMatrix>::ZDIR_CURVATURE;
			else if (m_directionZ == ZDIR_NORMALS)
				zCurv = OMToolkit::OMProjector<MeshT, MeshT::VertexMatrix>::ZDIR_NORMAL;
			else
			{
				MDS_CERR('<' << m_sFilename << "> Z direction error." << std::endl);
				return false;
			}

			// go computing
			timer.start();
			if (!projector.ComputeMatrices(m_size, m_resolution, zCurv, m_relative, dirFlag))
			{
				MDS_CERR('<' << m_sFilename << "> Failed to compute matrices. Is mesh triangular?" << std::endl);
				return false;
			}
			timer.stop();
						
			MDS_LOG_NOTE("Matrices successfully computed in " << timer.as_string(OpenMesh::Utils::Timer::MSeconds) << ".");

			// write output
			if (!OMToolkit::IO::writeMesh(mesh, *pOChannel))
			{
				MDS_CERR('<' << m_sFilename << "> Failed to write output 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 OMComputeMatrices::shutdown()
{
    // Note
    MDS_LOG_NOTE("Module shutdown");
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// Writes extended use of this module
///////////////////////////////////////////////////////////////////////////////////////////////////
void OMComputeMatrices::writeExtendedUsage(std::ostream& Stream)
{
    MDS_CERR("Necessary arguments: [-size matrixSize] [-relative] [-resolution matrixResolution] [-xdir XAxisDir]" << std::endl);
    MDS_CERR("Options:" << std::endl);
	MDS_CERR("  -size Specifies matrix size in mesh space." << std::endl);
	MDS_CERR("	  -Argument is double precision number greater than 0.0" << std::endl);
	MDS_CERR("  -relative Use this argument if you want to specify matrix size relatively." << std::endl);
	MDS_CERR("	  -If set, length is not static but is computed as matrixSize * medianOfEdgeLengths" << std::endl);
	MDS_CERR("  -resolution Specifies square matrix dimension in one direction." << std::endl);
	MDS_CERR("	  -Argument is double precision number greater than 0.0." << std::endl);
	MDS_CERR("	  -Must be odd number (for filtration purposes)" << std::endl);
	MDS_CERR("  -xdir Specifies vector, which will be used to align matrix X direction." << std::endl);
	MDS_CERR("	  " << XDIR_CURVATURE << " - Option sets X direction as computed curvature vector." << std::endl);
	MDS_CERR("	  " << XDIR_NONE      << " - Option sets X direction randomly (does not align)." << std::endl);
    MDS_CERR(std::endl);
}

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

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

    // Console application finished
    return 0;
}

