File size: 43,345 Bytes
985c397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// SPDX-License-Identifier: LGPL-2.1-or-later

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

 *   Copyright (c) 2005 Imetric 3D GmbH                                    *

 *                                                                         *

 *   This file is part of the FreeCAD CAx development system.              *

 *                                                                         *

 *   This library is free software; you can redistribute it and/or         *

 *   modify it under the terms of the GNU Library General Public           *

 *   License as published by the Free Software Foundation; either          *

 *   version 2 of the License, or (at your option) any later version.      *

 *                                                                         *

 *   This library  is distributed in the hope that it will be useful,      *

 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *

 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *

 *   GNU Library General Public License for more details.                  *

 *                                                                         *

 *   You should have received a copy of the GNU Library General Public     *

 *   License along with this library; see the file COPYING.LIB. If not,    *

 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *

 *   Suite 330, Boston, MA  02111-1307, USA                                *

 *                                                                         *

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


#include <algorithm>
#include <map>
#include <queue>


#include <boost/math/special_functions/fpclassify.hpp>

#include "Degeneration.h"
#include "Grid.h"
#include "Iterator.h"
#include "TopoAlgorithm.h"
#include "Triangulation.h"


using namespace MeshCore;

bool MeshEvalInvalids::Evaluate()

{
    const MeshFacetArray& rFaces = _rclMesh.GetFacets();
    for (const auto& it : rFaces) {
        if (!it.IsValid()) {
            return false;
        }
    }

    const MeshPointArray& rPoints = _rclMesh.GetPoints();
    for (const auto& it : rPoints) {
        if (!it.IsValid()) {
            return false;
        }
    }

    return true;
}

std::vector<FacetIndex> MeshEvalInvalids::GetIndices() const

{
    std::vector<FacetIndex> aInds;
    const MeshFacetArray& rFaces = _rclMesh.GetFacets();
    const MeshPointArray& rPoints = _rclMesh.GetPoints();
    FacetIndex ind = 0;
    for (auto it = rFaces.begin(); it != rFaces.end(); ++it, ind++) {
        if (!it->IsValid()) {
            aInds.push_back(ind);
        }
        else if (!rPoints[it->_aulPoints[0]].IsValid()) {
            aInds.push_back(ind);
        }
        else if (!rPoints[it->_aulPoints[1]].IsValid()) {
            aInds.push_back(ind);
        }
        else if (!rPoints[it->_aulPoints[2]].IsValid()) {
            aInds.push_back(ind);
        }
    }

    return aInds;
}

bool MeshFixInvalids::Fixup()

{
    _rclMesh.RemoveInvalids();
    return true;
}

// ----------------------------------------------------------------------

namespace MeshCore
{

using VertexIterator = MeshPointArray::_TConstIterator;
/*

 * When building up a mesh then usually the class MeshBuilder is used. This

 * class uses internally a std::set<MeshPoint> which uses the '<' operator of

 * MeshPoint to sort the points. Thus to be consistent (and avoid using the

 * '==' operator of MeshPoint) we use the same operator when comparing the

 * points in the function object.

 */
struct Vertex_EqualTo
{
    bool operator()(const VertexIterator& x, const VertexIterator& y) const

    {
        if ((*x) < (*y)) {
            return false;
        }
        if ((*y) < (*x)) {
            return false;
        }
        return true;
    }
};

struct Vertex_Less
{
    bool operator()(const VertexIterator& x, const VertexIterator& y) const

    {
        return (*x) < (*y);
    }
};

}  // namespace MeshCore

bool MeshEvalDuplicatePoints::Evaluate()

{
    // get an const iterator to each vertex and sort them in ascending order by
    // their (x,y,z) coordinates
    const MeshPointArray& rPoints = _rclMesh.GetPoints();
    std::vector<VertexIterator> vertices;
    vertices.reserve(rPoints.size());
    for (auto it = rPoints.begin(); it != rPoints.end(); ++it) {
        vertices.push_back(it);
    }

    // if there are two adjacent vertices which have the same coordinates
    std::sort(vertices.begin(), vertices.end(), Vertex_Less());
    return (std::adjacent_find(vertices.begin(), vertices.end(), Vertex_EqualTo()) == vertices.end());
}

std::vector<PointIndex> MeshEvalDuplicatePoints::GetIndices() const

{
    // Note: We must neither use map or set to get duplicated indices because
    // the sort algorithms deliver different results compared to std::sort of
    // a vector.
    const MeshPointArray& rPoints = _rclMesh.GetPoints();
    std::vector<VertexIterator> vertices;
    vertices.reserve(rPoints.size());
    for (auto it = rPoints.begin(); it != rPoints.end(); ++it) {
        vertices.push_back(it);
    }

    // if there are two adjacent vertices which have the same coordinates
    std::vector<PointIndex> aInds;
    Vertex_EqualTo pred;
    std::sort(vertices.begin(), vertices.end(), Vertex_Less());

    std::vector<VertexIterator>::iterator vt = vertices.begin();
    while (vt < vertices.end()) {
        // get first item which adjacent element has the same vertex
        vt = std::adjacent_find(vt, vertices.end(), pred);
        if (vt < vertices.end()) {
            ++vt;
            aInds.push_back(*vt - rPoints.begin());
        }
    }

    return aInds;
}

bool MeshFixDuplicatePoints::Fixup()

{
    // Note: We must neither use map or set to get duplicated indices because
    // the sort algorithms deliver different results compared to std::sort of
    // a vector.
    const MeshPointArray& rPoints = _rclMesh.GetPoints();
    std::vector<VertexIterator> vertices;
    vertices.reserve(rPoints.size());
    for (auto it = rPoints.begin(); it != rPoints.end(); ++it) {
        vertices.push_back(it);
    }

    // get the indices of adjacent vertices which have the same coordinates
    std::sort(vertices.begin(), vertices.end(), Vertex_Less());

    Vertex_EqualTo pred;
    std::vector<VertexIterator>::iterator next = vertices.begin();
    std::map<PointIndex, PointIndex> mapPointIndex;
    std::vector<PointIndex> pointIndices;
    while (next < vertices.end()) {
        next = std::adjacent_find(next, vertices.end(), pred);
        if (next < vertices.end()) {
            auto first = next;
            PointIndex first_index = *first - rPoints.begin();
            ++next;
            while (next < vertices.end() && pred(*first, *next)) {
                PointIndex next_index = *next - rPoints.begin();
                mapPointIndex[next_index] = first_index;
                pointIndices.push_back(next_index);
                ++next;
            }
        }
    }

    // now set all facets to the correct index
    MeshFacetArray& rFacets = _rclMesh._aclFacetArray;
    for (auto& it : rFacets) {
        for (PointIndex& point : it._aulPoints) {
            auto pt = mapPointIndex.find(point);
            if (pt != mapPointIndex.end()) {
                point = pt->second;
            }
        }
    }

    // remove invalid indices
    _rclMesh.DeletePoints(pointIndices);
    _rclMesh.RebuildNeighbours();

    return true;
}

// ----------------------------------------------------------------------

bool MeshEvalNaNPoints::Evaluate()

{
    const MeshPointArray& rPoints = _rclMesh.GetPoints();
    for (const auto& it : rPoints) {
        if (boost::math::isnan(it.x) || boost::math::isnan(it.y) || boost::math::isnan(it.z)) {
            return false;
        }
    }

    return true;
}

std::vector<PointIndex> MeshEvalNaNPoints::GetIndices() const

{
    std::vector<PointIndex> aInds;
    const MeshPointArray& rPoints = _rclMesh.GetPoints();
    for (auto it = rPoints.begin(); it != rPoints.end(); ++it) {
        if (boost::math::isnan(it->x) || boost::math::isnan(it->y) || boost::math::isnan(it->z)) {
            aInds.push_back(it - rPoints.begin());
        }
    }

    return aInds;
}

bool MeshFixNaNPoints::Fixup()

{
    std::vector<PointIndex> aInds;
    const MeshPointArray& rPoints = _rclMesh.GetPoints();
    for (auto it = rPoints.begin(); it != rPoints.end(); ++it) {
        if (boost::math::isnan(it->x) || boost::math::isnan(it->y) || boost::math::isnan(it->z)) {
            aInds.push_back(it - rPoints.begin());
        }
    }

    // remove invalid indices
    _rclMesh.DeletePoints(aInds);
    _rclMesh.RebuildNeighbours();

    return true;
}

// ----------------------------------------------------------------------

namespace MeshCore
{

using FaceIterator = MeshFacetArray::_TConstIterator;
/*

 * The facet with the lowset index is regarded as 'less'.

 */
struct MeshFacet_Less
{
    bool operator()(const FaceIterator& x, const FaceIterator& y) const

    {
        PointIndex tmp {};
        PointIndex x0 = x->_aulPoints[0];
        PointIndex x1 = x->_aulPoints[1];
        PointIndex x2 = x->_aulPoints[2];
        PointIndex y0 = y->_aulPoints[0];
        PointIndex y1 = y->_aulPoints[1];
        PointIndex y2 = y->_aulPoints[2];

        if (x0 > x1) {
            tmp = x0;
            x0 = x1;
            x1 = tmp;
        }
        if (x0 > x2) {
            tmp = x0;
            x0 = x2;
            x2 = tmp;
        }
        if (x1 > x2) {
            tmp = x1;
            x1 = x2;
            x2 = tmp;
        }
        if (y0 > y1) {
            tmp = y0;
            y0 = y1;
            y1 = tmp;
        }
        if (y0 > y2) {
            tmp = y0;
            y0 = y2;
            y2 = tmp;
        }
        if (y1 > y2) {
            tmp = y1;
            y1 = y2;
            y2 = tmp;
        }

        if (x0 < y0) {
            return true;
        }
        if (x0 > y0) {
            return false;
        }
        if (x1 < y1) {
            return true;
        }
        if (x1 > y1) {
            return false;
        }
        if (x2 < y2) {
            return true;
        }

        return false;
    }
};

}  // namespace MeshCore

/*

 * Two facets are equal if all its three point indices refer to the same

 * location in the point array of the mesh kernel they belong to.

 */
struct MeshFacet_EqualTo
{
    bool operator()(const FaceIterator& x, const FaceIterator& y) const

    {
        for (int i = 0; i < 3; i++) {
            if (x->_aulPoints[0] == y->_aulPoints[i]) {
                if (x->_aulPoints[1] == y->_aulPoints[(i + 1) % 3]
                    && x->_aulPoints[2] == y->_aulPoints[(i + 2) % 3]) {
                    return true;
                }
                if (x->_aulPoints[1] == y->_aulPoints[(i + 2) % 3]
                    && x->_aulPoints[2] == y->_aulPoints[(i + 1) % 3]) {
                    return true;
                }
            }
        }

        return false;
    }
};

bool MeshEvalDuplicateFacets::Evaluate()

{
    std::set<FaceIterator, MeshFacet_Less> aFaces;
    const MeshFacetArray& rFaces = _rclMesh.GetFacets();
    for (auto it = rFaces.begin(); it != rFaces.end(); ++it) {
        std::pair<std::set<FaceIterator, MeshFacet_Less>::iterator, bool> pI = aFaces.insert(it);
        if (!pI.second) {
            return false;
        }
    }

    return true;
}

std::vector<FacetIndex> MeshEvalDuplicateFacets::GetIndices() const

{
#if 1
    const MeshFacetArray& rFacets = _rclMesh.GetFacets();
    std::vector<FaceIterator> faces;
    faces.reserve(rFacets.size());
    for (MeshFacetArray::_TConstIterator it = rFacets.begin(); it != rFacets.end(); ++it) {
        faces.push_back(it);
    }

    // if there are two adjacent faces which references the same vertices
    std::vector<FacetIndex> aInds;
    MeshFacet_EqualTo pred;
    std::sort(faces.begin(), faces.end(), MeshFacet_Less());

    std::vector<FaceIterator>::iterator ft = faces.begin();
    while (ft < faces.end()) {
        // get first item which adjacent element has the same face
        ft = std::adjacent_find(ft, faces.end(), pred);
        if (ft < faces.end()) {
            ++ft;
            aInds.push_back(*ft - rFacets.begin());
        }
    }

    return aInds;
#else
    std::vector<FacetIndex> aInds;
    const MeshFacetArray& rFaces = _rclMesh.GetFacets();
    FacetIndex uIndex = 0;

    // get all facets
    std::set<FaceIterator, MeshFacet_Less> aFaceSet;
    for (MeshFacetArray::_TConstIterator it = rFaces.begin(); it != rFaces.end(); ++it, uIndex++) {
        std::pair<std::set<FaceIterator, MeshFacet_Less>::iterator, bool> pI = aFaceSet.insert(it);
        if (!pI.second) {
            aInds.push_back(uIndex);
        }
    }

    return aInds;
#endif
}

bool MeshFixDuplicateFacets::Fixup()

{
    FacetIndex uIndex = 0;
    std::vector<FacetIndex> aRemoveFaces;
    const MeshFacetArray& rFaces = _rclMesh.GetFacets();

    // get all facets
    std::set<FaceIterator, MeshFacet_Less> aFaceSet;
    for (auto it = rFaces.begin(); it != rFaces.end(); ++it, uIndex++) {
        std::pair<std::set<FaceIterator, MeshFacet_Less>::iterator, bool> pI = aFaceSet.insert(it);
        if (!pI.second) {
            aRemoveFaces.push_back(uIndex);
        }
    }

    _rclMesh.DeleteFacets(aRemoveFaces);
    _rclMesh.RebuildNeighbours();  // needs to be done here

    return true;
}

// ----------------------------------------------------------------------

bool MeshEvalInternalFacets::Evaluate()

{
    _indices.clear();
    FacetIndex uIndex = 0;
    const MeshFacetArray& rFaces = _rclMesh.GetFacets();

    // get all facets
    std::set<FaceIterator, MeshFacet_Less> aFaceSet;
    MeshFacetArray::_TConstIterator first = rFaces.begin();
    for (auto it = rFaces.begin(); it != rFaces.end(); ++it, uIndex++) {
        std::pair<std::set<FaceIterator, MeshFacet_Less>::iterator, bool> pI = aFaceSet.insert(it);
        if (!pI.second) {
            // collect both elements
            _indices.push_back(*pI.first - first);
            _indices.push_back(uIndex);
        }
    }

    return _indices.empty();
}

// ----------------------------------------------------------------------

bool MeshEvalDegeneratedFacets::Evaluate()

{
    MeshFacetIterator it(_rclMesh);
    for (it.Init(); it.More(); it.Next()) {
        if (it->IsDegenerated(fEpsilon)) {
            return false;
        }
    }

    return true;
}

unsigned long MeshEvalDegeneratedFacets::CountEdgeTooSmall(float fMinEdgeLength) const

{
    MeshFacetIterator clFIter(_rclMesh);
    unsigned long k = 0;

    while (!clFIter.EndReached()) {
        for (int i = 0; i < 3; i++) {
            if (Base::Distance(clFIter->_aclPoints[i], clFIter->_aclPoints[(i + 1) % 3])
                < fMinEdgeLength) {
                k++;
            }
        }
        ++clFIter;
    }

    return k;
}

std::vector<FacetIndex> MeshEvalDegeneratedFacets::GetIndices() const

{
    std::vector<FacetIndex> aInds;
    MeshFacetIterator it(_rclMesh);
    for (it.Init(); it.More(); it.Next()) {
        if (it->IsDegenerated(fEpsilon)) {
            aInds.push_back(it.Position());
        }
    }

    return aInds;
}

bool MeshFixDegeneratedFacets::Fixup()

{
    MeshTopoAlgorithm cTopAlg(_rclMesh);

    MeshFacetIterator it(_rclMesh);
    for (it.Init(); it.More(); it.Next()) {
        if (it->IsDegenerated(fEpsilon)) {
            FacetIndex uId = it.Position();
            bool removed = cTopAlg.RemoveDegeneratedFacet(uId);
            if (removed) {
                // due to a modification of the array the iterator became invalid
                it.Set(uId - 1);
            }
        }
    }

    return true;
}

bool MeshRemoveNeedles::Fixup()

{
    using FaceEdge = std::pair<unsigned long, int>;  // (face, edge) pair
    using FaceEdgePriority = std::pair<float, FaceEdge>;

    MeshTopoAlgorithm topAlg(_rclMesh);
    MeshRefPointToFacets vf_it(_rclMesh);
    const MeshFacetArray& rclFAry = _rclMesh.GetFacets();
    const MeshPointArray& rclPAry = _rclMesh.GetPoints();
    rclFAry.ResetInvalid();
    rclPAry.ResetInvalid();
    rclPAry.ResetFlag(MeshPoint::VISIT);
    std::size_t facetCount = rclFAry.size();

    std::priority_queue<FaceEdgePriority, std::vector<FaceEdgePriority>, std::greater<>> todo;
    for (std::size_t index = 0; index < facetCount; index++) {
        const MeshFacet& facet = rclFAry[index];
        MeshGeomFacet tria(_rclMesh.GetFacet(facet));
        float perimeter = tria.Perimeter();
        float fMinLen = perimeter * fMinEdgeLength;
        for (int i = 0; i < 3; i++) {
            const Base::Vector3f& p1 = rclPAry[facet._aulPoints[i]];
            const Base::Vector3f& p2 = rclPAry[facet._aulPoints[(i + 1) % 3]];

            float distance = Base::Distance(p1, p2);
            if (distance < fMinLen) {
                unsigned long facetIndex = static_cast<unsigned long>(index);
                todo.push(std::make_pair(distance, std::make_pair(facetIndex, i)));
            }
        }
    }

    bool removedEdge = false;
    while (!todo.empty()) {
        FaceEdge faceedge = todo.top().second;
        todo.pop();

        // check if one of the face pairs was already processed
        if (!rclFAry[faceedge.first].IsValid()) {
            continue;
        }

        // the facet points may have changed, so check the current distance again
        const MeshFacet& facet = rclFAry[faceedge.first];
        MeshGeomFacet tria(_rclMesh.GetFacet(facet));
        float perimeter = tria.Perimeter();
        float fMinLen = perimeter * fMinEdgeLength;
        const Base::Vector3f& p1 = rclPAry[facet._aulPoints[faceedge.second]];
        const Base::Vector3f& p2 = rclPAry[facet._aulPoints[(faceedge.second + 1) % 3]];
        float distance = Base::Distance(p1, p2);
        if (distance >= fMinLen) {
            continue;
        }

        // collect the collapse-edge information
        EdgeCollapse ce;
        ce._fromPoint = rclFAry[faceedge.first]._aulPoints[faceedge.second];
        ce._toPoint = rclFAry[faceedge.first]._aulPoints[(faceedge.second + 1) % 3];

        ce._removeFacets.push_back(faceedge.first);
        FacetIndex neighbour = rclFAry[faceedge.first]._aulNeighbours[faceedge.second];
        if (neighbour != FACET_INDEX_MAX) {
            ce._removeFacets.push_back(neighbour);
        }

        std::set<FacetIndex> vf = vf_it[ce._fromPoint];
        vf.erase(faceedge.first);
        if (neighbour != FACET_INDEX_MAX) {
            vf.erase(neighbour);
        }
        ce._changeFacets.insert(ce._changeFacets.begin(), vf.begin(), vf.end());

        // get adjacent points
        std::set<PointIndex> vv;
        vv = vf_it.NeighbourPoints(ce._fromPoint);
        ce._adjacentFrom.insert(ce._adjacentFrom.begin(), vv.begin(), vv.end());
        vv = vf_it.NeighbourPoints(ce._toPoint);
        ce._adjacentTo.insert(ce._adjacentTo.begin(), vv.begin(), vv.end());

        if (topAlg.IsCollapseEdgeLegal(ce)) {
            topAlg.CollapseEdge(ce);
            for (auto it : ce._removeFacets) {
                vf_it.RemoveFacet(it);
            }
            for (auto it : ce._changeFacets) {
                vf_it.RemoveNeighbour(ce._fromPoint, it);
                vf_it.AddNeighbour(ce._toPoint, it);
            }
            removedEdge = true;
        }
    }

    if (removedEdge) {
        topAlg.Cleanup();
        _rclMesh.RebuildNeighbours();
    }

    return true;
}

// ----------------------------------------------------------------------

bool MeshFixCaps::Fixup()

{
    using FaceVertex = std::pair<unsigned long, int>;  // (face, vertex) pair
    using FaceVertexPriority = std::pair<float, FaceVertex>;

    MeshTopoAlgorithm topAlg(_rclMesh);
    const MeshFacetArray& rclFAry = _rclMesh.GetFacets();
    const MeshPointArray& rclPAry = _rclMesh.GetPoints();
    std::size_t facetCount = rclFAry.size();

    float fCosMaxAngle = static_cast<float>(cos(fMaxAngle));

    std::priority_queue<FaceVertexPriority, std::vector<FaceVertexPriority>, std::greater<>> todo;
    for (std::size_t index = 0; index < facetCount; index++) {
        for (int i = 0; i < 3; i++) {
            const MeshFacet& facet = rclFAry[index];
            const Base::Vector3f& p1 = rclPAry[facet._aulPoints[i]];
            const Base::Vector3f& p2 = rclPAry[facet._aulPoints[(i + 1) % 3]];
            const Base::Vector3f& p3 = rclPAry[facet._aulPoints[(i + 2) % 3]];
            Base::Vector3f dir1(p2 - p1);
            dir1.Normalize();
            Base::Vector3f dir2(p3 - p1);
            dir2.Normalize();

            float fCosAngle = dir1.Dot(dir2);
            if (fCosAngle < fCosMaxAngle) {
                unsigned long facetIndex = static_cast<unsigned long>(index);
                todo.push(std::make_pair(fCosAngle, std::make_pair(facetIndex, i)));
            }
        }
    }

    while (!todo.empty()) {
        FaceVertex facevertex = todo.top().second;
        todo.pop();

        // the facet points may have changed, so check the current distance again
        const MeshFacet& facet = rclFAry[facevertex.first];
        const Base::Vector3f& p1 = rclPAry[facet._aulPoints[facevertex.second]];
        const Base::Vector3f& p2 = rclPAry[facet._aulPoints[(facevertex.second + 1) % 3]];
        const Base::Vector3f& p3 = rclPAry[facet._aulPoints[(facevertex.second + 2) % 3]];
        Base::Vector3f dir1(p2 - p1);
        dir1.Normalize();
        Base::Vector3f dir2(p3 - p1);
        dir2.Normalize();

        // check that the criterion is still OK in case
        // an earlier edge-swap has an impact
        float fCosAngle = dir1.Dot(dir2);
        if (fCosAngle >= fCosMaxAngle) {
            continue;
        }

        // the triangle shouldn't be a needle, therefore the projection of the point with
        // the maximum angle must have a clear distance to the other corner points
        // as factor we choose a default value of 25% of the corresponding edge length
        Base::Vector3f p4 = p1.Perpendicular(p2, p3 - p2);
        float distP2P3 = Base::Distance(p2, p3);
        float distP2P4 = Base::Distance(p2, p4);
        float distP3P4 = Base::Distance(p3, p4);
        if (distP2P4 / distP2P3 < fSplitFactor || distP3P4 / distP2P3 < fSplitFactor) {
            continue;
        }

        FacetIndex facetpos = facevertex.first;
        FacetIndex neighbour = rclFAry[facetpos]._aulNeighbours[(facevertex.second + 1) % 3];
        if (neighbour != FACET_INDEX_MAX) {
            topAlg.SwapEdge(facetpos, neighbour);
        }
    }

    return true;
}

// ----------------------------------------------------------------------

bool MeshEvalDeformedFacets::Evaluate()

{
    float fCosMinAngle = cos(fMinAngle);
    float fCosMaxAngle = cos(fMaxAngle);

    MeshFacetIterator it(_rclMesh);
    for (it.Init(); it.More(); it.Next()) {
        if (it->IsDeformed(fCosMinAngle, fCosMaxAngle)) {
            return false;
        }
    }

    return true;
}

std::vector<FacetIndex> MeshEvalDeformedFacets::GetIndices() const

{
    float fCosMinAngle = cos(fMinAngle);
    float fCosMaxAngle = cos(fMaxAngle);

    std::vector<FacetIndex> aInds;
    MeshFacetIterator it(_rclMesh);
    for (it.Init(); it.More(); it.Next()) {
        if (it->IsDeformed(fCosMinAngle, fCosMaxAngle)) {
            aInds.push_back(it.Position());
        }
    }

    return aInds;
}

bool MeshFixDeformedFacets::Fixup()

{
    float fCosMinAngle = cos(fMinAngle);
    float fCosMaxAngle = cos(fMaxAngle);

    Base::Vector3f u, v;
    MeshTopoAlgorithm cTopAlg(_rclMesh);

    MeshFacetIterator it(_rclMesh);
    for (it.Init(); it.More(); it.Next()) {
        // possibly deformed but not degenerated
        if (!it->IsDegenerated(fEpsilon)) {
            // store the angles to avoid to compute twice
            float fCosAngles[3] = {0, 0, 0};
            bool done = false;

            for (int i = 0; i < 3; i++) {
                u = it->_aclPoints[(i + 1) % 3] - it->_aclPoints[i];
                v = it->_aclPoints[(i + 2) % 3] - it->_aclPoints[i];
                u.Normalize();
                v.Normalize();

                float fCosAngle = u * v;
                fCosAngles[i] = fCosAngle;
            }

            // first check for angle > 120 deg: in this case we swap with the opposite edge
            for (int i = 0; i < 3; i++) {
                float fCosAngle = fCosAngles[i];
                if (fCosAngle < fCosMaxAngle) {
                    const MeshFacet& face = it.GetReference();
                    FacetIndex uNeighbour = face._aulNeighbours[(i + 1) % 3];
                    if (uNeighbour != FACET_INDEX_MAX
                        && cTopAlg.ShouldSwapEdge(it.Position(), uNeighbour, fMaxSwapAngle)) {
                        cTopAlg.SwapEdge(it.Position(), uNeighbour);
                        done = true;
                    }
                    break;
                }
            }

            // we have swapped already
            if (done) {
                continue;
            }

            // now check for angle < 30 deg: in this case we swap with one of the edges the corner
            // is part of
            for (int j = 0; j < 3; j++) {
                float fCosAngle = fCosAngles[j];
                if (fCosAngle > fCosMinAngle) {
                    const MeshFacet& face = it.GetReference();

                    FacetIndex uNeighbour = face._aulNeighbours[j];
                    if (uNeighbour != FACET_INDEX_MAX
                        && cTopAlg.ShouldSwapEdge(it.Position(), uNeighbour, fMaxSwapAngle)) {
                        cTopAlg.SwapEdge(it.Position(), uNeighbour);
                        break;
                    }

                    uNeighbour = face._aulNeighbours[(j + 2) % 3];
                    if (uNeighbour != FACET_INDEX_MAX
                        && cTopAlg.ShouldSwapEdge(it.Position(), uNeighbour, fMaxSwapAngle)) {
                        cTopAlg.SwapEdge(it.Position(), uNeighbour);
                        break;
                    }
                }
            }
        }
    }

    return true;
}

// ----------------------------------------------------------------------

bool MeshFixMergeFacets::Fixup()

{
    MeshCore::MeshRefPointToPoints vv_it(_rclMesh);
    MeshCore::MeshRefPointToFacets vf_it(_rclMesh);
    unsigned long countPoints = _rclMesh.CountPoints();

    std::vector<MeshFacet> newFacets;
    newFacets.reserve(countPoints / 20);  // 5% should be sufficient

    MeshTopoAlgorithm topAlg(_rclMesh);
    for (unsigned long i = 0; i < countPoints; i++) {
        if (vv_it[i].size() == 3 && vf_it[i].size() == 3) {
            VertexCollapse vc;
            vc._point = i;
            const std::set<PointIndex>& adjPts = vv_it[i];
            vc._circumPoints.insert(vc._circumPoints.begin(), adjPts.begin(), adjPts.end());
            const std::set<FacetIndex>& adjFts = vf_it[i];
            vc._circumFacets.insert(vc._circumFacets.begin(), adjFts.begin(), adjFts.end());
            topAlg.CollapseVertex(vc);
        }
    }

    topAlg.Cleanup();
    return true;
}

// ----------------------------------------------------------------------

bool MeshEvalDentsOnSurface::Evaluate()

{
    this->indices.clear();
    MeshRefPointToFacets clPt2Facets(_rclMesh);
    const MeshPointArray& rPntAry = _rclMesh.GetPoints();
    MeshFacetArray::_TConstIterator f_beg = _rclMesh.GetFacets().begin();

    MeshGeomFacet rTriangle;
    Base::Vector3f tmp;
    unsigned long ctPoints = _rclMesh.CountPoints();
    for (unsigned long index = 0; index < ctPoints; index++) {
        std::vector<PointIndex> point;
        point.push_back(index);

        // get the local neighbourhood of the point
        std::set<PointIndex> nb = clPt2Facets.NeighbourPoints(point, 1);
        const std::set<FacetIndex>& faces = clPt2Facets[index];

        for (PointIndex pt : nb) {
            const MeshPoint& mp = rPntAry[pt];
            for (FacetIndex ft : faces) {
                // the point must not be part of the facet we test
                if (f_beg[ft]._aulPoints[0] == pt) {
                    continue;
                }
                if (f_beg[ft]._aulPoints[1] == pt) {
                    continue;
                }
                if (f_beg[ft]._aulPoints[2] == pt) {
                    continue;
                }
                // is the point projectable onto the facet?
                rTriangle = _rclMesh.GetFacet(f_beg[ft]);
                if (rTriangle.IntersectWithLine(mp, rTriangle.GetNormal(), tmp)) {
                    const std::set<FacetIndex>& f = clPt2Facets[pt];
                    this->indices.insert(this->indices.end(), f.begin(), f.end());
                    break;
                }
            }
        }
    }

    // remove duplicates
    std::sort(this->indices.begin(), this->indices.end());
    this->indices.erase(std::unique(this->indices.begin(), this->indices.end()), this->indices.end());

    return this->indices.empty();
}

std::vector<FacetIndex> MeshEvalDentsOnSurface::GetIndices() const

{
    return this->indices;
}

/*

Forbidden is:

 + two facets share a common point but not a common edge



 Repair:

 + store the point indices which can be projected on a face

 + store the face indices on which a point can be projected

 + remove faces with an edge length smaller than a certain threshold (e.g. 0.01) from the stored

triangles or that reference one of the stored points

 + for this edge merge the two points

 + if a point of a face can be projected onto another face and they have a common point then split

the second face if the distance is under a certain threshold

 */
bool MeshFixDentsOnSurface::Fixup()

{
    MeshEvalDentsOnSurface eval(_rclMesh);
    if (!eval.Evaluate()) {
        std::vector<FacetIndex> inds = eval.GetIndices();
        _rclMesh.DeleteFacets(inds);
    }

    return true;
}

// ----------------------------------------------------------------------

bool MeshEvalFoldsOnSurface::Evaluate()

{
    this->indices.clear();
    const MeshFacetArray& rFAry = _rclMesh.GetFacets();
    unsigned long ct = 0;
    for (auto it = rFAry.begin(); it != rFAry.end(); ++it, ct++) {
        for (int i = 0; i < 3; i++) {
            FacetIndex n1 = it->_aulNeighbours[i];
            FacetIndex n2 = it->_aulNeighbours[(i + 1) % 3];
            Base::Vector3f v1 = _rclMesh.GetFacet(*it).GetNormal();
            if (n1 != FACET_INDEX_MAX && n2 != FACET_INDEX_MAX) {
                Base::Vector3f v2 = _rclMesh.GetFacet(n1).GetNormal();
                Base::Vector3f v3 = _rclMesh.GetFacet(n2).GetNormal();
                if (v2 * v3 > 0.0F) {
                    if (v1 * v2 < -0.1F && v1 * v3 < -0.1F) {
                        indices.push_back(n1);
                        indices.push_back(n2);
                        indices.push_back(ct);
                    }
                }
            }
        }
    }

    // remove duplicates
    std::sort(this->indices.begin(), this->indices.end());
    this->indices.erase(std::unique(this->indices.begin(), this->indices.end()), this->indices.end());
    return this->indices.empty();
}

std::vector<FacetIndex> MeshEvalFoldsOnSurface::GetIndices() const

{
    return this->indices;
}

// ----------------------------------------------------------------------

bool MeshEvalFoldsOnBoundary::Evaluate()

{
    // remove all boundary facets with two open edges and where
    // the angle to the neighbour is more than 60 degree
    this->indices.clear();
    const MeshFacetArray& rFacAry = _rclMesh.GetFacets();
    for (auto it = rFacAry.begin(); it != rFacAry.end(); ++it) {
        if (it->CountOpenEdges() == 2) {
            for (FacetIndex nbIndex : it->_aulNeighbours) {
                if (nbIndex != FACET_INDEX_MAX) {
                    MeshGeomFacet f1 = _rclMesh.GetFacet(*it);
                    MeshGeomFacet f2 = _rclMesh.GetFacet(nbIndex);
                    float cos_angle = f1.GetNormal() * f2.GetNormal();
                    if (cos_angle <= 0.5F) {  // ~ 60 degree
                        indices.push_back(it - rFacAry.begin());
                    }
                }
            }
        }
    }

    return this->indices.empty();
}

std::vector<FacetIndex> MeshEvalFoldsOnBoundary::GetIndices() const

{
    return this->indices;
}

bool MeshFixFoldsOnBoundary::Fixup()

{
    MeshEvalFoldsOnBoundary eval(_rclMesh);
    if (!eval.Evaluate()) {
        std::vector<FacetIndex> inds = eval.GetIndices();
        _rclMesh.DeleteFacets(inds);
    }

    return true;
}

// ----------------------------------------------------------------------

bool MeshEvalFoldOversOnSurface::Evaluate()

{
    this->indices.clear();
    const MeshCore::MeshFacetArray& facets = _rclMesh.GetFacets();
    MeshCore::MeshFacetArray::_TConstIterator f_it, f_beg = facets.begin(), f_end = facets.end();

    Base::Vector3f n1, n2;
    for (f_it = facets.begin(); f_it != f_end; ++f_it) {
        for (int i = 0; i < 3; i++) {
            FacetIndex index1 = f_it->_aulNeighbours[i];
            FacetIndex index2 = f_it->_aulNeighbours[(i + 1) % 3];
            if (index1 != FACET_INDEX_MAX && index2 != FACET_INDEX_MAX) {
                // if the topology is correct but the normals flip from
                // two neighbours we have a fold
                if (f_it->HasSameOrientation(f_beg[index1])
                    && f_it->HasSameOrientation(f_beg[index2])) {
                    n1 = _rclMesh.GetFacet(index1).GetNormal();
                    n2 = _rclMesh.GetFacet(index2).GetNormal();
                    if (n1 * n2 < -0.5F) {  // angle > 120 deg
                        this->indices.push_back(f_it - f_beg);
                        break;
                    }
                }
            }
        }
    }

    return this->indices.empty();
}

// ----------------------------------------------------------------

bool MeshEvalBorderFacet::Evaluate()

{
    const MeshCore::MeshFacetArray& facets = _rclMesh.GetFacets();
    MeshCore::MeshFacetArray::_TConstIterator f_it, f_beg = facets.begin(), f_end = facets.end();
    MeshCore::MeshRefPointToPoints vv_it(_rclMesh);
    MeshCore::MeshRefPointToFacets vf_it(_rclMesh);

    for (f_it = facets.begin(); f_it != f_end; ++f_it) {
        bool ok = true;
        for (PointIndex index : f_it->_aulPoints) {
            if (vv_it[index].size() == vf_it[index].size()) {
                ok = false;
                break;
            }
        }

        if (ok) {
            _facets.push_back(f_it - f_beg);
        }
    }

    return _facets.empty();
}

// ----------------------------------------------------------------------

bool MeshEvalRangeFacet::Evaluate()

{
    const MeshFacetArray& rFaces = _rclMesh.GetFacets();
    FacetIndex ulCtFacets = rFaces.size();

    for (const auto& it : rFaces) {
        for (FacetIndex nbFacet : it._aulNeighbours) {
            if ((nbFacet >= ulCtFacets) && (nbFacet < FACET_INDEX_MAX)) {
                return false;
            }
        }
    }

    return true;
}

std::vector<FacetIndex> MeshEvalRangeFacet::GetIndices() const

{
    std::vector<FacetIndex> aInds;
    const MeshFacetArray& rFaces = _rclMesh.GetFacets();
    FacetIndex ulCtFacets = rFaces.size();

    FacetIndex ind = 0;
    for (auto it = rFaces.begin(); it != rFaces.end(); ++it, ind++) {
        for (FacetIndex nbIndex : it->_aulNeighbours) {
            if ((nbIndex >= ulCtFacets) && (nbIndex < FACET_INDEX_MAX)) {
                aInds.push_back(ind);
                break;
            }
        }
    }

    return aInds;
}

bool MeshFixRangeFacet::Fixup()

{
    _rclMesh.RebuildNeighbours();
    return true;
}

// ----------------------------------------------------------------------

bool MeshEvalRangePoint::Evaluate()

{
    const MeshFacetArray& rFaces = _rclMesh.GetFacets();
    PointIndex ulCtPoints = _rclMesh.CountPoints();

    for (const auto& it : rFaces) {
        if (std::find_if(
                it._aulPoints,
                it._aulPoints + 3,
                [ulCtPoints](PointIndex i) { return i >= ulCtPoints; }
            )
            < it._aulPoints + 3) {
            return false;
        }
    }

    return true;
}

std::vector<PointIndex> MeshEvalRangePoint::GetIndices() const

{
    std::vector<PointIndex> aInds;
    const MeshFacetArray& rFaces = _rclMesh.GetFacets();
    PointIndex ulCtPoints = _rclMesh.CountPoints();

    PointIndex ind = 0;
    for (auto it = rFaces.begin(); it != rFaces.end(); ++it, ind++) {
        if (std::find_if(
                it->_aulPoints,
                it->_aulPoints + 3,
                [ulCtPoints](PointIndex i) { return i >= ulCtPoints; }
            )
            < it->_aulPoints + 3) {
            aInds.push_back(ind);
        }
    }

    return aInds;
}

bool MeshFixRangePoint::Fixup()

{
    MeshEvalRangePoint eval(_rclMesh);
    if (_rclMesh.CountPoints() == 0) {
        // if no points are there but facets then the whole mesh can be cleared
        _rclMesh.Clear();
    }
    else {
        // facets with point indices out of range cannot be directly deleted because
        // 'DeleteFacets' will segfault. But setting all point indices to 0 works.
        std::vector<PointIndex> invalid = eval.GetIndices();
        if (!invalid.empty()) {
            for (PointIndex it : invalid) {
                _rclMesh.SetFacetPoints(it, 0, 0, 0);
            }

            _rclMesh.DeleteFacets(invalid);
        }
    }
    return true;
}

// ----------------------------------------------------------------------

bool MeshEvalCorruptedFacets::Evaluate()

{
    const MeshFacetArray& rFaces = _rclMesh.GetFacets();

    for (const auto& it : rFaces) {
        // duplicated point indices
        if (it.IsDegenerated()) {
            return false;
        }
    }

    return true;
}

std::vector<FacetIndex> MeshEvalCorruptedFacets::GetIndices() const

{
    std::vector<FacetIndex> aInds;
    const MeshFacetArray& rFaces = _rclMesh.GetFacets();
    FacetIndex ind = 0;

    for (auto it = rFaces.begin(); it != rFaces.end(); ++it, ind++) {
        if (it->IsDegenerated()) {
            aInds.push_back(ind);
        }
    }

    return aInds;
}

bool MeshFixCorruptedFacets::Fixup()

{
    MeshTopoAlgorithm cTopAlg(_rclMesh);

    MeshFacetIterator it(_rclMesh);
    for (it.Init(); it.More(); it.Next()) {
        if (it.GetReference().IsDegenerated()) {
            unsigned long uId = it.Position();
            bool removed = cTopAlg.RemoveCorruptedFacet(uId);
            if (removed) {
                // due to a modification of the array the iterator became invalid
                it.Set(uId - 1);
            }
        }
    }

    return true;
}

// ----------------------------------------------------------------------

bool MeshEvalPointOnEdge::Evaluate()

{
    MeshFacetGrid facetGrid(_rclMesh);
    const MeshPointArray& points = _rclMesh.GetPoints();
    const MeshFacetArray& facets = _rclMesh.GetFacets();

    auto IsPointOnEdge = [&points](PointIndex idx, const MeshFacet& facet) {
        // point must not be a corner of the facet
        if (!facet.HasPoint(idx)) {
            for (int i = 0; i < 3; i++) {
                MeshGeomEdge edge;
                edge._aclPoints[0] = points[facet._aulPoints[i]];
                edge._aclPoints[1] = points[facet._aulPoints[(i + 1) % 3]];

                if (edge.GetBoundBox().IsInBox(points[idx])) {
                    if (edge.IsPointOf(points[idx], 0.001F)) {
                        return true;
                    }
                }
            }
        }
        return false;
    };

    PointIndex maxPoints = _rclMesh.CountPoints();
    for (PointIndex i = 0; i < maxPoints; i++) {
        std::vector<FacetIndex> elements;
        facetGrid.GetElements(points[i], elements);

        for (const auto& it : elements) {
            const MeshFacet& face = facets[it];
            if (IsPointOnEdge(i, face)) {
                pointsIndices.push_back(i);
                if (face.HasOpenEdge()) {
                    facetsIndices.push_back(it);
                }
            }
        }
    }
    return pointsIndices.empty();
}

std::vector<PointIndex> MeshEvalPointOnEdge::GetPointIndices() const

{
    return pointsIndices;
}

std::vector<FacetIndex> MeshEvalPointOnEdge::GetFacetIndices() const

{
    return facetsIndices;
}

bool MeshFixPointOnEdge::Fixup()

{
    MeshEvalPointOnEdge eval(_rclMesh);
    eval.Evaluate();
    std::vector<PointIndex> pointsIndices = eval.GetPointIndices();
    std::vector<FacetIndex> facetsIndices = eval.GetFacetIndices();

    if (!pointsIndices.empty()) {
        if (fillBoundary) {
            MarkBoundaries(facetsIndices);
        }

        _rclMesh.DeletePoints(pointsIndices);

        if (fillBoundary) {
            std::list<std::vector<PointIndex>> borderList;
            FindBoundaries(borderList);
            if (!borderList.empty()) {
                FillBoundaries(borderList);
            }
        }
    }

    return true;
}

void MeshFixPointOnEdge::MarkBoundaries(const std::vector<FacetIndex>& facetsIndices)

{
    MeshAlgorithm meshalg(_rclMesh);
    meshalg.ResetFacetFlag(MeshFacet::TMP0);
    meshalg.SetFacetsFlag(facetsIndices, MeshFacet::TMP0);
}

void MeshFixPointOnEdge::FindBoundaries(std::list<std::vector<PointIndex>>& borderList)

{
    std::vector<FacetIndex> tmp;
    MeshAlgorithm meshalg(_rclMesh);
    meshalg.GetFacetsFlag(tmp, MeshFacet::TMP0);

    if (!tmp.empty()) {
        meshalg.GetFacetsBorders(tmp, borderList);
    }
}

void MeshFixPointOnEdge::FillBoundaries(const std::list<std::vector<PointIndex>>& borderList)

{
    FlatTriangulator tria;
    tria.SetVerifier(new MeshCore::TriangulationVerifierV2);
    MeshTopoAlgorithm topalg(_rclMesh);
    std::list<std::vector<PointIndex>> failed;
    topalg.FillupHoles(1, tria, borderList, failed);
}