File: voronoi_processing.h

package info (click to toggle)
meshlab 2020.09%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 45,132 kB
  • sloc: cpp: 400,238; ansic: 31,952; javascript: 1,578; sh: 387; yacc: 238; lex: 139; python: 86; makefile: 30
file content (1936 lines) | stat: -rw-r--r-- 73,780 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
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
/****************************************************************************
* 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 VORONOI_PROCESSING_H
#define VORONOI_PROCESSING_H

#include<vcg/complex/algorithms/geodesic.h>
#include<vcg/complex/algorithms/update/color.h>
#include<vcg/complex/algorithms/refine.h>
#include<vcg/complex/algorithms/smooth.h>
#include<vcg/space/fitting3.h>
#include<wrap/callback.h>

namespace vcg
{
namespace tri
{

struct VoronoiProcessingParameter
{
  enum {
    None=0,
    DistanceFromSeed=1,
    DistanceFromBorder=2,
    RegionArea=3
  };

  VoronoiProcessingParameter()  {}
  
  int colorStrategy=DistanceFromSeed;

  float areaThresholdPerc=0;
  bool deleteUnreachedRegionFlag=false;

  bool unbiasedSeedFlag= true;
  bool constrainSelectedSeed=false;   /// If true the selected vertexes define a constraining domain:
                                /// During relaxation all selected seeds are constrained to move
                                /// only on other selected vertices.
                                /// In this way you can constrain some seed to move only on certain
                                /// domains, for example moving only along some linear features
                                /// like border of creases.

  bool relaxOnlyConstrainedFlag=false;

  bool preserveFixedSeed=false;       /// If true the 'fixed' seeds are not moved during relaxation.
                                /// \see MarkVertexVectorAsFixed function to see how to fix a set of seeds.

  float refinementRatio = 5.0f; /// It defines how much the input mesh has to be refined in order to have a supporting
                                /// triangulation that is dense enough to well approximate the voronoi diagram.
                                /// reasonable values are in the range 4..10. It is used by PreprocessForVoronoi and this value
                                /// says how many triangles you should expect in a voronoi region of a given radius.
  float seedPerturbationProbability=0;      /// if true at each iteration step each seed has the given probability to be perturbed a little.
  float seedPerturbationAmount = 0.001f;      /// As a bbox diag fraction (e.g. in the 0..1 range).

  // Convertion to Voronoi Diagram Parameters

  bool triangulateRegion=false; /// If true when building the voronoi diagram mesh each region is a
                                /// triangulated polygon. Otherwise it each voronoi region is a star
                                /// triangulation with the original seed in the center.

  bool collapseShortEdge=false;
  float collapseShortEdgePerc = 0.01f;

  bool geodesicRelaxFlag= true;
  
  CallBackPos *lcb=DummyCallBackPos;
};

template <class MeshType, class DistanceFunctor = EuclideanDistance<MeshType> >
class VoronoiProcessing
{
  typedef typename MeshType::CoordType				CoordType;
  typedef typename MeshType::ScalarType				ScalarType;
  typedef typename MeshType::VertexType				VertexType;
  typedef typename MeshType::VertexPointer		VertexPointer;
  typedef typename MeshType::VertexIterator		VertexIterator;
  typedef typename MeshType::FacePointer			FacePointer;
  typedef typename MeshType::FaceIterator			FaceIterator;
  typedef typename MeshType::FaceType					FaceType;
  typedef typename MeshType::FaceContainer		FaceContainer;
  typedef typename tri::Geodesic<MeshType>::VertDist VertDist;
  typedef typename face::Pos<FaceType>        PosType;

public:
	static math::MarsenneTwisterRNG &RandomGenerator()
    {
        static math::MarsenneTwisterRNG rnd;
        return rnd;
    }

  typedef typename MeshType::template PerVertexAttributeHandle<VertexPointer> PerVertexPointerHandle;
  typedef typename MeshType::template PerVertexAttributeHandle<bool> PerVertexBoolHandle;
  typedef typename MeshType::template PerVertexAttributeHandle<float> PerVertexFloatHandle;
  typedef typename MeshType::template PerFaceAttributeHandle<VertexPointer> PerFacePointerHandle;



// Given a vector of point3f it finds the closest vertices on the mesh.
static void SeedToVertexConversion(MeshType &m,std::vector<CoordType> &seedPVec,std::vector<VertexType *> &seedVVec, bool compactFlag = true)
{
    typedef typename vcg::SpatialHashTable<VertexType, ScalarType> HashVertexGrid;
    seedVVec.clear();

    HashVertexGrid HG;
    HG.Set(m.vert.begin(),m.vert.end());

    const float dist_upper_bound=m.bbox.Diag()/10.0;

    typename std::vector<CoordType>::iterator pi;
    for(pi=seedPVec.begin();pi!=seedPVec.end();++pi)
        {
            ScalarType dist;
            VertexPointer vp;
            vp=tri::GetClosestVertex<MeshType,HashVertexGrid>(m, HG, *pi, dist_upper_bound, dist);
            if(vp)
                {
                    seedVVec.push_back(vp);
                }
        }
    if(compactFlag)
    {
      std::sort(seedVVec.begin(),seedVVec.end());
      typename std::vector<VertexType *>::iterator vi = std::unique(seedVVec.begin(),seedVVec.end());
      seedVVec.resize( std::distance(seedVVec.begin(),vi) );
    }
}


static void ComputePerVertexSources(MeshType &m, std::vector<VertexType *> &seedVec, DistanceFunctor &df)
{
  tri::Allocator<MeshType>::DeletePerVertexAttribute(m,"sources"); // delete any conflicting handle regardless of the type...
  PerVertexPointerHandle vertexSources =  tri::Allocator<MeshType>:: template AddPerVertexAttribute<VertexPointer> (m,"sources");

  tri::Allocator<MeshType>::DeletePerFaceAttribute(m,"sources"); // delete any conflicting handle regardless of the type...
  tri::Allocator<MeshType>::template AddPerFaceAttribute<VertexPointer> (m,"sources");

  assert(tri::Allocator<MeshType>::IsValidHandle(m,vertexSources));

  tri::Geodesic<MeshType>::Compute(m,seedVec,df,std::numeric_limits<ScalarType>::max(),0,&vertexSources);
}

static void VoronoiColoring(MeshType &m, bool frontierFlag=true)
{
  PerVertexPointerHandle sources =  tri::Allocator<MeshType>:: template GetPerVertexAttribute<VertexPointer> (m,"sources");
  assert(tri::Allocator<MeshType>::IsValidHandle(m,sources));

  if(frontierFlag)
  {
    //static_cast<VertexPointer>(NULL) has been introduced just to avoid an error in the MSVS2010's compiler confusing pointer with int. You could use nullptr to avoid it, but it's not supported by all compilers.
    //The error should have been removed from MSVS2012
    std::pair<float,VertexPointer> zz(0.0f,static_cast<VertexPointer>(NULL));
    std::vector< std::pair<float,VertexPointer> > regionArea(m.vert.size(),zz);
    std::vector<VertexPointer> frontierVec;
    GetAreaAndFrontier(m, sources,  regionArea, frontierVec);
    tri::Geodesic<MeshType>::Compute(m,frontierVec);
  }
  float minQ =  std::numeric_limits<float>::max();
  float maxQ = -std::numeric_limits<float>::max();
  
  for(VertexIterator vi=m.vert.begin();vi!=m.vert.end();++vi)
    if(sources[*vi])
    {
      if( (*vi).Q() < minQ) minQ=(*vi).Q();
      if( (*vi).Q() > maxQ) maxQ=(*vi).Q();
    }
  for(VertexIterator vi=m.vert.begin();vi!=m.vert.end();++vi)
    if(sources[*vi])
          (*vi).C().SetColorRamp(minQ,maxQ,(*vi).Q());
  else 
      (*vi).C()=Color4b::DarkGray;
  
//  tri::UpdateColor<MeshType>::PerVertexQualityRamp(m);
}

static void VoronoiAreaColoring(MeshType &m,std::vector<VertexType *> &seedVec,
                                std::vector< std::pair<float,VertexPointer> > &regionArea)
{
  PerVertexPointerHandle vertexSources =  tri::Allocator<MeshType>:: template GetPerVertexAttribute<VertexPointer> (m,"sources");
  float meshArea = tri::Stat<MeshType>::ComputeMeshArea(m);
  float expectedArea = meshArea/float(seedVec.size());
  for(size_t i=0;i<m.vert.size();++i)
      m.vert[i].C()=Color4b::ColorRamp(expectedArea *0.75f ,expectedArea*1.25f, regionArea[tri::Index(m,vertexSources[i])].first);
}
// It associates the faces with a given vertex according to the vertex associations
//
// It READS  the PerVertex attribute 'sources'
// It WRITES the PerFace attribute 'sources'

static void FaceAssociateRegion(MeshType &m)
{
  PerFacePointerHandle   faceSources =  tri::Allocator<MeshType>:: template GetPerFaceAttribute<VertexPointer> (m,"sources");
  PerVertexPointerHandle vertexSources =  tri::Allocator<MeshType>:: template GetPerVertexAttribute<VertexPointer> (m,"sources");
  for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi)
  {
    faceSources[fi]=0;
    std::vector<VertexPointer> vp(3);
    for(int i=0;i<3;++i) vp[i]=vertexSources[fi->V(i)];

    for(int i=0;i<3;++i) // First try to associate to the most reached vertex
    {
      if(vp[0]==vp[1] && vp[0]==vp[2]) faceSources[fi] = vp[0];
      else
      {
        if(vp[0]==vp[1] && vp[0]->Q()< vp[2]->Q()) faceSources[fi] = vp[0];
        if(vp[0]==vp[2] && vp[0]->Q()< vp[1]->Q()) faceSources[fi] = vp[0];
        if(vp[1]==vp[2] && vp[1]->Q()< vp[0]->Q()) faceSources[fi] = vp[1];
      }
    }
  }
  tri::UpdateTopology<MeshType>::FaceFace(m);
  int unassCnt=0;
  do
  {
    unassCnt=0;
    for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi)
    {
      if(faceSources[fi]==0)
      {
        std::vector<VertexPointer> vp(3);
        for(int i=0;i<3;++i)
          vp[i]=faceSources[fi->FFp(i)];

        if(vp[0]!=0 && (vp[0]==vp[1] || vp[0]==vp[2]))
          faceSources[fi] = vp[0];
        else if(vp[1]!=0 && (vp[1]==vp[2]))
          faceSources[fi] = vp[1];
        else
          faceSources[fi] = std::max(vp[0],std::max(vp[1],vp[2]));
        if(faceSources[fi]==0) unassCnt++;
      }
    }
  }
  while(unassCnt>0);
}

// Select all the faces with a given source vertex <vp>
// It reads the PerFace attribute 'sources'

static int FaceSelectAssociateRegion(MeshType &m, VertexPointer vp)
{
  PerFacePointerHandle sources =  tri::Allocator<MeshType>:: template FindPerFaceAttribute<VertexPointer> (m,"sources");
  assert(tri::Allocator<MeshType>::IsValidHandle(m,sources));
  tri::UpdateSelection<MeshType>::Clear(m);
  int selCnt=0;
  for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi)
  {
    if(sources[fi]==vp)
    {
      fi->SetS();
      ++selCnt;
    }
  }
  return selCnt;
}

// Given a seed <vp>, it selects all the faces that have the minimal distance vertex sourced by the given <vp>.
// <vp> can be null (it search for unreached faces...)
// returns the number of selected faces;
//
// It reads the PerVertex attribute 'sources'
static int FaceSelectRegion(MeshType &m, VertexPointer vp)
{
  PerVertexPointerHandle sources =  tri::Allocator<MeshType>:: template GetPerVertexAttribute<VertexPointer> (m,"sources");
  assert(tri::Allocator<MeshType>::IsValidHandle(m,sources));
  tri::UpdateSelection<MeshType>::Clear(m);
  int selCnt=0;
  for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi)
  {
    int minInd = 0; float minVal=std::numeric_limits<float>::max();
    for(int i=0;i<3;++i)
    {
      if((*fi).V(i)->Q()<minVal)
      {
        minInd=i;
        minVal=(*fi).V(i)->Q();
      }
    }

    if(	sources[(*fi).V(minInd)] == vp)
    {
      fi->SetS();
      selCnt++;
    }
  }
  return selCnt;
}

/// Given a mesh with for each vertex the link to the closest seed
/// (e.g. for all vertexes we know what is the corresponding voronoi region)
/// we compute:
///  area of all the voronoi regions
///  the vector of the frontier vertexes (e.g. vert of faces shared by at least two regions)
///
///  Area is computed only for triangles that fully belong to a given source.

static void GetAreaAndFrontier(MeshType &m, PerVertexPointerHandle &sources,
                               std::vector< std::pair<float, VertexPointer> > &regionArea, // for each seed we store area
                               std::vector<VertexPointer> &frontierVec)
{
  tri::UpdateFlags<MeshType>::VertexClearV(m);
  frontierVec.clear();
  for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi)
  {
    VertexPointer s0 = sources[(*fi).V(0)];
    VertexPointer s1 = sources[(*fi).V(1)];
    VertexPointer s2 = sources[(*fi).V(2)];
    assert(s0 && s1 && s2);
    if((s0 != s1) || (s0 != s2) )
    {
      for(int i=0;i<3;++i)
        if(!fi->V(i)->IsV())
        {
          frontierVec.push_back(fi->V(i));
          fi->V(i)->SetV();
        }
    }
    else // the face belongs to a single region; accumulate area;
    {
      if(s0 != 0)
      {
        int seedIndex = tri::Index(m,s0);
        regionArea[seedIndex].first+=DoubleArea(*fi)*0.5f;
        regionArea[seedIndex].second=s0;
      }
    }
  }
}


/// Given a mesh with for each vertex the link to the closest seed
/// we compute:
///  the vector of the corner faces (ie the faces shared exactly by three regions)
///  the vector of the frontier faces that are on the boundary.

static void GetFaceCornerVec(MeshType &m, PerVertexPointerHandle &sources,
                               std::vector<FacePointer> &cornerVec,
                               std::vector<FacePointer> &borderCornerVec)
{
  tri::UpdateFlags<MeshType>::VertexClearV(m);
  cornerVec.clear();
  for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi)
  {
    VertexPointer s0 = sources[(*fi).V(0)];
    VertexPointer s1 = sources[(*fi).V(1)];
    VertexPointer s2 = sources[(*fi).V(2)];
    assert(s0 && s1 && s2);
    if(s1!=s2 && s0!=s1 && s0!=s2) {
        cornerVec.push_back(&*fi);
      }
    else
    {
      if(isBorderCorner(&*fi,sources))
          borderCornerVec.push_back(&*fi);
    }
  }
}

static bool isBorderCorner(FaceType *f, typename MeshType::template PerVertexAttributeHandle<VertexPointer> &sources)
{
  for(int i=0;i<3;++i)
  {
    if(sources[(*f).V0(i)] != sources[(*f).V1(i)] && f->IsB(i))
      return true;
  }
  return false;
}

// Given two supposedly adjacent border corner faces it finds the source common to them;
static VertexPointer CommonSourceBetweenBorderCorner(FacePointer f0, FacePointer f1,  typename MeshType::template PerVertexAttributeHandle<VertexPointer> &sources)
{
  assert(isBorderCorner(f0,sources));
  assert(isBorderCorner(f1,sources));
  int b0 =-1,b1=-1;
  for(int i=0;i<3;++i)
  {
    if(face::IsBorder(*f0,i)) b0=i;
    if(face::IsBorder(*f1,i)) b1=i;
  }
  assert(b0!=-1 && b1!=-1);

  if( (sources[f0->V0(b0)] == sources[f1->V0(b1)]) || (sources[f0->V0(b0)] == sources[f1->V1(b1)]) )
    return sources[f0->V0(b0)];

  if( (sources[f0->V1(b0)] == sources[f1->V0(b1)]) || (sources[f0->V1(b0)] == sources[f1->V1(b1)]) )
    return sources[f0->V1(b0)];

  assert(0);
  return 0;
}


static void ConvertVoronoiDiagramToMesh(MeshType &m,
                                        MeshType &outMesh, MeshType &outPoly,
                                        std::vector<VertexType *> &seedVec,
                                        VoronoiProcessingParameter &vpp )
{
  tri::RequirePerVertexAttribute(m,"sources");
  PerVertexPointerHandle sources = tri::Allocator<MeshType>:: template GetPerVertexAttribute<VertexPointer> (m,"sources");
  outMesh.Clear();
  outPoly.Clear();
  tri::UpdateTopology<MeshType>::FaceFace(m);
  tri::UpdateFlags<MeshType>::FaceBorderFromFF(m);

  std::vector<FacePointer> innerCornerVec,   // Faces adjacent to three different regions
                           borderCornerVec;  // Faces that are on the border and adjacent to at least two regions.
  GetFaceCornerVec(m, sources, innerCornerVec, borderCornerVec);

  // For each seed collect all the vertices and build
  for(size_t i=0;i<seedVec.size();++i)
    tri::Allocator<MeshType>::AddVertex(outMesh,seedVec[i]->P(),Color4b::DarkGray);

  for(size_t i=0;i<seedVec.size();++i)
  {
    VertexPointer curSeed=seedVec[i];
    vector<CoordType> pt;
    for(size_t j=0;j<innerCornerVec.size();++j)
      for(int qq=0;qq<3;qq++)
        if(sources[innerCornerVec[j]->V(qq)] == curSeed)
        {
          pt.push_back(Barycenter(*innerCornerVec[j]));
          break;
        }
    for(size_t j=0;j<borderCornerVec.size();++j)
      for(int qq=0;qq<3;qq++)
        if(sources[borderCornerVec[j]->V(qq)] == curSeed)
        {
          CoordType edgeCenter;
          for(int jj=0;jj<3;++jj) if(face::IsBorder(*(borderCornerVec[j]),jj))
            edgeCenter=(borderCornerVec[j]->P0(jj)+borderCornerVec[j]->P1(jj))/2.0f;
          pt.push_back(edgeCenter);
          break;
        }
    Plane3<ScalarType> pl;
    pt.push_back(curSeed->P());
    FitPlaneToPointSet(pt,pl);
    pt.pop_back();
    CoordType nZ = pl.Direction();
    CoordType nX = (pt[0]-curSeed->P()).Normalize();
    CoordType nY = (nX^nZ).Normalize();
    vector<std::pair<float,int> > angleVec(pt.size());
    for(size_t j=0;j<pt.size();++j)
    {
      CoordType p = (pt[j]-curSeed->P()).Normalize();
      float angle = 180.0f+math::ToDeg(atan2(p*nY,p*nX));
      angleVec[j] = make_pair(angle,j);
    }
    std::sort(angleVec.begin(),angleVec.end());
    // Now build another piece of mesh.
    int curRegionStart=outMesh.vert.size();


    for(size_t j=0;j<pt.size();++j)
      tri::Allocator<MeshType>::AddVertex(outMesh,pt[angleVec[j].second],Color4b::LightGray);

    for(size_t j=0;j<pt.size();++j){
      float curAngle = angleVec[(j+1)%pt.size()].first - angleVec[j].first;
//      printf("seed %4i (%i) - face %i angle %5.1f %5.1f %5.1f\n",i,curRegionStart,j,angleVec[j].first,angleVec[(j+1)%pt.size()].first,curAngle);
      if(curAngle < 0) curAngle += 360.0;
      if(curAngle < 170.0)
        tri::Allocator<MeshType>::AddFace(outMesh,
                                          &outMesh.vert[i   ],
                                          &outMesh.vert[curRegionStart + j ],
            &outMesh.vert[curRegionStart + ((j+1)%pt.size())]);
       outMesh.face.back().SetF(0);
       outMesh.face.back().SetF(2);
    }
  } // end for each seed.
  tri::Clean<MeshType>::RemoveDuplicateVertex(outMesh);
  tri::UpdateTopology<MeshType>::FaceFace(outMesh);
  bool oriented,orientable;
  tri::Clean<MeshType>::OrientCoherentlyMesh(outMesh,oriented,orientable);
  tri::UpdateTopology<MeshType>::FaceFace(outMesh);

  // last loop to remove faux edges bit that are now on the boundary.
  for(FaceIterator fi=outMesh.face.begin();fi!=outMesh.face.end();++fi)
    for(int i=0;i<3;++i)
      if(face::IsBorder(*fi,i) && fi->IsF(i)) fi->ClearF(i);

  std::vector< typename tri::UpdateTopology<MeshType>::PEdge> EdgeVec;

  // ******************* star to tri conversion *********
  // If requested the voronoi regions are converted from a star arragned polygon
  // with vertex on the seed to a simple triangulated polygon by mean of a simple edge collapse
  if(vpp.triangulateRegion)
  {
    tri::UpdateFlags<MeshType>::FaceBorderFromFF(outMesh);
    tri::UpdateFlags<MeshType>::VertexBorderFromFaceBorder(outMesh);
    for(FaceIterator fi=outMesh.face.begin();fi!=outMesh.face.end();++fi) if(!fi->IsD())
    {
      for(int i=0;i<3;++i)
      {
        bool b0 = fi->V0(i)->IsB();
        bool b1 = fi->V1(i)->IsB();
        if( ((b0  && b1) || (fi->IsF(i) && !b0) ) &&
            tri::Index(outMesh,fi->V0(i))<seedVec.size())
        {
          if(!seedVec[tri::Index(outMesh,fi->V0(i))]->IsS())
            if(face::FFLinkCondition(*fi, i))
            {
              face::FFEdgeCollapse(outMesh, *fi,i); // we delete vertex fi->V0(i)
              break;
            }
        }
      }
    }
  }

  // Now a plain conversion of the non faux edges into a polygonal mesh
  tri::UpdateTopology<MeshType>::FillUniqueEdgeVector(outMesh,EdgeVec,false);
  tri::UpdateTopology<MeshType>::AllocateEdge(outMesh);
  for(size_t i=0;i<outMesh.vert.size();++i)
    tri::Allocator<MeshType>::AddVertex(outPoly,outMesh.vert[i].P());
  for(size_t i=0;i<EdgeVec.size();++i)
  {
    size_t e0 = tri::Index(outMesh,EdgeVec[i].v[0]);
    size_t e1 = tri::Index(outMesh,EdgeVec[i].v[1]);
    assert(e0<outPoly.vert.size());
    tri::Allocator<MeshType>::AddEdge(outPoly,&(outPoly.vert[e0]),&(outPoly.vert[e1]));
  }

}

/// \brief Build a mesh of voronoi diagram from the given seeds
///
/// This function assumes that you have just run a geodesic like algorithm over your mesh using
/// a seed set as starting points and that there is an PerVertex Attribute called 'sources'
/// with pointers to the seed source. Usually you can initialize it with something like
///
///   DistanceFunctor &df,
///   tri::Geodesic<MeshType>::Compute(m, seedVec, df, std::numeric_limits<ScalarType>::max(),0,&sources);
///

static void ConvertVoronoiDiagramToMeshOld(MeshType &m,
                                        MeshType &outMesh, MeshType &outPoly,
                                        std::vector<VertexType *> &seedVec,
                                        VoronoiProcessingParameter &vpp )
{
  tri::RequirePerVertexAttribute(m,"sources");
  PerVertexPointerHandle sources = tri::Allocator<MeshType>:: template GetPerVertexAttribute<VertexPointer> (m,"sources");

  outMesh.Clear();
  outPoly.Clear();
  tri::UpdateTopology<MeshType>::FaceFace(m);
  tri::UpdateFlags<MeshType>::FaceBorderFromFF(m);

  std::map<VertexPointer, int> seedMap;  // It says if a given vertex of m is a seed (and what position it has in the seed vector)
  for(size_t i=0;i<m.vert.size();++i)
    seedMap[&(m.vert[i])]=-1;
  for(size_t i=0;i<seedVec.size();++i)
    seedMap[seedVec[i]]=i;

  // Consistency Checks
  for(VertexIterator vi=m.vert.begin();vi!=m.vert.end();++vi)
  {
    assert(sources[vi] != 0);  // all vertices mush have a source must be seeds.
    int ind=tri::Index(m,sources[vi]);
    assert((ind>=0) && (ind<m.vn)); // the source must be a vertex of the mesh
    assert(seedMap[sources[vi]]!=-1); // the source must be one of the seedVec
  }

  std::vector<FacePointer> innerCornerVec,   // Faces adjacent to three different regions
                           borderCornerVec;  // Faces that are on the border and adjacent to at least two regions.
  GetFaceCornerVec(m, sources, innerCornerVec, borderCornerVec);

  std::map<FacePointer,int> vertexIndCornerMap; // Given a cornerFace (border or inner) what is the corresponding vertex?
  for(size_t i=0;i<m.face.size();++i)
    vertexIndCornerMap[&(m.face[i])]=-1;

  // First add all the needed vertices: seeds and corners
  for(size_t i=0;i<seedVec.size();++i)
    tri::Allocator<MeshType>::AddVertex(outMesh, seedVec[i]->P(),Color4b::White);

  for(size_t i=0;i<innerCornerVec.size();++i){
    tri::Allocator<MeshType>::AddVertex(outMesh, vcg::Barycenter(*(innerCornerVec[i])),Color4b::Gray);
    vertexIndCornerMap[innerCornerVec[i]] = outMesh.vn-1;
  }
  for(size_t i=0;i<borderCornerVec.size();++i){
    Point3f edgeCenter;
    for(int j=0;j<3;++j) if(face::IsBorder(*(borderCornerVec[i]),j))
      edgeCenter=(borderCornerVec[i]->P0(j)+borderCornerVec[i]->P1(j))/2.0f;
    tri::Allocator<MeshType>::AddVertex(outMesh, edgeCenter,Color4b::Gray);
    vertexIndCornerMap[borderCornerVec[i]] = outMesh.vn-1;
  }
  tri::Append<MeshType,MeshType>::MeshCopy(outPoly,outMesh);

  // There is a voronoi edge if there are two corner face that share two sources.
  // In such a case we add a pair of triangles with an edge connecting these two corner faces
  // and with the two involved sources
  // For each pair of adjacent seed we store the first of the two corner that we encounter.
  std::map<std::pair<VertexPointer,VertexPointer>, FacePointer > VoronoiEdge;

  // 1) Build internal triangles
  // Loop build all the triangles connecting seeds with internal corners
  // we loop over the all the voronoi corner (triangles with three different sources)
  // we build
  for(size_t i=0;i<innerCornerVec.size();++i)
  {
    for(int j=0;j<3;++j)
    {
      VertexPointer v0 = sources[innerCornerVec[i]->V0(j)];
      VertexPointer v1 = sources[innerCornerVec[i]->V1(j)];
      assert(seedMap[v0]>=0);assert(seedMap[v1]>=0);

      if(v1<v0) std::swap(v0,v1); assert(v1!=v0);

      if(VoronoiEdge[std::make_pair(v0,v1)] == 0)
        VoronoiEdge[std::make_pair(v0,v1)] = innerCornerVec[i];
      else
      {
        FacePointer otherCorner = VoronoiEdge[std::make_pair(v0,v1)];
        VertexPointer corner0 = &(outMesh.vert[vertexIndCornerMap[innerCornerVec[i]]]);
        VertexPointer corner1 = &(outMesh.vert[vertexIndCornerMap[otherCorner]]);
        tri::Allocator<MeshType>::AddFace(outMesh,&(outMesh.vert[seedMap[v0]]), corner0, corner1);
        tri::Allocator<MeshType>::AddFace(outMesh,&(outMesh.vert[seedMap[v1]]), corner1, corner0);
      }
    }
  }

  // 2) build the boundary facets:
  // We loop over border corners and build triangles with seed vertex
  // we do **only** triangles with a  bordercorner and a internal 'corner'
  for(size_t i=0;i<borderCornerVec.size();++i)
  {
    VertexPointer s0 = sources[borderCornerVec[i]->V(0)]; // All bordercorner faces have only two different regions
    VertexPointer s1 = sources[borderCornerVec[i]->V(1)];
    if(s1==s0)    s1 = sources[borderCornerVec[i]->V(2)];
    if(s1<s0) std::swap(s0,s1); assert(s1!=s0);

    FacePointer innerCorner = VoronoiEdge[std::make_pair(s0,s1)] ;
    if(innerCorner)
    {
      VertexPointer corner0 = &(outMesh.vert[vertexIndCornerMap[innerCorner]]);
      VertexPointer corner1 = &(outMesh.vert[vertexIndCornerMap[borderCornerVec[i]]]);
      tri::Allocator<MeshType>::AddFace(outMesh,&(outMesh.vert[seedMap[s0]]), corner0, corner1);
      tri::Allocator<MeshType>::AddFace(outMesh,&(outMesh.vert[seedMap[s1]]), corner0, corner1);
    }
  }

  // Final pass
  tri::UpdateFlags<MeshType>::FaceClearV(m);
  bool AllFaceVisited = false;
  while(!AllFaceVisited)
  {
    // search for a unvisited boundary face
    face::Pos<FaceType> pos,startPos;
    AllFaceVisited=true;
    for(size_t i=0; (AllFaceVisited) && (i<borderCornerVec.size()); ++i)
      if(!borderCornerVec[i]->IsV())
      {
        for(int j=0;j<3;++j)
          if(face::IsBorder(*(borderCornerVec[i]),j))
          {
            pos.Set(borderCornerVec[i],j,borderCornerVec[i]->V(j));
            AllFaceVisited =false;
          }
      }
    if(AllFaceVisited) break;
    assert(pos.IsBorder());
    startPos=pos;
    bool foundBorderSeed=false;
    FacePointer curBorderCorner = pos.F();
    do
    {
      pos.F()->SetV();
      pos.NextB();
      if(sources[pos.V()]==pos.V())
        foundBorderSeed=true;
      assert(isBorderCorner(curBorderCorner,sources));
      if(isBorderCorner(pos.F(),sources))
        if(pos.F() != curBorderCorner)
        {
          VertexPointer curReg = CommonSourceBetweenBorderCorner(curBorderCorner, pos.F(),sources);
          VertexPointer curSeed = &(outMesh.vert[seedMap[curReg]]);
          int otherCorner0 = vertexIndCornerMap[pos.F() ];
          int otherCorner1 = vertexIndCornerMap[curBorderCorner];
          VertexPointer corner0 = &(outMesh.vert[otherCorner0]);
          VertexPointer corner1 = &(outMesh.vert[otherCorner1]);
          if(!foundBorderSeed)
            tri::Allocator<MeshType>::AddFace(outMesh,curSeed,corner0,corner1);
          foundBorderSeed=false;
          curBorderCorner=pos.F();
        }
    }
    while(pos!=startPos);
  }

  //**************** CLEANING ***************
  // 1) reorient
  bool oriented,orientable;
  tri::UpdateTopology<MeshType>::FaceFace(outMesh);
  tri::Clean<MeshType>::OrientCoherentlyMesh(outMesh,oriented,orientable);
//  assert(orientable);
  // check that the normal of the input mesh are consistent with the result
  tri::UpdateNormal<MeshType>::PerVertexNormalizedPerFaceNormalized(outMesh);
  tri::UpdateNormal<MeshType>::PerVertexNormalizedPerFaceNormalized(m);
  if(seedVec[0]->N() * outMesh.vert[0].N() < 0 )
    tri::Clean<MeshType>::FlipMesh(outMesh);

  tri::UpdateTopology<MeshType>::FaceFace(outMesh);
  tri::UpdateFlags<MeshType>::FaceBorderFromFF(outMesh);

  // 2) Remove Flips
  tri::UpdateNormal<MeshType>::PerFaceNormalized(outMesh);
  tri::UpdateFlags<MeshType>::FaceClearV(outMesh);
  for(FaceIterator fi=outMesh.face.begin();fi!=outMesh.face.end();++fi)
  {
    int badDiedralCnt=0;
    for(int i=0;i<3;++i)
      if(fi->N() * fi->FFp(i)->N() <0 ) badDiedralCnt++;

    if(badDiedralCnt == 2) fi->SetV();
  }
  for(FaceIterator fi=outMesh.face.begin();fi!=outMesh.face.end();++fi)
    if(fi->IsV())  Allocator<MeshType>::DeleteFace(outMesh,*fi);
  tri::Allocator<MeshType>::CompactEveryVector(outMesh);
  tri::UpdateTopology<MeshType>::FaceFace(outMesh);
  tri::UpdateFlags<MeshType>::FaceBorderFromFF(outMesh);
  tri::UpdateFlags<MeshType>::VertexBorderFromFaceBorder(outMesh);

  // 3) set up faux bits
  for(FaceIterator fi=outMesh.face.begin();fi!=outMesh.face.end();++fi)
    for(int i=0;i<3;++i)
    {
      size_t v0 = tri::Index(outMesh,fi->V0(i) );
      size_t v1 = tri::Index(outMesh,fi->V1(i) );
      if (v0 < seedVec.size() && !(seedVec[v0]->IsB() && fi->IsB(i))) fi->SetF(i);
      if (v1 < seedVec.size() && !(seedVec[v1]->IsB() && fi->IsB(i))) fi->SetF(i);
    }

  if(vpp.collapseShortEdge)
  {
    float distThr = m.bbox.Diag() * vpp.collapseShortEdgePerc;
    for(FaceIterator fi=outMesh.face.begin();fi!=outMesh.face.end();++fi) if(!fi->IsD())
    {
      for(int i=0;i<3;++i)
        if((Distance(fi->P0(i),fi->P1(i))<distThr) && !fi->IsF(i))
        {
//          printf("Collapsing face %i:%i e%i \n",tri::Index(outMesh,*fi),tri::Index(outMesh,fi->FFp(i)),i);
          if ((!fi->V(i)->IsB())&&(face::FFLinkCondition(*fi, i)))
            face::FFEdgeCollapse(outMesh, *fi,i);
          break;
        }
    }
  }

  //******************** END OF CLEANING ****************


  // ******************* star to tri conversion *********
  // If requested the voronoi regions are converted from a star arragned polygon
  // with vertex on the seed to a simple triangulated polygon by mean of a simple edge collapse
  if(vpp.triangulateRegion)
  {
    for(FaceIterator fi=outMesh.face.begin();fi!=outMesh.face.end();++fi) if(!fi->IsD())
    {
      for(int i=0;i<3;++i)
      {
        bool b0 = fi->V0(i)->IsB();
        bool b1 = fi->V1(i)->IsB();
        if( ((b0  && b1) || (fi->IsF(i) && !b0 && !b1) ) &&
            tri::Index(outMesh,fi->V(i))<seedVec.size())
        {
          if(!seedVec[tri::Index(outMesh,fi->V(i))]->IsS())
            if(face::FFLinkCondition(*fi, i))
            {
              face::FFEdgeCollapse(outMesh, *fi,i);
              break;
            }
        }
      }
    }
  }

  // Now a plain conversion of the non faux edges into a polygonal mesh
  std::vector< typename tri::UpdateTopology<MeshType>::PEdge> EdgeVec;
  tri::UpdateTopology<MeshType>::FillUniqueEdgeVector(outMesh,EdgeVec,false);
  tri::UpdateTopology<MeshType>::AllocateEdge(outMesh);

  for(size_t i=0;i<EdgeVec.size();++i)
  {
    size_t e0 = tri::Index(outMesh,EdgeVec[i].v[0]);
    size_t e1 = tri::Index(outMesh,EdgeVec[i].v[1]);
    assert(e0<outPoly.vert.size());
    tri::Allocator<MeshType>::AddEdge(outPoly,&(outPoly.vert[e0]),&(outPoly.vert[e1]));
  }
}

class VoronoiEdge
{
public:
  VertexPointer r0,r1;
  FacePointer f0,f1;
  bool operator == (const VoronoiEdge &ve) const {return ve.r0==r0 && ve.r1==r1; }
  bool operator < (const VoronoiEdge &ve) const { return (ve.r0==r0)?ve.r1<r1:ve.r0<r0; }
  float Len() const { return Distance(vcg::Barycenter(*f0), vcg::Barycenter(*f1)); }
};

static void BuildVoronoiEdgeVec(MeshType &m, std::vector<VoronoiEdge> &edgeVec)
{
  PerVertexPointerHandle sources =  tri::Allocator<MeshType>:: template GetPerVertexAttribute<VertexPointer> (m,"sources");

  edgeVec.clear();
  std::vector<FacePointer> cornerVec;
  std::vector<FacePointer> borderCornerVec;
  GetFaceCornerVec(m,sources,cornerVec,borderCornerVec);
  // Now find all the voronoi edges: each edge (a *face pair) is identified by two voronoi regions
  typedef std::map< std::pair<VertexPointer,VertexPointer>, std::pair<FacePointer,FacePointer> > EdgeMapType;
  EdgeMapType EdgeMap;
  printf("cornerVec.size() %i\n",(int)cornerVec.size());

  for(size_t i=0;i<cornerVec.size();++i)
  {
    for(int j=0;j<3;++j)
    {
      VertexPointer v0 = sources[cornerVec[i]->V0(j)];
      VertexPointer v1 = sources[cornerVec[i]->V1(j)];
      assert(v0!=v1);
      if(v0>v1) std::swap(v1,v0);
      std::pair<VertexPointer,VertexPointer> adjRegion = std::make_pair(v0,v1);
      if(EdgeMap[adjRegion].first==0)
        EdgeMap[adjRegion].first = cornerVec[i];
      else
        EdgeMap[adjRegion].second = cornerVec[i];
    }
  }
  for(size_t i=0;i<borderCornerVec.size();++i)
  {
    VertexPointer v0 = sources[borderCornerVec[i]->V(0)];
    VertexPointer v1 = sources[borderCornerVec[i]->V(1)];
    if(v0==v1) v1 = sources[borderCornerVec[i]->V(2)];
    assert(v0!=v1);
    if(v0>v1) std::swap(v1,v0);
    std::pair<VertexPointer,VertexPointer> adjRegion = std::make_pair(v0,v1);
    if(EdgeMap[adjRegion].first==0)
      EdgeMap[adjRegion].first = borderCornerVec[i];
    else
      EdgeMap[adjRegion].second = borderCornerVec[i];

  }
  typename EdgeMapType::iterator mi;
  for(mi=EdgeMap.begin();mi!=EdgeMap.end();++mi)
  {
    if((*mi).second.first && (*mi).second.second)
    {
      assert((*mi).first.first && (*mi).first.second);
    edgeVec.push_back(VoronoiEdge());
    edgeVec.back().r0 = (*mi).first.first;
    edgeVec.back().r1 = (*mi).first.second;
    edgeVec.back().f0 = (*mi).second.first;
    edgeVec.back().f1 = (*mi).second.second;
    }
  }
}

static void BuildBiasedSeedVec(MeshType &m,
                               DistanceFunctor &df,
                               std::vector<VertexPointer> &seedVec,
                               std::vector<VertexPointer> &frontierVec,
                               std::vector<VertDist> &biasedFrontierVec,
                               VoronoiProcessingParameter &vpp)
{
    (void)df;
  biasedFrontierVec.clear();
  if(vpp.unbiasedSeedFlag)
  {
    for(size_t i=0;i<frontierVec.size();++i)
      biasedFrontierVec.push_back(VertDist(frontierVec[i],0));
    assert(biasedFrontierVec.size() == frontierVec.size());
    return;
  }

  std::vector<VoronoiEdge> edgeVec;
  BuildVoronoiEdgeVec(m,edgeVec);
  printf("Found %i edges on a diagram of %i seeds\n",int(edgeVec.size()),int(seedVec.size()));

  std::map<VertexPointer,std::vector<VoronoiEdge *> > SeedToEdgeVecMap;
  std::map< std::pair<VertexPointer,VertexPointer>, VoronoiEdge *> SeedPairToEdgeMap;
  float totalLen=0;
  for(size_t i=0;i<edgeVec.size();++i)
  {
    SeedToEdgeVecMap[edgeVec[i].r0].push_back(&(edgeVec[i]));
    SeedToEdgeVecMap[edgeVec[i].r1].push_back(&(edgeVec[i]));
    SeedPairToEdgeMap[std::make_pair(edgeVec[i].r0, edgeVec[i].r1)]=&(edgeVec[i]);
    assert (edgeVec[i].r0 < edgeVec[i].r1);
    totalLen +=edgeVec[i].Len();
  }

  // compute the perimeter of each region
  std::map <VertexPointer, float> regionPerymeter;
  for(size_t i=0;i<seedVec.size();++i)
  {
    for(size_t j=0;j<SeedToEdgeVecMap[seedVec[i]].size();++j)
    {
      VoronoiEdge *vep = SeedToEdgeVecMap[seedVec[i]][j];
      regionPerymeter[seedVec[i]]+=vep->Len();
    }
    printf("perimeter of region %i is %f\n",(int)i,regionPerymeter[seedVec[i]]);
  }


  PerVertexPointerHandle sources =  tri::Allocator<MeshType>:: template GetPerVertexAttribute<VertexPointer> (m,"sources");
  // The real bias for each edge is (perim)/(edge)
  // each source can belong to two edges max. so the weight is
  std::map<VertexPointer,float> weight;
  std::map<VertexPointer,int> cnt;
  float biasSum = totalLen/5.0f;
  for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi)
  {
    for(int i=0;i<3;++i)
    {
      VertexPointer s0 = sources[(*fi).V0(i)];
      VertexPointer s1 = sources[(*fi).V1(i)];
      if(s0!=s1)
      {
        if(s0>s1) std::swap(s0,s1);
        VoronoiEdge *ve = SeedPairToEdgeMap[std::make_pair(s0,s1)];
        if(!ve) printf("v %i %i \n",(int)tri::Index(m,s0),(int)tri::Index(m,s1));
        assert(ve);
        float el = ve->Len();
        weight[(*fi).V0(i)] += (regionPerymeter[s0]+biasSum)/(el+biasSum) ;
        weight[(*fi).V1(i)] += (regionPerymeter[s1]+biasSum)/(el+biasSum) ;
        cnt[(*fi).V0(i)]++;
        cnt[(*fi).V1(i)]++;
      }
    }
  }
  for(VertexIterator vi=m.vert.begin();vi!=m.vert.end();++vi)
  {
    if(cnt[&*vi]>0)
    {
//      float bias = weight[&*vi]/float(cnt[&*vi]);
      float bias = weight[&*vi]/float(cnt[&*vi]) + totalLen;
      biasedFrontierVec.push_back(VertDist(&*vi, bias));
    }
  }
  printf("Collected %i frontier vertexes\n",(int)biasedFrontierVec.size());
}


static void DeleteUnreachedRegions(MeshType &m, PerVertexPointerHandle &sources)
{
  tri::UpdateFlags<MeshType>::VertexClearV(m);
  for(size_t i=0;i<m.vert.size();++i)
    if(sources[i]==0) m.vert[i].SetV();

  for(FaceIterator fi=m.face.begin(); fi!=m.face.end();++fi)
    if(fi->V(0)->IsV() || fi->V(1)->IsV() || fi->V(2)->IsV() )
    {
      face::VFDetach(*fi);
      tri::Allocator<MeshType>::DeleteFace(m,*fi);
    }
  //		qDebug("Deleted faces not reached: %i -> %i",int(m.face.size()),m.fn);
  tri::Clean<MeshType>::RemoveUnreferencedVertex(m);
  tri::Allocator<MeshType>::CompactEveryVector(m);
}

/// Let f_p(q) be the squared distance of q from p
/// f_p(q) = (p_x-q_x)^2 + (p_y-q_y)^2 + (p_z-q_z)^2
/// f_p(q) = p_x^2 -2p_xq_x +q_x^2 + ... + p_z^2 -2p_zq_z +q_z^2
///

struct QuadricSumDistance
{
  ScalarType a;
  ScalarType c;
  CoordType b;
  QuadricSumDistance() {a=0; c=0; b[0]=0; b[1]=0; b[2]=0;}
  void AddPoint(CoordType p)
  {
    a+=1;
    assert(c>=0);
    c+=p*p;
    b[0]+= -2.0f*p[0];
    b[1]+= -2.0f*p[1];
    b[2]+= -2.0f*p[2];
  }

  ScalarType Eval(CoordType p) const
  {
    ScalarType d = a*(p*p) + b*p + c;
    assert(d>=0);
    return d;
  }

  CoordType Min() const
  {
    return b * -0.5f;
  }
};

/// \brief Relax the seeds of a Voronoi diagram according to the quadric distance rule.
///
/// For each region it search the vertex that minimize the sum of the squared distance
/// from all the points of the region.
///
/// It uses a vector of QuadricSumDistances;
/// for simplicity it is sized as the vertex vector even if only the ones of the quadric
/// corresponding to seeds are actually used.
///
/// It return true if at least one seed changed position.
///
static bool QuadricRelax(MeshType &m, std::vector<VertexType *> &seedVec,
                         std::vector<VertexPointer> &frontierVec,
                         std::vector<VertexType *> &newSeeds,
                         DistanceFunctor &df,
                         VoronoiProcessingParameter &vpp)
{
    (void)seedVec;
    (void)frontierVec;
    (void)df;
  newSeeds.clear();
  PerVertexPointerHandle sources = tri::Allocator<MeshType>:: template GetPerVertexAttribute<VertexPointer> (m,"sources");
  PerVertexBoolHandle fixed = tri::Allocator<MeshType>:: template GetPerVertexAttribute<bool> (m,"fixed");

  QuadricSumDistance dz;
  std::vector<QuadricSumDistance> dVec(m.vert.size(),dz);
  for(VertexIterator vi=m.vert.begin();vi!=m.vert.end();++vi)
  {
    assert(sources[vi]!=0);
    int seedIndex = tri::Index(m,sources[vi]);
    // When constraining seeds movement we move selected seeds only onto other selected vertices
    if(vpp.constrainSelectedSeed)
    { // So we sum only the contribs of the selected vertices
      if( (sources[vi]->IsS() && vi->IsS()) || (!sources[vi]->IsS()))
        dVec[seedIndex].AddPoint(vi->P());
    }
    else
      dVec[seedIndex].AddPoint(vi->P());
  }

  // Search the local maxima for each region and use them as new seeds
  std::pair<float,VertexPointer> zz(std::numeric_limits<ScalarType>::max(), static_cast<VertexPointer>(0));
  std::vector< std::pair<float,VertexPointer> > seedMaximaVec(m.vert.size(),zz);
  for(VertexIterator vi=m.vert.begin();vi!=m.vert.end();++vi)
  {
    assert(sources[vi]!=0);
    int seedIndex = tri::Index(m,sources[vi]);
    ScalarType val = dVec[seedIndex].Eval(vi->P());
    vi->Q()=val;
    // if constrainSelectedSeed we search only among selected vertices
    if(!vpp.constrainSelectedSeed || !sources[vi]->IsS() || vi->IsS())
    {
      if(seedMaximaVec[seedIndex].first > val)
      {
        seedMaximaVec[seedIndex].first = val;
        seedMaximaVec[seedIndex].second = &*vi;
      }
    }
  }

  if(vpp.colorStrategy==VoronoiProcessingParameter::DistanceFromBorder)
    tri::UpdateColor<MeshType>::PerVertexQualityRamp(m);

//  tri::io::ExporterPLY<MeshType>::Save(m,"last.ply",tri::io::Mask::IOM_VERTCOLOR + tri::io::Mask::IOM_VERTQUALITY );
  bool seedChanged=false;
  // update the seedvector with the new maxima (For the vertex not fixed)
  for(size_t i=0;i<m.vert.size();++i)
    if(seedMaximaVec[i].second) // Most of the seedMaximaVec is unused: only the updated entries have a non zero pointer
    {
      VertexPointer curSrc = sources[seedMaximaVec[i].second];
      if(vpp.preserveFixedSeed && fixed[curSrc])
        newSeeds.push_back(curSrc);
      else
      {
        newSeeds.push_back(seedMaximaVec[i].second);
        if(curSrc != seedMaximaVec[i].second)
          seedChanged=true;
      }
    }

  return seedChanged;
}

/// \brief Relax the Seeds of a Voronoi diagram according to the geodesic rule.
///
/// For each region, given the frontiers, it chooses the point with the highest distance from the frontier
/// This strategy automatically moves the vertices onto the boundary (if any).
///
/// It return true if at least one seed changed position.
///

static bool GeodesicRelax(MeshType &m, std::vector<VertexType *> &seedVec, std::vector<VertexPointer> &frontierVec,
                          std::vector<VertexType *> &newSeeds,
                          DistanceFunctor &df, VoronoiProcessingParameter &vpp)
{
  newSeeds.clear();
  typename MeshType::template PerVertexAttributeHandle<VertexPointer> sources;
  sources = tri::Allocator<MeshType>:: template GetPerVertexAttribute<VertexPointer> (m,"sources");
  typename MeshType::template PerVertexAttributeHandle<bool> fixed;
  fixed = tri::Allocator<MeshType>:: template GetPerVertexAttribute<bool> (m,"fixed");

  std::vector<typename tri::Geodesic<MeshType>::VertDist> biasedFrontierVec;
  BuildBiasedSeedVec(m,df,seedVec,frontierVec,biasedFrontierVec,vpp);
  tri::Geodesic<MeshType>::Visit(m,biasedFrontierVec,df);
  if(vpp.colorStrategy == VoronoiProcessingParameter::DistanceFromSeed)
    tri::UpdateColor<MeshType>::PerVertexQualityRamp(m);
  //    tri::io::ExporterPLY<MeshType>::Save(m,"last.ply",tri::io::Mask::IOM_VERTCOLOR + tri::io::Mask::IOM_VERTQUALITY );

  if(vpp.colorStrategy == VoronoiProcessingParameter::DistanceFromBorder)
    tri::UpdateColor<MeshType>::PerVertexQualityRamp(m);

  // Search the local maxima for each region and use them as new seeds
  std::pair<float,VertexPointer> zz(0.0f,nullptr);
  std::vector< std::pair<float,VertexPointer> > seedMaximaVec(m.vert.size(),zz);
  for(VertexIterator vi=m.vert.begin();vi!=m.vert.end();++vi)
  {
    assert(sources[vi]!=0);
    int seedIndex = tri::Index(m,sources[vi]);

    if(!vpp.constrainSelectedSeed || !sources[vi]->IsS() || vi->IsS())
    {
      if(seedMaximaVec[seedIndex].first < (*vi).Q())
      {
        seedMaximaVec[seedIndex].first=(*vi).Q();
        seedMaximaVec[seedIndex].second=&*vi;
      }
    }
  }

  bool seedChanged=false;

  // update the seedvector with the new maxima (For the vertex not selected)
  for(size_t i=0;i<seedMaximaVec.size();++i)
    if(seedMaximaVec[i].second)// only updated entries have a non zero pointer
    {
      VertexPointer curSrc = sources[seedMaximaVec[i].second];
      if(vpp.preserveFixedSeed && fixed[curSrc])
        newSeeds.push_back(curSrc);
      else
      {
        newSeeds.push_back(seedMaximaVec[i].second);
        if(curSrc != seedMaximaVec[i].second) seedChanged=true;
      }
    }
  return seedChanged;
}

static void PruneSeedByRegionArea(std::vector<VertexType *> &seedVec,
                                  std::vector< std::pair<float,VertexPointer> > &regionArea,
                                  VoronoiProcessingParameter &vpp)
{
  // Smaller area region are discarded
  Distribution<float> H;
  for(size_t i=0;i<regionArea.size();++i)
    if(regionArea[i].second) H.Add(regionArea[i].first);
  float areaThreshold=0;
  if(vpp.areaThresholdPerc != 0) areaThreshold = H.Percentile(vpp.areaThresholdPerc);
  std::vector<VertexType *> newSeedVec;

  // update the seedvector with the new maxima (For the vertex not selected)
  for(size_t i=0;i<seedVec.size();++i)
  {
    if(regionArea[i].first >= areaThreshold)
      newSeedVec.push_back(seedVec[i]);
  }
  swap(seedVec,newSeedVec);
}

/// \brief Mark a vector of seeds to be fixed.
///
/// Vertex pointers must belong to the mesh.
/// The framework use a boolean attribute called "fixed" to store this info.
///
static void MarkVertexVectorAsFixed(MeshType &m, std::vector<VertexType *> &vertToFixVec)
{
  typename MeshType::template PerVertexAttributeHandle<bool> fixed;
  fixed = tri::Allocator<MeshType>:: template GetPerVertexAttribute<bool> (m,"fixed");
  for(VertexIterator vi=m.vert.begin();vi!=m.vert.end();++vi)
    fixed[vi]=false;
  for(size_t i=0;i<vertToFixVec.size();++i)
    fixed[vertToFixVec[i]]=true;
}


static int RestrictedVoronoiRelaxing(MeshType &m, std::vector<CoordType> &seedPosVec,
                                     std::vector<bool> &fixedVec,
                                     int relaxStep,
                                     VoronoiProcessingParameter &vpp)
{
  PerVertexFloatHandle area = tri::Allocator<MeshType>:: template GetPerVertexAttribute<float> (m,"area");

  for(VertexIterator vi=m.vert.begin();vi!=m.vert.end();++vi)
    area[vi]=0;

  for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi)
  {
    ScalarType a3 = DoubleArea(*fi)/6.0;
    for(int i=0;i<3;++i)
      area[fi->V(i)]+=a3;
  }

//  assert(m.vn > (int)seedPosVec.size()*20);
  int i;
  ScalarType perturb = m.bbox.Diag()*vpp.seedPerturbationAmount;
  for(i=0;i<relaxStep;++i)
  {
    vpp.lcb(i*100/relaxStep,StrFormat("RestrictedVoronoiRelaxing %i on %i",i,relaxStep));    
    // Kdtree for the seeds must be rebuilt at each step;
    VectorConstDataWrapper<std::vector<CoordType> > vdw(seedPosVec);
    KdTree<ScalarType> seedTree(vdw);

    std::vector<std::pair<ScalarType,CoordType> > sumVec(seedPosVec.size(),std::make_pair(0,CoordType(0,0,0)));
    for(VertexIterator vi=m.vert.begin();vi!=m.vert.end();++vi)
    {
      unsigned int seedInd;
      ScalarType sqdist;
      seedTree.doQueryClosest(vi->P(),seedInd,sqdist);
      vi->Q()=sqrt(sqdist);
      sumVec[seedInd].first+=area[vi];
      sumVec[seedInd].second+=vi->cP()*area[vi];
    }

    vector<CoordType> newseedVec;
    vector<bool> newfixedVec;

    for(size_t i=0;i<seedPosVec.size();++i)
    {
      if(fixedVec[i])
      {
        newseedVec.push_back(seedPosVec[i]);
        newfixedVec.push_back(true);
      }
      else
      {
        if(sumVec[i].first != 0)
        {
          newseedVec.push_back(sumVec[i].second /ScalarType(sumVec[i].first));
          if(vpp.seedPerturbationProbability > 0  && (vpp.seedPerturbationProbability > RandomGenerator().generate01()))
            newseedVec.back()+=math::GeneratePointInUnitBallUniform<ScalarType,math::MarsenneTwisterRNG>( RandomGenerator())*perturb;
          newfixedVec.push_back(false);
        }
      }
    }
    std::swap(seedPosVec,newseedVec);
    std::swap(fixedVec,newfixedVec);
    tri::UpdateColor<MeshType>::PerVertexQualityRamp(m);
  }
  return relaxStep;
}

/// \brief Perform a Lloyd relaxation cycle over a mesh
///  It uses two conventions:
///  1) a few vertexes can remain fixed, you have to set a per vertex bool attribute named 'fixed'
///  2)
///

static int VoronoiRelaxing(MeshType &m, std::vector<VertexType *> &seedVec,
                            int relaxIter, DistanceFunctor &df,
                            VoronoiProcessingParameter &vpp,
                            vcg::CallBackPos *cb=0)
{
  tri::RequireVFAdjacency(m);
  tri::RequireCompactness(m);
  for(VertexIterator vi=m.vert.begin();vi!=m.vert.end();++vi)
    assert(vi->VFp() && "Require mesh without unreferenced vertexes\n");
  std::vector<VertexType *> selectedVec;
  if(vpp.relaxOnlyConstrainedFlag)
  {
    for(size_t i=0;i<seedVec.size();++i)
      if(seedVec[i]->IsS())
        selectedVec.push_back(seedVec[i]);
    std::swap(seedVec,selectedVec);
  }

  tri::UpdateFlags<MeshType>::FaceBorderFromVF(m);
  tri::UpdateFlags<MeshType>::VertexBorderFromFaceBorder(m);
  PerVertexPointerHandle sources = tri::Allocator<MeshType>:: template GetPerVertexAttribute<VertexPointer> (m,"sources");
  PerVertexBoolHandle fixed = tri::Allocator<MeshType>:: template GetPerVertexAttribute<bool> (m,"fixed");
  int iter;
  for(iter=0;iter<relaxIter;++iter)
  {
    if(cb) cb(iter*100/relaxIter,"Voronoi Lloyd Relaxation: First Partitioning");

    // first run: find for each point what is the closest to one of the seeds.
    tri::Geodesic<MeshType>::Compute(m, seedVec, df,std::numeric_limits<ScalarType>::max(),0,&sources);

    if(vpp.colorStrategy == VoronoiProcessingParameter::DistanceFromSeed)
      tri::UpdateColor<MeshType>::PerVertexQualityRamp(m);
    // Delete all the (hopefully) small regions that have not been reached by the seeds;

    if(vpp.deleteUnreachedRegionFlag)  DeleteUnreachedRegions(m,sources);
    std::pair<float,VertexPointer> zz(0.0f,static_cast<VertexPointer>(NULL));
    std::vector< std::pair<float,VertexPointer> > regionArea(m.vert.size(),zz);
    std::vector<VertexPointer> frontierVec;

    GetAreaAndFrontier(m, sources,  regionArea, frontierVec);
    assert(frontierVec.size()>0);

    if(vpp.colorStrategy == VoronoiProcessingParameter::RegionArea) VoronoiAreaColoring(m, seedVec, regionArea);

    //    qDebug("We have found %i regions range (%f %f), avg area is %f, Variance is %f 10perc is %f",(int)seedVec.size(),H.Min(),H.Max(),H.Avg(),H.StandardDeviation(),areaThreshold);

    if(cb) cb(iter*100/relaxIter,"Voronoi Lloyd Relaxation: Searching New Seeds");
    std::vector<VertexPointer> newSeedVec;

    bool changed;
    if(vpp.geodesicRelaxFlag)
      changed = GeodesicRelax(m,seedVec, frontierVec, newSeedVec, df,vpp);
    else
      changed = QuadricRelax(m,seedVec,frontierVec, newSeedVec, df,vpp);

    //assert(newSeedVec.size() == seedVec.size());
    PruneSeedByRegionArea(newSeedVec,regionArea,vpp);

    for(size_t i=0;i<frontierVec.size();++i)
      frontierVec[i]->C() = Color4b::Gray;
    for(size_t i=0;i<seedVec.size();++i)
      seedVec[i]->C() = Color4b::Black;
    for(size_t i=0;i<newSeedVec.size();++i)
      newSeedVec[i]->C() = Color4b::White;

    swap(newSeedVec,seedVec);
    if(!changed) break;
  }

  // Last run: Needed if we have changed the seed set to leave the sources handle correct.
  if(iter==relaxIter)
    tri::Geodesic<MeshType>::Compute(m, seedVec, df,std::numeric_limits<ScalarType>::max(),0,&sources);

  if(vpp.relaxOnlyConstrainedFlag)
  {
    std::swap(seedVec,selectedVec);
    size_t i,j;
    for(i=0,j=0;i<seedVec.size();++i){
      if(seedVec[i]->IsS())
      {
        seedVec[i]=selectedVec[j];
        fixed[seedVec[i]]=true;
        ++j;
      }
    }
  }
  return iter;
}


// Base vertex voronoi coloring algorithm.
// It assumes VF adjacency. 
// No attempt of computing real geodesic distnace is done. Just a BFS visit starting from the seeds
// It leaves in each vertex quality the index of the seed.

static void TopologicalVertexColoring(MeshType &m, std::vector<VertexType *> &seedVec)
{
  std::queue<VertexPointer> VQ;

  tri::UpdateQuality<MeshType>::VertexConstant(m,0);

  for(size_t i=0;i<seedVec.size();++i)
  {
    VQ.push(seedVec[i]);
    seedVec[i]->Q()=i+1;
  }

  while(!VQ.empty())
  {
    VertexPointer vp = VQ.front();
    VQ.pop();

    std::vector<VertexPointer> vertStar;
    vcg::face::VVStarVF<FaceType>(vp,vertStar);
    for(typename std::vector<VertexPointer>::iterator vv = vertStar.begin();vv!=vertStar.end();++vv)
    {
      if((*vv)->Q()==0)
      {
        (*vv)->Q()=vp->Q();
        VQ.push(*vv);
      }
    }
  } // end while(!VQ.empty())

}


template <class genericType>
static std::pair<genericType, genericType> ordered_pair(const genericType &a, const genericType &b)
{
  if(a<b) return std::make_pair(a,b);
  return std::make_pair(b,a);
}

/// For each edge of the delaunay triangulation it search a 'good' middle point:
/// E.g the point that belongs on the corresponding edge of the voronoi diagram (e.g. on a frontier face)
/// and that has minimal distance from the two seeds.
///
///  Note: if the edge connects two "constrained" vertices (e.g. selected) we must search only among the constrained.
///
///
static void GenerateMidPointMap(MeshType &m,
                                map<std::pair<VertexPointer,VertexPointer>, VertexPointer > &midMap)
{
  PerVertexPointerHandle sources = tri::Allocator<MeshType>:: template GetPerVertexAttribute<VertexPointer> (m,"sources");

  for(FaceIterator fi = m.face.begin(); fi!=m.face.end(); ++fi)
  {
    VertexPointer vp[3],sp[3];
    vp[0] =    (*fi).V(0);  vp[1] =    (*fi).V(1);  vp[2] =    (*fi).V(2);
    sp[0] = sources[vp[0]]; sp[1] = sources[vp[1]]; sp[2] = sources[vp[2]];
    if((sp[0] == sp[1]) && (sp[0] == sp[2])) continue; // skip internal faces
//    if((sp[0] != sp[1]) && (sp[0] != sp[2]) && (sp[1] != sp[2])) continue; // skip corner faces

    for(int i=0;i<3;++i) // for each edge of a frontier face
    {
      int i0 = i;
      int i1 = (i+1)%3;
//      if((sp[i0]->IsS() && sp[i1]->IsS()) && !( vp[i0]->IsS() || vp[i1]->IsS() ) ) continue;

      VertexPointer closestVert = vp[i0];
      if( vp[i1]->Q() <  closestVert->Q()) closestVert =  vp[i1];

      if(sp[i0]->IsS() && sp[i1]->IsS())
      {
         if ( (vp[i0]->IsS()) && !(vp[i1]->IsS()) ) closestVert =  vp[i0];
         if (!(vp[i0]->IsS()) &&  (vp[i1]->IsS()) ) closestVert =  vp[i1];
         if ( (vp[i0]->IsS()) &&  (vp[i1]->IsS()) ) closestVert =  (vp[i0]->Q() < vp[i1]->Q()) ? vp[i0]:vp[i1];
      }

      if(midMap[ordered_pair(sp[i0],sp[i1])] == 0 ) {
        midMap[ordered_pair(sp[i0],sp[i1])] = closestVert;
      }
      else {
        if(sp[i0]->IsS() && sp[i1]->IsS()) // constrained edge
        {
          if(!(midMap[ordered_pair(sp[i0],sp[i1])]->IsS()) && closestVert->IsS())
             midMap[ordered_pair(sp[i0],sp[i1])] = closestVert;
          if( midMap[ordered_pair(sp[i0],sp[i1])]->IsS() && closestVert->IsS() &&
            closestVert->Q() < midMap[ordered_pair(sp[i0],sp[i1])]->Q())
          {
            midMap[ordered_pair(sp[i0],sp[i1])] = closestVert;
          }
        }
        else // UNCOSTRAINED EDGE
        {
        if(closestVert->Q() < midMap[ordered_pair(sp[i0],sp[i1])]->Q())
          midMap[ordered_pair(sp[i0],sp[i1])] = closestVert;
        }
      }
    }
  }
}

/// \brief Check the topological correcteness of the induced Voronoi diagram
///
/// This function assumes that you have just run a geodesic like algorithm over your mesh using
/// a seed set as starting points and that there is an PerVertex Attribute called 'sources'
/// with pointers to the seed source. Usually you can initialize it with something like
///
///   DistanceFunctor &df,
///   tri::Geodesic<MeshType>::Compute(m, seedVec, df, std::numeric_limits<ScalarType>::max(),0,&sources);

static bool CheckVoronoiTopology(MeshType& m,std::vector<VertexType *> &seedVec)
{
  tri::RequirePerVertexAttribute(m,"sources");
  tri::RequireCompactness(m);

  typename MeshType::template PerVertexAttributeHandle<VertexPointer> sources;
  sources = tri::Allocator<MeshType>:: template GetPerVertexAttribute<VertexPointer> (m,"sources");

  std::map<VertexPointer, int> seedMap;  // It says if a given vertex of m is a seed (and its index in seedVec)
  BuildSeedMap(m,seedVec,seedMap);

  // Very basic check: each vertex must have a source that is a seed.
  for(int i=0;i<m.vn;++i)
  {
    VertexPointer vp = sources[i];
    int seedInd = seedMap[vp];
    if(seedInd <0)
      return false;
  }

  std::vector<MeshType *> regionVec(seedVec.size(),0);
  for(size_t i=0; i< seedVec.size();i++) regionVec[i] = new MeshType;

  for(int i=0;i<m.fn;++i)
  {
    int vi0 = seedMap[sources[m.face[i].V(0)]];
    int vi1 = seedMap[sources[m.face[i].V(1)]];
    int vi2 = seedMap[sources[m.face[i].V(2)]];
    assert(vi0>=0 && vi1>=0 && vi2>=0);
    tri::Allocator<MeshType>::AddFace(*regionVec[vi0], m.face[i].cP(0),m.face[i].cP(1),m.face[i].cP(2));

    if(vi1 != vi0)
      tri::Allocator<MeshType>::AddFace(*regionVec[vi1], m.face[i].cP(0),m.face[i].cP(1),m.face[i].cP(2));

    if((vi2 != vi0) && (vi2 != vi1) )
      tri::Allocator<MeshType>::AddFace(*regionVec[vi2], m.face[i].cP(0),m.face[i].cP(1),m.face[i].cP(2));
  }

  bool AllDiskRegion=true;
  for(size_t i=0; i< seedVec.size();i++)
  {
    MeshType &rm = *(regionVec[i]);
    tri::Clean<MeshType>::RemoveDuplicateVertex(rm);
    tri::Allocator<MeshType>::CompactEveryVector(rm);
    tri::UpdateTopology<MeshType>::FaceFace(rm);
    //    char buf[100]; sprintf(buf,"disk%04i.ply",i); tri::io::ExporterPLY<MeshType>::Save(rm,buf,tri::io::Mask::IOM_VERTCOLOR + tri::io::Mask::IOM_VERTQUALITY );

    int NNmanifoldE=tri::Clean<MeshType>::CountNonManifoldEdgeFF(rm);
    if (NNmanifoldE!=0)
      AllDiskRegion= false;
    int G=tri::Clean<MeshType>::MeshGenus(rm);
    int numholes=tri::Clean<MeshType>::CountHoles(rm);
    if (numholes!=1)
      AllDiskRegion= false;
    if(G!=0) AllDiskRegion= false;
    delete regionVec[i];
  }

  if(!AllDiskRegion) return false;

  // **** Final step build a rough delaunay tri and check that it is manifold
  MeshType delaMesh;
  std::vector<FacePointer> innerCornerVec,   // Faces adjacent to three different regions
      borderCornerVec;  // Faces that are on the border and adjacent to at least two regions.
  GetFaceCornerVec(m, sources, innerCornerVec, borderCornerVec);

  // First add all the needed vertices: seeds and corners
  for(size_t i=0;i<seedVec.size();++i)
    tri::Allocator<MeshType>::AddVertex(delaMesh, seedVec[i]->P());

  // Now just add one face for each inner corner
  for(size_t i=0;i<innerCornerVec.size();++i)
  {
    VertexPointer v0 = & delaMesh.vert[seedMap[sources[innerCornerVec[i]->V(0)]]];
    VertexPointer v1 = & delaMesh.vert[seedMap[sources[innerCornerVec[i]->V(1)]]];
    VertexPointer v2 = & delaMesh.vert[seedMap[sources[innerCornerVec[i]->V(2)]]];
    tri::Allocator<MeshType>::AddFace(delaMesh,v0,v1,v2);
  }
  Clean<MeshType>::RemoveUnreferencedVertex(delaMesh);
  tri::Allocator<MeshType>::CompactVertexVector(delaMesh);
  tri::UpdateTopology<MeshType>::FaceFace(delaMesh);

  int nonManif = tri::Clean<MeshType>::CountNonManifoldEdgeFF(delaMesh);
  if(nonManif>0) return false;

  return true;
}

static void BuildSeedMap(MeshType &m, std::vector<VertexType *> &seedVec,  std::map<VertexPointer, int> &seedMap)
{
  seedMap.clear();
  for(size_t i=0;i<m.vert.size();++i)
    seedMap[&(m.vert[i])]=-1;
  for(size_t i=0;i<seedVec.size();++i)
    seedMap[seedVec[i]]=i;
  for(size_t i=0;i<seedVec.size();++i)
    assert(tri::Index(m,seedVec[i])>=0 && tri::Index(m,seedVec[i])<size_t(m.vn));
}

/// \brief Build a mesh of the Delaunay triangulation induced by the given seeds
///
/// This function assumes that you have just run a geodesic like algorithm over your mesh using
/// a seed set as starting points and that there is an PerVertex Attribute called 'sources'
/// with pointers to the seed source. Usually you can initialize it with something like
///
///   DistanceFunctor &df,
///   tri::Geodesic<MeshType>::Compute(m, seedVec, df, std::numeric_limits<ScalarType>::max(),0,&sources);
///
/// The function can also
static void ConvertDelaunayTriangulationToMesh(MeshType &m,
                                               MeshType &outMesh,
                                               std::vector<VertexType *> &seedVec, bool refineFlag=true)
{
  tri::RequirePerVertexAttribute(m,"sources");
  tri::RequireCompactness(m);
  tri::RequireVFAdjacency(m);

  PerVertexPointerHandle sources = tri::Allocator<MeshType>:: template GetPerVertexAttribute<VertexPointer> (m,"sources");

  outMesh.Clear();
  tri::UpdateTopology<MeshType>::FaceFace(m);
  tri::UpdateFlags<MeshType>::FaceBorderFromFF(m);

  std::map<VertexPointer, int> seedMap;  // It says if a given vertex of m is a seed (and its index in seedVec)
  BuildSeedMap(m,seedVec,seedMap);

  std::vector<FacePointer> innerCornerVec,   // Faces adjacent to three different regions
      borderCornerVec;  // Faces that are on the border and adjacent to at least two regions.
  GetFaceCornerVec(m, sources, innerCornerVec, borderCornerVec);

  // First add all the needed vertices: seeds and corners
  for(size_t i=0;i<seedVec.size();++i)
    tri::Allocator<MeshType>::AddVertex(outMesh, seedVec[i]->P(),Color4b::White);

  map<std::pair<VertexPointer,VertexPointer>, int > midMapInd;

  // Given a pair of sources gives the index of the mid vertex
  map<std::pair<VertexPointer,VertexPointer>, VertexPointer > midMapPt;
  if(refineFlag)
  {
    GenerateMidPointMap(m, midMapPt);
    typename std::map<std::pair<VertexPointer,VertexPointer>, VertexPointer >::iterator mi;
    for(mi=midMapPt.begin(); mi!=midMapPt.end(); ++mi)
    {
      midMapInd[ordered_pair(mi->first.first, mi->first.second)]=outMesh.vert.size();
      tri::Allocator<MeshType>::AddVertex(outMesh, mi->second->cP(), Color4b::LightBlue);
    }
  }

  // Now just add one (or four) face for each inner corner
  for(size_t i=0;i<innerCornerVec.size();++i)
  {
    VertexPointer s0 = sources[innerCornerVec[i]->V(0)];
    VertexPointer s1 = sources[innerCornerVec[i]->V(1)];
    VertexPointer s2 = sources[innerCornerVec[i]->V(2)];
    assert ( (s0!=s1) && (s0!=s2) && (s1!=s2) );
    VertexPointer v0 = & outMesh.vert[seedMap[s0]];
    VertexPointer v1 = & outMesh.vert[seedMap[s1]];
    VertexPointer v2 = & outMesh.vert[seedMap[s2]];
    if(refineFlag)
    {
      VertexPointer mp01 =  & outMesh.vert[ midMapInd[ordered_pair(s0,s1)]];
      VertexPointer mp02 =  & outMesh.vert[ midMapInd[ordered_pair(s0,s2)]];
      VertexPointer mp12 =  & outMesh.vert[ midMapInd[ordered_pair(s1,s2)]];
      assert ( (mp01!=mp02) && (mp01!=mp12) && (mp02!=mp12) );
      tri::Allocator<MeshType>::AddFace(outMesh,v0,mp01,mp02);
      tri::Allocator<MeshType>::AddFace(outMesh,v1,mp12,mp01);
      tri::Allocator<MeshType>::AddFace(outMesh,v2,mp02,mp12);
      tri::Allocator<MeshType>::AddFace(outMesh,mp01,mp12,mp02);
    }
     else
      tri::Allocator<MeshType>::AddFace(outMesh,v0,v1,v2);
  }
  Clean<MeshType>::RemoveUnreferencedVertex(outMesh);
  tri::Allocator<MeshType>::CompactVertexVector(outMesh);
}

template <class MidPointType >
static void PreprocessForVoronoi(MeshType &m, ScalarType radius,
                                 MidPointType mid,
                                 VoronoiProcessingParameter &vpp)
{
  const int maxSubDiv = 10;
  tri::RequireFFAdjacency(m);
  tri::UpdateTopology<MeshType>::FaceFace(m);
  tri::Clean<MeshType>::RemoveUnreferencedVertex(m);
  ScalarType edgeLen = tri::Stat<MeshType>::ComputeFaceEdgeLengthAverage(m);

  for(int i=0;i<maxSubDiv;++i)
  {
    vpp.lcb(0,StrFormat("Subdividing %i vn %i",i,m.vn));
    bool ret = tri::Refine<MeshType, MidPointType >(m,mid,min(edgeLen*2.0f,radius/vpp.refinementRatio));
    if(!ret) break;
  }
  tri::Allocator<MeshType>::CompactEveryVector(m);
  tri::UpdateTopology<MeshType>::VertexFace(m);
}

static void PreprocessForVoronoi(MeshType &m, float radius, VoronoiProcessingParameter &vpp)
{
  tri::MidPoint<MeshType> mid(&m);
  PreprocessForVoronoi<tri::MidPoint<MeshType> >(m, radius,mid,vpp);
}

static void RelaxRefineTriangulationSpring(MeshType &m, MeshType &delaMesh, int relaxStep=10, int refineStep=3 )
{
  tri::RequireCompactness(m);
  tri::RequireCompactness(delaMesh);
  tri::RequireVFAdjacency(delaMesh);
  tri::RequireFFAdjacency(delaMesh);
  tri::RequirePerFaceMark(delaMesh);

  const float convergenceThr = 0.001f;
  const float eulerStep = 0.1f;

  tri::UpdateNormal<MeshType>::PerVertexNormalizedPerFaceNormalized(m);

  typedef GridStaticPtr<FaceType, ScalarType> TriMeshGrid;
  TriMeshGrid ug;
  ug.Set(m.face.begin(),m.face.end());

  typedef typename vcg::SpatialHashTable<VertexType, ScalarType> HashVertexGrid;
  HashVertexGrid HG;
  HG.Set(m.vert.begin(),m.vert.end());

  PerVertexBoolHandle fixed = tri::Allocator<MeshType>:: template GetPerVertexAttribute<bool> (m,"fixed");

  const ScalarType maxDist = m.bbox.Diag()/4.f;
  for(int kk=0;kk<refineStep+1;kk++)
  {
    tri::UpdateTopology<MeshType>::FaceFace(delaMesh);

    if(kk!=0) // first step do not refine;
    {
      int nonManif = tri::Clean<MeshType>::CountNonManifoldEdgeFF(delaMesh);
      if(nonManif) return;
      tri::Refine<MeshType, tri::MidPoint<MeshType> >(delaMesh,tri::MidPoint<MeshType>(&delaMesh));
    }
    tri::UpdateTopology<MeshType>::VertexFace(delaMesh);
    const float dist_upper_bound=m.bbox.Diag()/10.0;
    float dist;

    for(int k=0;k<relaxStep;k++) 
    {
      std::vector<Point3f> avgForce(delaMesh.vn);
      std::vector<float> avgLenVec(delaMesh.vn,0);
      for(int i=0;i<delaMesh.vn;++i)
      {
        vector<VertexPointer> starVec;
        face::VVStarVF<FaceType>(&delaMesh.vert[i],starVec);

        for(size_t j=0;j<starVec.size();++j)
          avgLenVec[i] +=Distance(delaMesh.vert[i].cP(),starVec[j]->cP());
        avgLenVec[i] /= float(starVec.size());

        avgForce[i] =Point3f(0,0,0);
        for(size_t j=0;j<starVec.size();++j)
        {
          Point3f force = delaMesh.vert[i].cP()-starVec[j]->cP();
          float len = force.Norm();
          force.Normalize();
          avgForce[i] += force * (avgLenVec[i]-len);
        }
      }
      bool changed=false;
      for(int i=0;i<delaMesh.vn;++i)
      {
        VertexPointer vp = tri::GetClosestVertex<MeshType,HashVertexGrid>(m, HG, delaMesh.vert[i].P(), dist_upper_bound, dist);
        if(!fixed[vp] && !(vp->IsS())) // update only non fixed vertices
        {
          delaMesh.vert[i].P() += (avgForce[i]*eulerStep);
          CoordType closest;
          float dist;
          tri::GetClosestFaceBase(m,ug,delaMesh.vert[i].cP(), maxDist,dist,closest);
          assert(dist!=maxDist);
          if(Distance(closest,delaMesh.vert[i].P()) > avgLenVec[i]*convergenceThr) changed = true;
          delaMesh.vert[i].P()=closest;
        }
      }

      if(!changed) k=relaxStep;
    } // end for k
  }
}

static void RelaxRefineTriangulationLaplacian(MeshType &m, MeshType &delaMesh, int refineStep=3, int relaxStep=10 )
{
  tri::RequireCompactness(m);
  tri::RequireCompactness(delaMesh);
  tri::RequireFFAdjacency(delaMesh);
  tri::RequirePerFaceMark(delaMesh);
  tri::UpdateTopology<MeshType>::FaceFace(delaMesh);

  typedef GridStaticPtr<FaceType, ScalarType> TriMeshGrid;
  TriMeshGrid ug;
  ug.Set(m.face.begin(),m.face.end());
  const ScalarType maxDist = m.bbox.Diag()/4.f;

  int origVertNum = delaMesh.vn;

  for(int k=0;k<refineStep;++k)
  {
    tri::UpdateSelection<MeshType>::VertexClear(delaMesh);

    tri::Refine<MeshType, tri::MidPoint<MeshType> >(delaMesh,tri::MidPoint<MeshType>(&delaMesh));

    for(int j=0;j<relaxStep;++j)
    {
//      tri::Smooth<MeshType>::VertexCoordLaplacian(delaMesh,1,true);
      for(int i=origVertNum;i<delaMesh.vn;++i)
      {
        float dist;
        delaMesh.vert[i].SetS();
        CoordType closest;
        tri::GetClosestFaceBase(m,ug,delaMesh.vert[i].cP(), maxDist,dist,closest);
        assert(dist!=maxDist);
        delaMesh.vert[i].P()= (delaMesh.vert[i].P()+closest)/2.0f;
      }
      tri::Smooth<MeshType>::VertexCoordLaplacianBlend(delaMesh,1,0.2f,true);
    }
  }
  for(int i=origVertNum;i<delaMesh.vn;++i) delaMesh.vert[i].C()=Color4b::LightBlue;
}

static void ConvertDelaunayTriangulationExtendedToMesh(MeshType &m,
                                                       MeshType &outMesh,
                                                       std::vector<VertexType *> &seedVec)
{
  RequirePerVertexAttribute(m ,"sources");
  RequireCompactness(m);
  RequireVFAdjacency(m);

  auto sources = Allocator<MeshType>::template GetPerVertexAttribute<VertexPointer> (m,"sources");

  outMesh.Clear();
  UpdateTopology<MeshType>::FaceFace(m);
  UpdateFlags<MeshType>::FaceBorderFromFF(m);

  std::map<VertexPointer, int> seedMap;  // It says if a given vertex of m is a seed (and its index in seedVec)
  BuildSeedMap(m, seedVec, seedMap);

  std::vector<FacePointer> innerCornerVec,   // Faces adjacent to three different regions
          borderCornerVec;  // Faces that are on the border and adjacent to at least two regions.
  GetFaceCornerVec(m, sources, innerCornerVec, borderCornerVec);

  // First add all the needed vertices: seeds and corners

  for(size_t i=0;i<seedVec.size();++i)
  {
    Allocator<MeshType>::AddVertex(outMesh, seedVec[i]->P(), vcg::Color4b::White);
  }

  // Now just add one face for each inner corner
  for(size_t i=0; i<innerCornerVec.size(); ++i)
  {
    VertexPointer s0 = sources[innerCornerVec[i]->V(0)];
    VertexPointer s1 = sources[innerCornerVec[i]->V(1)];
    VertexPointer s2 = sources[innerCornerVec[i]->V(2)];
    assert ( (s0!=s1) && (s0!=s2) && (s1!=s2) );
    VertexPointer v0 = & outMesh.vert[seedMap[s0]];
    VertexPointer v1 = & outMesh.vert[seedMap[s1]];
    VertexPointer v2 = & outMesh.vert[seedMap[s2]];
    Allocator<MeshType>::AddFace(outMesh, v0, v1, v2);
  }

  // Now loop around the borders and find the missing delaunay triangles
  // select border seed vertices only and pick one
  UpdateFlags<MeshType>::VertexBorderFromFaceAdj(m);
  UpdateFlags<MeshType>::VertexClearS(m);
  UpdateFlags<MeshType>::VertexClearV(m);

  std::vector<VertexPointer> borderSeeds;
  for (auto & s : seedVec)
  {
    if (s->IsB())
    {
      s->SetS();
      borderSeeds.emplace_back(s);
    }
  }

  for (VertexPointer startBorderVertex : borderSeeds)
  {
    if (startBorderVertex->IsV())
    {
      continue;
    }

    // unvisited border seed found

    // put the pos on the border
    PosType pos(startBorderVertex->VFp(), startBorderVertex->VFi());
    do {
      pos.NextE();
    } while (!pos.IsBorder() || (pos.VInd() != pos.E()));

    // check all border edges between each consecutive border seeds pair
    do {
      std::vector<VertexPointer> edgeVoroVertices(1, sources[pos.V()]);
      //	among all sources found
      do {
        pos.NextB();
        VertexPointer source = sources[pos.V()];
        if (edgeVoroVertices.empty() || edgeVoroVertices.back() != source)
        {
          edgeVoroVertices.push_back(source);
        }
      } while (!pos.V()->IsS());

      pos.V()->SetV();

//				assert(edgeVoroVertices.size() >= 2);


      if (edgeVoroVertices.size() >= 3)
      {
        std::vector<VertexPointer> v;
        for (size_t i=0; i<edgeVoroVertices.size(); i++)
        {
          v.push_back(&outMesh.vert[seedMap[edgeVoroVertices[i]]]);
        }
        // also handles N>3 vertices holes
        for (size_t i=0; i<edgeVoroVertices.size()-2; i++)
        {
          Allocator<MeshType>::AddFace(outMesh, v[0],v[i+1],v[i+2]);
        }
//					if (edgeVoroVertices.size() > 3)
//					{
//						std::cout << "Weird case: " << edgeVoroVertices.size() << " voroseeds on one border" << std::endl;
//					}
      }
//				// add face if 3 different voronoi regions are crossed by the edge
//				if (edgeVoroVertices.size() == 3)
//				{
//					VertexPointer v0 = & outMesh.vert[seedMap[edgeVoroVertices[0]]];
//					VertexPointer v1 = & outMesh.vert[seedMap[edgeVoroVertices[1]]];
//					VertexPointer v2 = & outMesh.vert[seedMap[edgeVoroVertices[2]]];
//					Allocator<MeshType>::AddFace(outMesh, v0,v1,v2);
//				}
//				else
//				{
//					std::cout << "Weird case!! " << edgeVoroVertices.size() << " voroseeds on one border" << std::endl;
//					if (edgeVoroVertices.size() == 4)
//					{
//						VertexPointer v0 = & outMesh.vert[seedMap[edgeVoroVertices[0]]];
//						VertexPointer v1 = & outMesh.vert[seedMap[edgeVoroVertices[1]]];
//						VertexPointer v2 = & outMesh.vert[seedMap[edgeVoroVertices[2]]];
//						VertexPointer v3 = & outMesh.vert[seedMap[edgeVoroVertices[3]]];
//						Allocator<MeshType>::AddFace(outMesh, v0,v1,v2);
//						Allocator<MeshType>::AddFace(outMesh, v0,v2,v3);
//					}
//				}

    } while ((pos.V() != startBorderVertex));
  }


  Clean<MeshType>::RemoveUnreferencedVertex(outMesh);
  Allocator<MeshType>::CompactVertexVector(outMesh);
}


}; // end class VoronoiProcessing

} // end namespace tri
} // end namespace vcg
#endif