Kaynağa Gözat

quadrangulation, planarization, various other VF functionalities

Former-commit-id: dacc9124d4496d3180608f2e9e7624a557a19ff0
Olga Diamanti 11 yıl önce
ebeveyn
işleme
f2050e5a81

+ 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

+ 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

+ 1 - 1
include/igl/embree/reorient_facets_raycast.cpp

@@ -10,7 +10,7 @@
 #include "../doublearea.h"
 #include "../random_dir.h"
 #include "../boost/bfs_orient.h"
-#include "orient_outward_ao.h"
+//#include "orient_outward_ao.h"
 #include "EmbreeIntersector.h"
 #include <iostream>
 #include <random>

+ 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

+ 4 - 4
include/igl/local_basis.cpp

@@ -28,10 +28,10 @@ namespace igl
 
     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;

+ 1 - 1
include/igl/min_quad_with_fixed.h

@@ -13,7 +13,7 @@
 #include <Eigen/Core>
 #include <Eigen/Dense>
 #include <Eigen/Sparse>
-#include <Eigen/SparseExtra>
+//#include <Eigen/SparseExtra>
 // Bug in unsupported/Eigen/SparseExtra needs iostream first
 #include <iostream>
 #include <unsupported/Eigen/SparseExtra>

+ 2269 - 0
include/igl/mixed_integer_quadrangulate.cpp

@@ -0,0 +1,2269 @@
+#include "mixed_integer_quadrangulate.h"
+#include "local_basis.h"
+#include "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 <ConstrainedSolver.hh>
+#include <MISolver.hh>
+#include <GMM_Tools.hh>
+//#include "auxmath.h"
+//#include "sparsesystemdata.h"
+#include "doublearea.h"
+#include "per_face_normals.h"
+
+//
+#include "cross_field_missmatch.h"
+#include "comb_frame_field.h"
+#include "cut_mesh_from_singularities.h"
+#include "find_cross_field_singularities.h"
+#include "compute_frame_field_bisectors.h"
+
+#define DEBUGPRINT 0
+
+
+namespace igl {
+  
+  class SparseMatrixData{
+  protected:
+    unsigned int m_nrows;
+    unsigned int m_ncols;
+    vector<unsigned int> m_rowind;
+    vector<unsigned int> m_colind;
+    vector<double>       m_vals;
+    
+  public:
+    unsigned int   nrows()    { return m_nrows      ; }
+    unsigned int   ncols()    { return m_ncols      ; }
+    unsigned int   nentries() { return m_vals.size(); }
+    vector<unsigned int>&  rowind()   { return m_rowind     ; }
+    vector<unsigned int>&  colind()   { return m_colind     ; }
+    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,
+                      vector<int> roundVertices = vector<int>(),
+                      vector<vector<int> > hardFeatures = vector<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(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 MatrixXd& WUV);
+    
+    double Distortion(int f, double h, const MatrixXd& WUV);
+    
+    double LaplaceDistortion(const int f, double h, const MatrixXd& WUV);
+    
+    bool updateStiffeningJacobianDistorsion(double grad_size, const MatrixXd& WUV);
+    
+    inline bool IsFlipped(const Vector2d &uv0,
+                          const Vector2d &uv1,
+                          const Vector2d &uv2);
+    
+    inline bool IsFlipped(const int i, const 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,
+                                                          vector<int> roundVertices,
+                                                          vector<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;
+  cerr << "No vertices to fix, I am fixing the first vertex to the origin!" << 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(vector<int> ids)
+{
+  for (int i = 0; i < ids.size(); ++i)
+  {
+    if (ids[i] < 0 || ids[i] >= V.rows())
+      cerr << "WARNING: Ignored round vertex constraint, vertex " << ids[i] << " does not exist in the mesh." << 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
+  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 = 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 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 MatrixXd& WUV)
+{
+  assert(h > 0);
+  
+  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 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 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 Vector2d &uv0,
+                                                              const Vector2d &uv1,
+                                                              const Vector2d &uv2)
+{
+  Vector2d e0 = (uv1-uv0);
+  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 MatrixXd& WUV)
+{
+  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/mixed_integer_quadrangulate.h

@@ -0,0 +1,63 @@
+#ifndef IGL_MIXED_INTEGER_QUADRANGULATE_H
+#define IGL_MIXED_INTEGER_QUADRANGULATE_H
+#include "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

+ 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;
 }