File: refine.h

package info (click to toggle)
meshlab 2020.09%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 45,124 kB
  • sloc: cpp: 400,238; ansic: 31,952; javascript: 1,578; sh: 387; yacc: 238; lex: 139; python: 86; makefile: 29
file content (1283 lines) | stat: -rw-r--r-- 44,581 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
/***********F*****************************************************************
* VCGLib                                                            o o     *
* Visual and Computer Graphics Library                            o     o   *
*                                                                _   O  _   *
* Copyright(C) 2004-2016                                           \/)\/    *
* Visual Computing Lab                                            /\/|      *
* ISTI - Italian National Research Council                           |      *
*                                                                    \      *
* All rights reserved.                                                      *
*                                                                           *
* This program is free software; you can redistribute it and/or modify      *
* it under the terms of the GNU General Public License as published by      *
* the Free Software Foundation; either version 2 of the License, or         *
* (at your option) any later version.                                       *
*                                                                           *
* This program is distributed in the hope that it will be useful,           *
* but WITHOUT ANY WARRANTY; without even the implied warranty of            *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt)          *
* for more details.                                                         *
*                                                                           *
****************************************************************************/

#ifndef __VCGLIB_REFINE
#define __VCGLIB_REFINE

#include <functional>
#include <map>
#include <vcg/space/sphere3.h>
#include <vcg/space/plane3.h>
#include <vcg/complex/algorithms/clean.h>
#include <vcg/space/texcoord2.h>
#include <vcg/space/triangle3.h>

namespace vcg{
namespace tri{

/* A very short intro about the generic refinement framework,
    the main fuction is the

 template<class MESH_TYPE,class MIDPOINT, class EDGEPRED>
 bool RefineE(MESH_TYPE &m, MIDPOINT mid, EDGEPRED ep,bool RefineSelected=false, CallBackPos *cb = 0)

 You have to provide two functor objects to this, one for deciding what edge has to be spltted and one to decide position and new values for the attributes of the new point.

 for example the minimal EDGEPRED is

 template <class MESH_TYPE, class FLT> class EdgeLen
 {
   public:
     FLT thr2;
     bool operator()(face::Pos<typename MESH_TYPE::FaceType> ep) const
     {
            return SquaredDistance(ep.f->V(ep.z)->P(), ep.f->V1(ep.z)->P())>thr2;
     }
 };

 With a bit of patience you can customize to make also slicing operation.

*/


/* The table which encodes how to subdivide a triangle depending
   on the splitted edges is organized as such:

    TriNum (the first number):    encodes the number of triangles
    TV (the following 4 triples): encodes the resulting triangles where
          0, 1, 2 are the original vertices of the triangles and 3, 4, 5
          (mp01, mp12, mp20) are the midpoints of the three edges.

   In the case two edges are splitted the triangle has 2 possible splittings:
we need to choose a diagonal of the resulting trapezoid.
'swap' encodes the two diagonals to test: if diag1 < diag2 we swap the diagonal
like this (140, 504 -> 150, 514) (the second vertex of each triangles is replaced
 by the first vertex of the other one).
            2
           / \
          5---4
         /     \
        0-------1

*/

class Split {
public:
    int TriNum;			// number of triangles
    int TV[4][3];   // The triangles coded as the following convention
                                    //     0..2 vertici originali del triangolo
                                    //     3..5 mp01, mp12, mp20 midpoints of the three edges
    int swap[2][2]; // the two diagonals to test for swapping
    int TE[4][3];   // the edge-edge correspondence between refined triangles and the old one
                                    //      (3) means the edge of the new triangle is internal;
};

const Split SplitTab[8]={
/* m20 m12 m01 */
/*  0   0   0 */	{1, {{0,1,2},{0,0,0},{0,0,0},{0,0,0}}, {{0,0},{0,0}},  {{0,1,2},{0,0,0},{0,0,0},{0,0,0}} },
/*  0   0   1 */	{2, {{0,3,2},{3,1,2},{0,0,0},{0,0,0}}, {{0,0},{0,0}},  {{0,3,2},{0,1,3},{0,0,0},{0,0,0}} },
/*  0   1   0 */	{2, {{0,1,4},{0,4,2},{0,0,0},{0,0,0}}, {{0,0},{0,0}},  {{0,1,3},{3,1,2},{0,0,0},{0,0,0}} },
/*  0   1   1 */	{3, {{3,1,4},{0,3,2},{4,2,3},{0,0,0}}, {{0,4},{3,2}},  {{0,1,3},{0,3,2},{1,3,3},{0,0,0}} },
/*  1   0   0 */	{2, {{0,1,5},{5,1,2},{0,0,0},{0,0,0}}, {{0,0},{0,0}},  {{0,3,2},{3,1,2},{0,0,0},{0,0,0}} },
/*  1   0   1 */	{3, {{0,3,5},{3,1,5},{2,5,1},{0,0,0}}, {{3,2},{5,1}},  {{0,3,2},{0,3,3},{2,3,1},{0,0,0}} },
/*  1   1   0 */	{3, {{2,5,4},{0,1,5},{4,5,1},{0,0,0}}, {{0,4},{5,1}},  {{2,3,1},{0,3,2},{3,3,1},{0,0,0}} },
/*  1   1   1 */	//{4, {{0,3,5},{3,1,4},{5,4,2},{3,4,5}}, {{0,0},{0,0}},  {{0,3,2},{0,1,3},{3,1,2},{3,3,3}} },
/*  1   1   1 */	{4, {{3,4,5},{0,3,5},{3,1,4},{5,4,2}}, {{0,0},{0,0}},  {{3,3,3},{0,3,2},{0,1,3},{3,1,2}} },
};


template <class MeshType>
struct BaseInterpolator
{
  typedef typename face::Pos<typename MeshType::FaceType> PosType;
  typedef typename MeshType::VertexType VertexType;
  void operator()(VertexType &, PosType  ){}
};

// Basic subdivision class
// This class must provide methods for finding the position of the newly created vertices
// In this implemenation we simply put the new vertex in the MidPoint position.
// Color and TexCoords are interpolated accordingly.
// This subdivision class allow also the correct interpolation of userdefined data by
// providing, in the constructor, an interpolator functor that will be called for each new vertex to be created.

template<class MESH_TYPE, class InterpolatorFunctorType = BaseInterpolator< MESH_TYPE> >
struct MidPoint : public   std::unary_function<face::Pos<typename MESH_TYPE::FaceType> ,  typename MESH_TYPE::CoordType >
{
     typedef typename face::Pos<typename MESH_TYPE::FaceType> PosType;
     typedef typename MESH_TYPE::VertexType VertexType;

     MidPoint(MESH_TYPE *_mp,
                InterpolatorFunctorType *_intFunc=0) {
       mp=_mp;
       intFunc =_intFunc;
     }

     MESH_TYPE *mp;
     InterpolatorFunctorType *intFunc; /// This callback is called to fill up

    void operator()(VertexType &nv, PosType  ep){
        assert(mp);
        VertexType *V0 = ep.V() ;
        VertexType *V1 = ep.VFlip() ;
        if(V0 > V1) std::swap(V1,V0);

        nv.P()=   (V0->P()+V1->P())/2.0;

        if( tri::HasPerVertexNormal(*mp))
            nv.N()= (V0->N()+V1->N()).normalized();

        if( tri::HasPerVertexColor(*mp))
            nv.C().lerp(V0->C(),V1->C(),.5f);

        if( tri::HasPerVertexQuality(*mp))
            nv.Q() = (V0->Q()+V1->Q()) / 2.0;

        if( tri::HasPerVertexTexCoord(*mp))
            nv.T().P() = (V0->T().P()+V1->T().P()) / 2.0;
        if(intFunc)
          (*intFunc)(nv,ep);
    }

    Color4<typename MESH_TYPE::ScalarType> WedgeInterp(Color4<typename MESH_TYPE::ScalarType> &c0, Color4<typename MESH_TYPE::ScalarType> &c1)
    {
        Color4<typename MESH_TYPE::ScalarType> cc;
        return cc.lerp(c0,c1,0.5f);
    }

    template<class FL_TYPE>
    TexCoord2<FL_TYPE,1> WedgeInterp(TexCoord2<FL_TYPE,1> &t0, TexCoord2<FL_TYPE,1> &t1)
    {
        TexCoord2<FL_TYPE,1> tmp;
        assert(t0.n()== t1.n());
        tmp.n()=t0.n();
        tmp.t()=(t0.t()+t1.t())/2.0;
        return tmp;
    }
};



template<class MESH_TYPE>
struct MidPointArc : public std::unary_function<face::Pos<typename MESH_TYPE::FaceType> ,  typename MESH_TYPE::CoordType>
{
    void operator()(typename MESH_TYPE::VertexType &nv, face::Pos<typename MESH_TYPE::FaceType> ep)
    {
        const typename MESH_TYPE::ScalarType EPS =1e-10;
        typename MESH_TYPE::CoordType vp = (ep.f->V(ep.z)->P()+ep.f->V1(ep.z)->P())/2.0;
        typename MESH_TYPE::CoordType  n = (ep.f->V(ep.z)->N()+ep.f->V1(ep.z)->N())/2.0;
        typename MESH_TYPE::ScalarType w =n.Norm();
        if(w<EPS) { nv.P()=(ep.f->V(ep.z)->P()+ep.f->V1(ep.z)->P())/2.0; return;}
        n/=w;
        typename MESH_TYPE::CoordType d0 = ep.f->V(ep.z)->P() - vp;
        typename MESH_TYPE::CoordType d1 = ep.f->V1(ep.z)->P()- vp;
        typename MESH_TYPE::ScalarType d=Distance(ep.f->V(ep.z)->P(),ep.f->V1(ep.z)->P())/2.0;

        typename MESH_TYPE::CoordType  nn = ep.f->V1(ep.z)->N() ^ ep.f->V(ep.z)->N();
        typename MESH_TYPE::CoordType  np = n ^ d0; //vector perpendicular to the edge plane, normal is interpolated
        np.Normalize();
        double sign=1;
        if(np*nn<0) sign=-1; // se le normali non divergono sposta il punto nella direzione opposta

        typename MESH_TYPE::CoordType n0=ep.f->V(ep.z)->N() -np*(ep.f->V(ep.z)->N()*np);
        n0.Normalize();
        typename MESH_TYPE::CoordType n1=ep.f->V1(ep.z)->N()-np*(ep.f->V1(ep.z)->N()*np);
        assert(n1.Norm()>EPS);
        n1.Normalize();
        typename MESH_TYPE::ScalarType cosa0=n0*n;
        typename MESH_TYPE::ScalarType cosa1=n1*n;
        if(2-cosa0-cosa1<EPS) {nv.P()=(ep.f->V(ep.z)->P()+ep.f->V1(ep.z)->P())/2.0;return;}
        typename MESH_TYPE::ScalarType cosb0=(d0*n)/d;
        typename MESH_TYPE::ScalarType cosb1=(d1*n)/d;
        assert(1+cosa0>EPS);
        assert(1+cosa1>EPS);
        typename MESH_TYPE::ScalarType delta0=d*(cosb0 +sqrt( ((1-cosb0*cosb0)*(1-cosa0))/(1+cosa0)) );
        typename MESH_TYPE::ScalarType delta1=d*(cosb1 +sqrt( ((1-cosb1*cosb1)*(1-cosa1))/(1+cosa1)) );
        assert(delta0+delta1<2*d);
        nv.P()=vp+n*sign*(delta0+delta1)/2.0;
        return ;
    }

    // Aggiunte in modo grezzo le due wedgeinterp
    Color4<typename MESH_TYPE::ScalarType> WedgeInterp(Color4<typename MESH_TYPE::ScalarType> &c0, Color4<typename MESH_TYPE::ScalarType> &c1)
    {
        Color4<typename MESH_TYPE::ScalarType> cc;
        return cc.lerp(c0,c1,0.5f);
    }

    template<class FL_TYPE>
    TexCoord2<FL_TYPE,1> WedgeInterp(TexCoord2<FL_TYPE,1> &t0, TexCoord2<FL_TYPE,1> &t1)
    {
        TexCoord2<FL_TYPE,1> tmp;
        assert(t0.n()== t1.n());
        tmp.n()=t0.n();
        tmp.t()=(t0.t()+t1.t())/2.0;
        return tmp;
    }

};

/*
Versione Della Midpoint basata sul paper:
S. Karbacher, S. Seeger, G. Hausler
A non linear subdivision scheme for triangle meshes

    Non funziona!
    Almeno due problemi:
    1) il verso delle normali influenza il risultato (e.g. si funziona solo se le normali divergono)
         Risolvibile controllando se le normali divergono
  2) gli archi vanno calcolati sul piano definito dalla normale interpolata e l'edge.
         funziona molto meglio nelle zone di sella e non semplici.

*/
template<class MESH_TYPE>
struct MidPointArcNaive : public std::unary_function< face::Pos<typename MESH_TYPE::FaceType> , typename MESH_TYPE::CoordType>
{
    typename MESH_TYPE::CoordType operator()(face::Pos<typename MESH_TYPE::FaceType>  ep)
    {

        typename MESH_TYPE::CoordType vp = (ep.f->V(ep.z)->P()+ep.f->V1(ep.z)->P())/2.0;
        typename MESH_TYPE::CoordType  n = (ep.f->V(ep.z)->N()+ep.f->V1(ep.z)->N())/2.0;
        n.Normalize();
        typename MESH_TYPE::CoordType d0 = ep.f->V(ep.z)->P() - vp;
        typename MESH_TYPE::CoordType d1 = ep.f->V1(ep.z)->P()- vp;
        typename MESH_TYPE::ScalarType d=Distance(ep.f->V(ep.z)->P(),ep.f->V1(ep.z)->P())/2.0;

        typename MESH_TYPE::ScalarType cosa0=ep.f->V(ep.z)->N()*n;
        typename MESH_TYPE::ScalarType cosa1=ep.f->V1(ep.z)->N()*n;
        typename MESH_TYPE::ScalarType cosb0=(d0*n)/d;
        typename MESH_TYPE::ScalarType cosb1=(d1*n)/d;

        typename MESH_TYPE::ScalarType delta0=d*(cosb0 +sqrt( ((1-cosb0*cosb0)*(1-cosa0))/(1+cosa0)) );
        typename MESH_TYPE::ScalarType delta1=d*(cosb1 +sqrt( ((1-cosb1*cosb1)*(1-cosa1))/(1+cosa1)) );

        return vp+n*(delta0+delta1)/2.0;
    }
};


// Basic Predicate that tells if a given edge must be splitted.
// the constructure requires the threshold.
// VERY IMPORTANT REQUIREMENT: this function must be symmetric
// e.g. it must return the same value if the Pos is VFlipped.
// If this function is not symmetric the Refine can crash.

template <class MESH_TYPE, class FLT>
class EdgeLen
{
    FLT squaredThr;
public:
    EdgeLen(){};
    EdgeLen(FLT threshold) {setThr(threshold);}
    void setThr(FLT threshold) {squaredThr = threshold*threshold; }
    bool operator()(face::Pos<typename MESH_TYPE::FaceType> ep) const
    {
        return SquaredDistance(ep.V()->P(), ep.VFlip()->P())>squaredThr;
    }
};

/*********************************************************/
/*********************************************************

Given a mesh the following function refines it according to two functor objects:

- a predicate that tells if a given edge must be splitted

- a functor that gives you the new poistion of the created vertices (starting from an edge)

If RefineSelected is true only selected faces are taken into account for being splitted.

Requirement: FF Adjacency and Manifoldness

**********************************************************/
/*********************************************************/
template <class VertexPointer>
class RefinedFaceData
    {
        public:
        RefinedFaceData(){
            ep[0] = ep[1] = ep[2] = false;
            vp[0] = vp[1] = vp[2] = NULL;
        }
        bool ep[3];
        VertexPointer vp[3];
    };

template<class MESH_TYPE,class MIDPOINT, class EDGEPRED>
bool RefineE(MESH_TYPE &m, MIDPOINT &mid, EDGEPRED &ep,bool RefineSelected=false, CallBackPos *cb = 0)
{
    // common typenames
    typedef typename MESH_TYPE::VertexIterator VertexIterator;
    typedef typename MESH_TYPE::FaceIterator FaceIterator;
    typedef typename MESH_TYPE::VertexPointer VertexPointer;
    typedef typename MESH_TYPE::FacePointer FacePointer;
    typedef typename MESH_TYPE::FaceType FaceType;
    typedef typename MESH_TYPE::FaceType::TexCoordType TexCoordType;
    assert(tri::HasFFAdjacency(m));
    tri::UpdateFlags<MESH_TYPE>::FaceBorderFromFF(m);
    typedef face::Pos<FaceType>  PosType;

    int j,NewVertNum=0,NewFaceNum=0;

    typedef RefinedFaceData<VertexPointer> RFD;
    typedef typename MESH_TYPE :: template PerFaceAttributeHandle<RFD> HandleType;
    HandleType RD  = tri::Allocator<MESH_TYPE>:: template AddPerFaceAttribute<RFD> (m,std::string("RefineData"));

    // Callback stuff
    int step=0;
    int PercStep=std::max(1,m.fn/33);

    // First Loop: We analyze the mesh to compute the number of the new faces and new vertices
    FaceIterator fi;
  for(fi=m.face.begin(),j=0;fi!=m.face.end();++fi) if(!(*fi).IsD())
    {
        if(cb && (++step%PercStep)==0) (*cb)(step/PercStep,"Refining...");
        // skip unselected faces if necessary
        if(RefineSelected && !(*fi).IsS()) continue;

        for(j=0;j<3;j++)
            {
                if(RD[fi].ep[j]) continue;

                PosType edgeCur(&*fi,j);
                if(RefineSelected && ! edgeCur.FFlip()->IsS()) continue;
                if(!ep(edgeCur)) continue;

                RD[edgeCur.F()].ep[edgeCur.E()]=true;
                ++NewFaceNum;
                ++NewVertNum;
                assert(edgeCur.IsManifold());
                if(!edgeCur.IsBorder())
                {
                    edgeCur.FlipF();
                    edgeCur.F()->SetV();
                    RD[edgeCur.F()].ep[edgeCur.E()]=true;
                    ++NewFaceNum;
                }
            }

  } // end face loop

    if(NewVertNum ==0 )
        {
            tri::Allocator<MESH_TYPE> :: template DeletePerFaceAttribute<RefinedFaceData<VertexPointer> >  (m,RD);
            return false;
        }
    VertexIterator lastv = tri::Allocator<MESH_TYPE>::AddVertices(m,NewVertNum);

    // Secondo loop: We initialize a edge->vertex map

    for(fi=m.face.begin();fi!=m.face.end();++fi) if(!(*fi).IsD())
  {
       if(cb && (++step%PercStep)==0)(*cb)(step/PercStep,"Refining...");
     for(j=0;j<3;j++)
         {
                // skip unselected faces if necessary
                if(RefineSelected && !(*fi).IsS()) continue;
                for(j=0;j<3;j++)
                {
                    PosType edgeCur(&*fi,j);
                    if(RefineSelected && ! edgeCur.FFlip()->IsS()) continue;

                    if( RD[edgeCur.F()].ep[edgeCur.E()] &&  RD[edgeCur.F()].vp[edgeCur.E()] ==0 )
                    {
                        RD[edgeCur.F()].vp[edgeCur.E()] = &*lastv;
                        mid(*lastv,edgeCur);
                        if(!edgeCur.IsBorder())
                        {
                            edgeCur.FlipF();
                            assert(RD[edgeCur.F()].ep[edgeCur.E()]);
                            RD[edgeCur.F()].vp[edgeCur.E()] = &*lastv;
                        }
                        ++lastv;
                    }
                }
         }
  }

    assert(lastv==m.vert.end()); // critical assert: we MUST have used all the vertex that we forecasted we need

    FaceIterator lastf = tri::Allocator<MESH_TYPE>::AddFaces(m,NewFaceNum);
    FaceIterator oldendf = lastf;

/*
 *               v0
 *
 *
 *               f0
 *
 *       mp01     f3     mp02
 *
 *
 *       f1               f2
 *
 *v1            mp12                v2
 *
*/

    VertexPointer vv[6];	// The six vertices that arise in the single triangle splitting
    //     0..2 Original triangle vertices
    //     3..5 mp01, mp12, mp20 midpoints of the three edges
    FacePointer nf[4];   // The (up to) four faces that are created.

    TexCoordType wtt[6];  // per ogni faccia sono al piu' tre i nuovi valori
    // di texture per wedge (uno per ogni edge)

    int fca=0;
    for(fi=m.face.begin();fi!=oldendf;++fi) if(!(*fi).IsD())
    {
      if(cb && (++step%PercStep)==0)
          (*cb)(step/PercStep,"Refining...");
      vv[0]=(*fi).V(0);
      vv[1]=(*fi).V(1);
      vv[2]=(*fi).V(2);
      vv[3] = RD[fi].vp[0];
      vv[4] = RD[fi].vp[1];
      vv[5] = RD[fi].vp[2];

      int ind = ((vv[3] != NULL) ? 1 : 0) + ((vv[4] != NULL) ? 2 : 0) + ((vv[5] != NULL) ? 4 : 0);

      nf[0]=&*fi;
      int i;
      for(i=1;i<SplitTab[ind].TriNum;++i){
        nf[i]=&*lastf; ++lastf; fca++;
        if(RefineSelected || (*fi).IsS()) (*nf[i]).SetS();
        nf[i]->ImportData(*fi);
//		if(tri::HasPerFaceColor(m))
//  		nf[i]->C()=(*fi).cC();
      }


	if(tri::HasPerWedgeTexCoord(m))
		for(i=0;i<3;++i)
		{
			wtt[i]=(*fi).WT(i);
			wtt[3+i]=mid.WedgeInterp((*fi).WT(i),(*fi).WT((i+1)%3));
		}

	int orgflag = (*fi).Flags();
	for (i=0; i<SplitTab[ind].TriNum; ++i)
		for(j=0;j<3;++j)
		{
			(*nf[i]).V(j)=&*vv[SplitTab[ind].TV[i][j]];

			if(tri::HasPerWedgeTexCoord(m)) //analogo ai vertici...
				(*nf[i]).WT(j) = wtt[SplitTab[ind].TV[i][j]];

			assert((*nf[i]).V(j)!=0);
			if(SplitTab[ind].TE[i][j]!=3)
			{
				if(orgflag & (MESH_TYPE::FaceType::BORDER0<<(SplitTab[ind].TE[i][j])))
					(*nf[i]).SetB(j);
				else
					(*nf[i]).ClearB(j);

				if(orgflag & (MESH_TYPE::FaceType::FACEEDGESEL0<<(SplitTab[ind].TE[i][j])))
					(*nf[i]).SetFaceEdgeS(j);
				else
					(*nf[i]).ClearFaceEdgeS(j);
			}
			else
			{
				(*nf[i]).ClearB(j);
				(*nf[i]).ClearFaceEdgeS(j);
			}
		}

      if(SplitTab[ind].TriNum==3 &&
         SquaredDistance(vv[SplitTab[ind].swap[0][0]]->P(),vv[SplitTab[ind].swap[0][1]]->P()) <
         SquaredDistance(vv[SplitTab[ind].swap[1][0]]->P(),vv[SplitTab[ind].swap[1][1]]->P()) )
      { // swap the last two triangles
        (*nf[2]).V(1)=(*nf[1]).V(0);
        (*nf[1]).V(1)=(*nf[2]).V(0);
        if(tri::HasPerWedgeTexCoord(m)){ //swap also textures coordinates
          (*nf[2]).WT(1)=(*nf[1]).WT(0);
          (*nf[1]).WT(1)=(*nf[2]).WT(0);
        }

        if((*nf[1]).IsB(0)) (*nf[2]).SetB(1); else (*nf[2]).ClearB(1);
        if((*nf[2]).IsB(0)) (*nf[1]).SetB(1); else (*nf[1]).ClearB(1);
        (*nf[1]).ClearB(0);
        (*nf[2]).ClearB(0);

        if((*nf[1]).IsFaceEdgeS(0)) (*nf[2]).SetFaceEdgeS(1); else (*nf[2]).ClearFaceEdgeS(1);
        if((*nf[2]).IsFaceEdgeS(0)) (*nf[1]).SetFaceEdgeS(1); else (*nf[1]).ClearFaceEdgeS(1);
        (*nf[1]).ClearFaceEdgeS(0);
        (*nf[2]).ClearFaceEdgeS(0);
      }
    }

    assert(lastf==m.face.end());	 // critical assert: we MUST have used all the faces that we forecasted we need and that we previously allocated.
    assert(!m.vert.empty());
    for(fi=m.face.begin();fi!=m.face.end();++fi) if(!(*fi).IsD()){
      assert((*fi).V(0)>=&*m.vert.begin() && (*fi).V(0)<=&m.vert.back() );
      assert((*fi).V(1)>=&*m.vert.begin() && (*fi).V(1)<=&m.vert.back() );
      assert((*fi).V(2)>=&*m.vert.begin() && (*fi).V(2)<=&m.vert.back() );
    }
    tri::UpdateTopology<MESH_TYPE>::FaceFace(m);

    tri::Allocator<MESH_TYPE> :: template DeletePerFaceAttribute<RefinedFaceData<VertexPointer> >  (m,RD);

    return true;
}

/*************************************************************************/
// simple wrapper of the base refine for lazy coder that do not need a edge predicate

template<class MESH_TYPE,class MIDPOINT>
bool Refine(MESH_TYPE &m, MIDPOINT mid, typename MESH_TYPE::ScalarType thr=0,bool RefineSelected=false, CallBackPos *cb = 0)
{
    EdgeLen <MESH_TYPE, typename MESH_TYPE::ScalarType> ep(thr);
  return RefineE(m,mid,ep,RefineSelected,cb);
}
/*************************************************************************/

/*
Modified Butterfly interpolation scheme,
as presented in
Zorin, Schroeder
Subdivision for modeling and animation
Siggraph 2000 Course Notes
*/

/*

    vul-------vu--------vur
      \      /  \      /
       \    /    \    /
        \  /  fu  \  /
         vl--------vr
        /  \  fd  /  \
       /    \    /    \
      /      \  /      \
    vdl-------vd--------vdr

*/

template<class MESH_TYPE>
struct MidPointButterfly : public std::unary_function<face::Pos<typename MESH_TYPE::FaceType> , typename MESH_TYPE::CoordType>
{
  MESH_TYPE &m;
  MidPointButterfly(MESH_TYPE &_m):m(_m){}

    void operator()(typename MESH_TYPE::VertexType &nv, face::Pos<typename MESH_TYPE::FaceType>  ep)
    {
        face::Pos<typename MESH_TYPE::FaceType> he(ep.f,ep.z,ep.f->V(ep.z));
        typename MESH_TYPE::CoordType *vl,*vr;
        typename MESH_TYPE::CoordType *vl0,*vr0;
        typename MESH_TYPE::CoordType *vu,*vd,*vul,*vur,*vdl,*vdr;
        vl=&he.v->P();
        he.FlipV();
        vr=&he.v->P();

        if( tri::HasPerVertexColor(m))
            nv.C().lerp(ep.f->V(ep.z)->C(),ep.f->V1(ep.z)->C(),.5f);

        if(he.IsBorder())
        {
            he.NextB();
            vr0=&he.v->P();
            he.FlipV();
            he.NextB();
            assert(&he.v->P()==vl);
            he.NextB();
            vl0=&he.v->P();
            nv.P()=((*vl)+(*vr))*(9.0/16.0)-((*vl0)+(*vr0))/16.0 ;
        }
        else
        {
            he.FlipE();he.FlipV();
            vu=&he.v->P();
            he.FlipF();he.FlipE();he.FlipV();
            vur=&he.v->P();
            he.FlipV();he.FlipE();he.FlipF(); assert(&he.v->P()==vu); // back to vu (on the right)
            he.FlipE();
            he.FlipF();he.FlipE();he.FlipV();
            vul=&he.v->P();
            he.FlipV();he.FlipE();he.FlipF(); assert(&he.v->P()==vu); // back to vu (on the left)
            he.FlipV();he.FlipE();he.FlipF(); assert(&he.v->P()==vl);// again on vl (but under the edge)
            he.FlipE();he.FlipV();
            vd=&he.v->P();
            he.FlipF();he.FlipE();he.FlipV();
            vdl=&he.v->P();
            he.FlipV();he.FlipE();he.FlipF(); assert(&he.v->P()==vd);// back to vd (on the right)
            he.FlipE();
            he.FlipF();he.FlipE();he.FlipV();
            vdr=&he.v->P();

            nv.P()=((*vl)+(*vr))/2.0+((*vu)+(*vd))/8.0 - ((*vul)+(*vur)+(*vdl)+(*vdr))/16.0;
            }
    }

    /// Aggiunte in modo grezzo le due wedge interp
    Color4<typename MESH_TYPE::ScalarType> WedgeInterp(Color4<typename MESH_TYPE::ScalarType> &c0, Color4<typename MESH_TYPE::ScalarType> &c1)
    {
        Color4<typename MESH_TYPE::ScalarType> cc;
        return cc.lerp(c0,c1,0.5f);
    }

    template<class FL_TYPE>
    TexCoord2<FL_TYPE,1> WedgeInterp(TexCoord2<FL_TYPE,1> &t0, TexCoord2<FL_TYPE,1> &t1)
    {
        TexCoord2<FL_TYPE,1> tmp;
        assert(t0.n()== t1.n());
        tmp.n()=t0.n();
        tmp.t()=(t0.t()+t1.t())/2.0;
        return tmp;
    }
};


#if 0
            int rule=0;
            if(vr==vul) rule+=1;
            if(vl==vur) rule+=2;
            if(vl==vdr) rule+=4;
            if(vr==vdl) rule+=8;
            switch(rule){
/*      */
/*      */			case  0 :	return ((*vl)+(*vr))/2.0+((*vu)+(*vd))/8.0 - ((*vul)+(*vur)+(*vdl)+(*vdr))/16.0;
/* ul   */  		case  1 : return (*vl*6 + *vr*10 + *vu + *vd*3 - *vur - *vdl -*vdr*2 )/16.0;
/* ur   */  		case  2 : return (*vr*6 + *vl*10 + *vu + *vd*3 - *vul - *vdr -*vdl*2 )/16.0;
/* dr   */  		case  4 : return (*vr*6 + *vl*10 + *vd + *vu*3 - *vdl - *vur -*vul*2 )/16.0;
/* dl   */  		case  8 : return (*vl*6 + *vr*10 + *vd + *vu*3 - *vdr - *vul -*vur*2 )/16.0;
/* ul,ur */  		case  3 : return (*vl*4 + *vr*4 + *vd*2 + - *vdr - *vdl )/8.0;
/* dl,dr */  		case 12 : return (*vl*4 + *vr*4 + *vu*2 + - *vur - *vul )/8.0;

/* ul,dr */  		case  5 :
/* ur,dl */  		case 10 :
                                default:
                                    return (*vl+ *vr)/2.0;
            }



#endif
/*
    vul-------vu--------vur
          \      /  \      /
             \    /    \    /
        \  /  fu  \  /
         vl--------vr
        /  \  fd  /  \
       /    \    /    \
      /      \  /      \
    vdl-------vd--------vdr

*/

// Versione modificata per tenere di conto in meniara corretta dei vertici con valenza alta

template<class MESH_TYPE>
struct MidPointButterfly2 : public std::unary_function<face::Pos<typename MESH_TYPE::FaceType> , typename MESH_TYPE::CoordType>
{
    typename MESH_TYPE::CoordType operator()(face::Pos<typename MESH_TYPE::FaceType>  ep)
    {
double Rules[11][10] =
{
    {.0}, // valenza 0
    {.0}, // valenza 1
    {.0}, // valenza 2
    {  .4166666667, -.08333333333 , -.08333333333  }, // valenza 3
    {  .375       ,  .0           ,  -0.125        ,  .0          }, // valenza 4
    {  .35        ,  .03090169945 ,  -.08090169945 , -.08090169945,  .03090169945	}, // valenza 5
    {  .5         ,  .125         ,  -0.0625       ,  .0          ,  -0.0625      , 0.125       }, // valenza 6
    {  .25        ,  .1088899050  , -.06042933822  , -.04846056675, -.04846056675, -.06042933822,  .1088899050  }, // valenza 7
    {  .21875     ,  .1196383476  , -.03125        , -.05713834763, -.03125      , -.05713834763, -.03125      ,.1196383476  }, // valenza 8
    {  .1944444444,  .1225409480  , -.00513312590  , -.05555555556, -.03407448880, -.03407448880, -.05555555556, -.00513312590, .1225409480  }, // valenza 9
    {  .175       ,  .1213525492  ,  .01545084973  , -.04635254918, -.04045084973, -.025        , -.04045084973, -.04635254918,  .01545084973,  .1213525492  } // valenza 10
};

face::Pos<typename MESH_TYPE::FaceType> he(ep.f,ep.z,ep.f->V(ep.z));
    typename MESH_TYPE::CoordType *vl,*vr;
    vl=&he.v->P();
    vr=&he.VFlip()->P();
    if(he.IsBorder())
        {he.FlipV();
        typename MESH_TYPE::CoordType *vl0,*vr0;
            he.NextB();
            vr0=&he.v->P();
            he.FlipV();
            he.NextB();
            assert(&he.v->P()==vl);
            he.NextB();
            vl0=&he.v->P();
            return ((*vl)+(*vr))*(9.0/16.0)-((*vl0)+(*vr0))/16.0 ;
        }

    int kl=0,kr=0; // valence of left and right vertices
    bool bl=false,br=false; // if left and right vertices are of border
  face::Pos<typename MESH_TYPE::FaceType> heStart=he;assert(he.v->P()==*vl);
    do { // compute valence of left vertex
        he.FlipE();he.FlipF();
        if(he.IsBorder()) bl=true;
        ++kl;
    }	while(he!=heStart);

    he.FlipV();heStart=he;assert(he.v->P()==*vr);
    do { // compute valence of right vertex
        he.FlipE();he.FlipF();
        if(he.IsBorder()) br=true;
        ++kr;
    }	while(he!=heStart);
  if(br||bl) return MidPointButterfly<MESH_TYPE>()( ep );
    if(kr==6 && kl==6) return MidPointButterfly<MESH_TYPE>()( ep );
    // TRACE("odd vertex among valences of %i %i\n",kl,kr);
    typename MESH_TYPE::CoordType newposl=*vl*.75, newposr=*vr*.75;
    he.FlipV();heStart=he; assert(he.v->P()==*vl);
    int i=0;
    if(kl!=6)
    do { // compute position  of left vertex
        newposl+= he.VFlip()->P() * Rules[kl][i];
        he.FlipE();he.FlipF();
        ++i;
    }	while(he!=heStart);
    i=0;he.FlipV();heStart=he;assert(he.v->P()==*vr);
    if(kr!=6)
    do { // compute position of right vertex
        newposr+=he.VFlip()->P()* Rules[kr][i];
        he.FlipE();he.FlipF();
        ++i;
    }	while(he!=heStart);
    if(kr==6) return newposl;
    if(kl==6) return newposr;
    return newposl+newposr;
    }
};

/* The two following classes are the functor and the predicate that you need for using the refine framework to cut a mesh along a linear interpolation of the quality.
   This can be used for example to slice a mesh with a plane. Just set the quality value as distance from plane and then functor and predicate
   initialized 0 and invoke the refine

  MyMesh A;
  tri::UpdateQuality:MyMesh>::VertexFromPlane(plane);
  QualityMidPointFunctor<MyMesh> slicingfunc(0.0);
  QualityEdgePredicate<MyMesh> slicingpred(0.0);
  tri::UpdateTopology<MyMesh>::FaceFace(A);
  RefineE<MyMesh, QualityMidPointFunctor<MyMesh>, QualityEdgePredicate<MyMesh> > (A, slicingfunc, slicingpred, false);

  Note that they store in the vertex quality the plane distance.
  */

template<class MESH_TYPE>
class QualityMidPointFunctor : public std::unary_function<face::Pos<typename MESH_TYPE::FaceType> , typename MESH_TYPE::CoordType>
{
public:
  typedef Point3<typename MESH_TYPE::ScalarType> Point3x;
  typedef typename MESH_TYPE::ScalarType ScalarType;

  ScalarType thr;

  QualityMidPointFunctor(ScalarType _thr):thr(_thr){}


  void operator()(typename MESH_TYPE::VertexType &nv, const face::Pos<typename MESH_TYPE::FaceType> &ep){
    Point3x p0=ep.f->V0(ep.z)->P();
    Point3x p1=ep.f->V1(ep.z)->P();
    ScalarType q0=ep.f->V0(ep.z)->Q()-thr;
    ScalarType q1=ep.f->V1(ep.z)->Q()-thr;
    double pp= q0/(q0-q1);
    nv.P()=p1*pp + p0*(1.0-pp);
    nv.Q()=thr;
    }

    Color4<typename MESH_TYPE::ScalarType> WedgeInterp(Color4<typename MESH_TYPE::ScalarType> &c0, Color4<typename MESH_TYPE::ScalarType> &c1)
    {
        Color4<typename MESH_TYPE::ScalarType> cc;
        return cc.lerp(c0,c1,0.5f);
    }

    template<class FL_TYPE>
    TexCoord2<FL_TYPE,1> WedgeInterp(TexCoord2<FL_TYPE,1> &t0, TexCoord2<FL_TYPE,1> &t1)
    {
        TexCoord2<FL_TYPE,1> tmp;
        assert(t0.n()== t1.n());
        tmp.n()=t0.n();
        tmp.t()=(t0.t()+t1.t())/2.0;
        return tmp;
    }
};


template <class MESH_TYPE>
class QualityEdgePredicate
{
  public:
  typedef Point3<typename MESH_TYPE::ScalarType> Point3x;
  typedef typename MESH_TYPE::ScalarType ScalarType;
  ScalarType thr;
  ScalarType tolerance;
  QualityEdgePredicate(const ScalarType &thr,ScalarType _tolerance=0.02):thr(thr) {tolerance=_tolerance;}
  bool operator()(face::Pos<typename MESH_TYPE::FaceType> ep)
    {
    ScalarType q0=ep.f->V0(ep.z)->Q()-thr;
    ScalarType q1=ep.f->V1(ep.z)->Q()-thr;
    if(q0>q1) std::swap(q0,q1);
    if ( q0*q1 >= 0) return false;
    // now a small check to be sure that we do not make too thin crossing.
    double pp= q0/(q0-q1);
    if ((fabs(pp)< tolerance)||(fabs(pp)> (1-tolerance))) return false;
    return true;
  }
};


template<class MESH_TYPE>
struct MidPointSphere : public std::unary_function<face::Pos<typename MESH_TYPE::FaceType> , typename MESH_TYPE::CoordType>
{
    Sphere3<typename MESH_TYPE::ScalarType> sph;
    typedef Point3<typename MESH_TYPE::ScalarType> Point3x;

    void operator()(typename MESH_TYPE::VertexType &nv, face::Pos<typename MESH_TYPE::FaceType>  ep){
        Point3x &p0=ep.f->V0(ep.z)->P();
        Point3x &p1=ep.f->V1(ep.z)->P();
    nv.P()= sph.c+((p0+p1)/2.0 - sph.c ).Normalize();
    }

    Color4<typename MESH_TYPE::ScalarType> WedgeInterp(Color4<typename MESH_TYPE::ScalarType> &c0, Color4<typename MESH_TYPE::ScalarType> &c1)
    {
        Color4<typename MESH_TYPE::ScalarType> cc;
        return cc.lerp(c0,c1,0.5f);
    }

    template<class FL_TYPE>
    TexCoord2<FL_TYPE,1> WedgeInterp(TexCoord2<FL_TYPE,1> &t0, TexCoord2<FL_TYPE,1> &t1)
    {
        TexCoord2<FL_TYPE,1> tmp;
        assert(t0.n()== t1.n());
        tmp.n()=t0.n();
        tmp.t()=(t0.t()+t1.t())/2.0;
        return tmp;
    }
};


template <class FLT>
class EdgeSplSphere
{
    public:
  Sphere3<FLT> sph;
    bool operator()(const Point3<FLT> &p0, const  Point3<FLT> &p1) const
    {
        if(Distance(sph,p0)>0) {
            if(Distance(sph,p1)>0) return false;
            else return true;
        }
        else if(Distance(sph,p1)<=0) return false;
        return true;
    }
};

template<class TRIMESH_TYPE>
struct CenterPointBarycenter : public std::unary_function<typename TRIMESH_TYPE::FacePointer, typename TRIMESH_TYPE::CoordType>
{
    typename TRIMESH_TYPE::CoordType operator()(typename TRIMESH_TYPE::FacePointer f){
        return vcg::Barycenter<typename TRIMESH_TYPE::FaceType>(*f);
    }
};

/// \brief Triangle split
/// Simple templated function for splitting a triangle with a internal point.
///  It can be templated on a CenterPoint class that is used to generate the position of the internal point.

template<class TRIMESH_TYPE, class CenterPoint=CenterPointBarycenter <TRIMESH_TYPE> >
class TriSplit
{
public:
  typedef typename TRIMESH_TYPE::FaceType FaceType;
  typedef typename TRIMESH_TYPE::VertexType VertexType;

  static void Apply(FaceType *f,
                    FaceType * f1,FaceType * f2,
                    VertexType * vB, CenterPoint	Center)
  {
    vB->P() = Center(f);

    //three vertices of the face to be split
    VertexType *V0,*V1,*V2;
    V0 = f->V(0);
    V1 = f->V(1);
    V2 = f->V(2);

    //reupdate initial face
    (*f).V(2) = &(*vB);
    //new face #1
    (*f1).V(0) = &(*vB);
    (*f1).V(1) = V1;
    (*f1).V(2) = V2;
    //new face #2
    (*f2).V(0) = V0;
    (*f2).V(1) = &(*vB);
    (*f2).V(2) = V2;

    if(f->HasFFAdjacency())
    {
      //update adjacency
      f->FFp(1)->FFp(f->FFi(1)) = f1;
      f->FFp(2)->FFp(f->FFi(2)) = f2;

      // ff adjacency
      FaceType *  FF0,*FF1,*FF2;
      FF0 = f->FFp(0);
      FF1 = f->FFp(1);
      FF2 = f->FFp(2);

      //ff adjacency indexes
      char FFi0,FFi1,FFi2;
      FFi0 = f->FFi(0);
      FFi1 = f->FFi(1);
      FFi2 = f->FFi(2);

      //initial face
      (*f).FFp(1) = &(*f1);
      (*f).FFi(1) = 0;
      (*f).FFp(2) = &(*f2);
      (*f).FFi(2) = 0;

      //face #1
      (*f1).FFp(0) = f;
      (*f1).FFi(0) = 1;

      (*f1).FFp(1) = FF1;
      (*f1).FFi(1) = FFi1;

      (*f1).FFp(2) = &(*f2);
      (*f1).FFi(2) = 1;

      //face #2
      (*f2).FFp(0) = f;
      (*f2).FFi(0) = 2;

      (*f2).FFp(1) = &(*f1);
      (*f2).FFi(1) = 2;

      (*f2).FFp(2) = FF2;
      (*f2).FFi(2) = FFi2;
    }
    //update faceEdge Sel if needed
    if (f->HasFlags())
    {
        bool IsFaceEdgeS[3];
        //collect and clear
        for (size_t i=0;i<3;i++)
        {
            IsFaceEdgeS[i]=(*f).IsFaceEdgeS(i);
            (*f).ClearFaceEdgeS(i);
            (*f1).ClearFaceEdgeS(i);
            (*f2).ClearFaceEdgeS(i);
        }
        //set back
        if (IsFaceEdgeS[0])(*f).SetFaceEdgeS(0);
        if (IsFaceEdgeS[1])(*f1).SetFaceEdgeS(1);
        if (IsFaceEdgeS[2])(*f2).SetFaceEdgeS(2);
    }
  }
}; // end class TriSplit

template <class MeshType>
void TrivialMidPointRefine(MeshType & m)
{
  typedef typename MeshType::VertexIterator VertexIterator;
  typedef typename MeshType::FaceIterator FaceIterator;
  typedef typename MeshType::VertexPointer VertexPointer;
  typedef typename MeshType::FacePointer FacePointer;
  
  Allocator<MeshType>::CompactEveryVector(m);
  int startFn = m.fn;
  FaceIterator lastf = tri::Allocator<MeshType>::AddFaces(m,m.fn*3);
  VertexIterator lastv = tri::Allocator<MeshType>::AddVertices(m,m.fn*3);
  
  /*
   *               v0
   *              /  \
   *            /  f0  \
   *          /          \
   *        mp01----------mp02
   *       /  \    f3    /   \
   *     / f1   \      /  f2   \
   *   /          \  /           \
   *v1 ---------- mp12------------v2
   *
  */
  
  for(int i=0;i<startFn;++i)
  {
    FacePointer f0= &m.face[i];
    FacePointer f1= &*lastf; ++lastf;
    FacePointer f2= &*lastf; ++lastf;
    FacePointer f3= &*lastf; ++lastf;    
    VertexPointer v0 =m.face[i].V(0); 
    VertexPointer v1 =m.face[i].V(1); 
    VertexPointer v2 =m.face[i].V(2); 
    VertexPointer mp01 = &*lastv; ++lastv; 
    VertexPointer mp12 = &*lastv; ++lastv; 
    VertexPointer mp02 = &*lastv; ++lastv; 
    
    f0->V(0) = v0;   f0->V(1) = mp01; f0->V(2) = mp02;
    f1->V(0) = v1;   f1->V(1) = mp12; f1->V(2) = mp01;
    f2->V(0) = v2;   f2->V(1) = mp02; f2->V(2) = mp12;
    f3->V(0) = mp12; f3->V(1) = mp02; f3->V(2) = mp01;
    mp01->P() = (v0>v1) ? (v0->P()+v1->P())/2.0 : (v1->P()+v0->P())/2.0;
    mp12->P() = (v1>v2) ? (v1->P()+v2->P())/2.0 : (v2->P()+v1->P())/2.0;
    mp02->P() = (v0>v2) ? (v0->P()+v2->P())/2.0 : (v2->P()+v0->P())/2.0;
  }
  
  int vd = tri::Clean<MeshType>::RemoveDuplicateVertex(m);
  printf("Vertex unification %i\n",vd);
  int vu = tri::Clean<MeshType>::RemoveUnreferencedVertex(m);
  printf("Vertex unref %i\n",vu);
  Allocator<MeshType>::CompactEveryVector(m);
}


template<class MESH_TYPE, class EDGEPRED>
bool RefineMidpoint(MESH_TYPE &m, EDGEPRED &ep, bool RefineSelected=false, CallBackPos *cb = 0)
{
	// common typenames
	typedef typename MESH_TYPE::VertexIterator VertexIterator;
	typedef typename MESH_TYPE::FaceIterator FaceIterator;
	typedef typename MESH_TYPE::VertexPointer VertexPointer;
	typedef typename MESH_TYPE::FacePointer FacePointer;
	typedef typename MESH_TYPE::FaceType FaceType;
	typedef typename MESH_TYPE::FaceType::TexCoordType TexCoordType;

	assert(tri::HasFFAdjacency(m));
	tri::UpdateFlags<MESH_TYPE>::FaceBorderFromFF(m);
	typedef face::Pos<FaceType>  PosType;

	int j,NewVertNum=0,NewFaceNum=0;

	typedef RefinedFaceData<VertexPointer> RFD;
	typedef typename MESH_TYPE :: template PerFaceAttributeHandle<RFD> HandleType;
	HandleType RD  = tri::Allocator<MESH_TYPE>:: template AddPerFaceAttribute<RFD> (m,std::string("RefineData"));

	MidPoint<MESH_TYPE> mid(&m);
	// Callback stuff
	int step=0;
	int PercStep=std::max(1,m.fn/33);

	// First Loop: We analyze the mesh to compute the number of the new faces and new vertices
	FaceIterator fi;
  for(fi=m.face.begin(),j=0;fi!=m.face.end();++fi) if(!(*fi).IsD())
    {
	    if(cb && (++step%PercStep)==0) (*cb)(step/PercStep,"Refining...");
		// skip unselected faces if necessary
		if(RefineSelected && !(*fi).IsS()) continue;

		for(j=0;j<3;j++)
		    {
			    if(RD[fi].ep[j]) continue;

				PosType edgeCur(&*fi,j);
				if(RefineSelected && ! edgeCur.FFlip()->IsS()) continue;
				if(!ep(edgeCur)) continue;

				RD[edgeCur.F()].ep[edgeCur.E()]=true;
				++NewFaceNum;
				++NewVertNum;
				PosType start = edgeCur;
				if (!edgeCur.IsBorder())
				{
					do
					{
						edgeCur.NextF();
						edgeCur.F()->SetV();
						RD[edgeCur.F()].ep[edgeCur.E()] = true;
						++NewFaceNum;
					} while (edgeCur != start);
					--NewFaceNum; //start is counted twice (could remove the first increment above)
				}
		    }

  } // end face loop

    if(NewVertNum ==0 )
	    {
		    tri::Allocator<MESH_TYPE> :: template DeletePerFaceAttribute<RefinedFaceData<VertexPointer> >  (m,RD);
			return false;
	    }
	VertexIterator lastv = tri::Allocator<MESH_TYPE>::AddVertices(m,NewVertNum);

	// Secondo loop: We initialize a edge->vertex map

	for(fi=m.face.begin();fi!=m.face.end();++fi) if(!(*fi).IsD())
  {
		if(cb && (++step%PercStep)==0)(*cb)(step/PercStep,"Refining...");
	 for(j=0;j<3;j++)
	     {
		        // skip unselected faces if necessary
		        if(RefineSelected && !(*fi).IsS()) continue;
				for(j=0;j<3;j++)
				{
					PosType edgeCur(&*fi,j);
					if(RefineSelected && ! edgeCur.FFlip()->IsS()) continue;

					if( RD[edgeCur.F()].ep[edgeCur.E()] &&  RD[edgeCur.F()].vp[edgeCur.E()] ==0 )
					{
						RD[edgeCur.F()].vp[edgeCur.E()] = &*lastv;
						mid(*lastv,edgeCur);
						PosType start = edgeCur;
						if (!edgeCur.IsBorder())
						{
							do
							{
								edgeCur.NextF();
								assert(RD[edgeCur.F()].ep[edgeCur.E()]);
								RD[edgeCur.F()].vp[edgeCur.E()] = &*lastv;
							} while (edgeCur != start);
						}
						++lastv;
					}
				}
	     }
  }

	assert(lastv==m.vert.end()); // critical assert: we MUST have used all the vertex that we forecasted we need

	FaceIterator lastf = tri::Allocator<MESH_TYPE>::AddFaces(m,NewFaceNum);
	FaceIterator oldendf = lastf;

/*
 *               v0
 *
 *
 *               f0
 *
 *       mp01     f3     mp02
 *
 *
 *       f1               f2
 *
 *v1            mp12                v2
 *
*/

	VertexPointer vv[6];	// The six vertices that arise in the single triangle splitting
	//     0..2 Original triangle vertices
	//     3..5 mp01, mp12, mp20 midpoints of the three edges
	FacePointer nf[4];   // The (up to) four faces that are created.

	TexCoordType wtt[6];  // per ogni faccia sono al piu' tre i nuovi valori
	// di texture per wedge (uno per ogni edge)

	int fca=0;
	for(fi=m.face.begin();fi!=oldendf;++fi) if(!(*fi).IsD())
	{
		if(cb && (++step%PercStep)==0)
		  (*cb)(step/PercStep,"Refining...");
	  vv[0]=(*fi).V(0);
	  vv[1]=(*fi).V(1);
	  vv[2]=(*fi).V(2);
	  vv[3] = RD[fi].vp[0];
	  vv[4] = RD[fi].vp[1];
	  vv[5] = RD[fi].vp[2];

	  int ind = ((vv[3] != NULL) ? 1 : 0) + ((vv[4] != NULL) ? 2 : 0) + ((vv[5] != NULL) ? 4 : 0);

	  nf[0]=&*fi;
	  int i;
	  for(i=1;i<SplitTab[ind].TriNum;++i){
		nf[i]=&*lastf; ++lastf; fca++;
		if(RefineSelected || (*fi).IsS()) (*nf[i]).SetS();
		nf[i]->ImportData(*fi);

	  }


	if(tri::HasPerWedgeTexCoord(m))
		for(i=0;i<3;++i)
		{
			wtt[i]=(*fi).WT(i);
			wtt[3+i]=mid.WedgeInterp((*fi).WT(i),(*fi).WT((i+1)%3));
		}

	int orgflag = (*fi).Flags();
	for (i=0; i<SplitTab[ind].TriNum; ++i)
		for(j=0;j<3;++j)
		{
			(*nf[i]).V(j)=&*vv[SplitTab[ind].TV[i][j]];

			if(tri::HasPerWedgeTexCoord(m)) //analogo ai vertici...
				(*nf[i]).WT(j) = wtt[SplitTab[ind].TV[i][j]];

			assert((*nf[i]).V(j)!=0);
			if(SplitTab[ind].TE[i][j]!=3)
			{
				if(orgflag & (MESH_TYPE::FaceType::BORDER0<<(SplitTab[ind].TE[i][j])))
					(*nf[i]).SetB(j);
				else
					(*nf[i]).ClearB(j);

				if(orgflag & (MESH_TYPE::FaceType::FACEEDGESEL0<<(SplitTab[ind].TE[i][j])))
					(*nf[i]).SetFaceEdgeS(j);
				else
					(*nf[i]).ClearFaceEdgeS(j);
			}
			else
			{
				(*nf[i]).ClearB(j);
				(*nf[i]).ClearFaceEdgeS(j);
			}
		}

	  if(SplitTab[ind].TriNum==3 &&
	     SquaredDistance(vv[SplitTab[ind].swap[0][0]]->P(),vv[SplitTab[ind].swap[0][1]]->P()) <
	     SquaredDistance(vv[SplitTab[ind].swap[1][0]]->P(),vv[SplitTab[ind].swap[1][1]]->P()) )
	  { // swap the last two triangles
		(*nf[2]).V(1)=(*nf[1]).V(0);
		(*nf[1]).V(1)=(*nf[2]).V(0);
		if(tri::HasPerWedgeTexCoord(m)){ //swap also textures coordinates
			(*nf[2]).WT(1)=(*nf[1]).WT(0);
			(*nf[1]).WT(1)=(*nf[2]).WT(0);
		}

		if((*nf[1]).IsB(0)) (*nf[2]).SetB(1); else (*nf[2]).ClearB(1);
		if((*nf[2]).IsB(0)) (*nf[1]).SetB(1); else (*nf[1]).ClearB(1);
		(*nf[1]).ClearB(0);
		(*nf[2]).ClearB(0);

		if((*nf[1]).IsFaceEdgeS(0)) (*nf[2]).SetFaceEdgeS(1); else (*nf[2]).ClearFaceEdgeS(1);
		if((*nf[2]).IsFaceEdgeS(0)) (*nf[1]).SetFaceEdgeS(1); else (*nf[1]).ClearFaceEdgeS(1);
		(*nf[1]).ClearFaceEdgeS(0);
		(*nf[2]).ClearFaceEdgeS(0);
	  }
	}

	assert(lastf==m.face.end());	 // critical assert: we MUST have used all the faces that we forecasted we need and that we previously allocated.
	assert(!m.vert.empty());
	for(fi=m.face.begin();fi!=m.face.end();++fi) if(!(*fi).IsD()){
		assert((*fi).V(0)>=&*m.vert.begin() && (*fi).V(0)<=&m.vert.back() );
	  assert((*fi).V(1)>=&*m.vert.begin() && (*fi).V(1)<=&m.vert.back() );
	  assert((*fi).V(2)>=&*m.vert.begin() && (*fi).V(2)<=&m.vert.back() );
	}
	tri::UpdateTopology<MESH_TYPE>::FaceFace(m);

	tri::Allocator<MESH_TYPE> :: template DeletePerFaceAttribute<RefinedFaceData<VertexPointer> >  (m,RD);

	return true;
}

} // namespace tri
} // namespace vcg

#endif