/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library 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 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library 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 library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#ifndef SOFA_COMPONENT_MAPPING_ProjectionToMeshEngine_H
#define SOFA_COMPONENT_MAPPING_ProjectionToMeshEngine_H

#include "initContactMapping.h"
#include <sofa/core/DataEngine.h>
#include <sofa/defaulttype/VecTypes.h>
#include <sofa/core/topology/BaseMeshTopology.h>
#include "projectToMesh.h"

namespace sofa
{

namespace component
{

namespace engine
{

/**
 * Projecting parent1 points to parent2 (mesh).
 * C_i is the closest vertex on parent2 from P_i in parent1 (provided by closestPointEngine through indexPairs)
 *
 * Two methods are available:
 * - if triangles or quads or edges are provided: projections are performed on primitives surrounding C_i
 * - if normals are provided: projections are performed on the tangent plane of C_i
 *
 * \warning if triangles or quads AND edges are provided, edges must NOT include edges from triangles or quads
 *
 * @author Matthieu Nesme, Benjamin Gilles
 * @date 2016
 */
template <class DataTypes>
class BaseProjectionToMeshEngine : public core::DataEngine
{
public:
    SOFA_ABSTRACT_CLASS(SOFA_TEMPLATE(BaseProjectionToMeshEngine, DataTypes), core::DataEngine);


    typedef typename DataTypes::Coord    InCoord;
    typedef typename DataTypes::Deriv    InDeriv;
    typedef typename DataTypes::VecCoord InVecCoord;
    typedef typename DataTypes::VecDeriv InVecDeriv;
    typedef typename DataTypes::Real     Real;


    typedef helper::ProjectToMesh<InCoord> ProjectToMesh;
    typedef typename ProjectToMesh::IndexToWeightPair IndexToWeightPair;
    typedef typename ProjectToMesh::ClosestStruct ClosestStruct;

    virtual std::string getTemplateName() const    { return templateName(this);    }
    static std::string templateName(const BaseProjectionToMeshEngine<DataTypes>* = NULL) { return DataTypes::Name();   }

protected:

    BaseProjectionToMeshEngine();

    virtual ~BaseProjectionToMeshEngine() {}


    ProjectToMesh projectToMesh;


    typedef std::map<unsigned int,Real> IndextoRealMap; ///< parent1 point -> original distance
    IndextoRealMap initialDistances;  ///< map to store original distances of each parent1 point
    inline Real getRestLength(const unsigned int index, const Real& actualDistance, const helper::vector<Real>* restLength=nullptr); ///< returns the restlength corresponding to point 'index' in source


    virtual void projectToMeshInit() = 0;
    virtual void projectToMeshGetClosest(ClosestStruct& closest,const InCoord& p, const unsigned int& c, const InVecCoord& positions) = 0;


public:

    virtual void init();
    virtual void reinit();

    virtual void update();


    Data< InVecCoord > d_source;
    Data< InVecCoord > d_target;


    Data<helper::vector<defaulttype::Vec2i> > f_indexPairs;    ///< input pairs of correspondences

    Data< bool > d_useRestLength;   ///< should a rest length be substracted to effective distances?

    /// Only valid when d_useRestLength is true.
    /// if size==1 => rest length of all links
    /// if size==source.size() => one specific rest lenth defined for each source points
    Data< helper::vector<Real> > d_restLength;


    Data< helper::vector<ClosestStruct> > o_closests; ///< store closest point on mesh from each parent1 point

    Data< bool > d_updateOnlyWhenAnimating; ///< to be able not to update this engine that can be costly during non-animating, initialization phase



};





template <class DataTypes>
class ProjectionToVertexPlaneEngine : public BaseProjectionToMeshEngine<DataTypes>
{

public:
    SOFA_CLASS(SOFA_TEMPLATE(ProjectionToVertexPlaneEngine, DataTypes), SOFA_TEMPLATE(BaseProjectionToMeshEngine, DataTypes));


    typedef typename Inherit1::InCoord InCoord;
    typedef typename Inherit1::InVecCoord InVecCoord;
    typedef typename Inherit1::ClosestStruct ClosestStruct;

    Data< InVecCoord > d_normals2;  ///< normals of input2

protected:

    ProjectionToVertexPlaneEngine();

    virtual void projectToMeshInit();
    virtual void projectToMeshGetClosest(ClosestStruct& closest,const InCoord& p, const unsigned int& c, const InVecCoord& positions);
};




template <class DataTypes>
class ProjectionToMeshEngine : public BaseProjectionToMeshEngine<DataTypes>
{

public:
    SOFA_CLASS(SOFA_TEMPLATE(ProjectionToMeshEngine, DataTypes), SOFA_TEMPLATE(BaseProjectionToMeshEngine, DataTypes));

    typedef typename Inherit1::InCoord InCoord;
    typedef typename Inherit1::InVecCoord InVecCoord;
    typedef typename Inherit1::ClosestStruct ClosestStruct;

    typedef typename core::topology::BaseMeshTopology::SeqEdges SeqEdges;
    typedef typename core::topology::BaseMeshTopology::SeqTriangles SeqTriangles;
    typedef typename core::topology::BaseMeshTopology::SeqQuads SeqQuads;

    Data< SeqTriangles > d_triangles2;  ///<triangles of input2
    Data< SeqQuads > d_quads2;  ///<quads of input2
    Data< SeqEdges > d_edges2;   ///< edges of input2

protected:

    ProjectionToMeshEngine();

    virtual void projectToMeshInit();
    virtual void projectToMeshGetClosest(ClosestStruct& closest,const InCoord& p, const unsigned int& c, const InVecCoord& positions);
};







#if defined(SOFA_EXTERN_TEMPLATE) && !defined(SOFA_COMPONENT_MAPPING_ProjectionToMeshEngine_CPP)
#ifndef SOFA_FLOAT
extern template class SOFA_ContactMapping_API ProjectionToVertexPlaneEngine< sofa::defaulttype::Vec3dTypes >;
extern template class SOFA_ContactMapping_API ProjectionToMeshEngine< sofa::defaulttype::Vec3dTypes >;
#endif
#ifndef SOFA_DOUBLE
extern template class SOFA_ContactMapping_API ProjectionToVertexPlaneEngine< sofa::defaulttype::Vec3fTypes >;
extern template class SOFA_ContactMapping_API ProjectionToMeshEngine< sofa::defaulttype::Vec3fTypes >;
#endif
#endif

} // namespace engine

} // namespace component

} // namespace sofa

#endif //SOFA_COMPONENT_MAPPING_ProjectionToMeshEngine_H
