Bladeren bron

Merge branch 'master' of github.com:libigl/libigl

Former-commit-id: d7ec40ff59569ebbf15bc5ab6c33175d9f624f68
Alec Jacobson 11 jaren geleden
bovenliggende
commit
21db3b3de1
37 gewijzigde bestanden met toevoegingen van 4989 en 21 verwijderingen
  1. 0 1
      .gitignore
  2. 4 2
      Makefile.conf
  3. 1 1
      examples/shadow-mapping/example.cpp
  4. 190 0
      include/igl/comb_cross_field.cpp
  5. 35 0
      include/igl/comb_cross_field.h
  6. 63 0
      include/igl/comb_frame_field.cpp
  7. 37 0
      include/igl/comb_frame_field.h
  8. 2267 0
      include/igl/comiso/mixed_integer_quadrangulate.cpp
  9. 63 0
      include/igl/comiso/mixed_integer_quadrangulate.h
  10. 903 0
      include/igl/comiso/nrosy.cpp
  11. 55 0
      include/igl/comiso/nrosy.h
  12. 68 0
      include/igl/compute_frame_field_bisectors.cpp
  13. 44 0
      include/igl/compute_frame_field_bisectors.h
  14. 151 0
      include/igl/cross_field_missmatch.cpp
  15. 36 0
      include/igl/cross_field_missmatch.h
  16. 177 0
      include/igl/cut_mesh_from_singularities.cpp
  17. 34 0
      include/igl/cut_mesh_from_singularities.h
  18. 66 0
      include/igl/find_cross_field_singularities.cpp
  19. 44 0
      include/igl/find_cross_field_singularities.h
  20. 1 0
      include/igl/list_to_matrix.cpp
  21. 7 7
      include/igl/local_basis.cpp
  22. 230 0
      include/igl/planarize_quad_mesh.cpp
  23. 39 0
      include/igl/planarize_quad_mesh.h
  24. 15 7
      include/igl/pos.h
  25. 30 0
      include/igl/quad_planarity.cpp
  26. 25 0
      include/igl/quad_planarity.h
  27. 1 0
      include/igl/readOBJ.cpp
  28. 8 2
      include/igl/writeOFF.cpp
  29. 1 1
      tutorial/103_DrawMesh/main.cpp
  30. 15 0
      tutorial/504_NRosyDesign/CMakeLists.txt
  31. 131 0
      tutorial/504_NRosyDesign/main.cpp
  32. 15 0
      tutorial/505_MIQ/CMakeLists.txt
  33. 137 0
      tutorial/505_MIQ/main.cpp
  34. 40 0
      tutorial/cmake/FindLIBCOMISO.cmake
  35. 54 0
      tutorial/cmake/FindMATLAB.cmake
  36. 1 0
      tutorial/shared/lilium.crossfield.REMOVED.git-id
  37. 1 0
      tutorial/shared/lilium.obj.REMOVED.git-id

+ 0 - 1
.gitignore

@@ -21,7 +21,6 @@ external/embree/bin/*
 external/embree/bin
 external/embree/doc/html/*
 external/embree/doc/latex/*
-*.cmake
 .DS_Store
 libigl.zip
 *tags

+ 4 - 2
Makefile.conf

@@ -109,9 +109,11 @@ ifeq ($(IGL_USERNAME),daniele)
 endif
 
 ifeq ($(IGL_USERNAME),olkido)
-        IGL_WITH_MATLAB=1
+    IGL_WITH_MATLAB=1
 	IGL_WITH_XML=1
-        AFLAGS= -m64
+    AFLAGS= -m64
+    IGL_WITH_EMBREE=1
+    IGL_WITH_PNG=1
 endif
 
 ifeq ($(IGL_USERNAME),chrsch)

+ 1 - 1
examples/shadow-mapping/example.cpp

@@ -28,7 +28,7 @@
 #include <igl/boost/components.h>
 #include <igl/boost/bfs_orient.h>
 #include <igl/orient_outward.h>
-#include <igl/embree/orient_outward_ao.h>
+//#include <igl/embree/orient_outward_ao.h>
 #include <igl/unique_simplices.h>
 #include <igl/C_STR.h>
 #include <igl/write.h>

+ 190 - 0
include/igl/comb_cross_field.cpp

@@ -0,0 +1,190 @@
+#include "comb_cross_field.h"
+
+#include <vector>
+#include <deque>
+#include "per_face_normals.h"
+#include "is_border_vertex.h"
+#include "tt.h"
+
+namespace igl {
+  template <typename DerivedV, typename DerivedF>
+  class Comb
+  {
+  public:
+    
+    const Eigen::PlainObjectBase<DerivedV> &V;
+    const Eigen::PlainObjectBase<DerivedF> &F;
+    const Eigen::PlainObjectBase<DerivedV> &PD1;
+    const Eigen::PlainObjectBase<DerivedV> &PD2;
+    Eigen::PlainObjectBase<DerivedV> N;
+    
+  private:
+    // internal
+    Eigen::PlainObjectBase<DerivedF> TT;
+    Eigen::PlainObjectBase<DerivedF> TTi;
+    
+    
+  private:
+    
+    
+    static double Sign(double a){return (double)((a>0)?+1:-1);}
+    
+    ///given 2 vector centered into origin calculate the rotation matrix from first to the second
+    static Eigen::Matrix<typename DerivedV::Scalar, 3, 3> RotationMatrix(Eigen::Matrix<typename DerivedV::Scalar, 3, 1> v0,
+                                                                         Eigen::Matrix<typename DerivedV::Scalar, 3, 1> v1,
+                                                                         bool normalized=true)
+    {
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> rotM;
+      const double epsilon=0.00001;
+      if (!normalized)
+      {
+        v0.normalize();
+        v1.normalize();
+      }
+      typename DerivedV::Scalar dot=v0.dot(v1);
+      ///control if there is no rotation
+      if (dot>((double)1-epsilon))
+      {
+        rotM = Eigen::Matrix<typename DerivedV::Scalar, 3, 3>::Identity();
+        return rotM;
+      }
+      
+      ///find the axis of rotation
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 1> axis;
+      axis=v0.cross(v1);
+      axis.normalize();
+      
+      ///construct rotation matrix
+      typename DerivedV::Scalar u=axis(0);
+      typename DerivedV::Scalar v=axis(1);
+      typename DerivedV::Scalar w=axis(2);
+      typename DerivedV::Scalar phi=acos(dot);
+      typename DerivedV::Scalar rcos = cos(phi);
+      typename DerivedV::Scalar rsin = sin(phi);
+      
+      rotM(0,0) =      rcos + u*u*(1-rcos);
+      rotM(1,0) =  w * rsin + v*u*(1-rcos);
+      rotM(2,0) = -v * rsin + w*u*(1-rcos);
+      rotM(0,1) = -w * rsin + u*v*(1-rcos);
+      rotM(1,1) =      rcos + v*v*(1-rcos);
+      rotM(2,1) =  u * rsin + w*v*(1-rcos);
+      rotM(0,2) =  v * rsin + u*w*(1-rcos);
+      rotM(1,2) = -u * rsin + v*w*(1-rcos);
+      rotM(2,2) =      rcos + w*w*(1-rcos);
+      
+      return rotM;
+    }
+    
+    
+  public:
+    ///rotate a given vector from the tangent space
+    ///of f0 to the tangent space of f1 by considering the difference of normals
+    static Eigen::Matrix<typename DerivedV::Scalar, 3, 1> Rotate(Eigen::Matrix<typename DerivedV::Scalar, 3, 1> N0,
+                                                                 Eigen::Matrix<typename DerivedV::Scalar, 3, 1> N1,
+                                                                 const Eigen::Matrix<typename DerivedV::Scalar, 3, 1>& dir3D)
+    {
+      ///find the rotation matrix that maps between normals
+      //    vcg::Matrix33<ScalarType> rotation=vcg::RotationMatrix(N0,N1);
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> rotation = RotationMatrix(N0,N1);
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 1> rotated=rotation*dir3D;
+      return rotated;
+    }
+    
+  private:
+    
+    // returns the 90 deg rotation of a (around n) most similar to target b
+    /// a and b should be in the same plane orthogonal to N
+    static Eigen::Matrix<typename DerivedV::Scalar, 3, 1> K_PI_new(const Eigen::Matrix<typename DerivedV::Scalar, 3, 1>& a,
+                                                                   const Eigen::Matrix<typename DerivedV::Scalar, 3, 1>& b,
+                                                                   const Eigen::Matrix<typename DerivedV::Scalar, 3, 1>& n)
+    {
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 1> c = (a.cross(n)).normalized();
+      typename DerivedV::Scalar scorea = a.dot(b);
+      typename DerivedV::Scalar scorec = c.dot(b);
+      if (fabs(scorea)>=fabs(scorec))
+        return a*Sign(scorea);
+      else
+        return c*Sign(scorec);
+    }
+    
+ 
+    
+  public:
+    Comb(const Eigen::PlainObjectBase<DerivedV> &_V,
+         const Eigen::PlainObjectBase<DerivedF> &_F,
+         const Eigen::PlainObjectBase<DerivedV> &_PD1,
+         const Eigen::PlainObjectBase<DerivedV> &_PD2
+         ):
+    V(_V),
+    F(_F),
+    PD1(_PD1),
+    PD2(_PD2)
+    {
+      igl::per_face_normals(V,F,N);
+      igl::tt(V,F,TT,TTi);
+    }
+    void comb(Eigen::PlainObjectBase<DerivedV> &PD1out,
+              Eigen::PlainObjectBase<DerivedV> &PD2out)
+    {
+//      PD1out = PD1;
+//      PD2out = PD2;
+      PD1out.setZero(F.rows(),3);PD1out<<PD1;
+      PD2out.setZero(F.rows(),3);PD2out<<PD2;
+      
+      Eigen::VectorXi mark = Eigen::VectorXi::Constant(F.rows(),false);
+      
+      std::deque<int> d;
+      
+      d.push_back(0);
+      mark(0) = true;
+      
+      while (!d.empty())
+      {
+        int f0 = d.at(0);
+        d.pop_front();
+        for (int k=0; k<3; k++)
+        {
+          int f1 = TT(f0,k);
+          if (f1==-1) continue;
+          if (mark(f1)) continue;
+          
+          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> dir0    = PD1out.row(f0);
+          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> dir1    = PD1out.row(f1);
+          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> n0    = N.row(f0);
+          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> n1    = N.row(f1);
+
+          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> dir0Rot = Rotate(n0,n1,dir0);
+          dir0Rot.normalize();
+          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> targD   = K_PI_new(dir1,dir0Rot,n1);
+          
+          PD1out.row(f1)  = targD;
+          PD2out.row(f1)  = n1.cross(targD).normalized();
+          
+          mark(f1) = true;
+          d.push_back(f1);
+
+        }
+      }
+      
+      // everything should be marked
+      for (int i=0; i<F.rows(); i++)
+      {
+        assert(mark(i));
+      }
+    }
+    
+    
+    
+  };
+}
+template <typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::comb_cross_field(const Eigen::PlainObjectBase<DerivedV> &V,
+                                      const Eigen::PlainObjectBase<DerivedF> &F,
+                                      const Eigen::PlainObjectBase<DerivedV> &PD1,
+                                      const Eigen::PlainObjectBase<DerivedV> &PD2,
+                                      Eigen::PlainObjectBase<DerivedV> &PD1out,
+                                      Eigen::PlainObjectBase<DerivedV> &PD2out)
+{
+  igl::Comb<DerivedV, DerivedF> cmb(V, F, PD1, PD2);
+  cmb.comb(PD1out, PD2out);
+}

+ 35 - 0
include/igl/comb_cross_field.h

@@ -0,0 +1,35 @@
+#ifndef IGL_COMB_CROSS_FIELD_H
+#define IGL_COMB_CROSS_FIELD_H
+#include "igl_inline.h"
+#include <Eigen/Core>
+namespace igl
+{
+  //todo
+  // Creates a quad mesh from a triangular mesh and a set of two directions
+  // per face, using the algorithm described in the paper
+  // "Mixed-Integer Quadrangulation" by D. Bommes, H. Zimmer, L. Kobbelt
+  // ACM SIGGRAPH 2009, Article No. 77 (http://dl.acm.org/citation.cfm?id=1531383)
+  
+  // Inputs:
+  //   Vin        #V by 3 eigen Matrix of mesh vertex 3D positions
+  //   F          #F by 4 eigen Matrix of face (quad) indices
+  //   maxIter    maximum numbers of iterations
+  //   threshold  minimum allowed threshold for non-planarity
+  // Output:
+  //   Vout       #V by 3 eigen Matrix of planar mesh vertex 3D positions
+  //
+  
+  
+  template <typename DerivedV, typename DerivedF>
+  IGL_INLINE void comb_cross_field(const Eigen::PlainObjectBase<DerivedV> &V,
+                                   const Eigen::PlainObjectBase<DerivedF> &F,
+                                   const Eigen::PlainObjectBase<DerivedV> &PD1in,
+                                   const Eigen::PlainObjectBase<DerivedV> &PD2in,
+                                   Eigen::PlainObjectBase<DerivedV> &PD1out,
+                                   Eigen::PlainObjectBase<DerivedV> &PD2out);
+}
+#ifdef IGL_HEADER_ONLY
+#include "comb_cross_field.cpp"
+#endif
+
+#endif

+ 63 - 0
include/igl/comb_frame_field.cpp

@@ -0,0 +1,63 @@
+#include "comb_frame_field.h"
+#include "local_basis.h"
+
+template <typename DerivedV, typename DerivedF, typename DerivedP>
+IGL_INLINE void igl::comb_frame_field(const Eigen::PlainObjectBase<DerivedV> &V,
+                                      const Eigen::PlainObjectBase<DerivedF> &F,
+                                      const Eigen::PlainObjectBase<DerivedP> &PD1,
+                                      const Eigen::PlainObjectBase<DerivedP> &PD2,
+                                      const Eigen::PlainObjectBase<DerivedP> &BIS1_combed,
+                                      const Eigen::PlainObjectBase<DerivedP> &BIS2_combed,
+                                      Eigen::PlainObjectBase<DerivedP> &PD1_combed,
+                                      Eigen::PlainObjectBase<DerivedP> &PD2_combed)
+{
+  Eigen::PlainObjectBase<DerivedV> B1, B2, B3;
+  igl::local_basis(V,F,B1,B2,B3);
+
+  PD1_combed.resize(BIS1_combed.rows(),3);
+  PD2_combed.resize(BIS2_combed.rows(),3);
+  
+  for (unsigned i=0; i<PD1.rows();++i)
+  {
+    Eigen::Matrix<typename DerivedP::Scalar,4,3> DIRs;
+    DIRs <<
+    PD1.row(i),
+    -PD1.row(i),
+    PD2.row(i),
+    -PD2.row(i);
+    
+    std::vector<double> a(4);
+    
+    
+    double a_combed = atan2(B2.row(i).dot(BIS1_combed.row(i)),B1.row(i).dot(BIS1_combed.row(i)));
+    
+    // center on the combed sector center
+    for (unsigned j=0;j<4;++j)
+    {
+      a[j] = atan2(B2.row(i).dot(DIRs.row(j)),B1.row(i).dot(DIRs.row(j))) - a_combed;
+      //make it positive by adding some multiple of 2pi
+      a[j] += ceil (std::max(0., -a[j]) / (M_PI*2.)) * (M_PI*2.);
+      //take modulo 2pi
+      a[j] = fmod(a[j], (M_PI*2.));
+    }
+    // now the max is u and the min is v
+    
+    int m = std::min_element(a.begin(),a.end())-a.begin();
+    int M = std::max_element(a.begin(),a.end())-a.begin();
+    
+    assert(
+           ((m>=0 && m<=1) && (M>=2 && M<=3))
+           ||
+           ((m>=2 && m<=3) && (M>=0 && M<=1))
+           );
+    
+    PD1_combed.row(i) = DIRs.row(m);
+    PD2_combed.row(i) = DIRs.row(M);
+    
+  }
+  
+  
+  //    PD1_combed = BIS1_combed;
+  //    PD2_combed = BIS2_combed;
+}
+

+ 37 - 0
include/igl/comb_frame_field.h

@@ -0,0 +1,37 @@
+#ifndef IGL_COMB_FRAME_FIELD_H
+#define IGL_COMB_FRAME_FIELD_H
+#include "igl_inline.h"
+#include <Eigen/Core>
+namespace igl
+{
+  //todo
+  // Creates a quad mesh from a triangular mesh and a set of two directions
+  // per face, using the algorithm described in the paper
+  // "Mixed-Integer Quadrangulation" by D. Bommes, H. Zimmer, L. Kobbelt
+  // ACM SIGGRAPH 2009, Article No. 77 (http://dl.acm.org/citation.cfm?id=1531383)
+  
+  // Inputs:
+  //   Vin        #V by 3 eigen Matrix of mesh vertex 3D positions
+  //   F          #F by 4 eigen Matrix of face (quad) indices
+  //   maxIter    maximum numbers of iterations
+  //   threshold  minimum allowed threshold for non-planarity
+  // Output:
+  //   Vout       #V by 3 eigen Matrix of planar mesh vertex 3D positions
+  //
+  
+  
+  template <typename DerivedV, typename DerivedF, typename DerivedP>
+  IGL_INLINE void comb_frame_field(const Eigen::PlainObjectBase<DerivedV> &V,
+                                        const Eigen::PlainObjectBase<DerivedF> &F,
+                                        const Eigen::PlainObjectBase<DerivedP> &PD1,
+                                        const Eigen::PlainObjectBase<DerivedP> &PD2,
+                                        const Eigen::PlainObjectBase<DerivedP> &BIS1_combed,
+                                        const Eigen::PlainObjectBase<DerivedP> &BIS2_combed,
+                                        Eigen::PlainObjectBase<DerivedP> &PD1_combed,
+                                        Eigen::PlainObjectBase<DerivedP> &PD2_combed);
+}
+#ifdef IGL_HEADER_ONLY
+#include "comb_frame_field.cpp"
+#endif
+
+#endif

+ 2267 - 0
include/igl/comiso/mixed_integer_quadrangulate.cpp

@@ -0,0 +1,2267 @@
+#include <igl/comiso/mixed_integer_quadrangulate.h>
+#include <igl/local_basis.h>
+#include <igl/tt.h>
+
+// includes for VertexIndexing
+#include <igl/Pos.h>
+#include <igl/is_border_vertex.h>
+#include <igl/vf.h>
+
+
+// includes for poissonSolver
+#include <gmm/gmm.h>
+#include <CoMISo/Solver/ConstrainedSolver.hh>
+#include <CoMISo/Solver/MISolver.hh>
+#include <CoMISo/Solver/GMM_Tools.hh>
+#include <igl/doublearea.h>
+#include <igl/per_face_normals.h>
+
+//
+#include <igl/cross_field_missmatch.h>
+#include <igl/comb_frame_field.h>
+#include <igl/cut_mesh_from_singularities.h>
+#include <igl/find_cross_field_singularities.h>
+#include <igl/compute_frame_field_bisectors.h>
+
+#define DEBUGPRINT 0
+
+
+namespace igl {
+
+  class SparseMatrixData{
+  protected:
+    unsigned int m_nrows;
+    unsigned int m_ncols;
+    std::vector<unsigned int> m_rowind;
+    std::vector<unsigned int> m_colind;
+    std::vector<double>       m_vals;
+
+  public:
+    unsigned int   nrows()    { return m_nrows      ; }
+    unsigned int   ncols()    { return m_ncols      ; }
+    unsigned int   nentries() { return m_vals.size(); }
+    std::vector<unsigned int>&  rowind()   { return m_rowind     ; }
+    std::vector<unsigned int>&  colind()   { return m_colind     ; }
+    std::vector<double>&        vals()     { return m_vals       ; }
+
+    // create an empty matrix with a fixed number of rows
+    SparseMatrixData()
+    {
+      initialize(0,0);
+    }
+
+    // create an empty matrix with a fixed number of rows
+    void initialize(int nr, int nc) {
+      assert(nr >= 0 && nc >=0);
+      m_nrows = nr;
+      m_ncols = nc;
+
+      m_rowind.resize(0);
+      m_colind.resize(0);
+      m_vals.resize(0);
+    }
+
+    // add a nonzero entry to the matrix
+    // no checks are done for coinciding entries
+    // the interpretation of the repeated entries (replace or add)
+    // depends on how the actual sparse matrix datastructure is constructed
+
+    void addEntryCmplx(unsigned int i, unsigned int j, std::complex<double> val) {
+      m_rowind.push_back(2*i);   m_colind.push_back(2*j);   m_vals.push_back( val.real());
+      m_rowind.push_back(2*i);   m_colind.push_back(2*j+1); m_vals.push_back(-val.imag());
+      m_rowind.push_back(2*i+1); m_colind.push_back(2*j);   m_vals.push_back( val.imag());
+      m_rowind.push_back(2*i+1); m_colind.push_back(2*j+1); m_vals.push_back( val.real());
+    }
+
+    void addEntryReal(unsigned int i, unsigned int j, double val) {
+      m_rowind.push_back(i);   m_colind.push_back(j);   m_vals.push_back(val);
+    }
+
+    virtual ~SparseMatrixData() {
+    }
+
+  };
+
+  // a small class to manage storage for matrix data
+  // not using stl vectors: want to make all memory management
+  // explicit to avoid hidden automatic reallocation
+  // TODO: redo with STL vectors but with explicit mem. management
+
+  class SparseSystemData {
+  private:
+    // matrix representation,  A[rowind[i],colind[i]] = vals[i]
+    // right-hand side
+    SparseMatrixData m_A;
+    double       *m_b;
+    double       *m_x;
+
+  public:
+    SparseMatrixData& A() { return m_A; }
+    double*        b()        { return m_b       ; }
+    double*        x()        { return m_x       ; }
+    unsigned int   nrows()    { return  m_A.nrows(); }
+
+  public:
+
+    SparseSystemData(): m_A(), m_b(NULL), m_x(NULL){ }
+
+    void initialize(unsigned int nr, unsigned int nc) {
+      m_A.initialize(nr,nc);
+      m_b      = new          double[nr];
+      m_x      = new          double[nr];
+      assert(m_b);
+      std::fill( m_b,  m_b+nr, 0.);
+    }
+
+    void addRHSCmplx(unsigned int i, std::complex<double> val) {
+      assert( 2*i+1 < m_A.nrows());
+      m_b[2*i] += val.real(); m_b[2*i+1] += val.imag();
+    }
+
+    void setRHSCmplx(unsigned int i, std::complex<double> val) {
+      assert( 2*i+1 < m_A.nrows());
+      m_b[2*i] = val.real(); m_b[2*i+1] = val.imag();
+    }
+
+    std::complex<double> getRHSCmplx(unsigned int i) {
+      assert( 2*i+1 < m_A.nrows());
+      return std::complex<double>( m_b[2*i], m_b[2*i+1]);
+    }
+
+    double getRHSReal(unsigned int i) {
+      assert( i < m_A.nrows());
+      return m_b[i];
+    }
+
+    std::complex<double> getXCmplx(unsigned int i) {
+      assert( 2*i+1 < m_A.nrows());
+      return std::complex<double>( m_x[2*i], m_x[2*i+1]);
+    }
+
+    void cleanMem() {
+      //m_A.cleanup();
+      delete [] m_b;
+      delete [] m_x;
+    }
+
+    virtual ~SparseSystemData() {
+      delete [] m_b;
+      delete [] m_x;
+    }
+  };
+
+  struct SeamInfo
+  {
+    int v0,v0p,v1,v1p;
+    int integerVar;
+    unsigned char MMatch;
+
+    SeamInfo(int _v0,
+             int _v1,
+             int _v0p,
+             int _v1p,
+             int _MMatch,
+             int _integerVar);
+
+    SeamInfo(const SeamInfo &S1);
+  };
+
+  struct MeshSystemInfo
+  {
+    ///total number of scalar variables
+    int num_scalar_variables;
+    ////number of vertices variables
+    int num_vert_variables;
+    ///num of integer for cuts
+    int num_integer_cuts;
+    ///this are used for drawing purposes
+    std::vector<SeamInfo> EdgeSeamInfo;
+#if 0
+    ///this are values of integer variables after optimization
+    std::vector<int> IntegerValues;
+#endif
+  };
+
+
+  template <typename DerivedV, typename DerivedF>
+  class VertexIndexing
+  {
+  public:
+    // Input:
+    const Eigen::PlainObjectBase<DerivedV> &V;
+    const Eigen::PlainObjectBase<DerivedF> &F;
+    const Eigen::PlainObjectBase<DerivedF> &TT;
+    const Eigen::PlainObjectBase<DerivedF> &TTi;
+    const Eigen::PlainObjectBase<DerivedV> &PD1;
+    const Eigen::PlainObjectBase<DerivedV> &PD2;
+
+    const Eigen::Matrix<int, Eigen::Dynamic, 3> &Handle_MMatch;
+    const Eigen::Matrix<int, Eigen::Dynamic, 1> &Handle_Singular; // bool
+    const Eigen::Matrix<int, Eigen::Dynamic, 1> &Handle_SingularDegree; // vertex;
+    const Eigen::Matrix<int, Eigen::Dynamic, 3> &Handle_Seams; // 3 bool
+
+
+    ///this handle for mesh TODO: move with the other global variables
+    MeshSystemInfo Handle_SystemInfo;
+
+    // Output:
+    ///this maps the integer for edge - face
+    Eigen::MatrixXi Handle_Integer; // TODO: remove it is useless
+
+    ///per face indexes of vertex in the solver
+    Eigen::MatrixXi HandleS_Index;
+
+    ///per vertex variable indexes
+    std::vector<std::vector<int> > HandleV_Integer;
+
+    // internal
+    std::vector<std::vector<int> > VF, VFi;
+    std::vector<bool> V_border; // bool
+
+    VertexIndexing(const Eigen::PlainObjectBase<DerivedV> &_V,
+                   const Eigen::PlainObjectBase<DerivedF> &_F,
+                   const Eigen::PlainObjectBase<DerivedF> &_TT,
+                   const Eigen::PlainObjectBase<DerivedF> &_TTi,
+                   const Eigen::PlainObjectBase<DerivedV> &_PD1,
+                   const Eigen::PlainObjectBase<DerivedV> &_PD2,
+                   const Eigen::Matrix<int, Eigen::Dynamic, 3> &_Handle_MMatch,
+                   const Eigen::Matrix<int, Eigen::Dynamic, 1> &_Handle_Singular,
+                   const Eigen::Matrix<int, Eigen::Dynamic, 1> &_Handle_SingularDegree,
+                   const Eigen::Matrix<int, Eigen::Dynamic, 3> &_Handle_Seams
+                   );
+
+    ///vertex to variable mapping
+    void InitMapping();
+
+    void InitFaceIntegerVal();
+
+    void InitSeamInfo();
+
+
+  private:
+    ///this maps back index to vertices
+    std::vector<int> IndexToVert; // TODO remove it is useless
+
+    ///this is used for drawing purposes
+    std::vector<int> duplicated; // TODO remove it is useless
+
+    void FirstPos(const int v, int &f, int &edge);
+
+    int AddNewIndex(const int v0);
+
+    bool HasIndex(int indexVert,int indexVar);
+
+    void GetSeamInfo(const int f0,
+                     const int f1,
+                     const int indexE,
+                     int &v0,int &v1,
+                     int &v0p,int &v1p,
+                     unsigned char &_MMatch,
+                     int &integerVar);
+    bool IsSeam(const int f0, const int f1);
+
+    ///find initial position of the pos to
+    // assing face to vert inxex correctly
+    void FindInitialPos(const int vert, int &edge, int &face);
+
+
+    ///intialize the mapping given an initial pos
+    ///whih must be initialized with FindInitialPos
+    void MapIndexes(const int  vert, const int edge_init, const int f_init);
+
+    ///intialize the mapping for a given vertex
+    void InitMappingSeam(const int vert);
+
+    ///intialize the mapping for a given sampled mesh
+    void InitMappingSeam();
+
+    ///test consistency of face variables per vert mapping
+    void TestSeamMappingFace(const int f);
+
+    ///test consistency of face variables per vert mapping
+    void TestSeamMappingVertex(int indexVert);
+
+    ///check consistency of variable mapping across seams
+    void TestSeamMapping();
+
+  };
+
+
+  template <typename DerivedV, typename DerivedF>
+  class PoissonSolver
+  {
+
+  public:
+    void SolvePoisson(Eigen::VectorXd Stiffness,
+                      double vector_field_scale=0.1f,
+                      double grid_res=1.f,
+                      bool direct_round=true,
+                      int localIter=0,
+                      bool _integer_rounding=true,
+                      std::vector<int> roundVertices = std::vector<int>(),
+                      std::vector<std::vector<int> > hardFeatures = std::vector<std::vector<int> >());
+
+    PoissonSolver(const Eigen::PlainObjectBase<DerivedV> &_V,
+                  const Eigen::PlainObjectBase<DerivedF> &_F,
+                  const Eigen::PlainObjectBase<DerivedF> &_TT,
+                  const Eigen::PlainObjectBase<DerivedF> &_TTi,
+                  const Eigen::PlainObjectBase<DerivedV> &_PD1,
+                  const Eigen::PlainObjectBase<DerivedV> &_PD2,
+                  const Eigen::MatrixXi &_HandleS_Index,
+                  const Eigen::Matrix<int, Eigen::Dynamic, 1>&_Handle_Singular,
+                  const MeshSystemInfo &_Handle_SystemInfo
+                  );
+
+    // Input:
+    //    Eigen::MatrixXd V;
+    //    Eigen::MatrixXi F;
+    //    Eigen::MatrixXd PD1;
+    //    Eigen::MatrixXd PD2;
+    //    Eigen::MatrixXi HandleS_Index;
+    //    Eigen::VectorXi Handle_Singular;
+
+    const Eigen::PlainObjectBase<DerivedV> &V;
+    const Eigen::PlainObjectBase<DerivedF> &F;
+    const Eigen::PlainObjectBase<DerivedF> &TT;
+    const Eigen::PlainObjectBase<DerivedF> &TTi;
+    const Eigen::PlainObjectBase<DerivedV> &PD1;
+    const Eigen::PlainObjectBase<DerivedV> &PD2;
+    const Eigen::Matrix<int, Eigen::Dynamic, 1> &Handle_Singular; // bool
+    const Eigen::MatrixXi &HandleS_Index; //todo
+
+    const MeshSystemInfo &Handle_SystemInfo;
+
+    // Internal:
+    Eigen::MatrixXd doublearea;
+    Eigen::VectorXd Handle_Stiffness;
+    Eigen::PlainObjectBase<DerivedV> N;
+    std::vector<std::vector<int> > VF;
+    std::vector<std::vector<int> > VFi;
+    Eigen::MatrixXd UV; // this is probably useless
+
+    // Output:
+    // per wedge UV coordinates, 6 coordinates (1 face) per row
+    Eigen::MatrixXd WUV;
+
+    ///solver data
+    SparseSystemData S;
+
+    ///vector of unknowns
+    std::vector< double > X;
+
+    ////REAL PART
+    ///number of fixed vertex
+    unsigned int n_fixed_vars;
+
+    ///the number of REAL variables for vertices
+    unsigned int n_vert_vars;
+
+    ///total number of variables of the system,
+    ///do not consider constraints, but consider integer vars
+    unsigned int num_total_vars;
+
+    //////INTEGER PART
+    ///the total number of integer variables
+    unsigned int n_integer_vars;
+
+    ///CONSTRAINT PART
+    ///number of cuts constraints
+    unsigned int num_cut_constraint;
+
+    // number of user-defined constraints
+    unsigned int num_userdefined_constraint;
+
+    ///total number of constraints equations
+    unsigned int num_constraint_equations;
+
+    ///total size of the system including constraints
+    unsigned int system_size;
+
+    ///if you intend to make integer rotation
+    ///and translations
+    bool integer_jumps_bary;
+
+    ///vector of blocked vertices
+    std::vector<int> Hard_constraints;
+
+    ///vector of indexes to round
+    std::vector<int> ids_to_round;
+
+    ///vector of indexes to round
+    std::vector<std::vector<int > > userdefined_constraints;
+
+    ///boolean that is true if rounding to integer is needed
+    bool integer_rounding;
+
+    ///START SYSTEM ACCESS METHODS
+    ///add an entry to the LHS
+    void AddValA(int Xindex,
+                 int Yindex,
+                 double val);
+
+    ///add a complex entry to the LHS
+    void AddComplexA(int VarXindex,
+                     int VarYindex,
+                     std::complex<double> val);
+
+    ///add a velue to the RHS
+    void AddValB(int Xindex,
+                 double val);
+
+    ///add the area term, scalefactor is used to sum up
+    ///and normalize on the overlap zones
+    void AddAreaTerm(int index[3][3][2],double ScaleFactor);
+
+    ///set the diagonal of the matrix (which is zero at the beginning)
+    ///such that the sum of a row or a colums is zero
+    void SetDiagonal(double val[3][3]);
+
+    ///given a vector of scalar values and
+    ///a vector of indexes add such values
+    ///as specified by the indexes
+    void AddRHS(double b[6],
+                int index[3]);
+
+    ///add a 3x3 block matrix to the system matrix...
+    ///indexes are specified in the 3x3 matrix of x,y pairs
+    ///indexes must be multiplied by 2 cause u and v
+    void Add33Block(double val[3][3], int index[3][3][2]);
+
+    ///add a 3x3 block matrix to the system matrix...
+    ///indexes are specified in the 3x3 matrix of x,y pairs
+    ///indexes must be multiplied by 2 cause u and v
+    void Add44Block(double val[4][4],int index[4][4][2]);
+    ///END SYSTEM ACCESS METHODS
+
+    ///START COMMON MATH FUNCTIONS
+    ///return the complex encoding the rotation
+    ///for a given missmatch interval
+    std::complex<double> GetRotationComplex(int interval);
+    ///END COMMON MATH FUNCTIONS
+
+
+    ///START ENERGY MINIMIZATION PART
+    ///initialize the LHS for a given face
+    ///for minimization of Dirichlet's energy
+    void perElementLHS(int f,
+                       double val[3][3],
+                       int index[3][3][2]);
+
+    ///initialize the RHS for a given face
+    ///for minimization of Dirichlet's energy
+    void perElementRHS(int f,
+                       double b[6],
+                       double vector_field_scale=1);
+
+    ///evaluate the LHS and RHS for a single face
+    ///for minimization of Dirichlet's energy
+    void PerElementSystemReal(int f,
+                              double val[3][3],
+                              int index[3][3][2],
+                              double b[6],
+                              double vector_field_scale=1.0);
+    ///END ENERGY MINIMIZATION PART
+
+    ///START FIXING VERTICES
+    ///set a given vertex as fixed
+    void AddFixedVertex(int v);
+
+    ///find vertex to fix in case we're using
+    ///a vector field NB: multiple components not handled
+    void FindFixedVertField();
+
+    ///find hard constraint depending if using or not
+    ///a vector field
+    void FindFixedVert();
+
+    int GetFirstVertexIndex(int v);
+
+    ///fix the vertices which are flagged as fixed
+    void FixBlockedVertex();
+    ///END FIXING VERTICES
+
+    ///HANDLING SINGULARITY
+    //set the singularity round to integer location
+    void AddSingularityRound();
+
+    void AddToRoundVertices(std::vector<int> ids);
+
+    ///START GENERIC SYSTEM FUNCTIONS
+    //build the laplacian matrix cyclyng over all rangemaps
+    //and over all faces
+    void BuildLaplacianMatrix(double vfscale=1);
+
+    ///find different sized of the system
+    void FindSizes();
+
+    void AllocateSystem();
+
+    ///intitialize the whole matrix
+    void InitMatrix();
+
+    ///map back coordinates after that
+    ///the system has been solved
+    void MapCoords();
+    ///END GENERIC SYSTEM FUNCTIONS
+
+    ///set the constraints for the inter-range cuts
+    void BuildSeamConstraintsExplicitTranslation();
+
+    ///set the constraints for the inter-range cuts
+    void BuildUserDefinedConstraints();
+
+    ///call of the mixed integer solver
+    void MixedIntegerSolve(double cone_grid_res=1,
+                           bool direct_round=true,
+                           int localIter=0);
+
+    void clearUserConstraint();
+
+    void addSharpEdgeConstraint(int fid, int vid);
+
+  };
+
+  template <typename DerivedV, typename DerivedF, typename DerivedU>
+  class MIQ
+  {
+  private:
+    const Eigen::PlainObjectBase<DerivedV> &V;
+    const Eigen::PlainObjectBase<DerivedF> &F;
+    Eigen::MatrixXd WUV;
+    // internal
+    Eigen::PlainObjectBase<DerivedF> TT;
+    Eigen::PlainObjectBase<DerivedF> TTi;
+
+    // Stiffness per face
+    Eigen::VectorXd Handle_Stiffness;
+    Eigen::PlainObjectBase<DerivedV> B1, B2, B3;
+
+  public:
+    MIQ(const Eigen::PlainObjectBase<DerivedV> &V_,
+        const Eigen::PlainObjectBase<DerivedF> &F_,
+        const Eigen::PlainObjectBase<DerivedV> &PD1_combed,
+        const Eigen::PlainObjectBase<DerivedV> &PD2_combed,
+        const Eigen::PlainObjectBase<DerivedV> &BIS1_combed,
+        const Eigen::PlainObjectBase<DerivedV> &BIS2_combed,
+        const Eigen::Matrix<int, Eigen::Dynamic, 3> &Handle_MMatch,
+        const Eigen::Matrix<int, Eigen::Dynamic, 1> &Handle_Singular,
+        const Eigen::Matrix<int, Eigen::Dynamic, 1> &Handle_SingularDegree,
+        const Eigen::Matrix<int, Eigen::Dynamic, 3> &Handle_Seams,
+        Eigen::PlainObjectBase<DerivedU> &UV,
+        Eigen::PlainObjectBase<DerivedF> &FUV,
+        double GradientSize = 30.0,
+        double Stiffness = 5.0,
+        bool DirectRound = false,
+        int iter = 5,
+        int localIter = 5,
+        bool DoRound = true,
+        std::vector<int> roundVertices = std::vector<int>(),
+        std::vector<std::vector<int> > hardFeatures = std::vector<std::vector<int> >());
+
+
+    void extractUV(Eigen::PlainObjectBase<DerivedU> &UV_out,
+                   Eigen::PlainObjectBase<DerivedF> &FUV_out);
+
+  private:
+    int NumFlips(const Eigen::MatrixXd& WUV);
+
+    double Distortion(int f, double h, const Eigen::MatrixXd& WUV);
+
+    double LaplaceDistortion(const int f, double h, const Eigen::MatrixXd& WUV);
+
+    bool updateStiffeningJacobianDistorsion(double grad_size, const Eigen::MatrixXd& WUV);
+
+    inline bool IsFlipped(const Eigen::Vector2d &uv0,
+                          const Eigen::Vector2d &uv1,
+                          const Eigen::Vector2d &uv2);
+
+    inline bool IsFlipped(const int i, const Eigen::MatrixXd& WUV);
+
+  };
+};
+
+igl::SeamInfo::SeamInfo(int _v0,
+                        int _v1,
+                        int _v0p,
+                        int _v1p,
+                        int _MMatch,
+                        int _integerVar)
+{
+  v0=_v0;
+  v1=_v1;
+  v0p=_v0p;
+  v1p=_v1p;
+  integerVar=_integerVar;
+  MMatch=_MMatch;
+}
+
+igl::SeamInfo::SeamInfo(const SeamInfo &S1)
+{
+  v0=S1.v0;
+  v1=S1.v1;
+  v0p=S1.v0p;
+  v1p=S1.v1p;
+  integerVar=S1.integerVar;
+  MMatch=S1.MMatch;
+}
+
+
+template <typename DerivedV, typename DerivedF>
+igl::VertexIndexing<DerivedV, DerivedF>::VertexIndexing(const Eigen::PlainObjectBase<DerivedV> &_V,
+                                                        const Eigen::PlainObjectBase<DerivedF> &_F,
+                                                        const Eigen::PlainObjectBase<DerivedF> &_TT,
+                                                        const Eigen::PlainObjectBase<DerivedF> &_TTi,
+                                                        const Eigen::PlainObjectBase<DerivedV> &_PD1,
+                                                        const Eigen::PlainObjectBase<DerivedV> &_PD2,
+                                                        const Eigen::Matrix<int, Eigen::Dynamic, 3> &_Handle_MMatch,
+                                                        const Eigen::Matrix<int, Eigen::Dynamic, 1> &_Handle_Singular,
+                                                        const Eigen::Matrix<int, Eigen::Dynamic, 1> &_Handle_SingularDegree,
+                                                        const Eigen::Matrix<int, Eigen::Dynamic, 3> &_Handle_Seams
+
+                                                        ):
+V(_V),
+F(_F),
+TT(_TT),
+TTi(_TTi),
+PD1(_PD1),
+PD2(_PD2),
+Handle_MMatch(_Handle_MMatch),
+Handle_Singular(_Handle_Singular),
+Handle_SingularDegree(_Handle_SingularDegree),
+Handle_Seams(_Handle_Seams)
+{
+
+  V_border = igl::is_border_vertex(V,F);
+  igl::vf(V,F,VF,VFi);
+
+  IndexToVert.clear();
+
+  Handle_SystemInfo.num_scalar_variables=0;
+  Handle_SystemInfo.num_vert_variables=0;
+  Handle_SystemInfo.num_integer_cuts=0;
+
+  duplicated.clear();
+
+  HandleS_Index = Eigen::MatrixXi::Constant(F.rows(),3,-1);
+
+  Handle_Integer = Eigen::MatrixXi::Constant(F.rows(),3,-1);
+
+  HandleV_Integer.resize(V.rows());
+}
+
+template <typename DerivedV, typename DerivedF>
+void igl::VertexIndexing<DerivedV, DerivedF>::FirstPos(const int v, int &f, int &edge)
+{
+  f    = VF[v][0];  // f=v->cVFp();
+  edge = VFi[v][0]; // edge=v->cVFi();
+}
+
+template <typename DerivedV, typename DerivedF>
+int igl::VertexIndexing<DerivedV, DerivedF>::AddNewIndex(const int v0)
+{
+  Handle_SystemInfo.num_scalar_variables++;
+  HandleV_Integer[v0].push_back(Handle_SystemInfo.num_scalar_variables);
+  IndexToVert.push_back(v0);
+  return Handle_SystemInfo.num_scalar_variables;
+}
+
+template <typename DerivedV, typename DerivedF>
+bool igl::VertexIndexing<DerivedV, DerivedF>::HasIndex(int indexVert,int indexVar)
+{
+  for (unsigned int i=0;i<HandleV_Integer[indexVert].size();i++)
+    if (HandleV_Integer[indexVert][i]==indexVar)return true;
+  return false;
+}
+
+template <typename DerivedV, typename DerivedF>
+void igl::VertexIndexing<DerivedV, DerivedF>::GetSeamInfo(const int f0,
+                                                          const int f1,
+                                                          const int indexE,
+                                                          int &v0,int &v1,
+                                                          int &v0p,int &v1p,
+                                                          unsigned char &_MMatch,
+                                                          int &integerVar)
+{
+  int edgef0 = indexE;
+  v0 = HandleS_Index(f0,edgef0);
+  v1 = HandleS_Index(f0,(edgef0+1)%3);
+  ////get the index on opposite side
+  assert(TT(f0,edgef0) == f1);
+  int edgef1 = TTi(f0,edgef0);
+  v1p = HandleS_Index(f1,edgef1);
+  v0p = HandleS_Index(f1,(edgef1+1)%3);
+
+  integerVar = Handle_Integer(f0,edgef0);
+  _MMatch = Handle_MMatch(f0,edgef0);
+  assert(F(f0,edgef0)         == F(f1,((edgef1+1)%3)));
+  assert(F(f0,((edgef0+1)%3)) == F(f1,edgef1));
+}
+
+template <typename DerivedV, typename DerivedF>
+bool igl::VertexIndexing<DerivedV, DerivedF>::IsSeam(const int f0, const int f1)
+{
+  for (int i=0;i<3;i++)
+  {
+    int f_clos = TT(f0,i);
+
+    if (f_clos == -1)
+      continue; ///border
+
+    if (f_clos == f1)
+      return(Handle_Seams(f0,i));
+  }
+  assert(0);
+  return false;
+}
+
+///find initial position of the pos to
+// assing face to vert inxex correctly
+template <typename DerivedV, typename DerivedF>
+void igl::VertexIndexing<DerivedV, DerivedF>::FindInitialPos(const int vert,
+                                                             int &edge,
+                                                             int &face)
+{
+  int f_init;
+  int edge_init;
+  FirstPos(vert,f_init,edge_init); // todo manually inline the function
+  igl::Pos<DerivedF> VFI(&F,&TT,&TTi,f_init,edge_init);
+
+  bool vertexB = V_border[vert];
+  bool possible_split=false;
+  bool complete_turn=false;
+  do
+  {
+    int curr_f = VFI.Fi();
+    int curr_edge=VFI.Ei();
+    VFI.NextFE();
+    int next_f=VFI.Fi();
+    ///test if I've just crossed a border
+    bool on_border=(TT(curr_f,curr_edge)==-1);
+    //bool mismatch=false;
+    bool seam=false;
+
+    ///or if I've just crossed a seam
+    ///if I'm on a border I MUST start from the one next t othe border
+    if (!vertexB)
+      //seam=curr_f->IsSeam(next_f);
+      seam=IsSeam(curr_f,next_f);
+    if (vertexB)
+      assert(!Handle_Singular(vert));
+    ;
+    //assert(!vert->IsSingular());
+    possible_split=((on_border)||(seam));
+    complete_turn = next_f == f_init;
+  } while ((!possible_split)&&(!complete_turn));
+  face=VFI.Fi();
+  edge=VFI.Ei();
+  ///test that is not on a border
+  //assert(face->FFp(edge)!=face);
+}
+
+
+
+///intialize the mapping given an initial pos
+///whih must be initialized with FindInitialPos
+template <typename DerivedV, typename DerivedF>
+void igl::VertexIndexing<DerivedV, DerivedF>::MapIndexes(const int  vert,
+                                                         const int edge_init,
+                                                         const int f_init)
+{
+  ///check that is not on border..
+  ///in such case maybe it's non manyfold
+  ///insert an initial index
+  int curr_index=AddNewIndex(vert);
+  ///and initialize the jumping pos
+  igl::Pos<DerivedF> VFI(&F,&TT,&TTi,f_init,edge_init);
+  bool complete_turn=false;
+  do
+  {
+    int curr_f = VFI.Fi();
+    int curr_edge = VFI.Ei();
+    ///assing the current index
+    HandleS_Index(curr_f,curr_edge) = curr_index;
+    VFI.NextFE();
+    int next_f = VFI.Fi();
+    ///test if I've finiseh with the face exploration
+    complete_turn = (next_f==f_init);
+    ///or if I've just crossed a mismatch
+    if (!complete_turn)
+    {
+      bool seam=false;
+      //seam=curr_f->IsSeam(next_f);
+      seam=IsSeam(curr_f,next_f);
+      if (seam)
+      {
+        ///then add a new index
+        curr_index=AddNewIndex(vert);
+      }
+    }
+  } while (!complete_turn);
+}
+
+///intialize the mapping for a given vertex
+template <typename DerivedV, typename DerivedF>
+void igl::VertexIndexing<DerivedV, DerivedF>::InitMappingSeam(const int vert)
+{
+  ///first rotate until find the first pos after a mismatch
+  ///or a border or return to the first position...
+  int f_init = VF[vert][0];
+  int indexE = VFi[vert][0];
+
+  igl::Pos<DerivedF> VFI(&F,&TT,&TTi,f_init,indexE);
+
+  int edge_init;
+  int face_init;
+  FindInitialPos(vert,edge_init,face_init);
+  MapIndexes(vert,edge_init,face_init);
+}
+
+///intialize the mapping for a given sampled mesh
+template <typename DerivedV, typename DerivedF>
+void igl::VertexIndexing<DerivedV, DerivedF>::InitMappingSeam()
+{
+  //num_scalar_variables=-1;
+  Handle_SystemInfo.num_scalar_variables=-1;
+  for (unsigned int i=0;i<V.rows();i++)
+    InitMappingSeam(i);
+
+  for (unsigned int j=0;j<V.rows();j++)
+  {
+    assert(HandleV_Integer[j].size()>0);
+    if (HandleV_Integer[j].size()>1)
+      duplicated.push_back(j);
+  }
+}
+
+///test consistency of face variables per vert mapping
+template <typename DerivedV, typename DerivedF>
+void igl::VertexIndexing<DerivedV, DerivedF>::TestSeamMappingFace(const int f)
+{
+  for (int k=0;k<3;k++)
+  {
+    int indexV=HandleS_Index(f,k);
+    int v = F(f,k);
+    bool has_index=HasIndex(v,indexV);
+    assert(has_index);
+  }
+}
+
+///test consistency of face variables per vert mapping
+template <typename DerivedV, typename DerivedF>
+void igl::VertexIndexing<DerivedV, DerivedF>::TestSeamMappingVertex(int indexVert)
+{
+  for (unsigned int k=0;k<HandleV_Integer[indexVert].size();k++)
+  {
+    int indexV=HandleV_Integer[indexVert][k];
+
+    ///get faces sharing vertex
+    std::vector<int> faces = VF[indexVert];
+    std::vector<int> indexes = VFi[indexVert];
+
+    for (unsigned int j=0;j<faces.size();j++)
+    {
+      int f = faces[j];
+      int index = indexes[j];
+      assert(F(f,index) == indexVert);
+      assert((index>=0)&&(index<3));
+
+      if (HandleS_Index(f,index) == indexV)
+        return;
+    }
+  }
+  assert(0);
+}
+
+
+///check consistency of variable mapping across seams
+template <typename DerivedV, typename DerivedF>
+void igl::VertexIndexing<DerivedV, DerivedF>::TestSeamMapping()
+{
+  printf("\n TESTING SEAM INDEXES \n");
+  ///test F-V mapping
+  for (unsigned int j=0;j<F.rows();j++)
+    TestSeamMappingFace(j);
+
+  ///TEST  V-F MAPPING
+  for (unsigned int j=0;j<V.rows();j++)
+    TestSeamMappingVertex(j);
+
+}
+
+
+///vertex to variable mapping
+template <typename DerivedV, typename DerivedF>
+void igl::VertexIndexing<DerivedV, DerivedF>::InitMapping()
+{
+  //use_direction_field=_use_direction_field;
+
+  IndexToVert.clear();
+  duplicated.clear();
+
+  InitMappingSeam();
+
+  Handle_SystemInfo.num_vert_variables=Handle_SystemInfo.num_scalar_variables+1;
+
+  ///end testing...
+  TestSeamMapping();
+}
+
+template <typename DerivedV, typename DerivedF>
+void igl::VertexIndexing<DerivedV, DerivedF>::InitFaceIntegerVal()
+{
+  Handle_SystemInfo.num_integer_cuts=0;
+  for (unsigned int j=0;j<F.rows();j++)
+  {
+    for (int k=0;k<3;k++)
+    {
+      if (Handle_Seams(j,k))
+      {
+        Handle_Integer(j,k) = Handle_SystemInfo.num_integer_cuts;
+        Handle_SystemInfo.num_integer_cuts++;
+      }
+      else
+        Handle_Integer(j,k)=-1;
+    }
+  }
+}
+
+
+template <typename DerivedV, typename DerivedF>
+void igl::VertexIndexing<DerivedV, DerivedF>::InitSeamInfo()
+{
+  Handle_SystemInfo.EdgeSeamInfo.clear();
+  for (unsigned int f0=0;f0<F.rows();f0++)
+  {
+    for (int k=0;k<3;k++)
+    {
+      int f1 = TT(f0,k);
+
+      if (f1 == -1)
+        continue;
+
+      bool seam = Handle_Seams(f0,k);
+      if (seam)
+      {
+        int v0,v0p,v1,v1p;
+        unsigned char MM;
+        int integerVar;
+        GetSeamInfo(f0,f1,k,v0,v1,v0p,v1p,MM,integerVar);
+        Handle_SystemInfo.EdgeSeamInfo.push_back(SeamInfo(v0,v1,v0p,v1p,MM,integerVar));
+      }
+    }
+  }
+}
+
+
+
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::SolvePoisson(Eigen::VectorXd Stiffness,
+                                                          double vector_field_scale,
+                                                          double grid_res,
+                                                          bool direct_round,
+                                                          int localIter,
+                                                          bool _integer_rounding,
+                                                          std::vector<int> roundVertices,
+                                                          std::vector<std::vector<int> > hardFeatures)
+{
+  Handle_Stiffness = Stiffness;
+
+  //initialization of flags and data structures
+  integer_rounding=_integer_rounding;
+
+  ids_to_round.clear();
+
+  clearUserConstraint();
+  // copy the user constraints number
+  for (int i = 0; i < hardFeatures.size(); ++i)
+  {
+    addSharpEdgeConstraint(hardFeatures[i][0],hardFeatures[i][1]);
+  }
+
+  ///Initializing Matrix
+
+  int t0=clock();
+
+  ///initialize the matrix ALLOCATING SPACE
+  InitMatrix();
+  if (DEBUGPRINT)
+    printf("\n ALLOCATED THE MATRIX \n");
+
+  ///build the laplacian system
+  BuildLaplacianMatrix(vector_field_scale);
+
+  // add seam constraints
+  BuildSeamConstraintsExplicitTranslation();
+
+  // add user defined constraints
+  BuildUserDefinedConstraints();
+
+  ////add the lagrange multiplier
+  FixBlockedVertex();
+
+  if (DEBUGPRINT)
+    printf("\n BUILT THE MATRIX \n");
+
+  if (integer_rounding)
+  {
+    AddSingularityRound();
+    AddToRoundVertices(roundVertices);
+  }
+
+  int t1=clock();
+  if (DEBUGPRINT) printf("\n time:%d \n",t1-t0);
+  if (DEBUGPRINT) printf("\n SOLVING \n");
+
+  MixedIntegerSolve(grid_res,direct_round,localIter);
+
+  int t2=clock();
+  if (DEBUGPRINT) printf("\n time:%d \n",t2-t1);
+  if (DEBUGPRINT) printf("\n ASSIGNING COORDS \n");
+
+  MapCoords();
+
+  int t3=clock();
+  if (DEBUGPRINT) printf("\n time:%d \n",t3-t2);
+  if (DEBUGPRINT) printf("\n FINISHED \n");
+}
+
+template <typename DerivedV, typename DerivedF>
+igl::PoissonSolver<DerivedV, DerivedF>
+::PoissonSolver(const Eigen::PlainObjectBase<DerivedV> &_V,
+                const Eigen::PlainObjectBase<DerivedF> &_F,
+                const Eigen::PlainObjectBase<DerivedF> &_TT,
+                const Eigen::PlainObjectBase<DerivedF> &_TTi,
+                const Eigen::PlainObjectBase<DerivedV> &_PD1,
+                const Eigen::PlainObjectBase<DerivedV> &_PD2,
+                const Eigen::MatrixXi &_HandleS_Index,
+                const Eigen::Matrix<int, Eigen::Dynamic, 1>&_Handle_Singular,
+                const MeshSystemInfo &_Handle_SystemInfo //todo: const?
+):
+V(_V),
+F(_F),
+TT(_TT),
+TTi(_TTi),
+PD1(_PD1),
+PD2(_PD2),
+HandleS_Index(_HandleS_Index),
+Handle_Singular(_Handle_Singular),
+Handle_SystemInfo(_Handle_SystemInfo)
+{
+  UV        = Eigen::MatrixXd(V.rows(),2);
+  WUV       = Eigen::MatrixXd(F.rows(),6);
+  igl::doublearea(V,F,doublearea);
+  igl::per_face_normals(V,F,N);
+  igl::vf(V,F,VF,VFi);
+}
+
+
+///START SYSTEM ACCESS METHODS
+///add an entry to the LHS
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::AddValA(int Xindex,
+                                                     int Yindex,
+                                                     double val)
+{
+  int size=(int)S.nrows();
+  assert(0 <= Xindex && Xindex < size);
+  assert(0 <= Yindex && Yindex < size);
+  S.A().addEntryReal(Xindex,Yindex,val);
+}
+
+///add a complex entry to the LHS
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::AddComplexA(int VarXindex,
+                                                         int VarYindex,
+                                                         std::complex<double> val)
+{
+  int size=(int)S.nrows()/2;
+  assert(0 <= VarXindex && VarXindex < size);
+  assert(0 <= VarYindex && VarYindex < size);
+  S.A().addEntryCmplx(VarXindex,VarYindex,val);
+}
+
+///add a velue to the RHS
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::AddValB(int Xindex,
+                                                     double val)
+{
+  int size=(int)S.nrows();
+  assert(0 <= Xindex && Xindex < size);
+  S.b()[Xindex] += val;
+}
+
+///add the area term, scalefactor is used to sum up
+///and normalize on the overlap zones
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::AddAreaTerm(int index[3][3][2],double ScaleFactor)
+{
+  const double entry = 0.5*ScaleFactor;
+  double val[3][3]= {
+    {0,       entry, -entry},
+    {-entry,      0,  entry},
+    {entry,  -entry,      0}
+  };
+
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+    {
+      ///add for both u and v
+      int Xindex=index[i][j][0]*2;
+      int Yindex=index[i][j][1]*2;
+
+      AddValA(Xindex+1,Yindex,-val[i][j]);
+      AddValA(Xindex,Yindex+1,val[i][j]);
+    }
+}
+
+///set the diagonal of the matrix (which is zero at the beginning)
+///such that the sum of a row or a colums is zero
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::SetDiagonal(double val[3][3])
+{
+  for (int i=0;i<3;i++)
+  {
+    double sum=0;
+    for (int j=0;j<3;j++)
+      sum+=val[i][j];
+    val[i][i]=-sum;
+  }
+}
+
+///given a vector of scalar values and
+///a vector of indexes add such values
+///as specified by the indexes
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::AddRHS(double b[6],
+                                                    int index[3])
+{
+  for (int i=0;i<3;i++)
+  {
+    double valU=b[i*2];
+    double valV=b[(i*2)+1];
+    AddValB((index[i]*2),valU);
+    AddValB((index[i]*2)+1,valV);
+  }
+}
+
+///add a 3x3 block matrix to the system matrix...
+///indexes are specified in the 3x3 matrix of x,y pairs
+///indexes must be multiplied by 2 cause u and v
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::Add33Block(double val[3][3], int index[3][3][2])
+{
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+    {
+      ///add for both u and v
+      int Xindex=index[i][j][0]*2;
+      int Yindex=index[i][j][1]*2;
+      assert((unsigned)Xindex<(n_vert_vars*2));
+      assert((unsigned)Yindex<(n_vert_vars*2));
+      AddValA(Xindex,Yindex,val[i][j]);
+      AddValA(Xindex+1,Yindex+1,val[i][j]);
+    }
+}
+
+///add a 3x3 block matrix to the system matrix...
+///indexes are specified in the 3x3 matrix of x,y pairs
+///indexes must be multiplied by 2 cause u and v
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::Add44Block(double val[4][4],int index[4][4][2])
+{
+  for (int i=0;i<4;i++)
+    for (int j=0;j<4;j++)
+    {
+      ///add for both u and v
+      int Xindex=index[i][j][0]*2;
+      int Yindex=index[i][j][1]*2;
+      assert((unsigned)Xindex<(n_vert_vars*2));
+      assert((unsigned)Yindex<(n_vert_vars*2));
+      AddValA(Xindex,Yindex,val[i][j]);
+      AddValA(Xindex+1,Yindex+1,val[i][j]);
+    }
+}
+///END SYSTEM ACCESS METHODS
+
+///START COMMON MATH FUNCTIONS
+///return the complex encoding the rotation
+///for a given missmatch interval
+template <typename DerivedV, typename DerivedF>
+std::complex<double> igl::PoissonSolver<DerivedV, DerivedF>::GetRotationComplex(int interval)
+{
+  assert((interval>=0)&&(interval<4));
+
+  switch(interval)
+  {
+    case 0:return std::complex<double>(1,0);
+    case 1:return std::complex<double>(0,1);
+    case 2:return std::complex<double>(-1,0);
+    default:return std::complex<double>(0,-1);
+  }
+}
+
+///END COMMON MATH FUNCTIONS
+
+
+///START ENERGY MINIMIZATION PART
+///initialize the LHS for a given face
+///for minimization of Dirichlet's energy
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::perElementLHS(int f,
+                                                           double val[3][3],
+                                                           int index[3][3][2])
+{
+  ///initialize to zero
+  for (int x=0;x<3;x++)
+    for (int y=0;y<3;y++)
+      val[x][y]=0;
+
+  ///get the vertices
+  int v[3];
+  v[0] = F(f,0);
+  v[1] = F(f,1);
+  v[2] = F(f,2);
+
+  ///get the indexes of vertex instance (to consider cuts)
+  ///for the current face
+  int Vindexes[3];
+  Vindexes[0]=HandleS_Index(f,0);
+  Vindexes[1]=HandleS_Index(f,1);
+  Vindexes[2]=HandleS_Index(f,2);
+
+  ///initialize the indexes for the block
+  for (int x=0;x<3;x++)
+    for (int y=0;y<3;y++)
+    {
+      index[x][y][0]=Vindexes[x];
+      index[x][y][1]=Vindexes[y];
+    }
+
+  ///initialize edges
+  Eigen::Matrix<typename DerivedV::Scalar, 3, 1> e[3];
+  for (int k=0;k<3;k++)
+    e[k] = V.row(v[(k+2)%3]) - V.row(v[(k+1)%3]);
+
+  ///then consider area but also considering scale factor dur to overlaps
+
+  double areaT = doublearea(f)/2.0;
+
+  for (int x=0;x<3;x++)
+    for (int y=0;y<3;y++)
+      if (x!=y)
+      {
+        double num =  (e[x].dot(e[y]));
+        val[x][y]  =  num/(4.0*areaT);
+        val[x][y]  *= Handle_Stiffness[f];//f->stiffening;
+      }
+
+  ///set the matrix as diagonal
+  SetDiagonal(val);
+}
+
+///initialize the RHS for a given face
+///for minimization of Dirichlet's energy
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::perElementRHS(int f,
+                                                           double b[6],
+                                                           double vector_field_scale)
+{
+
+  /// then set the rhs
+  Eigen::Matrix<typename DerivedV::Scalar, 3, 1> scaled_Kreal;
+  Eigen::Matrix<typename DerivedV::Scalar, 3, 1> scaled_Kimag;
+  Eigen::Matrix<typename DerivedV::Scalar, 3, 1> fNorm = N.row(f);
+  Eigen::Matrix<typename DerivedV::Scalar, 3, 1> p[3];
+  p[0] = V.row(F(f,0));
+  p[1] = V.row(F(f,1));
+  p[2] = V.row(F(f,2));
+
+  Eigen::Matrix<typename DerivedV::Scalar, 3, 1> neg_t[3];
+  neg_t[0] = fNorm.cross(p[2] - p[1]);
+  neg_t[1] = fNorm.cross(p[0] - p[2]);
+  neg_t[2] = fNorm.cross(p[1] - p[0]);
+
+  Eigen::Matrix<typename DerivedV::Scalar, 3, 1> K1,K2;
+  K1 = PD1.row(f);
+  K2 = PD2.row(f);
+
+  scaled_Kreal = K1*(vector_field_scale)/2;
+  scaled_Kimag = K2*(vector_field_scale)/2;
+
+  double stiff_val = Handle_Stiffness[f];
+
+  b[0] = scaled_Kreal.dot(neg_t[0]) * stiff_val;
+  b[1] = scaled_Kimag.dot(neg_t[0]) * stiff_val;
+  b[2] = scaled_Kreal.dot(neg_t[1]) * stiff_val;
+  b[3] = scaled_Kimag.dot(neg_t[1]) * stiff_val;
+  b[4] = scaled_Kreal.dot(neg_t[2]) * stiff_val;
+  b[5] = scaled_Kimag.dot(neg_t[2]) * stiff_val;
+
+  //    if (f == 0)
+  //    {
+  //      cerr << "DEBUG!!!" << endl;
+  //
+  //
+  //      for (unsigned z = 0; z<6; ++z)
+  //        cerr << b[z] << " ";
+  //      cerr << endl;
+  //
+  //      scaled_Kreal = K1*(vector_field_scale)/2;
+  //      scaled_Kimag = -K2*(vector_field_scale)/2;
+  //
+  //      double stiff_val = Handle_Stiffness[f];
+  //
+  //      b[0] = scaled_Kreal.dot(neg_t[0]) * stiff_val;
+  //      b[1] = scaled_Kimag.dot(neg_t[0]) * stiff_val;
+  //      b[2] = scaled_Kreal.dot(neg_t[1]) * stiff_val;
+  //      b[3] = scaled_Kimag.dot(neg_t[1]) * stiff_val;
+  //      b[4] = scaled_Kreal.dot(neg_t[2]) * stiff_val;
+  //      b[5] = scaled_Kimag.dot(neg_t[2]) * stiff_val;
+  //
+  //      for (unsigned z = 0; z<6; ++z)
+  //        cerr << b[z] << " ";
+  //      cerr << endl;
+  //
+  //    }
+
+}
+
+///evaluate the LHS and RHS for a single face
+///for minimization of Dirichlet's energy
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::PerElementSystemReal(int f,
+                                                                  double val[3][3],
+                                                                  int index[3][3][2],
+                                                                  double b[6],
+                                                                  double vector_field_scale)
+{
+  perElementLHS(f,val,index);
+  perElementRHS(f,b,vector_field_scale);
+}
+///END ENERGY MINIMIZATION PART
+
+///START FIXING VERTICES
+///set a given vertex as fixed
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::AddFixedVertex(int v)
+{
+  n_fixed_vars++;
+  Hard_constraints.push_back(v);
+}
+
+///find vertex to fix in case we're using
+///a vector field NB: multiple components not handled
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::FindFixedVertField()
+{
+  Hard_constraints.clear();
+
+  n_fixed_vars=0;
+  ///fix the first singularity
+  for (unsigned int v=0;v<V.rows();v++)
+  {
+    if (Handle_Singular(v))
+    {
+      AddFixedVertex(v);
+      UV.row(v) << 0,0;
+      return;
+    }
+  }
+
+  ///if anything fixed fix the first
+  AddFixedVertex(0); // TODO HERE IT ISSSSSS
+  UV.row(0) << 0,0;
+  std::cerr << "No vertices to fix, I am fixing the first vertex to the origin!" << std::endl;
+}
+
+///find hard constraint depending if using or not
+///a vector field
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::FindFixedVert()
+{
+  Hard_constraints.clear();
+  FindFixedVertField();
+}
+
+template <typename DerivedV, typename DerivedF>
+int igl::PoissonSolver<DerivedV, DerivedF>::GetFirstVertexIndex(int v)
+{
+  return HandleS_Index(VF[v][0],VFi[v][0]);
+}
+
+///fix the vertices which are flagged as fixed
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::FixBlockedVertex()
+{
+  int offset_row = n_vert_vars*2 + num_cut_constraint*2;
+
+  unsigned int constr_num = 0;
+  for (unsigned int i=0;i<Hard_constraints.size();i++)
+  {
+    int v = Hard_constraints[i];
+
+    ///get first index of the vertex that must blocked
+    //int index=v->vertex_index[0];
+    int index = GetFirstVertexIndex(v);
+
+    ///multiply times 2 because of uv
+    int indexvert = index*2;
+
+    ///find the first free row to add the constraint
+    int indexRow = (offset_row+constr_num*2);
+    int indexCol = indexRow;
+
+    ///add fixing constraint LHS
+    AddValA(indexRow,indexvert,1);
+    AddValA(indexRow+1,indexvert+1,1);
+
+    ///add fixing constraint RHS
+    AddValB(indexCol,  UV(v,0));
+    AddValB(indexCol+1,UV(v,1));
+
+    constr_num++;
+  }
+  assert(constr_num==n_fixed_vars);
+}
+///END FIXING VERTICES
+
+///HANDLING SINGULARITY
+//set the singularity round to integer location
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::AddSingularityRound()
+{
+  for (unsigned int v=0;v<V.rows();v++)
+  {
+    if (Handle_Singular(v))
+    {
+      int index0=GetFirstVertexIndex(v);
+      ids_to_round.push_back( index0*2   );
+      ids_to_round.push_back((index0*2)+1);
+    }
+  }
+}
+
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::AddToRoundVertices(std::vector<int> ids)
+{
+  for (int i = 0; i < ids.size(); ++i)
+  {
+    if (ids[i] < 0 || ids[i] >= V.rows())
+      std::cerr << "WARNING: Ignored round vertex constraint, vertex " << ids[i] << " does not exist in the mesh." << std::endl;
+    int index0 = GetFirstVertexIndex(ids[i]);
+    ids_to_round.push_back( index0*2   );
+    ids_to_round.push_back((index0*2)+1);
+  }
+}
+
+///START GENERIC SYSTEM FUNCTIONS
+//build the laplacian matrix cyclyng over all rangemaps
+//and over all faces
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::BuildLaplacianMatrix(double vfscale)
+{
+  ///then for each face
+  for (unsigned int f=0;f<F.rows();f++)
+  {
+
+    int var_idx[3]; //vertex variable indices
+
+    for(int k = 0; k < 3; ++k)
+      var_idx[k] = HandleS_Index(f,k);
+
+    ///block of variables
+    double val[3][3];
+    ///block of vertex indexes
+    int index[3][3][2];
+    ///righe hand side
+    double b[6];
+    ///compute the system for the given face
+    PerElementSystemReal(f, val,index, b, vfscale);
+
+    //Add the element to the matrix
+    Add33Block(val,index);
+
+    ///add right hand side
+    AddRHS(b,var_idx);
+  }
+}
+
+///find different sized of the system
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::FindSizes()
+{
+  ///find the vertex that need to be fixed
+  FindFixedVert();
+
+  ///REAL PART
+  n_vert_vars = Handle_SystemInfo.num_vert_variables;
+
+  ///INTEGER PART
+  ///the total number of integer variables
+  n_integer_vars = Handle_SystemInfo.num_integer_cuts;
+
+  ///CONSTRAINT PART
+  num_cut_constraint = Handle_SystemInfo.EdgeSeamInfo.size()*2;
+
+  num_constraint_equations = num_cut_constraint*2 + n_fixed_vars*2 + num_userdefined_constraint;
+
+  ///total variable of the system
+  num_total_vars = n_vert_vars*2+n_integer_vars*2;
+
+  ///initialize matrix size
+
+  system_size = num_total_vars + num_constraint_equations;
+
+  if (DEBUGPRINT)     printf("\n*** SYSTEM VARIABLES *** \n");
+  if (DEBUGPRINT)     printf("* NUM REAL VERTEX VARIABLES %d \n",n_vert_vars);
+
+  if (DEBUGPRINT)     printf("\n*** SINGULARITY *** \n ");
+  if (DEBUGPRINT)     printf("* NUM SINGULARITY %d\n",(int)ids_to_round.size()/2);
+
+  if (DEBUGPRINT)     printf("\n*** INTEGER VARIABLES *** \n");
+  if (DEBUGPRINT)     printf("* NUM INTEGER VARIABLES %d \n",(int)n_integer_vars);
+
+  if (DEBUGPRINT)     printf("\n*** CONSTRAINTS *** \n ");
+  if (DEBUGPRINT)     printf("* NUM FIXED CONSTRAINTS %d\n",n_fixed_vars);
+  if (DEBUGPRINT)     printf("* NUM CUTS CONSTRAINTS %d\n",num_cut_constraint);
+  if (DEBUGPRINT)     printf("* NUM USER DEFINED CONSTRAINTS %d\n",num_userdefined_constraint);
+
+  if (DEBUGPRINT)     printf("\n*** TOTAL SIZE *** \n");
+  if (DEBUGPRINT)     printf("* TOTAL VARIABLE SIZE (WITH INTEGER TRASL) %d \n",num_total_vars);
+  if (DEBUGPRINT)     printf("* TOTAL CONSTRAINTS %d \n",num_constraint_equations);
+  if (DEBUGPRINT)     printf("* MATRIX SIZE  %d \n",system_size);
+}
+
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::AllocateSystem()
+{
+  S.initialize(system_size, system_size);
+  printf("\n INITIALIZED SPARSE MATRIX OF %d x %d \n",system_size, system_size);
+}
+
+///intitialize the whole matrix
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::InitMatrix()
+{
+  FindSizes();
+  AllocateSystem();
+}
+
+///map back coordinates after that
+///the system has been solved
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::MapCoords()
+{
+  ///map coords to faces
+  for (unsigned int f=0;f<F.rows();f++)
+  {
+
+    for (int k=0;k<3;k++)
+    {
+      //get the index of the variable in the system
+      int indexUV = HandleS_Index(f,k);
+      ///then get U and V coords
+      double U=X[indexUV*2];
+      double V=X[indexUV*2+1];
+
+      WUV(f,k*2 + 0) = U;
+      WUV(f,k*2 + 1) = V;
+    }
+  }
+
+#if 0
+  ///initialize the vector of integer variables to return their values
+  Handle_SystemInfo.IntegerValues.resize(n_integer_vars*2);
+  int baseIndex = (n_vert_vars)*2;
+  int endIndex  = baseIndex+n_integer_vars*2;
+  int index     = 0;
+  for (int i=baseIndex; i<endIndex; i++)
+  {
+    ///assert that the value is an integer value
+    double value=X[i];
+    double diff = value-(int)floor(value+0.5);
+    assert(diff<0.00000001);
+    Handle_SystemInfo.IntegerValues[index] = value;
+    index++;
+  }
+#endif
+}
+
+///END GENERIC SYSTEM FUNCTIONS
+
+///set the constraints for the inter-range cuts
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::BuildSeamConstraintsExplicitTranslation()
+{
+  ///add constraint(s) for every seam edge (not halfedge)
+  int offset_row = n_vert_vars;
+  ///current constraint row
+  int constr_row = offset_row;
+  ///current constraint
+  unsigned int constr_num = 0;
+
+  for (unsigned int i=0; i<num_cut_constraint/2; i++)
+  {
+    unsigned char interval = Handle_SystemInfo.EdgeSeamInfo[i].MMatch;
+    if (interval==1)
+      interval=3;
+    else
+      if(interval==3)
+        interval=1;
+
+    int p0  = Handle_SystemInfo.EdgeSeamInfo[i].v0;
+    int p1  = Handle_SystemInfo.EdgeSeamInfo[i].v1;
+    int p0p = Handle_SystemInfo.EdgeSeamInfo[i].v0p;
+    int p1p = Handle_SystemInfo.EdgeSeamInfo[i].v1p;
+
+    std::complex<double> rot = GetRotationComplex(interval);
+
+    ///get the integer variable
+    int integerVar = offset_row+Handle_SystemInfo.EdgeSeamInfo[i].integerVar;
+
+    if (integer_rounding)
+    {
+      ids_to_round.push_back(integerVar*2);
+      ids_to_round.push_back(integerVar*2+1);
+    }
+
+    AddComplexA(constr_row, p0 ,  rot);
+    AddComplexA(constr_row, p0p,   -1);
+    ///then translation...considering the rotation
+    ///due to substitution
+    AddComplexA(constr_row, integerVar, 1);
+
+    AddValB(2*constr_row  ,0);
+    AddValB(2*constr_row+1,0);
+    constr_row +=1;
+    constr_num++;
+
+    AddComplexA(constr_row, p1,  rot);
+    AddComplexA(constr_row, p1p, -1);
+
+    ///other translation
+    AddComplexA(constr_row, integerVar  , 1);
+
+    AddValB(2*constr_row,0);
+    AddValB(2*constr_row+1,0);
+
+    constr_row +=1;
+    constr_num++;
+  }
+}
+
+///set the constraints for the inter-range cuts
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::BuildUserDefinedConstraints()
+{
+  /// the user defined constraints are at the end
+  int offset_row = n_vert_vars*2 + num_cut_constraint*2 + n_fixed_vars*2;
+
+  ///current constraint row
+  int constr_row = offset_row;
+
+  assert(num_userdefined_constraint == userdefined_constraints.size());
+
+  for (unsigned int i=0; i<num_userdefined_constraint; i++)
+  {
+    for (unsigned int j=0; j<userdefined_constraints[i].size()-1; ++j)
+    {
+      AddValA(constr_row, j ,  userdefined_constraints[i][j]);
+    }
+
+    AddValB(constr_row,userdefined_constraints[i][userdefined_constraints[i].size()-1]);
+
+    constr_row +=1;
+  }
+}
+
+///call of the mixed integer solver
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::MixedIntegerSolve(double cone_grid_res,
+                                                               bool direct_round,
+                                                               int localIter)
+{
+  X = std::vector<double>((n_vert_vars+n_integer_vars)*2);
+
+  ///variables part
+  int ScalarSize = n_vert_vars*2;
+  int SizeMatrix = (n_vert_vars+n_integer_vars)*2;
+
+  if (DEBUGPRINT)
+    printf("\n ALLOCATED X \n");
+
+  ///matrix A
+  gmm::col_matrix< gmm::wsvector< double > > A(SizeMatrix,SizeMatrix); // lhs matrix variables +
+
+  ///constraints part
+  int CsizeX = num_constraint_equations;
+  int CsizeY = SizeMatrix+1;
+  gmm::row_matrix< gmm::wsvector< double > > C(CsizeX,CsizeY); // constraints
+
+  if (DEBUGPRINT)
+    printf("\n ALLOCATED QMM STRUCTURES \n");
+
+  std::vector<double> rhs(SizeMatrix,0);  // rhs
+
+  if (DEBUGPRINT)
+    printf("\n ALLOCATED RHS STRUCTURES \n");
+
+  //// copy LHS
+  for(int i = 0; i < (int)S.A().nentries(); ++i)
+  {
+    int row  = S.A().rowind()[i];
+    int col  = S.A().colind()[i];
+    int size =(int)S.nrows();
+    assert(0 <= row && row < size);
+    assert(0 <= col && col < size);
+
+    // it's either part of the matrix
+    if (row < ScalarSize)
+    {
+      A(row, col) += S.A().vals()[i];
+    }
+    // or it's a part of the constraint
+    else
+    {
+      assert ((unsigned int)row < (n_vert_vars+num_constraint_equations)*2);
+      int r = row - ScalarSize;
+      assert(r   < CsizeX);
+      assert(col < CsizeY);
+      C(r  , col  ) +=  S.A().vals()[i];
+    }
+  }
+
+  if (DEBUGPRINT)
+    printf("\n SET %d INTEGER VALUES \n",n_integer_vars);
+
+  ///add penalization term for integer variables
+  double penalization = 0.000001;
+  int offline_index   = ScalarSize;
+  for(unsigned int i = 0; i < (n_integer_vars)*2; ++i)
+  {
+    int index=offline_index+i;
+    A(index,index)=penalization;
+  }
+
+  if (DEBUGPRINT)
+    printf("\n SET RHS \n");
+
+  // copy RHS
+  for(int i = 0; i < (int)ScalarSize; ++i)
+  {
+    rhs[i] = S.getRHSReal(i) * cone_grid_res;
+  }
+
+  // copy constraint RHS
+  if (DEBUGPRINT)
+    printf("\n SET %d CONSTRAINTS \n",num_constraint_equations);
+
+  for(unsigned int i = 0; i < num_constraint_equations; ++i)
+  {
+    C(i, SizeMatrix) = -S.getRHSReal(ScalarSize + i) * cone_grid_res;
+  }
+
+  ///copy values back into S
+  COMISO::ConstrainedSolver solver;
+
+  solver.misolver().set_local_iters(localIter);
+  solver.misolver().set_direct_rounding(direct_round);
+
+  std::sort(ids_to_round.begin(),ids_to_round.end());
+  std::vector<int>::iterator new_end=std::unique(ids_to_round.begin(),ids_to_round.end());
+  int dist=distance(ids_to_round.begin(),new_end);
+  ids_to_round.resize(dist);
+
+  solver.solve( C, A, X, rhs, ids_to_round, 0.0, false, false);
+}
+
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::clearUserConstraint()
+{
+  num_userdefined_constraint = 0;
+  userdefined_constraints.clear();
+}
+
+template <typename DerivedV, typename DerivedF>
+void igl::PoissonSolver<DerivedV, DerivedF>::addSharpEdgeConstraint(int fid, int vid)
+{
+  // prepare constraint
+  std::vector<int> c(Handle_SystemInfo.num_vert_variables*2 + 1);
+
+  for (int i = 0; i < c.size(); ++i)
+  {
+    c[i] = 0;
+  }
+
+  int v1 = F(fid,vid);
+  int v2 = F(fid,(vid+1)%3);
+
+  Eigen::Matrix<typename DerivedV::Scalar, 3, 1> e = V.row(v2) - V.row(v1);
+
+  int v1i = GetFirstVertexIndex(v1);
+  int v2i = GetFirstVertexIndex(v2);
+
+  double d1 = fabs(e.dot(PD1.row(fid)));
+  double d2 = fabs(e.dot(PD2.row(fid)));
+
+  int offset = 0;
+
+  if (d1>d2)
+    offset = 1;
+
+  ids_to_round.push_back((v1i * 2) + offset);
+  ids_to_round.push_back((v2i * 2) + offset);
+
+  // add constraint
+  c[(v1i * 2) + offset] =  1;
+  c[(v2i * 2) + offset] = -1;
+
+  // add to the user-defined constraints
+  num_userdefined_constraint++;
+  userdefined_constraints.push_back(c);
+
+}
+
+
+
+template <typename DerivedV, typename DerivedF, typename DerivedU>
+igl::MIQ<DerivedV, DerivedF, DerivedU>::MIQ(const Eigen::PlainObjectBase<DerivedV> &V_,
+                                            const Eigen::PlainObjectBase<DerivedF> &F_,
+                                            const Eigen::PlainObjectBase<DerivedV> &PD1_combed,
+                                            const Eigen::PlainObjectBase<DerivedV> &PD2_combed,
+                                            const Eigen::PlainObjectBase<DerivedV> &BIS1_combed,
+                                            const Eigen::PlainObjectBase<DerivedV> &BIS2_combed,
+                                            const Eigen::Matrix<int, Eigen::Dynamic, 3> &Handle_MMatch,
+                                            const Eigen::Matrix<int, Eigen::Dynamic, 1> &Handle_Singular,
+                                            const Eigen::Matrix<int, Eigen::Dynamic, 1> &Handle_SingularDegree,
+                                            const Eigen::Matrix<int, Eigen::Dynamic, 3> &Handle_Seams,
+                                            Eigen::PlainObjectBase<DerivedU> &UV,
+                                            Eigen::PlainObjectBase<DerivedF> &FUV,
+                                            double GradientSize,
+                                            double Stiffness,
+                                            bool DirectRound,
+                                            int iter,
+                                            int localIter,
+                                            bool DoRound,
+                                            std::vector<int> roundVertices,
+                                            std::vector<std::vector<int> > hardFeatures):
+V(V_),
+F(F_)
+{
+  igl::local_basis(V,F,B1,B2,B3);
+  igl::tt(V,F,TT,TTi);
+
+  // Prepare indexing for the linear system
+  VertexIndexing<DerivedV, DerivedF> VInd(V, F, TT, TTi, BIS1_combed, BIS2_combed, Handle_MMatch, Handle_Singular, Handle_SingularDegree, Handle_Seams);
+
+  VInd.InitMapping();
+  VInd.InitFaceIntegerVal();
+  VInd.InitSeamInfo();
+
+  Eigen::PlainObjectBase<DerivedV> PD1_combed_for_poisson, PD2_combed_for_poisson;
+  // Rotate by 90 degrees CCW
+  PD1_combed_for_poisson.setZero(BIS1_combed.rows(),3);
+  PD2_combed_for_poisson.setZero(BIS2_combed.rows(),3);
+  for (unsigned i=0; i<PD1_combed.rows();++i)
+  {
+    double n1 = PD1_combed.row(i).norm();
+    double n2 = PD2_combed.row(i).norm();
+
+    double a1 = atan2(B2.row(i).dot(PD1_combed.row(i)),B1.row(i).dot(PD1_combed.row(i)));
+    double a2 = atan2(B2.row(i).dot(PD2_combed.row(i)),B1.row(i).dot(PD2_combed.row(i)));
+
+    a1 += M_PI/2;
+    a2 += M_PI/2;
+
+
+    PD1_combed_for_poisson.row(i) = cos(a1) * B1.row(i) + sin(a1) * B2.row(i);
+    PD2_combed_for_poisson.row(i) = cos(a2) * B1.row(i) + sin(a2) * B2.row(i);
+
+    PD1_combed_for_poisson.row(i) = PD1_combed_for_poisson.row(i).normalized() * n1;
+    PD2_combed_for_poisson.row(i) = PD2_combed_for_poisson.row(i).normalized() * n2;
+  }
+
+
+  // Assemble the system and solve
+  PoissonSolver<DerivedV, DerivedF> PSolver(V,
+                                            F,
+                                            TT,
+                                            TTi,
+                                            PD1_combed_for_poisson,
+                                            PD2_combed_for_poisson,
+                                            VInd.HandleS_Index,
+                                            VInd.Handle_Singular,
+                                            VInd.Handle_SystemInfo);
+  Handle_Stiffness = Eigen::VectorXd::Constant(F.rows(),1);
+
+
+  if (iter > 0) // do stiffening
+  {
+    for (int i=0;i<iter;i++)
+    {
+      PSolver.SolvePoisson(Handle_Stiffness, GradientSize,1.f,DirectRound,localIter,DoRound,roundVertices,hardFeatures);
+      int nflips=NumFlips(PSolver.WUV);
+      bool folded = updateStiffeningJacobianDistorsion(GradientSize,PSolver.WUV);
+      printf("ITERATION %d FLIPS %d \n",i,nflips);
+      if (!folded)break;
+    }
+  }
+  else
+  {
+    PSolver.SolvePoisson(Handle_Stiffness,GradientSize,1.f,DirectRound,localIter,DoRound,roundVertices,hardFeatures);
+  }
+
+  int nflips=NumFlips(PSolver.WUV);
+  printf("**** END OPTIMIZING #FLIPS %d  ****\n",nflips);
+
+  fflush(stdout);
+  WUV = PSolver.WUV;
+
+}
+
+template <typename DerivedV, typename DerivedF, typename DerivedU>
+void igl::MIQ<DerivedV, DerivedF, DerivedU>::extractUV(Eigen::PlainObjectBase<DerivedU> &UV_out,
+                                                       Eigen::PlainObjectBase<DerivedF> &FUV_out)
+{
+  //      int f = F.rows();
+  int f = WUV.rows();
+
+  unsigned vtfaceid[f*3];
+  std::vector<double> vtu;
+  std::vector<double> vtv;
+
+  std::vector<std::vector<double> > listUV;
+  unsigned counter = 0;
+
+  for (unsigned i=0; i<f; ++i)
+  {
+    for (unsigned j=0; j<3; ++j)
+    {
+      std::vector<double> t(3);
+      t[0] = WUV(i,j*2 + 0);
+      t[1] = WUV(i,j*2 + 1);
+      t[2] = counter++;
+      listUV.push_back(t);
+    }
+  }
+  std::sort(listUV.begin(),listUV.end());
+
+  counter = 0;
+  unsigned k = 0;
+  while (k < f*3)
+  {
+    double u = listUV[k][0];
+    double v = listUV[k][1];
+    unsigned id = round(listUV[k][2]);
+
+    vtfaceid[id] = counter;
+    vtu.push_back(u);
+    vtv.push_back(v);
+
+    unsigned j=1;
+    while(k+j < f*3 && u == listUV[k+j][0] && v == listUV[k+j][1])
+    {
+      unsigned tid = round(listUV[k+j][2]);
+      vtfaceid[tid] = counter;
+      ++j;
+    }
+    k = k+j;
+    counter++;
+  }
+
+  UV_out.resize(vtu.size(),2);
+  for (unsigned i=0; i<vtu.size(); ++i)
+  {
+    UV_out(i,0) = vtu[i];
+    UV_out(i,1) = vtv[i];
+  }
+
+  FUV_out.resize(f,3);
+
+  unsigned vcounter = 0;
+  for (unsigned i=0; i<f; ++i)
+  {
+    FUV_out(i,0)  = vtfaceid[vcounter++];
+    FUV_out(i,1)  = vtfaceid[vcounter++];
+    FUV_out(i,2)  = vtfaceid[vcounter++];
+  }
+
+}
+
+template <typename DerivedV, typename DerivedF, typename DerivedU>
+int igl::MIQ<DerivedV, DerivedF, DerivedU>::NumFlips(const Eigen::MatrixXd& WUV)
+{
+  int numFl=0;
+  for (unsigned int i=0;i<F.rows();i++)
+  {
+    if (IsFlipped(i, WUV))
+      numFl++;
+  }
+  return numFl;
+}
+
+template <typename DerivedV, typename DerivedF, typename DerivedU>
+double igl::MIQ<DerivedV, DerivedF, DerivedU>::Distortion(int f, double h, const Eigen::MatrixXd& WUV)
+{
+  assert(h > 0);
+
+  Eigen::Vector2d uv0,uv1,uv2;
+
+  uv0 << WUV(f,0), WUV(f,1);
+  uv1 << WUV(f,2), WUV(f,3);
+  uv2 << WUV(f,4), WUV(f,5);
+
+  Eigen::Matrix<typename DerivedV::Scalar, 3, 1> p0 = V.row(F(f,0));
+  Eigen::Matrix<typename DerivedV::Scalar, 3, 1> p1 = V.row(F(f,1));
+  Eigen::Matrix<typename DerivedV::Scalar, 3, 1> p2 = V.row(F(f,2));
+
+  Eigen::Matrix<typename DerivedV::Scalar, 3, 1> norm = (p1 - p0).cross(p2 - p0);
+  double area2 = norm.norm();
+  double area2_inv  = 1.0 / area2;
+  norm *= area2_inv;
+
+  if (area2 > 0)
+  {
+    // Singular values of the Jacobian
+    Eigen::Matrix<typename DerivedV::Scalar, 3, 1> neg_t0 = norm.cross(p2 - p1);
+    Eigen::Matrix<typename DerivedV::Scalar, 3, 1> neg_t1 = norm.cross(p0 - p2);
+    Eigen::Matrix<typename DerivedV::Scalar, 3, 1> neg_t2 = norm.cross(p1 - p0);
+
+    Eigen::Matrix<typename DerivedV::Scalar, 3, 1> diffu =  (neg_t0 * uv0(0) +neg_t1 *uv1(0) +  neg_t2 * uv2(0) )*area2_inv;
+    Eigen::Matrix<typename DerivedV::Scalar, 3, 1> diffv = (neg_t0 * uv0(1) + neg_t1*uv1(1) +  neg_t2*uv2(1) )*area2_inv;
+
+    // first fundamental form
+    double I00 = diffu.dot(diffu);  // guaranteed non-neg
+    double I01 = diffu.dot(diffv);  // I01 = I10
+    double I11 = diffv.dot(diffv);  // guaranteed non-neg
+
+    // eigenvalues of a 2x2 matrix
+    // [a00 a01]
+    // [a10 a11]
+    // 1/2 * [ (a00 + a11) +/- sqrt((a00 - a11)^2 + 4 a01 a10) ]
+    double trI = I00 + I11;                     // guaranteed non-neg
+    double diffDiag = I00 - I11;                // guaranteed non-neg
+    double sqrtDet = sqrt(std::max(0.0, diffDiag*diffDiag +
+                                   4 * I01 * I01)); // guaranteed non-neg
+    double sig1 = 0.5 * (trI + sqrtDet); // higher singular value
+    double sig2 = 0.5 * (trI - sqrtDet); // lower singular value
+
+    // Avoid sig2 < 0 due to numerical error
+    if (fabs(sig2) < 1.0e-8)
+      sig2 = 0;
+
+    assert(sig1 >= 0);
+    assert(sig2 >= 0);
+
+    if (sig2 < 0) {
+      printf("Distortion will be NaN! sig1^2 is negative (%lg)\n",
+             sig2);
+    }
+
+    // The singular values of the Jacobian are the sqrts of the
+    // eigenvalues of the first fundamental form.
+    sig1 = sqrt(sig1);
+    sig2 = sqrt(sig2);
+
+    // distortion
+    double tao = IsFlipped(f,WUV) ? -1 : 1;
+    double factor = tao / h;
+    double lam = fabs(factor * sig1 - 1) + fabs(factor * sig2 - 1);
+    return lam;
+  }
+  else {
+    return 10; // something "large"
+  }
+}
+
+////////////////////////////////////////////////////////////////////////////
+// Approximate the distortion laplacian using a uniform laplacian on
+//  the dual mesh:
+//      ___________
+//      \-1 / \-1 /
+//       \ / 3 \ /
+//        \-----/
+//         \-1 /
+//          \ /
+//
+//  @param[in]  f   facet on which to compute distortion laplacian
+//  @param[in]  h   scaling factor applied to cross field
+//  @return     distortion laplacian for f
+///////////////////////////////////////////////////////////////////////////
+template <typename DerivedV, typename DerivedF, typename DerivedU>
+double igl::MIQ<DerivedV, DerivedF, DerivedU>::LaplaceDistortion(const int f, double h, const Eigen::MatrixXd& WUV)
+{
+  double mydist = Distortion(f, h, WUV);
+  double lapl=0;
+  for (int i=0;i<3;i++)
+  {
+    if (TT(f,i) != -1)
+      lapl += (mydist - Distortion(TT(f,i), h, WUV));
+  }
+  return lapl;
+}
+
+template <typename DerivedV, typename DerivedF, typename DerivedU>
+bool igl::MIQ<DerivedV, DerivedF, DerivedU>::updateStiffeningJacobianDistorsion(double grad_size, const Eigen::MatrixXd& WUV)
+{
+  bool flipped = NumFlips(WUV)>0;
+
+  if (!flipped)
+    return false;
+
+  double maxL=0;
+  double maxD=0;
+
+  if (flipped)
+  {
+    const double c = 1.0;
+    const double d = 5.0;
+
+    for (unsigned int i = 0; i < F.rows(); ++i)
+    {
+      double dist=Distortion(i,grad_size,WUV);
+      if (dist > maxD)
+        maxD=dist;
+
+      double absLap=fabs(LaplaceDistortion(i, grad_size,WUV));
+      if (absLap > maxL)
+        maxL = absLap;
+
+      double stiffDelta = std::min(c * absLap, d);
+
+      Handle_Stiffness[i]+=stiffDelta;
+    }
+  }
+  printf("Maximum Distorsion %4.4f \n",maxD);
+  printf("Maximum Laplacian %4.4f \n",maxL);
+  return flipped;
+}
+
+template <typename DerivedV, typename DerivedF, typename DerivedU>
+inline bool igl::MIQ<DerivedV, DerivedF, DerivedU>::IsFlipped(const Eigen::Vector2d &uv0,
+                                                              const Eigen::Vector2d &uv1,
+                                                              const Eigen::Vector2d &uv2)
+{
+  Eigen::Vector2d e0 = (uv1-uv0);
+  Eigen::Vector2d e1 = (uv2-uv0);
+
+  double Area = e0(0)*e1(1) - e0(1)*e1(0);
+  return (Area<=0);
+}
+
+template <typename DerivedV, typename DerivedF, typename DerivedU>
+inline bool igl::MIQ<DerivedV, DerivedF, DerivedU>::IsFlipped(const int i, const Eigen::MatrixXd& WUV)
+{
+  Eigen::Vector2d uv0,uv1,uv2;
+  uv0 << WUV(i,0), WUV(i,1);
+  uv1 << WUV(i,2), WUV(i,3);
+  uv2 << WUV(i,4), WUV(i,5);
+
+  return (IsFlipped(uv0,uv1,uv2));
+}
+
+
+
+
+template <typename DerivedV, typename DerivedF, typename DerivedU>
+IGL_INLINE void igl::mixed_integer_quadrangulate(const Eigen::PlainObjectBase<DerivedV> &V,
+                                                 const Eigen::PlainObjectBase<DerivedF> &F,
+                                                 const Eigen::PlainObjectBase<DerivedV> &PD1_combed,
+                                                 const Eigen::PlainObjectBase<DerivedV> &PD2_combed,
+                                                 const Eigen::PlainObjectBase<DerivedV> &BIS1_combed,
+                                                 const Eigen::PlainObjectBase<DerivedV> &BIS2_combed,
+                                                 const Eigen::Matrix<int, Eigen::Dynamic, 3> &Handle_MMatch,
+                                                 const Eigen::Matrix<int, Eigen::Dynamic, 1> &Handle_Singular,
+                                                 const Eigen::Matrix<int, Eigen::Dynamic, 1> &Handle_SingularDegree,
+                                                 const Eigen::Matrix<int, Eigen::Dynamic, 3> &Handle_Seams,
+                                                 Eigen::PlainObjectBase<DerivedU> &UV,
+                                                 Eigen::PlainObjectBase<DerivedF> &FUV,
+                                                 double GradientSize,
+                                                 double Stiffness,
+                                                 bool DirectRound,
+                                                 int iter,
+                                                 int localIter,
+                                                 bool DoRound,
+                                                 std::vector<int> roundVertices,
+                                                 std::vector<std::vector<int> > hardFeatures)
+{
+  GradientSize = GradientSize/(V.colwise().maxCoeff()-V.colwise().minCoeff()).norm();
+
+  igl::MIQ<DerivedV, DerivedF, DerivedU> miq(V,
+                                             F,
+                                             PD1_combed,
+                                             PD2_combed,
+                                             BIS1_combed,
+                                             BIS2_combed,
+                                             Handle_MMatch,
+                                             Handle_Singular,
+                                             Handle_SingularDegree,
+                                             Handle_Seams,
+                                             UV,
+                                             FUV,
+                                             GradientSize,
+                                             Stiffness,
+                                             DirectRound,
+                                             iter,
+                                             localIter,
+                                             DoRound,
+                                             roundVertices,
+                                             hardFeatures);
+
+  miq.extractUV(UV,FUV);
+}
+
+template <typename DerivedV, typename DerivedF, typename DerivedU>
+IGL_INLINE void igl::mixed_integer_quadrangulate(const Eigen::PlainObjectBase<DerivedV> &V,
+                                                 const Eigen::PlainObjectBase<DerivedF> &F,
+                                                 const Eigen::PlainObjectBase<DerivedV> &PD1,
+                                                 const Eigen::PlainObjectBase<DerivedV> &PD2,
+                                                 Eigen::PlainObjectBase<DerivedU> &UV,
+                                                 Eigen::PlainObjectBase<DerivedF> &FUV,
+                                                 double GradientSize,
+                                                 double Stiffness,
+                                                 bool DirectRound,
+                                                 int iter,
+                                                 int localIter,
+                                                 bool DoRound,
+                                                 std::vector<int> roundVertices,
+                                                 std::vector<std::vector<int> > hardFeatures)
+{
+  Eigen::PlainObjectBase<DerivedV> BIS1, BIS2;
+  igl::compute_frame_field_bisectors(V, F, PD1, PD2, BIS1, BIS2);
+
+  Eigen::PlainObjectBase<DerivedV> BIS1_combed, BIS2_combed;
+  igl::comb_cross_field(V, F, BIS1, BIS2, BIS1_combed, BIS2_combed);
+
+  Eigen::Matrix<int, Eigen::Dynamic, 3> Handle_MMatch;
+  igl::cross_field_missmatch(V, F, BIS1_combed, BIS2_combed, true, Handle_MMatch);
+
+  Eigen::Matrix<int, Eigen::Dynamic, 1> isSingularity, singularityIndex;
+  igl::find_cross_field_singularities(V, F, Handle_MMatch, isSingularity, singularityIndex);
+
+  Eigen::Matrix<int, Eigen::Dynamic, 3> Handle_Seams;
+  igl::cut_mesh_from_singularities(V, F, Handle_MMatch, isSingularity, singularityIndex, Handle_Seams);
+
+  Eigen::PlainObjectBase<DerivedV> PD1_combed, PD2_combed;
+  igl::comb_frame_field(V, F, PD1, PD2, BIS1_combed, BIS2_combed, PD1_combed, PD2_combed);
+
+  igl::mixed_integer_quadrangulate(V,
+                                   F,
+                                   PD1_combed,
+                                   PD2_combed,
+                                   BIS1_combed,
+                                   BIS2_combed,
+                                   Handle_MMatch,
+                                   isSingularity,
+                                   singularityIndex,
+                                   Handle_Seams,
+                                   UV,
+                                   FUV,
+                                   GradientSize,
+                                   Stiffness,
+                                   DirectRound,
+                                   iter,
+                                   localIter,
+                                   DoRound);
+
+}

+ 63 - 0
include/igl/comiso/mixed_integer_quadrangulate.h

@@ -0,0 +1,63 @@
+#ifndef IGL_MIXED_INTEGER_QUADRANGULATE_H
+#define IGL_MIXED_INTEGER_QUADRANGULATE_H
+#include <igl/igl_inline.h>
+#include <Eigen/Core>
+#include <vector>
+
+namespace igl
+{
+  // Creates a quad mesh from a triangular mesh and a set of two directions
+  // per face, using the algorithm described in the paper
+  // "Mixed-Integer Quadrangulation" by D. Bommes, H. Zimmer, L. Kobbelt
+  // ACM SIGGRAPH 2009, Article No. 77 (http://dl.acm.org/citation.cfm?id=1531383)
+
+  // Inputs:
+  //   Vin        #V by 3 eigen Matrix of mesh vertex 3D positions
+  //   F          #F by 4 eigen Matrix of face (quad) indices
+  //   maxIter    maximum numbers of iterations
+  //   threshold  minimum allowed threshold for non-planarity
+  // Output:
+  //   Vout       #V by 3 eigen Matrix of planar mesh vertex 3D positions
+  //
+
+  template <typename DerivedV, typename DerivedF, typename DerivedU>
+  IGL_INLINE void mixed_integer_quadrangulate(const Eigen::PlainObjectBase<DerivedV> &V,
+                                              const Eigen::PlainObjectBase<DerivedF> &F,
+                                              const Eigen::PlainObjectBase<DerivedV> &PD1,
+                                              const Eigen::PlainObjectBase<DerivedV> &PD2,
+                                              Eigen::PlainObjectBase<DerivedU> &UV,
+                                              Eigen::PlainObjectBase<DerivedF> &FUV,
+                                              double GradientSize = 30.0,
+                                              double Stiffness = 5.0,
+                                              bool DirectRound = false,
+                                              int iter = 5,
+                                              int localIter = 5, bool DoRound = true,
+                                              std::vector<int> roundVertices = std::vector<int>(),
+                                              std::vector<std::vector<int> > hardFeatures = std::vector<std::vector<int> >());
+
+  template <typename DerivedV, typename DerivedF, typename DerivedU>
+  IGL_INLINE void mixed_integer_quadrangulate(const Eigen::PlainObjectBase<DerivedV> &V,
+                                              const Eigen::PlainObjectBase<DerivedF> &F,
+                                              const Eigen::PlainObjectBase<DerivedV> &PD1_combed,
+                                              const Eigen::PlainObjectBase<DerivedV> &PD2_combed,
+                                              const Eigen::PlainObjectBase<DerivedV> &BIS1_combed,
+                                              const Eigen::PlainObjectBase<DerivedV> &BIS2_combed,
+                                              const Eigen::Matrix<int, Eigen::Dynamic, 3> &Handle_MMatch,
+                                              const Eigen::Matrix<int, Eigen::Dynamic, 1> &Handle_Singular,
+                                              const Eigen::Matrix<int, Eigen::Dynamic, 1> &Handle_SingularDegree,
+                                              const Eigen::Matrix<int, Eigen::Dynamic, 3> &Handle_Seams,
+                                              Eigen::PlainObjectBase<DerivedU> &UV,
+                                              Eigen::PlainObjectBase<DerivedF> &FUV,
+                                              double GradientSize = 30.0,
+                                              double Stiffness = 5.0,
+                                              bool DirectRound = false,
+                                              int iter = 5,
+                                              int localIter = 5, bool DoRound = true,
+                                              std::vector<int> roundVertices = std::vector<int>(),
+                                              std::vector<std::vector<int> > hardFeatures = std::vector<std::vector<int> >());
+};
+#ifdef IGL_HEADER_ONLY
+#include "mixed_integer_quadrangulate.cpp"
+#endif
+
+#endif

+ 903 - 0
include/igl/comiso/nrosy.cpp

@@ -0,0 +1,903 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#include <igl/comiso/nrosy.h>
+#include <igl/tt.h>
+#include <igl/edgetopology.h>
+#include <igl/per_face_normals.h>
+
+#include <iostream>
+#include <fstream>
+
+#include <Eigen/Geometry>
+#include <Eigen/Sparse>
+#include <queue>
+
+#include <gmm/gmm.h>
+#include <CoMISo/Solver/ConstrainedSolver.hh>
+#include <CoMISo/Solver/MISolver.hh>
+#include <CoMISo/Solver/GMM_Tools.hh>
+namespace igl
+{
+class NRosyField
+{
+public:
+  // Init
+  IGL_INLINE NRosyField(const Eigen::MatrixXd& _V, const Eigen::MatrixXi& _F);
+
+  // Generate the N-rosy field
+  // N degree of the rosy field
+  // roundseparately: round the integer variables one at a time, slower but higher quality
+  IGL_INLINE void solve(const int N = 4);
+
+  // Set a hard constraint on fid
+  // fid: face id
+  // v: direction to fix (in 3d)
+  IGL_INLINE void setConstraintHard(const int fid, const Eigen::Vector3d& v);
+
+  // Set a soft constraint on fid
+  // fid: face id
+  // w: weight of the soft constraint, clipped between 0 and 1
+  // v: direction to fix (in 3d)
+  IGL_INLINE void setConstraintSoft(const int fid, const double w, const Eigen::Vector3d& v);
+
+  // Set the ratio between smoothness and soft constraints (0 -> smoothness only, 1 -> soft constr only)
+  IGL_INLINE void setSoftAlpha(double alpha);
+
+  // Reset constraints (at least one constraint must be present or solve will fail)
+  IGL_INLINE void resetConstraints();
+
+  // Return the current field
+  IGL_INLINE Eigen::MatrixXd getFieldPerFace();
+
+  // Return the current field (in Ahish's ffield format)
+  IGL_INLINE Eigen::MatrixXd getFFieldPerFace();
+
+  // Compute singularity indexes
+  IGL_INLINE void findCones(int N);
+
+  // Return the singularities
+  IGL_INLINE Eigen::VectorXd getSingularityIndexPerVertex();
+
+private:
+
+  // Compute angle differences between reference frames
+  IGL_INLINE void computek();
+
+  // Remove useless matchings
+  IGL_INLINE void reduceSpace();
+
+  // Prepare the system matrix
+  IGL_INLINE void prepareSystemMatrix(const int N);
+
+  // Solve without roundings
+  IGL_INLINE void solveNoRoundings();
+
+  // Solve with roundings using CoMIso
+  IGL_INLINE void solveRoundings();
+
+  // Round all p to 0 and fix
+  IGL_INLINE void roundAndFixToZero();
+
+  // Round all p and fix
+  IGL_INLINE void roundAndFix();
+
+  // Convert a vector in 3d to an angle wrt the local reference system
+  IGL_INLINE double convert3DtoLocal(unsigned fid, const Eigen::Vector3d& v);
+
+  // Convert an angle wrt the local reference system to a 3d vector
+  IGL_INLINE Eigen::Vector3d convertLocalto3D(unsigned fid, double a);
+
+  // Compute the per vertex angle defect
+  IGL_INLINE Eigen::VectorXd angleDefect();
+
+  // Temporary variable for the field
+  Eigen::VectorXd angles;
+
+  // Hard constraints
+  Eigen::VectorXd hard;
+  std::vector<bool> isHard;
+
+  // Soft constraints
+  Eigen::VectorXd soft;
+  Eigen::VectorXd wSoft;
+  double          softAlpha;
+
+  // Face Topology
+  Eigen::MatrixXi TT, TTi;
+
+  // Edge Topology
+  Eigen::MatrixXi EV, FE, EF;
+  std::vector<bool> isBorderEdge;
+
+  // Per Edge information
+  // Angle between two reference frames
+  Eigen::VectorXd k;
+
+  // Jumps
+  Eigen::VectorXi p;
+  std::vector<bool> pFixed;
+
+  // Mesh
+  Eigen::MatrixXd V;
+  Eigen::MatrixXi F;
+
+  // Normals per face
+  Eigen::MatrixXd N;
+
+  // Singularity index
+  Eigen::VectorXd singularityIndex;
+
+  // Reference frame per triangle
+  std::vector<Eigen::MatrixXd> TPs;
+
+  // System stuff
+  Eigen::SparseMatrix<double> A;
+  Eigen::VectorXd b;
+  Eigen::VectorXi tag_t;
+  Eigen::VectorXi tag_p;
+
+};
+
+} // NAMESPACE IGL
+
+igl::NRosyField::NRosyField(const Eigen::MatrixXd& _V, const Eigen::MatrixXi& _F)
+{
+  using namespace std;
+  using namespace Eigen;
+
+  V = _V;
+  F = _F;
+
+  assert(V.rows() > 0);
+  assert(F.rows() > 0);
+
+
+  // Generate topological relations
+  igl::tt(V,F,TT,TTi);
+  igl::edgetopology(V,F, EV, FE, EF);
+
+  // Flag border edges
+  isBorderEdge.resize(EV.rows());
+  for(unsigned i=0; i<EV.rows(); ++i)
+    isBorderEdge[i] = (EF(i,0) == -1) || ((EF(i,1) == -1));
+
+  // Generate normals per face
+  igl::per_face_normals(V, F, N);
+
+  // Generate reference frames
+  for(unsigned fid=0; fid<F.rows(); ++fid)
+  {
+    // First edge
+    Vector3d e1 = V.row(F(fid,1)) - V.row(F(fid,0));
+    e1.normalize();
+    Vector3d e2 = N.row(fid);
+    e2 = e2.cross(e1);
+    e2.normalize();
+
+    MatrixXd TP(2,3);
+    TP << e1.transpose(), e2.transpose();
+    TPs.push_back(TP);
+  }
+
+  // Alloc internal variables
+  angles = VectorXd::Zero(F.rows());
+  p = VectorXi::Zero(EV.rows());
+  pFixed.resize(EV.rows());
+  k = VectorXd::Zero(EV.rows());
+  singularityIndex = VectorXd::Zero(V.rows());
+
+  // Reset the constraints
+  resetConstraints();
+
+  // Compute k, differences between reference frames
+  computek();
+
+  softAlpha = 0.5;
+}
+
+void igl::NRosyField::setSoftAlpha(double alpha)
+{
+  assert(alpha >= 0 && alpha < 1);
+  softAlpha = alpha;
+}
+
+
+void igl::NRosyField::prepareSystemMatrix(const int N)
+{
+  using namespace std;
+  using namespace Eigen;
+
+  double Nd = N;
+
+  // Minimize the MIQ energy
+  // Energy on edge ij is
+  //     (t_i - t_j + kij + pij*(2*pi/N))^2
+  // Partial derivatives:
+  //   t_i: 2     ( t_i - t_j + kij + pij*(2*pi/N)) = 0
+  //   t_j: 2     (-t_i + t_j - kij - pij*(2*pi/N)) = 0
+  //   pij: 4pi/N ( t_i - t_j + kij + pij*(2*pi/N)) = 0
+  //
+  //          t_i      t_j         pij       kij
+  // t_i [     2       -2           4pi/N      2    ]
+  // t_j [    -2        2          -4pi/N     -2    ]
+  // pij [   4pi/N   -4pi/N    2*(2pi/N)^2   4pi/N  ]
+
+  // Count and tag the variables
+  tag_t = VectorXi::Constant(F.rows(),-1);
+  vector<int> id_t;
+  int count = 0;
+  for(unsigned i=0; i<F.rows(); ++i)
+    if (!isHard[i])
+    {
+      tag_t(i) = count++;
+      id_t.push_back(i);
+    }
+
+  unsigned count_t = id_t.size();
+
+  tag_p = VectorXi::Constant(EF.rows(),-1);
+  vector<int> id_p;
+  for(unsigned i=0; i<EF.rows(); ++i)
+  {
+    if (!pFixed[i])
+    {
+      // if it is not fixed then it is a variable
+      tag_p(i) = count++;
+    }
+
+    // if it is not a border edge,
+    if (!isBorderEdge[i])
+    {
+      // and it is not between two fixed faces
+      if (!(isHard[EF(i,0)] && isHard[EF(i,1)]))
+      {
+          // then it participates in the energy!
+          id_p.push_back(i);
+      }
+    }
+  }
+
+  unsigned count_p = count - count_t;
+  // System sizes: A (count_t + count_p) x (count_t + count_p)
+  //               b (count_t + count_p)
+
+  b = VectorXd::Zero(count_t + count_p);
+
+  std::vector<Eigen::Triplet<double> > T;
+  T.reserve(3 * 4 * count_p);
+
+  for(unsigned r=0; r<id_p.size(); ++r)
+  {
+    int eid = id_p[r];
+    int i = EF(eid,0);
+    int j = EF(eid,1);
+    bool isFixed_i = isHard[i];
+    bool isFixed_j = isHard[j];
+    bool isFixed_p = pFixed[eid];
+    int row;
+    // (i)-th row: t_i [     2       -2           4pi/N      2    ]
+    if (!isFixed_i)
+    {
+      row = tag_t[i];
+      if (isFixed_i) b(row) += -2               * hard[i]; else T.push_back(Eigen::Triplet<double>(row,tag_t[i]  , 2             ));
+      if (isFixed_j) b(row) +=  2               * hard[j]; else T.push_back(Eigen::Triplet<double>(row,tag_t[j]  ,-2             ));
+      if (isFixed_p) b(row) += -((4 * M_PI)/Nd) * p[eid] ; else T.push_back(Eigen::Triplet<double>(row,tag_p[eid],((4 * M_PI)/Nd)));
+      b(row) += -2 * k[eid];
+      assert(hard[i] == hard[i]);
+      assert(hard[j] == hard[j]);
+      assert(p[eid] == p[eid]);
+      assert(k[eid] == k[eid]);
+      assert(b(row) == b(row));
+    }
+    // (j)+1 -th row: t_j [    -2        2          -4pi/N     -2    ]
+    if (!isFixed_j)
+    {
+      row = tag_t[j];
+      if (isFixed_i) b(row) += 2               * hard[i]; else T.push_back(Eigen::Triplet<double>(row,tag_t[i]  , -2             ));
+      if (isFixed_j) b(row) += -2              * hard[j]; else T.push_back(Eigen::Triplet<double>(row,tag_t[j] ,  2              ));
+      if (isFixed_p) b(row) += ((4 * M_PI)/Nd) * p[eid] ; else T.push_back(Eigen::Triplet<double>(row,tag_p[eid],-((4 * M_PI)/Nd)));
+      b(row) += 2 * k[eid];
+      assert(k[eid] == k[eid]);
+      assert(b(row) == b(row));
+    }
+    // (r*3)+2 -th row: pij [   4pi/N   -4pi/N    2*(2pi/N)^2   4pi/N  ]
+    if (!isFixed_p)
+    {
+      row = tag_p[eid];
+      if (isFixed_i) b(row) += -(4 * M_PI)/Nd              * hard[i]; else T.push_back(Eigen::Triplet<double>(row,tag_t[i] ,   (4 * M_PI)/Nd             ));
+      if (isFixed_j) b(row) +=  (4 * M_PI)/Nd              * hard[j]; else T.push_back(Eigen::Triplet<double>(row,tag_t[j] ,  -(4 * M_PI)/Nd             ));
+      if (isFixed_p) b(row) += -(2 * pow(((2*M_PI)/Nd),2)) * p[eid] ;  else T.push_back(Eigen::Triplet<double>(row,tag_p[eid],  (2 * pow(((2*M_PI)/Nd),2))));
+      b(row) += - (4 * M_PI)/Nd * k[eid];
+      assert(k[eid] == k[eid]);
+      assert(b(row) == b(row));
+    }
+
+  }
+
+  A = SparseMatrix<double>(count_t + count_p, count_t + count_p);
+  A.setFromTriplets(T.begin(), T.end());
+
+  // Soft constraints
+  bool addSoft = false;
+
+  for(unsigned i=0; i<wSoft.size();++i)
+    if (wSoft[i] != 0)
+      addSoft = true;
+
+  if (addSoft)
+  {
+    cerr << " Adding soft here: " << endl;
+    cerr << " softAplha: " << softAlpha << endl;
+    VectorXd bSoft = VectorXd::Zero(count_t + count_p);
+
+    std::vector<Eigen::Triplet<double> > TSoft;
+    TSoft.reserve(2 * count_p);
+
+    for(unsigned i=0; i<F.rows(); ++i)
+    {
+      int varid = tag_t[i];
+      if (varid != -1) // if it is a variable in the system
+      {
+        TSoft.push_back(Eigen::Triplet<double>(varid,varid,wSoft[i]));
+        bSoft[varid] += wSoft[i] * soft[i];
+      }
+    }
+    SparseMatrix<double> ASoft(count_t + count_p, count_t + count_p);
+    ASoft.setFromTriplets(TSoft.begin(), TSoft.end());
+
+//    ofstream s("/Users/daniele/As.txt");
+//    for(unsigned i=0; i<TSoft.size(); ++i)
+//      s << TSoft[i].row() << " " << TSoft[i].col() << " " << TSoft[i].value() << endl;
+//    s.close();
+
+//    ofstream s2("/Users/daniele/bs.txt");
+//    for(unsigned i=0; i<bSoft.rows(); ++i)
+//      s2 << bSoft(i) << endl;
+//    s2.close();
+
+    // Stupid Eigen bug
+    SparseMatrix<double> Atmp (count_t + count_p, count_t + count_p);
+    SparseMatrix<double> Atmp2(count_t + count_p, count_t + count_p);
+    SparseMatrix<double> Atmp3(count_t + count_p, count_t + count_p);
+
+    // Merge the two part of the energy
+    Atmp = (1.0 - softAlpha)*A;
+    Atmp2 = softAlpha * ASoft;
+    Atmp3 = Atmp+Atmp2;
+
+    A = Atmp3;
+    b = b*(1.0 - softAlpha) + bSoft * softAlpha;
+  }
+
+//  ofstream s("/Users/daniele/A.txt");
+//  for (int k=0; k<A.outerSize(); ++k)
+//    for (SparseMatrix<double>::InnerIterator it(A,k); it; ++it)
+//    {
+//      s << it.row() << " " << it.col() << " " << it.value() << endl;
+//    }
+//  s.close();
+//
+//  ofstream s2("/Users/daniele/b.txt");
+//  for(unsigned i=0; i<b.rows(); ++i)
+//    s2 << b(i) << endl;
+//  s2.close();
+}
+
+void igl::NRosyField::solveNoRoundings()
+{
+  using namespace std;
+  using namespace Eigen;
+
+  // Solve the linear system
+  SimplicialLDLT<SparseMatrix<double> > solver;
+  solver.compute(A);
+  VectorXd x = solver.solve(b);
+
+  // Copy the result back
+  for(unsigned i=0; i<F.rows(); ++i)
+    if (tag_t[i] != -1)
+      angles[i] = x(tag_t[i]);
+    else
+      angles[i] = hard[i];
+
+  for(unsigned i=0; i<EF.rows(); ++i)
+    if(tag_p[i]  != -1)
+      p[i] = roundl(x[tag_p[i]]);
+}
+
+void igl::NRosyField::solveRoundings()
+{
+  using namespace std;
+  using namespace Eigen;
+
+  unsigned n = A.rows();
+
+  gmm::col_matrix< gmm::wsvector< double > > gmm_A;
+  std::vector<double> gmm_b;
+  std::vector<int> ids_to_round;
+  std::vector<double> x;
+
+  gmm_A.resize(n,n);
+  gmm_b.resize(n);
+  x.resize(n);
+
+  // Copy A
+  for (int k=0; k<A.outerSize(); ++k)
+    for (SparseMatrix<double>::InnerIterator it(A,k); it; ++it)
+    {
+      gmm_A(it.row(),it.col()) += it.value();
+    }
+
+  // Copy b
+  for(unsigned i=0; i<n;++i)
+    gmm_b[i] = b[i];
+
+  // Set variables to round
+  ids_to_round.clear();
+  for(unsigned i=0; i<tag_p.size();++i)
+    if(tag_p[i] != -1)
+      ids_to_round.push_back(tag_p[i]);
+
+  // Empty constraints
+  gmm::row_matrix< gmm::wsvector< double > > gmm_C(0, n);
+
+  COMISO::ConstrainedSolver cs;
+  //print_miso_settings(cs.misolver());
+  cs.solve(gmm_C, gmm_A, x, gmm_b, ids_to_round, 0.0, false, true);
+
+  // Copy the result back
+  for(unsigned i=0; i<F.rows(); ++i)
+    if (tag_t[i] != -1)
+      angles[i] = x[tag_t[i]];
+    else
+      angles[i] = hard[i];
+
+  for(unsigned i=0; i<EF.rows(); ++i)
+    if(tag_p[i]  != -1)
+      p[i] = roundl(x[tag_p[i]]);
+
+}
+
+
+void igl::NRosyField::roundAndFix()
+{
+  for(unsigned i=0; i<p.rows(); ++i)
+    pFixed[i] = true;
+}
+
+void igl::NRosyField::roundAndFixToZero()
+{
+  for(unsigned i=0; i<p.rows(); ++i)
+  {
+    pFixed[i] = true;
+    p[i] = 0;
+  }
+}
+
+void igl::NRosyField::solve(const int N)
+{
+  // Reduce the search space by fixing matchings
+  reduceSpace();
+
+  // Build the system
+  prepareSystemMatrix(N);
+
+  // Solve with integer roundings
+  solveRoundings();
+
+  // This is a very greedy solving strategy
+  // // Solve with no roundings
+  // solveNoRoundings();
+  //
+  // // Round all p and fix them
+  // roundAndFix();
+  //
+  // // Build the system
+  // prepareSystemMatrix(N);
+  //
+  // // Solve with no roundings (they are all fixed)
+  // solveNoRoundings();
+
+  // Find the cones
+  findCones(N);
+}
+
+void igl::NRosyField::setConstraintHard(const int fid, const Eigen::Vector3d& v)
+{
+  isHard[fid] = true;
+  hard(fid) = convert3DtoLocal(fid, v);
+}
+
+void igl::NRosyField::setConstraintSoft(const int fid, const double w, const Eigen::Vector3d& v)
+{
+  wSoft(fid) = w;
+  soft(fid) = convert3DtoLocal(fid, v);
+}
+
+void igl::NRosyField::resetConstraints()
+{
+  using namespace std;
+  using namespace Eigen;
+
+  isHard.resize(F.rows());
+  for(unsigned i=0; i<F.rows(); ++i)
+    isHard[i] = false;
+  hard   = VectorXd::Zero(F.rows());
+
+  wSoft  = VectorXd::Zero(F.rows());
+  soft   = VectorXd::Zero(F.rows());
+}
+
+Eigen::MatrixXd igl::NRosyField::getFieldPerFace()
+{
+  using namespace std;
+  using namespace Eigen;
+
+  MatrixXd result(F.rows(),3);
+  for(unsigned i=0; i<F.rows(); ++i)
+    result.row(i) = convertLocalto3D(i, angles(i));
+  return result;
+}
+
+Eigen::MatrixXd igl::NRosyField::getFFieldPerFace()
+{
+  using namespace std;
+  using namespace Eigen;
+
+  MatrixXd result(F.rows(),6);
+  for(unsigned i=0; i<F.rows(); ++i)
+  {
+      Vector3d v1 = convertLocalto3D(i, angles(i));
+      Vector3d n = N.row(i);
+      Vector3d v2 = n.cross(v1);
+      v1.normalize();
+      v2.normalize();
+
+      result.block(i,0,1,3) = v1.transpose();
+      result.block(i,3,1,3) = v2.transpose();
+  }
+  return result;
+}
+
+
+void igl::NRosyField::computek()
+{
+  using namespace std;
+  using namespace Eigen;
+
+  // For every non-border edge
+  for (unsigned eid=0; eid<EF.rows(); ++eid)
+  {
+    if (!isBorderEdge[eid])
+    {
+      int fid0 = EF(eid,0);
+      int fid1 = EF(eid,1);
+
+      Vector3d N0 = N.row(fid0);
+      Vector3d N1 = N.row(fid1);
+
+      // find common edge on triangle 0 and 1
+      int fid0_vc = -1;
+      int fid1_vc = -1;
+      for (unsigned i=0;i<3;++i)
+      {
+        if (EV(eid,0) == F(fid0,i))
+          fid0_vc = i;
+        if (EV(eid,1) == F(fid1,i))
+          fid1_vc = i;
+      }
+      assert(fid0_vc != -1);
+      assert(fid1_vc != -1);
+
+      Vector3d common_edge = V.row(F(fid0,(fid0_vc+1)%3)) - V.row(F(fid0,fid0_vc));
+      common_edge.normalize();
+
+      // Map the two triangles in a new space where the common edge is the x axis and the N0 the z axis
+      MatrixXd P(3,3);
+      VectorXd o = V.row(F(fid0,fid0_vc));
+      VectorXd tmp = -N0.cross(common_edge);
+      P << common_edge, tmp, N0;
+      P.transposeInPlace();
+
+
+      MatrixXd V0(3,3);
+      V0.row(0) = V.row(F(fid0,0)).transpose() -o;
+      V0.row(1) = V.row(F(fid0,1)).transpose() -o;
+      V0.row(2) = V.row(F(fid0,2)).transpose() -o;
+
+      V0 = (P*V0.transpose()).transpose();
+
+      assert(V0(0,2) < 10e-10);
+      assert(V0(1,2) < 10e-10);
+      assert(V0(2,2) < 10e-10);
+
+      MatrixXd V1(3,3);
+      V1.row(0) = V.row(F(fid1,0)).transpose() -o;
+      V1.row(1) = V.row(F(fid1,1)).transpose() -o;
+      V1.row(2) = V.row(F(fid1,2)).transpose() -o;
+      V1 = (P*V1.transpose()).transpose();
+
+      assert(V1(fid1_vc,2) < 10e-10);
+      assert(V1((fid1_vc+1)%3,2) < 10e-10);
+
+      // compute rotation R such that R * N1 = N0
+      // i.e. map both triangles to the same plane
+      double alpha = -atan2(V1((fid1_vc+2)%3,2),V1((fid1_vc+2)%3,1));
+
+      MatrixXd R(3,3);
+      R << 1,          0,            0,
+           0, cos(alpha), -sin(alpha) ,
+           0, sin(alpha),  cos(alpha);
+      V1 = (R*V1.transpose()).transpose();
+
+      assert(V1(0,2) < 10e-10);
+      assert(V1(1,2) < 10e-10);
+      assert(V1(2,2) < 10e-10);
+
+      // measure the angle between the reference frames
+      // k_ij is the angle between the triangle on the left and the one on the right
+      VectorXd ref0 = V0.row(1) - V0.row(0);
+      VectorXd ref1 = V1.row(1) - V1.row(0);
+
+      ref0.normalize();
+      ref1.normalize();
+
+      double ktemp = atan2(ref1(1),ref1(0)) - atan2(ref0(1),ref0(0));
+
+      // just to be sure, rotate ref0 using angle ktemp...
+      MatrixXd R2(2,2);
+      R2 << cos(ktemp), -sin(ktemp), sin(ktemp), cos(ktemp);
+
+      tmp = R2*ref0.head<2>();
+
+      assert(tmp(0) - ref1(0) < 10^10);
+      assert(tmp(1) - ref1(1) < 10^10);
+
+      k[eid] = ktemp;
+    }
+  }
+
+}
+
+void igl::NRosyField::reduceSpace()
+{
+  using namespace std;
+  using namespace Eigen;
+
+  // All variables are free in the beginning
+  for(unsigned i=0; i<EV.rows(); ++i)
+    pFixed[i] = false;
+
+  vector<VectorXd> debug;
+
+  // debug
+//  MatrixXd B(F.rows(),3);
+//  for(unsigned i=0; i<F.rows(); ++i)
+//    B.row(i) = 1./3. * (V.row(F(i,0)) + V.row(F(i,1)) + V.row(F(i,2)));
+
+  vector<bool> visited(EV.rows());
+  for(unsigned i=0; i<EV.rows(); ++i)
+    visited[i] = false;
+
+  vector<bool> starting(EV.rows());
+  for(unsigned i=0; i<EV.rows(); ++i)
+    starting[i] = false;
+
+  queue<int> q;
+  for(unsigned i=0; i<F.rows(); ++i)
+    if (isHard[i] || wSoft[i] != 0)
+    {
+      q.push(i);
+      starting[i] = true;
+    }
+
+  // Reduce the search space (see MI paper)
+  while (!q.empty())
+  {
+    int c = q.front();
+    q.pop();
+
+    visited[c] = true;
+    for(int i=0; i<3; ++i)
+    {
+      int eid = FE(c,i);
+      int fid = TT(c,i);
+
+      // skip borders
+      if (fid != -1)
+      {
+        assert((EF(eid,0) == c && EF(eid,1) == fid) || (EF(eid,1) == c && EF(eid,0) == fid));
+        // for every neighbouring face
+        if (!visited[fid] && !starting[fid])
+        {
+          pFixed[eid] = true;
+          p[eid] = 0;
+          visited[fid] = true;
+          q.push(fid);
+
+        }
+      }
+      else
+      {
+        // fix borders
+        pFixed[eid] = true;
+        p[eid] = 0;
+      }
+    }
+
+  }
+
+  // Force matchings between fixed faces
+  for(unsigned i=0; i<F.rows();++i)
+  {
+    if (isHard[i])
+    {
+      for(unsigned int j=0; j<3; ++j)
+      {
+        int fid = TT(i,j);
+        if ((fid!=-1) && (isHard[fid]))
+        {
+          // i and fid are adjacent and fixed
+          int eid = FE(i,j);
+          int fid0 = EF(eid,0);
+          int fid1 = EF(eid,1);
+
+          pFixed[eid] = true;
+          p[eid] = roundl(2.0/M_PI*(hard(fid1) - hard(fid0) - k(eid)));
+        }
+      }
+    }
+  }
+
+//  std::ofstream s("/Users/daniele/debug.txt");
+//  for(unsigned i=0; i<debug.size(); i += 2)
+//    s << debug[i].transpose() << " " << debug[i+1].transpose() << endl;
+//  s.close();
+
+}
+
+double igl::NRosyField::convert3DtoLocal(unsigned fid, const Eigen::Vector3d& v)
+{
+  using namespace std;
+  using namespace Eigen;
+
+  // Project onto the tangent plane
+  Vector2d vp = TPs[fid] * v;
+
+  // Convert to angle
+  return atan2(vp(1),vp(0));
+}
+
+Eigen::Vector3d igl::NRosyField::convertLocalto3D(unsigned fid, double a)
+{
+  using namespace std;
+  using namespace Eigen;
+
+  Vector2d vp(cos(a),sin(a));
+  return vp.transpose() * TPs[fid];
+}
+
+Eigen::VectorXd igl::NRosyField::angleDefect()
+{
+  Eigen::VectorXd A = Eigen::VectorXd::Constant(V.rows(),-2*M_PI);
+
+  for (unsigned i=0; i < F.rows(); ++i)
+  {
+    for (int j = 0; j < 3; ++j)
+    {
+      Eigen::VectorXd a = V.row(F(i,(j+1)%3)) - V.row(F(i,j));
+      Eigen::VectorXd b = V.row(F(i,(j+2)%3)) - V.row(F(i,j));
+      double t = a.transpose()*b;
+      t /= (a.norm() * b.norm());
+      A(F(i,j)) += acos(t);
+    }
+  }
+
+  return A;
+}
+
+void igl::NRosyField::findCones(int N)
+{
+  // Compute I0, see http://www.graphics.rwth-aachen.de/media/papers/bommes_zimmer_2009_siggraph_011.pdf for details
+
+  Eigen::VectorXd I0 = Eigen::VectorXd::Zero(V.rows());
+
+  // first the k
+  for (unsigned i=0; i < EV.rows(); ++i)
+  {
+    if (!isBorderEdge[i])
+    {
+      I0(EV(i,0)) -= k(i);
+      I0(EV(i,1)) += k(i);
+    }
+  }
+
+  // then the A
+  Eigen::VectorXd A = angleDefect();
+
+  I0 = I0 + A;
+
+  // normalize
+  I0 = I0 / (2*M_PI);
+
+  // round to integer (remove numerical noise)
+  for (unsigned i=0; i < I0.size(); ++i)
+    I0(i) = round(I0(i));
+
+  // compute I
+  Eigen::VectorXd I = I0;
+
+  for (unsigned i=0; i < EV.rows(); ++i)
+  {
+    if (!isBorderEdge[i])
+    {
+      I(EV(i,0)) -= double(p(i))/double(N);
+      I(EV(i,1)) += double(p(i))/double(N);
+    }
+  }
+
+  // Clear the vertices on the edges
+  for (unsigned i=0; i < EV.rows(); ++i)
+  {
+    if (isBorderEdge[i])
+    {
+      I0(EV(i,0)) = 0;
+      I0(EV(i,1)) = 0;
+      I(EV(i,0)) = 0;
+      I(EV(i,1)) = 0;
+      A(EV(i,0)) = 0;
+      A(EV(i,1)) = 0;
+    }
+  }
+
+  singularityIndex = I;
+}
+
+Eigen::VectorXd igl::NRosyField::getSingularityIndexPerVertex()
+{
+  return singularityIndex;
+}
+
+IGL_INLINE void igl::nrosy(
+                           const Eigen::MatrixXd& V,
+                           const Eigen::MatrixXi& F,
+                           const Eigen::VectorXi& b,
+                           const Eigen::MatrixXd& bc,
+                           const Eigen::VectorXi& b_soft,
+                           const Eigen::VectorXd& w_soft,
+                           const Eigen::MatrixXd& bc_soft,
+                           const int N,
+                           const double soft,
+                           Eigen::MatrixXd& R,
+                           Eigen::VectorXd& S
+                           )
+{
+  // Init solver
+  igl::NRosyField solver(V,F);
+
+  // Add hard constraints
+  for (unsigned i=0; i<b.size();++i)
+    solver.setConstraintHard(b(i),bc.row(i));
+
+  // Add soft constraints
+  for (unsigned i=0; i<b_soft.size();++i)
+    solver.setConstraintSoft(b_soft(i),w_soft(i),bc_soft.row(i));
+
+  // Set the soft constraints global weight
+  solver.setSoftAlpha(soft);
+
+  // Interpolate
+  solver.solve(N);
+
+  // Copy the result back
+  R = solver.getFieldPerFace();
+
+  // Extract singularity indices
+  S = solver.getSingularityIndexPerVertex();
+}

+ 55 - 0
include/igl/comiso/nrosy.h

@@ -0,0 +1,55 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+#ifndef IGL_NROSY_H
+#define IGL_NROSY_H
+
+#include <iostream>
+#include <Eigen/Core>
+#include <Eigen/Sparse>
+#include <vector>
+
+namespace igl
+{
+// Generate a N-RoSy field from a sparse set of constraints
+//
+// Inputs:
+//   V       #V by 3 list of mesh vertex coordinates
+//   F       #F by 3 list of mesh faces (must be triangles)
+//   b       #B by 1 list of constrained face indices
+//   bc      #B by 3 list of representative vectors for the constrained faces
+//   b_soft  #S by 1 b for soft constraints
+//   w_soft  #S by 1 weight for the soft constraints (0-1)
+//   bc_soft #S by 3 bc for soft constraints
+//   N       the degree of the N-RoSy vector field
+//   soft    the strenght of the soft contraints w.r.t. smoothness
+//           (0 -> smoothness only, 1->constraints only)
+
+// Outputs:
+//   R       #V by 3 the representative vectors of the interpolated field
+//   S       #V by 1 the singularity index for each vertex (0 = regular)
+
+IGL_INLINE void nrosy(
+  const Eigen::MatrixXd& V,
+  const Eigen::MatrixXi& F,
+  const Eigen::VectorXi& b,
+  const Eigen::MatrixXd& bc,
+  const Eigen::VectorXi& b_soft,
+  const Eigen::VectorXd& w_soft,
+  const Eigen::MatrixXd& bc_soft,
+  const int N,
+  const double soft,
+  Eigen::MatrixXd& R,
+  Eigen::VectorXd& S
+  );
+}
+
+#ifdef IGL_HEADER_ONLY
+#  include "nrosy.cpp"
+#endif
+
+#endif

+ 68 - 0
include/igl/compute_frame_field_bisectors.cpp

@@ -0,0 +1,68 @@
+#include "compute_frame_field_bisectors.h"
+#include "igl/local_basis.h"
+
+template <typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::compute_frame_field_bisectors(
+                                                   const Eigen::PlainObjectBase<DerivedV>& V,
+                                                   const Eigen::PlainObjectBase<DerivedF>& F,
+                                                   const Eigen::PlainObjectBase<DerivedV>& B1,
+                                                   const Eigen::PlainObjectBase<DerivedV>& B2,
+                                                   const Eigen::PlainObjectBase<DerivedV>& PD1,
+                                                   const Eigen::PlainObjectBase<DerivedV>& PD2,
+                                                   Eigen::PlainObjectBase<DerivedV>& BIS1,
+                                                   Eigen::PlainObjectBase<DerivedV>& BIS2)
+{
+  BIS1.resize(PD1.rows(),3);
+  BIS2.resize(PD1.rows(),3);
+  
+  for (unsigned i=0; i<PD1.rows();++i)
+  {
+    // project onto the tangent plane and convert to angle
+    // Convert to angle
+    double a1 = atan2(B2.row(i).dot(PD1.row(i)),B1.row(i).dot(PD1.row(i)));
+    //make it positive by adding some multiple of 2pi
+    a1 += ceil (std::max(0., -a1) / (M_PI*2.)) * (M_PI*2.);
+    //take modulo 2pi
+    a1 = fmod(a1, (M_PI*2.));
+    double a2 = atan2(B2.row(i).dot(PD2.row(i)),B1.row(i).dot(PD2.row(i)));
+    //make it positive by adding some multiple of 2pi
+    a2 += ceil (std::max(0., -a2) / (M_PI*2.)) * (M_PI*2.);
+    //take modulo 2pi
+    a2 = fmod(a2, (M_PI*2.));
+    
+    double b1 = (a1+a2)/2.0;
+    //make it positive by adding some multiple of 2pi
+    b1 += ceil (std::max(0., -b1) / (M_PI*2.)) * (M_PI*2.);
+    //take modulo 2pi
+    b1 = fmod(b1, (M_PI*2.));
+
+    double b2 = b1+(M_PI/2.);
+    //make it positive by adding some multiple of 2pi
+    b2 += ceil (std::max(0., -b2) / (M_PI*2.)) * (M_PI*2.);
+    //take modulo 2pi
+    b2 = fmod(b2, (M_PI*2.));
+    
+    BIS1.row(i) = cos(b1) * B1.row(i) + sin(b1) * B2.row(i);
+    BIS2.row(i) = cos(b2) * B1.row(i) + sin(b2) * B2.row(i);
+    
+  }
+}
+
+template <typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::compute_frame_field_bisectors(
+                                                   const Eigen::PlainObjectBase<DerivedV>& V,
+                                                   const Eigen::PlainObjectBase<DerivedF>& F,
+                                                   const Eigen::PlainObjectBase<DerivedV>& PD1,
+                                                   const Eigen::PlainObjectBase<DerivedV>& PD2,
+                                                   Eigen::PlainObjectBase<DerivedV>& BIS1,
+                                                   Eigen::PlainObjectBase<DerivedV>& BIS2)
+{
+  Eigen::PlainObjectBase<DerivedV> B1, B2, B3;
+  igl::local_basis(V,F,B1,B2,B3);
+  
+  compute_frame_field_bisectors( V, F, B1, B2, PD1, PD2, BIS1, BIS2);
+
+}
+
+#ifndef IGL_HEADER_ONLY
+#endif

+ 44 - 0
include/igl/compute_frame_field_bisectors.h

@@ -0,0 +1,44 @@
+#ifndef IGL_COMPUTE_FRAME_FIELD_BISECTORS_H
+#define IGL_COMPUTE_FRAME_FIELD_BISECTORS_H
+#include "igl_inline.h"
+#include <Eigen/Core>
+namespace igl
+{
+  // Compute face normals via vertex position list, face list
+  // Inputs:
+  //   V     #V by 3 eigen Matrix of mesh vertex 3D positions
+  //   F     #F by 3 eigen Matrix of face (triangle) indices
+  //   B1    #F by 3 eigen Matrix of face (triangle) base vector 1
+  //   B2    #F by 3 eigen Matrix of face (triangle) base vector 2
+  //   PD1   #F by 3 eigen Matrix of the first per face frame field vector
+  //   PD2   #F by 3 eigen Matrix of the second per face frame field vector
+  // Output:
+  //   BIS1  #F by 3 eigen Matrix of the first per face frame field bisector
+  //   BIS2  #F by 3 eigen Matrix of the second per face frame field bisector
+  //
+  template <typename DerivedV, typename DerivedF>
+  IGL_INLINE void compute_frame_field_bisectors(
+                                                const Eigen::PlainObjectBase<DerivedV>& V,
+                                                const Eigen::PlainObjectBase<DerivedF>& F,
+                                                const Eigen::PlainObjectBase<DerivedV>& B1,
+                                                const Eigen::PlainObjectBase<DerivedV>& B2,
+                                                const Eigen::PlainObjectBase<DerivedV>& PD1,
+                                                const Eigen::PlainObjectBase<DerivedV>& PD2,
+                                                Eigen::PlainObjectBase<DerivedV>& BIS1,
+                                                Eigen::PlainObjectBase<DerivedV>& BIS2);
+  // Wrapper without given basis vectors.
+  template <typename DerivedV, typename DerivedF>
+  IGL_INLINE void compute_frame_field_bisectors(
+                                                const Eigen::PlainObjectBase<DerivedV>& V,
+                                                const Eigen::PlainObjectBase<DerivedF>& F,
+                                                const Eigen::PlainObjectBase<DerivedV>& PD1,
+                                                const Eigen::PlainObjectBase<DerivedV>& PD2,
+                                                Eigen::PlainObjectBase<DerivedV>& BIS1,
+                                                Eigen::PlainObjectBase<DerivedV>& BIS2);
+}
+
+#ifdef IGL_HEADER_ONLY
+#  include "compute_frame_field_bisectors.cpp"
+#endif
+
+#endif

+ 151 - 0
include/igl/cross_field_missmatch.cpp

@@ -0,0 +1,151 @@
+#include "cross_field_missmatch.h"
+#include "comb_cross_field.h"
+
+#include <vector>
+#include <deque>
+#include "per_face_normals.h"
+#include "is_border_vertex.h"
+#include "vf.h"
+#include "tt.h"
+
+
+namespace igl {
+  template <typename DerivedV, typename DerivedF, typename DerivedO>
+  class MissMatchCalculator
+  {
+  public:
+    
+    const Eigen::PlainObjectBase<DerivedV> &V;
+    const Eigen::PlainObjectBase<DerivedF> &F;
+    const Eigen::PlainObjectBase<DerivedV> &PD1;
+    const Eigen::PlainObjectBase<DerivedV> &PD2;
+    Eigen::PlainObjectBase<DerivedV> N;
+    
+  private:
+    // internal
+    std::vector<bool> V_border; // bool
+    std::vector<std::vector<int> > VF;
+    std::vector<std::vector<int> > VFi;
+    Eigen::PlainObjectBase<DerivedF> TT;
+    Eigen::PlainObjectBase<DerivedF> TTi;
+    
+    
+  private:
+    
+    ///return true if a vertex is singluar by looking at initialized missmatches
+    // possible bugs, verify deleted flag vs IsD()
+    // not sorted vf, but should not make a difference
+    // olga: TODO: this returns the index modulo 4.
+    int oneRingMissMatch(const int vid)
+    {
+      ///check that is on border..
+      if (V_border[vid])
+        return 0;
+      
+      int missmatch=0;
+      for (unsigned int i=0;i<VF[vid].size();i++)
+      {
+        // look for the vertex
+        int j=-1;
+        for (unsigned z=0; z<3; ++z)
+          if (F(VF[vid][i],z) == vid)
+            j=z;
+        assert(j!=-1);
+        
+        missmatch+=Handle_MMatch(VF[vid][i],j);
+      }
+      
+      missmatch=missmatch%4;
+      return missmatch;
+    }
+    
+    
+    ///compute the mismatch between 2 faces
+    int MissMatchByCross(const int f0,
+                         const int f1)
+    {
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 1> dir0 = PD1.row(f0);
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 1> dir1 = PD1.row(f1);
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 1> n0 = N.row(f0);
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 1> n1 = N.row(f1);
+      
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 1> dir1Rot = Comb<DerivedV, DerivedF>::Rotate(n1,n0,dir1);
+      dir1Rot.normalize();
+      
+      // TODO: this should be equivalent to the other code below, to check!
+      // Compute the angle between the two vectors
+      //    double a0 = atan2(dir0.dot(B2.row(f0)),dir0.dot(B1.row(f0)));
+      //    double a1 = atan2(dir1Rot.dot(B2.row(f0)),dir1Rot.dot(B1.row(f0)));
+      //
+      //    double angle_diff = a1-a0;   //VectToAngle(f0,dir1Rot);
+      
+      double angle_diff = atan2(dir1Rot.dot(PD2.row(f0)),dir1Rot.dot(PD1.row(f0)));
+      
+      //    std::cerr << "Dani: " << dir0(0) << " " << dir0(1) << " " << dir0(2) << " " << dir1Rot(0) << " " << dir1Rot(1) << " " << dir1Rot(2) << " " << angle_diff << std::endl;
+      
+      double step=M_PI/2.0;
+      int i=(int)floor((angle_diff/step)+0.5);
+      int k=0;
+      if (i>=0)
+        k=i%4;
+      else
+        k=(-(3*i))%4;
+      return k;
+    }
+    
+    
+public:
+  MissMatchCalculator(const Eigen::PlainObjectBase<DerivedV> &_V,
+                      const Eigen::PlainObjectBase<DerivedF> &_F,
+                      const Eigen::PlainObjectBase<DerivedV> &_PD1,
+                      const Eigen::PlainObjectBase<DerivedV> &_PD2
+                      ):
+  V(_V),
+  F(_F),
+  PD1(_PD1),
+  PD2(_PD2)
+  {
+    igl::per_face_normals(V,F,N);
+    V_border = igl::is_border_vertex(V,F);
+    igl::vf(V,F,VF,VFi);
+    igl::tt(V,F,TT,TTi);
+  }
+  
+  void calculateMissmatch(Eigen::PlainObjectBase<DerivedO> &Handle_MMatch)
+  {
+    Handle_MMatch.setConstant(F.rows(),3,-1);
+    for (unsigned int i=0;i<F.rows();i++)
+    {
+      for (int j=0;j<3;j++)
+      {
+        if (i==TT(i,j) || TT(i,j) == -1)
+          Handle_MMatch(i,j)=0;
+        else
+          Handle_MMatch(i,j) = MissMatchByCross(i,TT(i,j));
+      }
+    }
+  }
+  
+};
+}
+template <typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::cross_field_missmatch(const Eigen::PlainObjectBase<DerivedV> &V,
+                                           const Eigen::PlainObjectBase<DerivedF> &F,
+                                           const Eigen::PlainObjectBase<DerivedV> &PD1,
+                                           const Eigen::PlainObjectBase<DerivedV> &PD2,
+                                           const bool isCombed,
+                                           Eigen::PlainObjectBase<DerivedO> &missmatch)
+{
+  Eigen::PlainObjectBase<DerivedV> PD1_combed;
+  Eigen::PlainObjectBase<DerivedV> PD2_combed;
+  
+  if (!isCombed)
+    igl::comb_cross_field(V,F,PD1,PD2,PD1_combed,PD2_combed);
+  else
+  {
+    PD1_combed = PD1;
+    PD2_combed = PD2;
+  }
+  igl::MissMatchCalculator<DerivedV, DerivedF, DerivedO> sf(V, F, PD1_combed, PD2_combed);
+  sf.calculateMissmatch(missmatch);
+}

+ 36 - 0
include/igl/cross_field_missmatch.h

@@ -0,0 +1,36 @@
+#ifndef IGL_CROSS_FIELD_MISSMATCH_H
+#define IGL_CROSS_FIELD_MISSMATCH_H
+#include "igl_inline.h"
+#include <Eigen/Core>
+namespace igl
+{
+  //todo
+  // Creates a quad mesh from a triangular mesh and a set of two directions
+  // per face, using the algorithm described in the paper
+  // "Mixed-Integer Quadrangulation" by D. Bommes, H. Zimmer, L. Kobbelt
+  // ACM SIGGRAPH 2009, Article No. 77 (http://dl.acm.org/citation.cfm?id=1531383)
+  
+  // Inputs:
+  //   Vin        #V by 3 eigen Matrix of mesh vertex 3D positions
+  //   F          #F by 4 eigen Matrix of face (quad) indices
+  //   maxIter    maximum numbers of iterations
+  //   threshold  minimum allowed threshold for non-planarity
+  // Output:
+  //   Vout       #V by 3 eigen Matrix of planar mesh vertex 3D positions
+  //
+  
+  
+  // TODO: this returns singularity index modulo 4. It may need to be modified to cover indices
+  template <typename DerivedV, typename DerivedF, typename DerivedO>
+  IGL_INLINE void cross_field_missmatch(const Eigen::PlainObjectBase<DerivedV> &V,
+                                        const Eigen::PlainObjectBase<DerivedF> &F,
+                                        const Eigen::PlainObjectBase<DerivedV> &PD1,
+                                        const Eigen::PlainObjectBase<DerivedV> &PD2,
+                                        const bool isCombed,
+                                        Eigen::PlainObjectBase<DerivedO> &missmatch);
+}
+#ifdef IGL_HEADER_ONLY
+#include "cross_field_missmatch.cpp"
+#endif
+
+#endif

+ 177 - 0
include/igl/cut_mesh_from_singularities.cpp

@@ -0,0 +1,177 @@
+#include "cut_mesh_from_singularities.h"
+
+#include <vector>
+#include <deque>
+
+
+namespace igl {
+  template <
+  typename DerivedV,
+  typename DerivedF,
+  typename DerivedM,
+  typename DerivedS,
+  typename DerivedO
+  >
+  class MeshCutter
+  {
+  protected:
+    const Eigen::PlainObjectBase<DerivedV> &V;
+    const Eigen::PlainObjectBase<DerivedF> &F;
+    const Eigen::PlainObjectBase<DerivedS> &Handle_Singular;
+    const Eigen::PlainObjectBase<DerivedS> &Handle_SingularDegree;
+    const Eigen::PlainObjectBase<DerivedM> &Handle_MMatch;
+
+    Eigen::VectorXi F_visited;
+    Eigen::PlainObjectBase<DerivedF> TT;
+    Eigen::PlainObjectBase<DerivedF> TTi;
+
+  protected:
+    
+    bool IsRotSeam(const int f0,const int edge)
+    {
+      unsigned char MM = Handle_MMatch(f0,edge);
+      return (MM!=0);
+    }
+    
+    void FloodFill(const int start, Eigen::PlainObjectBase<DerivedO> &Handle_Seams)
+    {
+      std::deque<int> d;
+      ///clean the visited flag
+      F_visited(start) = true;
+      d.push_back(start);
+      
+      while (!d.empty())
+      {
+        int f = d.at(0); d.pop_front();
+        for (int s = 0; s<3; s++)
+        {
+          int g = TT(f,s); // f->FFp(s);
+          int j = TTi(f,s); // f->FFi(s);
+          
+          if (j == -1)
+          {
+            g = f;
+            j = s;
+          }
+          
+          if ((!(IsRotSeam(f,s))) && (!(IsRotSeam(g,j)))  && (!F_visited(g)) )
+          {
+            Handle_Seams(f,s)=false;
+            Handle_Seams(g,j)=false;
+            F_visited(g) = true;
+            d.push_back(g);
+          }
+        }
+      }
+    }
+    
+    void Retract(Eigen::PlainObjectBase<DerivedO> &Handle_Seams)
+    {
+      std::vector<int> e(V.rows(),0); // number of edges per vert
+      
+      for (unsigned f=0; f<F.rows(); f++)
+      {
+        for (int s = 0; s<3; s++)
+        {
+          if (Handle_Seams(f,s))
+            if (TT(f,s)<=f)
+            {
+              e[ F(f,s) ] ++;
+              e[ F(f,(s+1)%3) ] ++;
+            }
+        }
+      }
+      
+      bool over=true;
+      int guard = 0;
+      do
+      {
+        over = true;
+        for (int f = 0; f<F.rows(); f++) //if (!f->IsD())
+        {
+          for (int s = 0; s<3; s++)
+          {
+            if (Handle_Seams(f,s))
+              if (!(IsRotSeam(f,s))) // never retract rot seams
+              {
+                if (e[ F(f,s) ] == 1) {
+                  // dissolve seam
+                  Handle_Seams(f,s)=false;
+                  if (TT(f,s) != -1)
+                    Handle_Seams(TT(f,s),TTi(f,s))=false;
+                  
+                  e[ F(f,s)] --;
+                  e[ F(f,(s+1)%3) ] --;
+                  over = false;
+                }
+              }
+          }
+        }
+        
+        if (guard++>10000)
+          over = true;
+        
+      } while (!over);
+    }
+
+  public:
+   
+    MeshCutter(const Eigen::PlainObjectBase<DerivedV> &V_,
+               const Eigen::PlainObjectBase<DerivedF> &F_,
+               const Eigen::PlainObjectBase<DerivedM> &Handle_MMatch_,
+               const Eigen::PlainObjectBase<DerivedS> &Handle_Singular_,
+               const Eigen::PlainObjectBase<DerivedS> &Handle_SingularDegree_):
+    V(V_),
+    F(F_),
+    Handle_MMatch(Handle_MMatch_),
+    Handle_Singular(Handle_Singular_),
+    Handle_SingularDegree(Handle_SingularDegree_)
+    {
+      tt(V,F,TT,TTi);
+    };
+    
+    void cut(Eigen::PlainObjectBase<DerivedO> &Handle_Seams)
+    {
+      F_visited.setConstant(F.rows(),0);
+      Handle_Seams.setConstant(F.rows(),3,1);
+      
+      int index=0;
+      for (unsigned f = 0; f<F.rows(); f++)
+      {
+        if (!F_visited(f))
+        {
+          index++;
+          FloodFill(f, Handle_Seams);
+        }
+      }
+      
+      Retract(Handle_Seams);
+
+      for (unsigned int f=0;f<F.rows();f++)
+        for (int j=0;j<3;j++)
+          if (IsRotSeam(f,j))
+            Handle_Seams(f,j)=true;
+
+    }
+
+    
+    
+  
+  };
+}
+template <typename DerivedV,
+  typename DerivedF,
+  typename DerivedM,
+  typename DerivedS,
+  typename DerivedO>
+IGL_INLINE void igl::cut_mesh_from_singularities(const Eigen::PlainObjectBase<DerivedV> &V,
+                                                 const Eigen::PlainObjectBase<DerivedF> &F,
+                                                 const Eigen::PlainObjectBase<DerivedM> &Handle_MMatch,
+                                                 const Eigen::PlainObjectBase<DerivedS> &isSingularity,
+                                                 const Eigen::PlainObjectBase<DerivedS> &singularityIndex,
+                                                 Eigen::PlainObjectBase<DerivedO> &Handle_Seams)
+{
+  igl::MeshCutter< DerivedV, DerivedF, DerivedM, DerivedS, DerivedO> mc(V, F, Handle_MMatch, isSingularity, singularityIndex);
+  mc.cut(Handle_Seams);
+
+}

+ 34 - 0
include/igl/cut_mesh_from_singularities.h

@@ -0,0 +1,34 @@
+#ifndef IGL_CUT_MESH_FROM_SINGULARITIES_H
+#define IGL_CUT_MESH_FROM_SINGULARITIES_H
+#include "igl_inline.h"
+#include <Eigen/Core>
+namespace igl
+{
+  //todo
+  // Creates a quad mesh from a triangular mesh and a set of two directions
+  // per face, using the algorithm described in the paper
+  // "Mixed-Integer Quadrangulation" by D. Bommes, H. Zimmer, L. Kobbelt
+  // ACM SIGGRAPH 2009, Article No. 77 (http://dl.acm.org/citation.cfm?id=1531383)
+  
+  // Inputs:
+  //   Vin        #V by 3 eigen Matrix of mesh vertex 3D positions
+  //   F          #F by 4 eigen Matrix of face (quad) indices
+  //   maxIter    maximum numbers of iterations
+  //   threshold  minimum allowed threshold for non-planarity
+  // Output:
+  //   Vout       #V by 3 eigen Matrix of planar mesh vertex 3D positions
+  //
+  
+  template <typename DerivedV, typename DerivedF, typename DerivedM, typename DerivedS, typename DerivedO>
+  IGL_INLINE void cut_mesh_from_singularities(const Eigen::PlainObjectBase<DerivedV> &V,
+                                                   const Eigen::PlainObjectBase<DerivedF> &F,
+                                                   const Eigen::PlainObjectBase<DerivedM> &Handle_MMatch,
+                                                   const Eigen::PlainObjectBase<DerivedS> &isSingularity,
+                                                   const Eigen::PlainObjectBase<DerivedS> &singularityIndex,
+                                                   Eigen::PlainObjectBase<DerivedO> &Handle_Seams);
+}
+#ifdef IGL_HEADER_ONLY
+#include "cut_mesh_from_singularities.cpp"
+#endif
+
+#endif

+ 66 - 0
include/igl/find_cross_field_singularities.cpp

@@ -0,0 +1,66 @@
+#include "find_cross_field_singularities.h"
+#include "cross_field_missmatch.h"
+
+#include <vector>
+#include "is_border_vertex.h"
+#include "vf.h"
+#include "is_border_vertex.h"
+#include "cross_field_missmatch.h"
+
+
+template <typename DerivedV, typename DerivedF, typename DerivedM, typename DerivedO>
+IGL_INLINE void igl::find_cross_field_singularities(const Eigen::PlainObjectBase<DerivedV> &V,
+                                                    const Eigen::PlainObjectBase<DerivedF> &F,
+                                                    const Eigen::PlainObjectBase<DerivedM> &Handle_MMatch,
+                                                    Eigen::PlainObjectBase<DerivedO> &isSingularity,
+                                                    Eigen::PlainObjectBase<DerivedO> &singularityIndex)
+{
+  std::vector<bool> V_border = igl::is_border_vertex(V,F);
+  
+  std::vector<std::vector<int> > VF;
+  std::vector<std::vector<int> > VFi;
+  igl::vf(V,F,VF,VFi);
+  
+
+  isSingularity.setZero(V.rows(),1);
+  singularityIndex.setZero(V.rows(),1);
+  for (unsigned int vid=0;vid<V.rows();vid++)
+  {
+    ///check that is on border..
+    if (V_border[vid])
+      return;
+    
+    int missmatch=0;
+    for (unsigned int i=0;i<VF[vid].size();i++)
+    {
+      // look for the vertex
+      int j=-1;
+      for (unsigned z=0; z<3; ++z)
+        if (F(VF[vid][i],z) == vid)
+          j=z;
+      assert(j!=-1);
+      
+      missmatch+=Handle_MMatch(VF[vid][i],j);
+    }
+    missmatch=missmatch%4;
+    
+    isSingularity(vid)=(missmatch!=0);
+    singularityIndex(vid)=missmatch;
+  }
+  
+
+}
+
+template <typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::find_cross_field_singularities(const Eigen::PlainObjectBase<DerivedV> &V,
+                                                    const Eigen::PlainObjectBase<DerivedF> &F,
+                                                    const Eigen::PlainObjectBase<DerivedV> &PD1,
+                                                    const Eigen::PlainObjectBase<DerivedV> &PD2,
+                                                    Eigen::PlainObjectBase<DerivedO> &isSingularity,
+                                                    Eigen::PlainObjectBase<DerivedO> &singularityIndex)
+{
+
+  Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 3> Handle_MMatch;
+  igl::cross_field_missmatch<DerivedV, DerivedF, DerivedO>(V, F, PD1, PD2, Handle_MMatch);
+  igl::find_cross_field_singularities(V, F, Handle_MMatch, isSingularity, singularityIndex);
+}

+ 44 - 0
include/igl/find_cross_field_singularities.h

@@ -0,0 +1,44 @@
+#ifndef IGL_FIND_CROSS_FIELD_SINGULARITIES_H
+#define IGL_FIND_CROSS_FIELD_SINGULARITIES_H
+#include "igl_inline.h"
+#include <Eigen/Core>
+namespace igl
+{
+  //todo
+  // Creates a quad mesh from a triangular mesh and a set of two directions
+  // per face, using the algorithm described in the paper
+  // "Mixed-Integer Quadrangulation" by D. Bommes, H. Zimmer, L. Kobbelt
+  // ACM SIGGRAPH 2009, Article No. 77 (http://dl.acm.org/citation.cfm?id=1531383)
+  
+  // Inputs:
+  //   Vin        #V by 3 eigen Matrix of mesh vertex 3D positions
+  //   F          #F by 4 eigen Matrix of face (quad) indices
+  //   maxIter    maximum numbers of iterations
+  //   threshold  minimum allowed threshold for non-planarity
+  // Output:
+  //   Vout       #V by 3 eigen Matrix of planar mesh vertex 3D positions
+  //
+  
+  
+  template <typename DerivedV, typename DerivedF, typename DerivedM, typename DerivedO>
+  IGL_INLINE void find_cross_field_singularities(const Eigen::PlainObjectBase<DerivedV> &V,
+                                                 const Eigen::PlainObjectBase<DerivedF> &F,
+                                                 const Eigen::PlainObjectBase<DerivedM> &Handle_MMatch,
+                                                 Eigen::PlainObjectBase<DerivedO> &isSingularity,
+                                                 Eigen::PlainObjectBase<DerivedO> &singularityIndex);
+
+  
+  // TODO: this returns singularity index modulo 4. It may need to be modified to cover indices
+  template <typename DerivedV, typename DerivedF, typename DerivedO>
+  IGL_INLINE void find_cross_field_singularities(const Eigen::PlainObjectBase<DerivedV> &V,
+                                                 const Eigen::PlainObjectBase<DerivedF> &F,
+                                                 const Eigen::PlainObjectBase<DerivedV> &PD1,
+                                                 const Eigen::PlainObjectBase<DerivedV> &PD2,
+                                                 Eigen::PlainObjectBase<DerivedO> &isSingularity,
+                                                 Eigen::PlainObjectBase<DerivedO> &singularityIndex);
+}
+#ifdef IGL_HEADER_ONLY
+#include "find_cross_field_singularities.cpp"
+#endif
+
+#endif

+ 1 - 0
include/igl/list_to_matrix.cpp

@@ -121,4 +121,5 @@ template bool igl::list_to_matrix<int, Eigen::PlainObjectBase<Eigen::Matrix<int,
 template bool igl::list_to_matrix<double, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > >(std::vector<std::vector<double, std::allocator<double> >, std::allocator<std::vector<double, std::allocator<double> > > > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);
 template bool igl::list_to_matrix<int, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > >(std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&);
 template bool igl::list_to_matrix<double, Eigen::Matrix<double, 1, -1, 1, 1, -1> >(std::vector<double, std::allocator<double> > const&, Eigen::Matrix<double, 1, -1, 1, 1, -1>&);
+template bool igl::list_to_matrix<double, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 2, 0, -1, 2> > >(std::__1::vector<std::__1::vector<double, std::__1::allocator<double> >, std::__1::allocator<std::__1::vector<double, std::__1::allocator<double> > > > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 2, 0, -1, 2> >&);
 #endif

+ 7 - 7
include/igl/local_basis.cpp

@@ -32,14 +32,14 @@ IGL_INLINE void igl::local_basis(
 
   for (unsigned i=0;i<F.rows();++i)
   {
-    RowVector3d v1 = (V.row(F(i,1)) - V.row(F(i,0))).normalized();
-    RowVector3d t = V.row(F(i,2)) - V.row(F(i,0));
-    RowVector3d v3 = v1.cross(t).normalized();
-    RowVector3d v2 = v1.cross(v3).normalized();
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v1 = (V.row(F(i,1)) - V.row(F(i,0))).normalized();
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> t = V.row(F(i,2)) - V.row(F(i,0));
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v3 = v1.cross(t).normalized();
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v2 = v1.cross(v3).normalized();
 
-    B1.row(i) = v1;
-    B2.row(i) = v2;
-    B3.row(i) = v3;
+      B1.row(i) = v1;
+      B2.row(i) = v2;
+      B3.row(i) = v3;
   }
 }
 

+ 230 - 0
include/igl/planarize_quad_mesh.cpp

@@ -0,0 +1,230 @@
+#include "planarize_quad_mesh.h"
+#include "quad_planarity.h"
+#include <Eigen/Sparse>
+
+namespace igl
+{
+  template <typename DerivedV, typename DerivedF>
+  class PlanarizerShapeUp
+  {
+  protected:
+    // number of faces, number of vertices
+    long numV, numF;
+    // references to the input faces and vertices
+    const Eigen::PlainObjectBase<DerivedV> &Vin;
+    const Eigen::PlainObjectBase<DerivedF> &Fin;
+    
+    // vector consisting of the vertex positions stacked: [x;y;z;x;y;z...]
+    // vector consisting of a weight per face (currently all set to 1)
+    // vector consisting of the projected face vertices (might be different for the same vertex belonging to different faces)
+    Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> Vv, weightsSqrt, P;
+    
+    // Matrices as in the paper
+    // Q: lhs matrix
+    // Ni: matrix that subtracts the mean of a face from the 4 vertices of a face
+    Eigen::SparseMatrix<typename DerivedV::Scalar > Q, Ni;
+    Eigen::SimplicialLDLT<Eigen::SparseMatrix<typename DerivedV::Scalar > > solver;
+    
+    int maxIter;
+    double threshold;
+    const int ni = 4;
+    
+    // Matrix assemblers
+    void assembleQ();
+    void assembleP();
+    void assembleNi();
+
+    // Selects out of Vv the 4 vertices belonging to face fi
+    void assembleSelector(int fi,
+                          Eigen::SparseMatrix<typename DerivedV::Scalar > &S);
+    
+    
+  public:
+    // Init - assemble stacked vector and lhs matrix, factorize
+    inline PlanarizerShapeUp(const Eigen::PlainObjectBase<DerivedV> &V_,
+                             const Eigen::PlainObjectBase<DerivedF> &F_,
+                             const int maxIter_,
+                             const double &threshold_);
+    // Planarization - output to Vout
+    inline void planarize(Eigen::PlainObjectBase<DerivedV> &Vout);
+  };
+}
+
+//Implementation
+
+template <typename DerivedV, typename DerivedF>
+inline igl::PlanarizerShapeUp<DerivedV, DerivedF>::PlanarizerShapeUp(const Eigen::PlainObjectBase<DerivedV> &V_,
+                                                                     const Eigen::PlainObjectBase<DerivedF> &F_,
+                                                                     const int maxIter_,
+                                                                     const double &threshold_):
+Vin(V_),
+Fin(F_),
+maxIter(maxIter_),
+threshold(threshold_),
+numF(F_.rows()),
+numV(V_.rows()),
+weightsSqrt(Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1>::Ones(numF,1))
+{
+  // assemble stacked vertex position vector
+  Vv.setZero(3*numV,1);
+  for (int i =0;i<numV;++i)
+    Vv.segment(3*i,3) = Vin.row(i);
+  // assemble and factorize lhs matrix
+  assembleQ();
+};
+
+template <typename DerivedV, typename DerivedF>
+inline void igl::PlanarizerShapeUp<DerivedV, DerivedF>::assembleQ()
+{
+  std::vector<Eigen::Triplet<typename DerivedV::Scalar> > tripletList;
+  
+  // assemble the Ni matrix
+  assembleNi();
+  
+  for (int fi = 0; fi< numF; fi++)
+  {
+    Eigen::SparseMatrix<typename DerivedV::Scalar > Sfi;
+    assembleSelector(fi, Sfi);
+    
+    // the final matrix per face
+    Eigen::SparseMatrix<typename DerivedV::Scalar > Qi = weightsSqrt(fi)*Ni*Sfi;
+    // put it in the correct block of Q
+    // todo: this can be made faster by omitting the selector matrix
+    for (int k=0; k<Qi.outerSize(); ++k)
+      for (typename Eigen::SparseMatrix<typename DerivedV::Scalar >::InnerIterator it(Qi,k); it; ++it)
+      {
+        typename DerivedV::Scalar val = it.value();
+        int row = it.row();
+        int col = it.col();
+        tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(row+3*ni*fi,col,val));
+      }
+  }
+  
+  Q.resize(3*ni*numF,3*numV);
+  Q.setFromTriplets(tripletList.begin(), tripletList.end());
+  // the actual lhs matrix is Q'*Q
+  // prefactor that matrix
+  solver.compute(Q.transpose()*Q);
+  if(solver.info()!=Eigen::Success)
+  {
+    std::cerr << "Cholesky failed - PlanarizerShapeUp.cpp" << std::endl;
+    assert(0);
+  }
+}
+
+template <typename DerivedV, typename DerivedF>
+inline void igl::PlanarizerShapeUp<DerivedV, DerivedF>::assembleNi()
+{
+  std::vector<Eigen::Triplet<typename DerivedV::Scalar>> tripletList;
+  for (int ii = 0; ii< ni; ii++)
+  {
+    for (int jj = 0; jj< ni; jj++)
+    {
+      tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*ii+0,3*jj+0,-1./ni));
+      tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*ii+1,3*jj+1,-1./ni));
+      tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*ii+2,3*jj+2,-1./ni));
+    }
+    tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*ii+0,3*ii+0,1.));
+    tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*ii+1,3*ii+1,1.));
+    tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*ii+2,3*ii+2,1.));
+  }
+  Ni.resize(3*ni,3*ni);
+  Ni.setFromTriplets(tripletList.begin(), tripletList.end());
+}
+
+//assumes V stacked [x;y;z;x;y;z...];
+template <typename DerivedV, typename DerivedF>
+inline void igl::PlanarizerShapeUp<DerivedV, DerivedF>::assembleSelector(int fi,
+                                                                            Eigen::SparseMatrix<typename DerivedV::Scalar > &S)
+{
+  
+  std::vector<Eigen::Triplet<typename DerivedV::Scalar>> tripletList;
+  for (int fvi = 0; fvi< ni; fvi++)
+  {
+    int vi = Fin(fi,fvi);
+    tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*fvi+0,3*vi+0,1.));
+    tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*fvi+1,3*vi+1,1.));
+    tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*fvi+2,3*vi+2,1.));
+  }
+  
+  S.resize(3*ni,3*numV);
+  S.setFromTriplets(tripletList.begin(), tripletList.end());
+  
+}
+
+//project all faces to their closest planar face
+template <typename DerivedV, typename DerivedF>
+inline void igl::PlanarizerShapeUp<DerivedV, DerivedF>::assembleP()
+{
+  P.setZero(3*ni*numF);
+  for (int fi = 0; fi< numF; fi++)
+  {
+    // todo: this can be made faster by omitting the selector matrix
+    Eigen::SparseMatrix<typename DerivedV::Scalar > Sfi;
+    assembleSelector(fi, Sfi);
+    Eigen::SparseMatrix<typename DerivedV::Scalar > NSi = Ni*Sfi;
+    
+    Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> Vi = NSi*Vv;
+    Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> CC(3,ni);
+    for (int i = 0; i <ni; ++i)
+      CC.col(i) = Vi.segment(3*i, 3);
+    Eigen::Matrix<typename DerivedV::Scalar, 3, 3> C = CC*CC.transpose();
+    
+    Eigen::EigenSolver<Eigen::Matrix<typename DerivedV::Scalar, 3, 3>> es(C);
+    // the real() is for compilation purposes
+    Eigen::Matrix<typename DerivedV::Scalar, 3, 1> lambda = es.eigenvalues().real();
+    Eigen::Matrix<typename DerivedV::Scalar, 3, 3> U = es.eigenvectors().real();
+    int min_i;
+    lambda.cwiseAbs().minCoeff(&min_i);
+    U.col(min_i).setZero();
+    Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> PP = U*U.transpose()*CC;
+    for (int i = 0; i <ni; ++i)
+      P.segment(3*ni*fi+3*i, 3) =  weightsSqrt[fi]*PP.col(i);
+    
+  }
+}
+
+
+template <typename DerivedV, typename DerivedF>
+inline void igl::PlanarizerShapeUp<DerivedV, DerivedF>::planarize(Eigen::PlainObjectBase<DerivedV> &Vout)
+{
+  Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> planarity;
+  Vout = Vin;
+  
+  for (int iter =0; iter<maxIter; ++iter)
+  {
+    igl::quad_planarity(Vout, Fin, planarity);
+    typename DerivedV::Scalar nonPlanarity = planarity.cwiseAbs().maxCoeff();
+    std::cerr<<"iter #"<<iter<<": max non-planarity: "<<nonPlanarity<<std::endl;
+    if (nonPlanarity<threshold)
+      break;
+    assembleP();
+    Vv = solver.solve(Q.transpose()*P);
+    if(solver.info()!=Eigen::Success)
+    {
+      std::cerr << "Linear solve failed - PlanarizerShapeUp.cpp" << std::endl;
+      assert(0);
+    }
+    for (int i =0;i<numV;++i)
+      Vout.row(i) << Vv.segment(3*i,3).transpose();
+  }
+  // set the mean of Vout to the mean of Vin
+  Eigen::Matrix<typename DerivedV::Scalar, 1, 3> oldMean, newMean;
+  oldMean = Vin.colwise().mean();
+  newMean = Vout.colwise().mean();
+  Vout.rowwise() += (oldMean - newMean);
+  
+};
+
+  
+
+template <typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::planarize_quad_mesh(const Eigen::PlainObjectBase<DerivedV> &Vin,
+                                    const Eigen::PlainObjectBase<DerivedF> &Fin,
+                                    const int maxIter,
+                                    const double &threshold,
+                                    Eigen::PlainObjectBase<DerivedV> &Vout)
+{
+  PlanarizerShapeUp<DerivedV, DerivedF> planarizer(Vin, Fin, maxIter, threshold);
+  planarizer.planarize(Vout);
+}

+ 39 - 0
include/igl/planarize_quad_mesh.h

@@ -0,0 +1,39 @@
+#ifndef IGL_PLANARIZE_QUAD_MESH_H
+#define IGL_PLANARIZE_QUAD_MESH_H
+#include "igl_inline.h"
+#include <Eigen/Core>
+namespace igl
+{
+  // Planarizes a given quad mesh using the algorithm described in the paper
+  // "Shape-Up: Shaping Discrete Geometry with Projections" by S. Bouaziz,
+  // M. Deuss, Y. Schwartzburg, T. Weise, M. Pauly, Computer Graphics Forum,
+  // Volume 31, Issue 5, August 2012, p. 1657-1667
+  // (http://dl.acm.org/citation.cfm?id=2346802).
+  // The algorithm iterates between projecting each quad to its closest planar
+  // counterpart and stitching those quads together via a least squares
+  // optimization. It stops whenever all quads' non-planarity is less than a
+  // given threshold (suggested value: 0.01), or a maximum number of iterations
+  // is reached.
+
+  
+  // Inputs:
+  //   Vin        #V by 3 eigen Matrix of mesh vertex 3D positions
+  //   F          #F by 4 eigen Matrix of face (quad) indices
+  //   maxIter    maximum numbers of iterations
+  //   threshold  minimum allowed threshold for non-planarity
+  // Output:
+  //   Vout       #V by 3 eigen Matrix of planar mesh vertex 3D positions
+  //
+  
+  template <typename DerivedV, typename DerivedF>
+  IGL_INLINE void planarize_quad_mesh(const Eigen::PlainObjectBase<DerivedV> &Vin,
+                                      const Eigen::PlainObjectBase<DerivedF> &F,
+                                      const int maxIter,
+                                      const double &threshold,
+                                      Eigen::PlainObjectBase<DerivedV> &Vout);
+}
+#ifdef IGL_HEADER_ONLY
+#  include "planarize_quad_mesh.cpp"
+#endif
+
+#endif

+ 15 - 7
include/igl/pos.h

@@ -16,14 +16,19 @@
 namespace igl 
 {
   // Pos - Fake halfedge for fast and easy navigation on triangle meshes with VT and TT adj
-template <typename S>
+//template <typename S>
+  template <typename DerivedF>
   class Pos
   {
   public:
     // Init the pos by specifying Face,Edge Index and Orientation
-    Pos(const Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic>* F, 
-        Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic>* FF, 
-        Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic>* FFi, 
+    Pos(
+//        const Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic>* F,
+//        Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic>* FF, 
+//        Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic>* FFi, 
+        const Eigen::PlainObjectBase<DerivedF>* F,
+        const Eigen::PlainObjectBase<DerivedF>* FF,
+        const Eigen::PlainObjectBase<DerivedF>* FFi,
         int fi,
         int ei,
         bool reverse = false
@@ -144,9 +149,12 @@ template <typename S>
     int ei;
     bool reverse;
     
-    const Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic>*     F;
-    const Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic>*     FF;
-    const Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic>*     FFi;
+    const Eigen::PlainObjectBase<DerivedF>* F;
+    const Eigen::PlainObjectBase<DerivedF>* FF;
+    const Eigen::PlainObjectBase<DerivedF>* FFi;
+//    const Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic>*     F;
+//    const Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic>*     FF;
+//    const Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic>*     FFi;
   };
   
 }

+ 30 - 0
include/igl/quad_planarity.cpp

@@ -0,0 +1,30 @@
+#include "quad_planarity.h"
+#include <Eigen/Geometry>
+
+template <typename DerivedV, typename DerivedF, typename DerivedP>
+IGL_INLINE void igl::quad_planarity(
+  const Eigen::PlainObjectBase<DerivedV>& V,
+  const Eigen::PlainObjectBase<DerivedF>& F,
+  Eigen::PlainObjectBase<DerivedP> & P)
+{
+  int nf = F.rows();
+  P.setZero(nf,1);
+  for (int i =0; i<nf; ++i)
+  {
+    const Eigen::Matrix<typename DerivedV::Scalar,1,3> &v1 = V.row(F(i,0));
+    const Eigen::Matrix<typename DerivedV::Scalar,1,3> &v2 = V.row(F(i,1));
+    const Eigen::Matrix<typename DerivedV::Scalar,1,3> &v3 = V.row(F(i,2));
+    const Eigen::Matrix<typename DerivedV::Scalar,1,3> &v4 = V.row(F(i,3));
+    Eigen::Matrix<typename DerivedV::Scalar,1,3> diagCross=(v3-v1).cross(v4-v2);
+    typename Eigen::PlainObjectBase<DerivedV>::Scalar denom = diagCross.norm()*(((v3-v1).norm()+(v4-v2).norm())/2);
+    if (fabs(denom)<1e-8)
+      //degenerate quad is still planar
+      P[i] = 0;
+    else
+      P[i] = (diagCross.dot(v2-v1)/denom);
+  }
+}
+
+#ifndef IGL_HEADER_ONLY
+// Explicit template specialization
+#endif

+ 25 - 0
include/igl/quad_planarity.h

@@ -0,0 +1,25 @@
+#ifndef IGL_QUAD_PLANARITY_H
+#define IGL_QUAD_PLANARITY_H
+#include "igl_inline.h"
+#include <Eigen/Core>
+namespace igl
+{
+  // Compute planarity of the faces of a quad mesh
+  // Inputs:
+  //   V  #V by 3 eigen Matrix of mesh vertex 3D positions
+  //   F  #F by 4 eigen Matrix of face (quad) indices
+  // Output:
+  //   P  #F by 1 eigen Matrix of mesh face (quad) planarities
+  //
+  template <typename DerivedV, typename DerivedF, typename DerivedP>
+  IGL_INLINE void quad_planarity(
+    const Eigen::PlainObjectBase<DerivedV>& V,
+    const Eigen::PlainObjectBase<DerivedF>& F,
+    Eigen::PlainObjectBase<DerivedP> & P);
+}
+
+#ifdef IGL_HEADER_ONLY
+#  include "quad_planarity.cpp"
+#endif
+
+#endif

+ 1 - 0
include/igl/readOBJ.cpp

@@ -388,4 +388,5 @@ template bool igl::readOBJ<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matr
 template bool igl::readOBJ<Eigen::Matrix<double, -1, 3, 1, -1, 3>, Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1>, Eigen::Matrix<double, -1, 2, 1, -1, 2> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 2, 1, -1, 2> >&, Eigen::PlainObjectBase<Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> >&);
 template bool igl::readOBJ<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);
 template bool igl::readOBJ<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3> >(std::string, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&);
+template bool igl::readOBJ<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, 2, 0, -1, 2> >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 2, 0, -1, 2> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&);
 #endif

+ 8 - 2
include/igl/writeOFF.cpp

@@ -36,9 +36,15 @@ IGL_INLINE bool igl::writeOFF(
       (double)V(i,2));
   }
   
+//  for (int i = 0; i < F.rows(); i++)
+//      fprintf (fp, "3 %d %d %d\n", F(i,0), F(i,1), F(i,2));
   for (int i = 0; i < F.rows(); i++)
-      fprintf (fp, "3 %d %d %d\n", F(i,0), F(i,1), F(i,2));
-  
+  {
+    fprintf (fp, "%d", F.cols());
+    for (int j = 0; j < F.cols(); j++)
+      fprintf (fp, " %d", F(i,j));
+    fprintf (fp, "\n");
+  }
   fclose (fp);
   return true;
 }

+ 1 - 1
tutorial/103_DrawMesh/main.cpp

@@ -11,6 +11,6 @@ int main(int argc, char *argv[])
 
   // Plot the mesh
   igl::Viewer viewer;
-  viewer.draw_mesh(V, F);
+  viewer.set_mesh(V, F);
   viewer.launch();
 }

+ 15 - 0
tutorial/504_NRosyDesign/CMakeLists.txt

@@ -0,0 +1,15 @@
+cmake_minimum_required(VERSION 2.6)
+project(504_NRoSyDesign)
+
+include("../CMakeLists.shared")
+
+find_package(LIBCOMISO REQUIRED)
+
+include_directories( ${LIBCOMISO_INCLUDE_DIR} )
+
+set(SOURCES
+${PROJECT_SOURCE_DIR}/main.cpp
+)
+
+add_executable(${CMAKE_PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${CMAKE_PROJECT_NAME} ${SHARED_LIBRARIES} ${LIBCOMISO_LIBRARY})

+ 131 - 0
tutorial/504_NRosyDesign/main.cpp

@@ -0,0 +1,131 @@
+#include <igl/readOFF.h>
+#include <igl/viewer/Viewer.h>
+#include <igl/local_basis.h>
+#include <igl/barycenter.h>
+#include <igl/avg_edge_length.h>
+#include <igl/comiso/nrosy.h>
+
+using namespace Eigen;
+using namespace std;
+
+// Mesh
+Eigen::MatrixXd V;
+Eigen::MatrixXi F;
+
+// Constrained faces id
+Eigen::VectorXi b;
+
+// Cosntrained faces representative vector
+Eigen::MatrixXd bc;
+
+// Degree of the N-RoSy field
+int N = 4;
+
+// Converts a representative vector per face in the full set of vectors that describe
+// an N-RoSy field
+void representative_to_nrosy(const MatrixXd& V, const MatrixXi& F, const MatrixXd& R, const int N, MatrixXd& Y)
+{
+  MatrixXd B1, B2, B3;
+  
+  igl::local_basis(V,F,B1,B2,B3);
+  
+  Y.resize(F.rows()*N,3);
+  for (unsigned i=0;i<F.rows();++i)
+  {
+    double x = R.row(i) * B1.row(i).transpose();
+    double y = R.row(i) * B2.row(i).transpose();
+    double angle = atan2(y,x);
+    
+    for (unsigned j=0; j<N;++j)
+    {
+      double anglej = angle + 2*M_PI*double(j)/double(N);
+      double xj = cos(anglej);
+      double yj = sin(anglej);
+      Y.row(i*N+j) = xj * B1.row(i) + yj * B2.row(i);
+    }
+  }
+}
+
+// Plots the mesh with an N-RoSy field and its singularities on top
+// The constrained faces (b) are colored in red.
+void plot_mesh_nrosy(igl::Viewer& viewer, MatrixXd& V, MatrixXi& F, int N, MatrixXd& PD1, VectorXd& S, VectorXi& b)
+{
+  // Clear the mesh
+  viewer.clear_mesh();
+  viewer.set_mesh(V,F);
+  
+  // Expand the representative vectors in the full vector set and plot them as lines
+  double avg = igl::avg_edge_length(V, F);
+  MatrixXd Y;
+  representative_to_nrosy(V, F, PD1, N, Y);
+  
+  MatrixXd B;
+  igl::barycenter(V,F,B);
+  
+  MatrixXd Be(B.rows()*N,3);
+  for(unsigned i=0; i<B.rows();++i)
+    for(unsigned j=0; j<N; ++j)
+      Be.row(i*N+j) = B.row(i);
+  
+  viewer.add_edges(Be,Be+Y*(avg/2),RowVector3d(0,0,1));
+  
+  // Plot the singularities as colored dots (red for negative, blue for positive)
+  for (unsigned i=0; i<S.size();++i)
+  {
+    if (S(i) < -0.001)
+      viewer.add_points(V.row(i),RowVector3d(1,0,0));
+    else if (S(i) > 0.001)
+      viewer.add_points(V.row(i),RowVector3d(0,1,0));
+  }
+  
+  // Highlight in red the constrained faces
+  MatrixXd C = MatrixXd::Constant(F.rows(),3,1);
+  for (unsigned i=0; i<b.size();++i)
+    C.row(b(i)) << 1, 0, 0;
+  viewer.set_colors(C);
+}
+
+  // It allows to change the degree of the field when a number is pressed
+bool key_down(igl::Viewer& viewer, unsigned char key, int modifier)
+{
+  if (key >= '1' && key <= '9')
+    N = key - '0';
+
+  MatrixXd R;
+  VectorXd S;
+  
+  igl::nrosy(V,F,b,bc,VectorXi(),VectorXd(),MatrixXd(),N,0.5,R,S);
+  plot_mesh_nrosy(viewer,V,F,N,R,S,b);
+  
+  return false;
+}
+
+int main(int argc, char *argv[])
+{
+  using namespace std;
+  using namespace Eigen;
+
+  // Load a mesh in OFF format
+  igl::readOFF("../shared/bumpy.off", V, F);
+
+  // Threshold faces with high anisotropy
+  b.resize(1);
+  b << 0;
+  bc.resize(1,3);
+  bc << 1,1,1;
+
+  igl::Viewer viewer;
+
+  // Interpolate the field and plot
+  key_down(viewer, '4', 0);
+  
+  // Plot the mesh
+  viewer.set_mesh(V, F);
+  viewer.callback_key_down = &key_down;
+
+  // Disable wireframe
+  viewer.options.show_lines = false;
+
+  // Launch the viewer
+  viewer.launch();
+}

+ 15 - 0
tutorial/505_MIQ/CMakeLists.txt

@@ -0,0 +1,15 @@
+cmake_minimum_required(VERSION 2.6)
+project(505_MIQ)
+
+include("../CMakeLists.shared")
+
+find_package(LIBCOMISO REQUIRED)
+
+include_directories( ${LIBCOMISO_INCLUDE_DIR} )
+
+set(SOURCES
+${PROJECT_SOURCE_DIR}/main.cpp
+)
+
+add_executable(${CMAKE_PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${CMAKE_PROJECT_NAME} ${SHARED_LIBRARIES} ${LIBCOMISO_LIBRARY})

+ 137 - 0
tutorial/505_MIQ/main.cpp

@@ -0,0 +1,137 @@
+#define IGL_HEADER_ONLY
+#include <igl/readOBJ.h>
+#include <igl/viewer/Viewer.h>
+#include <igl/comiso/mixed_integer_quadrangulate.h>
+#include <igl/barycenter.h>
+#include <igl/avg_edge_length.h>
+#include <sstream>
+
+
+void line_texture(Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic> &texture_R,
+                  Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic> &texture_G,
+                  Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic> &texture_B)
+  {
+    unsigned size = 128;
+    unsigned size2 = size/2;
+    unsigned lineWidth = 3;
+    texture_R.setConstant(size, size, 255);
+    for (unsigned i=0; i<size; ++i)
+      for (unsigned j=size2-lineWidth; j<=size2+lineWidth; ++j)
+        texture_R(i,j) = 0;
+    for (unsigned i=size2-lineWidth; i<=size2+lineWidth; ++i)
+      for (unsigned j=0; j<size; ++j)
+        texture_R(i,j) = 0;
+
+    texture_G = texture_R;
+    texture_B = texture_R;
+  }
+
+
+bool readPolyVf(const char *fname,
+                Eigen::VectorXi &isConstrained,
+                std::vector<Eigen::MatrixXd> &polyVF)
+{
+  FILE *fp = fopen(fname,"r");
+  if (!fp)
+    return false;
+  int degree, numF;
+  if (fscanf(fp,"%d %d", &degree, &numF) !=2)
+    return false;
+  polyVF.resize(degree, Eigen::MatrixXd::Zero(numF, 3));
+  isConstrained.setZero(numF,1);
+  int vali; float u0,u1,u2;
+  for (int i = 0; i<numF; ++i)
+  {
+    if (fscanf(fp,"%d", &vali)!=1)
+      return false;
+    isConstrained[i] = vali;
+    for (int j = 0; j<degree; ++j)
+    {
+      if (fscanf(fp,"%g %g %g", &u0, &u1, &u2) !=3)
+        return false;
+      polyVF[j](i,0) = u0;
+      polyVF[j](i,1) = u1;
+      polyVF[j](i,2) = u2;
+    }
+  }
+  fclose(fp);
+  return true;
+}
+
+void writePolyVf(const char *fname,
+                 const Eigen::VectorXi &isConstrained,
+                 const std::vector<Eigen::MatrixXd> &polyVF)
+{
+  int numF = polyVF[0].rows();
+  int degree = polyVF.size();
+  FILE *fp = fopen(fname,"w");
+  fprintf(fp,"%d %d\n", degree,numF);
+  for (int i = 0; i<numF; ++i)
+  {
+    fprintf(fp,"%d ", isConstrained[i]);
+    for (int j = 0; j<degree; ++j)
+      fprintf(fp,"%.15g %.15g %.15g ", polyVF[j](i,0), polyVF[j](i,1), polyVF[j](i,2));
+    fprintf(fp, "\n");
+  }
+  fclose(fp);
+
+}
+
+
+int main(int argc, char *argv[])
+{
+  Eigen::MatrixXd V;
+  Eigen::MatrixXi F;
+  // Load a mesh in OFF format
+  igl::readOBJ("../shared/lilium.obj", V, F);
+
+
+  // Load a frame field
+  Eigen::VectorXi isConstrained;
+  std::vector<Eigen::MatrixXd> polyVF;
+  readPolyVf("../shared/lilium.crossfield", isConstrained, polyVF);
+
+  Eigen::MatrixXd UV;
+  Eigen::MatrixXi FUV;
+
+  double gradientSize = 50;
+  double quadIter = 0;
+  double stiffness = 5.0;
+  bool directRound = 1;
+  igl::mixed_integer_quadrangulate(V,
+                                 F,
+                                 polyVF[0],
+                                 polyVF[1],
+                                 UV,
+                                 FUV,
+                                 gradientSize,
+                                 stiffness,
+                                 directRound,
+                                 quadIter);
+
+
+  // Face barycenters
+  Eigen::MatrixXd MF;
+  igl::barycenter(V, F, MF);
+
+  double scale =  .5*igl::avg_edge_length(V, F);
+
+  // Plot the mesh
+  igl::Viewer viewer;
+  viewer.set_mesh(V, F);
+
+  // Plot the field
+  viewer.add_edges (MF, MF+scale*polyVF[0],Eigen::RowVector3d(1,0,1));
+  viewer.add_edges (MF, MF+scale*polyVF[1],Eigen::RowVector3d(1,0,1));
+  viewer.set_uv(UV,FUV);
+  viewer.options.show_texture = true;
+
+  Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic> texture_R, texture_G, texture_B;
+  line_texture(texture_R, texture_G, texture_B);
+  viewer.set_texture(texture_R, texture_B, texture_G);
+  // Increase the thickness of the lines
+  viewer.options.line_width = 2.0f;
+
+  // Launch the viewer
+  viewer.launch();
+}

+ 40 - 0
tutorial/cmake/FindLIBCOMISO.cmake

@@ -0,0 +1,40 @@
+# - Try to find the LIBCOMISO library
+# Once done this will define
+#
+#  LIBCOMISO_FOUND - system has LIBCOMISO
+#  LIBCOMISO_INCLUDE_DIR - the LIBCOMISO include directory
+#  LIBCOMISO_LIBRARY - the LIBCOMISO binary lib
+
+FIND_PATH(LIBCOMISO_INCLUDE_DIR CoMISo/Solver/ConstrainedSolver.hh
+   /usr/include
+   /usr/local/include
+   $ENV{LIBCOMISOROOT}/include
+   $ENV{LIBCOMISO_ROOT}/include
+   $ENV{LIBCOMISO_DIR}/include
+   $ENV{LIBCOMISO_DIR}/inc
+   ${PROJECT_SOURCE_DIR}/../CoMISo/
+   ${PROJECT_SOURCE_DIR}/../CoMISo/include
+   /Users/daniele/Dropbox/igl/MIQ/src
+)
+
+FIND_LIBRARY(LIBCOMISO_LIBRARY NAMES CoMISo
+  PATHS
+    /usr/local
+    /usr/X11
+    /usr
+    /
+    ${PROJECT_SOURCE_DIR}/../CoMISo/
+    ${PROJECT_SOURCE_DIR}/../CoMISo/build
+    /Users/daniele/Dropbox/igl/MIQ/src/CoMISo/build
+)
+
+if(LIBCOMISO_INCLUDE_DIR AND LIBCOMISO_LIBRARY)
+
+   set(LIBCOMISO_INCLUDE_DIR ${LIBCOMISO_INCLUDE_DIR} ${LIBCOMISO_INCLUDE_DIR}/CoMISo/gmm/include)
+
+   add_definitions(-DINCLUDE_TEMPLATES)
+   message(STATUS "Found LIBCOMISO: ${LIBCOMISO_INCLUDE_DIR} ${LIBCOMISO_LIBRARY}")
+   set(LIBCOMISO_FOUND TRUE)
+else(LIBCOMISO_INCLUDE_DIR)
+   message(FATAL_ERROR "could NOT find LIBCOMISO")
+endif(LIBCOMISO_INCLUDE_DIR AND LIBCOMISO_LIBRARY)

+ 54 - 0
tutorial/cmake/FindMATLAB.cmake

@@ -0,0 +1,54 @@
+#
+# Try to find a MATLAB installation
+# Once done this will define
+#
+# MATLAB_FOUND
+# MATLAB_INCLUDE_DIR
+# MATLAB_LIBRARIES
+#
+
+FIND_PATH(MATLAB_INCLUDE_DIR engine.h
+      PATHS
+      /Applications/MATLAB_R2012b.app/extern/include
+      /Applications/MATLAB_R2013a.app/extern/include
+      /Applications/MATLAB_R2013b.app/extern/include
+      /Applications/MATLAB_R2014a.app/extern/include
+      /Applications/MATLAB_R2014b.app/extern/include
+      NO_DEFAULT_PATH)
+
+FIND_LIBRARY(MATLAB_LIBRARY1 eng
+  PATHS
+    /Applications/MATLAB_R2012b.app/bin/maci64
+    /Applications/MATLAB_R2013a.app/bin/maci64
+    /Applications/MATLAB_R2013b.app/bin/maci64
+    /Applications/MATLAB_R2014a.app/bin/maci64
+    /Applications/MATLAB_R2014b.app/bin/maci64
+  PATH_SUFFIXES`
+    a
+    lib64
+    lib
+    dylib
+    NO_DEFAULT_PATH
+)
+
+FIND_LIBRARY(MATLAB_LIBRARY2 mx
+  PATHS
+    /Applications/MATLAB_R2012b.app/bin/maci64/
+    /Applications/MATLAB_R2013a.app/bin/maci64/
+    /Applications/MATLAB_R2013b.app/bin/maci64/
+    /Applications/MATLAB_R2014a.app/bin/maci64/
+    /Applications/MATLAB_R2014b.app/bin/maci64/
+  PATH_SUFFIXES
+    a
+    lib64
+    lib
+    dylib
+    NO_DEFAULT_PATH
+)
+
+if(MATLAB_INCLUDE_DIR AND MATLAB_LIBRARY1 AND MATLAB_LIBRARY2)
+	message(STATUS "Found MATLAB: ${MATLAB_INCLUDE_DIR}")
+  set(MATLAB_LIBRARIES ${MATLAB_LIBRARY1} ${MATLAB_LIBRARY2})
+else(MATLAB_INCLUDE_DIR AND MATLAB_LIBRARY1 AND MATLAB_LIBRARY2)
+	message(FATAL_ERROR "could NOT find MATLAB")
+endif(MATLAB_INCLUDE_DIR AND MATLAB_LIBRARY1 AND MATLAB_LIBRARY2)

+ 1 - 0
tutorial/shared/lilium.crossfield.REMOVED.git-id

@@ -0,0 +1 @@
+7a76795232c55cd71eefe7fc9a3368f9b62bf51c

+ 1 - 0
tutorial/shared/lilium.obj.REMOVED.git-id

@@ -0,0 +1 @@
+1b8b8b556105b6103bd2d77736451f968ba5a823