Welcome to mirror list, hosted at ThFree Co, Russian Federation.

editmesh_tools.c « mesh « editors « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d7617a14ff34e70dd26a8ae625bd5ae8260db50a (plain)
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
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
/*
 * ***** BEGIN GPL LICENSE BLOCK *****
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * The Original Code is Copyright (C) 2004 by Blender Foundation.
 * All rights reserved.
 *
 * The Original Code is: all of this file.
 *
 * Contributor(s): Joseph Eagar
 *
 * ***** END GPL LICENSE BLOCK *****
 */

/** \file blender/editors/mesh/editmesh_tools.c
 *  \ingroup edmesh
 */

#include <stddef.h>

#include "MEM_guardedalloc.h"

#include "DNA_key_types.h"
#include "DNA_material_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_modifier_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"

#include "BLI_listbase.h"
#include "BLI_noise.h"
#include "BLI_math.h"
#include "BLI_rand.h"
#include "BLI_sort_utils.h"

#include "BKE_layer.h"
#include "BKE_material.h"
#include "BKE_context.h"
#include "BKE_deform.h"
#include "BKE_report.h"
#include "BKE_texture.h"
#include "BKE_main.h"
#include "BKE_editmesh.h"

#include "DEG_depsgraph.h"
#include "DEG_depsgraph_build.h"

#include "BLT_translation.h"

#include "RNA_define.h"
#include "RNA_access.h"
#include "RNA_enum_types.h"

#include "WM_api.h"
#include "WM_types.h"

#include "ED_mesh.h"
#include "ED_object.h"
#include "ED_screen.h"
#include "ED_transform.h"
#include "ED_transform_snap_object_context.h"
#include "ED_uvedit.h"
#include "ED_view3d.h"

#include "RE_render_ext.h"

#include "UI_interface.h"
#include "UI_resources.h"

#include "mesh_intern.h"  /* own include */

#include "bmesh_tools.h"

#define USE_FACE_CREATE_SEL_EXTEND

/* -------------------------------------------------------------------- */
/** \name Subdivide Operator
 * \{ */

static int edbm_subdivide_exec(bContext *C, wmOperator *op)
{
	const int cuts = RNA_int_get(op->ptr, "number_cuts");
	const float smooth = RNA_float_get(op->ptr, "smoothness");
	const float fractal = RNA_float_get(op->ptr, "fractal") / 2.5f;
	const float along_normal = RNA_float_get(op->ptr, "fractal_along_normal");

	if (RNA_boolean_get(op->ptr, "ngon") &&
	    RNA_enum_get(op->ptr, "quadcorner") == SUBD_CORNER_STRAIGHT_CUT)
	{
		RNA_enum_set(op->ptr, "quadcorner", SUBD_CORNER_INNERVERT);
	}
	const int quad_corner_type = RNA_enum_get(op->ptr, "quadcorner");
	const bool use_quad_tri = !RNA_boolean_get(op->ptr, "ngon");
	const int seed = RNA_int_get(op->ptr, "seed");

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (!(em->bm->totedgesel || em->bm->totfacesel)) {
			continue;
		}

		BM_mesh_esubdivide(
		        em->bm, BM_ELEM_SELECT,
		        smooth, SUBD_FALLOFF_LIN, false,
		        fractal, along_normal,
		        cuts,
		        SUBDIV_SELECT_ORIG, quad_corner_type,
		        use_quad_tri, true, false,
		        seed);

		EDBM_update_generic(em, true, true);
	}

	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

/* Note, these values must match delete_mesh() event values */
static const EnumPropertyItem prop_mesh_cornervert_types[] = {
	{SUBD_CORNER_INNERVERT,     "INNERVERT", 0,      "Inner Vert", ""},
	{SUBD_CORNER_PATH,          "PATH", 0,           "Path", ""},
	{SUBD_CORNER_STRAIGHT_CUT,  "STRAIGHT_CUT", 0,   "Straight Cut", ""},
	{SUBD_CORNER_FAN,           "FAN", 0,            "Fan", ""},
	{0, NULL, 0, NULL, NULL}
};

void MESH_OT_subdivide(wmOperatorType *ot)
{
	PropertyRNA *prop;

	/* identifiers */
	ot->name = "Subdivide";
	ot->description = "Subdivide selected edges";
	ot->idname = "MESH_OT_subdivide";

	/* api callbacks */
	ot->exec = edbm_subdivide_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* properties */
	prop = RNA_def_int(ot->srna, "number_cuts", 1, 1, 100, "Number of Cuts", "", 1, 10);
	/* avoid re-using last var because it can cause _very_ high poly meshes and annoy users (or worse crash) */
	RNA_def_property_flag(prop, PROP_SKIP_SAVE);

	RNA_def_float(ot->srna, "smoothness", 0.0f, 0.0f, 1e3f, "Smoothness", "Smoothness factor", 0.0f, 1.0f);

	WM_operatortype_props_advanced_begin(ot);

	RNA_def_boolean(ot->srna, "ngon", true, "Create N-Gons", "When disabled, newly created faces are limited to 3-4 sided faces");
	RNA_def_enum(ot->srna, "quadcorner", prop_mesh_cornervert_types, SUBD_CORNER_STRAIGHT_CUT,
	             "Quad Corner Type", "How to subdivide quad corners (anything other than Straight Cut will prevent ngons)");

	RNA_def_float(ot->srna, "fractal", 0.0f, 0.0f, 1e6f, "Fractal", "Fractal randomness factor", 0.0f, 1000.0f);
	RNA_def_float(ot->srna, "fractal_along_normal", 0.0f, 0.0f, 1.0f,
	              "Along Normal", "Apply fractal displacement along normal only", 0.0f, 1.0f);
	RNA_def_int(ot->srna, "seed", 0, 0, INT_MAX, "Random Seed", "Seed for the random number generator", 0, 255);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Edge Ring Subdivide Operator
 *
 * Bridge code shares props.
 *
 * \{ */

struct EdgeRingOpSubdProps {
	int interp_mode;
	int cuts;
	float smooth;

	int profile_shape;
	float profile_shape_factor;
};


static void mesh_operator_edgering_props(wmOperatorType *ot, const int cuts_min, const int cuts_default)
{
	/* Note, these values must match delete_mesh() event values */
	static const EnumPropertyItem prop_subd_edgering_types[] = {
		{SUBD_RING_INTERP_LINEAR, "LINEAR", 0, "Linear", ""},
		{SUBD_RING_INTERP_PATH, "PATH", 0, "Blend Path", ""},
		{SUBD_RING_INTERP_SURF, "SURFACE", 0, "Blend Surface", ""},
		{0, NULL, 0, NULL, NULL}
	};

	PropertyRNA *prop;

	prop = RNA_def_int(ot->srna, "number_cuts", cuts_default, 0, 1000, "Number of Cuts", "", cuts_min, 64);
	RNA_def_property_flag(prop, PROP_SKIP_SAVE);

	RNA_def_enum(ot->srna, "interpolation", prop_subd_edgering_types, SUBD_RING_INTERP_PATH,
	             "Interpolation", "Interpolation method");

	RNA_def_float(ot->srna, "smoothness", 1.0f, 0.0f, 1e3f,
	              "Smoothness", "Smoothness factor", 0.0f, 2.0f);

	/* profile-shape */
	RNA_def_float(ot->srna, "profile_shape_factor", 0.0f, -1e3f, 1e3f,
	              "Profile Factor", "How much intermediary new edges are shrunk/expanded", -2.0f, 2.0f);

	prop = RNA_def_property(ot->srna, "profile_shape", PROP_ENUM, PROP_NONE);
	RNA_def_property_enum_items(prop, rna_enum_proportional_falloff_curve_only_items);
	RNA_def_property_enum_default(prop, PROP_SMOOTH);
	RNA_def_property_ui_text(prop, "Profile Shape", "Shape of the profile");
	RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_CURVE); /* Abusing id_curve :/ */
}

static void mesh_operator_edgering_props_get(wmOperator *op, struct EdgeRingOpSubdProps *op_props)
{
	op_props->interp_mode = RNA_enum_get(op->ptr, "interpolation");
	op_props->cuts = RNA_int_get(op->ptr, "number_cuts");
	op_props->smooth = RNA_float_get(op->ptr, "smoothness");

	op_props->profile_shape = RNA_enum_get(op->ptr, "profile_shape");
	op_props->profile_shape_factor = RNA_float_get(op->ptr, "profile_shape_factor");
}

static int edbm_subdivide_edge_ring_exec(bContext *C, wmOperator *op)
{

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object * *objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	struct EdgeRingOpSubdProps op_props;

	mesh_operator_edgering_props_get(op, &op_props);

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object * obedit = objects[ob_index];
		BMEditMesh * em = BKE_editmesh_from_object(obedit);

		if (em->bm->totedgesel == 0) {
			continue;
		}

		if (!EDBM_op_callf(
		        em, op,
		        "subdivide_edgering edges=%he interp_mode=%i cuts=%i smooth=%f "
		        "profile_shape=%i profile_shape_factor=%f",
		        BM_ELEM_SELECT, op_props.interp_mode, op_props.cuts, op_props.smooth,
		        op_props.profile_shape, op_props.profile_shape_factor))
		{
			continue;
		}

		EDBM_update_generic(em, true, true);
	}

	MEM_freeN(objects);
	return OPERATOR_FINISHED;
}

void MESH_OT_subdivide_edgering(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Subdivide Edge-Ring";
	ot->description = "";
	ot->idname = "MESH_OT_subdivide_edgering";

	/* api callbacks */
	ot->exec = edbm_subdivide_edge_ring_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* properties */
	mesh_operator_edgering_props(ot, 1, 10);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Un-Subdivide Operator
 * \{ */

static int edbm_unsubdivide_exec(bContext *C, wmOperator *op)
{
	const int iterations = RNA_int_get(op->ptr, "iterations");
	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if ((em->bm->totvertsel == 0) &&
		    (em->bm->totedgesel == 0) &&
		    (em->bm->totfacesel == 0))
		{
			continue;
		}

		BMOperator bmop;
		EDBM_op_init(em, &bmop, op,
	               "unsubdivide verts=%hv iterations=%i", BM_ELEM_SELECT, iterations);

		BMO_op_exec(em->bm, &bmop);

		if (!EDBM_op_finish(em, &bmop, op, true)) {
			continue;
		}

		if ((em->selectmode & SCE_SELECT_VERTEX) == 0) {
			EDBM_selectmode_flush_ex(em, SCE_SELECT_VERTEX);  /* need to flush vert->face first */
		}
		EDBM_selectmode_flush(em);

		EDBM_update_generic(em, true, true);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_unsubdivide(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Un-Subdivide";
	ot->description = "UnSubdivide selected edges & faces";
	ot->idname = "MESH_OT_unsubdivide";

	/* api callbacks */
	ot->exec = edbm_unsubdivide_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* props */
	RNA_def_int(ot->srna, "iterations", 2, 1, 1000, "Iterations", "Number of times to unsubdivide", 1, 100);
}

void EMBM_project_snap_verts(bContext *C, ARegion *ar, BMEditMesh *em)
{
	Main *bmain = CTX_data_main(C);
	Object *obedit = em->ob;
	BMIter iter;
	BMVert *eve;

	ED_view3d_init_mats_rv3d(obedit, ar->regiondata);

	struct SnapObjectContext *snap_context = ED_transform_snap_object_context_create_view3d(
	        bmain, CTX_data_scene(C), CTX_data_depsgraph(C), 0,
	        ar, CTX_wm_view3d(C));

	BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
		if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
			float mval[2], co_proj[3];
			if (ED_view3d_project_float_object(ar, eve->co, mval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
				if (ED_transform_snap_object_project_view3d(
				        snap_context,
				        SCE_SNAP_MODE_FACE,
				        &(const struct SnapObjectParams){
				            .snap_select = SNAP_NOT_ACTIVE,
				            .use_object_edit_cage = false,
				            .use_occlusion_test = true,
				        },
				        mval, NULL,
				        co_proj, NULL))
				{
					mul_v3_m4v3(eve->co, obedit->imat, co_proj);
				}
			}
		}
	}

	ED_transform_snap_object_context_destroy(snap_context);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Delete Operator
 * \{ */

/* Note, these values must match delete_mesh() event values */
enum {
	MESH_DELETE_VERT      = 0,
	MESH_DELETE_EDGE      = 1,
	MESH_DELETE_FACE      = 2,
	MESH_DELETE_EDGE_FACE = 3,
	MESH_DELETE_ONLY_FACE = 4,
};

static void edbm_report_delete_info(ReportList *reports, const int totelem_old[3], const int totelem_new[3])
{
	BKE_reportf(reports, RPT_INFO,
	            "Removed: %d vertices, %d edges, %d faces",
	            totelem_old[0] - totelem_new[0], totelem_old[1] - totelem_new[1], totelem_old[2] - totelem_new[2]);
}

static int edbm_delete_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);

	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	bool changed_multi = false;

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		const int type = RNA_enum_get(op->ptr, "type");

		switch (type) {
			case MESH_DELETE_VERT: /* Erase Vertices */
				if (!(em->bm->totvertsel &&
				      EDBM_op_callf(em, op, "delete geom=%hv context=%i", BM_ELEM_SELECT, DEL_VERTS)))
				{
					continue;
				}
				break;
			case MESH_DELETE_EDGE: /* Erase Edges */
				if (!(em->bm->totedgesel &&
				      EDBM_op_callf(em, op, "delete geom=%he context=%i", BM_ELEM_SELECT, DEL_EDGES)))
				{
					continue;
				}
				break;
			case MESH_DELETE_FACE: /* Erase Faces */
				if (!(em->bm->totfacesel &&
				      EDBM_op_callf(em, op, "delete geom=%hf context=%i", BM_ELEM_SELECT, DEL_FACES)))
				{
					continue;
				}
				break;
			case MESH_DELETE_EDGE_FACE:
				/* Edges and Faces */
				if (!((em->bm->totedgesel || em->bm->totfacesel) &&
				      EDBM_op_callf(em, op, "delete geom=%hef context=%i", BM_ELEM_SELECT, DEL_EDGESFACES)))
				{
					continue;
				}
				break;
			case MESH_DELETE_ONLY_FACE:
				/* Only faces. */
				if (!(em->bm->totfacesel &&
				      EDBM_op_callf(em, op, "delete geom=%hf context=%i", BM_ELEM_SELECT, DEL_ONLYFACES)))
				{
					continue;
				}
				break;
			default:
				BLI_assert(0);
				break;
		}

		changed_multi = true;

		EDBM_flag_disable_all(em, BM_ELEM_SELECT);

		EDBM_update_generic(em, true, true);
	}

	MEM_freeN(objects);

	return changed_multi ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
}

void MESH_OT_delete(wmOperatorType *ot)
{
	static const EnumPropertyItem prop_mesh_delete_types[] = {
		{MESH_DELETE_VERT,      "VERT",      0, "Vertices", ""},
		{MESH_DELETE_EDGE,      "EDGE",      0, "Edges", ""},
		{MESH_DELETE_FACE,      "FACE",      0, "Faces", ""},
		{MESH_DELETE_EDGE_FACE, "EDGE_FACE", 0, "Only Edges & Faces", ""},
		{MESH_DELETE_ONLY_FACE, "ONLY_FACE", 0, "Only Faces", ""},
		{0, NULL, 0, NULL, NULL}
	};

	/* identifiers */
	ot->name = "Delete";
	ot->description = "Delete selected vertices, edges or faces";
	ot->idname = "MESH_OT_delete";

	/* api callbacks */
	ot->invoke = WM_menu_invoke;
	ot->exec = edbm_delete_exec;

	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* props */
	ot->prop = RNA_def_enum(ot->srna, "type", prop_mesh_delete_types, MESH_DELETE_VERT,
	                        "Type", "Method used for deleting mesh data");
	RNA_def_property_flag(ot->prop, PROP_HIDDEN | PROP_SKIP_SAVE);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Delete Loose Operator
 * \{ */

static bool bm_face_is_loose(BMFace *f)
{
	BMLoop *l_iter, *l_first;

	l_iter = l_first = BM_FACE_FIRST_LOOP(f);
	do {
		if (!BM_edge_is_boundary(l_iter->e)) {
			return false;
		}
	} while ((l_iter = l_iter->next) != l_first);

	return true;
}

static int edbm_delete_loose_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);
	int totelem_old_sel[3];
	int totelem_old[3];

	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	EDBM_mesh_stats_multi(objects, objects_len, totelem_old, totelem_old_sel);

	const bool use_verts = (RNA_boolean_get(op->ptr, "use_verts") && totelem_old_sel[0]);
	const bool use_edges = (RNA_boolean_get(op->ptr, "use_edges") && totelem_old_sel[1]);
	const bool use_faces = (RNA_boolean_get(op->ptr, "use_faces") && totelem_old_sel[2]);

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];

		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		BMesh *bm = em->bm;
		BMIter iter;

		BM_mesh_elem_hflag_disable_all(bm, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_TAG, false);

		if (use_faces) {
			BMFace *f;

			BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
				if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
					BM_elem_flag_set(f, BM_ELEM_TAG, bm_face_is_loose(f));
				}
			}

			BM_mesh_delete_hflag_context(bm, BM_ELEM_TAG, DEL_FACES);
		}

		if (use_edges) {
			BMEdge *e;

			BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
				if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
					BM_elem_flag_set(e, BM_ELEM_TAG, BM_edge_is_wire(e));
				}
			}

			BM_mesh_delete_hflag_context(bm, BM_ELEM_TAG, DEL_EDGES);
		}

		if (use_verts) {
			BMVert *v;

			BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
				if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
					BM_elem_flag_set(v, BM_ELEM_TAG, (v->e == NULL));
				}
			}

			BM_mesh_delete_hflag_context(bm, BM_ELEM_TAG, DEL_VERTS);
		}

		EDBM_flag_disable_all(em, BM_ELEM_SELECT);

		EDBM_update_generic(em, true, true);
	}

	int totelem_new[3];
	EDBM_mesh_stats_multi(objects, objects_len, totelem_new, NULL);

	edbm_report_delete_info(op->reports, totelem_old, totelem_new);

	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}


void MESH_OT_delete_loose(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Delete Loose";
	ot->description = "Delete loose vertices, edges or faces";
	ot->idname = "MESH_OT_delete_loose";

	/* api callbacks */
	ot->exec = edbm_delete_loose_exec;

	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* props */
	RNA_def_boolean(ot->srna, "use_verts", true, "Vertices", "Remove loose vertices");
	RNA_def_boolean(ot->srna, "use_edges", true, "Edges", "Remove loose edges");
	RNA_def_boolean(ot->srna, "use_faces", false, "Faces", "Remove loose faces");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Collapse Edge Operator
 * \{ */

static int edbm_collapse_edge_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totedgesel == 0) {
			continue;
		}

		if (!EDBM_op_callf(em, op, "collapse edges=%he uvs=%b", BM_ELEM_SELECT, true)) {
			continue;
		}

		EDBM_update_generic(em, true, true);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_edge_collapse(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Edge Collapse";
	ot->description = "Collapse selected edges";
	ot->idname = "MESH_OT_edge_collapse";

	/* api callbacks */
	ot->exec = edbm_collapse_edge_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Create Edge/Face Operator
 * \{ */

static bool edbm_add_edge_face__smooth_get(BMesh *bm)
{
	BMEdge *e;
	BMIter iter;

	unsigned int vote_on_smooth[2] = {0, 0};

	BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
		if (BM_elem_flag_test(e, BM_ELEM_SELECT) && e->l) {
			vote_on_smooth[BM_elem_flag_test_bool(e->l->f, BM_ELEM_SMOOTH)]++;
		}
	}

	return (vote_on_smooth[0] < vote_on_smooth[1]);
}

#ifdef USE_FACE_CREATE_SEL_EXTEND
/**
 * Function used to get a fixed number of edges linked to a vertex that passes a test function.
 * This is used so we can request all boundary edges connected to a vertex for eg.
 */
static int edbm_add_edge_face_exec__vert_edge_lookup(
        BMVert *v, BMEdge *e_used, BMEdge **e_arr, const int e_arr_len,
        bool (* func)(const BMEdge *))
{
	BMIter iter;
	BMEdge *e_iter;
	int i = 0;
	BM_ITER_ELEM (e_iter, &iter, v, BM_EDGES_OF_VERT) {
		if (BM_elem_flag_test(e_iter, BM_ELEM_HIDDEN) == false) {
			if ((e_used == NULL) || (e_used != e_iter)) {
				if (func(e_iter)) {
					e_arr[i++] = e_iter;
					if (i >= e_arr_len) {
						break;
					}
				}
			}
		}
	}
	return i;
}

static BMElem *edbm_add_edge_face_exec__tricky_extend_sel(BMesh *bm)
{
	BMIter iter;
	bool found = false;

	if (bm->totvertsel == 1 && bm->totedgesel == 0 && bm->totfacesel == 0) {
		/* first look for 2 boundary edges */
		BMVert *v;

		BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
			if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
				found = true;
				break;
			}
		}

		if (found) {
			BMEdge *ed_pair[3];
			if (
			    ((edbm_add_edge_face_exec__vert_edge_lookup(v, NULL, ed_pair, 3, BM_edge_is_wire) == 2) &&
			     (BM_edge_share_face_check(ed_pair[0], ed_pair[1]) == false)) ||

			    ((edbm_add_edge_face_exec__vert_edge_lookup(v, NULL, ed_pair, 3, BM_edge_is_boundary) == 2) &&
			     (BM_edge_share_face_check(ed_pair[0], ed_pair[1]) == false))
			    )
			{
				BMEdge *e_other = BM_edge_exists(
				        BM_edge_other_vert(ed_pair[0], v),
				        BM_edge_other_vert(ed_pair[1], v));
				BM_edge_select_set(bm, ed_pair[0], true);
				BM_edge_select_set(bm, ed_pair[1], true);
				if (e_other) {
					BM_edge_select_set(bm, e_other, true);
				}
				return (BMElem *)v;
			}
		}
	}
	else if (bm->totvertsel == 2 && bm->totedgesel == 1 && bm->totfacesel == 0) {
		/* first look for 2 boundary edges */
		BMEdge *e;

		BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
			if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
				found = true;
				break;
			}
		}
		if (found) {
			BMEdge *ed_pair_v1[2];
			BMEdge *ed_pair_v2[2];
			if (
			    ((edbm_add_edge_face_exec__vert_edge_lookup(e->v1, e, ed_pair_v1, 2, BM_edge_is_wire) == 1) &&
			     (edbm_add_edge_face_exec__vert_edge_lookup(e->v2, e, ed_pair_v2, 2, BM_edge_is_wire) == 1) &&
			     (BM_edge_share_face_check(e, ed_pair_v1[0]) == false) &&
			     (BM_edge_share_face_check(e, ed_pair_v2[0]) == false)) ||

#if 1  /* better support mixed cases [#37203] */
			    ((edbm_add_edge_face_exec__vert_edge_lookup(e->v1, e, ed_pair_v1, 2, BM_edge_is_wire)     == 1) &&
			     (edbm_add_edge_face_exec__vert_edge_lookup(e->v2, e, ed_pair_v2, 2, BM_edge_is_boundary) == 1) &&
			     (BM_edge_share_face_check(e, ed_pair_v1[0]) == false) &&
			     (BM_edge_share_face_check(e, ed_pair_v2[0]) == false)) ||

			    ((edbm_add_edge_face_exec__vert_edge_lookup(e->v1, e, ed_pair_v1, 2, BM_edge_is_boundary) == 1) &&
			     (edbm_add_edge_face_exec__vert_edge_lookup(e->v2, e, ed_pair_v2, 2, BM_edge_is_wire)     == 1) &&
			     (BM_edge_share_face_check(e, ed_pair_v1[0]) == false) &&
			     (BM_edge_share_face_check(e, ed_pair_v2[0]) == false)) ||
#endif

			    ((edbm_add_edge_face_exec__vert_edge_lookup(e->v1, e, ed_pair_v1, 2, BM_edge_is_boundary) == 1) &&
			     (edbm_add_edge_face_exec__vert_edge_lookup(e->v2, e, ed_pair_v2, 2, BM_edge_is_boundary) == 1) &&
			     (BM_edge_share_face_check(e, ed_pair_v1[0]) == false) &&
			     (BM_edge_share_face_check(e, ed_pair_v2[0]) == false))
			    )
			{
				BMVert *v1_other = BM_edge_other_vert(ed_pair_v1[0], e->v1);
				BMVert *v2_other = BM_edge_other_vert(ed_pair_v2[0], e->v2);
				BMEdge *e_other = (v1_other != v2_other) ? BM_edge_exists(v1_other, v2_other) : NULL;
				BM_edge_select_set(bm, ed_pair_v1[0], true);
				BM_edge_select_set(bm, ed_pair_v2[0], true);
				if (e_other) {
					BM_edge_select_set(bm, e_other, true);
				}
				return (BMElem *)e;
			}
		}
	}

	return NULL;
}
static void edbm_add_edge_face_exec__tricky_finalize_sel(BMesh *bm, BMElem *ele_desel, BMFace *f)
{
	/* now we need to find the edge that isnt connected to this element */
	BM_select_history_clear(bm);

	/* Notes on hidden geometry:
	 * - un-hide the face since its possible hidden was copied when copying surrounding face attributes.
	 * - un-hide before adding to select history
	 *   since we may extend into an existing, hidden vert/edge.
	 */

	BM_elem_flag_disable(f, BM_ELEM_HIDDEN);
	BM_face_select_set(bm, f, false);

	if (ele_desel->head.htype == BM_VERT) {
		BMLoop *l = BM_face_vert_share_loop(f, (BMVert *)ele_desel);
		BLI_assert(f->len == 3);
		BM_vert_select_set(bm, (BMVert *)ele_desel, false);
		BM_edge_select_set(bm, l->next->e, true);
		BM_select_history_store(bm, l->next->e);
	}
	else {
		BMLoop *l = BM_face_edge_share_loop(f, (BMEdge *)ele_desel);
		BLI_assert(f->len == 4 || f->len == 3);

		BM_edge_select_set(bm, (BMEdge *)ele_desel, false);
		if (f->len == 4) {
			BMEdge *e_active = l->next->next->e;
			BM_elem_flag_disable(e_active, BM_ELEM_HIDDEN);
			BM_edge_select_set(bm, e_active, true);
			BM_select_history_store(bm, e_active);
		}
		else {
			BMVert *v_active = l->next->next->v;
			BM_elem_flag_disable(v_active, BM_ELEM_HIDDEN);
			BM_vert_select_set(bm, v_active, true);
			BM_select_history_store(bm, v_active);
		}
	}
}
#endif  /* USE_FACE_CREATE_SEL_EXTEND */

static int edbm_add_edge_face_exec(bContext *C, wmOperator *op)
{
	/* when this is used to dissolve we could avoid this, but checking isnt too slow */

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if ((em->bm->totvertsel == 0) &&
		    (em->bm->totedgesel == 0) &&
		    (em->bm->totvertsel == 0))
		{
			continue;
		}

		bool use_smooth = edbm_add_edge_face__smooth_get(em->bm);
		int totedge_orig = em->bm->totedge;
		int totface_orig = em->bm->totface;

		BMOperator bmop;
#ifdef USE_FACE_CREATE_SEL_EXTEND
		BMElem *ele_desel;
		BMFace *ele_desel_face;

		/* be extra clever, figure out if a partial selection should be extended so we can create geometry
		 * with single vert or single edge selection */
		ele_desel = edbm_add_edge_face_exec__tricky_extend_sel(em->bm);
#endif
		if (!EDBM_op_init(
		            em, &bmop, op,
		            "contextual_create geom=%hfev mat_nr=%i use_smooth=%b",
		            BM_ELEM_SELECT, em->mat_nr, use_smooth))
		{
			continue;
		}

		BMO_op_exec(em->bm, &bmop);

		/* cancel if nothing was done */
		if ((totedge_orig == em->bm->totedge) &&
		    (totface_orig == em->bm->totface))
		{
			EDBM_op_finish(em, &bmop, op, true);
			continue;
		}
#ifdef USE_FACE_CREATE_SEL_EXTEND
		/* normally we would want to leave the new geometry selected,
		 * but being able to press F many times to add geometry is too useful! */
		if (ele_desel &&
		    (BMO_slot_buffer_count(bmop.slots_out, "faces.out") == 1) &&
		    (ele_desel_face = BMO_slot_buffer_get_first(bmop.slots_out, "faces.out")))
		{
			edbm_add_edge_face_exec__tricky_finalize_sel(em->bm, ele_desel, ele_desel_face);
		}
		else
#endif
		{
			/* Newly created faces may include existing hidden edges,
			 * copying face data from surrounding, may have copied hidden face flag too.
			 *
			 * Important that faces use flushing since 'edges.out' wont include hidden edges that already existed.
			 */
			BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_HIDDEN, true);
			BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_HIDDEN, false);

			BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true);
			BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true);
		}

		if (!EDBM_op_finish(em, &bmop, op, true)) {
			continue;
		}

		EDBM_update_generic(em, true, true);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_edge_face_add(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Make Edge/Face";
	ot->description = "Add an edge or face to selected";
	ot->idname = "MESH_OT_edge_face_add";

	/* api callbacks */
	ot->exec = edbm_add_edge_face_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Mark Edge (Seam) Operator
 * \{ */

static int edbm_mark_seam_exec(bContext *C, wmOperator *op)
{
	Scene *scene = CTX_data_scene(C);
	ViewLayer *view_layer = CTX_data_view_layer(C);
	BMEdge *eed;
	BMIter iter;
	const bool clear = RNA_boolean_get(op->ptr, "clear");

	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		BMesh *bm = em->bm;

		if (bm->totedgesel == 0) {
			continue;
		}

		Mesh *me = ((Mesh *)obedit->data);

		/* auto-enable seams drawing */
		if (clear == 0) {
			me->drawflag |= ME_DRAWSEAMS;
		}

		if (clear) {
			BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
				if (!BM_elem_flag_test(eed, BM_ELEM_SELECT) || BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
					continue;
				}

				BM_elem_flag_disable(eed, BM_ELEM_SEAM);
			}
		}
		else {
			BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
				if (!BM_elem_flag_test(eed, BM_ELEM_SELECT) || BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
					continue;
				}
				BM_elem_flag_enable(eed, BM_ELEM_SEAM);
			}
		}

		ED_uvedit_live_unwrap(scene, obedit);
		EDBM_update_generic(em, true, false);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_mark_seam(wmOperatorType *ot)
{
	PropertyRNA *prop;

	/* identifiers */
	ot->name = "Mark Seam";
	ot->idname = "MESH_OT_mark_seam";
	ot->description = "(Un)mark selected edges as a seam";

	/* api callbacks */
	ot->exec = edbm_mark_seam_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	prop = RNA_def_boolean(ot->srna, "clear", 0, "Clear", "");
	RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);

	WM_operatortype_props_advanced_begin(ot);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Mark Edge (Sharp) Operator
 * \{ */

static int edbm_mark_sharp_exec(bContext *C, wmOperator *op)
{
	BMEdge *eed;
	BMIter iter;
	const bool clear = RNA_boolean_get(op->ptr, "clear");
	const bool use_verts = RNA_boolean_get(op->ptr, "use_verts");
	ViewLayer *view_layer = CTX_data_view_layer(C);

	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		BMesh *bm = em->bm;
		Mesh *me = ((Mesh *)obedit->data);

		if (bm->totedgesel == 0) {
			continue;
		}

		/* auto-enable sharp edge drawing */
		if (clear == 0) {
			me->drawflag |= ME_DRAWSHARP;
		}

		BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
			if (use_verts) {
				if (!(BM_elem_flag_test(eed->v1, BM_ELEM_SELECT) || BM_elem_flag_test(eed->v2, BM_ELEM_SELECT))) {
					continue;
				}
			}
			else if (!BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
				continue;
			}

			BM_elem_flag_set(eed, BM_ELEM_SMOOTH, clear);
		}

		EDBM_update_generic(em, true, false);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_mark_sharp(wmOperatorType *ot)
{
	PropertyRNA *prop;

	/* identifiers */
	ot->name = "Mark Sharp";
	ot->idname = "MESH_OT_mark_sharp";
	ot->description = "(Un)mark selected edges as sharp";

	/* api callbacks */
	ot->exec = edbm_mark_sharp_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	prop = RNA_def_boolean(ot->srna, "clear", false, "Clear", "");
	RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
	prop = RNA_def_boolean(ot->srna, "use_verts", false, "Vertices",
	                       "Consider vertices instead of edges to select which edges to (un)tag as sharp");
	RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}

static bool edbm_connect_vert_pair(BMEditMesh *em, wmOperator *op)
{
	BMesh *bm = em->bm;
	BMOperator bmop;
	const int verts_len = bm->totvertsel;
	bool is_pair = (verts_len == 2);
	int len = 0;
	bool check_degenerate = true;

	BMVert **verts;
	bool checks_succeded = true;

	/* sanity check */
	if (!is_pair) {
		return false;
	}

	verts = MEM_mallocN(sizeof(*verts) * verts_len, __func__);
	{
		BMIter iter;
		BMVert *v;
		int i = 0;

		BM_ITER_MESH(v, &iter, bm, BM_VERTS_OF_MESH) {
			if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
				verts[i++] = v;
			}
		}

		if (BM_vert_pair_share_face_check_cb(
		            verts[0], verts[1],
		            BM_elem_cb_check_hflag_disabled_simple(BMFace *, BM_ELEM_HIDDEN)))
		{
			check_degenerate = false;
			is_pair = false;
		}
	}

	if (is_pair) {
		if (!EDBM_op_init(
		            em, &bmop, op,
		            "connect_vert_pair verts=%eb verts_exclude=%hv faces_exclude=%hf",
		            verts, verts_len, BM_ELEM_HIDDEN, BM_ELEM_HIDDEN))
		{
			checks_succeded = false;
		}
	}
	else {
		if (!EDBM_op_init(
		            em, &bmop, op,
		            "connect_verts verts=%eb faces_exclude=%hf check_degenerate=%b",
		            verts, verts_len, BM_ELEM_HIDDEN, check_degenerate))
		{
			checks_succeded = false;
		}
	}
	if (checks_succeded) {
		BMO_op_exec(bm, &bmop);
		len = BMO_slot_get(bmop.slots_out, "edges.out")->len;

		if (len && is_pair) {
			/* new verts have been added, we have to select the edges, not just flush */
			BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true);
		}

		if (!EDBM_op_finish(em, &bmop, op, true)) {
			len = 0;
		}
		else {
			EDBM_selectmode_flush(em);  /* so newly created edges get the selection state from the vertex */

			EDBM_update_generic(em, true, true);
		}
	}
	MEM_freeN(verts);

	return len;
}

static int edbm_vert_connect_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	uint failed_objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (!edbm_connect_vert_pair(em, op)) {
			failed_objects_len++;
		}
	}
	MEM_freeN(objects);
	return failed_objects_len == objects_len ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
}

void MESH_OT_vert_connect(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Vertex Connect";
	ot->idname = "MESH_OT_vert_connect";
	ot->description = "Connect selected vertices of faces, splitting the face";

	/* api callbacks */
	ot->exec = edbm_vert_connect_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Split Concave Faces Operator
 * \{ */

/**
 * check that endpoints are verts and only have a single selected edge connected.
 */
static bool bm_vert_is_select_history_open(BMesh *bm)
{
	BMEditSelection *ele_a = bm->selected.first;
	BMEditSelection *ele_b = bm->selected.last;
	if ((ele_a->htype == BM_VERT) &&
	    (ele_b->htype == BM_VERT))
	{
		if ((BM_iter_elem_count_flag(BM_EDGES_OF_VERT, (BMVert *)ele_a->ele, BM_ELEM_SELECT, true) == 1) &&
		    (BM_iter_elem_count_flag(BM_EDGES_OF_VERT, (BMVert *)ele_b->ele, BM_ELEM_SELECT, true) == 1))
		{
			return true;
		}
	}

	return false;
}

static bool bm_vert_connect_pair(BMesh *bm, BMVert *v_a, BMVert *v_b)
{
	BMOperator bmop;
	BMVert **verts;
	const int totedge_orig = bm->totedge;

	BMO_op_init(bm, &bmop, BMO_FLAG_DEFAULTS, "connect_vert_pair");

	verts = BMO_slot_buffer_alloc(&bmop, bmop.slots_in, "verts", 2);
	verts[0] = v_a;
	verts[1] = v_b;

	BM_vert_normal_update(verts[0]);
	BM_vert_normal_update(verts[1]);

	BMO_op_exec(bm, &bmop);
	BMO_slot_buffer_hflag_enable(bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true);
	BMO_op_finish(bm, &bmop);
	return (bm->totedge != totedge_orig);
}

static bool bm_vert_connect_select_history(BMesh *bm)
{
	/* Logic is as follows:
	 *
	 * - If there are any isolated/wire verts - connect as edges.
	 * - Otherwise connect faces.
	 * - If all edges have been created already, closed the loop.
	 */
	if (BLI_listbase_count_at_most(&bm->selected, 2) == 2 && (bm->totvertsel > 2)) {
		BMEditSelection *ese;
		int tot = 0;
		bool changed = false;
		bool has_wire = false;
		// bool all_verts;

		/* ensure all verts have history */
		for (ese = bm->selected.first; ese; ese = ese->next, tot++) {
			BMVert *v;
			if (ese->htype != BM_VERT) {
				break;
			}
			v = (BMVert *)ese->ele;
			if ((has_wire == false) && ((v->e == NULL) || BM_vert_is_wire(v))) {
				has_wire = true;
			}
		}
		// all_verts = (ese == NULL);

		if (has_wire == false) {
			/* all verts have faces , connect verts via faces! */
			if (tot == bm->totvertsel) {
				BMEditSelection *ese_last;
				ese_last = bm->selected.first;
				ese = ese_last->next;

				do {

					if (BM_edge_exists((BMVert *)ese_last->ele, (BMVert *)ese->ele)) {
						/* pass, edge exists (and will be selected) */
					}
					else {
						changed |= bm_vert_connect_pair(bm, (BMVert *)ese_last->ele, (BMVert *)ese->ele);
					}
				} while ((void)
				         (ese_last = ese),
				         (ese = ese->next));

				if (changed) {
					return true;
				}
			}

			if (changed == false) {
				/* existing loops: close the selection */
				if (bm_vert_is_select_history_open(bm)) {
					changed |= bm_vert_connect_pair(
					        bm,
					        (BMVert *)((BMEditSelection *)bm->selected.first)->ele,
					        (BMVert *)((BMEditSelection *)bm->selected.last)->ele);

					if (changed) {
						return true;
					}
				}
			}
		}

		else {
			/* no faces, simply connect the verts by edges */
			BMEditSelection *ese_prev;
			ese_prev = bm->selected.first;
			ese = ese_prev->next;


			do {
				if (BM_edge_exists((BMVert *)ese_prev->ele, (BMVert *)ese->ele)) {
					/* pass, edge exists (and will be selected) */
				}
				else {
					BMEdge *e;
					e = BM_edge_create(bm, (BMVert *)ese_prev->ele, (BMVert *)ese->ele, NULL, 0);
					BM_edge_select_set(bm, e, true);
					changed = true;
				}
			} while ((void)
			         (ese_prev = ese),
			         (ese = ese->next));

			if (changed == false) {
				/* existing loops: close the selection */
				if (bm_vert_is_select_history_open(bm)) {
					BMEdge *e;
					ese_prev = bm->selected.first;
					ese = bm->selected.last;
					e = BM_edge_create(bm, (BMVert *)ese_prev->ele, (BMVert *)ese->ele, NULL, 0);
					BM_edge_select_set(bm, e, true);
				}
			}

			return true;
		}
	}

	return false;
}

/**
 * Convert an edge selection to a temp vertex selection
 * (which must be cleared after use as a path to connect).
 */
static bool bm_vert_connect_select_history_edge_to_vert_path(BMesh *bm, ListBase *r_selected)
{
	ListBase selected_orig = {NULL, NULL};
	BMEditSelection *ese;
	int edges_len = 0;
	bool side = false;

	/* first check all edges are OK */
	for (ese = bm->selected.first; ese; ese = ese->next) {
		if (ese->htype == BM_EDGE) {
			edges_len += 1;
		}
		else {
			return false;
		}
	}
	/* if this is a mixed selection, bail out! */
	if (bm->totedgesel != edges_len) {
		return false;
	}

	SWAP(ListBase, bm->selected, selected_orig);

	/* convert edge selection into 2 ordered loops (where the first edge ends up in the middle) */
	for (ese = selected_orig.first; ese; ese = ese->next) {
		BMEdge *e_curr = (BMEdge *)ese->ele;
		BMEdge *e_prev = ese->prev ? (BMEdge *)ese->prev->ele : NULL;
		BMLoop *l_curr;
		BMLoop *l_prev;
		BMVert *v;

		if (e_prev) {
			BMFace *f = BM_edge_pair_share_face_by_len(e_curr, e_prev, &l_curr, &l_prev, true);
			if (f) {
				if ((e_curr->v1 != l_curr->v) == (e_prev->v1 != l_prev->v)) {
					side = !side;
				}
			}
			else if (is_quad_flip_v3(e_curr->v1->co, e_curr->v2->co, e_prev->v2->co, e_prev->v1->co)) {
				side = !side;
			}
		}

		v = (&e_curr->v1)[side];
		if (!bm->selected.last || (BMVert *)((BMEditSelection *)bm->selected.last)->ele != v) {
			BM_select_history_store_notest(bm, v);
		}

		v = (&e_curr->v1)[!side];
		if (!bm->selected.first || (BMVert *)((BMEditSelection *)bm->selected.first)->ele != v) {
			BM_select_history_store_head_notest(bm, v);
		}

		e_prev = e_curr;
	}

	*r_selected = bm->selected;
	bm->selected = selected_orig;

	return true;
}

static int edbm_vert_connect_path_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	uint failed_selection_order_len = 0;
	uint failed_connect_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		BMesh *bm = em->bm;
		const bool is_pair = (em->bm->totvertsel == 2);
		ListBase selected_orig = {NULL, NULL};

		if (bm->totvertsel == 0) {
			continue;
		}

		/* when there is only 2 vertices, we can ignore selection order */
		if (is_pair) {
			if (!edbm_connect_vert_pair(em, op)) {
				failed_connect_len++;
			}
			continue;
		}

		if (bm->selected.first) {
			BMEditSelection *ese = bm->selected.first;
			if (ese->htype == BM_EDGE) {
				if (bm_vert_connect_select_history_edge_to_vert_path(bm, &selected_orig)) {
					SWAP(ListBase, bm->selected, selected_orig);
				}
			}
		}

		if (bm_vert_connect_select_history(bm)) {
			EDBM_selectmode_flush(em);
			EDBM_update_generic(em, true, true);
		}
		else {
			failed_selection_order_len++;
		}

		if (!BLI_listbase_is_empty(&selected_orig)) {
			BM_select_history_clear(bm);
			bm->selected = selected_orig;
		}
	}

	MEM_freeN(objects);

	if (failed_selection_order_len == objects_len) {
		BKE_report(op->reports, RPT_ERROR, "Invalid selection order");
		return OPERATOR_CANCELLED;
	}
	else if (failed_connect_len == objects_len) {
		BKE_report(op->reports, RPT_ERROR, "Could not connect vertices");
		return OPERATOR_CANCELLED;
	}

	return OPERATOR_FINISHED;
}

void MESH_OT_vert_connect_path(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Vertex Connect Path";
	ot->idname = "MESH_OT_vert_connect_path";
	ot->description = "Connect vertices by their selection order, creating edges, splitting faces";

	/* api callbacks */
	ot->exec = edbm_vert_connect_path_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

static int edbm_vert_connect_concave_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totfacesel == 0) {
			continue;
		}

		if (!EDBM_op_call_and_selectf(
		             em, op,
		             "faces.out", true,
		             "connect_verts_concave faces=%hf",
		             BM_ELEM_SELECT))
		{
			continue;
		}
		EDBM_update_generic(em, true, true);
	}

	MEM_freeN(objects);
	return OPERATOR_FINISHED;
}

void MESH_OT_vert_connect_concave(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Split Concave Faces";
	ot->idname = "MESH_OT_vert_connect_concave";
	ot->description = "Make all faces convex";

	/* api callbacks */
	ot->exec = edbm_vert_connect_concave_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Split Non-Planar Faces Operator
 * \{ */

static int edbm_vert_connect_nonplaner_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);
	const float angle_limit = RNA_float_get(op->ptr, "angle_limit");
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totfacesel == 0) {
			continue;
		}

		if (!EDBM_op_call_and_selectf(
		            em, op,
		            "faces.out", true,
		            "connect_verts_nonplanar faces=%hf angle_limit=%f",
		            BM_ELEM_SELECT, angle_limit))
		{
			continue;
		}

		EDBM_update_generic(em, true, true);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_vert_connect_nonplanar(wmOperatorType *ot)
{
	PropertyRNA *prop;

	/* identifiers */
	ot->name = "Split Non-Planar Faces";
	ot->idname = "MESH_OT_vert_connect_nonplanar";
	ot->description = "Split non-planar faces that exceed the angle threshold";

	/* api callbacks */
	ot->exec = edbm_vert_connect_nonplaner_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* props */
	prop = RNA_def_float_rotation(ot->srna, "angle_limit", 0, NULL, 0.0f, DEG2RADF(180.0f),
	                              "Max Angle", "Angle limit", 0.0f, DEG2RADF(180.0f));
	RNA_def_property_float_default(prop, DEG2RADF(5.0f));
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Make Planar Faces Operator
 * \{ */

static int edbm_face_make_planar_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	const int repeat = RNA_int_get(op->ptr, "repeat");
	const float fac = RNA_float_get(op->ptr, "factor");

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		if (em->bm->totfacesel == 0) {
			continue;
		}

		if (!EDBM_op_callf(
		            em, op, "planar_faces faces=%hf iterations=%i factor=%f",
		            BM_ELEM_SELECT, repeat, fac))
		{
			continue;
		}

		EDBM_update_generic(em, true, true);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_face_make_planar(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Make Planar Faces";
	ot->idname = "MESH_OT_face_make_planar";
	ot->description = "Flatten selected faces";

	/* api callbacks */
	ot->exec = edbm_face_make_planar_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* props */
	RNA_def_float(ot->srna, "factor", 1.0f, -10.0f, 10.0f, "Factor", "", 0.0f, 1.0f);
	RNA_def_int(ot->srna, "repeat", 1, 1, 10000, "Iterations", "", 1, 200);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Split Edge Operator
 * \{ */

static int edbm_edge_split_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		if (em->bm->totedgesel == 0) {
			continue;
		}

		if (!EDBM_op_call_and_selectf(
		            em, op,
		            "edges.out", false,
		            "split_edges edges=%he",
		            BM_ELEM_SELECT))
		{
			continue;
		}

		if (em->selectmode == SCE_SELECT_FACE) {
			EDBM_select_flush(em);
		}

		EDBM_update_generic(em, true, true);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_edge_split(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Edge Split";
	ot->idname = "MESH_OT_edge_split";
	ot->description = "Split selected edges so that each neighbor face gets its own copy";

	/* api callbacks */
	ot->exec = edbm_edge_split_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Duplicate Operator
 * \{ */

static int edbm_duplicate_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		if (em->bm->totvertsel == 0) {
			continue;
		}

		BMOperator bmop;
		BMesh *bm = em->bm;

		EDBM_op_init(
		        em, &bmop, op,
		        "duplicate geom=%hvef use_select_history=%b",
		        BM_ELEM_SELECT, true);

		BMO_op_exec(bm, &bmop);

		/* de-select all would clear otherwise */
		BM_SELECT_HISTORY_BACKUP(bm);

		EDBM_flag_disable_all(em, BM_ELEM_SELECT);

		BMO_slot_buffer_hflag_enable(bm, bmop.slots_out, "geom.out", BM_ALL_NOLOOP, BM_ELEM_SELECT, true);

		/* rebuild editselection */
		BM_SELECT_HISTORY_RESTORE(bm);

		if (!EDBM_op_finish(em, &bmop, op, true)) {
			continue;
		}
		EDBM_update_generic(em, true, true);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

static int edbm_duplicate_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
{
	WM_cursor_wait(1);
	edbm_duplicate_exec(C, op);
	WM_cursor_wait(0);

	return OPERATOR_FINISHED;
}

void MESH_OT_duplicate(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Duplicate";
	ot->description = "Duplicate selected vertices, edges or faces";
	ot->idname = "MESH_OT_duplicate";

	/* api callbacks */
	ot->invoke = edbm_duplicate_invoke;
	ot->exec = edbm_duplicate_exec;

	ot->poll = ED_operator_editmesh;

	/* to give to transform */
	RNA_def_int(ot->srna, "mode", TFM_TRANSLATION, 0, INT_MAX, "Mode", "", 0, INT_MAX);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Flip Normals Operator
 * \{ */
static int edbm_flip_normals_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totfacesel == 0) {
			continue;
		}

		if (!EDBM_op_callf(
		        em, op, "reverse_faces faces=%hf flip_multires=%b",
		        BM_ELEM_SELECT, true))
		{
			continue;
		}

		EDBM_update_generic(em, true, false);
	}

	MEM_freeN(objects);
	return OPERATOR_FINISHED;
}

void MESH_OT_flip_normals(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Flip Normals";
	ot->description = "Flip the direction of selected faces' normals (and of their vertices)";
	ot->idname = "MESH_OT_flip_normals";

	/* api callbacks */
	ot->exec = edbm_flip_normals_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Rotate Edge Operator
 * \{ */

/**
 * Rotate the edges between selected faces, otherwise rotate the selected edges.
 */
static int edbm_edge_rotate_selected_exec(bContext *C, wmOperator *op)
{
	BMEdge *eed;
	BMIter iter;
	const bool use_ccw = RNA_boolean_get(op->ptr, "use_ccw");

	int tot_rotate_all = 0, tot_failed_all = 0;
	bool no_selected_edges = true, invalid_selected_edges = true;

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		int tot = 0;

		if (em->bm->totedgesel == 0) {
			continue;
		}
		no_selected_edges = false;

		/* first see if we have two adjacent faces */
		BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
			BM_elem_flag_disable(eed, BM_ELEM_TAG);
			if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
				BMFace *fa, *fb;
				if (BM_edge_face_pair(eed, &fa, &fb)) {
					/* if both faces are selected we rotate between them,
					 * otherwise - rotate between 2 unselected - but not mixed */
					if (BM_elem_flag_test(fa, BM_ELEM_SELECT) == BM_elem_flag_test(fb, BM_ELEM_SELECT)) {
						BM_elem_flag_enable(eed, BM_ELEM_TAG);
						tot++;
					}
				}
			}
		}

		/* ok, we don't have two adjacent faces, but we do have two selected ones.
		 * that's an error condition.*/
		if (tot == 0) {
			continue;
		}
		invalid_selected_edges = false;

		BMOperator bmop;
		EDBM_op_init(em, &bmop, op, "rotate_edges edges=%he use_ccw=%b", BM_ELEM_TAG, use_ccw);

		/* avoids leaving old verts selected which can be a problem running multiple times,
		 * since this means the edges become selected around the face which then attempt to rotate */
		BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_in, "edges", BM_EDGE, BM_ELEM_SELECT, true);

		BMO_op_exec(em->bm, &bmop);
		/* edges may rotate into hidden vertices, if this does _not_ run we get an ilogical state */
		BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_HIDDEN, true);
		BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true);

		const int tot_rotate = BMO_slot_buffer_count(bmop.slots_out, "edges.out");
		const int tot_failed = tot - tot_rotate;

		tot_rotate_all += tot_rotate;
		tot_failed_all += tot_failed;

		if (tot_failed != 0) {
			/* If some edges fail to rotate, we need to re-select them,
			 * otherwise we can end up with invalid selection
			 * (unselected edge between 2 selected faces). */
			BM_mesh_elem_hflag_enable_test(em->bm, BM_EDGE, BM_ELEM_SELECT, true, false, BM_ELEM_TAG);
		}

		EDBM_selectmode_flush(em);

		if (!EDBM_op_finish(em, &bmop, op, true)) {
			continue;
		}

		EDBM_update_generic(em, true, true);
	}
	MEM_freeN(objects);

	if (no_selected_edges) {
		BKE_report(op->reports, RPT_ERROR, "Select edges or face pairs for edge loops to rotate about");
		return OPERATOR_CANCELLED;
	}

	/* Ok, we don't have two adjacent faces, but we do have two selected ones.
	 * that's an error condition. */
	if (invalid_selected_edges) {
		BKE_report(op->reports, RPT_ERROR, "Could not find any selected edges that can be rotated");
		return OPERATOR_CANCELLED;
	}

	if (tot_failed_all != 0) {
		BKE_reportf(op->reports, RPT_WARNING, "Unable to rotate %d edge(s)", tot_failed_all);
	}

	return OPERATOR_FINISHED;
}

void MESH_OT_edge_rotate(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Rotate Selected Edge";
	ot->description = "Rotate selected edge or adjoining faces";
	ot->idname = "MESH_OT_edge_rotate";

	/* api callbacks */
	ot->exec = edbm_edge_rotate_selected_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* props */
	RNA_def_boolean(ot->srna, "use_ccw", false, "Counter Clockwise", "");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Hide Operator
 * \{ */

static int edbm_hide_exec(bContext *C, wmOperator *op)
{
	const bool unselected = RNA_boolean_get(op->ptr, "unselected");
	ViewLayer *view_layer = CTX_data_view_layer(C);

	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		BMesh *bm = em->bm;

		if ((bm->totvertsel == 0) &&
		    (bm->totedgesel == 0) &&
		    (bm->totfacesel == 0))
		{
			continue;
		}

		EDBM_mesh_hide(em, unselected);
		EDBM_update_generic(em, true, false);
	}

	MEM_freeN(objects);
	return OPERATOR_FINISHED;
}

void MESH_OT_hide(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Hide Selection";
	ot->idname = "MESH_OT_hide";
	ot->description = "Hide (un)selected vertices, edges or faces";

	/* api callbacks */
	ot->exec = edbm_hide_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* props */
	RNA_def_boolean(ot->srna, "unselected", false, "Unselected", "Hide unselected rather than selected");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Reveal Operator
 * \{ */

static int edbm_reveal_exec(bContext *C, wmOperator *op)
{
	const bool select = RNA_boolean_get(op->ptr, "select");
	ViewLayer *view_layer = CTX_data_view_layer(C);

	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		EDBM_mesh_reveal(em, select);
		EDBM_update_generic(em, true, false);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_reveal(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Reveal Hidden";
	ot->idname = "MESH_OT_reveal";
	ot->description = "Reveal all hidden vertices, edges and faces";

	/* api callbacks */
	ot->exec = edbm_reveal_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	RNA_def_boolean(ot->srna, "select", true, "Select", "");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Recalculate Normals Operator
 * \{ */

static int edbm_normals_make_consistent_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);

	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totfacesel == 0) {
			continue;
		}

		if (!EDBM_op_callf(em, op, "recalc_face_normals faces=%hf", BM_ELEM_SELECT)) {
			continue;
		}
		if (RNA_boolean_get(op->ptr, "inside")) {
			EDBM_op_callf(em, op, "reverse_faces faces=%hf flip_multires=%b", BM_ELEM_SELECT, true);
		}

		EDBM_update_generic(em, true, false);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_normals_make_consistent(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Make Normals Consistent";
	ot->description = "Make face and vertex normals point either outside or inside the mesh";
	ot->idname = "MESH_OT_normals_make_consistent";

	/* api callbacks */
	ot->exec = edbm_normals_make_consistent_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	RNA_def_boolean(ot->srna, "inside", false, "Inside", "");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Smooth Vertex Operator
 * \{ */

static int edbm_do_smooth_vertex_exec(bContext *C, wmOperator *op)
{
	const float fac = RNA_float_get(op->ptr, "factor");

	const bool xaxis = RNA_boolean_get(op->ptr, "xaxis");
	const bool yaxis = RNA_boolean_get(op->ptr, "yaxis");
	const bool zaxis = RNA_boolean_get(op->ptr, "zaxis");
	int repeat = RNA_int_get(op->ptr, "repeat");

	if (!repeat) {
		repeat = 1;
	}

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		Mesh *me = obedit->data;
		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		ModifierData *md;
		bool mirrx = false, mirry = false, mirrz = false;
		int i;
		float clip_dist = 0.0f;
		const bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;

		if (em->bm->totvertsel == 0) {
			continue;
		}

		/* mirror before smooth */
		if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
			EDBM_verts_mirror_cache_begin(em, 0, false, true, use_topology);
		}

		/* if there is a mirror modifier with clipping, flag the verts that
		 * are within tolerance of the plane(s) of reflection
		 */
		for (md = obedit->modifiers.first; md; md = md->next) {
			if (md->type == eModifierType_Mirror && (md->mode & eModifierMode_Realtime)) {
				MirrorModifierData *mmd = (MirrorModifierData *)md;

				if (mmd->flag & MOD_MIR_CLIPPING) {
					if (mmd->flag & MOD_MIR_AXIS_X)
						mirrx = true;
					if (mmd->flag & MOD_MIR_AXIS_Y)
						mirry = true;
					if (mmd->flag & MOD_MIR_AXIS_Z)
						mirrz = true;

					clip_dist = mmd->tolerance;
				}
			}
		}

		for (i = 0; i < repeat; i++) {
			if (!EDBM_op_callf(
			        em, op,
			        "smooth_vert verts=%hv factor=%f mirror_clip_x=%b mirror_clip_y=%b mirror_clip_z=%b "
			        "clip_dist=%f use_axis_x=%b use_axis_y=%b use_axis_z=%b",
			        BM_ELEM_SELECT, fac, mirrx, mirry, mirrz, clip_dist, xaxis, yaxis, zaxis))
			{
				continue;
			}
		}

		/* apply mirror */
		if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
			EDBM_verts_mirror_apply(em, BM_ELEM_SELECT, 0);
			EDBM_verts_mirror_cache_end(em);
		}

		EDBM_update_generic(em, true, false);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_vertices_smooth(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Smooth Vertex";
	ot->description = "Flatten angles of selected vertices";
	ot->idname = "MESH_OT_vertices_smooth";

	/* api callbacks */
	ot->exec = edbm_do_smooth_vertex_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	RNA_def_float(ot->srna, "factor", 0.5f, -10.0f, 10.0f, "Smoothing", "Smoothing factor", 0.0f, 1.0f);
	RNA_def_int(ot->srna, "repeat", 1, 1, 1000, "Repeat", "Number of times to smooth the mesh", 1, 100);

	WM_operatortype_props_advanced_begin(ot);

	RNA_def_boolean(ot->srna, "xaxis", true, "X-Axis", "Smooth along the X axis");
	RNA_def_boolean(ot->srna, "yaxis", true, "Y-Axis", "Smooth along the Y axis");
	RNA_def_boolean(ot->srna, "zaxis", true, "Z-Axis", "Smooth along the Z axis");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Laplacian Vertex Smooth Operator
 * \{ */

static int edbm_do_smooth_laplacian_vertex_exec(bContext *C, wmOperator *op)
{
	Object *obedit = CTX_data_edit_object(C);
	BMEditMesh *em = BKE_editmesh_from_object(obedit);
	Mesh *me = obedit->data;
	bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
	bool usex = true, usey = true, usez = true, preserve_volume = true;
	int i, repeat;
	float lambda_factor;
	float lambda_border;
	BMIter fiter;
	BMFace *f;

	/* Check if select faces are triangles */
	BM_ITER_MESH (f, &fiter, em->bm, BM_FACES_OF_MESH) {
		if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
			if (f->len > 4) {
				BKE_report(op->reports, RPT_WARNING, "Selected faces must be triangles or quads");
				return OPERATOR_CANCELLED;
			}
		}
	}

	/* mirror before smooth */
	if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
		EDBM_verts_mirror_cache_begin(em, 0, false, true, use_topology);
	}

	repeat = RNA_int_get(op->ptr, "repeat");
	lambda_factor = RNA_float_get(op->ptr, "lambda_factor");
	lambda_border = RNA_float_get(op->ptr, "lambda_border");
	usex = RNA_boolean_get(op->ptr, "use_x");
	usey = RNA_boolean_get(op->ptr, "use_y");
	usez = RNA_boolean_get(op->ptr, "use_z");
	preserve_volume = RNA_boolean_get(op->ptr, "preserve_volume");
	if (!repeat)
		repeat = 1;

	for (i = 0; i < repeat; i++) {
		if (!EDBM_op_callf(
		            em, op,
		            "smooth_laplacian_vert verts=%hv lambda_factor=%f lambda_border=%f use_x=%b use_y=%b use_z=%b preserve_volume=%b",
		            BM_ELEM_SELECT, lambda_factor, lambda_border, usex, usey, usez, preserve_volume))
		{
			return OPERATOR_CANCELLED;
		}
	}

	/* apply mirror */
	if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
		EDBM_verts_mirror_apply(em, BM_ELEM_SELECT, 0);
		EDBM_verts_mirror_cache_end(em);
	}

	EDBM_update_generic(em, true, false);

	return OPERATOR_FINISHED;
}

void MESH_OT_vertices_smooth_laplacian(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Laplacian Smooth Vertex";
	ot->description = "Laplacian smooth of selected vertices";
	ot->idname = "MESH_OT_vertices_smooth_laplacian";

	/* api callbacks */
	ot->exec = edbm_do_smooth_laplacian_vertex_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	RNA_def_int(ot->srna, "repeat", 1, 1, 1000,
	            "Number of iterations to smooth the mesh", "", 1, 200);
	RNA_def_float(ot->srna, "lambda_factor", 1.0f, 1e-7f, 1000.0f,
	              "Lambda factor", "", 1e-7f, 1000.0f);
	RNA_def_float(ot->srna, "lambda_border", 5e-5f, 1e-7f, 1000.0f,
	              "Lambda factor in border", "", 1e-7f, 1000.0f);

	WM_operatortype_props_advanced_begin(ot);

	RNA_def_boolean(ot->srna, "use_x", true, "Smooth X Axis", "Smooth object along X axis");
	RNA_def_boolean(ot->srna, "use_y", true, "Smooth Y Axis", "Smooth object along Y axis");
	RNA_def_boolean(ot->srna, "use_z", true, "Smooth Z Axis", "Smooth object along Z axis");
	RNA_def_boolean(ot->srna, "preserve_volume", true, "Preserve Volume", "Apply volume preservation after smooth");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Set Faces Smooth Shading Operator
 * \{ */

static void mesh_set_smooth_faces(BMEditMesh *em, short smooth)
{
	BMIter iter;
	BMFace *efa;

	if (em == NULL) return;

	BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
		if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
			BM_elem_flag_set(efa, BM_ELEM_SMOOTH, smooth);
		}
	}
}

static int edbm_faces_shade_smooth_exec(bContext *C, wmOperator *UNUSED(op))
{
	ViewLayer * view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object * *objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object * obedit = objects[ob_index];
		BMEditMesh * em = BKE_editmesh_from_object(obedit);

		if (em->bm->totfacesel == 0) {
			continue;
		}

		mesh_set_smooth_faces(em, 1);
		EDBM_update_generic(em, false, false);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_faces_shade_smooth(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Shade Smooth";
	ot->description = "Display faces smooth (using vertex normals)";
	ot->idname = "MESH_OT_faces_shade_smooth";

	/* api callbacks */
	ot->exec = edbm_faces_shade_smooth_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Set Faces Flat Shading Operator
 * \{ */

static int edbm_faces_shade_flat_exec(bContext *C, wmOperator *UNUSED(op))
{
	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totfacesel == 0) {
			continue;
		}

		mesh_set_smooth_faces(em, 0);
		EDBM_update_generic(em, false, false);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_faces_shade_flat(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Shade Flat";
	ot->description = "Display faces flat";
	ot->idname = "MESH_OT_faces_shade_flat";

	/* api callbacks */
	ot->exec = edbm_faces_shade_flat_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name UV/Color Rotate/Reverse Operator
 * \{ */

static int edbm_rotate_uvs_exec(bContext *C, wmOperator *op)
{
	/* get the direction from RNA */
	const bool use_ccw = RNA_boolean_get(op->ptr, "use_ccw");

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totfacesel == 0) {
			continue;
		}

		BMOperator bmop;

		/* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
		EDBM_op_init(em, &bmop, op, "rotate_uvs faces=%hf use_ccw=%b", BM_ELEM_SELECT, use_ccw);

		/* execute the operator */
		BMO_op_exec(em->bm, &bmop);

		if (!EDBM_op_finish(em, &bmop, op, true)) {
			continue;
		}

		EDBM_update_generic(em, false, false);
	}

	MEM_freeN(objects);
	return OPERATOR_FINISHED;
}

static int edbm_reverse_uvs_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totfacesel == 0) {
			continue;
		}

		BMOperator bmop;

		/* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
		EDBM_op_init(em, &bmop, op, "reverse_uvs faces=%hf", BM_ELEM_SELECT);

		/* execute the operator */
		BMO_op_exec(em->bm, &bmop);

		/* finish the operator */
		if (!EDBM_op_finish(em, &bmop, op, true)) {
			continue;
		}
		EDBM_update_generic(em, false, false);
	}

	MEM_freeN(objects);
	return OPERATOR_FINISHED;
}

static int edbm_rotate_colors_exec(bContext *C, wmOperator *op)
{
		/* get the direction from RNA */
	const bool use_ccw = RNA_boolean_get(op->ptr, "use_ccw");

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *ob = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(ob);
		if (em->bm->totfacesel == 0) {
			continue;
		}

		BMOperator bmop;

		/* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
		EDBM_op_init(em, &bmop, op, "rotate_colors faces=%hf use_ccw=%b", BM_ELEM_SELECT, use_ccw);

		/* execute the operator */
		BMO_op_exec(em->bm, &bmop);

		/* finish the operator */
		if (!EDBM_op_finish(em, &bmop, op, true)) {
			continue;
		}

		/* dependencies graph and notification stuff */
		EDBM_update_generic(em, false, false);
	}

	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}


static int edbm_reverse_colors_exec(bContext *C, wmOperator *op)
{
	Object *ob = CTX_data_edit_object(C);
	BMEditMesh *em = BKE_editmesh_from_object(ob);
	BMOperator bmop;

	/* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
	EDBM_op_init(em, &bmop, op, "reverse_colors faces=%hf", BM_ELEM_SELECT);

	/* execute the operator */
	BMO_op_exec(em->bm, &bmop);

	/* finish the operator */
	if (!EDBM_op_finish(em, &bmop, op, true)) {
		return OPERATOR_CANCELLED;
	}

	EDBM_update_generic(em, false, false);

	return OPERATOR_FINISHED;
}

void MESH_OT_uvs_rotate(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Rotate UVs";
	ot->idname = "MESH_OT_uvs_rotate";
	ot->description = "Rotate UV coordinates inside faces";

	/* api callbacks */
	ot->exec = edbm_rotate_uvs_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* props */
	RNA_def_boolean(ot->srna, "use_ccw", false, "Counter Clockwise", "");
}

void MESH_OT_uvs_reverse(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Reverse UVs";
	ot->idname = "MESH_OT_uvs_reverse";
	ot->description = "Flip direction of UV coordinates inside faces";

	/* api callbacks */
	ot->exec = edbm_reverse_uvs_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* props */
	//RNA_def_enum(ot->srna, "axis", axis_items, DIRECTION_CW, "Axis", "Axis to mirror UVs around");
}

void MESH_OT_colors_rotate(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Rotate Colors";
	ot->idname = "MESH_OT_colors_rotate";
	ot->description = "Rotate vertex colors inside faces";

	/* api callbacks */
	ot->exec = edbm_rotate_colors_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* props */
	RNA_def_boolean(ot->srna, "use_ccw", false, "Counter Clockwise", "");
}

void MESH_OT_colors_reverse(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Reverse Colors";
	ot->idname = "MESH_OT_colors_reverse";
	ot->description = "Flip direction of vertex colors inside faces";

	/* api callbacks */
	ot->exec = edbm_reverse_colors_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* props */
	//RNA_def_enum(ot->srna, "axis", axis_items, DIRECTION_CW, "Axis", "Axis to mirror colors around");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Merge Vertices Operator
 * \{ */

enum {
	MESH_MERGE_LAST     = 1,
	MESH_MERGE_CENTER   = 3,
	MESH_MERGE_CURSOR   = 4,
	MESH_MERGE_COLLAPSE = 5,
	MESH_MERGE_FIRST    = 6,
};

static bool merge_firstlast(BMEditMesh *em, const bool use_first, const bool use_uvmerge, wmOperator *wmop)
{
	BMVert *mergevert;
	BMEditSelection *ese;

	/* operator could be called directly from shortcut or python,
	 * so do extra check for data here
	 */

	/* do sanity check in mergemenu in edit.c ?*/
	if (use_first == false) {
		if (!em->bm->selected.last || ((BMEditSelection *)em->bm->selected.last)->htype != BM_VERT)
			return false;

		ese = em->bm->selected.last;
		mergevert = (BMVert *)ese->ele;
	}
	else {
		if (!em->bm->selected.first || ((BMEditSelection *)em->bm->selected.first)->htype != BM_VERT)
			return false;

		ese = em->bm->selected.first;
		mergevert = (BMVert *)ese->ele;
	}

	if (!BM_elem_flag_test(mergevert, BM_ELEM_SELECT))
		return false;

	if (use_uvmerge) {
		if (!EDBM_op_callf(em, wmop, "pointmerge_facedata verts=%hv vert_snap=%e", BM_ELEM_SELECT, mergevert))
			return false;
	}

	if (!EDBM_op_callf(em, wmop, "pointmerge verts=%hv merge_co=%v", BM_ELEM_SELECT, mergevert->co))
		return false;

	return true;
}

static bool merge_target(
        BMEditMesh *em, Scene *scene, View3D *v3d, Object *ob,
        const bool use_cursor, const bool use_uvmerge, wmOperator *wmop)
{
	BMIter iter;
	BMVert *v;
	float co[3], cent[3] = {0.0f, 0.0f, 0.0f};
	const float *vco = NULL;

	if (use_cursor) {
		vco = ED_view3d_cursor3d_get(scene, v3d)->location;
		copy_v3_v3(co, vco);
		invert_m4_m4(ob->imat, ob->obmat);
		mul_m4_v3(ob->imat, co);
	}
	else {
		float fac;
		int i = 0;
		BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
			if (!BM_elem_flag_test(v, BM_ELEM_SELECT))
				continue;
			add_v3_v3(cent, v->co);
			i++;
		}

		if (!i)
			return false;

		fac = 1.0f / (float)i;
		mul_v3_fl(cent, fac);
		copy_v3_v3(co, cent);
		vco = co;
	}

	if (!vco)
		return false;

	if (use_uvmerge) {
		if (!EDBM_op_callf(em, wmop, "average_vert_facedata verts=%hv", BM_ELEM_SELECT))
			return false;
	}

	if (!EDBM_op_callf(em, wmop, "pointmerge verts=%hv merge_co=%v", BM_ELEM_SELECT, co))
		return false;

	return true;
}

static int edbm_merge_exec(bContext *C, wmOperator *op)
{
	Scene *scene = CTX_data_scene(C);
	View3D *v3d = CTX_wm_view3d(C);
	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	const int type = RNA_enum_get(op->ptr, "type");
	const bool uvs = RNA_boolean_get(op->ptr, "uvs");

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totvertsel == 0) {
			continue;
		}

		bool ok = false;
		switch (type) {
			case MESH_MERGE_CENTER:
				ok = merge_target(em, scene, v3d, obedit, false, uvs, op);
				break;
			case MESH_MERGE_CURSOR:
				ok = merge_target(em, scene, v3d, obedit, true, uvs, op);
				break;
			case MESH_MERGE_LAST:
				ok = merge_firstlast(em, false, uvs, op);
				break;
			case MESH_MERGE_FIRST:
				ok = merge_firstlast(em, true, uvs, op);
				break;
			case MESH_MERGE_COLLAPSE:
				ok = EDBM_op_callf(em, op, "collapse edges=%he uvs=%b", BM_ELEM_SELECT, uvs);
				break;
			default:
				BLI_assert(0);
				break;
		}

		if (!ok) {
			continue;
		}

		EDBM_update_generic(em, true, true);

		/* once collapsed, we can't have edge/face selection */
		if ((em->selectmode & SCE_SELECT_VERTEX) == 0) {
			EDBM_flag_disable_all(em, BM_ELEM_SELECT);
		}
		/* Only active object supported, see comment below. */
		if (ELEM(type, MESH_MERGE_FIRST, MESH_MERGE_LAST)) {
			break;
		}
	}

	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

static const EnumPropertyItem merge_type_items[] = {
	{MESH_MERGE_FIRST, "FIRST", 0, "At First", ""},
	{MESH_MERGE_LAST, "LAST", 0, "At Last", ""},
	{MESH_MERGE_CENTER, "CENTER", 0, "At Center", ""},
	{MESH_MERGE_CURSOR, "CURSOR", 0, "At Cursor", ""},
	{MESH_MERGE_COLLAPSE, "COLLAPSE", 0, "Collapse", ""},
	{0, NULL, 0, NULL, NULL}
};

static const EnumPropertyItem *merge_type_itemf(bContext *C, PointerRNA *UNUSED(ptr),  PropertyRNA *UNUSED(prop), bool *r_free)
{
	Object *obedit;
	EnumPropertyItem *item = NULL;
	int totitem = 0;

	if (!C) /* needed for docs */
		return merge_type_items;

	obedit = CTX_data_edit_object(C);
	if (obedit && obedit->type == OB_MESH) {
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		/* Only active object supported:
		 * In practice it doesn't make sense to run this operation on non-active meshes
		 * since selecting will activate - we could have own code-path for these but it's a hassle
		 * for now just apply to the active (first) object. */
		if (em->selectmode & SCE_SELECT_VERTEX) {
			if (em->bm->selected.first && em->bm->selected.last &&
			    ((BMEditSelection *)em->bm->selected.first)->htype == BM_VERT &&
			    ((BMEditSelection *)em->bm->selected.last)->htype == BM_VERT)
			{
				RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_FIRST);
				RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_LAST);
			}
			else if (em->bm->selected.first && ((BMEditSelection *)em->bm->selected.first)->htype == BM_VERT) {
				RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_FIRST);
			}
			else if (em->bm->selected.last && ((BMEditSelection *)em->bm->selected.last)->htype == BM_VERT) {
				RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_LAST);
			}
		}

		RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_CENTER);
		RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_CURSOR);
		RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_COLLAPSE);
		RNA_enum_item_end(&item, &totitem);

		*r_free = true;

		return item;
	}

	return NULL;
}

void MESH_OT_merge(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Merge";
	ot->description = "Merge selected vertices";
	ot->idname = "MESH_OT_merge";

	/* api callbacks */
	ot->exec = edbm_merge_exec;
	ot->invoke = WM_menu_invoke;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* properties */
	ot->prop = RNA_def_enum(ot->srna, "type", merge_type_items, MESH_MERGE_CENTER, "Type", "Merge method to use");
	RNA_def_enum_funcs(ot->prop, merge_type_itemf);

	WM_operatortype_props_advanced_begin(ot);

	RNA_def_boolean(ot->srna, "uvs", false, "UVs", "Move UVs according to merge");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Remove Doubles Operator
 * \{ */

static int edbm_remove_doubles_exec(bContext *C, wmOperator *op)
{
	const float threshold = RNA_float_get(op->ptr, "threshold");
	const bool use_unselected = RNA_boolean_get(op->ptr, "use_unselected");
	int count_multi = 0;

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		/* Selection used as target with 'use_unselected'. */
		if (em->bm->totvertsel == 0) {
			continue;
		}

		BMOperator bmop;
		const int totvert_orig = em->bm->totvert;

		/* avoid loosing selection state (select -> tags) */
		char htype_select;
		if      (em->selectmode & SCE_SELECT_VERTEX) htype_select = BM_VERT;
		else if (em->selectmode & SCE_SELECT_EDGE)   htype_select = BM_EDGE;
		else                                         htype_select = BM_FACE;

		/* store selection as tags */
		BM_mesh_elem_hflag_enable_test(em->bm, htype_select, BM_ELEM_TAG, true, true, BM_ELEM_SELECT);


		if (use_unselected) {
			EDBM_op_init(
			        em, &bmop, op,
			        "automerge verts=%hv dist=%f",
			        BM_ELEM_SELECT, threshold);
			BMO_op_exec(em->bm, &bmop);

			if (!EDBM_op_finish(em, &bmop, op, true)) {
				continue;
			}
		}
		else {
			EDBM_op_init(
			        em, &bmop, op,
			        "find_doubles verts=%hv dist=%f",
			        BM_ELEM_SELECT, threshold);

			BMO_op_exec(em->bm, &bmop);

			if (!EDBM_op_callf(em, op, "weld_verts targetmap=%S", &bmop, "targetmap.out")) {
				BMO_op_finish(em->bm, &bmop);
				continue;
			}

			if (!EDBM_op_finish(em, &bmop, op, true)) {
				continue;
			}
		}

		const int count = (totvert_orig - em->bm->totvert);

		/* restore selection from tags */
		BM_mesh_elem_hflag_enable_test(em->bm, htype_select, BM_ELEM_SELECT, true, true, BM_ELEM_TAG);
		EDBM_selectmode_flush(em);

		if (count) {
			count_multi += count;
			EDBM_update_generic(em, true, true);
		}
	}
	MEM_freeN(objects);

	BKE_reportf(op->reports, RPT_INFO, "Removed %d vertices", count_multi);

	return OPERATOR_FINISHED;
}

void MESH_OT_remove_doubles(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Remove Doubles";
	ot->description = "Remove duplicate vertices";
	ot->idname = "MESH_OT_remove_doubles";

	/* api callbacks */
	ot->exec = edbm_remove_doubles_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	RNA_def_float_distance(ot->srna, "threshold", 1e-4f, 1e-6f, 50.0f, "Merge Distance",
	                       "Minimum distance between elements to merge", 1e-5f, 10.0f);
	RNA_def_boolean(ot->srna, "use_unselected", false, "Unselected", "Merge selected to other unselected vertices");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Shape Key Propagate Operator
 * \{ */

/* BMESH_TODO this should be properly encapsulated in a bmop.  but later.*/
static void shape_propagate(BMEditMesh *em, wmOperator *op)
{
	BMIter iter;
	BMVert *eve = NULL;
	float *co;
	int i, totshape = CustomData_number_of_layers(&em->bm->vdata, CD_SHAPEKEY);

	if (!CustomData_has_layer(&em->bm->vdata, CD_SHAPEKEY)) {
		BKE_report(op->reports, RPT_ERROR, "Mesh does not have shape keys");
		return;
	}

	BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
		if (!BM_elem_flag_test(eve, BM_ELEM_SELECT) || BM_elem_flag_test(eve, BM_ELEM_HIDDEN))
			continue;

		for (i = 0; i < totshape; i++) {
			co = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, i);
			copy_v3_v3(co, eve->co);
		}
	}

#if 0
	//TAG Mesh Objects that share this data
	for (base = scene->base.first; base; base = base->next) {
		if (base->object && base->object->data == me) {
			DEG_id_tag_update(&base->object->id, OB_RECALC_DATA);
		}
	}
#endif
}


static int edbm_shape_propagate_to_all_exec(bContext *C, wmOperator *op)
{
	Object *obedit = CTX_data_edit_object(C);
	Mesh *me = obedit->data;
	BMEditMesh *em = me->edit_btmesh;

	shape_propagate(em, op);

	EDBM_update_generic(em, false, false);

	return OPERATOR_FINISHED;
}


void MESH_OT_shape_propagate_to_all(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Shape Propagate";
	ot->description = "Apply selected vertex locations to all other shape keys";
	ot->idname = "MESH_OT_shape_propagate_to_all";

	/* api callbacks */
	ot->exec = edbm_shape_propagate_to_all_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Blend from Shape Operator
 * \{ */

/* BMESH_TODO this should be properly encapsulated in a bmop.  but later.*/
static int edbm_blend_from_shape_exec(bContext *C, wmOperator *op)
{
	Object *obedit = CTX_data_edit_object(C);
	Mesh *me = obedit->data;
	Key *key = me->key;
	KeyBlock *kb = NULL;
	BMEditMesh *em = me->edit_btmesh;
	BMVert *eve;
	BMIter iter;
	float co[3], *sco;
	int totshape;

	const float blend = RNA_float_get(op->ptr, "blend");
	const int shape = RNA_enum_get(op->ptr, "shape");
	const bool use_add = RNA_boolean_get(op->ptr, "add");

	/* sanity check */
	totshape = CustomData_number_of_layers(&em->bm->vdata, CD_SHAPEKEY);
	if (totshape == 0 || shape < 0 || shape >= totshape)
		return OPERATOR_CANCELLED;

	/* get shape key - needed for finding reference shape (for add mode only) */
	if (key) {
		kb = BLI_findlink(&key->block, shape);
	}

	/* perform blending on selected vertices*/
	BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
		if (!BM_elem_flag_test(eve, BM_ELEM_SELECT) || BM_elem_flag_test(eve, BM_ELEM_HIDDEN))
			continue;

		/* get coordinates of shapekey we're blending from */
		sco = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, shape);
		copy_v3_v3(co, sco);

		if (use_add) {
			/* in add mode, we add relative shape key offset */
			if (kb) {
				const float *rco = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, kb->relative);
				sub_v3_v3v3(co, co, rco);
			}

			madd_v3_v3fl(eve->co, co, blend);
		}
		else {
			/* in blend mode, we interpolate to the shape key */
			interp_v3_v3v3(eve->co, eve->co, co, blend);
		}
	}

	EDBM_update_generic(em, true, false);

	return OPERATOR_FINISHED;
}

static const EnumPropertyItem *shape_itemf(bContext *C, PointerRNA *UNUSED(ptr),  PropertyRNA *UNUSED(prop), bool *r_free)
{
	Object *obedit = CTX_data_edit_object(C);
	BMEditMesh *em;
	EnumPropertyItem *item = NULL;
	int totitem = 0;

	if ((obedit && obedit->type == OB_MESH) &&
	    (em = BKE_editmesh_from_object(obedit)) &&
	    CustomData_has_layer(&em->bm->vdata, CD_SHAPEKEY))
	{
		EnumPropertyItem tmp = {0, "", 0, "", ""};
		int a;

		for (a = 0; a < em->bm->vdata.totlayer; a++) {
			if (em->bm->vdata.layers[a].type != CD_SHAPEKEY)
				continue;

			tmp.value = totitem;
			tmp.identifier = em->bm->vdata.layers[a].name;
			tmp.name = em->bm->vdata.layers[a].name;
			/* RNA_enum_item_add sets totitem itself! */
			RNA_enum_item_add(&item, &totitem, &tmp);
		}
	}

	RNA_enum_item_end(&item, &totitem);
	*r_free = true;

	return item;
}

static void edbm_blend_from_shape_ui(bContext *C, wmOperator *op)
{
	uiLayout *layout = op->layout;
	PointerRNA ptr;
	Object *obedit = CTX_data_edit_object(C);
	Mesh *me = obedit->data;
	PointerRNA ptr_key;

	RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr);
	RNA_id_pointer_create((ID *)me->key, &ptr_key);

	uiItemPointerR(layout, &ptr, "shape", &ptr_key, "key_blocks", "", ICON_SHAPEKEY_DATA);
	uiItemR(layout, &ptr, "blend", 0, NULL, ICON_NONE);
	uiItemR(layout, &ptr, "add", 0, NULL, ICON_NONE);
}

void MESH_OT_blend_from_shape(wmOperatorType *ot)
{
	PropertyRNA *prop;

	/* identifiers */
	ot->name = "Blend From Shape";
	ot->description = "Blend in shape from a shape key";
	ot->idname = "MESH_OT_blend_from_shape";

	/* api callbacks */
	ot->exec = edbm_blend_from_shape_exec;
//	ot->invoke = WM_operator_props_popup_call;  /* disable because search popup closes too easily */
	ot->ui = edbm_blend_from_shape_ui;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* properties */
	prop = RNA_def_enum(ot->srna, "shape", DummyRNA_NULL_items, 0, "Shape", "Shape key to use for blending");
	RNA_def_enum_funcs(prop, shape_itemf);
	RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE | PROP_NEVER_UNLINK);
	RNA_def_float(ot->srna, "blend", 1.0f, -1e3f, 1e3f, "Blend", "Blending factor", -2.0f, 2.0f);
	RNA_def_boolean(ot->srna, "add", true, "Add", "Add rather than blend between shapes");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Solidify Mesh Operator
 * \{ */

static int edbm_solidify_exec(bContext *C, wmOperator *op)
{
	const float thickness = RNA_float_get(op->ptr, "thickness");

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		BMesh *bm = em->bm;

		if (em->bm->totfacesel == 0) {
			continue;
		}

		BMOperator bmop;

		if (!EDBM_op_init(em, &bmop, op, "solidify geom=%hf thickness=%f", BM_ELEM_SELECT, thickness)) {
			continue;
		}

		/* deselect only the faces in the region to be solidified (leave wire
		 * edges and loose verts selected, as there will be no corresponding
		 * geometry selected below) */
		BMO_slot_buffer_hflag_disable(bm, bmop.slots_in, "geom", BM_FACE, BM_ELEM_SELECT, true);

		/* run the solidify operator */
		BMO_op_exec(bm, &bmop);

		/* select the newly generated faces */
		BMO_slot_buffer_hflag_enable(bm, bmop.slots_out, "geom.out", BM_FACE, BM_ELEM_SELECT, true);

		if (!EDBM_op_finish(em, &bmop, op, true)) {
			continue;
		}

		EDBM_update_generic(em, true, true);
	}

	MEM_freeN(objects);
	return OPERATOR_FINISHED;
}

void MESH_OT_solidify(wmOperatorType *ot)
{
	PropertyRNA *prop;
	/* identifiers */
	ot->name = "Solidify";
	ot->description = "Create a solid skin by extruding, compensating for sharp angles";
	ot->idname = "MESH_OT_solidify";

	/* api callbacks */
	ot->exec = edbm_solidify_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	prop = RNA_def_float_distance(ot->srna, "thickness", 0.01f, -1e4f, 1e4f, "Thickness", "", -10.0f, 10.0f);
	RNA_def_property_ui_range(prop, -10.0, 10.0, 0.1, 4);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Knife Subdivide Operator
 * \{ */

/* ******************************************************************** */
/* Knife Subdivide Tool.  Subdivides edges intersected by a mouse trail
 * drawn by user.
 *
 * Currently mapped to KKey when in MeshEdit mode.
 * Usage:
 * - Hit Shift K, Select Centers or Exact
 * - Hold LMB down to draw path, hit RETKEY.
 * - ESC cancels as expected.
 *
 * Contributed by Robert Wenzlaff (Det. Thorn).
 *
 * 2.5 Revamp:
 *  - non modal (no menu before cutting)
 *  - exit on mouse release
 *  - polygon/segment drawing can become handled by WM cb later
 *
 * bmesh port version
 */

#define KNIFE_EXACT     1
#define KNIFE_MIDPOINT  2
#define KNIFE_MULTICUT  3

static const EnumPropertyItem knife_items[] = {
	{KNIFE_EXACT, "EXACT", 0, "Exact", ""},
	{KNIFE_MIDPOINT, "MIDPOINTS", 0, "Midpoints", ""},
	{KNIFE_MULTICUT, "MULTICUT", 0, "Multicut", ""},
	{0, NULL, 0, NULL, NULL}
};

/* bm_edge_seg_isect() Determines if and where a mouse trail intersects an BMEdge */

static float bm_edge_seg_isect(
        const float sco_a[2], const float sco_b[2],
        float (*mouse_path)[2], int len, char mode, int *isected)
{
#define MAXSLOPE 100000
	float x11, y11, x12 = 0, y12 = 0, x2max, x2min, y2max;
	float y2min, dist, lastdist = 0, xdiff2, xdiff1;
	float m1, b1, m2, b2, x21, x22, y21, y22, xi;
	float yi, x1min, x1max, y1max, y1min, perc = 0;
	float threshold = 0.0;
	int i;

	//threshold = 0.000001; /* tolerance for vertex intersection */
	// XXX threshold = scene->toolsettings->select_thresh / 100;

	/* Get screen coords of verts */
	x21 = sco_a[0];
	y21 = sco_a[1];

	x22 = sco_b[0];
	y22 = sco_b[1];

	xdiff2 = (x22 - x21);
	if (xdiff2) {
		m2 = (y22 - y21) / xdiff2;
		b2 = ((x22 * y21) - (x21 * y22)) / xdiff2;
	}
	else {
		m2 = MAXSLOPE;  /* Verticle slope  */
		b2 = x22;
	}

	*isected = 0;

	/* check for _exact_ vertex intersection first */
	if (mode != KNIFE_MULTICUT) {
		for (i = 0; i < len; i++) {
			if (i > 0) {
				x11 = x12;
				y11 = y12;
			}
			else {
				x11 = mouse_path[i][0];
				y11 = mouse_path[i][1];
			}
			x12 = mouse_path[i][0];
			y12 = mouse_path[i][1];

			/* test e->v1 */
			if ((x11 == x21 && y11 == y21) || (x12 == x21 && y12 == y21)) {
				perc = 0;
				*isected = 1;
				return perc;
			}
			/* test e->v2 */
			else if ((x11 == x22 && y11 == y22) || (x12 == x22 && y12 == y22)) {
				perc = 0;
				*isected = 2;
				return perc;
			}
		}
	}

	/* now check for edge intersect (may produce vertex intersection as well) */
	for (i = 0; i < len; i++) {
		if (i > 0) {
			x11 = x12;
			y11 = y12;
		}
		else {
			x11 = mouse_path[i][0];
			y11 = mouse_path[i][1];
		}
		x12 = mouse_path[i][0];
		y12 = mouse_path[i][1];

		/* Perp. Distance from point to line */
		if (m2 != MAXSLOPE) dist = (y12 - m2 * x12 - b2);  /* /sqrt(m2 * m2 + 1); Only looking for */
		/* change in sign.  Skip extra math */
		else dist = x22 - x12;

		if (i == 0) lastdist = dist;

		/* if dist changes sign, and intersect point in edge's Bound Box */
		if ((lastdist * dist) <= 0) {
			xdiff1 = (x12 - x11); /* Equation of line between last 2 points */
			if (xdiff1) {
				m1 = (y12 - y11) / xdiff1;
				b1 = ((x12 * y11) - (x11 * y12)) / xdiff1;
			}
			else {
				m1 = MAXSLOPE;
				b1 = x12;
			}
			x2max = max_ff(x21, x22) + 0.001f; /* prevent missed edges   */
			x2min = min_ff(x21, x22) - 0.001f; /* due to round off error */
			y2max = max_ff(y21, y22) + 0.001f;
			y2min = min_ff(y21, y22) - 0.001f;

			/* Found an intersect,  calc intersect point */
			if (m1 == m2) { /* co-incident lines */
				/* cut at 50% of overlap area */
				x1max = max_ff(x11, x12);
				x1min = min_ff(x11, x12);
				xi = (min_ff(x2max, x1max) + max_ff(x2min, x1min)) / 2.0f;

				y1max = max_ff(y11, y12);
				y1min = min_ff(y11, y12);
				yi = (min_ff(y2max, y1max) + max_ff(y2min, y1min)) / 2.0f;
			}
			else if (m2 == MAXSLOPE) {
				xi = x22;
				yi = m1 * x22 + b1;
			}
			else if (m1 == MAXSLOPE) {
				xi = x12;
				yi = m2 * x12 + b2;
			}
			else {
				xi = (b1 - b2) / (m2 - m1);
				yi = (b1 * m2 - m1 * b2) / (m2 - m1);
			}

			/* Intersect inside bounding box of edge?*/
			if ((xi >= x2min) && (xi <= x2max) && (yi <= y2max) && (yi >= y2min)) {
				/* test for vertex intersect that may be 'close enough'*/
				if (mode != KNIFE_MULTICUT) {
					if (xi <= (x21 + threshold) && xi >= (x21 - threshold)) {
						if (yi <= (y21 + threshold) && yi >= (y21 - threshold)) {
							*isected = 1;
							perc = 0;
							break;
						}
					}
					if (xi <= (x22 + threshold) && xi >= (x22 - threshold)) {
						if (yi <= (y22 + threshold) && yi >= (y22 - threshold)) {
							*isected = 2;
							perc = 0;
							break;
						}
					}
				}
				if ((m2 <= 1.0f) && (m2 >= -1.0f)) perc = (xi - x21) / (x22 - x21);
				else perc = (yi - y21) / (y22 - y21);  /* lower slope more accurate */
				//isect = 32768.0 * (perc + 0.0000153); /* Percentage in 1 / 32768ths */

				break;
			}
		}
		lastdist = dist;
	}
	return perc;
}

#define ELE_EDGE_CUT 1

static int edbm_knife_cut_exec(bContext *C, wmOperator *op)
{
	Object *obedit = CTX_data_edit_object(C);
	BMEditMesh *em = BKE_editmesh_from_object(obedit);
	BMesh *bm = em->bm;
	ARegion *ar = CTX_wm_region(C);
	BMVert *bv;
	BMIter iter;
	BMEdge *be;
	BMOperator bmop;
	float isect = 0.0f;
	int len = 0, isected, i;
	short numcuts = 1;
	const short mode = RNA_int_get(op->ptr, "type");
	BMOpSlot *slot_edge_percents;

	/* allocd vars */
	float (*screen_vert_coords)[2], (*sco)[2], (*mouse_path)[2];

	/* edit-object needed for matrix, and ar->regiondata for projections to work */
	if (ELEM(NULL, obedit, ar, ar->regiondata))
		return OPERATOR_CANCELLED;

	if (bm->totvertsel < 2) {
		BKE_report(op->reports, RPT_ERROR, "No edges are selected to operate on");
		return OPERATOR_CANCELLED;
	}

	len = RNA_collection_length(op->ptr, "path");

	if (len < 2) {
		BKE_report(op->reports, RPT_ERROR, "Mouse path too short");
		return OPERATOR_CANCELLED;
	}

	mouse_path = MEM_mallocN(len * sizeof(*mouse_path), __func__);

	/* get the cut curve */
	RNA_BEGIN (op->ptr, itemptr, "path")
	{
		RNA_float_get_array(&itemptr, "loc", (float *)&mouse_path[len]);
	}
	RNA_END;

	/* for ED_view3d_project_float_object */
	ED_view3d_init_mats_rv3d(obedit, ar->regiondata);

	/* TODO, investigate using index lookup for screen_vert_coords() rather then a hash table */

	/* the floating point coordinates of verts in screen space will be stored in a hash table according to the vertices pointer */
	screen_vert_coords = sco = MEM_mallocN(bm->totvert * sizeof(float) * 2, __func__);

	BM_ITER_MESH_INDEX (bv, &iter, bm, BM_VERTS_OF_MESH, i) {
		if (ED_view3d_project_float_object(ar, bv->co, *sco, V3D_PROJ_TEST_CLIP_NEAR) != V3D_PROJ_RET_OK) {
			copy_v2_fl(*sco, FLT_MAX);  /* set error value */
		}
		BM_elem_index_set(bv, i); /* set_inline */
		sco++;

	}
	bm->elem_index_dirty &= ~BM_VERT; /* clear dirty flag */

	if (!EDBM_op_init(em, &bmop, op, "subdivide_edges")) {
		MEM_freeN(mouse_path);
		MEM_freeN(screen_vert_coords);
		return OPERATOR_CANCELLED;
	}

	/* store percentage of edge cut for KNIFE_EXACT here.*/
	slot_edge_percents = BMO_slot_get(bmop.slots_in, "edge_percents");
	BM_ITER_MESH (be, &iter, bm, BM_EDGES_OF_MESH) {
		bool is_cut = false;
		if (BM_elem_flag_test(be, BM_ELEM_SELECT)) {
			const float *sco_a = screen_vert_coords[BM_elem_index_get(be->v1)];
			const float *sco_b = screen_vert_coords[BM_elem_index_get(be->v2)];

			/* check for error value (vert cant be projected) */
			if ((sco_a[0] != FLT_MAX) && (sco_b[0] != FLT_MAX)) {
				isect = bm_edge_seg_isect(sco_a, sco_b, mouse_path, len, mode, &isected);

				if (isect != 0.0f) {
					if (mode != KNIFE_MULTICUT && mode != KNIFE_MIDPOINT) {
						BMO_slot_map_float_insert(&bmop, slot_edge_percents, be, isect);
					}
				}
			}
		}

		BMO_edge_flag_set(bm, be, ELE_EDGE_CUT, is_cut);
	}


	/* free all allocs */
	MEM_freeN(screen_vert_coords);
	MEM_freeN(mouse_path);


	BMO_slot_buffer_from_enabled_flag(bm, &bmop, bmop.slots_in, "edges", BM_EDGE, ELE_EDGE_CUT);

	if (mode == KNIFE_MIDPOINT) numcuts = 1;
	BMO_slot_int_set(bmop.slots_in, "cuts", numcuts);

	BMO_slot_int_set(bmop.slots_in, "quad_corner_type", SUBD_CORNER_STRAIGHT_CUT);
	BMO_slot_bool_set(bmop.slots_in, "use_single_edge", false);
	BMO_slot_bool_set(bmop.slots_in, "use_grid_fill", false);

	BMO_slot_float_set(bmop.slots_in, "radius", 0);

	BMO_op_exec(bm, &bmop);
	if (!EDBM_op_finish(em, &bmop, op, true)) {
		return OPERATOR_CANCELLED;
	}

	EDBM_update_generic(em, true, true);

	return OPERATOR_FINISHED;
}

#undef ELE_EDGE_CUT

void MESH_OT_knife_cut(wmOperatorType *ot)
{
	ot->name = "Knife Cut";
	ot->description = "Cut selected edges and faces into parts";
	ot->idname = "MESH_OT_knife_cut";

	ot->invoke = WM_gesture_lines_invoke;
	ot->modal = WM_gesture_lines_modal;
	ot->exec = edbm_knife_cut_exec;

	ot->poll = EDBM_view3d_poll;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* properties */
	PropertyRNA *prop;
	prop = RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
	RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);

	RNA_def_enum(ot->srna, "type", knife_items, KNIFE_EXACT, "Type", "");

	/* internal */
	RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, BC_NUMCURSORS, "Cursor", "", 0, BC_NUMCURSORS);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Separate Parts Operator
 * \{ */

enum {
	MESH_SEPARATE_SELECTED = 0,
	MESH_SEPARATE_MATERIAL = 1,
	MESH_SEPARATE_LOOSE    = 2,
};

static Base *mesh_separate_tagged(Main *bmain, Scene *scene, ViewLayer *view_layer, Base *base_old, BMesh *bm_old)
{
	Base *base_new;
	Object *obedit = base_old->object;
	BMesh *bm_new;

	bm_new = BM_mesh_create(
	        &bm_mesh_allocsize_default,
	        &((struct BMeshCreateParams){.use_toolflags = true,}));
	BM_mesh_elem_toolflags_ensure(bm_new);  /* needed for 'duplicate' bmo */

	CustomData_copy(&bm_old->vdata, &bm_new->vdata, CD_MASK_BMESH, CD_CALLOC, 0);
	CustomData_copy(&bm_old->edata, &bm_new->edata, CD_MASK_BMESH, CD_CALLOC, 0);
	CustomData_copy(&bm_old->ldata, &bm_new->ldata, CD_MASK_BMESH, CD_CALLOC, 0);
	CustomData_copy(&bm_old->pdata, &bm_new->pdata, CD_MASK_BMESH, CD_CALLOC, 0);

	CustomData_bmesh_init_pool(&bm_new->vdata, bm_mesh_allocsize_default.totvert, BM_VERT);
	CustomData_bmesh_init_pool(&bm_new->edata, bm_mesh_allocsize_default.totedge, BM_EDGE);
	CustomData_bmesh_init_pool(&bm_new->ldata, bm_mesh_allocsize_default.totloop, BM_LOOP);
	CustomData_bmesh_init_pool(&bm_new->pdata, bm_mesh_allocsize_default.totface, BM_FACE);

	base_new = ED_object_add_duplicate(bmain, scene, view_layer, base_old, USER_DUP_MESH);
	/* DAG_relations_tag_update(bmain); */ /* normally would call directly after but in this case delay recalc */
	assign_matarar(bmain, base_new->object, give_matarar(obedit), *give_totcolp(obedit)); /* new in 2.5 */

	ED_object_base_select(base_new, BA_SELECT);

	BMO_op_callf(bm_old, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
	             "duplicate geom=%hvef dest=%p", BM_ELEM_TAG, bm_new);
	BMO_op_callf(bm_old, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
	             "delete geom=%hvef context=%i", BM_ELEM_TAG, DEL_FACES);

	/* deselect loose data - this used to get deleted,
	 * we could de-select edges and verts only, but this turns out to be less complicated
	 * since de-selecting all skips selection flushing logic */
	BM_mesh_elem_hflag_disable_all(bm_old, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_SELECT, false);

	BM_mesh_normals_update(bm_new);

	BM_mesh_bm_to_me(bmain, bm_new, base_new->object->data, (&(struct BMeshToMeshParams){0}));

	BM_mesh_free(bm_new);
	((Mesh *)base_new->object->data)->edit_btmesh = NULL;

	return base_new;
}

static bool mesh_separate_selected(Main *bmain, Scene *scene, ViewLayer *view_layer, Base *base_old, BMesh *bm_old)
{
	/* we may have tags from previous operators */
	BM_mesh_elem_hflag_disable_all(bm_old, BM_FACE | BM_EDGE | BM_VERT, BM_ELEM_TAG, false);

	/* sel -> tag */
	BM_mesh_elem_hflag_enable_test(bm_old, BM_FACE | BM_EDGE | BM_VERT, BM_ELEM_TAG, true, false, BM_ELEM_SELECT);

	return (mesh_separate_tagged(bmain, scene, view_layer, base_old, bm_old) != NULL);
}

/* flush a hflag to from verts to edges/faces */
static void bm_mesh_hflag_flush_vert(BMesh *bm, const char hflag)
{
	BMEdge *e;
	BMLoop *l_iter;
	BMLoop *l_first;
	BMFace *f;

	BMIter eiter;
	BMIter fiter;

	bool ok;

	BM_ITER_MESH (e, &eiter, bm, BM_EDGES_OF_MESH) {
		if (BM_elem_flag_test(e->v1, hflag) &&
		    BM_elem_flag_test(e->v2, hflag))
		{
			BM_elem_flag_enable(e, hflag);
		}
		else {
			BM_elem_flag_disable(e, hflag);
		}
	}
	BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) {
		ok = true;
		l_iter = l_first = BM_FACE_FIRST_LOOP(f);
		do {
			if (!BM_elem_flag_test(l_iter->v, hflag)) {
				ok = false;
				break;
			}
		} while ((l_iter = l_iter->next) != l_first);

		BM_elem_flag_set(f, hflag, ok);
	}
}

/**
 * Sets an object to a single material. from one of its slots.
 *
 * \note This could be used for split-by-material for non mesh types.
 * \note This could take material data from another object or args.
 */
static void mesh_separate_material_assign_mat_nr(Main *bmain, Object *ob, const short mat_nr)
{
	ID *obdata = ob->data;

	Material ***matarar;
	const short *totcolp;

	totcolp = give_totcolp_id(obdata);
	matarar = give_matarar_id(obdata);

	if ((totcolp && matarar) == 0) {
		BLI_assert(0);
		return;
	}

	if (*totcolp) {
		Material *ma_ob;
		Material *ma_obdata;
		char matbit;

		if (mat_nr < ob->totcol) {
			ma_ob = ob->mat[mat_nr];
			matbit = ob->matbits[mat_nr];
		}
		else {
			ma_ob = NULL;
			matbit = 0;
		}

		if (mat_nr < *totcolp) {
			ma_obdata = (*matarar)[mat_nr];
		}
		else {
			ma_obdata = NULL;
		}

		BKE_material_clear_id(bmain, obdata, true);
		BKE_material_resize_object(bmain, ob, 1, true);
		BKE_material_resize_id(bmain, obdata, 1, true);

		ob->mat[0] = ma_ob;
		id_us_plus((ID *)ma_ob);
		ob->matbits[0] = matbit;
		(*matarar)[0] = ma_obdata;
		id_us_plus((ID *)ma_obdata);
	}
	else {
		BKE_material_clear_id(bmain, obdata, true);
		BKE_material_resize_object(bmain, ob, 0, true);
		BKE_material_resize_id(bmain, obdata, 0, true);
	}
}

static bool mesh_separate_material(Main *bmain, Scene *scene, ViewLayer *view_layer, Base *base_old, BMesh *bm_old)
{
	BMFace *f_cmp, *f;
	BMIter iter;
	bool result = false;

	while ((f_cmp = BM_iter_at_index(bm_old, BM_FACES_OF_MESH, NULL, 0))) {
		Base *base_new;
		const short mat_nr = f_cmp->mat_nr;
		int tot = 0;

		BM_mesh_elem_hflag_disable_all(bm_old, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_TAG, false);

		BM_ITER_MESH (f, &iter, bm_old, BM_FACES_OF_MESH) {
			if (f->mat_nr == mat_nr) {
				BMLoop *l_iter;
				BMLoop *l_first;

				BM_elem_flag_enable(f, BM_ELEM_TAG);
				l_iter = l_first = BM_FACE_FIRST_LOOP(f);
				do {
					BM_elem_flag_enable(l_iter->v, BM_ELEM_TAG);
					BM_elem_flag_enable(l_iter->e, BM_ELEM_TAG);
				} while ((l_iter = l_iter->next) != l_first);

				tot++;
			}
		}

		/* leave the current object with some materials */
		if (tot == bm_old->totface) {
			mesh_separate_material_assign_mat_nr(bmain, base_old->object, mat_nr);

			/* since we're in editmode, must set faces here */
			BM_ITER_MESH (f, &iter, bm_old, BM_FACES_OF_MESH) {
				f->mat_nr = 0;
			}
			break;
		}

		/* Move selection into a separate object */
		base_new = mesh_separate_tagged(bmain, scene, view_layer, base_old, bm_old);
		if (base_new) {
			mesh_separate_material_assign_mat_nr(bmain, base_new->object, mat_nr);
		}

		result |= (base_new != NULL);
	}

	return result;
}

static bool mesh_separate_loose(Main *bmain, Scene *scene, ViewLayer *view_layer, Base *base_old, BMesh *bm_old)
{
	int i;
	BMEdge *e;
	BMVert *v_seed;
	BMWalker walker;
	bool result = false;
	int max_iter = bm_old->totvert;

	/* Clear all selected vertices */
	BM_mesh_elem_hflag_disable_all(bm_old, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_TAG, false);

	/* A "while (true)" loop should work here as each iteration should
	 * select and remove at least one vertex and when all vertices
	 * are selected the loop will break out. But guard against bad
	 * behavior by limiting iterations to the number of vertices in the
	 * original mesh.*/
	for (i = 0; i < max_iter; i++) {
		int tot = 0;
		/* Get a seed vertex to start the walk */
		v_seed = BM_iter_at_index(bm_old, BM_VERTS_OF_MESH, NULL, 0);

		/* No vertices available, can't do anything */
		if (v_seed == NULL) {
			break;
		}

		/* Select the seed explicitly, in case it has no edges */
		if (!BM_elem_flag_test(v_seed, BM_ELEM_TAG)) { BM_elem_flag_enable(v_seed, BM_ELEM_TAG); tot++; }

		/* Walk from the single vertex, selecting everything connected
		 * to it */
		BMW_init(&walker, bm_old, BMW_VERT_SHELL,
		         BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
		         BMW_FLAG_NOP,
		         BMW_NIL_LAY);

		for (e = BMW_begin(&walker, v_seed); e; e = BMW_step(&walker)) {
			if (!BM_elem_flag_test(e->v1, BM_ELEM_TAG)) { BM_elem_flag_enable(e->v1, BM_ELEM_TAG); tot++; }
			if (!BM_elem_flag_test(e->v2, BM_ELEM_TAG)) { BM_elem_flag_enable(e->v2, BM_ELEM_TAG); tot++; }
		}
		BMW_end(&walker);

		if (bm_old->totvert == tot) {
			/* Every vertex selected, nothing to separate, work is done */
			break;
		}

		/* Flush the selection to get edge/face selections matching
		 * the vertex selection */
		bm_mesh_hflag_flush_vert(bm_old, BM_ELEM_TAG);

		/* Move selection into a separate object */
		result |= (mesh_separate_tagged(bmain, scene, view_layer, base_old, bm_old) != NULL);
	}

	return result;
}

static int edbm_separate_exec(bContext *C, wmOperator *op)
{
	Main *bmain = CTX_data_main(C);
	Scene *scene = CTX_data_scene(C);
	ViewLayer *view_layer = CTX_data_view_layer(C);
	const int type = RNA_enum_get(op->ptr, "type");
	int retval = 0;

	if (ED_operator_editmesh(C)) {
		uint bases_len = 0;
		uint empty_selection_len = 0;
		Base **bases = BKE_view_layer_array_from_bases_in_edit_mode_unique_data(view_layer, &bases_len);
		for (uint bs_index = 0; bs_index < bases_len; bs_index++) {
			Base *base = bases[bs_index];
			BMEditMesh *em = BKE_editmesh_from_object(base->object);

			if (type == 0) {
				if ((em->bm->totvertsel == 0) &&
				    (em->bm->totedgesel == 0) &&
				    (em->bm->totfacesel == 0))
				{
					/* when all objects has no selection */
					if (++empty_selection_len == bases_len) {
						BKE_report(op->reports, RPT_ERROR, "Nothing selected");
					}
					continue;
				}
			}

			/* editmode separate */
			switch (type) {
				case MESH_SEPARATE_SELECTED:
					retval = mesh_separate_selected(bmain, scene, view_layer, base, em->bm);
					break;
				case MESH_SEPARATE_MATERIAL:
					retval = mesh_separate_material(bmain, scene, view_layer, base, em->bm);
					break;
				case MESH_SEPARATE_LOOSE:
					retval = mesh_separate_loose(bmain, scene, view_layer, base, em->bm);
					break;
				default:
					BLI_assert(0);
					break;
			}

			if (retval) {
				EDBM_update_generic(em, true, true);
			}
		}
		MEM_freeN(bases);
	}
	else {
		if (type == MESH_SEPARATE_SELECTED) {
			BKE_report(op->reports, RPT_ERROR, "Selection not supported in object mode");
			return OPERATOR_CANCELLED;
		}

		/* object mode separate */
		CTX_DATA_BEGIN(C, Base *, base_iter, selected_editable_bases)
		{
			Object *ob = base_iter->object;
			if (ob->type == OB_MESH) {
				Mesh *me = ob->data;
				if (!ID_IS_LINKED(me)) {
					BMesh *bm_old = NULL;
					int retval_iter = 0;

					bm_old = BM_mesh_create(
					        &bm_mesh_allocsize_default,
					        &((struct BMeshCreateParams){.use_toolflags = true,}));

					BM_mesh_bm_from_me(bm_old, me, (&(struct BMeshFromMeshParams){0}));

					switch (type) {
						case MESH_SEPARATE_MATERIAL:
							retval_iter = mesh_separate_material(bmain, scene, view_layer, base_iter, bm_old);
							break;
						case MESH_SEPARATE_LOOSE:
							retval_iter = mesh_separate_loose(bmain, scene, view_layer, base_iter, bm_old);
							break;
						default:
							BLI_assert(0);
							break;
					}

					if (retval_iter) {
						BM_mesh_bm_to_me(
						        bmain, bm_old, me,
						        (&(struct BMeshToMeshParams){
						            .calc_object_remap = true,
						        }));

						DEG_id_tag_update(&me->id, OB_RECALC_DATA);
						WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
					}

					BM_mesh_free(bm_old);

					retval |= retval_iter;
				}
			}
		}
		CTX_DATA_END;
	}

	if (retval) {
		/* delay depsgraph recalc until all objects are duplicated */
		DEG_relations_tag_update(bmain);
		WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, NULL);

		return OPERATOR_FINISHED;
	}

	return OPERATOR_CANCELLED;
}

void MESH_OT_separate(wmOperatorType *ot)
{
	static const EnumPropertyItem prop_separate_types[] = {
		{MESH_SEPARATE_SELECTED, "SELECTED", 0, "Selection", ""},
		{MESH_SEPARATE_MATERIAL, "MATERIAL", 0, "By Material", ""},
		{MESH_SEPARATE_LOOSE, "LOOSE", 0, "By loose parts", ""},
		{0, NULL, 0, NULL, NULL}
	};

	/* identifiers */
	ot->name = "Separate";
	ot->description = "Separate selected geometry into a new mesh";
	ot->idname = "MESH_OT_separate";

	/* api callbacks */
	ot->invoke = WM_menu_invoke;
	ot->exec = edbm_separate_exec;
	ot->poll = ED_operator_scene_editable; /* object and editmode */

	/* flags */
	ot->flag = OPTYPE_UNDO;

	ot->prop = RNA_def_enum(ot->srna, "type", prop_separate_types, MESH_SEPARATE_SELECTED, "Type", "");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Triangle Fill Operator
 * \{ */

static int edbm_fill_exec(bContext *C, wmOperator *op)
{
	const bool use_beauty = RNA_boolean_get(op->ptr, "use_beauty");

	bool has_selected_edges = false, has_faces_filled = false;

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		const int totface_orig = em->bm->totface;

		if (em->bm->totedgesel == 0) {
			continue;
		}
		has_selected_edges = true;

		BMOperator bmop;
		if (!EDBM_op_init(
		            em, &bmop, op,
		            "triangle_fill edges=%he use_beauty=%b",
		            BM_ELEM_SELECT, use_beauty))
		{
			continue;
		}

		BMO_op_exec(em->bm, &bmop);

		/* cancel if nothing was done */
		if (totface_orig == em->bm->totface) {
			EDBM_op_finish(em, &bmop, op, true);
			continue;
		}
		has_faces_filled = true;

		/* select new geometry */
		BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "geom.out", BM_FACE | BM_EDGE, BM_ELEM_SELECT, true);

		if (!EDBM_op_finish(em, &bmop, op, true)) {
			continue;
		}

		EDBM_update_generic(em, true, true);
	}
	MEM_freeN(objects);

	if (!has_selected_edges) {
		BKE_report(op->reports, RPT_ERROR, "No edges selected");
		return OPERATOR_CANCELLED;
	}

	if (!has_faces_filled) {
		BKE_report(op->reports, RPT_WARNING, "No faces filled");
		return OPERATOR_CANCELLED;
	}

	return OPERATOR_FINISHED;
}

void MESH_OT_fill(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Fill";
	ot->idname = "MESH_OT_fill";
	ot->description = "Fill a selected edge loop with faces";

	/* api callbacks */
	ot->exec = edbm_fill_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	RNA_def_boolean(ot->srna, "use_beauty", true, "Beauty", "Use best triangulation division");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Grid Fill Operator
 * \{ */

static bool bm_edge_test_fill_grid_cb(BMEdge *e, void *UNUSED(bm_v))
{
	return BM_elem_flag_test_bool(e, BM_ELEM_TAG);
}

static float edbm_fill_grid_vert_tag_angle(BMVert *v)
{
	BMIter iter;
	BMEdge *e_iter;
	BMVert *v_pair[2];
	int i = 0;
	BM_ITER_ELEM (e_iter, &iter, v, BM_EDGES_OF_VERT) {
		if (BM_elem_flag_test(e_iter, BM_ELEM_TAG)) {
			v_pair[i++] = BM_edge_other_vert(e_iter, v);
		}
	}
	BLI_assert(i == 2);

	return fabsf((float)M_PI - angle_v3v3v3(v_pair[0]->co, v->co, v_pair[1]->co));
}

/**
 * non-essential utility function to select 2 open edge loops from a closed loop.
 */
static void edbm_fill_grid_prepare(BMesh *bm, int offset, int *r_span, bool span_calc)
{
	/* angle differences below this value are considered 'even'
	 * in that they shouldn't be used to calculate corners used for the 'span' */
	const float eps_even = 1e-3f;
	BMEdge *e;
	BMIter iter;
	int count;
	int span = *r_span;

	ListBase eloops = {NULL};
	struct BMEdgeLoopStore *el_store;
	// LinkData *el_store;

	/* select -> tag */
	BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
		BM_elem_flag_set(e, BM_ELEM_TAG, BM_elem_flag_test(e, BM_ELEM_SELECT));
	}

	count = BM_mesh_edgeloops_find(bm, &eloops, bm_edge_test_fill_grid_cb, bm);
	el_store = eloops.first;

	if (count == 1 && BM_edgeloop_is_closed(el_store) && (BM_edgeloop_length_get(el_store) & 1) == 0) {
		/* be clever! detect 2 edge loops from one closed edge loop */
		const int verts_len = BM_edgeloop_length_get(el_store);
		ListBase *verts = BM_edgeloop_verts_get(el_store);
		BMVert *v_act = BM_mesh_active_vert_get(bm);
		LinkData *v_act_link;
		BMEdge **edges = MEM_mallocN(sizeof(*edges) * verts_len, __func__);
		int i;

		if (v_act && (v_act_link = BLI_findptr(verts, v_act, offsetof(LinkData, data)))) {
			/* pass */
		}
		else {
			/* find the vertex with the best angle (a corner vertex) */
			LinkData *v_link, *v_link_best = NULL;
			float angle_best = -1.0f;
			for (v_link = verts->first; v_link; v_link = v_link->next) {
				const float angle = edbm_fill_grid_vert_tag_angle(v_link->data);
				if ((angle > angle_best) || (v_link_best == NULL)) {
					angle_best = angle;
					v_link_best = v_link;
				}
			}

			v_act_link = v_link_best;
			v_act = v_act_link->data;
		}

		/* set this vertex first */
		BLI_listbase_rotate_first(verts, v_act_link);

		if (offset != 0) {
			v_act_link = BLI_findlink(verts, offset);
			v_act = v_act_link->data;
			BLI_listbase_rotate_first(verts, v_act_link);
		}

		BM_edgeloop_edges_get(el_store, edges);


		if (span_calc) {
			/* calculate the span by finding the next corner in 'verts'
			 * we dont know what defines a corner exactly so find the 4 verts
			 * in the loop with the greatest angle.
			 * Tag them and use the first tagged vertex to calculate the span.
			 *
			 * note: we may have already checked 'edbm_fill_grid_vert_tag_angle()' on each
			 * vert, but advantage of de-duplicating is minimal. */
			struct SortPtrByFloat *ele_sort = MEM_mallocN(sizeof(*ele_sort) * verts_len, __func__);
			LinkData *v_link;
			for (v_link = verts->first, i = 0; v_link; v_link = v_link->next, i++) {
				BMVert *v = v_link->data;
				const float angle = edbm_fill_grid_vert_tag_angle(v);
				ele_sort[i].sort_value = angle;
				ele_sort[i].data = v;

				BM_elem_flag_disable(v, BM_ELEM_TAG);
			}

			qsort(ele_sort, verts_len, sizeof(*ele_sort), BLI_sortutil_cmp_float_reverse);

			/* check that we have at least 3 corners,
			 * if the angle on the 3rd angle is roughly the same as the last,
			 * then we can't calculate 3+ corners - fallback to the even span. */
			if ((ele_sort[2].sort_value - ele_sort[verts_len - 1].sort_value) > eps_even) {
				for (i = 0; i < 4; i++) {
					BMVert *v = ele_sort[i].data;
					BM_elem_flag_enable(v, BM_ELEM_TAG);
				}

				/* now find the first... */
				for (v_link = verts->first, i = 0; i < verts_len / 2; v_link = v_link->next, i++) {
					BMVert *v = v_link->data;
					if (BM_elem_flag_test(v, BM_ELEM_TAG)) {
						if (v != v_act) {
							span = i;
							break;
						}
					}
				}
			}
			MEM_freeN(ele_sort);
		}
		/* end span calc */


		/* un-flag 'rails' */
		for (i = 0; i < span; i++) {
			BM_elem_flag_disable(edges[i], BM_ELEM_TAG);
			BM_elem_flag_disable(edges[(verts_len / 2) + i], BM_ELEM_TAG);
		}
		MEM_freeN(edges);
	}
	/* else let the bmesh-operator handle it */

	BM_mesh_edgeloops_free(&eloops);

	*r_span = span;
}

static int edbm_fill_grid_exec(bContext *C, wmOperator *op)
{
	const bool use_prepare = true;
	const bool use_interp_simple = RNA_boolean_get(op->ptr, "use_interp_simple");

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {

		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		const bool use_smooth = edbm_add_edge_face__smooth_get(em->bm);
		const int totedge_orig = em->bm->totedge;
		const int totface_orig = em->bm->totface;

		if (em->bm->totedgesel == 0) {
			continue;
		}

		if (use_prepare) {
			/* use when we have a single loop selected */
			PropertyRNA *prop_span = RNA_struct_find_property(op->ptr, "span");
			PropertyRNA *prop_offset = RNA_struct_find_property(op->ptr, "offset");
			bool calc_span;

			const int clamp = em->bm->totvertsel;
			int span;
			int offset;

			if (RNA_property_is_set(op->ptr, prop_span)) {
				span = RNA_property_int_get(op->ptr, prop_span);
				span = min_ii(span, (clamp / 2) - 1);
				calc_span = false;
			}
			else {
				span = clamp / 4;
				calc_span = true;
			}

			offset = RNA_property_int_get(op->ptr, prop_offset);
			offset = clamp ? mod_i(offset, clamp) : 0;

			/* in simple cases, move selection for tags, but also support more advanced cases */
			edbm_fill_grid_prepare(em->bm, offset, &span, calc_span);

			RNA_property_int_set(op->ptr, prop_span, span);
		}
		/* end tricky prepare code */

		BMOperator bmop;
		if (!EDBM_op_init(
		            em, &bmop, op,
		            "grid_fill edges=%he mat_nr=%i use_smooth=%b use_interp_simple=%b",
		            use_prepare ? BM_ELEM_TAG : BM_ELEM_SELECT,
		            em->mat_nr, use_smooth, use_interp_simple))
		{
			continue;
		}

		BMO_op_exec(em->bm, &bmop);

		/* NOTE: EDBM_op_finish() will change bmesh pointer inside of edit mesh,
		 * so need to tell evaluated objects to sync new bmesh pointer to their
		 * edit mesh structures.
		 */
		DEG_id_tag_update(&obedit->id, 0);

		/* cancel if nothing was done */
		if ((totedge_orig == em->bm->totedge) &&
		    (totface_orig == em->bm->totface))
		{
			EDBM_op_finish(em, &bmop, op, true);
			continue;
		}

		BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true);

		if (!EDBM_op_finish(em, &bmop, op, true)) {
			continue;
		}

		EDBM_update_generic(em, true, true);
	}

	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_fill_grid(wmOperatorType *ot)
{
	PropertyRNA *prop;

	/* identifiers */
	ot->name = "Grid Fill";
	ot->description = "Fill grid from two loops";
	ot->idname = "MESH_OT_fill_grid";

	/* api callbacks */
	ot->exec = edbm_fill_grid_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* properties */
	prop = RNA_def_int(ot->srna, "span", 1, 1, 1000, "Span", "Number of grid columns", 1, 100);
	RNA_def_property_flag(prop, PROP_SKIP_SAVE);
	prop = RNA_def_int(ot->srna, "offset", 0, -1000, 1000, "Offset",
	                             "Vertex that is the corner of the grid", -100, 100);
	RNA_def_property_flag(prop, PROP_SKIP_SAVE);
	RNA_def_boolean(ot->srna, "use_interp_simple", false, "Simple Blending",
	                          "Use simple interpolation of grid vertices");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Hole Fill Operator
 * \{ */

static int edbm_fill_holes_exec(bContext *C, wmOperator *op)
{
	const int sides = RNA_int_get(op->ptr, "sides");

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totedgesel == 0) {
			continue;
		}

		if (!EDBM_op_call_and_selectf(
		            em, op,
		            "faces.out", true,
		            "holes_fill edges=%he sides=%i",
		            BM_ELEM_SELECT, sides))
		{
			continue;
		}

		EDBM_update_generic(em, true, true);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;

}

void MESH_OT_fill_holes(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Fill Holes";
	ot->idname = "MESH_OT_fill_holes";
	ot->description = "Fill in holes (boundary edge loops)";

	/* api callbacks */
	ot->exec = edbm_fill_holes_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	RNA_def_int(ot->srna, "sides", 4, 0, 1000,
	            "Sides", "Number of sides in hole required to fill (zero fills all holes)", 0, 100);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Beauty Fill Operator
 * \{ */

static int edbm_beautify_fill_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	const float angle_max = M_PI;
	const float angle_limit = RNA_float_get(op->ptr, "angle_limit");
	char hflag;

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totfacesel == 0) {
			continue;
		}

		if (angle_limit >= angle_max) {
			hflag = BM_ELEM_SELECT;
		}
		else {
			BMIter iter;
			BMEdge *e;

			BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
				BM_elem_flag_set(
				        e, BM_ELEM_TAG,
				        (BM_elem_flag_test(e, BM_ELEM_SELECT) &&
				         BM_edge_calc_face_angle_ex(e, angle_max) < angle_limit));

			}
			hflag = BM_ELEM_TAG;
		}

		if (!EDBM_op_call_and_selectf(
		        em, op, "geom.out", true,
		        "beautify_fill faces=%hf edges=%he",
		        BM_ELEM_SELECT, hflag))
		{
			continue;
		}

		EDBM_update_generic(em, true, true);
	}

	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_beautify_fill(wmOperatorType *ot)
{
	PropertyRNA *prop;

	/* identifiers */
	ot->name = "Beautify Faces";
	ot->idname = "MESH_OT_beautify_fill";
	ot->description = "Rearrange some faces to try to get less degenerated geometry";

	/* api callbacks */
	ot->exec = edbm_beautify_fill_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* props */
	prop = RNA_def_float_rotation(ot->srna, "angle_limit", 0, NULL, 0.0f, DEG2RADF(180.0f),
	                              "Max Angle", "Angle limit", 0.0f, DEG2RADF(180.0f));
	RNA_def_property_float_default(prop, DEG2RADF(180.0f));
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Poke Face Operator
 * \{ */

static int edbm_poke_face_exec(bContext *C, wmOperator *op)
{
	const float offset = RNA_float_get(op->ptr, "offset");
	const bool use_relative_offset = RNA_boolean_get(op->ptr, "use_relative_offset");
	const int center_mode = RNA_enum_get(op->ptr, "center_mode");

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totfacesel == 0) {
			continue;
		}

		BMOperator bmop;
		EDBM_op_init(em, &bmop, op, "poke faces=%hf offset=%f use_relative_offset=%b center_mode=%i",
		             BM_ELEM_SELECT, offset, use_relative_offset, center_mode);
		BMO_op_exec(em->bm, &bmop);

		EDBM_flag_disable_all(em, BM_ELEM_SELECT);

		BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "verts.out", BM_VERT, BM_ELEM_SELECT, true);
		BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true);

		if (!EDBM_op_finish(em, &bmop, op, true)) {
			continue;
		}

		EDBM_mesh_normals_update(em);

		EDBM_update_generic(em, true, true);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;

}

void MESH_OT_poke(wmOperatorType *ot)
{
	static const EnumPropertyItem poke_center_modes[] = {
		{BMOP_POKE_MEAN_WEIGHTED, "MEAN_WEIGHTED", 0, "Weighted Mean", "Weighted Mean Face Center"},
		{BMOP_POKE_MEAN, "MEAN", 0, "Mean", "Mean Face Center"},
		{BMOP_POKE_BOUNDS, "BOUNDS", 0, "Bounds", "Face Bounds Center"},
		{0, NULL, 0, NULL, NULL}};


	/* identifiers */
	ot->name = "Poke Faces";
	ot->idname = "MESH_OT_poke";
	ot->description = "Split a face into a fan";

	/* api callbacks */
	ot->exec = edbm_poke_face_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	RNA_def_float_distance(ot->srna, "offset", 0.0f, -1e3f, 1e3f, "Poke Offset", "Poke Offset", -1.0f, 1.0f);
	RNA_def_boolean(ot->srna, "use_relative_offset", false, "Offset Relative", "Scale the offset by surrounding geometry");
	RNA_def_enum(ot->srna, "center_mode", poke_center_modes, BMOP_POKE_MEAN_WEIGHTED,
	             "Poke Center", "Poke Face Center Calculation");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Triangulate Face Operator
 * \{ */

static int edbm_quads_convert_to_tris_exec(bContext *C, wmOperator *op)
{
	const int quad_method = RNA_enum_get(op->ptr, "quad_method");
	const int ngon_method = RNA_enum_get(op->ptr, "ngon_method");
	ViewLayer *view_layer = CTX_data_view_layer(C);

	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totfacesel == 0) {
			continue;
		}

		BMOperator bmop;
		BMOIter oiter;
		BMFace *f;

		EDBM_op_init(
		        em, &bmop, op,
		        "triangulate faces=%hf quad_method=%i ngon_method=%i",
		        BM_ELEM_SELECT, quad_method, ngon_method);
		BMO_op_exec(em->bm, &bmop);

		/* select the output */
		BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true);

		/* remove the doubles */
		BMO_ITER (f, &oiter, bmop.slots_out, "face_map_double.out", BM_FACE) {
			BM_face_kill(em->bm, f);
		}

		EDBM_selectmode_flush(em);

		if (!EDBM_op_finish(em, &bmop, op, true)) {
			continue;
		}

		EDBM_update_generic(em, true, true);
	}

	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}


void MESH_OT_quads_convert_to_tris(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Triangulate Faces";
	ot->idname = "MESH_OT_quads_convert_to_tris";
	ot->description = "Triangulate selected faces";

	/* api callbacks */
	ot->exec = edbm_quads_convert_to_tris_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	RNA_def_enum(ot->srna, "quad_method", rna_enum_modifier_triangulate_quad_method_items, MOD_TRIANGULATE_QUAD_BEAUTY,
	             "Quad Method", "Method for splitting the quads into triangles");
	RNA_def_enum(ot->srna, "ngon_method", rna_enum_modifier_triangulate_ngon_method_items, MOD_TRIANGULATE_NGON_BEAUTY,
	             "Polygon Method", "Method for splitting the polygons into triangles");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Convert to Quads Operator
 * \{ */

static int edbm_tris_convert_to_quads_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);

	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	bool is_face_pair;

	{
		int totelem_sel[3];
		EDBM_mesh_stats_multi(objects, objects_len, NULL, totelem_sel);
		is_face_pair = (totelem_sel[2] == 2);
	}

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];

		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		bool do_seam, do_sharp, do_uvs, do_vcols, do_materials;
		float angle_face_threshold, angle_shape_threshold;
		PropertyRNA *prop;

		/* When joining exactly 2 faces, no limit.
		 * this is useful for one off joins while editing. */
		prop = RNA_struct_find_property(op->ptr, "face_threshold");
		if (is_face_pair &&
		    (RNA_property_is_set(op->ptr, prop) == false))
		{
			angle_face_threshold = DEG2RADF(180.0f);
		}
		else {
			angle_face_threshold = RNA_property_float_get(op->ptr, prop);
		}

		prop = RNA_struct_find_property(op->ptr, "shape_threshold");
		if (is_face_pair &&
		    (RNA_property_is_set(op->ptr, prop) == false))
		{
			angle_shape_threshold = DEG2RADF(180.0f);
		}
		else {
			angle_shape_threshold = RNA_property_float_get(op->ptr, prop);
		}

		do_seam = RNA_boolean_get(op->ptr, "seam");
		do_sharp = RNA_boolean_get(op->ptr, "sharp");
		do_uvs = RNA_boolean_get(op->ptr, "uvs");
		do_vcols = RNA_boolean_get(op->ptr, "vcols");
		do_materials = RNA_boolean_get(op->ptr, "materials");

		if (!EDBM_op_call_and_selectf(
		        em, op,
		        "faces.out", true,
		        "join_triangles faces=%hf angle_face_threshold=%f angle_shape_threshold=%f "
		        "cmp_seam=%b cmp_sharp=%b cmp_uvs=%b cmp_vcols=%b cmp_materials=%b",
		        BM_ELEM_SELECT, angle_face_threshold, angle_shape_threshold,
		        do_seam, do_sharp, do_uvs, do_vcols, do_materials))
		{
			continue;
		}

		EDBM_update_generic(em, true, true);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

static void join_triangle_props(wmOperatorType *ot)
{
	PropertyRNA *prop;

	prop = RNA_def_float_rotation(
	        ot->srna, "face_threshold", 0, NULL, 0.0f, DEG2RADF(180.0f),
	        "Max Face Angle", "Face angle limit", 0.0f, DEG2RADF(180.0f));
	RNA_def_property_float_default(prop, DEG2RADF(40.0f));

	prop = RNA_def_float_rotation(
	        ot->srna, "shape_threshold", 0, NULL, 0.0f, DEG2RADF(180.0f),
	        "Max Shape Angle", "Shape angle limit", 0.0f, DEG2RADF(180.0f));
	RNA_def_property_float_default(prop, DEG2RADF(40.0f));

	RNA_def_boolean(ot->srna, "uvs", false, "Compare UVs", "");
	RNA_def_boolean(ot->srna, "vcols", false, "Compare VCols", "");
	RNA_def_boolean(ot->srna, "seam", false, "Compare Seam", "");
	RNA_def_boolean(ot->srna, "sharp", false, "Compare Sharp", "");
	RNA_def_boolean(ot->srna, "materials", false, "Compare Materials", "");
}

void MESH_OT_tris_convert_to_quads(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Tris to Quads";
	ot->idname = "MESH_OT_tris_convert_to_quads";
	ot->description = "Join triangles into quads";

	/* api callbacks */
	ot->exec = edbm_tris_convert_to_quads_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	join_triangle_props(ot);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Decimate Operator
 *
 * \note The function to decimate is intended for use as a modifier,
 * while its handy allow access as a tool - this does cause access to be a little awkward
 * (passing selection as weights for eg).
 *
 * \{ */

static int edbm_decimate_exec(bContext *C, wmOperator *op)
{
	const float ratio = RNA_float_get(op->ptr, "ratio");
	bool use_vertex_group = RNA_boolean_get(op->ptr, "use_vertex_group");
	const float vertex_group_factor = RNA_float_get(op->ptr, "vertex_group_factor");
	const bool invert_vertex_group = RNA_boolean_get(op->ptr, "invert_vertex_group");
	const bool use_symmetry = RNA_boolean_get(op->ptr, "use_symmetry");
	const float symmetry_eps = 0.00002f;
	const int symmetry_axis = use_symmetry ? RNA_enum_get(op->ptr, "symmetry_axis") : -1;

	/* nop */
	if (ratio == 1.0f) {
		return OPERATOR_FINISHED;
	}

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		BMesh *bm = em->bm;
		if (bm->totedgesel == 0) {
			continue;
		}

		float *vweights = MEM_mallocN(sizeof(*vweights) * bm->totvert, __func__);
		{
			const int cd_dvert_offset = CustomData_get_offset(&bm->vdata, CD_MDEFORMVERT);
			const int defbase_act = obedit->actdef - 1;

			if (use_vertex_group && (cd_dvert_offset == -1)) {
				BKE_report(op->reports, RPT_WARNING, "No active vertex group");
				use_vertex_group = false;
			}

			BMIter iter;
			BMVert *v;
			int i;
			BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) {
				float weight = 0.0f;
				if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
					if (use_vertex_group) {
						const MDeformVert *dv = BM_ELEM_CD_GET_VOID_P(v, cd_dvert_offset);
						weight = defvert_find_weight(dv, defbase_act);
						if (invert_vertex_group) {
							weight = 1.0f - weight;
						}
					}
					else {
						weight = 1.0f;
					}
				}

				vweights[i] = weight;
				BM_elem_index_set(v, i); /* set_inline */
			}
			bm->elem_index_dirty &= ~BM_VERT;
		}

		float ratio_adjust;

		if ((bm->totface == bm->totfacesel) || (ratio == 0.0f)) {
			ratio_adjust = ratio;
		}
		else {
			/**
			 * Calculate a new ratio based on faces that could be remoevd during decimation.
			 * needed so 0..1 has a meaningful range when operating on the selection.
			 *
			 * This doesn't have to be totally accurate,
			 * but needs to be greater than the number of selected faces
			 */

			int totface_basis = 0;
			int totface_adjacent = 0;
			BMIter iter;
			BMFace *f;
			BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
				/* count faces during decimation, ngons are triangulated */
				const int f_len = f->len > 4 ? (f->len - 2) : 1;
				totface_basis += f_len;

				BMLoop *l_iter, *l_first;
				l_iter = l_first = BM_FACE_FIRST_LOOP(f);
				do {
					if (vweights[BM_elem_index_get(l_iter->v)] != 0.0f) {
						totface_adjacent += f_len;
						break;
					}
				} while ((l_iter = l_iter->next) != l_first);
			}

			ratio_adjust = ratio;
			ratio_adjust = 1.0f - ratio_adjust;
			ratio_adjust *= (float)totface_adjacent / (float)totface_basis;
			ratio_adjust = 1.0f - ratio_adjust;
		}

		BM_mesh_decimate_collapse(
		        em->bm, ratio_adjust, vweights, vertex_group_factor, false,
		        symmetry_axis, symmetry_eps);

		MEM_freeN(vweights);

		{
			short selectmode = em->selectmode;
			if ((selectmode & (SCE_SELECT_VERTEX | SCE_SELECT_EDGE)) == 0) {
				/* ensure we flush edges -> faces */
				selectmode |= SCE_SELECT_EDGE;
			}
			EDBM_selectmode_flush_ex(em, selectmode);
		}
		EDBM_update_generic(em, true, true);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}


static bool edbm_decimate_check(bContext *UNUSED(C), wmOperator *UNUSED(op))
{
	return true;
}


static void edbm_decimate_ui(bContext *UNUSED(C), wmOperator *op)
{
	uiLayout *layout = op->layout, *box, *row, *col;
	PointerRNA ptr;

	RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr);

	uiItemR(layout, &ptr, "ratio", 0, NULL, ICON_NONE);

	box = uiLayoutBox(layout);
	uiItemR(box, &ptr, "use_vertex_group", 0, NULL, ICON_NONE);
	col = uiLayoutColumn(box, false);
	uiLayoutSetActive(col, RNA_boolean_get(&ptr, "use_vertex_group"));
	uiItemR(col, &ptr, "vertex_group_factor", 0, NULL, ICON_NONE);
	uiItemR(col, &ptr, "invert_vertex_group", 0, NULL, ICON_NONE);

	box = uiLayoutBox(layout);
	uiItemR(box, &ptr, "use_symmetry", 0, NULL, ICON_NONE);
	row = uiLayoutRow(box, true);
	uiLayoutSetActive(row, RNA_boolean_get(&ptr, "use_symmetry"));
	uiItemR(row, &ptr, "symmetry_axis", UI_ITEM_R_EXPAND, NULL, ICON_NONE);
}


void MESH_OT_decimate(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Decimate Geometry";
	ot->idname = "MESH_OT_decimate";
	ot->description = "Simplify geometry by collapsing edges";

	/* api callbacks */
	ot->exec = edbm_decimate_exec;
	ot->check = edbm_decimate_check;
	ot->ui = edbm_decimate_ui;
	ot->poll = ED_operator_editmesh;


	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* Note, keep in sync with 'rna_def_modifier_decimate' */
	RNA_def_float(ot->srna, "ratio", 1.0f, 0.0f, 1.0f, "Ratio", "", 0.0f, 1.0f);

	RNA_def_boolean(ot->srna, "use_vertex_group", false, "Vertex Group",
	                "Use active vertex group as an influence");
	RNA_def_float(ot->srna, "vertex_group_factor", 1.0f, 0.0f, 1000.0f, "Weight",
	              "Vertex group strength", 0.0f, 10.0f);
	RNA_def_boolean(ot->srna, "invert_vertex_group", false, "Invert",
	                "Invert vertex group influence");

	RNA_def_boolean(ot->srna, "use_symmetry", false, "Symmetry",
	                "Maintain symmetry on an axis");

	RNA_def_enum(ot->srna, "symmetry_axis", rna_enum_axis_xyz_items, 1, "Axis", "Axis of symmetry");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Dissolve Vertices Operator
 * \{ */

static void edbm_dissolve_prop__use_verts(wmOperatorType *ot, bool value, int flag)
{
	PropertyRNA *prop;

	prop = RNA_def_boolean(ot->srna, "use_verts", value, "Dissolve Verts",
	                       "Dissolve remaining vertices");

	if (flag) {
		RNA_def_property_flag(prop, flag);
	}
}
static void edbm_dissolve_prop__use_face_split(wmOperatorType *ot)
{
	RNA_def_boolean(ot->srna, "use_face_split", false, "Face Split",
	                "Split off face corners to maintain surrounding geometry");
}
static void edbm_dissolve_prop__use_boundary_tear(wmOperatorType *ot)
{
	RNA_def_boolean(ot->srna, "use_boundary_tear", false, "Tear Boundary",
	                "Split off face corners instead of merging faces");
}

static int edbm_dissolve_verts_exec(bContext *C, wmOperator *op)
{
	const bool use_face_split = RNA_boolean_get(op->ptr, "use_face_split");
	const bool use_boundary_tear = RNA_boolean_get(op->ptr, "use_boundary_tear");

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totvertsel == 0) {
			continue;
		}

		if (!EDBM_op_callf(
		            em, op,
		            "dissolve_verts verts=%hv use_face_split=%b use_boundary_tear=%b",
		            BM_ELEM_SELECT, use_face_split, use_boundary_tear))
		{
			continue;
		}
		EDBM_update_generic(em, true, true);
	}

	MEM_freeN(objects);
	return OPERATOR_FINISHED;
}

void MESH_OT_dissolve_verts(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Dissolve Vertices";
	ot->description = "Dissolve verts, merge edges and faces";
	ot->idname = "MESH_OT_dissolve_verts";

	/* api callbacks */
	ot->exec = edbm_dissolve_verts_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	edbm_dissolve_prop__use_face_split(ot);
	edbm_dissolve_prop__use_boundary_tear(ot);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Dissolve Edges Operator
 * \{ */

static int edbm_dissolve_edges_exec(bContext *C, wmOperator *op)
{
	const bool use_verts = RNA_boolean_get(op->ptr, "use_verts");
	const bool use_face_split = RNA_boolean_get(op->ptr, "use_face_split");

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totedgesel == 0) {
			continue;
		}

		if (!EDBM_op_callf(
		        em, op,
		        "dissolve_edges edges=%he use_verts=%b use_face_split=%b",
		        BM_ELEM_SELECT, use_verts, use_face_split))
		{
			continue;
		}

		EDBM_update_generic(em, true, true);
	}

	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_dissolve_edges(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Dissolve Edges";
	ot->description = "Dissolve edges, merging faces";
	ot->idname = "MESH_OT_dissolve_edges";

	/* api callbacks */
	ot->exec = edbm_dissolve_edges_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	edbm_dissolve_prop__use_verts(ot, true, 0);
	edbm_dissolve_prop__use_face_split(ot);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Dissolve Faces Operator
 * \{ */

static int edbm_dissolve_faces_exec(bContext *C, wmOperator *op)
{
	const bool use_verts = RNA_boolean_get(op->ptr, "use_verts");
	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totfacesel == 0) {
			continue;
		}

		if (!EDBM_op_call_and_selectf(
		        em, op,
		        "region.out", true,
		        "dissolve_faces faces=%hf use_verts=%b",
		        BM_ELEM_SELECT, use_verts))
		{
			continue;
		}

		EDBM_update_generic(em, true, true);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_dissolve_faces(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Dissolve Faces";
	ot->description = "Dissolve faces";
	ot->idname = "MESH_OT_dissolve_faces";

	/* api callbacks */
	ot->exec = edbm_dissolve_faces_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	edbm_dissolve_prop__use_verts(ot, false, 0);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Dissolve (Context Sensitive) Operator
 * \{ */

static int edbm_dissolve_mode_exec(bContext *C, wmOperator *op)
{
	Object *obedit = CTX_data_edit_object(C);
	BMEditMesh *em = BKE_editmesh_from_object(obedit);
	PropertyRNA *prop;

	prop = RNA_struct_find_property(op->ptr, "use_verts");
	if (!RNA_property_is_set(op->ptr, prop)) {
		/* always enable in edge-mode */
		if ((em->selectmode & SCE_SELECT_FACE) == 0) {
			RNA_property_boolean_set(op->ptr, prop, true);
		}
	}

	if (em->selectmode & SCE_SELECT_VERTEX) {
		return edbm_dissolve_verts_exec(C, op);
	}
	else if (em->selectmode & SCE_SELECT_EDGE) {
		return edbm_dissolve_edges_exec(C, op);
	}
	else {
		return edbm_dissolve_faces_exec(C, op);
	}
}

void MESH_OT_dissolve_mode(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Dissolve Selection";
	ot->description = "Dissolve geometry based on the selection mode";
	ot->idname = "MESH_OT_dissolve_mode";

	/* api callbacks */
	ot->exec = edbm_dissolve_mode_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	edbm_dissolve_prop__use_verts(ot, false, PROP_SKIP_SAVE);
	edbm_dissolve_prop__use_face_split(ot);
	edbm_dissolve_prop__use_boundary_tear(ot);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Limited Dissolve Operator
 * \{ */

static int edbm_dissolve_limited_exec(bContext *C, wmOperator *op)
{
	const float angle_limit = RNA_float_get(op->ptr, "angle_limit");
	const bool use_dissolve_boundaries = RNA_boolean_get(op->ptr, "use_dissolve_boundaries");
	const int delimit = RNA_enum_get(op->ptr, "delimit");
	char dissolve_flag;

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		BMesh *bm = em->bm;

		if ((bm->totvertsel == 0) &&
		    (bm->totedgesel == 0) &&
		    (bm->totfacesel == 0))
		{
			continue;
		}

		if (em->selectmode == SCE_SELECT_FACE) {
			/* flush selection to tags and untag edges/verts with partially selected faces */
			BMIter iter;
			BMIter liter;

			BMElem *ele;
			BMFace *f;
			BMLoop *l;

			BM_ITER_MESH (ele, &iter, bm, BM_VERTS_OF_MESH) {
				BM_elem_flag_set(ele, BM_ELEM_TAG, BM_elem_flag_test(ele, BM_ELEM_SELECT));
			}
			BM_ITER_MESH (ele, &iter, bm, BM_EDGES_OF_MESH) {
				BM_elem_flag_set(ele, BM_ELEM_TAG, BM_elem_flag_test(ele, BM_ELEM_SELECT));
			}

			BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
				if (!BM_elem_flag_test(f, BM_ELEM_SELECT)) {
					BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
						BM_elem_flag_disable(l->v, BM_ELEM_TAG);
						BM_elem_flag_disable(l->e, BM_ELEM_TAG);
					}
				}
			}

			dissolve_flag = BM_ELEM_TAG;
		}
		else {
			dissolve_flag = BM_ELEM_SELECT;
		}

		EDBM_op_call_and_selectf(
		        em, op, "region.out", true,
		        "dissolve_limit edges=%he verts=%hv angle_limit=%f use_dissolve_boundaries=%b delimit=%i",
		        dissolve_flag, dissolve_flag, angle_limit, use_dissolve_boundaries, delimit);

		EDBM_update_generic(em, true, true);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_dissolve_limited(wmOperatorType *ot)
{
	PropertyRNA *prop;

	/* identifiers */
	ot->name = "Limited Dissolve";
	ot->idname = "MESH_OT_dissolve_limited";
	ot->description = "Dissolve selected edges and verts, limited by the angle of surrounding geometry";

	/* api callbacks */
	ot->exec = edbm_dissolve_limited_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	prop = RNA_def_float_rotation(ot->srna, "angle_limit", 0, NULL, 0.0f, DEG2RADF(180.0f),
	                              "Max Angle", "Angle limit", 0.0f, DEG2RADF(180.0f));
	RNA_def_property_float_default(prop, DEG2RADF(5.0f));
	RNA_def_boolean(ot->srna, "use_dissolve_boundaries", false, "All Boundaries",
	                "Dissolve all vertices inbetween face boundaries");
	RNA_def_enum_flag(ot->srna, "delimit", rna_enum_mesh_delimit_mode_items, BMO_DELIM_NORMAL, "Delimit",
	                  "Delimit dissolve operation");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Degenerate Dissolve Operator
 * \{ */

static int edbm_dissolve_degenerate_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);
	int totelem_old[3] = {0, 0, 0};
	int totelem_new[3] = {0, 0, 0};

	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		BMesh *bm = em->bm;
		totelem_old[0] += bm->totvert;
		totelem_old[1] += bm->totedge;
		totelem_old[2] += bm->totface;
	} /* objects */

	const float thresh = RNA_float_get(op->ptr, "threshold");

	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		BMesh *bm = em->bm;

		if (!EDBM_op_callf(
		        em, op,
		        "dissolve_degenerate edges=%he dist=%f",
		        BM_ELEM_SELECT, thresh))
		{
			return OPERATOR_CANCELLED;
		}

		/* tricky to maintain correct selection here, so just flush up from verts */
		EDBM_select_flush(em);

		EDBM_update_generic(em, true, true);

		totelem_new[0] += bm->totvert;
		totelem_new[1] += bm->totedge;
		totelem_new[2] += bm->totface;
	}

	edbm_report_delete_info(op->reports, totelem_old, totelem_new);

	return OPERATOR_FINISHED;
}

void MESH_OT_dissolve_degenerate(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Degenerate Dissolve";
	ot->idname = "MESH_OT_dissolve_degenerate";
	ot->description = "Dissolve zero area faces and zero length edges";

	/* api callbacks */
	ot->exec = edbm_dissolve_degenerate_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	RNA_def_float_distance(ot->srna, "threshold", 1e-4f, 1e-6f, 50.0f,  "Merge Distance",
	                       "Minimum distance between elements to merge", 1e-5f, 10.0f);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Delete Edge-Loop Operator
 * \{ */

/* internally uses dissolve */
static int edbm_delete_edgeloop_exec(bContext *C, wmOperator *op)
{
	const bool use_face_split = RNA_boolean_get(op->ptr, "use_face_split");
	ViewLayer *view_layer = CTX_data_view_layer(C);

	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totedgesel == 0) {
			continue;
		}

		/* deal with selection */
		{
			BMEdge *e;
			BMIter iter;

			BM_mesh_elem_hflag_disable_all(em->bm, BM_FACE, BM_ELEM_TAG, false);

			BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
				if (BM_elem_flag_test(e, BM_ELEM_SELECT) && e->l) {
					BMLoop *l_iter = e->l;
					do {
						BM_elem_flag_enable(l_iter->f, BM_ELEM_TAG);
					} while ((l_iter = l_iter->radial_next) != e->l);
				}
			}
		}

		if (!EDBM_op_callf(
		            em, op,
		            "dissolve_edges edges=%he use_verts=%b use_face_split=%b",
		            BM_ELEM_SELECT, true, use_face_split))
		{
			continue;
		}

		BM_mesh_elem_hflag_enable_test(em->bm, BM_FACE, BM_ELEM_SELECT, true, false, BM_ELEM_TAG);

		EDBM_selectmode_flush_ex(em, SCE_SELECT_VERTEX);

		EDBM_update_generic(em, true, true);
	}

	MEM_freeN(objects);
	return OPERATOR_FINISHED;
}

void MESH_OT_delete_edgeloop(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Delete Edge Loop";
	ot->description = "Delete an edge loop by merging the faces on each side";
	ot->idname = "MESH_OT_delete_edgeloop";

	/* api callbacks */
	ot->exec = edbm_delete_edgeloop_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	RNA_def_boolean(ot->srna, "use_face_split", true, "Face Split",
	                "Split off face corners to maintain surrounding geometry");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Split Geometry Operator
 * \{ */

static int edbm_split_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);
		if ((em->bm->totvertsel == 0) &&
		    (em->bm->totedgesel == 0) &&
		    (em->bm->totfacesel == 0))
		{
			continue;
		}
		BMOperator bmop;
		EDBM_op_init(em, &bmop, op, "split geom=%hvef use_only_faces=%b", BM_ELEM_SELECT, false);
		BMO_op_exec(em->bm, &bmop);
		BM_mesh_elem_hflag_disable_all(em->bm, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_SELECT, false);
		BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "geom.out", BM_ALL_NOLOOP, BM_ELEM_SELECT, true);

		if (!EDBM_op_finish(em, &bmop, op, true)) {
			continue;
		}

		/* Geometry has changed, need to recalc normals and looptris */
		EDBM_mesh_normals_update(em);

		EDBM_update_generic(em, true, true);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_split(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Split";
	ot->idname = "MESH_OT_split";
	ot->description = "Split off selected geometry from connected unselected geometry";

	/* api callbacks */
	ot->exec = edbm_split_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Sort Geometry Elements Operator
 *
 * Unified for vertices/edges/faces.
 *
 * \{ */

enum {
	SRT_VIEW_ZAXIS = 1,  /* Use view Z (deep) axis. */
	SRT_VIEW_XAXIS,      /* Use view X (left to right) axis. */
	SRT_CURSOR_DISTANCE, /* Use distance from element to 3D cursor. */
	SRT_MATERIAL,        /* Face only: use mat number. */
	SRT_SELECTED,        /* Move selected elements in first, without modifying
	                      * relative order of selected and unselected elements. */
	SRT_RANDOMIZE,       /* Randomize selected elements. */
	SRT_REVERSE,         /* Reverse current order of selected elements. */
};

typedef struct BMElemSort {
	float srt; /* Sort factor */
	int org_idx; /* Original index of this element _in its mempool_ */
} BMElemSort;

static int bmelemsort_comp(const void *v1, const void *v2)
{
	const BMElemSort *x1 = v1, *x2 = v2;

	return (x1->srt > x2->srt) - (x1->srt < x2->srt);
}

/* Reorders vertices/edges/faces using a given methods. Loops are not supported. */
static void sort_bmelem_flag(
        Scene *scene, Object *ob,
        View3D *v3d, RegionView3D *rv3d,
        const int types, const int flag, const int action,
        const int reverse, const unsigned int seed)
{
	BMEditMesh *em = BKE_editmesh_from_object(ob);

	BMVert *ve;
	BMEdge *ed;
	BMFace *fa;
	BMIter iter;

	/* In all five elements below, 0 = vertices, 1 = edges, 2 = faces. */
	/* Just to mark protected elements. */
	char *pblock[3] = {NULL, NULL, NULL}, *pb;
	BMElemSort *sblock[3] = {NULL, NULL, NULL}, *sb;
	unsigned int *map[3] = {NULL, NULL, NULL}, *mp;
	int totelem[3] = {0, 0, 0};
	int affected[3] = {0, 0, 0};
	int i, j;

	if (!(types && flag && action))
		return;

	if (types & BM_VERT)
		totelem[0] = em->bm->totvert;
	if (types & BM_EDGE)
		totelem[1] = em->bm->totedge;
	if (types & BM_FACE)
		totelem[2] = em->bm->totface;

	if (ELEM(action, SRT_VIEW_ZAXIS, SRT_VIEW_XAXIS)) {
		float mat[4][4];
		float fact = reverse ? -1.0 : 1.0;
		int coidx = (action == SRT_VIEW_ZAXIS) ? 2 : 0;

		mul_m4_m4m4(mat, rv3d->viewmat, ob->obmat);  /* Apply the view matrix to the object matrix. */

		if (totelem[0]) {
			pb = pblock[0] = MEM_callocN(sizeof(char) * totelem[0], "sort_bmelem vert pblock");
			sb = sblock[0] = MEM_callocN(sizeof(BMElemSort) * totelem[0], "sort_bmelem vert sblock");

			BM_ITER_MESH_INDEX (ve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
				if (BM_elem_flag_test(ve, flag)) {
					float co[3];
					mul_v3_m4v3(co, mat, ve->co);

					pb[i] = false;
					sb[affected[0]].org_idx = i;
					sb[affected[0]++].srt = co[coidx] * fact;
				}
				else {
					pb[i] = true;
				}
			}
		}

		if (totelem[1]) {
			pb = pblock[1] = MEM_callocN(sizeof(char) * totelem[1], "sort_bmelem edge pblock");
			sb = sblock[1] = MEM_callocN(sizeof(BMElemSort) * totelem[1], "sort_bmelem edge sblock");

			BM_ITER_MESH_INDEX (ed, &iter, em->bm, BM_EDGES_OF_MESH, i) {
				if (BM_elem_flag_test(ed, flag)) {
					float co[3];
					mid_v3_v3v3(co, ed->v1->co, ed->v2->co);
					mul_m4_v3(mat, co);

					pb[i] = false;
					sb[affected[1]].org_idx = i;
					sb[affected[1]++].srt = co[coidx] * fact;
				}
				else {
					pb[i] = true;
				}
			}
		}

		if (totelem[2]) {
			pb = pblock[2] = MEM_callocN(sizeof(char) * totelem[2], "sort_bmelem face pblock");
			sb = sblock[2] = MEM_callocN(sizeof(BMElemSort) * totelem[2], "sort_bmelem face sblock");

			BM_ITER_MESH_INDEX (fa, &iter, em->bm, BM_FACES_OF_MESH, i) {
				if (BM_elem_flag_test(fa, flag)) {
					float co[3];
					BM_face_calc_center_mean(fa, co);
					mul_m4_v3(mat, co);

					pb[i] = false;
					sb[affected[2]].org_idx = i;
					sb[affected[2]++].srt = co[coidx] * fact;
				}
				else {
					pb[i] = true;
				}
			}
		}
	}

	else if (action == SRT_CURSOR_DISTANCE) {
		float cur[3];
		float mat[4][4];
		float fact = reverse ? -1.0 : 1.0;

		if (v3d && v3d->localvd)
			copy_v3_v3(cur, v3d->cursor.location);
		else
			copy_v3_v3(cur, scene->cursor.location);
		invert_m4_m4(mat, ob->obmat);
		mul_m4_v3(mat, cur);

		if (totelem[0]) {
			pb = pblock[0] = MEM_callocN(sizeof(char) * totelem[0], "sort_bmelem vert pblock");
			sb = sblock[0] = MEM_callocN(sizeof(BMElemSort) * totelem[0], "sort_bmelem vert sblock");

			BM_ITER_MESH_INDEX (ve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
				if (BM_elem_flag_test(ve, flag)) {
					pb[i] = false;
					sb[affected[0]].org_idx = i;
					sb[affected[0]++].srt = len_squared_v3v3(cur, ve->co) * fact;
				}
				else {
					pb[i] = true;
				}
			}
		}

		if (totelem[1]) {
			pb = pblock[1] = MEM_callocN(sizeof(char) * totelem[1], "sort_bmelem edge pblock");
			sb = sblock[1] = MEM_callocN(sizeof(BMElemSort) * totelem[1], "sort_bmelem edge sblock");

			BM_ITER_MESH_INDEX (ed, &iter, em->bm, BM_EDGES_OF_MESH, i) {
				if (BM_elem_flag_test(ed, flag)) {
					float co[3];
					mid_v3_v3v3(co, ed->v1->co, ed->v2->co);

					pb[i] = false;
					sb[affected[1]].org_idx = i;
					sb[affected[1]++].srt = len_squared_v3v3(cur, co) * fact;
				}
				else {
					pb[i] = true;
				}
			}
		}

		if (totelem[2]) {
			pb = pblock[2] = MEM_callocN(sizeof(char) * totelem[2], "sort_bmelem face pblock");
			sb = sblock[2] = MEM_callocN(sizeof(BMElemSort) * totelem[2], "sort_bmelem face sblock");

			BM_ITER_MESH_INDEX (fa, &iter, em->bm, BM_FACES_OF_MESH, i) {
				if (BM_elem_flag_test(fa, flag)) {
					float co[3];
					BM_face_calc_center_mean(fa, co);

					pb[i] = false;
					sb[affected[2]].org_idx = i;
					sb[affected[2]++].srt = len_squared_v3v3(cur, co) * fact;
				}
				else {
					pb[i] = true;
				}
			}
		}
	}

	/* Faces only! */
	else if (action == SRT_MATERIAL && totelem[2]) {
		pb = pblock[2] = MEM_callocN(sizeof(char) * totelem[2], "sort_bmelem face pblock");
		sb = sblock[2] = MEM_callocN(sizeof(BMElemSort) * totelem[2], "sort_bmelem face sblock");

		BM_ITER_MESH_INDEX (fa, &iter, em->bm, BM_FACES_OF_MESH, i) {
			if (BM_elem_flag_test(fa, flag)) {
				/* Reverse materials' order, not order of faces inside each mat! */
				/* Note: cannot use totcol, as mat_nr may sometimes be greater... */
				float srt = reverse ? (float)(MAXMAT - fa->mat_nr) : (float)fa->mat_nr;
				pb[i] = false;
				sb[affected[2]].org_idx = i;
				/* Multiplying with totface and adding i ensures us we keep current order for all faces of same mat. */
				sb[affected[2]++].srt = srt * ((float)totelem[2]) + ((float)i);
/*				printf("e: %d; srt: %f; final: %f\n", i, srt, srt * ((float)totface) + ((float)i));*/
			}
			else {
				pb[i] = true;
			}
		}
	}

	else if (action == SRT_SELECTED) {
		unsigned int *tbuf[3] = {NULL, NULL, NULL}, *tb;

		if (totelem[0]) {
			tb = tbuf[0] = MEM_callocN(sizeof(int) * totelem[0], "sort_bmelem vert tbuf");
			mp = map[0] = MEM_callocN(sizeof(int) * totelem[0], "sort_bmelem vert map");

			BM_ITER_MESH_INDEX (ve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
				if (BM_elem_flag_test(ve, flag)) {
					mp[affected[0]++] = i;
				}
				else {
					*tb = i;
					tb++;
				}
			}
		}

		if (totelem[1]) {
			tb = tbuf[1] = MEM_callocN(sizeof(int) * totelem[1], "sort_bmelem edge tbuf");
			mp = map[1] = MEM_callocN(sizeof(int) * totelem[1], "sort_bmelem edge map");

			BM_ITER_MESH_INDEX (ed, &iter, em->bm, BM_EDGES_OF_MESH, i) {
				if (BM_elem_flag_test(ed, flag)) {
					mp[affected[1]++] = i;
				}
				else {
					*tb = i;
					tb++;
				}
			}
		}

		if (totelem[2]) {
			tb = tbuf[2] = MEM_callocN(sizeof(int) * totelem[2], "sort_bmelem face tbuf");
			mp = map[2] = MEM_callocN(sizeof(int) * totelem[2], "sort_bmelem face map");

			BM_ITER_MESH_INDEX (fa, &iter, em->bm, BM_FACES_OF_MESH, i) {
				if (BM_elem_flag_test(fa, flag)) {
					mp[affected[2]++] = i;
				}
				else {
					*tb = i;
					tb++;
				}
			}
		}

		for (j = 3; j--; ) {
			int tot = totelem[j];
			int aff = affected[j];
			tb = tbuf[j];
			mp = map[j];
			if (!(tb && mp))
				continue;
			if (ELEM(aff, 0, tot)) {
				MEM_freeN(tb);
				MEM_freeN(mp);
				map[j] = NULL;
				continue;
			}
			if (reverse) {
				memcpy(tb + (tot - aff), mp, aff * sizeof(int));
			}
			else {
				memcpy(mp + aff, tb, (tot - aff) * sizeof(int));
				tb = mp;
				mp = map[j] = tbuf[j];
				tbuf[j] = tb;
			}

			/* Reverse mapping, we want an org2new one! */
			for (i = tot, tb = tbuf[j] + tot - 1; i--; tb--) {
				mp[*tb] = i;
			}
			MEM_freeN(tbuf[j]);
		}
	}

	else if (action == SRT_RANDOMIZE) {
		if (totelem[0]) {
			/* Re-init random generator for each element type, to get consistent random when
			 * enabling/disabling an element type. */
			RNG *rng = BLI_rng_new_srandom(seed);
			pb = pblock[0] = MEM_callocN(sizeof(char) * totelem[0], "sort_bmelem vert pblock");
			sb = sblock[0] = MEM_callocN(sizeof(BMElemSort) * totelem[0], "sort_bmelem vert sblock");

			BM_ITER_MESH_INDEX (ve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
				if (BM_elem_flag_test(ve, flag)) {
					pb[i] = false;
					sb[affected[0]].org_idx = i;
					sb[affected[0]++].srt = BLI_rng_get_float(rng);
				}
				else {
					pb[i] = true;
				}
			}

			BLI_rng_free(rng);
		}

		if (totelem[1]) {
			RNG *rng = BLI_rng_new_srandom(seed);
			pb = pblock[1] = MEM_callocN(sizeof(char) * totelem[1], "sort_bmelem edge pblock");
			sb = sblock[1] = MEM_callocN(sizeof(BMElemSort) * totelem[1], "sort_bmelem edge sblock");

			BM_ITER_MESH_INDEX (ed, &iter, em->bm, BM_EDGES_OF_MESH, i) {
				if (BM_elem_flag_test(ed, flag)) {
					pb[i] = false;
					sb[affected[1]].org_idx = i;
					sb[affected[1]++].srt = BLI_rng_get_float(rng);
				}
				else {
					pb[i] = true;
				}
			}

			BLI_rng_free(rng);
		}

		if (totelem[2]) {
			RNG *rng = BLI_rng_new_srandom(seed);
			pb = pblock[2] = MEM_callocN(sizeof(char) * totelem[2], "sort_bmelem face pblock");
			sb = sblock[2] = MEM_callocN(sizeof(BMElemSort) * totelem[2], "sort_bmelem face sblock");

			BM_ITER_MESH_INDEX (fa, &iter, em->bm, BM_FACES_OF_MESH, i) {
				if (BM_elem_flag_test(fa, flag)) {
					pb[i] = false;
					sb[affected[2]].org_idx = i;
					sb[affected[2]++].srt = BLI_rng_get_float(rng);
				}
				else {
					pb[i] = true;
				}
			}

			BLI_rng_free(rng);
		}
	}

	else if (action == SRT_REVERSE) {
		if (totelem[0]) {
			pb = pblock[0] = MEM_callocN(sizeof(char) * totelem[0], "sort_bmelem vert pblock");
			sb = sblock[0] = MEM_callocN(sizeof(BMElemSort) * totelem[0], "sort_bmelem vert sblock");

			BM_ITER_MESH_INDEX (ve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
				if (BM_elem_flag_test(ve, flag)) {
					pb[i] = false;
					sb[affected[0]].org_idx = i;
					sb[affected[0]++].srt = (float)-i;
				}
				else {
					pb[i] = true;
				}
			}
		}

		if (totelem[1]) {
			pb = pblock[1] = MEM_callocN(sizeof(char) * totelem[1], "sort_bmelem edge pblock");
			sb = sblock[1] = MEM_callocN(sizeof(BMElemSort) * totelem[1], "sort_bmelem edge sblock");

			BM_ITER_MESH_INDEX (ed, &iter, em->bm, BM_EDGES_OF_MESH, i) {
				if (BM_elem_flag_test(ed, flag)) {
					pb[i] = false;
					sb[affected[1]].org_idx = i;
					sb[affected[1]++].srt = (float)-i;
				}
				else {
					pb[i] = true;
				}
			}
		}

		if (totelem[2]) {
			pb = pblock[2] = MEM_callocN(sizeof(char) * totelem[2], "sort_bmelem face pblock");
			sb = sblock[2] = MEM_callocN(sizeof(BMElemSort) * totelem[2], "sort_bmelem face sblock");

			BM_ITER_MESH_INDEX (fa, &iter, em->bm, BM_FACES_OF_MESH, i) {
				if (BM_elem_flag_test(fa, flag)) {
					pb[i] = false;
					sb[affected[2]].org_idx = i;
					sb[affected[2]++].srt = (float)-i;
				}
				else {
					pb[i] = true;
				}
			}
		}
	}

/*	printf("%d vertices: %d to be affected...\n", totelem[0], affected[0]);*/
/*	printf("%d edges: %d to be affected...\n", totelem[1], affected[1]);*/
/*	printf("%d faces: %d to be affected...\n", totelem[2], affected[2]);*/
	if (affected[0] == 0 && affected[1] == 0 && affected[2] == 0) {
		for (j = 3; j--; ) {
			if (pblock[j])
				MEM_freeN(pblock[j]);
			if (sblock[j])
				MEM_freeN(sblock[j]);
			if (map[j])
				MEM_freeN(map[j]);
		}
		return;
	}

	/* Sort affected elements, and populate mapping arrays, if needed. */
	for (j = 3; j--; ) {
		pb = pblock[j];
		sb = sblock[j];
		if (pb && sb && !map[j]) {
			const char *p_blk;
			BMElemSort *s_blk;
			int tot = totelem[j];
			int aff = affected[j];

			qsort(sb, aff, sizeof(BMElemSort), bmelemsort_comp);

			mp = map[j] = MEM_mallocN(sizeof(int) * tot, "sort_bmelem map");
			p_blk = pb + tot - 1;
			s_blk = sb + aff - 1;
			for (i = tot; i--; p_blk--) {
				if (*p_blk) { /* Protected! */
					mp[i] = i;
				}
				else {
					mp[s_blk->org_idx] = i;
					s_blk--;
				}
			}
		}
		if (pb)
			MEM_freeN(pb);
		if (sb)
			MEM_freeN(sb);
	}

	BM_mesh_remap(em->bm, map[0], map[1], map[2]);
/*	DEG_id_tag_update(ob->data, 0);*/

	for (j = 3; j--; ) {
		if (map[j])
			MEM_freeN(map[j]);
	}
}

static int edbm_sort_elements_exec(bContext *C, wmOperator *op)
{
	Scene *scene = CTX_data_scene(C);
	Object *ob = CTX_data_edit_object(C);

	/* may be NULL */
	View3D *v3d = CTX_wm_view3d(C);
	RegionView3D *rv3d = ED_view3d_context_rv3d(C);

	const int action = RNA_enum_get(op->ptr, "type");
	PropertyRNA *prop_elem_types = RNA_struct_find_property(op->ptr, "elements");
	const bool use_reverse = RNA_boolean_get(op->ptr, "reverse");
	unsigned int seed = RNA_int_get(op->ptr, "seed");
	int elem_types = 0;

	if (ELEM(action, SRT_VIEW_ZAXIS, SRT_VIEW_XAXIS)) {
		if (rv3d == NULL) {
			BKE_report(op->reports, RPT_ERROR, "View not found, cannot sort by view axis");
			return OPERATOR_CANCELLED;
		}
	}

	/* If no elem_types set, use current selection mode to set it! */
	if (RNA_property_is_set(op->ptr, prop_elem_types)) {
		elem_types = RNA_property_enum_get(op->ptr, prop_elem_types);
	}
	else {
		BMEditMesh *em = BKE_editmesh_from_object(ob);
		if (em->selectmode & SCE_SELECT_VERTEX)
			elem_types |= BM_VERT;
		if (em->selectmode & SCE_SELECT_EDGE)
			elem_types |= BM_EDGE;
		if (em->selectmode & SCE_SELECT_FACE)
			elem_types |= BM_FACE;
		RNA_enum_set(op->ptr, "elements", elem_types);
	}

	sort_bmelem_flag(
	        scene, ob, v3d, rv3d,
	        elem_types, BM_ELEM_SELECT, action, use_reverse, seed);
	return OPERATOR_FINISHED;
}

static bool edbm_sort_elements_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop)
{
	const char *prop_id = RNA_property_identifier(prop);
	const int action = RNA_enum_get(ptr, "type");

	/* Only show seed for randomize action! */
	if (STREQ(prop_id, "seed")) {
		if (action == SRT_RANDOMIZE)
			return true;
		else
			return false;
	}

	/* Hide seed for reverse and randomize actions! */
	if (STREQ(prop_id, "reverse")) {
		if (ELEM(action, SRT_RANDOMIZE, SRT_REVERSE))
			return false;
		else
			return true;
	}

	return true;
}

static void edbm_sort_elements_ui(bContext *C, wmOperator *op)
{
	uiLayout *layout = op->layout;
	wmWindowManager *wm = CTX_wm_manager(C);
	PointerRNA ptr;

	RNA_pointer_create(&wm->id, op->type->srna, op->properties, &ptr);

	/* Main auto-draw call. */
	uiDefAutoButsRNA(layout, &ptr, edbm_sort_elements_draw_check_prop, UI_BUT_LABEL_ALIGN_NONE, false);
}

void MESH_OT_sort_elements(wmOperatorType *ot)
{
	static const EnumPropertyItem type_items[] = {
		{SRT_VIEW_ZAXIS, "VIEW_ZAXIS", 0, "View Z Axis",
		                 "Sort selected elements from farthest to nearest one in current view"},
		{SRT_VIEW_XAXIS, "VIEW_XAXIS", 0, "View X Axis",
		                 "Sort selected elements from left to right one in current view"},
		{SRT_CURSOR_DISTANCE, "CURSOR_DISTANCE", 0, "Cursor Distance",
		                      "Sort selected elements from nearest to farthest from 3D cursor"},
		{SRT_MATERIAL, "MATERIAL", 0, "Material",
		               "Sort selected elements from smallest to greatest material index (faces only!)"},
		{SRT_SELECTED, "SELECTED", 0, "Selected",
		               "Move all selected elements in first places, preserving their relative order "
		               "(WARNING: this will affect unselected elements' indices as well!)"},
		{SRT_RANDOMIZE, "RANDOMIZE", 0, "Randomize", "Randomize order of selected elements"},
		{SRT_REVERSE, "REVERSE", 0, "Reverse", "Reverse current order of selected elements"},
		{0, NULL, 0, NULL, NULL},
	};

	static const EnumPropertyItem elem_items[] = {
		{BM_VERT, "VERT", 0, "Vertices", ""},
		{BM_EDGE, "EDGE", 0, "Edges", ""},
		{BM_FACE, "FACE", 0, "Faces", ""},
		{0, NULL, 0, NULL, NULL},
	};

	/* identifiers */
	ot->name = "Sort Mesh Elements";
	ot->description = "The order of selected vertices/edges/faces is modified, based on a given method";
	ot->idname = "MESH_OT_sort_elements";

	/* api callbacks */
	ot->invoke = WM_menu_invoke;
	ot->exec = edbm_sort_elements_exec;
	ot->poll = ED_operator_editmesh;
	ot->ui = edbm_sort_elements_ui;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* properties */
	ot->prop = RNA_def_enum(ot->srna, "type", type_items, SRT_VIEW_ZAXIS,
	                        "Type", "Type of re-ordering operation to apply");
	RNA_def_enum_flag(ot->srna, "elements", elem_items, BM_VERT, "Elements",
	                  "Which elements to affect (vertices, edges and/or faces)");
	RNA_def_boolean(ot->srna, "reverse", false, "Reverse", "Reverse the sorting effect");
	RNA_def_int(ot->srna, "seed", 0, 0, INT_MAX, "Seed", "Seed for random-based operations", 0, 255);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Bridge Operator
 * \{ */

enum {
	MESH_BRIDGELOOP_SINGLE = 0,
	MESH_BRIDGELOOP_CLOSED = 1,
	MESH_BRIDGELOOP_PAIRS  = 2,
};

static int edbm_bridge_tag_boundary_edges(BMesh *bm)
{
	/* tags boundary edges from a face selection */
	BMIter iter;
	BMFace *f;
	BMEdge *e;
	int totface_del = 0;

	BM_mesh_elem_hflag_disable_all(bm, BM_EDGE | BM_FACE, BM_ELEM_TAG, false);

	BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
		if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
			if (BM_edge_is_wire(e) || BM_edge_is_boundary(e)) {
				BM_elem_flag_enable(e, BM_ELEM_TAG);
			}
			else {
				BMIter fiter;
				bool is_all_sel = true;
				/* check if its only used by selected faces */
				BM_ITER_ELEM (f, &fiter, e, BM_FACES_OF_EDGE) {
					if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
						/* tag face for removal*/
						if (!BM_elem_flag_test(f, BM_ELEM_TAG)) {
							BM_elem_flag_enable(f, BM_ELEM_TAG);
							totface_del++;
						}
					}
					else {
						is_all_sel = false;
					}
				}

				if (is_all_sel == false) {
					BM_elem_flag_enable(e, BM_ELEM_TAG);
				}
			}
		}
	}

	return totface_del;
}

static int edbm_bridge_edge_loops_exec(bContext *C, wmOperator *op)
{
	BMOperator bmop;
	Object *obedit = CTX_data_edit_object(C);
	BMEditMesh *em = BKE_editmesh_from_object(obedit);
	const int type = RNA_enum_get(op->ptr, "type");
	const bool use_pairs = (type == MESH_BRIDGELOOP_PAIRS);
	const bool use_cyclic = (type == MESH_BRIDGELOOP_CLOSED);
	const bool use_merge = RNA_boolean_get(op->ptr, "use_merge");
	const float merge_factor = RNA_float_get(op->ptr, "merge_factor");
	const int twist_offset = RNA_int_get(op->ptr, "twist_offset");
	const bool use_faces = (em->bm->totfacesel != 0);
	char edge_hflag;

	int totface_del = 0;
	BMFace **totface_del_arr = NULL;

	if (use_faces) {
		BMIter iter;
		BMFace *f;
		int i;

		totface_del = edbm_bridge_tag_boundary_edges(em->bm);
		totface_del_arr = MEM_mallocN(sizeof(*totface_del_arr) * totface_del, __func__);

		i = 0;
		BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) {
			if (BM_elem_flag_test(f, BM_ELEM_TAG)) {
				totface_del_arr[i++] = f;
			}
		}
		edge_hflag = BM_ELEM_TAG;
	}
	else {
		edge_hflag = BM_ELEM_SELECT;
	}

	EDBM_op_init(
	        em, &bmop, op,
	        "bridge_loops edges=%he use_pairs=%b use_cyclic=%b use_merge=%b merge_factor=%f twist_offset=%i",
	        edge_hflag, use_pairs, use_cyclic, use_merge, merge_factor, twist_offset);

	if (use_faces && totface_del) {
		int i;
		BM_mesh_elem_hflag_disable_all(em->bm, BM_FACE, BM_ELEM_TAG, false);
		for (i = 0; i < totface_del; i++) {
			BM_elem_flag_enable(totface_del_arr[i], BM_ELEM_TAG);
		}
		BMO_op_callf(
		        em->bm, BMO_FLAG_DEFAULTS,
		        "delete geom=%hf context=%i",
		        BM_ELEM_TAG, DEL_FACES_KEEP_BOUNDARY);
	}

	BMO_op_exec(em->bm, &bmop);

	if (!BMO_error_occurred(em->bm)) {
		/* when merge is used the edges are joined and remain selected */
		if (use_merge == false) {
			EDBM_flag_disable_all(em, BM_ELEM_SELECT);
			BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true);
		}

		if (use_merge == false) {
			struct EdgeRingOpSubdProps op_props;
			mesh_operator_edgering_props_get(op, &op_props);

			if (op_props.cuts) {
				BMOperator bmop_subd;
				/* we only need face normals updated */
				EDBM_mesh_normals_update(em);

				BMO_op_initf(
				        em->bm, &bmop_subd, 0,
				        "subdivide_edgering edges=%S interp_mode=%i cuts=%i smooth=%f "
				        "profile_shape=%i profile_shape_factor=%f",
				        &bmop, "edges.out", op_props.interp_mode, op_props.cuts, op_props.smooth,
				        op_props.profile_shape, op_props.profile_shape_factor
				        );
				BMO_op_exec(em->bm, &bmop_subd);

				BMO_slot_buffer_hflag_enable(em->bm, bmop_subd.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true);

				BMO_op_finish(em->bm, &bmop_subd);

			}
		}
	}

	if (totface_del_arr) {
		MEM_freeN(totface_del_arr);
	}

	if (!EDBM_op_finish(em, &bmop, op, true)) {
		/* grr, need to return finished so the user can select different options */
		//return OPERATOR_CANCELLED;
		return OPERATOR_FINISHED;
	}
	else {
		EDBM_update_generic(em, true, true);
		return OPERATOR_FINISHED;
	}
}

void MESH_OT_bridge_edge_loops(wmOperatorType *ot)
{
	static const EnumPropertyItem type_items[] = {
		{MESH_BRIDGELOOP_SINGLE, "SINGLE", 0, "Open Loop", ""},
		{MESH_BRIDGELOOP_CLOSED, "CLOSED", 0, "Closed Loop", ""},
		{MESH_BRIDGELOOP_PAIRS, "PAIRS", 0, "Loop Pairs", ""},
		{0, NULL, 0, NULL, NULL}
	};

	/* identifiers */
	ot->name = "Bridge Edge Loops";
	ot->description = "Make faces between two or more edge loops";
	ot->idname = "MESH_OT_bridge_edge_loops";

	/* api callbacks */
	ot->exec = edbm_bridge_edge_loops_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	ot->prop = RNA_def_enum(ot->srna, "type", type_items, MESH_BRIDGELOOP_SINGLE,
	                        "Connect Loops", "Method of bridging multiple loops");

	RNA_def_boolean(ot->srna, "use_merge", false, "Merge", "Merge rather than creating faces");
	RNA_def_float(ot->srna, "merge_factor", 0.5f, 0.0f, 1.0f, "Merge Factor", "", 0.0f, 1.0f);
	RNA_def_int(ot->srna, "twist_offset", 0, -1000, 1000, "Twist", "Twist offset for closed loops", -1000, 1000);

	mesh_operator_edgering_props(ot, 0, 0);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Wire-Frame Operator
 * \{ */

static int edbm_wireframe_exec(bContext *C, wmOperator *op)
{
	const bool use_boundary        = RNA_boolean_get(op->ptr, "use_boundary");
	const bool use_even_offset     = RNA_boolean_get(op->ptr, "use_even_offset");
	const bool use_replace         = RNA_boolean_get(op->ptr, "use_replace");
	const bool use_relative_offset = RNA_boolean_get(op->ptr, "use_relative_offset");
	const bool use_crease          = RNA_boolean_get(op->ptr, "use_crease");
	const float crease_weight      = RNA_float_get(op->ptr,   "crease_weight");
	const float thickness          = RNA_float_get(op->ptr,   "thickness");
	const float offset             = RNA_float_get(op->ptr,   "offset");

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totfacesel == 0) {
			continue;
		}

		BMOperator bmop;

		EDBM_op_init(
		        em, &bmop, op,
		        "wireframe faces=%hf use_replace=%b use_boundary=%b use_even_offset=%b use_relative_offset=%b "
		        "use_crease=%b crease_weight=%f thickness=%f offset=%f",
		        BM_ELEM_SELECT, use_replace, use_boundary, use_even_offset, use_relative_offset,
		        use_crease, crease_weight, thickness, offset);

		BMO_op_exec(em->bm, &bmop);

		BM_mesh_elem_hflag_disable_all(em->bm, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_SELECT, false);
		BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true);

		if (!EDBM_op_finish(em, &bmop, op, true)) {
			continue;
		}

		EDBM_update_generic(em, true, true);
	}

	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_wireframe(wmOperatorType *ot)
{
	PropertyRNA *prop;

	/* identifiers */
	ot->name = "Wire Frame";
	ot->idname = "MESH_OT_wireframe";
	ot->description = "Create a solid wire-frame from faces";

	/* api callbacks */
	ot->exec = edbm_wireframe_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* properties */
	RNA_def_boolean(ot->srna, "use_boundary", true, "Boundary", "Inset face boundaries");
	RNA_def_boolean(ot->srna, "use_even_offset", true, "Offset Even", "Scale the offset to give more even thickness");
	RNA_def_boolean(ot->srna, "use_relative_offset", false, "Offset Relative", "Scale the offset by surrounding geometry");
	RNA_def_boolean(ot->srna, "use_replace", true, "Replace", "Remove original faces");
	prop = RNA_def_float_distance(ot->srna, "thickness", 0.01f, 0.0f, 1e4f, "Thickness", "", 0.0f, 10.0f);
	/* use 1 rather then 10 for max else dragging the button moves too far */
	RNA_def_property_ui_range(prop, 0.0, 1.0, 0.01, 4);
	RNA_def_float_distance(ot->srna, "offset", 0.01f, 0.0f, 1e4f, "Offset", "", 0.0f, 10.0f);
	RNA_def_boolean(ot->srna, "use_crease", false, "Crease", "Crease hub edges for improved subsurf");
	prop = RNA_def_float(ot->srna, "crease_weight", 0.01f, 0.0f, 1e3f, "Crease weight", "", 0.0f, 1.0f);
	RNA_def_property_ui_range(prop, 0.0, 1.0, 0.1, 2);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Offset Edge-Loop Operator
 * \{ */

static int edbm_offset_edgeloop_exec(bContext *C, wmOperator *op)
{
	Object *obedit = CTX_data_edit_object(C);
	BMEditMesh *em = BKE_editmesh_from_object(obedit);
	BMOperator bmop;
	const bool use_cap_endpoint = RNA_boolean_get(op->ptr, "use_cap_endpoint");

	EDBM_op_init(
	        em, &bmop, op,
	        "offset_edgeloops edges=%he use_cap_endpoint=%b",
	        BM_ELEM_SELECT, use_cap_endpoint);

	BMO_op_exec(em->bm, &bmop);

	BM_mesh_elem_hflag_disable_all(em->bm, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_SELECT, false);

	/* If in face-only select mode, switch to edge select mode so that
	 * an edge-only selection is not inconsistent state */
	if (em->selectmode == SCE_SELECT_FACE) {
		em->selectmode = SCE_SELECT_EDGE;
		EDBM_selectmode_set(em);
		EDBM_selectmode_to_scene(C);
	}

	BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true);

	if (!EDBM_op_finish(em, &bmop, op, true)) {
		return OPERATOR_CANCELLED;
	}
	else {
		EDBM_update_generic(em, true, true);
		return OPERATOR_FINISHED;
	}
}

void MESH_OT_offset_edge_loops(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Offset Edge Loop";
	ot->idname = "MESH_OT_offset_edge_loops";
	ot->description = "Create offset edge loop from the current selection";

	/* api callbacks */
	ot->exec = edbm_offset_edgeloop_exec;
	ot->poll = ED_operator_editmesh;

	/* Keep internal, since this is only meant to be accessed via 'MESH_OT_offset_edge_loops_slide' */

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_INTERNAL;

	RNA_def_boolean(ot->srna, "use_cap_endpoint", false, "Cap Endpoint", "Extend loop around end-points");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Convex Hull Operator
 * \{ */

#ifdef WITH_BULLET
static int edbm_convex_hull_exec(bContext *C, wmOperator *op)
{
	const bool use_existing_faces = RNA_boolean_get(op->ptr, "use_existing_faces");
	const bool delete_unused = RNA_boolean_get(op->ptr, "delete_unused");
	const bool make_holes = RNA_boolean_get(op->ptr, "make_holes");
	const bool join_triangles = RNA_boolean_get(op->ptr, "join_triangles");

	float angle_face_threshold = RNA_float_get(op->ptr, "face_threshold");
	float angle_shape_threshold = RNA_float_get(op->ptr, "shape_threshold");

	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totvertsel == 0) {
			continue;
		}

		BMOperator bmop;

		EDBM_op_init(
		        em, &bmop, op, "convex_hull input=%hvef "
		        "use_existing_faces=%b",
		        BM_ELEM_SELECT,
		        use_existing_faces);
		BMO_op_exec(em->bm, &bmop);

		/* Hull fails if input is coplanar */
		if (BMO_error_occurred(em->bm)) {
			EDBM_op_finish(em, &bmop, op, true);
			continue;
		}

		BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "geom.out", BM_FACE, BM_ELEM_SELECT, true);

		/* Delete unused vertices, edges, and faces */
		if (delete_unused) {
			if (!EDBM_op_callf(
			            em, op, "delete geom=%S context=%i",
			            &bmop, "geom_unused.out", DEL_ONLYTAGGED))
			{
				EDBM_op_finish(em, &bmop, op, true);
				continue;
			}
		}

		/* Delete hole edges/faces */
		if (make_holes) {
			if (!EDBM_op_callf(
			            em, op, "delete geom=%S context=%i",
			            &bmop, "geom_holes.out", DEL_ONLYTAGGED))
			{
				EDBM_op_finish(em, &bmop, op, true);
				continue;
			}
		}

		/* Merge adjacent triangles */
		if (join_triangles) {
			if (!EDBM_op_call_and_selectf(
			        em, op,
			        "faces.out", true,
			        "join_triangles faces=%S "
			        "angle_face_threshold=%f angle_shape_threshold=%f",
			        &bmop, "geom.out",
			        angle_face_threshold, angle_shape_threshold))
			{
				EDBM_op_finish(em, &bmop, op, true);
				continue;
			}
		}

		if (!EDBM_op_finish(em, &bmop, op, true)) {
			continue;
		}

		EDBM_update_generic(em, true, true);
		EDBM_selectmode_flush(em);
	}

	MEM_freeN(objects);
	return OPERATOR_FINISHED;
}

void MESH_OT_convex_hull(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Convex Hull";
	ot->description = "Enclose selected vertices in a convex polyhedron";
	ot->idname = "MESH_OT_convex_hull";

	/* api callbacks */
	ot->exec = edbm_convex_hull_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* props */
	RNA_def_boolean(ot->srna, "delete_unused", true,
	                "Delete Unused",
	                "Delete selected elements that are not used by the hull");

	RNA_def_boolean(ot->srna, "use_existing_faces", true,
	                "Use Existing Faces",
	                "Skip hull triangles that are covered by a pre-existing face");

	RNA_def_boolean(ot->srna, "make_holes", false,
	                "Make Holes",
	                "Delete selected faces that are used by the hull");

	RNA_def_boolean(ot->srna, "join_triangles", true,
	                "Join Triangles",
	                "Merge adjacent triangles into quads");

	join_triangle_props(ot);
}
#endif  /* WITH_BULLET */

/** \} */

/* -------------------------------------------------------------------- */
/** \name Symmetrize Operator
 * \{ */

static int mesh_symmetrize_exec(bContext *C, wmOperator *op)
{
	ViewLayer *view_layer = CTX_data_view_layer(C);
	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);

	for (uint ob_index = 0; ob_index < objects_len; ob_index++)	{
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em->bm->totvertsel == 0 ) {
			continue;
		}
		BMOperator bmop;

		const float thresh = RNA_float_get(op->ptr, "threshold");

		EDBM_op_init(
		        em, &bmop, op,
		        "symmetrize input=%hvef direction=%i dist=%f",
		        BM_ELEM_SELECT, RNA_enum_get(op->ptr, "direction"), thresh);
		BMO_op_exec(em->bm, &bmop);

		EDBM_flag_disable_all(em, BM_ELEM_SELECT);

		BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "geom.out", BM_ALL_NOLOOP, BM_ELEM_SELECT, true);

		if (!EDBM_op_finish(em, &bmop, op, true)) {
			continue;
		}
		else {
			EDBM_update_generic(em, true, true);
			EDBM_selectmode_flush(em);
		}
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_symmetrize(struct wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Symmetrize";
	ot->description = "Enforce symmetry (both form and topological) across an axis";
	ot->idname = "MESH_OT_symmetrize";

	/* api callbacks */
	ot->exec = mesh_symmetrize_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	ot->prop = RNA_def_enum(
	        ot->srna, "direction", rna_enum_symmetrize_direction_items,
	        BMO_SYMMETRIZE_NEGATIVE_X,
	        "Direction", "Which sides to copy from and to");
	RNA_def_float(ot->srna, "threshold", 1e-4f, 0.0f, 10.0f, "Threshold",
	                        "Limit for snap middle vertices to the axis center", 1e-5f, 0.1f);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Snap to Symmetry Operator
 * \{ */

static int mesh_symmetry_snap_exec(bContext *C, wmOperator *op)
{
	const float eps = 0.00001f;
	const float eps_sq = eps * eps;

	Object *obedit = CTX_data_edit_object(C);
	BMEditMesh *em = BKE_editmesh_from_object(obedit);
	BMesh *bm = em->bm;
	int *index = MEM_mallocN(bm->totvert * sizeof(*index), __func__);
	const bool use_topology = false;

	const float thresh = RNA_float_get(op->ptr, "threshold");
	const float fac = RNA_float_get(op->ptr, "factor");
	const bool use_center = RNA_boolean_get(op->ptr, "use_center");

	/* stats */
	int totmirr = 0, totfail = 0, totfound = 0;

	/* axix */
	const int axis_dir = RNA_enum_get(op->ptr, "direction");
	int axis = axis_dir % 3;
	bool axis_sign = axis != axis_dir;

	/* vertex iter */
	BMIter iter;
	BMVert *v;
	int i;

	EDBM_verts_mirror_cache_begin_ex(em, axis, true, true, use_topology, thresh, index);

	BM_mesh_elem_table_ensure(bm, BM_VERT);

	BM_mesh_elem_hflag_disable_all(bm, BM_VERT, BM_ELEM_TAG, false);


	BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) {
		if ((BM_elem_flag_test(v, BM_ELEM_SELECT) != false) &&
		    (BM_elem_flag_test(v, BM_ELEM_TAG) == false))
		{
			int i_mirr = index[i];
			if (i_mirr != -1) {

				BMVert *v_mirr = BM_vert_at_index(bm, index[i]);

				if (v != v_mirr) {
					float co[3], co_mirr[3];

					if ((v->co[axis] > v_mirr->co[axis]) == axis_sign) {
						SWAP(BMVert *, v, v_mirr);
					}

					copy_v3_v3(co_mirr, v_mirr->co);
					co_mirr[axis] *= -1.0f;

					if (len_squared_v3v3(v->co, co_mirr) > eps_sq) {
						totmirr++;
					}

					interp_v3_v3v3(co, v->co, co_mirr, fac);

					copy_v3_v3(v->co, co);

					co[axis] *= -1.0f;
					copy_v3_v3(v_mirr->co, co);

					BM_elem_flag_enable(v, BM_ELEM_TAG);
					BM_elem_flag_enable(v_mirr, BM_ELEM_TAG);
					totfound++;
				}
				else {
					if (use_center) {

						if (fabsf(v->co[axis]) > eps) {
							totmirr++;
						}

						v->co[axis] = 0.0f;
					}
					BM_elem_flag_enable(v, BM_ELEM_TAG);
					totfound++;
				}
			}
			else {
				totfail++;
			}
		}
	}


	if (totfail) {
		BKE_reportf(op->reports, RPT_WARNING, "%d already symmetrical, %d pairs mirrored, %d failed",
		            totfound - totmirr, totmirr, totfail);
	}
	else {
		BKE_reportf(op->reports, RPT_INFO, "%d already symmetrical, %d pairs mirrored",
		            totfound - totmirr, totmirr);
	}

	/* no need to end cache, just free the array */
	MEM_freeN(index);

	return OPERATOR_FINISHED;
}

void MESH_OT_symmetry_snap(struct wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Snap to Symmetry";
	ot->description = "Snap vertex pairs to their mirrored locations";
	ot->idname = "MESH_OT_symmetry_snap";

	/* api callbacks */
	ot->exec = mesh_symmetry_snap_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	ot->prop = RNA_def_enum(
	        ot->srna, "direction", rna_enum_symmetrize_direction_items,
	        BMO_SYMMETRIZE_NEGATIVE_X,
	        "Direction", "Which sides to copy from and to");
	RNA_def_float_distance(ot->srna, "threshold", 0.05f, 0.0f, 10.0f, "Threshold",
	                                 "Distance within which matching vertices are searched", 1e-4f, 1.0f);
	RNA_def_float(ot->srna, "factor", 0.5f, 0.0f, 1.0f, "Factor",
	                        "Mix factor of the locations of the vertices", 0.0f, 1.0f);
	RNA_def_boolean(ot->srna, "use_center", true, "Center", "Snap middle vertices to the axis center");
}

/** \} */

#ifdef WITH_FREESTYLE

/* -------------------------------------------------------------------- */
/** \name Mark Edge (FreeStyle) Operator
 * \{ */

static int edbm_mark_freestyle_edge_exec(bContext *C, wmOperator *op)
{
	BMEdge *eed;
	BMIter iter;
	FreestyleEdge *fed;
	const bool clear = RNA_boolean_get(op->ptr, "clear");
	ViewLayer *view_layer = CTX_data_view_layer(C);

	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em == NULL) {
			continue;
		}

		BMesh *bm = em->bm;
		Mesh *me = ((Mesh *)obedit->data);

		if (bm->totedgesel == 0) {
			continue;
		}

		/* auto-enable Freestyle edge mark drawing */
		if (clear == 0) {
			me->drawflag |= ME_DRAW_FREESTYLE_EDGE;
		}

		if (!CustomData_has_layer(&em->bm->edata, CD_FREESTYLE_EDGE)) {
			BM_data_layer_add(em->bm, &em->bm->edata, CD_FREESTYLE_EDGE);
		}

		if (clear) {
			BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
				if (BM_elem_flag_test(eed, BM_ELEM_SELECT) && !BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
					fed = CustomData_bmesh_get(&em->bm->edata, eed->head.data, CD_FREESTYLE_EDGE);
					fed->flag &= ~FREESTYLE_EDGE_MARK;
				}
			}
		}
		else {
			BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
				if (BM_elem_flag_test(eed, BM_ELEM_SELECT) && !BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
					fed = CustomData_bmesh_get(&em->bm->edata, eed->head.data, CD_FREESTYLE_EDGE);
					fed->flag |= FREESTYLE_EDGE_MARK;
				}
			}
		}

		DEG_id_tag_update(obedit->data, OB_RECALC_DATA);
		WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_mark_freestyle_edge(wmOperatorType *ot)
{
	PropertyRNA *prop;

	/* identifiers */
	ot->name = "Mark Freestyle Edge";
	ot->description = "(Un)mark selected edges as Freestyle feature edges";
	ot->idname = "MESH_OT_mark_freestyle_edge";

	/* api callbacks */
	ot->exec = edbm_mark_freestyle_edge_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	prop = RNA_def_boolean(ot->srna, "clear", false, "Clear", "");
	RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Mark Face (FreeStyle) Operator
 * \{ */

static int edbm_mark_freestyle_face_exec(bContext *C, wmOperator *op)
{
	BMFace *efa;
	BMIter iter;
	FreestyleFace *ffa;
	const bool clear = RNA_boolean_get(op->ptr, "clear");
	ViewLayer *view_layer = CTX_data_view_layer(C);

	uint objects_len = 0;
	Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
	for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
		Object *obedit = objects[ob_index];
		Mesh *me = (Mesh *)obedit->data;
		BMEditMesh *em = BKE_editmesh_from_object(obedit);

		if (em == NULL) {
			continue;
		}

		if (em->bm->totfacesel == 0) {
			continue;
		}

		/* auto-enable Freestyle face mark drawing */
		if (!clear) {
			me->drawflag |= ME_DRAW_FREESTYLE_FACE;
		}

		if (!CustomData_has_layer(&em->bm->pdata, CD_FREESTYLE_FACE)) {
			BM_data_layer_add(em->bm, &em->bm->pdata, CD_FREESTYLE_FACE);
		}

		if (clear) {
			BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
				if (BM_elem_flag_test(efa, BM_ELEM_SELECT) && !BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
					ffa = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_FREESTYLE_FACE);
					ffa->flag &= ~FREESTYLE_FACE_MARK;
				}
			}
		}
		else {
			BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
				if (BM_elem_flag_test(efa, BM_ELEM_SELECT) && !BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
					ffa = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_FREESTYLE_FACE);
					ffa->flag |= FREESTYLE_FACE_MARK;
				}
			}
		}

		DEG_id_tag_update(obedit->data, OB_RECALC_DATA);
		WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
	}
	MEM_freeN(objects);

	return OPERATOR_FINISHED;
}

void MESH_OT_mark_freestyle_face(wmOperatorType *ot)
{
	PropertyRNA *prop;

	/* identifiers */
	ot->name = "Mark Freestyle Face";
	ot->description = "(Un)mark selected faces for exclusion from Freestyle feature edge detection";
	ot->idname = "MESH_OT_mark_freestyle_face";

	/* api callbacks */
	ot->exec = edbm_mark_freestyle_face_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	prop = RNA_def_boolean(ot->srna, "clear", false, "Clear", "");
	RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
}

/** \} */

#endif  /* WITH_FREESTYLE */