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
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
|
#include "TriangleMesh.hpp"
#include "ClipperUtils.hpp"
#include "Geometry.hpp"
#include "MultiPoint.hpp"
#include "qhull/src/libqhullcpp/Qhull.h"
#include "qhull/src/libqhullcpp/QhullFacetList.h"
#include "qhull/src/libqhullcpp/QhullVertexSet.h"
#include <cmath>
#include <deque>
#include <queue>
#include <set>
#include <vector>
#include <map>
#include <utility>
#include <algorithm>
#include <math.h>
#include <type_traits>
#include <boost/log/trivial.hpp>
#include <tbb/parallel_for.h>
#include <Eigen/Dense>
// for SLIC3R_DEBUG_SLICE_PROCESSING
#include "libslic3r.h"
#if 0
#define DEBUG
#define _DEBUG
#undef NDEBUG
#define SLIC3R_DEBUG
// #define SLIC3R_TRIANGLEMESH_DEBUG
#endif
#include <assert.h>
#if defined(SLIC3R_DEBUG) || defined(SLIC3R_DEBUG_SLICE_PROCESSING)
#include "SVG.hpp"
#endif
namespace Slic3r {
TriangleMesh::TriangleMesh()
: repaired(false)
{
stl_initialize(&this->stl);
}
TriangleMesh::TriangleMesh(const Pointf3s &points, const std::vector<Point3>& facets )
: repaired(false)
{
stl_initialize(&this->stl);
stl_file &stl = this->stl;
stl.error = 0;
stl.stats.type = inmemory;
// count facets and allocate memory
stl.stats.number_of_facets = facets.size();
stl.stats.original_num_facets = stl.stats.number_of_facets;
stl_allocate(&stl);
for (int i = 0; i < stl.stats.number_of_facets; i++) {
stl_facet facet;
const Pointf3& ref_f1 = points[facets[i].x];
facet.vertex[0].x = ref_f1.x;
facet.vertex[0].y = ref_f1.y;
facet.vertex[0].z = ref_f1.z;
const Pointf3& ref_f2 = points[facets[i].y];
facet.vertex[1].x = ref_f2.x;
facet.vertex[1].y = ref_f2.y;
facet.vertex[1].z = ref_f2.z;
const Pointf3& ref_f3 = points[facets[i].z];
facet.vertex[2].x = ref_f3.x;
facet.vertex[2].y = ref_f3.y;
facet.vertex[2].z = ref_f3.z;
facet.extra[0] = 0;
facet.extra[1] = 0;
float normal[3];
stl_calculate_normal(normal, &facet);
stl_normalize_vector(normal);
facet.normal.x = normal[0];
facet.normal.y = normal[1];
facet.normal.z = normal[2];
stl.facet_start[i] = facet;
}
stl_get_size(&stl);
}
TriangleMesh::TriangleMesh(const TriangleMesh &other) :
repaired(false)
{
stl_initialize(&this->stl);
*this = other;
}
TriangleMesh::TriangleMesh(TriangleMesh &&other) :
repaired(false)
{
stl_initialize(&this->stl);
this->swap(other);
}
TriangleMesh& TriangleMesh::operator=(const TriangleMesh &other)
{
stl_close(&this->stl);
this->stl = other.stl;
this->repaired = other.repaired;
this->stl.heads = nullptr;
this->stl.tail = nullptr;
this->stl.error = other.stl.error;
if (other.stl.facet_start != nullptr) {
this->stl.facet_start = (stl_facet*)calloc(other.stl.stats.number_of_facets, sizeof(stl_facet));
std::copy(other.stl.facet_start, other.stl.facet_start + other.stl.stats.number_of_facets, this->stl.facet_start);
}
if (other.stl.neighbors_start != nullptr) {
this->stl.neighbors_start = (stl_neighbors*)calloc(other.stl.stats.number_of_facets, sizeof(stl_neighbors));
std::copy(other.stl.neighbors_start, other.stl.neighbors_start + other.stl.stats.number_of_facets, this->stl.neighbors_start);
}
if (other.stl.v_indices != nullptr) {
this->stl.v_indices = (v_indices_struct*)calloc(other.stl.stats.number_of_facets, sizeof(v_indices_struct));
std::copy(other.stl.v_indices, other.stl.v_indices + other.stl.stats.number_of_facets, this->stl.v_indices);
}
if (other.stl.v_shared != nullptr) {
this->stl.v_shared = (stl_vertex*)calloc(other.stl.stats.shared_vertices, sizeof(stl_vertex));
std::copy(other.stl.v_shared, other.stl.v_shared + other.stl.stats.shared_vertices, this->stl.v_shared);
}
return *this;
}
TriangleMesh& TriangleMesh::operator=(TriangleMesh &&other)
{
this->swap(other);
return *this;
}
void
TriangleMesh::swap(TriangleMesh &other)
{
std::swap(this->stl, other.stl);
std::swap(this->repaired, other.repaired);
}
TriangleMesh::~TriangleMesh() {
stl_close(&this->stl);
}
void
TriangleMesh::ReadSTLFile(const char* input_file) {
stl_open(&stl, input_file);
}
void
TriangleMesh::write_ascii(const char* output_file)
{
stl_write_ascii(&this->stl, output_file, "");
}
void
TriangleMesh::write_binary(const char* output_file)
{
stl_write_binary(&this->stl, output_file, "");
}
void
TriangleMesh::repair() {
if (this->repaired) return;
// admesh fails when repairing empty meshes
if (this->stl.stats.number_of_facets == 0) return;
BOOST_LOG_TRIVIAL(debug) << "TriangleMesh::repair() started";
// checking exact
stl_check_facets_exact(&stl);
stl.stats.facets_w_1_bad_edge = (stl.stats.connected_facets_2_edge - stl.stats.connected_facets_3_edge);
stl.stats.facets_w_2_bad_edge = (stl.stats.connected_facets_1_edge - stl.stats.connected_facets_2_edge);
stl.stats.facets_w_3_bad_edge = (stl.stats.number_of_facets - stl.stats.connected_facets_1_edge);
// checking nearby
//int last_edges_fixed = 0;
float tolerance = stl.stats.shortest_edge;
float increment = stl.stats.bounding_diameter / 10000.0;
int iterations = 2;
if (stl.stats.connected_facets_3_edge < stl.stats.number_of_facets) {
for (int i = 0; i < iterations; i++) {
if (stl.stats.connected_facets_3_edge < stl.stats.number_of_facets) {
//printf("Checking nearby. Tolerance= %f Iteration=%d of %d...", tolerance, i + 1, iterations);
stl_check_facets_nearby(&stl, tolerance);
//printf(" Fixed %d edges.\n", stl.stats.edges_fixed - last_edges_fixed);
//last_edges_fixed = stl.stats.edges_fixed;
tolerance += increment;
} else {
break;
}
}
}
// remove_unconnected
if (stl.stats.connected_facets_3_edge < stl.stats.number_of_facets) {
stl_remove_unconnected_facets(&stl);
}
// fill_holes
#if 0
// Don't fill holes, the current algorithm does more harm than good on complex holes.
// Rather let the slicing algorithm close gaps in 2D slices.
if (stl.stats.connected_facets_3_edge < stl.stats.number_of_facets) {
stl_fill_holes(&stl);
stl_clear_error(&stl);
}
#endif
// normal_directions
stl_fix_normal_directions(&stl);
// normal_values
stl_fix_normal_values(&stl);
// always calculate the volume and reverse all normals if volume is negative
stl_calculate_volume(&stl);
// neighbors
stl_verify_neighbors(&stl);
this->repaired = true;
BOOST_LOG_TRIVIAL(debug) << "TriangleMesh::repair() finished";
}
float TriangleMesh::volume()
{
if (this->stl.stats.volume == -1)
stl_calculate_volume(&this->stl);
return this->stl.stats.volume;
}
void TriangleMesh::check_topology()
{
// checking exact
stl_check_facets_exact(&stl);
stl.stats.facets_w_1_bad_edge = (stl.stats.connected_facets_2_edge - stl.stats.connected_facets_3_edge);
stl.stats.facets_w_2_bad_edge = (stl.stats.connected_facets_1_edge - stl.stats.connected_facets_2_edge);
stl.stats.facets_w_3_bad_edge = (stl.stats.number_of_facets - stl.stats.connected_facets_1_edge);
// checking nearby
//int last_edges_fixed = 0;
float tolerance = stl.stats.shortest_edge;
float increment = stl.stats.bounding_diameter / 10000.0;
int iterations = 2;
if (stl.stats.connected_facets_3_edge < stl.stats.number_of_facets) {
for (int i = 0; i < iterations; i++) {
if (stl.stats.connected_facets_3_edge < stl.stats.number_of_facets) {
//printf("Checking nearby. Tolerance= %f Iteration=%d of %d...", tolerance, i + 1, iterations);
stl_check_facets_nearby(&stl, tolerance);
//printf(" Fixed %d edges.\n", stl.stats.edges_fixed - last_edges_fixed);
//last_edges_fixed = stl.stats.edges_fixed;
tolerance += increment;
} else {
break;
}
}
}
}
bool TriangleMesh::is_manifold() const
{
return this->stl.stats.connected_facets_3_edge == this->stl.stats.number_of_facets;
}
void
TriangleMesh::reset_repair_stats() {
this->stl.stats.degenerate_facets = 0;
this->stl.stats.edges_fixed = 0;
this->stl.stats.facets_removed = 0;
this->stl.stats.facets_added = 0;
this->stl.stats.facets_reversed = 0;
this->stl.stats.backwards_edges = 0;
this->stl.stats.normals_fixed = 0;
}
bool
TriangleMesh::needed_repair() const
{
return this->stl.stats.degenerate_facets > 0
|| this->stl.stats.edges_fixed > 0
|| this->stl.stats.facets_removed > 0
|| this->stl.stats.facets_added > 0
|| this->stl.stats.facets_reversed > 0
|| this->stl.stats.backwards_edges > 0;
}
size_t
TriangleMesh::facets_count() const
{
return this->stl.stats.number_of_facets;
}
void
TriangleMesh::WriteOBJFile(char* output_file) {
stl_generate_shared_vertices(&stl);
stl_write_obj(&stl, output_file);
}
void TriangleMesh::scale(float factor)
{
stl_scale(&(this->stl), factor);
stl_invalidate_shared_vertices(&this->stl);
}
void TriangleMesh::scale(const Pointf3 &versor)
{
float fversor[3];
fversor[0] = versor.x;
fversor[1] = versor.y;
fversor[2] = versor.z;
stl_scale_versor(&this->stl, fversor);
stl_invalidate_shared_vertices(&this->stl);
}
void TriangleMesh::translate(float x, float y, float z)
{
if (x == 0.f && y == 0.f && z == 0.f)
return;
stl_translate_relative(&(this->stl), x, y, z);
stl_invalidate_shared_vertices(&this->stl);
}
void TriangleMesh::rotate(float angle, Pointf3 axis)
{
if (angle == 0.f)
return;
axis = normalize(axis);
Eigen::Transform<float, 3, Eigen::Affine> m = Eigen::Transform<float, 3, Eigen::Affine>::Identity();
m.rotate(Eigen::AngleAxisf(angle, Eigen::Vector3f(axis.x, axis.y, axis.z)));
stl_transform(&stl, (float*)m.data());
}
void TriangleMesh::rotate(float angle, const Axis &axis)
{
if (angle == 0.f)
return;
// admesh uses degrees
angle = Slic3r::Geometry::rad2deg(angle);
if (axis == X) {
stl_rotate_x(&(this->stl), angle);
} else if (axis == Y) {
stl_rotate_y(&(this->stl), angle);
} else if (axis == Z) {
stl_rotate_z(&(this->stl), angle);
}
stl_invalidate_shared_vertices(&this->stl);
}
void TriangleMesh::rotate_x(float angle)
{
this->rotate(angle, X);
}
void TriangleMesh::rotate_y(float angle)
{
this->rotate(angle, Y);
}
void TriangleMesh::rotate_z(float angle)
{
this->rotate(angle, Z);
}
void TriangleMesh::mirror(const Axis &axis)
{
if (axis == X) {
stl_mirror_yz(&this->stl);
} else if (axis == Y) {
stl_mirror_xz(&this->stl);
} else if (axis == Z) {
stl_mirror_xy(&this->stl);
}
stl_invalidate_shared_vertices(&this->stl);
}
void TriangleMesh::mirror_x()
{
this->mirror(X);
}
void TriangleMesh::mirror_y()
{
this->mirror(Y);
}
void TriangleMesh::mirror_z()
{
this->mirror(Z);
}
void TriangleMesh::transform(const float* matrix3x4)
{
if (matrix3x4 == nullptr)
return;
stl_transform(&stl, const_cast<float*>(matrix3x4));
stl_invalidate_shared_vertices(&stl);
}
void TriangleMesh::align_to_origin()
{
this->translate(
-(this->stl.stats.min.x),
-(this->stl.stats.min.y),
-(this->stl.stats.min.z)
);
}
void TriangleMesh::rotate(double angle, Point* center)
{
if (angle == 0.)
return;
this->translate(float(-center->x), float(-center->y), 0);
stl_rotate_z(&(this->stl), (float)angle);
this->translate(float(+center->x), float(+center->y), 0);
}
bool TriangleMesh::has_multiple_patches() const
{
// we need neighbors
if (!this->repaired) CONFESS("split() requires repair()");
if (this->stl.stats.number_of_facets == 0)
return false;
std::vector<int> facet_queue(this->stl.stats.number_of_facets, 0);
std::vector<char> facet_visited(this->stl.stats.number_of_facets, false);
int facet_queue_cnt = 1;
facet_queue[0] = 0;
facet_visited[0] = true;
while (facet_queue_cnt > 0) {
int facet_idx = facet_queue[-- facet_queue_cnt];
facet_visited[facet_idx] = true;
for (int j = 0; j < 3; ++ j) {
int neighbor_idx = this->stl.neighbors_start[facet_idx].neighbor[j];
if (neighbor_idx != -1 && ! facet_visited[neighbor_idx])
facet_queue[facet_queue_cnt ++] = neighbor_idx;
}
}
// If any of the face was not visited at the first time, return "multiple bodies".
for (int facet_idx = 0; facet_idx < this->stl.stats.number_of_facets; ++ facet_idx)
if (! facet_visited[facet_idx])
return true;
return false;
}
size_t TriangleMesh::number_of_patches() const
{
// we need neighbors
if (!this->repaired) CONFESS("split() requires repair()");
if (this->stl.stats.number_of_facets == 0)
return false;
std::vector<int> facet_queue(this->stl.stats.number_of_facets, 0);
std::vector<char> facet_visited(this->stl.stats.number_of_facets, false);
int facet_queue_cnt = 0;
size_t num_bodies = 0;
for (;;) {
// Find a seeding triangle for a new body.
int facet_idx = 0;
for (; facet_idx < this->stl.stats.number_of_facets; ++ facet_idx)
if (! facet_visited[facet_idx]) {
// A seed triangle was found.
facet_queue[facet_queue_cnt ++] = facet_idx;
facet_visited[facet_idx] = true;
break;
}
if (facet_idx == this->stl.stats.number_of_facets)
// No seed found.
break;
++ num_bodies;
while (facet_queue_cnt > 0) {
int facet_idx = facet_queue[-- facet_queue_cnt];
facet_visited[facet_idx] = true;
for (int j = 0; j < 3; ++ j) {
int neighbor_idx = this->stl.neighbors_start[facet_idx].neighbor[j];
if (neighbor_idx != -1 && ! facet_visited[neighbor_idx])
facet_queue[facet_queue_cnt ++] = neighbor_idx;
}
}
}
return num_bodies;
}
TriangleMeshPtrs TriangleMesh::split() const
{
TriangleMeshPtrs meshes;
std::set<int> seen_facets;
// we need neighbors
if (!this->repaired) CONFESS("split() requires repair()");
// loop while we have remaining facets
for (;;) {
// get the first facet
std::queue<int> facet_queue;
std::deque<int> facets;
for (int facet_idx = 0; facet_idx < this->stl.stats.number_of_facets; facet_idx++) {
if (seen_facets.find(facet_idx) == seen_facets.end()) {
// if facet was not seen put it into queue and start searching
facet_queue.push(facet_idx);
break;
}
}
if (facet_queue.empty()) break;
while (!facet_queue.empty()) {
int facet_idx = facet_queue.front();
facet_queue.pop();
if (seen_facets.find(facet_idx) != seen_facets.end()) continue;
facets.push_back(facet_idx);
for (int j = 0; j <= 2; j++) {
facet_queue.push(this->stl.neighbors_start[facet_idx].neighbor[j]);
}
seen_facets.insert(facet_idx);
}
TriangleMesh* mesh = new TriangleMesh;
meshes.push_back(mesh);
mesh->stl.stats.type = inmemory;
mesh->stl.stats.number_of_facets = facets.size();
mesh->stl.stats.original_num_facets = mesh->stl.stats.number_of_facets;
stl_clear_error(&mesh->stl);
stl_allocate(&mesh->stl);
int first = 1;
for (std::deque<int>::const_iterator facet = facets.begin(); facet != facets.end(); ++facet) {
mesh->stl.facet_start[facet - facets.begin()] = this->stl.facet_start[*facet];
stl_facet_stats(&mesh->stl, this->stl.facet_start[*facet], first);
first = 0;
}
}
return meshes;
}
void TriangleMesh::merge(const TriangleMesh &mesh)
{
// reset stats and metadata
int number_of_facets = this->stl.stats.number_of_facets;
stl_invalidate_shared_vertices(&this->stl);
this->repaired = false;
// update facet count and allocate more memory
this->stl.stats.number_of_facets = number_of_facets + mesh.stl.stats.number_of_facets;
this->stl.stats.original_num_facets = this->stl.stats.number_of_facets;
stl_reallocate(&this->stl);
// copy facets
for (int i = 0; i < mesh.stl.stats.number_of_facets; i++) {
this->stl.facet_start[number_of_facets + i] = mesh.stl.facet_start[i];
}
// update size
stl_get_size(&this->stl);
}
// Calculate projection of the mesh into the XY plane, in scaled coordinates.
//FIXME This could be extremely slow! Use it for tiny meshes only!
ExPolygons TriangleMesh::horizontal_projection() const
{
Polygons pp;
pp.reserve(this->stl.stats.number_of_facets);
for (int i = 0; i < this->stl.stats.number_of_facets; i++) {
stl_facet* facet = &this->stl.facet_start[i];
Polygon p;
p.points.resize(3);
p.points[0] = Point::new_scale(facet->vertex[0].x, facet->vertex[0].y);
p.points[1] = Point::new_scale(facet->vertex[1].x, facet->vertex[1].y);
p.points[2] = Point::new_scale(facet->vertex[2].x, facet->vertex[2].y);
p.make_counter_clockwise(); // do this after scaling, as winding order might change while doing that
pp.push_back(p);
}
// the offset factor was tuned using groovemount.stl
return union_ex(offset(pp, scale_(0.01)), true);
}
Polygon TriangleMesh::convex_hull()
{
this->require_shared_vertices();
Points pp;
pp.reserve(this->stl.stats.shared_vertices);
for (int i = 0; i < this->stl.stats.shared_vertices; ++ i) {
stl_vertex* v = &this->stl.v_shared[i];
pp.emplace_back(Point::new_scale(v->x, v->y));
}
return Slic3r::Geometry::convex_hull(pp);
}
BoundingBoxf3 TriangleMesh::bounding_box() const
{
BoundingBoxf3 bb;
bb.defined = true;
bb.min.x = this->stl.stats.min.x;
bb.min.y = this->stl.stats.min.y;
bb.min.z = this->stl.stats.min.z;
bb.max.x = this->stl.stats.max.x;
bb.max.y = this->stl.stats.max.y;
bb.max.z = this->stl.stats.max.z;
return bb;
}
BoundingBoxf3 TriangleMesh::transformed_bounding_box(const std::vector<float>& matrix) const
{
bool has_shared = (stl.v_shared != nullptr);
if (!has_shared)
stl_generate_shared_vertices(&stl);
unsigned int vertices_count = (stl.stats.shared_vertices > 0) ? (unsigned int)stl.stats.shared_vertices : 3 * (unsigned int)stl.stats.number_of_facets;
if (vertices_count == 0)
return BoundingBoxf3();
Eigen::MatrixXf src_vertices(3, vertices_count);
if (stl.stats.shared_vertices > 0)
{
stl_vertex* vertex_ptr = stl.v_shared;
for (int i = 0; i < stl.stats.shared_vertices; ++i)
{
src_vertices(0, i) = vertex_ptr->x;
src_vertices(1, i) = vertex_ptr->y;
src_vertices(2, i) = vertex_ptr->z;
vertex_ptr += 1;
}
}
else
{
stl_facet* facet_ptr = stl.facet_start;
unsigned int v_id = 0;
while (facet_ptr < stl.facet_start + stl.stats.number_of_facets)
{
for (int i = 0; i < 3; ++i)
{
src_vertices(0, v_id) = facet_ptr->vertex[i].x;
src_vertices(1, v_id) = facet_ptr->vertex[i].y;
src_vertices(2, v_id) = facet_ptr->vertex[i].z;
}
facet_ptr += 1;
++v_id;
}
}
if (!has_shared && (stl.stats.shared_vertices > 0))
stl_invalidate_shared_vertices(&stl);
Eigen::Transform<float, 3, Eigen::Affine> m;
::memcpy((void*)m.data(), (const void*)matrix.data(), 16 * sizeof(float));
Eigen::MatrixXf dst_vertices(3, vertices_count);
dst_vertices = m * src_vertices.colwise().homogeneous();
float min_x = dst_vertices(0, 0);
float max_x = dst_vertices(0, 0);
float min_y = dst_vertices(1, 0);
float max_y = dst_vertices(1, 0);
float min_z = dst_vertices(2, 0);
float max_z = dst_vertices(2, 0);
for (int i = 1; i < vertices_count; ++i)
{
min_x = std::min(min_x, dst_vertices(0, i));
max_x = std::max(max_x, dst_vertices(0, i));
min_y = std::min(min_y, dst_vertices(1, i));
max_y = std::max(max_y, dst_vertices(1, i));
min_z = std::min(min_z, dst_vertices(2, i));
max_z = std::max(max_z, dst_vertices(2, i));
}
return BoundingBoxf3(Pointf3((coordf_t)min_x, (coordf_t)min_y, (coordf_t)min_z), Pointf3((coordf_t)max_x, (coordf_t)max_y, (coordf_t)max_z));
}
TriangleMesh TriangleMesh::convex_hull_3d() const
{
// Helper struct for qhull:
struct PointForQHull{
PointForQHull(float x_p, float y_p, float z_p) : x((realT)x_p), y((realT)y_p), z((realT)z_p) {}
realT x, y, z;
};
std::vector<PointForQHull> src_vertices;
// We will now fill the vector with input points for computation:
stl_facet* facet_ptr = stl.facet_start;
while (facet_ptr < stl.facet_start + stl.stats.number_of_facets)
{
for (int i = 0; i < 3; ++i)
{
const stl_vertex& v = facet_ptr->vertex[i];
src_vertices.emplace_back(v.x, v.y, v.z);
}
facet_ptr += 1;
}
// The qhull call:
orgQhull::Qhull qhull;
qhull.disableOutputStream(); // we want qhull to be quiet
try
{
qhull.runQhull("", 3, (int)src_vertices.size(), (const realT*)(src_vertices.data()), "Qt");
}
catch (...)
{
std::cout << "Unable to create convex hull" << std::endl;
return TriangleMesh();
}
// Let's collect results:
Pointf3s det_vertices;
std::vector<Point3> facets;
auto facet_list = qhull.facetList().toStdVector();
for (const orgQhull::QhullFacet& facet : facet_list)
{ // iterate through facets
orgQhull::QhullVertexSet vertices = facet.vertices();
for (int i = 0; i < 3; ++i)
{ // iterate through facet's vertices
orgQhull::QhullPoint p = vertices[i].point();
const float* coords = p.coordinates();
det_vertices.emplace_back(coords[0], coords[1], coords[2]);
}
unsigned int size = (unsigned int)det_vertices.size();
facets.emplace_back(size - 3, size - 2, size - 1);
}
TriangleMesh output_mesh(det_vertices, facets);
output_mesh.repair();
output_mesh.require_shared_vertices();
return output_mesh;
}
const float* TriangleMesh::first_vertex() const
{
return stl.facet_start ? &stl.facet_start->vertex[0].x : nullptr;
}
void TriangleMesh::require_shared_vertices()
{
BOOST_LOG_TRIVIAL(trace) << "TriangleMeshSlicer::require_shared_vertices - start";
if (!this->repaired)
this->repair();
if (this->stl.v_shared == NULL) {
BOOST_LOG_TRIVIAL(trace) << "TriangleMeshSlicer::require_shared_vertices - stl_generate_shared_vertices";
stl_generate_shared_vertices(&(this->stl));
}
#ifdef _DEBUG
// Verify validity of neighborship data.
for (int facet_idx = 0; facet_idx < stl.stats.number_of_facets; ++facet_idx) {
const stl_neighbors &nbr = stl.neighbors_start[facet_idx];
const int *vertices = stl.v_indices[facet_idx].vertex;
for (int nbr_idx = 0; nbr_idx < 3; ++nbr_idx) {
int nbr_face = this->stl.neighbors_start[facet_idx].neighbor[nbr_idx];
if (nbr_face != -1) {
assert(stl.v_indices[nbr_face].vertex[(nbr.which_vertex_not[nbr_idx] + 1) % 3] == vertices[(nbr_idx + 1) % 3]);
assert(stl.v_indices[nbr_face].vertex[(nbr.which_vertex_not[nbr_idx] + 2) % 3] == vertices[nbr_idx]);
}
}
}
#endif /* _DEBUG */
BOOST_LOG_TRIVIAL(trace) << "TriangleMeshSlicer::require_shared_vertices - end";
}
TriangleMeshSlicer::TriangleMeshSlicer(TriangleMesh* _mesh) :
mesh(_mesh)
{
_mesh->require_shared_vertices();
facets_edges.assign(_mesh->stl.stats.number_of_facets * 3, -1);
v_scaled_shared.assign(_mesh->stl.v_shared, _mesh->stl.v_shared + _mesh->stl.stats.shared_vertices);
// Scale the copied vertices.
for (int i = 0; i < this->mesh->stl.stats.shared_vertices; ++ i) {
this->v_scaled_shared[i].x /= float(SCALING_FACTOR);
this->v_scaled_shared[i].y /= float(SCALING_FACTOR);
this->v_scaled_shared[i].z /= float(SCALING_FACTOR);
}
// Create a mapping from triangle edge into face.
struct EdgeToFace {
// Index of the 1st vertex of the triangle edge. vertex_low <= vertex_high.
int vertex_low;
// Index of the 2nd vertex of the triangle edge.
int vertex_high;
// Index of a triangular face.
int face;
// Index of edge in the face, starting with 1. Negative indices if the edge was stored reverse in (vertex_low, vertex_high).
int face_edge;
bool operator==(const EdgeToFace &other) const { return vertex_low == other.vertex_low && vertex_high == other.vertex_high; }
bool operator<(const EdgeToFace &other) const { return vertex_low < other.vertex_low || (vertex_low == other.vertex_low && vertex_high < other.vertex_high); }
};
std::vector<EdgeToFace> edges_map;
edges_map.assign(this->mesh->stl.stats.number_of_facets * 3, EdgeToFace());
for (int facet_idx = 0; facet_idx < this->mesh->stl.stats.number_of_facets; ++ facet_idx)
for (int i = 0; i < 3; ++ i) {
EdgeToFace &e2f = edges_map[facet_idx*3+i];
e2f.vertex_low = this->mesh->stl.v_indices[facet_idx].vertex[i];
e2f.vertex_high = this->mesh->stl.v_indices[facet_idx].vertex[(i + 1) % 3];
e2f.face = facet_idx;
// 1 based indexing, to be always strictly positive.
e2f.face_edge = i + 1;
if (e2f.vertex_low > e2f.vertex_high) {
// Sort the vertices
std::swap(e2f.vertex_low, e2f.vertex_high);
// and make the face_edge negative to indicate a flipped edge.
e2f.face_edge = - e2f.face_edge;
}
}
std::sort(edges_map.begin(), edges_map.end());
// Assign a unique common edge id to touching triangle edges.
int num_edges = 0;
for (size_t i = 0; i < edges_map.size(); ++ i) {
EdgeToFace &edge_i = edges_map[i];
if (edge_i.face == -1)
// This edge has been connected to some neighbor already.
continue;
// Unconnected edge. Find its neighbor with the correct orientation.
size_t j;
bool found = false;
for (j = i + 1; j < edges_map.size() && edge_i == edges_map[j]; ++ j)
if (edge_i.face_edge * edges_map[j].face_edge < 0 && edges_map[j].face != -1) {
// Faces touching with opposite oriented edges and none of the edges is connected yet.
found = true;
break;
}
if (! found) {
//FIXME Vojtech: Trying to find an edge with equal orientation. This smells.
// admesh can assign the same edge ID to more than two facets (which is
// still topologically correct), so we have to search for a duplicate of
// this edge too in case it was already seen in this orientation
for (j = i + 1; j < edges_map.size() && edge_i == edges_map[j]; ++ j)
if (edges_map[j].face != -1) {
// Faces touching with equally oriented edges and none of the edges is connected yet.
found = true;
break;
}
}
// Assign an edge index to the 1st face.
this->facets_edges[edge_i.face * 3 + std::abs(edge_i.face_edge) - 1] = num_edges;
if (found) {
EdgeToFace &edge_j = edges_map[j];
this->facets_edges[edge_j.face * 3 + std::abs(edge_j.face_edge) - 1] = num_edges;
// Mark the edge as connected.
edge_j.face = -1;
}
++ num_edges;
}
}
void TriangleMeshSlicer::slice(const std::vector<float> &z, std::vector<Polygons>* layers) const
{
BOOST_LOG_TRIVIAL(debug) << "TriangleMeshSlicer::slice";
/*
This method gets called with a list of unscaled Z coordinates and outputs
a vector pointer having the same number of items as the original list.
Each item is a vector of polygons created by slicing our mesh at the
given heights.
This method should basically combine the behavior of the existing
Perl methods defined in lib/Slic3r/TriangleMesh.pm:
- analyze(): this creates the 'facets_edges' and the 'edges_facets'
tables (we don't need the 'edges' table)
- slice_facet(): this has to be done for each facet. It generates
intersection lines with each plane identified by the Z list.
The get_layer_range() binary search used to identify the Z range
of the facet is already ported to C++ (see Object.xsp)
- make_loops(): this has to be done for each layer. It creates polygons
from the lines generated by the previous step.
At the end, we free the tables generated by analyze() as we don't
need them anymore.
NOTE: this method accepts a vector of floats because the mesh coordinate
type is float.
*/
BOOST_LOG_TRIVIAL(debug) << "TriangleMeshSlicer::_slice_do";
std::vector<IntersectionLines> lines(z.size());
{
boost::mutex lines_mutex;
tbb::parallel_for(
tbb::blocked_range<int>(0,this->mesh->stl.stats.number_of_facets),
[&lines, &lines_mutex, &z, this](const tbb::blocked_range<int>& range) {
for (int facet_idx = range.begin(); facet_idx < range.end(); ++ facet_idx)
this->_slice_do(facet_idx, &lines, &lines_mutex, z);
}
);
}
// v_scaled_shared could be freed here
// build loops
BOOST_LOG_TRIVIAL(debug) << "TriangleMeshSlicer::_make_loops_do";
layers->resize(z.size());
tbb::parallel_for(
tbb::blocked_range<size_t>(0, z.size()),
[&lines, &layers, this](const tbb::blocked_range<size_t>& range) {
for (size_t line_idx = range.begin(); line_idx < range.end(); ++ line_idx)
this->make_loops(lines[line_idx], &(*layers)[line_idx]);
}
);
BOOST_LOG_TRIVIAL(debug) << "TriangleMeshSlicer::slice finished";
#ifdef SLIC3R_DEBUG
{
static int iRun = 0;
for (size_t i = 0; i < z.size(); ++ i) {
Polygons &polygons = (*layers)[i];
ExPolygons expolygons = union_ex(polygons, true);
SVG::export_expolygons(debug_out_path("slice_%d_%d.svg", iRun, i).c_str(), expolygons);
{
BoundingBox bbox;
for (const IntersectionLine &l : lines[i]) {
bbox.merge(l.a);
bbox.merge(l.b);
}
SVG svg(debug_out_path("slice_loops_%d_%d.svg", iRun, i).c_str(), bbox);
svg.draw(expolygons);
for (const IntersectionLine &l : lines[i])
svg.draw(l, "red", 0);
svg.draw_outline(expolygons, "black", "blue", 0);
svg.Close();
}
#if 0
//FIXME slice_facet() may create zero length edges due to rounding of doubles into coord_t.
for (Polygon &poly : polygons) {
for (size_t i = 1; i < poly.points.size(); ++ i)
assert(poly.points[i-1] != poly.points[i]);
assert(poly.points.front() != poly.points.back());
}
#endif
}
++ iRun;
}
#endif
}
void TriangleMeshSlicer::_slice_do(size_t facet_idx, std::vector<IntersectionLines>* lines, boost::mutex* lines_mutex,
const std::vector<float> &z) const
{
const stl_facet &facet = this->mesh->stl.facet_start[facet_idx];
// find facet extents
const float min_z = fminf(facet.vertex[0].z, fminf(facet.vertex[1].z, facet.vertex[2].z));
const float max_z = fmaxf(facet.vertex[0].z, fmaxf(facet.vertex[1].z, facet.vertex[2].z));
#ifdef SLIC3R_TRIANGLEMESH_DEBUG
printf("\n==> FACET %d (%f,%f,%f - %f,%f,%f - %f,%f,%f):\n", facet_idx,
facet.vertex[0].x, facet.vertex[0].y, facet.vertex[0].z,
facet.vertex[1].x, facet.vertex[1].y, facet.vertex[1].z,
facet.vertex[2].x, facet.vertex[2].y, facet.vertex[2].z);
printf("z: min = %.2f, max = %.2f\n", min_z, max_z);
#endif /* SLIC3R_TRIANGLEMESH_DEBUG */
// find layer extents
std::vector<float>::const_iterator min_layer, max_layer;
min_layer = std::lower_bound(z.begin(), z.end(), min_z); // first layer whose slice_z is >= min_z
max_layer = std::upper_bound(z.begin() + (min_layer - z.begin()), z.end(), max_z) - 1; // last layer whose slice_z is <= max_z
#ifdef SLIC3R_TRIANGLEMESH_DEBUG
printf("layers: min = %d, max = %d\n", (int)(min_layer - z.begin()), (int)(max_layer - z.begin()));
#endif /* SLIC3R_TRIANGLEMESH_DEBUG */
for (std::vector<float>::const_iterator it = min_layer; it != max_layer + 1; ++it) {
std::vector<float>::size_type layer_idx = it - z.begin();
IntersectionLine il;
if (this->slice_facet(*it / SCALING_FACTOR, facet, facet_idx, min_z, max_z, &il) == TriangleMeshSlicer::Slicing) {
boost::lock_guard<boost::mutex> l(*lines_mutex);
if (il.edge_type == feHorizontal) {
// Ignore horizontal triangles. Any valid horizontal triangle must have a vertical triangle connected, otherwise the part has zero volume.
} else
(*lines)[layer_idx].emplace_back(il);
}
}
}
void TriangleMeshSlicer::slice(const std::vector<float> &z, std::vector<ExPolygons>* layers) const
{
std::vector<Polygons> layers_p;
this->slice(z, &layers_p);
BOOST_LOG_TRIVIAL(debug) << "TriangleMeshSlicer::make_expolygons in parallel - start";
layers->resize(z.size());
tbb::parallel_for(
tbb::blocked_range<size_t>(0, z.size()),
[&layers_p, layers, this](const tbb::blocked_range<size_t>& range) {
for (size_t layer_id = range.begin(); layer_id < range.end(); ++ layer_id) {
#ifdef SLIC3R_TRIANGLEMESH_DEBUG
printf("Layer " PRINTF_ZU " (slice_z = %.2f):\n", layer_id, z[layer_id]);
#endif
this->make_expolygons(layers_p[layer_id], &(*layers)[layer_id]);
}
});
BOOST_LOG_TRIVIAL(debug) << "TriangleMeshSlicer::make_expolygons in parallel - end";
}
// Return true, if the facet has been sliced and line_out has been filled.
TriangleMeshSlicer::FacetSliceType TriangleMeshSlicer::slice_facet(
float slice_z, const stl_facet &facet, const int facet_idx,
const float min_z, const float max_z,
IntersectionLine *line_out) const
{
IntersectionPoint points[3];
size_t num_points = 0;
size_t point_on_layer = size_t(-1);
// Reorder vertices so that the first one is the one with lowest Z.
// This is needed to get all intersection lines in a consistent order
// (external on the right of the line)
const int *vertices = this->mesh->stl.v_indices[facet_idx].vertex;
int i = (facet.vertex[1].z == min_z) ? 1 : ((facet.vertex[2].z == min_z) ? 2 : 0);
for (int j = i; j - i < 3; ++j) { // loop through facet edges
int edge_id = this->facets_edges[facet_idx * 3 + (j % 3)];
int a_id = vertices[j % 3];
int b_id = vertices[(j+1) % 3];
const stl_vertex *a = &this->v_scaled_shared[a_id];
const stl_vertex *b = &this->v_scaled_shared[b_id];
// Is edge or face aligned with the cutting plane?
if (a->z == slice_z && b->z == slice_z) {
// Edge is horizontal and belongs to the current layer.
const stl_vertex &v0 = this->v_scaled_shared[vertices[0]];
const stl_vertex &v1 = this->v_scaled_shared[vertices[1]];
const stl_vertex &v2 = this->v_scaled_shared[vertices[2]];
const stl_normal &normal = this->mesh->stl.facet_start[facet_idx].normal;
// We may ignore this edge for slicing purposes, but we may still use it for object cutting.
FacetSliceType result = Slicing;
const stl_neighbors &nbr = this->mesh->stl.neighbors_start[facet_idx];
if (min_z == max_z) {
// All three vertices are aligned with slice_z.
line_out->edge_type = feHorizontal;
result = Cutting;
if (normal.z < 0) {
// If normal points downwards this is a bottom horizontal facet so we reverse its point order.
std::swap(a, b);
std::swap(a_id, b_id);
}
} else {
// Two vertices are aligned with the cutting plane, the third vertex is below or above the cutting plane.
int nbr_idx = j % 3;
int nbr_face = nbr.neighbor[nbr_idx];
// Is the third vertex below the cutting plane?
bool third_below = v0.z < slice_z || v1.z < slice_z || v2.z < slice_z;
// Two vertices on the cutting plane, the third vertex is below the plane. Consider the edge to be part of the slice
// only if it is the upper edge.
// (the bottom most edge resp. vertex of a triangle is not owned by the triangle, but the top most edge resp. vertex is part of the triangle
// in respect to the cutting plane).
result = third_below ? Slicing : Cutting;
if (third_below) {
line_out->edge_type = feTop;
std::swap(a, b);
std::swap(a_id, b_id);
} else
line_out->edge_type = feBottom;
}
line_out->a.x = a->x;
line_out->a.y = a->y;
line_out->b.x = b->x;
line_out->b.y = b->y;
line_out->a_id = a_id;
line_out->b_id = b_id;
assert(line_out->a != line_out->b);
return result;
}
if (a->z == slice_z) {
// Only point a alings with the cutting plane.
if (point_on_layer == size_t(-1) || points[point_on_layer].point_id != a_id) {
point_on_layer = num_points;
IntersectionPoint &point = points[num_points ++];
point.x = a->x;
point.y = a->y;
point.point_id = a_id;
}
} else if (b->z == slice_z) {
// Only point b alings with the cutting plane.
if (point_on_layer == size_t(-1) || points[point_on_layer].point_id != b_id) {
point_on_layer = num_points;
IntersectionPoint &point = points[num_points ++];
point.x = b->x;
point.y = b->y;
point.point_id = b_id;
}
} else if ((a->z < slice_z && b->z > slice_z) || (b->z < slice_z && a->z > slice_z)) {
// A general case. The face edge intersects the cutting plane. Calculate the intersection point.
assert(a_id != b_id);
// Sort the edge to give a consistent answer.
if (a_id > b_id) {
std::swap(a_id, b_id);
std::swap(a, b);
}
IntersectionPoint &point = points[num_points];
double t = (double(slice_z) - double(b->z)) / (double(a->z) - double(b->z));
if (t <= 0.) {
if (point_on_layer == size_t(-1) || points[point_on_layer].point_id != a_id) {
point.x = a->x;
point.y = a->y;
point_on_layer = num_points ++;
point.point_id = a_id;
}
} else if (t >= 1.) {
if (point_on_layer == size_t(-1) || points[point_on_layer].point_id != b_id) {
point.x = b->x;
point.y = b->y;
point_on_layer = num_points ++;
point.point_id = b_id;
}
} else {
point.x = coord_t(floor(double(b->x) + (double(a->x) - double(b->x)) * t + 0.5));
point.y = coord_t(floor(double(b->y) + (double(a->y) - double(b->y)) * t + 0.5));
point.edge_id = edge_id;
++ num_points;
}
}
}
// Facets must intersect each plane 0 or 2 times, or it may touch the plane at a single vertex only.
assert(num_points < 3);
if (num_points == 2) {
line_out->edge_type = feGeneral;
line_out->a = (Point)points[1];
line_out->b = (Point)points[0];
line_out->a_id = points[1].point_id;
line_out->b_id = points[0].point_id;
line_out->edge_a_id = points[1].edge_id;
line_out->edge_b_id = points[0].edge_id;
// Not a zero lenght edge.
//FIXME slice_facet() may create zero length edges due to rounding of doubles into coord_t.
//assert(line_out->a != line_out->b);
// The plane cuts at least one edge in a general position.
assert(line_out->a_id == -1 || line_out->b_id == -1);
assert(line_out->edge_a_id != -1 || line_out->edge_b_id != -1);
// General slicing position, use the segment for both slicing and object cutting.
#if 0
if (line_out->a_id != -1 && line_out->b_id != -1) {
// Solving a degenerate case, where both the intersections snapped to an edge.
// Correctly classify the face as below or above based on the position of the 3rd point.
int i = vertices[0];
if (i == line_out->a_id || i == line_out->b_id)
i = vertices[1];
if (i == line_out->a_id || i == line_out->b_id)
i = vertices[2];
assert(i != line_out->a_id && i != line_out->b_id);
line_out->edge_type = (this->v_scaled_shared[i].z < slice_z) ? feTop : feBottom;
}
#endif
return Slicing;
}
return NoSlice;
}
//FIXME Should this go away? For valid meshes the function slice_facet() returns Slicing
// and sets edges of vertical triangles to produce only a single edge per pair of neighbor faces.
// So the following code makes only sense now to handle degenerate meshes with more than two faces
// sharing a single edge.
static inline void remove_tangent_edges(std::vector<IntersectionLine> &lines)
{
std::vector<IntersectionLine*> by_vertex_pair;
by_vertex_pair.reserve(lines.size());
for (IntersectionLine& line : lines)
if (line.edge_type != feGeneral && line.a_id != -1)
// This is a face edge. Check whether there is its neighbor stored in lines.
by_vertex_pair.emplace_back(&line);
auto edges_lower_sorted = [](const IntersectionLine *l1, const IntersectionLine *l2) {
// Sort vertices of l1, l2 lexicographically
int l1a = l1->a_id;
int l1b = l1->b_id;
int l2a = l2->a_id;
int l2b = l2->b_id;
if (l1a > l1b)
std::swap(l1a, l1b);
if (l2a > l2b)
std::swap(l2a, l2b);
// Lexicographical "lower" operator on lexicographically sorted vertices should bring equal edges together when sored.
return l1a < l2a || (l1a == l2a && l1b < l2b);
};
std::sort(by_vertex_pair.begin(), by_vertex_pair.end(), edges_lower_sorted);
for (auto line = by_vertex_pair.begin(); line != by_vertex_pair.end(); ++ line) {
IntersectionLine &l1 = **line;
if (! l1.skip()) {
// Iterate as long as line and line2 edges share the same end points.
for (auto line2 = line + 1; line2 != by_vertex_pair.end() && ! edges_lower_sorted(*line, *line2); ++ line2) {
// Lines must share the end points.
assert(! edges_lower_sorted(*line, *line2));
assert(! edges_lower_sorted(*line2, *line));
IntersectionLine &l2 = **line2;
if (l2.skip())
continue;
if (l1.a_id == l2.a_id) {
assert(l1.b_id == l2.b_id);
l2.set_skip();
// If they are both oriented upwards or downwards (like a 'V'),
// then we can remove both edges from this layer since it won't
// affect the sliced shape.
// If one of them is oriented upwards and the other is oriented
// downwards, let's only keep one of them (it doesn't matter which
// one since all 'top' lines were reversed at slicing).
if (l1.edge_type == l2.edge_type) {
l1.set_skip();
break;
}
} else {
assert(l1.a_id == l2.b_id && l1.b_id == l2.a_id);
// If this edge joins two horizontal facets, remove both of them.
if (l1.edge_type == feHorizontal && l2.edge_type == feHorizontal) {
l1.set_skip();
l2.set_skip();
break;
}
}
}
}
}
}
struct OpenPolyline {
OpenPolyline() {};
OpenPolyline(const IntersectionReference &start, const IntersectionReference &end, Points &&points) :
start(start), end(end), points(std::move(points)), consumed(false) { this->length = Slic3r::length(this->points); }
void reverse() {
std::swap(start, end);
std::reverse(points.begin(), points.end());
}
IntersectionReference start;
IntersectionReference end;
Points points;
double length;
bool consumed;
};
// called by TriangleMeshSlicer::make_loops() to connect sliced triangles into closed loops and open polylines by the triangle connectivity.
// Only connects segments crossing triangles of the same orientation.
static void chain_lines_by_triangle_connectivity(std::vector<IntersectionLine> &lines, Polygons &loops, std::vector<OpenPolyline> &open_polylines)
{
// Build a map of lines by edge_a_id and a_id.
std::vector<IntersectionLine*> by_edge_a_id;
std::vector<IntersectionLine*> by_a_id;
by_edge_a_id.reserve(lines.size());
by_a_id.reserve(lines.size());
for (IntersectionLine &line : lines) {
if (! line.skip()) {
if (line.edge_a_id != -1)
by_edge_a_id.emplace_back(&line);
if (line.a_id != -1)
by_a_id.emplace_back(&line);
}
}
auto by_edge_lower = [](const IntersectionLine* il1, const IntersectionLine *il2) { return il1->edge_a_id < il2->edge_a_id; };
auto by_vertex_lower = [](const IntersectionLine* il1, const IntersectionLine *il2) { return il1->a_id < il2->a_id; };
std::sort(by_edge_a_id.begin(), by_edge_a_id.end(), by_edge_lower);
std::sort(by_a_id.begin(), by_a_id.end(), by_vertex_lower);
// Chain the segments with a greedy algorithm, collect the loops and unclosed polylines.
IntersectionLines::iterator it_line_seed = lines.begin();
for (;;) {
// take first spare line and start a new loop
IntersectionLine *first_line = nullptr;
for (; it_line_seed != lines.end(); ++ it_line_seed)
if (it_line_seed->is_seed_candidate()) {
//if (! it_line_seed->skip()) {
first_line = &(*it_line_seed ++);
break;
}
if (first_line == nullptr)
break;
first_line->set_skip();
Points loop_pts;
loop_pts.emplace_back(first_line->a);
IntersectionLine *last_line = first_line;
/*
printf("first_line edge_a_id = %d, edge_b_id = %d, a_id = %d, b_id = %d, a = %d,%d, b = %d,%d\n",
first_line->edge_a_id, first_line->edge_b_id, first_line->a_id, first_line->b_id,
first_line->a.x, first_line->a.y, first_line->b.x, first_line->b.y);
*/
IntersectionLine key;
for (;;) {
// find a line starting where last one finishes
IntersectionLine* next_line = nullptr;
if (last_line->edge_b_id != -1) {
key.edge_a_id = last_line->edge_b_id;
auto it_begin = std::lower_bound(by_edge_a_id.begin(), by_edge_a_id.end(), &key, by_edge_lower);
if (it_begin != by_edge_a_id.end()) {
auto it_end = std::upper_bound(it_begin, by_edge_a_id.end(), &key, by_edge_lower);
for (auto it_line = it_begin; it_line != it_end; ++ it_line)
if (! (*it_line)->skip()) {
next_line = *it_line;
break;
}
}
}
if (next_line == nullptr && last_line->b_id != -1) {
key.a_id = last_line->b_id;
auto it_begin = std::lower_bound(by_a_id.begin(), by_a_id.end(), &key, by_vertex_lower);
if (it_begin != by_a_id.end()) {
auto it_end = std::upper_bound(it_begin, by_a_id.end(), &key, by_vertex_lower);
for (auto it_line = it_begin; it_line != it_end; ++ it_line)
if (! (*it_line)->skip()) {
next_line = *it_line;
break;
}
}
}
if (next_line == nullptr) {
// Check whether we closed this loop.
if ((first_line->edge_a_id != -1 && first_line->edge_a_id == last_line->edge_b_id) ||
(first_line->a_id != -1 && first_line->a_id == last_line->b_id)) {
// The current loop is complete. Add it to the output.
loops.emplace_back(std::move(loop_pts));
#ifdef SLIC3R_TRIANGLEMESH_DEBUG
printf(" Discovered %s polygon of %d points\n", (p.is_counter_clockwise() ? "ccw" : "cw"), (int)p.points.size());
#endif
} else {
// This is an open polyline. Add it to the list of open polylines. These open polylines will processed later.
loop_pts.emplace_back(last_line->b);
open_polylines.emplace_back(OpenPolyline(
IntersectionReference(first_line->a_id, first_line->edge_a_id),
IntersectionReference(last_line->b_id, last_line->edge_b_id), std::move(loop_pts)));
}
break;
}
/*
printf("next_line edge_a_id = %d, edge_b_id = %d, a_id = %d, b_id = %d, a = %d,%d, b = %d,%d\n",
next_line->edge_a_id, next_line->edge_b_id, next_line->a_id, next_line->b_id,
next_line->a.x, next_line->a.y, next_line->b.x, next_line->b.y);
*/
loop_pts.emplace_back(next_line->a);
last_line = next_line;
next_line->set_skip();
}
}
}
std::vector<OpenPolyline*> open_polylines_sorted(std::vector<OpenPolyline> &open_polylines, bool update_lengths)
{
std::vector<OpenPolyline*> out;
out.reserve(open_polylines.size());
for (OpenPolyline &opl : open_polylines)
if (! opl.consumed) {
if (update_lengths)
opl.length = Slic3r::length(opl.points);
out.emplace_back(&opl);
}
std::sort(out.begin(), out.end(), [](const OpenPolyline *lhs, const OpenPolyline *rhs){ return lhs->length > rhs->length; });
return out;
}
// called by TriangleMeshSlicer::make_loops() to connect remaining open polylines across shared triangle edges and vertices.
// Depending on "try_connect_reversed", it may or may not connect segments crossing triangles of opposite orientation.
static void chain_open_polylines_exact(std::vector<OpenPolyline> &open_polylines, Polygons &loops, bool try_connect_reversed)
{
// Store the end points of open_polylines into vectors sorted
struct OpenPolylineEnd {
OpenPolylineEnd(OpenPolyline *polyline, bool start) : polyline(polyline), start(start) {}
OpenPolyline *polyline;
// Is it the start or end point?
bool start;
const IntersectionReference& ipref() const { return start ? polyline->start : polyline->end; }
// Return a unique ID for the intersection point.
// Return a positive id for a point, or a negative id for an edge.
int id() const { const IntersectionReference &r = ipref(); return (r.point_id >= 0) ? r.point_id : - r.edge_id; }
bool operator==(const OpenPolylineEnd &rhs) const { return this->polyline == rhs.polyline && this->start == rhs.start; }
};
auto by_id_lower = [](const OpenPolylineEnd &ope1, const OpenPolylineEnd &ope2) { return ope1.id() < ope2.id(); };
std::vector<OpenPolylineEnd> by_id;
by_id.reserve(2 * open_polylines.size());
for (OpenPolyline &opl : open_polylines) {
if (opl.start.point_id != -1 || opl.start.edge_id != -1)
by_id.emplace_back(OpenPolylineEnd(&opl, true));
if (try_connect_reversed && (opl.end.point_id != -1 || opl.end.edge_id != -1))
by_id.emplace_back(OpenPolylineEnd(&opl, false));
}
std::sort(by_id.begin(), by_id.end(), by_id_lower);
// Find an iterator to by_id_lower for the particular end of OpenPolyline (by comparing the OpenPolyline pointer and the start attribute).
auto find_polyline_end = [&by_id, by_id_lower](const OpenPolylineEnd &end) -> std::vector<OpenPolylineEnd>::iterator {
for (auto it = std::lower_bound(by_id.begin(), by_id.end(), end, by_id_lower);
it != by_id.end() && it->id() == end.id(); ++ it)
if (*it == end)
return it;
return by_id.end();
};
// Try to connect the loops.
std::vector<OpenPolyline*> sorted_by_length = open_polylines_sorted(open_polylines, false);
for (OpenPolyline *opl : sorted_by_length) {
if (opl->consumed)
continue;
opl->consumed = true;
OpenPolylineEnd end(opl, false);
for (;;) {
// find a line starting where last one finishes
auto it_next_start = std::lower_bound(by_id.begin(), by_id.end(), end, by_id_lower);
for (; it_next_start != by_id.end() && it_next_start->id() == end.id(); ++ it_next_start)
if (! it_next_start->polyline->consumed)
goto found;
// The current loop could not be closed. Unmark the segment.
opl->consumed = false;
break;
found:
// Attach this polyline to the end of the initial polyline.
if (it_next_start->start) {
auto it = it_next_start->polyline->points.begin();
std::copy(++ it, it_next_start->polyline->points.end(), back_inserter(opl->points));
} else {
auto it = it_next_start->polyline->points.rbegin();
std::copy(++ it, it_next_start->polyline->points.rend(), back_inserter(opl->points));
}
opl->length += it_next_start->polyline->length;
// Mark the next polyline as consumed.
it_next_start->polyline->points.clear();
it_next_start->polyline->length = 0.;
it_next_start->polyline->consumed = true;
if (try_connect_reversed) {
// Running in a mode, where the polylines may be connected by mixing their orientations.
// Update the end point lookup structure after the end point of the current polyline was extended.
auto it_end = find_polyline_end(end);
auto it_next_end = find_polyline_end(OpenPolylineEnd(it_next_start->polyline, !it_next_start->start));
// Swap the end points of the current and next polyline, but keep the polyline ptr and the start flag.
std::swap(opl->end, it_next_end->start ? it_next_end->polyline->start : it_next_end->polyline->end);
// Swap the positions of OpenPolylineEnd structures in the sorted array to match their respective end point positions.
std::swap(*it_end, *it_next_end);
}
// Check whether we closed this loop.
if ((opl->start.edge_id != -1 && opl->start.edge_id == opl->end.edge_id) ||
(opl->start.point_id != -1 && opl->start.point_id == opl->end.point_id)) {
// The current loop is complete. Add it to the output.
//assert(opl->points.front().point_id == opl->points.back().point_id);
//assert(opl->points.front().edge_id == opl->points.back().edge_id);
// Remove the duplicate last point.
opl->points.pop_back();
if (opl->points.size() >= 3) {
if (try_connect_reversed && area(opl->points) < 0)
// The closed polygon is patched from pieces with messed up orientation, therefore
// the orientation of the patched up polygon is not known.
// Orient the patched up polygons CCW. This heuristic may close some holes and cavities.
std::reverse(opl->points.begin(), opl->points.end());
loops.emplace_back(std::move(opl->points));
}
opl->points.clear();
break;
}
// Continue with the current loop.
}
}
}
// called by TriangleMeshSlicer::make_loops() to connect remaining open polylines across shared triangle edges and vertices,
// possibly closing small gaps.
// Depending on "try_connect_reversed", it may or may not connect segments crossing triangles of opposite orientation.
static void chain_open_polylines_close_gaps(std::vector<OpenPolyline> &open_polylines, Polygons &loops, double max_gap, bool try_connect_reversed)
{
const coord_t max_gap_scaled = (coord_t)scale_(max_gap);
// Sort the open polylines by their length, so the new loops will be seeded from longer chains.
// Update the polyline lengths, return only not yet consumed polylines.
std::vector<OpenPolyline*> sorted_by_length = open_polylines_sorted(open_polylines, true);
// Store the end points of open_polylines into ClosestPointInRadiusLookup<OpenPolylineEnd>.
struct OpenPolylineEnd {
OpenPolylineEnd(OpenPolyline *polyline, bool start) : polyline(polyline), start(start) {}
OpenPolyline *polyline;
// Is it the start or end point?
bool start;
const Point& point() const { return start ? polyline->points.front() : polyline->points.back(); }
bool operator==(const OpenPolylineEnd &rhs) const { return this->polyline == rhs.polyline && this->start == rhs.start; }
};
struct OpenPolylineEndAccessor {
const Point* operator()(const OpenPolylineEnd &pt) const { return pt.polyline->consumed ? nullptr : &pt.point(); }
};
typedef ClosestPointInRadiusLookup<OpenPolylineEnd, OpenPolylineEndAccessor> ClosestPointLookupType;
ClosestPointLookupType closest_end_point_lookup(max_gap_scaled);
for (OpenPolyline *opl : sorted_by_length) {
closest_end_point_lookup.insert(OpenPolylineEnd(opl, true));
if (try_connect_reversed)
closest_end_point_lookup.insert(OpenPolylineEnd(opl, false));
}
// Try to connect the loops.
for (OpenPolyline *opl : sorted_by_length) {
if (opl->consumed)
continue;
OpenPolylineEnd end(opl, false);
if (try_connect_reversed)
// The end point of this polyline will be modified, thus the following entry will become invalid. Remove it.
closest_end_point_lookup.erase(end);
opl->consumed = true;
size_t n_segments_joined = 1;
for (;;) {
// Find a line starting where last one finishes, only return non-consumed open polylines (OpenPolylineEndAccessor returns null for consumed).
std::pair<const OpenPolylineEnd*, double> next_start_and_dist = closest_end_point_lookup.find(end.point());
const OpenPolylineEnd *next_start = next_start_and_dist.first;
// Check whether we closed this loop.
double current_loop_closing_distance2 = opl->points.front().distance_to_sq(opl->points.back());
bool loop_closed = current_loop_closing_distance2 < coordf_t(max_gap_scaled) * coordf_t(max_gap_scaled);
if (next_start != nullptr && loop_closed && current_loop_closing_distance2 < next_start_and_dist.second) {
// Heuristics to decide, whether to close the loop, or connect another polyline.
// One should avoid closing loops shorter than max_gap_scaled.
loop_closed = sqrt(current_loop_closing_distance2) < 0.3 * length(opl->points);
}
if (loop_closed) {
// Remove the start point of the current polyline from the lookup.
// Mark the current segment as not consumed, otherwise the closest_end_point_lookup.erase() would fail.
opl->consumed = false;
closest_end_point_lookup.erase(OpenPolylineEnd(opl, true));
if (current_loop_closing_distance2 == 0.) {
// Remove the duplicate last point.
opl->points.pop_back();
} else {
// The end points are different, keep both of them.
}
if (opl->points.size() >= 3) {
if (try_connect_reversed && n_segments_joined > 1 && area(opl->points) < 0)
// The closed polygon is patched from pieces with messed up orientation, therefore
// the orientation of the patched up polygon is not known.
// Orient the patched up polygons CCW. This heuristic may close some holes and cavities.
std::reverse(opl->points.begin(), opl->points.end());
loops.emplace_back(std::move(opl->points));
}
opl->points.clear();
opl->consumed = true;
break;
}
if (next_start == nullptr) {
// The current loop could not be closed. Unmark the segment.
opl->consumed = false;
if (try_connect_reversed)
// Re-insert the end point.
closest_end_point_lookup.insert(OpenPolylineEnd(opl, false));
break;
}
// Attach this polyline to the end of the initial polyline.
if (next_start->start) {
auto it = next_start->polyline->points.begin();
if (*it == opl->points.back())
++ it;
std::copy(it, next_start->polyline->points.end(), back_inserter(opl->points));
} else {
auto it = next_start->polyline->points.rbegin();
if (*it == opl->points.back())
++ it;
std::copy(it, next_start->polyline->points.rend(), back_inserter(opl->points));
}
++ n_segments_joined;
// Remove the end points of the consumed polyline segment from the lookup.
OpenPolyline *opl2 = next_start->polyline;
closest_end_point_lookup.erase(OpenPolylineEnd(opl2, true));
if (try_connect_reversed)
closest_end_point_lookup.erase(OpenPolylineEnd(opl2, false));
opl2->points.clear();
opl2->consumed = true;
// Continue with the current loop.
}
}
}
void TriangleMeshSlicer::make_loops(std::vector<IntersectionLine> &lines, Polygons* loops) const
{
#if 0
//FIXME slice_facet() may create zero length edges due to rounding of doubles into coord_t.
//#ifdef _DEBUG
for (const Line &l : lines)
assert(l.a != l.b);
#endif /* _DEBUG */
// There should be no tangent edges, as the horizontal triangles are ignored and if two triangles touch at a cutting plane,
// only the bottom triangle is considered to be cutting the plane.
// remove_tangent_edges(lines);
#ifdef SLIC3R_DEBUG_SLICE_PROCESSING
BoundingBox bbox_svg;
{
static int iRun = 0;
for (const Line &line : lines) {
bbox_svg.merge(line.a);
bbox_svg.merge(line.b);
}
SVG svg(debug_out_path("TriangleMeshSlicer_make_loops-raw_lines-%d.svg", iRun ++).c_str(), bbox_svg);
for (const Line &line : lines)
svg.draw(line);
svg.Close();
}
#endif /* SLIC3R_DEBUG_SLICE_PROCESSING */
std::vector<OpenPolyline> open_polylines;
chain_lines_by_triangle_connectivity(lines, *loops, open_polylines);
#ifdef SLIC3R_DEBUG_SLICE_PROCESSING
{
static int iRun = 0;
SVG svg(debug_out_path("TriangleMeshSlicer_make_loops-polylines-%d.svg", iRun ++).c_str(), bbox_svg);
svg.draw(union_ex(*loops));
for (const OpenPolyline &pl : open_polylines)
svg.draw(Polyline(pl.points), "red");
svg.Close();
}
#endif /* SLIC3R_DEBUG_SLICE_PROCESSING */
// Now process the open polylines.
// Do it in two rounds, first try to connect in the same direction only,
// then try to connect the open polylines in reversed order as well.
chain_open_polylines_exact(open_polylines, *loops, false);
chain_open_polylines_exact(open_polylines, *loops, true);
#ifdef SLIC3R_DEBUG_SLICE_PROCESSING
{
static int iRun = 0;
SVG svg(debug_out_path("TriangleMeshSlicer_make_loops-polylines2-%d.svg", iRun++).c_str(), bbox_svg);
svg.draw(union_ex(*loops));
for (const OpenPolyline &pl : open_polylines) {
if (pl.points.empty())
continue;
svg.draw(Polyline(pl.points), "red");
svg.draw(pl.points.front(), "blue");
svg.draw(pl.points.back(), "blue");
}
svg.Close();
}
#endif /* SLIC3R_DEBUG_SLICE_PROCESSING */
// Try to close gaps.
// Do it in two rounds, first try to connect in the same direction only,
// then try to connect the open polylines in reversed order as well.
const double max_gap = 2.; //mm
chain_open_polylines_close_gaps(open_polylines, *loops, max_gap, false);
chain_open_polylines_close_gaps(open_polylines, *loops, max_gap, true);
#ifdef SLIC3R_DEBUG_SLICE_PROCESSING
{
static int iRun = 0;
SVG svg(debug_out_path("TriangleMeshSlicer_make_loops-polylines-final-%d.svg", iRun++).c_str(), bbox_svg);
svg.draw(union_ex(*loops));
for (const OpenPolyline &pl : open_polylines) {
if (pl.points.empty())
continue;
svg.draw(Polyline(pl.points), "red");
svg.draw(pl.points.front(), "blue");
svg.draw(pl.points.back(), "blue");
}
svg.Close();
}
#endif /* SLIC3R_DEBUG_SLICE_PROCESSING */
}
// Only used to cut the mesh into two halves.
void TriangleMeshSlicer::make_expolygons_simple(std::vector<IntersectionLine> &lines, ExPolygons* slices) const
{
assert(slices->empty());
Polygons loops;
this->make_loops(lines, &loops);
Polygons holes;
for (Polygons::const_iterator loop = loops.begin(); loop != loops.end(); ++ loop) {
if (loop->area() >= 0.) {
ExPolygon ex;
ex.contour = *loop;
slices->push_back(ex);
} else {
holes.push_back(*loop);
}
}
// If there are holes, then there should also be outer contours.
assert(holes.empty() || ! slices->empty());
if (slices->empty())
return;
// Assign holes to outer contours.
for (Polygons::const_iterator hole = holes.begin(); hole != holes.end(); ++ hole) {
// Find an outer contour to a hole.
int slice_idx = -1;
double current_contour_area = std::numeric_limits<double>::max();
for (ExPolygons::iterator slice = slices->begin(); slice != slices->end(); ++ slice) {
if (slice->contour.contains(hole->points.front())) {
double area = slice->contour.area();
if (area < current_contour_area) {
slice_idx = slice - slices->begin();
current_contour_area = area;
}
}
}
// assert(slice_idx != -1);
if (slice_idx == -1)
// Ignore this hole.
continue;
assert(current_contour_area < std::numeric_limits<double>::max() && current_contour_area >= -hole->area());
(*slices)[slice_idx].holes.emplace_back(std::move(*hole));
}
#if 0
// If the input mesh is not valid, the holes may intersect with the external contour.
// Rather subtract them from the outer contour.
Polygons poly;
for (auto it_slice = slices->begin(); it_slice != slices->end(); ++ it_slice) {
if (it_slice->holes.empty()) {
poly.emplace_back(std::move(it_slice->contour));
} else {
Polygons contours;
contours.emplace_back(std::move(it_slice->contour));
for (auto it = it_slice->holes.begin(); it != it_slice->holes.end(); ++ it)
it->reverse();
polygons_append(poly, diff(contours, it_slice->holes));
}
}
// If the input mesh is not valid, the input contours may intersect.
*slices = union_ex(poly);
#endif
#if 0
// If the input mesh is not valid, the holes may intersect with the external contour.
// Rather subtract them from the outer contour.
ExPolygons poly;
for (auto it_slice = slices->begin(); it_slice != slices->end(); ++ it_slice) {
Polygons contours;
contours.emplace_back(std::move(it_slice->contour));
for (auto it = it_slice->holes.begin(); it != it_slice->holes.end(); ++ it)
it->reverse();
expolygons_append(poly, diff_ex(contours, it_slice->holes));
}
// If the input mesh is not valid, the input contours may intersect.
*slices = std::move(poly);
#endif
}
void TriangleMeshSlicer::make_expolygons(const Polygons &loops, ExPolygons* slices) const
{
/*
Input loops are not suitable for evenodd nor nonzero fill types, as we might get
two consecutive concentric loops having the same winding order - and we have to
respect such order. In that case, evenodd would create wrong inversions, and nonzero
would ignore holes inside two concentric contours.
So we're ordering loops and collapse consecutive concentric loops having the same
winding order.
TODO: find a faster algorithm for this, maybe with some sort of binary search.
If we computed a "nesting tree" we could also just remove the consecutive loops
having the same winding order, and remove the extra one(s) so that we could just
supply everything to offset() instead of performing several union/diff calls.
we sort by area assuming that the outermost loops have larger area;
the previous sorting method, based on $b->contains($a->[0]), failed to nest
loops correctly in some edge cases when original model had overlapping facets
*/
/* The following lines are commented out because they can generate wrong polygons,
see for example issue #661 */
//std::vector<double> area;
//std::vector<size_t> sorted_area; // vector of indices
//for (Polygons::const_iterator loop = loops.begin(); loop != loops.end(); ++ loop) {
// area.push_back(loop->area());
// sorted_area.push_back(loop - loops.begin());
//}
//
//// outer first
//std::sort(sorted_area.begin(), sorted_area.end(),
// [&area](size_t a, size_t b) { return std::abs(area[a]) > std::abs(area[b]); });
//// we don't perform a safety offset now because it might reverse cw loops
//Polygons p_slices;
//for (std::vector<size_t>::const_iterator loop_idx = sorted_area.begin(); loop_idx != sorted_area.end(); ++ loop_idx) {
// /* we rely on the already computed area to determine the winding order
// of the loops, since the Orientation() function provided by Clipper
// would do the same, thus repeating the calculation */
// Polygons::const_iterator loop = loops.begin() + *loop_idx;
// if (area[*loop_idx] > +EPSILON)
// p_slices.push_back(*loop);
// else if (area[*loop_idx] < -EPSILON)
// //FIXME This is arbitrary and possibly very slow.
// // If the hole is inside a polygon, then there is no need to diff.
// // If the hole intersects a polygon boundary, then diff it, but then
// // there is no guarantee of an ordering of the loops.
// // Maybe we can test for the intersection before running the expensive diff algorithm?
// p_slices = diff(p_slices, *loop);
//}
// perform a safety offset to merge very close facets (TODO: find test case for this)
double safety_offset = scale_(0.0499);
//FIXME see https://github.com/prusa3d/Slic3r/issues/520
// double safety_offset = scale_(0.0001);
/* The following line is commented out because it can generate wrong polygons,
see for example issue #661 */
//ExPolygons ex_slices = offset2_ex(p_slices, +safety_offset, -safety_offset);
#ifdef SLIC3R_TRIANGLEMESH_DEBUG
size_t holes_count = 0;
for (ExPolygons::const_iterator e = ex_slices.begin(); e != ex_slices.end(); ++ e)
holes_count += e->holes.size();
printf(PRINTF_ZU " surface(s) having " PRINTF_ZU " holes detected from " PRINTF_ZU " polylines\n",
ex_slices.size(), holes_count, loops.size());
#endif
// append to the supplied collection
/* Fix for issue #661 { */
expolygons_append(*slices, offset2_ex(union_(loops, false), +safety_offset, -safety_offset));
//expolygons_append(*slices, ex_slices);
/* } */
}
void TriangleMeshSlicer::make_expolygons(std::vector<IntersectionLine> &lines, ExPolygons* slices) const
{
Polygons pp;
this->make_loops(lines, &pp);
this->make_expolygons(pp, slices);
}
void TriangleMeshSlicer::cut(float z, TriangleMesh* upper, TriangleMesh* lower) const
{
IntersectionLines upper_lines, lower_lines;
float scaled_z = scale_(z);
for (int facet_idx = 0; facet_idx < this->mesh->stl.stats.number_of_facets; ++ facet_idx) {
stl_facet* facet = &this->mesh->stl.facet_start[facet_idx];
// find facet extents
float min_z = std::min(facet->vertex[0].z, std::min(facet->vertex[1].z, facet->vertex[2].z));
float max_z = std::max(facet->vertex[0].z, std::max(facet->vertex[1].z, facet->vertex[2].z));
// intersect facet with cutting plane
IntersectionLine line;
if (this->slice_facet(scaled_z, *facet, facet_idx, min_z, max_z, &line) != TriangleMeshSlicer::NoSlice) {
// Save intersection lines for generating correct triangulations.
if (line.edge_type == feTop) {
lower_lines.push_back(line);
} else if (line.edge_type == feBottom) {
upper_lines.push_back(line);
} else if (line.edge_type != feHorizontal) {
lower_lines.push_back(line);
upper_lines.push_back(line);
}
}
if (min_z > z || (min_z == z && max_z > z)) {
// facet is above the cut plane and does not belong to it
if (upper != NULL) stl_add_facet(&upper->stl, facet);
} else if (max_z < z || (max_z == z && min_z < z)) {
// facet is below the cut plane and does not belong to it
if (lower != NULL) stl_add_facet(&lower->stl, facet);
} else if (min_z < z && max_z > z) {
// Facet is cut by the slicing plane.
// look for the vertex on whose side of the slicing plane there are no other vertices
int isolated_vertex;
if ( (facet->vertex[0].z > z) == (facet->vertex[1].z > z) ) {
isolated_vertex = 2;
} else if ( (facet->vertex[1].z > z) == (facet->vertex[2].z > z) ) {
isolated_vertex = 0;
} else {
isolated_vertex = 1;
}
// get vertices starting from the isolated one
stl_vertex* v0 = &facet->vertex[isolated_vertex];
stl_vertex* v1 = &facet->vertex[(isolated_vertex+1) % 3];
stl_vertex* v2 = &facet->vertex[(isolated_vertex+2) % 3];
// intersect v0-v1 and v2-v0 with cutting plane and make new vertices
stl_vertex v0v1, v2v0;
v0v1.x = v1->x + (v0->x - v1->x) * (z - v1->z) / (v0->z - v1->z);
v0v1.y = v1->y + (v0->y - v1->y) * (z - v1->z) / (v0->z - v1->z);
v0v1.z = z;
v2v0.x = v2->x + (v0->x - v2->x) * (z - v2->z) / (v0->z - v2->z);
v2v0.y = v2->y + (v0->y - v2->y) * (z - v2->z) / (v0->z - v2->z);
v2v0.z = z;
// build the triangular facet
stl_facet triangle;
triangle.normal = facet->normal;
triangle.vertex[0] = *v0;
triangle.vertex[1] = v0v1;
triangle.vertex[2] = v2v0;
// build the facets forming a quadrilateral on the other side
stl_facet quadrilateral[2];
quadrilateral[0].normal = facet->normal;
quadrilateral[0].vertex[0] = *v1;
quadrilateral[0].vertex[1] = *v2;
quadrilateral[0].vertex[2] = v0v1;
quadrilateral[1].normal = facet->normal;
quadrilateral[1].vertex[0] = *v2;
quadrilateral[1].vertex[1] = v2v0;
quadrilateral[1].vertex[2] = v0v1;
if (v0->z > z) {
if (upper != NULL) stl_add_facet(&upper->stl, &triangle);
if (lower != NULL) {
stl_add_facet(&lower->stl, &quadrilateral[0]);
stl_add_facet(&lower->stl, &quadrilateral[1]);
}
} else {
if (upper != NULL) {
stl_add_facet(&upper->stl, &quadrilateral[0]);
stl_add_facet(&upper->stl, &quadrilateral[1]);
}
if (lower != NULL) stl_add_facet(&lower->stl, &triangle);
}
}
}
// triangulate holes of upper mesh
if (upper != NULL) {
// compute shape of section
ExPolygons section;
this->make_expolygons_simple(upper_lines, §ion);
// triangulate section
Polygons triangles;
for (ExPolygons::const_iterator expolygon = section.begin(); expolygon != section.end(); ++expolygon)
expolygon->triangulate_p2t(&triangles);
// convert triangles to facets and append them to mesh
for (Polygons::const_iterator polygon = triangles.begin(); polygon != triangles.end(); ++polygon) {
Polygon p = *polygon;
p.reverse();
stl_facet facet;
facet.normal.x = 0;
facet.normal.y = 0;
facet.normal.z = -1;
for (size_t i = 0; i <= 2; ++i) {
facet.vertex[i].x = unscale(p.points[i].x);
facet.vertex[i].y = unscale(p.points[i].y);
facet.vertex[i].z = z;
}
stl_add_facet(&upper->stl, &facet);
}
}
// triangulate holes of lower mesh
if (lower != NULL) {
// compute shape of section
ExPolygons section;
this->make_expolygons_simple(lower_lines, §ion);
// triangulate section
Polygons triangles;
for (ExPolygons::const_iterator expolygon = section.begin(); expolygon != section.end(); ++expolygon)
expolygon->triangulate_p2t(&triangles);
// convert triangles to facets and append them to mesh
for (Polygons::const_iterator polygon = triangles.begin(); polygon != triangles.end(); ++polygon) {
stl_facet facet;
facet.normal.x = 0;
facet.normal.y = 0;
facet.normal.z = 1;
for (size_t i = 0; i <= 2; ++i) {
facet.vertex[i].x = unscale(polygon->points[i].x);
facet.vertex[i].y = unscale(polygon->points[i].y);
facet.vertex[i].z = z;
}
stl_add_facet(&lower->stl, &facet);
}
}
// Update the bounding box / sphere of the new meshes.
stl_get_size(&upper->stl);
stl_get_size(&lower->stl);
}
// Generate the vertex list for a cube solid of arbitrary size in X/Y/Z.
TriangleMesh make_cube(double x, double y, double z) {
Pointf3 pv[8] = {
Pointf3(x, y, 0), Pointf3(x, 0, 0), Pointf3(0, 0, 0),
Pointf3(0, y, 0), Pointf3(x, y, z), Pointf3(0, y, z),
Pointf3(0, 0, z), Pointf3(x, 0, z)
};
Point3 fv[12] = {
Point3(0, 1, 2), Point3(0, 2, 3), Point3(4, 5, 6),
Point3(4, 6, 7), Point3(0, 4, 7), Point3(0, 7, 1),
Point3(1, 7, 6), Point3(1, 6, 2), Point3(2, 6, 5),
Point3(2, 5, 3), Point3(4, 0, 3), Point3(4, 3, 5)
};
std::vector<Point3> facets(&fv[0], &fv[0]+12);
Pointf3s vertices(&pv[0], &pv[0]+8);
TriangleMesh mesh(vertices ,facets);
return mesh;
}
// Generate the mesh for a cylinder and return it, using
// the generated angle to calculate the top mesh triangles.
// Default is 360 sides, angle fa is in radians.
TriangleMesh make_cylinder(double r, double h, double fa) {
Pointf3s vertices;
std::vector<Point3> facets;
// 2 special vertices, top and bottom center, rest are relative to this
vertices.push_back(Pointf3(0.0, 0.0, 0.0));
vertices.push_back(Pointf3(0.0, 0.0, h));
// adjust via rounding to get an even multiple for any provided angle.
double angle = (2*PI / floor(2*PI / fa));
// for each line along the polygon approximating the top/bottom of the
// circle, generate four points and four facets (2 for the wall, 2 for the
// top and bottom.
// Special case: Last line shares 2 vertices with the first line.
unsigned id = vertices.size() - 1;
vertices.push_back(Pointf3(sin(0) * r , cos(0) * r, 0));
vertices.push_back(Pointf3(sin(0) * r , cos(0) * r, h));
for (double i = 0; i < 2*PI; i+=angle) {
Pointf3 b(0, r, 0);
Pointf3 t(0, r, h);
b.rotate(i, Pointf3(0,0,0));
t.rotate(i, Pointf3(0,0,h));
vertices.push_back(b);
vertices.push_back(t);
id = vertices.size() - 1;
facets.push_back(Point3( 0, id - 1, id - 3)); // top
facets.push_back(Point3(id, 1, id - 2)); // bottom
facets.push_back(Point3(id, id - 2, id - 3)); // upper-right of side
facets.push_back(Point3(id, id - 3, id - 1)); // bottom-left of side
}
// Connect the last set of vertices with the first.
facets.push_back(Point3( 2, 0, id - 1));
facets.push_back(Point3( 1, 3, id));
facets.push_back(Point3(id, 3, 2));
facets.push_back(Point3(id, 2, id - 1));
TriangleMesh mesh(vertices, facets);
return mesh;
}
// Generates mesh for a sphere centered about the origin, using the generated angle
// to determine the granularity.
// Default angle is 1 degree.
TriangleMesh make_sphere(double rho, double fa) {
Pointf3s vertices;
std::vector<Point3> facets;
// Algorithm:
// Add points one-by-one to the sphere grid and form facets using relative coordinates.
// Sphere is composed effectively of a mesh of stacked circles.
// adjust via rounding to get an even multiple for any provided angle.
double angle = (2*PI / floor(2*PI / fa));
// Ring to be scaled to generate the steps of the sphere
std::vector<double> ring;
for (double i = 0; i < 2*PI; i+=angle) {
ring.push_back(i);
}
const size_t steps = ring.size();
const double increment = (double)(1.0 / (double)steps);
// special case: first ring connects to 0,0,0
// insert and form facets.
vertices.push_back(Pointf3(0.0, 0.0, -rho));
size_t id = vertices.size();
for (size_t i = 0; i < ring.size(); i++) {
// Fixed scaling
const double z = -rho + increment*rho*2.0;
// radius of the circle for this step.
const double r = sqrt(abs(rho*rho - z*z));
Pointf3 b(0, r, z);
b.rotate(ring[i], Pointf3(0,0,z));
vertices.push_back(b);
if (i == 0) {
facets.push_back(Point3(1, 0, ring.size()));
} else {
facets.push_back(Point3(id, 0, id - 1));
}
id++;
}
// General case: insert and form facets for each step, joining it to the ring below it.
for (size_t s = 2; s < steps - 1; s++) {
const double z = -rho + increment*(double)s*2.0*rho;
const double r = sqrt(abs(rho*rho - z*z));
for (size_t i = 0; i < ring.size(); i++) {
Pointf3 b(0, r, z);
b.rotate(ring[i], Pointf3(0,0,z));
vertices.push_back(b);
if (i == 0) {
// wrap around
facets.push_back(Point3(id + ring.size() - 1 , id, id - 1));
facets.push_back(Point3(id, id - ring.size(), id - 1));
} else {
facets.push_back(Point3(id , id - ring.size(), (id - 1) - ring.size()));
facets.push_back(Point3(id, id - 1 - ring.size() , id - 1));
}
id++;
}
}
// special case: last ring connects to 0,0,rho*2.0
// only form facets.
vertices.push_back(Pointf3(0.0, 0.0, rho));
for (size_t i = 0; i < ring.size(); i++) {
if (i == 0) {
// third vertex is on the other side of the ring.
facets.push_back(Point3(id, id - ring.size(), id - 1));
} else {
facets.push_back(Point3(id, id - ring.size() + i, id - ring.size() + (i - 1)));
}
}
id++;
TriangleMesh mesh(vertices, facets);
return mesh;
}
}
|