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

VolumeToMesh.h « tools « openvdb « internal « openvdb « extern - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ef0f39c7f17e496cf39cc83f5a62f703cf9495a0 (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
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012-2013 DreamWorks Animation LLC
//
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
//
// Redistributions of source code must retain the above copyright
// and license notice and the following restrictions and disclaimer.
//
// *     Neither the name of DreamWorks Animation nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// IN NO EVENT SHALL THE COPYRIGHT HOLDERS' AND CONTRIBUTORS' AGGREGATE
// LIABILITY FOR ALL CLAIMS REGARDLESS OF THEIR BASIS EXCEED US$250.00.
//
///////////////////////////////////////////////////////////////////////////

#ifndef OPENVDB_TOOLS_VOLUME_TO_MESH_HAS_BEEN_INCLUDED
#define OPENVDB_TOOLS_VOLUME_TO_MESH_HAS_BEEN_INCLUDED

#include <openvdb/Platform.h> // for OPENVDB_HAS_CXX11
#include <openvdb/tree/ValueAccessor.h>
#include <openvdb/util/Util.h> // for COORD_OFFSETS
#include <openvdb/math/Operators.h> // for ISGradient
#include <openvdb/tools/Morphology.h> // for dilateVoxels()
#include <openvdb/tree/LeafManager.h>

#include <boost/scoped_array.hpp>
#include <boost/scoped_ptr.hpp>
#include <tbb/blocked_range.h>
#include <tbb/parallel_for.h>
#include <tbb/parallel_reduce.h>

#include <vector>
#include <memory> // for auto_ptr/unique_ptr


//////////


namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace tools {


////////////////////////////////////////


// Wrapper functions for the VolumeToMesh converter


/// @brief Uniformly mesh any scalar grid that has a continuous isosurface.
///
/// @param grid     a scalar grid to mesh
/// @param points   output list of world space points
/// @param quads    output quad index list
/// @param isovalue determines which isosurface to mesh
template<typename GridType>
void
volumeToMesh(
    const GridType& grid,
    std::vector<Vec3s>& points,
    std::vector<Vec4I>& quads,
    double isovalue = 0.0);


/// @brief Adaptively mesh any scalar grid that has a continuous isosurface.
///
/// @param grid         a scalar grid to mesh
/// @param points       output list of world space points
/// @param triangles    output quad index list
/// @param quads        output quad index list
/// @param isovalue     determines which isosurface to mesh
/// @param adaptivity   surface adaptivity threshold [0 to 1]
template<typename GridType>
void
volumeToMesh(
    const GridType& grid,
    std::vector<Vec3s>& points,
    std::vector<Vec3I>& triangles,
    std::vector<Vec4I>& quads,
    double isovalue = 0.0,
    double adaptivity = 0.0);


////////////////////////////////////////


/// @brief Polygon flags, used for reference based meshing.
enum { POLYFLAG_EXTERIOR = 0x1, POLYFLAG_FRACTURE_SEAM = 0x2,  POLYFLAG_SUBDIVIDED = 0x4};


/// @brief Collection of quads and triangles
class PolygonPool
{
public:

    inline PolygonPool();
    inline PolygonPool(const size_t numQuads, const size_t numTriangles);


    inline void copy(const PolygonPool& rhs);

    inline void resetQuads(size_t size);
    inline void clearQuads();

    inline void resetTriangles(size_t size);
    inline void clearTriangles();


    // polygon accessor methods

    const size_t& numQuads() const                      { return mNumQuads; }

    openvdb::Vec4I& quad(size_t n)                      { return mQuads[n]; }
    const openvdb::Vec4I& quad(size_t n) const          { return mQuads[n]; }


    const size_t& numTriangles() const                  { return mNumTriangles; }

    openvdb::Vec3I& triangle(size_t n)                  { return mTriangles[n]; }
    const openvdb::Vec3I& triangle(size_t n) const      { return mTriangles[n]; }


    // polygon flags accessor methods

    char& quadFlags(size_t n)                           { return mQuadFlags[n]; }
    const char& quadFlags(size_t n) const               { return mQuadFlags[n]; }

    char& triangleFlags(size_t n)                       { return mTriangleFlags[n]; }
    const char& triangleFlags(size_t n) const           { return mTriangleFlags[n]; }


    // reduce the polygon containers, n has to
    // be smaller than the current container size.

    inline bool trimQuads(const size_t n, bool reallocate = false);
    inline bool trimTrinagles(const size_t n, bool reallocate = false);

private:
    // disallow copy by assignment
    void operator=(const PolygonPool&) {}

    size_t mNumQuads, mNumTriangles;
    boost::scoped_array<openvdb::Vec4I> mQuads;
    boost::scoped_array<openvdb::Vec3I> mTriangles;
    boost::scoped_array<char> mQuadFlags, mTriangleFlags;
};


/// @{
/// @brief Point and primitive list types.
typedef boost::scoped_array<openvdb::Vec3s> PointList;
typedef boost::scoped_array<PolygonPool> PolygonPoolList;
/// @}


////////////////////////////////////////


/// @brief Mesh any scalar grid that has a continuous isosurface.
class VolumeToMesh
{
public:

    /// @param isovalue         Determines which isosurface to mesh.
    /// @param adaptivity       Adaptivity threshold [0 to 1]
    VolumeToMesh(double isovalue = 0, double adaptivity = 0);


    //////////

    // Mesh data accessors

    const size_t& pointListSize() const;
    PointList& pointList();

    const size_t& polygonPoolListSize() const;
    PolygonPoolList& polygonPoolList();
    const PolygonPoolList& polygonPoolList() const;

    std::vector<unsigned char>& pointFlags();
    const std::vector<unsigned char>& pointFlags() const;


    //////////


    /// @brief Main call
    /// @note Call with scalar typed grid.
    template<typename GridT>
    void operator()(const GridT&);


    //////////


    /// @brief  When surfacing fractured SDF fragments, the original unfractured
    ///         SDF grid can be used to eliminate seam lines and tag polygons that are
    ///         coincident with the reference surface with the @c POLYFLAG_EXTERIOR
    ///         flag and polygons that are in proximity to the seam lines with the
    ///         @c POLYFLAG_FRACTURE_SEAM flag. (The performance cost for using this
    ///         reference based scheme compared to the regular meshing scheme is
    ///         approximately 15% for the first fragment and neglect-able for
    ///         subsequent fragments.)
    ///
    /// @note   Attributes from the original asset such as uv coordinates, normals etc.
    ///         are typically transfered to polygons that are marked with the
    ///         @c POLYFLAG_EXTERIOR flag. Polygons that are not marked with this flag
    ///         are interior to reference surface and might need projected UV coordinates
    ///         or a different material. Polygons marked as @c POLYFLAG_FRACTURE_SEAM can
    ///         be used to drive secondary elements such as debris and dust in a FX pipeline.
    ///
    /// @param  grid            reference surface grid of @c GridT type.
    /// @param  secAdaptivity   Secondary adaptivity threshold [0 to 1]. Used in regions
    ///                         that do not exist in the reference grid. (Parts of the
    ///                         fragment surface that are not coincident with the
    ///                         reference surface.)
    void setRefGrid(const GridBase::ConstPtr& grid, double secAdaptivity = 0);


    /// @param mask A boolean grid whose active topology defines the region to mesh.
    /// @param invertMask Toggle to mesh the complement of the mask.
    /// @note The mask's tree configuration has to match @c GridT's tree configuration.
    void setSurfaceMask(const GridBase::ConstPtr& mask, bool invertMask = false);

    /// @param grid A scalar grid used as an spatial multiplier for the adaptivity threshold.
    /// @note The grid's tree configuration has to match @c GridT's tree configuration.
    void setSpatialAdaptivity(const GridBase::ConstPtr& grid);


    /// @param tree A boolean tree whose active topology defines the adaptivity mask.
    /// @note The tree configuration has to match @c GridT's tree configuration.
    void setAdaptivityMask(const TreeBase::ConstPtr& tree);


    /// @brief Subdivide volume and mesh into disjoint parts
    /// @param partitions Number of partitions.
    /// @param activePart Specific partition to mesh, 0 to @c partitions - 1.
    void partition(unsigned partitions = 1, unsigned activePart = 0);

private:

    PointList mPoints;
    PolygonPoolList mPolygons;

    size_t mPointListSize, mSeamPointListSize, mPolygonPoolListSize;
    double mIsovalue, mPrimAdaptivity, mSecAdaptivity;

    GridBase::ConstPtr mRefGrid, mSurfaceMaskGrid, mAdaptivityGrid;
    TreeBase::ConstPtr mAdaptivityMaskTree;

    TreeBase::Ptr mRefSignTree, mRefIdxTree;

    bool mInvertSurfaceMask;
    unsigned mPartitions, mActivePart;

    boost::scoped_array<uint32_t> mQuantizedSeamPoints;

    std::vector<unsigned char> mPointFlags;
};


////////////////////////////////////////


/// @brief  Given a set of tangent elements, @c points with corresponding @c normals,
///         this method returns the intersection point of all tangent elements.
///
/// @note   Used to extract surfaces with sharp edges and corners from volume data,
///         see the following paper for details: "Feature Sensitive Surface
///         Extraction from Volume Data, Kobbelt et al. 2001".
inline Vec3d findFeaturePoint(
    const std::vector<Vec3d>& points,
    const std::vector<Vec3d>& normals)
{
    typedef math::Mat3d Mat3d;

    Vec3d avgPos(0.0);

    if (points.empty()) return avgPos;

    for (size_t n = 0, N = points.size(); n < N; ++n) {
        avgPos += points[n];
    }

    avgPos /= double(points.size());

    // Unique components of the 3x3 A^TA matrix, where A is
    // the matrix of normals.
    double m00=0,m01=0,m02=0,
           m11=0,m12=0,
           m22=0;

    // The rhs vector, A^Tb, where b = n dot p
    Vec3d rhs(0.0);

    for (size_t n = 0, N = points.size(); n < N; ++n) {

        const Vec3d& n_ref = normals[n];

        // A^TA
        m00 += n_ref[0] * n_ref[0]; // diagonal
        m11 += n_ref[1] * n_ref[1];
        m22 += n_ref[2] * n_ref[2];

        m01 += n_ref[0] * n_ref[1]; // Upper-tri
        m02 += n_ref[0] * n_ref[2];
        m12 += n_ref[1] * n_ref[2];

        // A^Tb (centered around the origin)
        rhs += n_ref * n_ref.dot(points[n] - avgPos);
    }

    Mat3d A(m00,m01,m02,
            m01,m11,m12,
            m02,m12,m22);

    /*
    // Inverse
    const double det = A.det();
    if (det > 0.01) {
        Mat3d A_inv = A.adjoint();
        A_inv *= (1.0 / det);

        return avgPos + A_inv * rhs;
    }
    */

    // Compute the pseudo inverse

    math::Mat3d eigenVectors;
    Vec3d eigenValues;

    diagonalizeSymmetricMatrix(A, eigenVectors, eigenValues, 300);

    Mat3d D = Mat3d::identity();


    double tolerance = std::max(std::abs(eigenValues[0]), std::abs(eigenValues[1]));
    tolerance = std::max(tolerance, std::abs(eigenValues[2]));
    tolerance *= 0.01;

    int clamped = 0;
    for (int i = 0; i < 3; ++i ) {
        if (std::abs(eigenValues[i]) < tolerance) {
            D[i][i] = 0.0;
            ++clamped;
        } else {
            D[i][i] = 1.0 / eigenValues[i];
        }
    }

    // Assemble the pseudo inverse and calc. the intersection point
    if (clamped < 3) {
        Mat3d pseudoInv = eigenVectors * D *  eigenVectors.transpose();
        return avgPos + pseudoInv * rhs;
    }

    return avgPos;
}


////////////////////////////////////////


// Internal utility methods
namespace internal {

template<typename T>
struct UniquePtr
{
#ifdef OPENVDB_HAS_CXX11
    typedef std::unique_ptr<T>  type;
#else
    typedef std::auto_ptr<T>    type;
#endif
};


/// @brief  Bit-flags used to classify cells.
enum { SIGNS = 0xFF, EDGES = 0xE00, INSIDE = 0x100,
       XEDGE = 0x200, YEDGE = 0x400, ZEDGE = 0x800, SEAM = 0x1000};


/// @brief Used to quickly determine if a given cell is adaptable.
const bool sAdaptable[256] = {
    1,1,1,1,1,0,1,1,1,1,0,1,1,1,1,1,1,1,0,1,0,0,0,1,0,1,0,1,0,1,0,1,
    1,0,1,1,0,0,1,1,0,0,0,1,0,0,1,1,1,1,1,1,0,0,1,1,0,1,0,1,0,0,0,1,
    1,0,0,0,1,0,1,1,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    1,0,1,1,1,0,1,1,0,0,0,0,1,0,1,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,1,
    1,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,1,1,0,1,0,0,0,0,1,1,0,1,1,1,0,1,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,1,1,0,1,0,0,0,1,
    1,0,0,0,1,0,1,0,1,1,0,0,1,1,1,1,1,1,0,0,1,0,0,0,1,1,0,0,1,1,0,1,
    1,0,1,0,1,0,1,0,1,0,0,0,1,0,1,1,1,1,1,1,1,0,1,1,1,1,0,1,1,1,1,1};


/// @brief  Contains the ambiguous face index for certain cell configuration.
const unsigned char sAmbiguousFace[256] = {
    0,0,0,0,0,5,0,0,0,0,5,0,0,0,0,0,0,0,1,0,0,5,1,0,4,0,0,0,4,0,0,0,
    0,1,0,0,2,0,0,0,0,1,5,0,2,0,0,0,0,0,0,0,2,0,0,0,4,0,0,0,0,0,0,0,
    0,0,2,2,0,5,0,0,3,3,0,0,0,0,0,0,6,6,0,0,6,0,0,0,0,0,0,0,0,0,0,0,
    0,1,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,4,0,4,3,0,3,0,0,0,5,0,0,0,0,0,0,0,1,0,3,0,0,0,0,0,0,0,0,0,0,0,
    6,0,6,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,4,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};


/// @brief  Lookup table for different cell sign configurations. The first entry specifies
///         the total number of points that need to be generated inside a cell and the
///         remaining 12 entries indicate different edge groups.
const unsigned char sEdgeGroupTable[256][13] = {
    {0,0,0,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,0,0,0,0,1,0,0,0},{1,1,1,0,0,0,0,0,0,0,1,0,0},
    {1,0,1,0,1,0,0,0,0,1,1,0,0},{1,0,1,1,0,0,0,0,0,0,0,1,0},{1,1,1,1,1,0,0,0,0,1,0,1,0},
    {1,1,0,1,0,0,0,0,0,0,1,1,0},{1,0,0,1,1,0,0,0,0,1,1,1,0},{1,0,0,1,1,0,0,0,0,0,0,0,1},
    {1,1,0,1,0,0,0,0,0,1,0,0,1},{1,1,1,1,1,0,0,0,0,0,1,0,1},{1,0,1,1,0,0,0,0,0,1,1,0,1},
    {1,0,1,0,1,0,0,0,0,0,0,1,1},{1,1,1,0,0,0,0,0,0,1,0,1,1},{1,1,0,0,1,0,0,0,0,0,1,1,1},
    {1,0,0,0,0,0,0,0,0,1,1,1,1},{1,0,0,0,0,1,0,0,1,1,0,0,0},{1,1,0,0,1,1,0,0,1,0,0,0,0},
    {1,1,1,0,0,1,0,0,1,1,1,0,0},{1,0,1,0,1,1,0,0,1,0,1,0,0},{2,0,1,1,0,2,0,0,2,2,0,1,0},
    {1,1,1,1,1,1,0,0,1,0,0,1,0},{1,1,0,1,0,1,0,0,1,1,1,1,0},{1,0,0,1,1,1,0,0,1,0,1,1,0},
    {1,0,0,1,1,1,0,0,1,1,0,0,1},{1,1,0,1,0,1,0,0,1,0,0,0,1},{2,2,1,1,2,1,0,0,1,2,1,0,1},
    {1,0,1,1,0,1,0,0,1,0,1,0,1},{1,0,1,0,1,1,0,0,1,1,0,1,1},{1,1,1,0,0,1,0,0,1,0,0,1,1},
    {2,1,0,0,1,2,0,0,2,1,2,2,2},{1,0,0,0,0,1,0,0,1,0,1,1,1},{1,0,0,0,0,1,1,0,0,0,1,0,0},
    {1,1,0,0,1,1,1,0,0,1,1,0,0},{1,1,1,0,0,1,1,0,0,0,0,0,0},{1,0,1,0,1,1,1,0,0,1,0,0,0},
    {1,0,1,1,0,1,1,0,0,0,1,1,0},{2,2,2,1,1,1,1,0,0,1,2,1,0},{1,1,0,1,0,1,1,0,0,0,0,1,0},
    {1,0,0,1,1,1,1,0,0,1,0,1,0},{2,0,0,2,2,1,1,0,0,0,1,0,2},{1,1,0,1,0,1,1,0,0,1,1,0,1},
    {1,1,1,1,1,1,1,0,0,0,0,0,1},{1,0,1,1,0,1,1,0,0,1,0,0,1},{1,0,1,0,1,1,1,0,0,0,1,1,1},
    {2,1,1,0,0,2,2,0,0,2,1,2,2},{1,1,0,0,1,1,1,0,0,0,0,1,1},{1,0,0,0,0,1,1,0,0,1,0,1,1},
    {1,0,0,0,0,0,1,0,1,1,1,0,0},{1,1,0,0,1,0,1,0,1,0,1,0,0},{1,1,1,0,0,0,1,0,1,1,0,0,0},
    {1,0,1,0,1,0,1,0,1,0,0,0,0},{1,0,1,1,0,0,1,0,1,1,1,1,0},{2,1,1,2,2,0,2,0,2,0,1,2,0},
    {1,1,0,1,0,0,1,0,1,1,0,1,0},{1,0,0,1,1,0,1,0,1,0,0,1,0},{1,0,0,1,1,0,1,0,1,1,1,0,1},
    {1,1,0,1,0,0,1,0,1,0,1,0,1},{2,1,2,2,1,0,2,0,2,1,0,0,2},{1,0,1,1,0,0,1,0,1,0,0,0,1},
    {2,0,2,0,2,0,1,0,1,2,2,1,1},{2,2,2,0,0,0,1,0,1,0,2,1,1},{2,2,0,0,2,0,1,0,1,2,0,1,1},
    {1,0,0,0,0,0,1,0,1,0,0,1,1},{1,0,0,0,0,0,1,1,0,0,0,1,0},{2,1,0,0,1,0,2,2,0,1,0,2,0},
    {1,1,1,0,0,0,1,1,0,0,1,1,0},{1,0,1,0,1,0,1,1,0,1,1,1,0},{1,0,1,1,0,0,1,1,0,0,0,0,0},
    {1,1,1,1,1,0,1,1,0,1,0,0,0},{1,1,0,1,0,0,1,1,0,0,1,0,0},{1,0,0,1,1,0,1,1,0,1,1,0,0},
    {1,0,0,1,1,0,1,1,0,0,0,1,1},{1,1,0,1,0,0,1,1,0,1,0,1,1},{2,1,2,2,1,0,1,1,0,0,1,2,1},
    {2,0,1,1,0,0,2,2,0,2,2,1,2},{1,0,1,0,1,0,1,1,0,0,0,0,1},{1,1,1,0,0,0,1,1,0,1,0,0,1},
    {1,1,0,0,1,0,1,1,0,0,1,0,1},{1,0,0,0,0,0,1,1,0,1,1,0,1},{1,0,0,0,0,1,1,1,1,1,0,1,0},
    {1,1,0,0,1,1,1,1,1,0,0,1,0},{2,1,1,0,0,2,2,1,1,1,2,1,0},{2,0,2,0,2,1,1,2,2,0,1,2,0},
    {1,0,1,1,0,1,1,1,1,1,0,0,0},{2,2,2,1,1,2,2,1,1,0,0,0,0},{2,2,0,2,0,1,1,2,2,2,1,0,0},
    {2,0,0,1,1,2,2,1,1,0,2,0,0},{2,0,0,1,1,1,1,2,2,1,0,1,2},{2,2,0,2,0,2,2,1,1,0,0,2,1},
    {4,3,2,2,3,4,4,1,1,3,4,2,1},{3,0,2,2,0,1,1,3,3,0,1,2,3},{2,0,2,0,2,2,2,1,1,2,0,0,1},
    {2,1,1,0,0,1,1,2,2,0,0,0,2},{3,1,0,0,1,2,2,3,3,1,2,0,3},{2,0,0,0,0,1,1,2,2,0,1,0,2},
    {1,0,0,0,0,1,0,1,0,0,1,1,0},{1,1,0,0,1,1,0,1,0,1,1,1,0},{1,1,1,0,0,1,0,1,0,0,0,1,0},
    {1,0,1,0,1,1,0,1,0,1,0,1,0},{1,0,1,1,0,1,0,1,0,0,1,0,0},{2,1,1,2,2,2,0,2,0,2,1,0,0},
    {1,1,0,1,0,1,0,1,0,0,0,0,0},{1,0,0,1,1,1,0,1,0,1,0,0,0},{1,0,0,1,1,1,0,1,0,0,1,1,1},
    {2,2,0,2,0,1,0,1,0,1,2,2,1},{2,2,1,1,2,2,0,2,0,0,0,1,2},{2,0,2,2,0,1,0,1,0,1,0,2,1},
    {1,0,1,0,1,1,0,1,0,0,1,0,1},{2,2,2,0,0,1,0,1,0,1,2,0,1},{1,1,0,0,1,1,0,1,0,0,0,0,1},
    {1,0,0,0,0,1,0,1,0,1,0,0,1},{1,0,0,0,0,0,0,1,1,1,1,1,0},{1,1,0,0,1,0,0,1,1,0,1,1,0},
    {1,1,1,0,0,0,0,1,1,1,0,1,0},{1,0,1,0,1,0,0,1,1,0,0,1,0},{1,0,1,1,0,0,0,1,1,1,1,0,0},
    {2,2,2,1,1,0,0,1,1,0,2,0,0},{1,1,0,1,0,0,0,1,1,1,0,0,0},{1,0,0,1,1,0,0,1,1,0,0,0,0},
    {2,0,0,2,2,0,0,1,1,2,2,2,1},{2,1,0,1,0,0,0,2,2,0,1,1,2},{3,2,1,1,2,0,0,3,3,2,0,1,3},
    {2,0,1,1,0,0,0,2,2,0,0,1,2},{2,0,1,0,1,0,0,2,2,1,1,0,2},{2,1,1,0,0,0,0,2,2,0,1,0,2},
    {2,1,0,0,1,0,0,2,2,1,0,0,2},{1,0,0,0,0,0,0,1,1,0,0,0,1},{1,0,0,0,0,0,0,1,1,0,0,0,1},
    {1,1,0,0,1,0,0,1,1,1,0,0,1},{2,1,1,0,0,0,0,2,2,0,1,0,2},{1,0,1,0,1,0,0,1,1,1,1,0,1},
    {1,0,1,1,0,0,0,1,1,0,0,1,1},{2,1,1,2,2,0,0,1,1,1,0,1,2},{1,1,0,1,0,0,0,1,1,0,1,1,1},
    {2,0,0,1,1,0,0,2,2,2,2,2,1},{1,0,0,1,1,0,0,1,1,0,0,0,0},{1,1,0,1,0,0,0,1,1,1,0,0,0},
    {1,1,1,1,1,0,0,1,1,0,1,0,0},{1,0,1,1,0,0,0,1,1,1,1,0,0},{1,0,1,0,1,0,0,1,1,0,0,1,0},
    {1,1,1,0,0,0,0,1,1,1,0,1,0},{1,1,0,0,1,0,0,1,1,0,1,1,0},{1,0,0,0,0,0,0,1,1,1,1,1,0},
    {1,0,0,0,0,1,0,1,0,1,0,0,1},{1,1,0,0,1,1,0,1,0,0,0,0,1},{1,1,1,0,0,1,0,1,0,1,1,0,1},
    {1,0,1,0,1,1,0,1,0,0,1,0,1},{1,0,1,1,0,1,0,1,0,1,0,1,1},{2,2,2,1,1,2,0,2,0,0,0,2,1},
    {2,1,0,1,0,2,0,2,0,1,2,2,1},{2,0,0,2,2,1,0,1,0,0,1,1,2},{1,0,0,1,1,1,0,1,0,1,0,0,0},
    {1,1,0,1,0,1,0,1,0,0,0,0,0},{2,1,2,2,1,2,0,2,0,1,2,0,0},{1,0,1,1,0,1,0,1,0,0,1,0,0},
    {1,0,1,0,1,1,0,1,0,1,0,1,0},{1,1,1,0,0,1,0,1,0,0,0,1,0},{2,2,0,0,2,1,0,1,0,2,1,1,0},
    {1,0,0,0,0,1,0,1,0,0,1,1,0},{1,0,0,0,0,1,1,1,1,0,1,0,1},{2,1,0,0,1,2,1,1,2,2,1,0,1},
    {1,1,1,0,0,1,1,1,1,0,0,0,1},{2,0,2,0,2,1,2,2,1,1,0,0,2},{2,0,1,1,0,1,2,2,1,0,1,2,1},
    {4,1,1,3,3,2,4,4,2,2,1,4,3},{2,2,0,2,0,2,1,1,2,0,0,1,2},{3,0,0,1,1,2,3,3,2,2,0,3,1},
    {1,0,0,1,1,1,1,1,1,0,1,0,0},{2,2,0,2,0,1,2,2,1,1,2,0,0},{2,2,1,1,2,2,1,1,2,0,0,0,0},
    {2,0,1,1,0,2,1,1,2,2,0,0,0},{2,0,2,0,2,2,1,1,2,0,2,1,0},{3,1,1,0,0,3,2,2,3,3,1,2,0},
    {2,1,0,0,1,1,2,2,1,0,0,2,0},{2,0,0,0,0,2,1,1,2,2,0,1,0},{1,0,0,0,0,0,1,1,0,1,1,0,1},
    {1,1,0,0,1,0,1,1,0,0,1,0,1},{1,1,1,0,0,0,1,1,0,1,0,0,1},{1,0,1,0,1,0,1,1,0,0,0,0,1},
    {2,0,2,2,0,0,1,1,0,2,2,1,2},{3,1,1,2,2,0,3,3,0,0,1,3,2},{2,1,0,1,0,0,2,2,0,1,0,2,1},
    {2,0,0,1,1,0,2,2,0,0,0,2,1},{1,0,0,1,1,0,1,1,0,1,1,0,0},{1,1,0,1,0,0,1,1,0,0,1,0,0},
    {2,2,1,1,2,0,1,1,0,2,0,0,0},{1,0,1,1,0,0,1,1,0,0,0,0,0},{2,0,1,0,1,0,2,2,0,1,1,2,0},
    {2,1,1,0,0,0,2,2,0,0,1,2,0},{2,1,0,0,1,0,2,2,0,1,0,2,0},{1,0,0,0,0,0,1,1,0,0,0,1,0},
    {1,0,0,0,0,0,1,0,1,0,0,1,1},{1,1,0,0,1,0,1,0,1,1,0,1,1},{1,1,1,0,0,0,1,0,1,0,1,1,1},
    {2,0,2,0,2,0,1,0,1,1,1,2,2},{1,0,1,1,0,0,1,0,1,0,0,0,1},{2,2,2,1,1,0,2,0,2,2,0,0,1},
    {1,1,0,1,0,0,1,0,1,0,1,0,1},{2,0,0,2,2,0,1,0,1,1,1,0,2},{1,0,0,1,1,0,1,0,1,0,0,1,0},
    {1,1,0,1,0,0,1,0,1,1,0,1,0},{2,2,1,1,2,0,2,0,2,0,2,1,0},{2,0,2,2,0,0,1,0,1,1,1,2,0},
    {1,0,1,0,1,0,1,0,1,0,0,0,0},{1,1,1,0,0,0,1,0,1,1,0,0,0},{1,1,0,0,1,0,1,0,1,0,1,0,0},
    {1,0,0,0,0,0,1,0,1,1,1,0,0},{1,0,0,0,0,1,1,0,0,1,0,1,1},{1,1,0,0,1,1,1,0,0,0,0,1,1},
    {2,2,2,0,0,1,1,0,0,2,1,2,2},{2,0,1,0,1,2,2,0,0,0,2,1,1},{1,0,1,1,0,1,1,0,0,1,0,0,1},
    {2,1,1,2,2,1,1,0,0,0,0,0,2},{2,1,0,1,0,2,2,0,0,1,2,0,1},{2,0,0,2,2,1,1,0,0,0,1,0,2},
    {1,0,0,1,1,1,1,0,0,1,0,1,0},{1,1,0,1,0,1,1,0,0,0,0,1,0},{3,1,2,2,1,3,3,0,0,1,3,2,0},
    {2,0,1,1,0,2,2,0,0,0,2,1,0},{1,0,1,0,1,1,1,0,0,1,0,0,0},{1,1,1,0,0,1,1,0,0,0,0,0,0},
    {2,2,0,0,2,1,1,0,0,2,1,0,0},{1,0,0,0,0,1,1,0,0,0,1,0,0},{1,0,0,0,0,1,0,0,1,0,1,1,1},
    {2,2,0,0,2,1,0,0,1,1,2,2,2},{1,1,1,0,0,1,0,0,1,0,0,1,1},{2,0,1,0,1,2,0,0,2,2,0,1,1},
    {1,0,1,1,0,1,0,0,1,0,1,0,1},{3,1,1,3,3,2,0,0,2,2,1,0,3},{1,1,0,1,0,1,0,0,1,0,0,0,1},
    {2,0,0,2,2,1,0,0,1,1,0,0,2},{1,0,0,1,1,1,0,0,1,0,1,1,0},{2,1,0,1,0,2,0,0,2,2,1,1,0},
    {2,1,2,2,1,1,0,0,1,0,0,2,0},{2,0,1,1,0,2,0,0,2,2,0,1,0},{1,0,1,0,1,1,0,0,1,0,1,0,0},
    {2,1,1,0,0,2,0,0,2,2,1,0,0},{1,1,0,0,1,1,0,0,1,0,0,0,0},{1,0,0,0,0,1,0,0,1,1,0,0,0},
    {1,0,0,0,0,0,0,0,0,1,1,1,1},{1,1,0,0,1,0,0,0,0,0,1,1,1},{1,1,1,0,0,0,0,0,0,1,0,1,1},
    {1,0,1,0,1,0,0,0,0,0,0,1,1},{1,0,1,1,0,0,0,0,0,1,1,0,1},{2,1,1,2,2,0,0,0,0,0,1,0,2},
    {1,1,0,1,0,0,0,0,0,1,0,0,1},{1,0,0,1,1,0,0,0,0,0,0,0,1},{1,0,0,1,1,0,0,0,0,1,1,1,0},
    {1,1,0,1,0,0,0,0,0,0,1,1,0},{2,1,2,2,1,0,0,0,0,1,0,2,0},{1,0,1,1,0,0,0,0,0,0,0,1,0},
    {1,0,1,0,1,0,0,0,0,1,1,0,0},{1,1,1,0,0,0,0,0,0,0,1,0,0},{1,1,0,0,1,0,0,0,0,1,0,0,0},
    {0,0,0,0,0,0,0,0,0,0,0,0,0}};


////////////////////////////////////////

inline bool
isPlanarQuad(
    const Vec3d& p0, const Vec3d& p1,
    const Vec3d& p2, const Vec3d& p3,
    double epsilon = 0.001)
{
    // compute representative plane
    Vec3d normal = (p2-p0).cross(p1-p3);
    normal.normalize();
    const Vec3d centroid = (p0 + p1 + p2 + p3);
    const double d = centroid.dot(normal) * 0.25;


    // test vertice distance to plane
    double absDist = std::abs(p0.dot(normal) - d);
    if (absDist > epsilon) return false;

    absDist = std::abs(p1.dot(normal) - d);
    if (absDist > epsilon) return false;

    absDist = std::abs(p2.dot(normal) - d);
    if (absDist > epsilon) return false;

    absDist = std::abs(p3.dot(normal) - d);
    if (absDist > epsilon) return false;

    return true;
}


////////////////////////////////////////


/// @{
/// @brief  Utility methods for point quantization.

enum { MASK_FIRST_10_BITS = 0x000003FF, MASK_DIRTY_BIT = 0x80000000, MASK_INVALID_BIT = 0x40000000 };

inline uint32_t
packPoint(const Vec3d& v)
{
    uint32_t data = 0;

    // values are expected to be in the [0.0 to 1.0] range.
    assert(!(v.x() > 1.0) && !(v.y() > 1.0) && !(v.z() > 1.0));
    assert(!(v.x() < 0.0) && !(v.y() < 0.0) && !(v.z() < 0.0));

    data |= (uint32_t(v.x() * 1023.0) & MASK_FIRST_10_BITS) << 20;
    data |= (uint32_t(v.y() * 1023.0) & MASK_FIRST_10_BITS) << 10;
    data |= (uint32_t(v.z() * 1023.0) & MASK_FIRST_10_BITS);

    return data;
}

inline Vec3d
unpackPoint(uint32_t data)
{
    Vec3d v;
    v.z() = double(data & MASK_FIRST_10_BITS) * 0.0009775171;
    data = data >> 10;
    v.y() = double(data & MASK_FIRST_10_BITS) * 0.0009775171;
    data = data >> 10;
    v.x() = double(data & MASK_FIRST_10_BITS) * 0.0009775171;

    return v;
}

/// @}

////////////////////////////////////////


/// @brief  General method that computes the cell-sign configuration at the given
///         @c ijk coordinate.
template<typename AccessorT>
inline unsigned char
evalCellSigns(const AccessorT& accessor, const Coord& ijk, typename AccessorT::ValueType iso)
{
    unsigned signs = 0;
    Coord coord = ijk; // i, j, k
    if (accessor.getValue(coord) < iso) signs |= 1u;
    coord[0] += 1; // i+1, j, k
    if (accessor.getValue(coord) < iso) signs |= 2u;
    coord[2] += 1; // i+1, j, k+1
    if (accessor.getValue(coord) < iso) signs |= 4u;
    coord[0] = ijk[0]; // i, j, k+1
    if (accessor.getValue(coord) < iso) signs |= 8u;
    coord[1] += 1; coord[2] = ijk[2]; // i, j+1, k
    if (accessor.getValue(coord) < iso) signs |= 16u;
    coord[0] += 1; // i+1, j+1, k
    if (accessor.getValue(coord) < iso) signs |= 32u;
    coord[2] += 1; // i+1, j+1, k+1
    if (accessor.getValue(coord) < iso) signs |= 64u;
    coord[0] = ijk[0]; // i, j+1, k+1
    if (accessor.getValue(coord) < iso) signs |= 128u;
    return signs;
}


/// @brief  Leaf node optimized method that computes the cell-sign configuration
///         at the given local @c offset
template<typename LeafT>
inline unsigned char
evalCellSigns(const LeafT& leaf, const Index offset, typename LeafT::ValueType iso)
{
    unsigned char signs = 0;

    // i, j, k
    if (leaf.getValue(offset) < iso) signs |= 1u;

    // i, j, k+1
    if (leaf.getValue(offset + 1) < iso) signs |= 8u;

    // i, j+1, k
    if (leaf.getValue(offset + LeafT::DIM) < iso) signs |= 16u;

    // i, j+1, k+1
    if (leaf.getValue(offset + LeafT::DIM + 1) < iso) signs |= 128u;

    // i+1, j, k
    if (leaf.getValue(offset + (LeafT::DIM * LeafT::DIM) ) < iso) signs |= 2u;

    // i+1, j, k+1
    if (leaf.getValue(offset + (LeafT::DIM * LeafT::DIM) + 1) < iso) signs |= 4u;

    // i+1, j+1, k
    if (leaf.getValue(offset + (LeafT::DIM * LeafT::DIM) + LeafT::DIM) < iso) signs |= 32u;

    // i+1, j+1, k+1
    if (leaf.getValue(offset + (LeafT::DIM * LeafT::DIM) + LeafT::DIM + 1) < iso) signs |= 64u;

    return signs;
}


/// @brief  Used to correct topological ambiguities related to two adjacent cells
///         that share an ambiguous face.
template<class AccessorT>
inline void
correctCellSigns(unsigned char& signs, unsigned char face,
    const AccessorT& acc, Coord ijk, typename AccessorT::ValueType iso)
{
    if (face == 1) {
        ijk[2] -= 1;
        if (sAmbiguousFace[evalCellSigns(acc, ijk, iso)] == 3) signs = ~signs;
    } else if (face == 3) {
        ijk[2] += 1;
        if (sAmbiguousFace[evalCellSigns(acc, ijk, iso)] == 1) signs = ~signs;
    } else if (face == 2) {
        ijk[0] += 1;
        if (sAmbiguousFace[evalCellSigns(acc, ijk, iso)] == 4) signs = ~signs;
    } else if (face == 4) {
        ijk[0] -= 1;
        if (sAmbiguousFace[evalCellSigns(acc, ijk, iso)] == 2) signs = ~signs;
    } else if (face == 5) {
        ijk[1] -= 1;
        if (sAmbiguousFace[evalCellSigns(acc, ijk, iso)] == 6) signs = ~signs;
    } else if (face == 6) {
        ijk[1] += 1;
        if (sAmbiguousFace[evalCellSigns(acc, ijk, iso)] == 5) signs = ~signs;
    }
}


template<class AccessorT>
inline bool
isNonManifold(const AccessorT& accessor, const Coord& ijk,
    typename AccessorT::ValueType isovalue, const int dim)
{
    int hDim = dim >> 1;
    bool m, p[8]; // Corner signs

    Coord coord = ijk; // i, j, k
    p[0] = accessor.getValue(coord) < isovalue;
    coord[0] += dim; // i+dim, j, k
    p[1] = accessor.getValue(coord) < isovalue;
    coord[2] += dim; // i+dim, j, k+dim
    p[2] = accessor.getValue(coord) < isovalue;
    coord[0] = ijk[0]; // i, j, k+dim
    p[3] = accessor.getValue(coord) < isovalue;
    coord[1] += dim; coord[2] = ijk[2]; // i, j+dim, k
    p[4] = accessor.getValue(coord) < isovalue;
    coord[0] += dim; // i+dim, j+dim, k
    p[5] = accessor.getValue(coord) < isovalue;
    coord[2] += dim; // i+dim, j+dim, k+dim
    p[6] = accessor.getValue(coord) < isovalue;
    coord[0] = ijk[0]; // i, j+dim, k+dim
    p[7] = accessor.getValue(coord) < isovalue;

    // Check if the corner sign configuration is ambiguous
    unsigned signs = 0;
    if (p[0]) signs |= 1u;
    if (p[1]) signs |= 2u;
    if (p[2]) signs |= 4u;
    if (p[3]) signs |= 8u;
    if (p[4]) signs |= 16u;
    if (p[5]) signs |= 32u;
    if (p[6]) signs |= 64u;
    if (p[7]) signs |= 128u;
    if (!sAdaptable[signs]) return true;

    // Manifold check

    // Evaluate edges
    int i = ijk[0], ip = ijk[0] + hDim, ipp = ijk[0] + dim;
    int j = ijk[1], jp = ijk[1] + hDim, jpp = ijk[1] + dim;
    int k = ijk[2], kp = ijk[2] + hDim, kpp = ijk[2] + dim;

    // edge 1
    coord.reset(ip, j, k);
    m = accessor.getValue(coord) < isovalue;
    if (p[0] != m && p[1] != m) return true;

    // edge 2
    coord.reset(ipp, j, kp);
    m = accessor.getValue(coord) < isovalue;
    if (p[1] != m && p[2] != m) return true;

    // edge 3
    coord.reset(ip, j, kpp);
    m = accessor.getValue(coord) < isovalue;
    if (p[2] != m && p[3] != m) return true;

    // edge 4
    coord.reset(i, j, kp);
    m = accessor.getValue(coord) < isovalue;
    if (p[0] != m && p[3] != m) return true;

    // edge 5
    coord.reset(ip, jpp, k);
    m = accessor.getValue(coord) < isovalue;
    if (p[4] != m && p[5] != m) return true;

    // edge 6
    coord.reset(ipp, jpp, kp);
    m = accessor.getValue(coord) < isovalue;
    if (p[5] != m && p[6] != m) return true;

    // edge 7
    coord.reset(ip, jpp, kpp);
    m = accessor.getValue(coord) < isovalue;
    if (p[6] != m && p[7] != m) return true;

    // edge 8
    coord.reset(i, jpp, kp);
    m = accessor.getValue(coord) < isovalue;
    if (p[7] != m && p[4] != m) return true;

    // edge 9
    coord.reset(i, jp, k);
    m = accessor.getValue(coord) < isovalue;
    if (p[0] != m && p[4] != m) return true;

    // edge 10
    coord.reset(ipp, jp, k);
    m = accessor.getValue(coord) < isovalue;
    if (p[1] != m && p[5] != m) return true;

    // edge 11
    coord.reset(ipp, jp, kpp);
    m = accessor.getValue(coord) < isovalue;
    if (p[2] != m && p[6] != m) return true;


    // edge 12
    coord.reset(i, jp, kpp);
    m = accessor.getValue(coord) < isovalue;
    if (p[3] != m && p[7] != m) return true;


    // Evaluate faces

    // face 1
    coord.reset(ip, jp, k);
    m = accessor.getValue(coord) < isovalue;
    if (p[0] != m && p[1] != m && p[4] != m && p[5] != m) return true;

    // face 2
    coord.reset(ipp, jp, kp);
    m = accessor.getValue(coord) < isovalue;
    if (p[1] != m && p[2] != m && p[5] != m && p[6] != m) return true;

    // face 3
    coord.reset(ip, jp, kpp);
    m = accessor.getValue(coord) < isovalue;
    if (p[2] != m && p[3] != m && p[6] != m && p[7] != m) return true;

    // face 4
    coord.reset(i, jp, kp);
    m = accessor.getValue(coord) < isovalue;
    if (p[0] != m && p[3] != m && p[4] != m && p[7] != m) return true;

    // face 5
    coord.reset(ip, j, kp);
    m = accessor.getValue(coord) < isovalue;
    if (p[0] != m && p[1] != m && p[2] != m && p[3] != m) return true;

    // face 6
    coord.reset(ip, jpp, kp);
    m = accessor.getValue(coord) < isovalue;
    if (p[4] != m && p[5] != m && p[6] != m && p[7] != m) return true;

    // test cube center
    coord.reset(ip, jp, kp);
    m = accessor.getValue(coord) < isovalue;
    if (p[0] != m && p[1] != m && p[2] != m && p[3] != m &&
        p[4] != m && p[5] != m && p[6] != m && p[7] != m) return true;

    return false;
}


////////////////////////////////////////


template <class LeafType>
inline void
mergeVoxels(LeafType& leaf, const Coord& start, int dim, int regionId)
{
    Coord ijk, end = start;
    end[0] += dim;
    end[1] += dim;
    end[2] += dim;

    for (ijk[0] = start[0]; ijk[0] < end[0]; ++ijk[0]) {
        for (ijk[1] = start[1]; ijk[1] < end[1]; ++ijk[1]) {
            for (ijk[2] = start[2]; ijk[2] < end[2]; ++ijk[2]) {
                if(leaf.isValueOn(ijk)) leaf.setValue(ijk, regionId);
            }
        }
    }
}


// Note that we must use ValueType::value_type or else Visual C++ gets confused
// thinking that it is a constructor.
template <class LeafType>
inline bool
isMergable(LeafType& leaf, const Coord& start, int dim,
    typename LeafType::ValueType::value_type adaptivity)
{
    if (adaptivity < 1e-6) return false;

    typedef typename LeafType::ValueType VecT;
    Coord ijk, end = start;
    end[0] += dim;
    end[1] += dim;
    end[2] += dim;

    std::vector<VecT> norms;
    for (ijk[0] = start[0]; ijk[0] < end[0]; ++ijk[0]) {
        for (ijk[1] = start[1]; ijk[1] < end[1]; ++ijk[1]) {
            for (ijk[2] = start[2]; ijk[2] < end[2]; ++ijk[2]) {

                if(!leaf.isValueOn(ijk)) continue;
                norms.push_back(leaf.getValue(ijk));
            }
        }
    }

    size_t N = norms.size();
    for (size_t ni = 0; ni < N; ++ni) {
        VecT n_i = norms[ni];
        for (size_t nj = 0; nj < N; ++nj) {
            VecT n_j = norms[nj];
            if ((1.0 - n_i.dot(n_j)) > adaptivity) return false;
        }
    }
    return true;
}


////////////////////////////////////////


template<typename TreeT, typename LeafManagerT>
class SignData
{
public:
    typedef typename TreeT::ValueType ValueT;
    typedef tree::ValueAccessor<const TreeT> AccessorT;

    typedef typename TreeT::template ValueConverter<int>::Type IntTreeT;
    typedef tree::ValueAccessor<IntTreeT> IntAccessorT;

    typedef typename TreeT::template ValueConverter<Int16>::Type Int16TreeT;
    typedef tree::ValueAccessor<Int16TreeT> Int16AccessorT;

    //////////


    SignData(const TreeT& distTree, const LeafManagerT& leafs, ValueT iso);

    void run(bool threaded = true);

    typename Int16TreeT::Ptr signTree() const { return mSignTree; }
    typename IntTreeT::Ptr idxTree() const { return mIdxTree; }

    //////////

    SignData(SignData&, tbb::split);
    void operator()(const tbb::blocked_range<size_t>&);
    void join(const SignData& rhs)
    {
        mSignTree->merge(*rhs.mSignTree);
        mIdxTree->merge(*rhs.mIdxTree);
    }

private:

    const TreeT& mDistTree;
    AccessorT mDistAcc;

    const LeafManagerT& mLeafs;
    ValueT mIsovalue;

    typename Int16TreeT::Ptr mSignTree;
    Int16AccessorT mSignAcc;

    typename IntTreeT::Ptr mIdxTree;
    IntAccessorT mIdxAcc;

};


template<typename TreeT, typename LeafManagerT>
SignData<TreeT, LeafManagerT>::SignData(const TreeT& distTree,
    const LeafManagerT& leafs, ValueT iso)
    : mDistTree(distTree)
    , mDistAcc(mDistTree)
    , mLeafs(leafs)
    , mIsovalue(iso)
    , mSignTree(new Int16TreeT(0))
    , mSignAcc(*mSignTree)
    , mIdxTree(new IntTreeT(int(util::INVALID_IDX)))
    , mIdxAcc(*mIdxTree)
{
}


template<typename TreeT, typename LeafManagerT>
SignData<TreeT, LeafManagerT>::SignData(SignData& rhs, tbb::split)
    : mDistTree(rhs.mDistTree)
    , mDistAcc(mDistTree)
    , mLeafs(rhs.mLeafs)
    , mIsovalue(rhs.mIsovalue)
    , mSignTree(new Int16TreeT(0))
    , mSignAcc(*mSignTree)
    , mIdxTree(new IntTreeT(int(util::INVALID_IDX)))
    , mIdxAcc(*mIdxTree)
{
}


template<typename TreeT, typename LeafManagerT>
void
SignData<TreeT, LeafManagerT>::run(bool threaded)
{
    if (threaded) tbb::parallel_reduce(mLeafs.getRange(), *this);
    else (*this)(mLeafs.getRange());
}

template<typename TreeT, typename LeafManagerT>
void
SignData<TreeT, LeafManagerT>::operator()(const tbb::blocked_range<size_t>& range)
{
    typedef typename Int16TreeT::LeafNodeType Int16LeafT;
    typedef typename IntTreeT::LeafNodeType IntLeafT;
    typename LeafManagerT::TreeType::LeafNodeType::ValueOnCIter iter;
    unsigned char signs, face;
    Coord ijk, coord;

    typename internal::UniquePtr<Int16LeafT>::type signLeafPt(new Int16LeafT(ijk, 0));

    for (size_t n = range.begin(); n != range.end(); ++n) {

        bool collectedData = false;

        coord = mLeafs.leaf(n).origin();

        if (!signLeafPt.get()) signLeafPt.reset(new Int16LeafT(coord, 0));
        else signLeafPt->setOrigin(coord);

        const typename TreeT::LeafNodeType *leafPt = mDistAcc.probeConstLeaf(coord);

        coord.offset(TreeT::LeafNodeType::DIM - 1);

        for (iter = mLeafs.leaf(n).cbeginValueOn(); iter; ++iter) {

            ijk = iter.getCoord();

            if (leafPt && ijk[0] < coord[0] && ijk[1] < coord[1] && ijk[2] < coord[2]) {
                signs = evalCellSigns(*leafPt, iter.pos(), mIsovalue);
            } else {
                signs = evalCellSigns(mDistAcc, ijk, mIsovalue);
            }

            if (signs != 0 && signs != 0xFF) {
                Int16 flags = (signs & 0x1) ? INSIDE : 0;

                if (bool(signs & 0x1) != bool(signs & 0x2)) flags |= XEDGE;
                if (bool(signs & 0x1) != bool(signs & 0x10)) flags |= YEDGE;
                if (bool(signs & 0x1) != bool(signs & 0x8)) flags |= ZEDGE;

                face = internal::sAmbiguousFace[signs];
                if (face != 0) correctCellSigns(signs, face, mDistAcc, ijk, mIsovalue);

                flags |= Int16(signs);

                signLeafPt->setValue(ijk, flags);
                collectedData = true;
            }
        }

        if (collectedData) {

            IntLeafT* idxLeaf = mIdxAcc.touchLeaf(coord);
            idxLeaf->topologyUnion(*signLeafPt);
            typename IntLeafT::ValueOnIter it = idxLeaf->beginValueOn();
            for (; it; ++it) {
                it.setValue(0);
            }

            mSignAcc.addLeaf(signLeafPt.release());
        }
    }
}


////////////////////////////////////////


/// @brief Counts the total number of points per leaf, accounts for cells with multiple points.
class CountPoints
{
public:
    CountPoints(std::vector<size_t>& pointList) : mPointList(pointList) {}

    template <typename LeafNodeType>
    void operator()(LeafNodeType &leaf, size_t leafIndex) const
    {
        size_t points = 0;

        typename LeafNodeType::ValueOnCIter iter = leaf.cbeginValueOn();
        for (; iter; ++iter) {
            points += size_t(sEdgeGroupTable[(SIGNS & iter.getValue())][0]);
        }

        mPointList[leafIndex] = points;
    }

private:
    std::vector<size_t>& mPointList;
};


/// @brief Computes the point list indices for the index tree.
template<typename Int16TreeT>
class MapPoints
{
public:
    typedef tree::ValueAccessor<const Int16TreeT> Int16AccessorT;

    MapPoints(std::vector<size_t>& pointList, const Int16TreeT& signTree)
        : mPointList(pointList)
        , mSignAcc(signTree)
    {
    }

    template <typename LeafNodeType>
    void operator()(LeafNodeType &leaf, size_t leafIndex) const
    {
        size_t ptnIdx = mPointList[leafIndex];
        typename LeafNodeType::ValueOnIter iter = leaf.beginValueOn();

        const typename Int16TreeT::LeafNodeType *signLeafPt =
            mSignAcc.probeConstLeaf(leaf.origin());

        for (; iter; ++iter) {
            iter.setValue(ptnIdx);
            unsigned signs = SIGNS & signLeafPt->getValue(iter.pos());
            ptnIdx += size_t(sEdgeGroupTable[signs][0]);
        }
    }

private:
    std::vector<size_t>& mPointList;
    Int16AccessorT mSignAcc;
};


/// @brief Counts the total number of points per collapsed region
template<typename IntTreeT>
class CountRegions
{
public:
    typedef tree::ValueAccessor<IntTreeT> IntAccessorT;
    typedef typename IntTreeT::LeafNodeType IntLeafT;

    CountRegions(IntTreeT& idxTree, std::vector<size_t>& regions)
    : mIdxAcc(idxTree)
    , mRegions(regions)
    {
    }

    template <typename LeafNodeType>
    void operator()(LeafNodeType &leaf, size_t leafIndex) const
    {

        size_t regions = 0;

        IntLeafT tmpLeaf(*mIdxAcc.probeConstLeaf(leaf.origin()));

        typename IntLeafT::ValueOnIter iter = tmpLeaf.beginValueOn();
        for (; iter; ++iter) {
            if(iter.getValue() == 0) {
                iter.setValueOff();
                regions += size_t(sEdgeGroupTable[(SIGNS & leaf.getValue(iter.pos()))][0]);
            }
        }

        int onVoxelCount = int(tmpLeaf.onVoxelCount());
        while (onVoxelCount > 0) {
            ++regions;
            iter = tmpLeaf.beginValueOn();
            int regionId = iter.getValue();
            for (; iter; ++iter) {
                if (iter.getValue() == regionId) {
                    iter.setValueOff();
                    --onVoxelCount;
                }
            }
        }

        mRegions[leafIndex] = regions;
    }

private:
    IntAccessorT mIdxAcc;
    std::vector<size_t>& mRegions;
};


////////////////////////////////////////


// @brief linear interpolation.
inline double evalRoot(double v0, double v1, double iso) { return (iso - v0) / (v1 - v0); }


/// @brief Extracts the eight corner values for leaf inclusive cells.
template<typename LeafT>
inline void
collectCornerValues(const LeafT& leaf, const Index offset, std::vector<double>& values)
{
    values[0] = double(leaf.getValue(offset)); // i, j, k
    values[3] = double(leaf.getValue(offset + 1)); // i, j, k+1
    values[4] = double(leaf.getValue(offset + LeafT::DIM)); // i, j+1, k
    values[7] = double(leaf.getValue(offset + LeafT::DIM + 1)); // i, j+1, k+1
    values[1] = double(leaf.getValue(offset + (LeafT::DIM * LeafT::DIM))); // i+1, j, k
    values[2] = double(leaf.getValue(offset + (LeafT::DIM * LeafT::DIM) + 1)); // i+1, j, k+1
    values[5] = double(leaf.getValue(offset + (LeafT::DIM * LeafT::DIM) + LeafT::DIM)); // i+1, j+1, k
    values[6] = double(leaf.getValue(offset + (LeafT::DIM * LeafT::DIM) + LeafT::DIM + 1)); // i+1, j+1, k+1
}


/// @brief Extracts the eight corner values for a cell starting at the given @ijk coordinate.
template<typename AccessorT>
inline void
collectCornerValues(const AccessorT& acc, const Coord& ijk, std::vector<double>& values)
{
    Coord coord = ijk;
    values[0] = double(acc.getValue(coord)); // i, j, k

    coord[0] += 1;
    values[1] = double(acc.getValue(coord)); // i+1, j, k

    coord[2] += 1;
    values[2] = double(acc.getValue(coord)); // i+i, j, k+1

    coord[0] = ijk[0];
    values[3] = double(acc.getValue(coord)); // i, j, k+1

    coord[1] += 1; coord[2] = ijk[2];
    values[4] = double(acc.getValue(coord)); // i, j+1, k

    coord[0] += 1;
    values[5] = double(acc.getValue(coord)); // i+1, j+1, k

    coord[2] += 1;
    values[6] = double(acc.getValue(coord)); // i+1, j+1, k+1

    coord[0] = ijk[0];
    values[7] = double(acc.getValue(coord)); // i, j+1, k+1
}


/// @brief Computes the average cell point for a given edge group.
inline Vec3d
computePoint(const std::vector<double>& values, unsigned char signs,
    unsigned char edgeGroup, double iso)
{
    Vec3d avg(0.0, 0.0, 0.0);
    int samples = 0;

    if (sEdgeGroupTable[signs][1] == edgeGroup) { // Edged: 0 - 1
        avg[0] += evalRoot(values[0], values[1], iso);
        ++samples;
    }

    if (sEdgeGroupTable[signs][2] == edgeGroup) { // Edged: 1 - 2
        avg[0] += 1.0;
        avg[2] += evalRoot(values[1], values[2], iso);
        ++samples;
    }

    if (sEdgeGroupTable[signs][3] == edgeGroup) { // Edged: 3 - 2
        avg[0] += evalRoot(values[3], values[2], iso);
        avg[2] += 1.0;
        ++samples;
    }

    if (sEdgeGroupTable[signs][4] == edgeGroup) { // Edged: 0 - 3
        avg[2] += evalRoot(values[0], values[3], iso);
        ++samples;
    }

    if (sEdgeGroupTable[signs][5] == edgeGroup) { // Edged: 4 - 5
        avg[0] += evalRoot(values[4], values[5], iso);
        avg[1] += 1.0;
        ++samples;
    }

    if (sEdgeGroupTable[signs][6] == edgeGroup) { // Edged: 5 - 6
        avg[0] += 1.0;
        avg[1] += 1.0;
        avg[2] += evalRoot(values[5], values[6], iso);
        ++samples;
    }

    if (sEdgeGroupTable[signs][7] == edgeGroup) { // Edged: 7 - 6
        avg[0] += evalRoot(values[7], values[6], iso);
        avg[1] += 1.0;
        avg[2] += 1.0;
        ++samples;
    }

    if (sEdgeGroupTable[signs][8] == edgeGroup) { // Edged: 4 - 7
        avg[1] += 1.0;
        avg[2] += evalRoot(values[4], values[7], iso);
        ++samples;
    }

    if (sEdgeGroupTable[signs][9] == edgeGroup) { // Edged: 0 - 4
        avg[1] += evalRoot(values[0], values[4], iso);
        ++samples;
    }

    if (sEdgeGroupTable[signs][10] == edgeGroup) { // Edged: 1 - 5
        avg[0] += 1.0;
        avg[1] += evalRoot(values[1], values[5], iso);
        ++samples;
    }

    if (sEdgeGroupTable[signs][11] == edgeGroup) { // Edged: 2 - 6
        avg[0] += 1.0;
        avg[1] += evalRoot(values[2], values[6], iso);
        avg[2] += 1.0;
        ++samples;
    }

    if (sEdgeGroupTable[signs][12] == edgeGroup) { // Edged: 3 - 7
        avg[1] += evalRoot(values[3], values[7], iso);
        avg[2] += 1.0;
        ++samples;
    }

    if (samples > 1) {
        double w = 1.0 / double(samples);
        avg[0] *= w;
        avg[1] *= w;
        avg[2] *= w;
    }

    return avg;
}


/// @brief  Computes the average cell point for a given edge group, ignoring edge
///         samples present in the @c signsMask configuration.
inline int
computeMaskedPoint(Vec3d& avg, const std::vector<double>& values, unsigned char signs,
    unsigned char signsMask, unsigned char edgeGroup, double iso)
{
    avg = Vec3d(0.0, 0.0, 0.0);
    int samples = 0;

    if (sEdgeGroupTable[signs][1] == edgeGroup
        && sEdgeGroupTable[signsMask][1] == 0) { // Edged: 0 - 1
        avg[0] += evalRoot(values[0], values[1], iso);
        ++samples;
    }

    if (sEdgeGroupTable[signs][2] == edgeGroup
        && sEdgeGroupTable[signsMask][2] == 0) { // Edged: 1 - 2
        avg[0] += 1.0;
        avg[2] += evalRoot(values[1], values[2], iso);
        ++samples;
    }

    if (sEdgeGroupTable[signs][3] == edgeGroup
        && sEdgeGroupTable[signsMask][3] == 0) { // Edged: 3 - 2
        avg[0] += evalRoot(values[3], values[2], iso);
        avg[2] += 1.0;
        ++samples;
    }

    if (sEdgeGroupTable[signs][4] == edgeGroup
        && sEdgeGroupTable[signsMask][4] == 0) { // Edged: 0 - 3
        avg[2] += evalRoot(values[0], values[3], iso);
        ++samples;
    }

    if (sEdgeGroupTable[signs][5] == edgeGroup
        && sEdgeGroupTable[signsMask][5] == 0) { // Edged: 4 - 5
        avg[0] += evalRoot(values[4], values[5], iso);
        avg[1] += 1.0;
        ++samples;
    }

    if (sEdgeGroupTable[signs][6] == edgeGroup
        && sEdgeGroupTable[signsMask][6] == 0) { // Edged: 5 - 6
        avg[0] += 1.0;
        avg[1] += 1.0;
        avg[2] += evalRoot(values[5], values[6], iso);
        ++samples;
    }

    if (sEdgeGroupTable[signs][7] == edgeGroup
        && sEdgeGroupTable[signsMask][7] == 0) { // Edged: 7 - 6
        avg[0] += evalRoot(values[7], values[6], iso);
        avg[1] += 1.0;
        avg[2] += 1.0;
        ++samples;
    }

    if (sEdgeGroupTable[signs][8] == edgeGroup
        && sEdgeGroupTable[signsMask][8] == 0) { // Edged: 4 - 7
        avg[1] += 1.0;
        avg[2] += evalRoot(values[4], values[7], iso);
        ++samples;
    }

    if (sEdgeGroupTable[signs][9] == edgeGroup
        && sEdgeGroupTable[signsMask][9] == 0) { // Edged: 0 - 4
        avg[1] += evalRoot(values[0], values[4], iso);
        ++samples;
    }

    if (sEdgeGroupTable[signs][10] == edgeGroup
        && sEdgeGroupTable[signsMask][10] == 0) { // Edged: 1 - 5
        avg[0] += 1.0;
        avg[1] += evalRoot(values[1], values[5], iso);
        ++samples;
    }

    if (sEdgeGroupTable[signs][11] == edgeGroup
        && sEdgeGroupTable[signsMask][11] == 0) { // Edged: 2 - 6
        avg[0] += 1.0;
        avg[1] += evalRoot(values[2], values[6], iso);
        avg[2] += 1.0;
        ++samples;
    }

    if (sEdgeGroupTable[signs][12] == edgeGroup
        && sEdgeGroupTable[signsMask][12] == 0) { // Edged: 3 - 7
        avg[1] += evalRoot(values[3], values[7], iso);
        avg[2] += 1.0;
        ++samples;
    }

    if (samples > 1) {
        double w = 1.0 / double(samples);
        avg[0] *= w;
        avg[1] *= w;
        avg[2] *= w;
    }

    return samples;
}


/// @brief  Computes the average cell point for a given edge group, by computing
///         convex weights based on the distance from the sample point @c p.
inline Vec3d
computeWeightedPoint(const Vec3d& p, const std::vector<double>& values,
    unsigned char signs, unsigned char edgeGroup, double iso)
{
    std::vector<Vec3d> samples;
    samples.reserve(8);

    std::vector<double> weights;
    weights.reserve(8);

    Vec3d avg(0.0, 0.0, 0.0);

    if (sEdgeGroupTable[signs][1] == edgeGroup) { // Edged: 0 - 1
        avg[0] = evalRoot(values[0], values[1], iso);
        avg[1] = 0.0;
        avg[2] = 0.0;

        samples.push_back(avg);
        weights.push_back((avg-p).lengthSqr());
    }

    if (sEdgeGroupTable[signs][2] == edgeGroup) { // Edged: 1 - 2
        avg[0] = 1.0;
        avg[1] = 0.0;
        avg[2] = evalRoot(values[1], values[2], iso);

        samples.push_back(avg);
        weights.push_back((avg-p).lengthSqr());
    }

    if (sEdgeGroupTable[signs][3] == edgeGroup) { // Edged: 3 - 2
        avg[0] = evalRoot(values[3], values[2], iso);
        avg[1] = 0.0;
        avg[2] = 1.0;

        samples.push_back(avg);
        weights.push_back((avg-p).lengthSqr());
    }

    if (sEdgeGroupTable[signs][4] == edgeGroup) { // Edged: 0 - 3
        avg[0] = 0.0;
        avg[1] = 0.0;
        avg[2] = evalRoot(values[0], values[3], iso);

        samples.push_back(avg);
        weights.push_back((avg-p).lengthSqr());
    }

    if (sEdgeGroupTable[signs][5] == edgeGroup) { // Edged: 4 - 5
        avg[0] = evalRoot(values[4], values[5], iso);
        avg[1] = 1.0;
        avg[2] = 0.0;

        samples.push_back(avg);
        weights.push_back((avg-p).lengthSqr());
    }

    if (sEdgeGroupTable[signs][6] == edgeGroup) { // Edged: 5 - 6
        avg[0] = 1.0;
        avg[1] = 1.0;
        avg[2] = evalRoot(values[5], values[6], iso);

        samples.push_back(avg);
        weights.push_back((avg-p).lengthSqr());
    }

    if (sEdgeGroupTable[signs][7] == edgeGroup) { // Edged: 7 - 6
        avg[0] = evalRoot(values[7], values[6], iso);
        avg[1] = 1.0;
        avg[2] = 1.0;

        samples.push_back(avg);
        weights.push_back((avg-p).lengthSqr());
    }

    if (sEdgeGroupTable[signs][8] == edgeGroup) { // Edged: 4 - 7
        avg[0] = 0.0;
        avg[1] = 1.0;
        avg[2] = evalRoot(values[4], values[7], iso);

        samples.push_back(avg);
        weights.push_back((avg-p).lengthSqr());
    }

    if (sEdgeGroupTable[signs][9] == edgeGroup) { // Edged: 0 - 4
        avg[0] = 0.0;
        avg[1] = evalRoot(values[0], values[4], iso);
        avg[2] = 0.0;

        samples.push_back(avg);
        weights.push_back((avg-p).lengthSqr());
    }

    if (sEdgeGroupTable[signs][10] == edgeGroup) { // Edged: 1 - 5
        avg[0] = 1.0;
        avg[1] = evalRoot(values[1], values[5], iso);
        avg[2] = 0.0;

        samples.push_back(avg);
        weights.push_back((avg-p).lengthSqr());
    }

    if (sEdgeGroupTable[signs][11] == edgeGroup) { // Edged: 2 - 6
        avg[0] = 1.0;
        avg[1] = evalRoot(values[2], values[6], iso);
        avg[2] = 1.0;

        samples.push_back(avg);
        weights.push_back((avg-p).lengthSqr());
    }

    if (sEdgeGroupTable[signs][12] == edgeGroup) { // Edged: 3 - 7
        avg[0] = 0.0;
        avg[1] = evalRoot(values[3], values[7], iso);
        avg[2] = 1.0;

        samples.push_back(avg);
        weights.push_back((avg-p).lengthSqr());
    }


    double minWeight = std::numeric_limits<double>::max();
    double maxWeight = -std::numeric_limits<double>::max();

    for (size_t i = 0, I = weights.size(); i < I; ++i) {
        minWeight = std::min(minWeight, weights[i]);
        maxWeight = std::max(maxWeight, weights[i]);
    }

    const double offset = maxWeight + minWeight * 0.1;
    for (size_t i = 0, I = weights.size(); i < I; ++i) {
        weights[i] = offset - weights[i];
    }


    double weightSum = 0.0;
    for (size_t i = 0, I = weights.size(); i < I; ++i) {
        weightSum += weights[i];
    }

    avg[0] = 0.0;
    avg[1] = 0.0;
    avg[2] = 0.0;

    if (samples.size() > 1) {
        for (size_t i = 0, I = samples.size(); i < I; ++i) {
            avg += samples[i] * (weights[i] / weightSum);
        }
    } else {
        avg = samples.front();
    }

    return avg;
}


/// @brief  Computes the average cell points defined by the sign configuration
///         @c signs and the given corner values @c values.
inline void
computeCellPoints(std::vector<Vec3d>& points,
    const std::vector<double>& values, unsigned char signs, double iso)
{
    for (size_t n = 1, N = sEdgeGroupTable[signs][0] + 1; n < N; ++n) {
        points.push_back(computePoint(values, signs, n, iso));
    }
}


/// @brief  Given a sign configuration @c lhsSigns and an edge group @c groupId,
///         finds the corresponding edge group in a different sign configuration
///         @c rhsSigns. Returns -1 if no match is found.
inline int
matchEdgeGroup(unsigned char groupId, unsigned char lhsSigns, unsigned char rhsSigns)
{
    int id = -1;
    for (size_t i = 1; i <= 12; ++i) {
        if (sEdgeGroupTable[lhsSigns][i] == groupId && sEdgeGroupTable[rhsSigns][i] != 0) {
            id = sEdgeGroupTable[rhsSigns][i];
            break;
        }
    }
    return id;
}


/// @brief  Computes the average cell points defined by the sign configuration
///         @c signs and the given corner values @c values. Combines data from
///         two different level sets to eliminate seam lines when meshing
///         fractured segments.
inline void
computeCellPoints(std::vector<Vec3d>& points, std::vector<bool>& weightedPointMask,
    const std::vector<double>& lhsValues, const std::vector<double>& rhsValues,
    unsigned char lhsSigns, unsigned char rhsSigns,
    double iso, size_t pointIdx, const boost::scoped_array<uint32_t>& seamPoints)
{
    for (size_t n = 1, N = sEdgeGroupTable[lhsSigns][0] + 1; n < N; ++n) {

        int id = matchEdgeGroup(n, lhsSigns, rhsSigns);

        if (id != -1) {

            const unsigned char e(id);
            uint32_t& quantizedPoint = seamPoints[pointIdx + (id - 1)];

            if ((quantizedPoint & MASK_DIRTY_BIT) && !(quantizedPoint & MASK_INVALID_BIT)) {
                Vec3d p = unpackPoint(quantizedPoint);
                points.push_back(computeWeightedPoint(p, rhsValues, rhsSigns, e, iso));
                weightedPointMask.push_back(true);
            } else {
                points.push_back(computePoint(rhsValues, rhsSigns, e, iso));
                weightedPointMask.push_back(false);
            }

        } else {
            points.push_back(computePoint(lhsValues, lhsSigns, n, iso));
            weightedPointMask.push_back(false);
        }
    }
}


template <typename TreeT, typename LeafManagerT>
class GenPoints
{
public:
    typedef tree::ValueAccessor<const TreeT> AccessorT;

    typedef typename TreeT::template ValueConverter<int>::Type IntTreeT;
    typedef tree::ValueAccessor<IntTreeT> IntAccessorT;
    typedef tree::ValueAccessor<const IntTreeT> IntCAccessorT;

    typedef typename TreeT::template ValueConverter<Int16>::Type Int16TreeT;
    typedef tree::ValueAccessor<const Int16TreeT> Int16CAccessorT;

    typedef boost::scoped_array<uint32_t> QuantizedPointList;

    //////////


    GenPoints(const LeafManagerT& signLeafs, const TreeT& distTree,
        IntTreeT& idxTree, PointList& points, std::vector<size_t>& indices,
        const math::Transform& xform, double iso);

    void run(bool threaded = true);

    void setRefData(const Int16TreeT* refSignTree = NULL, const TreeT* refDistTree = NULL,
        IntTreeT* refIdxTree = NULL, const QuantizedPointList* seamPoints = NULL,
        std::vector<unsigned char>* mSeamPointMaskPt = NULL);

    //////////


    void operator()(const tbb::blocked_range<size_t>&) const;

private:
    const LeafManagerT& mSignLeafs;

    AccessorT mDistAcc;
    IntTreeT& mIdxTree;

    PointList& mPoints;
    std::vector<size_t>& mIndices;
    const math::Transform& mTransform;
    const double mIsovalue;

    // reference data
    const Int16TreeT *mRefSignTreePt;
    const TreeT* mRefDistTreePt;
    const IntTreeT* mRefIdxTreePt;
    const QuantizedPointList* mSeamPointsPt;
    std::vector<unsigned char>* mSeamPointMaskPt;
};


template <typename TreeT, typename LeafManagerT>
GenPoints<TreeT, LeafManagerT>::GenPoints(const LeafManagerT& signLeafs,
    const TreeT& distTree, IntTreeT& idxTree, PointList& points,
    std::vector<size_t>& indices, const math::Transform& xform, double iso)
    : mSignLeafs(signLeafs)
    , mDistAcc(distTree)
    , mIdxTree(idxTree)
    , mPoints(points)
    , mIndices(indices)
    , mTransform(xform)
    , mIsovalue(iso)
    , mRefSignTreePt(NULL)
    , mRefDistTreePt(NULL)
    , mRefIdxTreePt(NULL)
    , mSeamPointsPt(NULL)
    , mSeamPointMaskPt(NULL)
{
}


template <typename TreeT, typename LeafManagerT>
void
GenPoints<TreeT, LeafManagerT>::run(bool threaded)
{
    if (threaded) tbb::parallel_for(mSignLeafs.getRange(), *this);
    else (*this)(mSignLeafs.getRange());
}


template <typename TreeT, typename LeafManagerT>
void
GenPoints<TreeT, LeafManagerT>::setRefData(const Int16TreeT *refSignTree, const TreeT *refDistTree,
    IntTreeT* refIdxTree, const QuantizedPointList* seamPoints, std::vector<unsigned char>* seamPointMask)
{
    mRefSignTreePt = refSignTree;
    mRefDistTreePt = refDistTree;
    mRefIdxTreePt = refIdxTree;
    mSeamPointsPt = seamPoints;
    mSeamPointMaskPt = seamPointMask;
}


template <typename TreeT, typename LeafManagerT>
void
GenPoints<TreeT, LeafManagerT>::operator()(
    const tbb::blocked_range<size_t>& range) const
{
    typename IntTreeT::LeafNodeType::ValueOnIter iter;
    unsigned char signs, refSigns;
    Index offset;
    Coord ijk, coord;
    std::vector<Vec3d> points(4);
    std::vector<bool> weightedPointMask(4);
    std::vector<double> values(8), refValues(8);


    IntAccessorT idxAcc(mIdxTree);

    // reference data accessors
    boost::scoped_ptr<Int16CAccessorT> refSignAcc;
    if (mRefSignTreePt) refSignAcc.reset(new Int16CAccessorT(*mRefSignTreePt));

    boost::scoped_ptr<IntCAccessorT> refIdxAcc;
    if (mRefIdxTreePt) refIdxAcc.reset(new IntCAccessorT(*mRefIdxTreePt));

    boost::scoped_ptr<AccessorT> refDistAcc;
    if (mRefDistTreePt) refDistAcc.reset(new AccessorT(*mRefDistTreePt));


    for (size_t n = range.begin(); n != range.end(); ++n) {

        coord = mSignLeafs.leaf(n).origin();

        const typename TreeT::LeafNodeType *leafPt = mDistAcc.probeConstLeaf(coord);
        typename IntTreeT::LeafNodeType *idxLeafPt = idxAcc.probeLeaf(coord);


        // reference data leafs
        const typename Int16TreeT::LeafNodeType *refSignLeafPt = NULL;
        if (refSignAcc) refSignLeafPt = refSignAcc->probeConstLeaf(coord);

        const typename IntTreeT::LeafNodeType *refIdxLeafPt = NULL;
        if (refIdxAcc) refIdxLeafPt = refIdxAcc->probeConstLeaf(coord);

        const typename TreeT::LeafNodeType *refDistLeafPt = NULL;
        if (refDistAcc) refDistLeafPt = refDistAcc->probeConstLeaf(coord);


        // generate cell points
        size_t ptnIdx = mIndices[n];
        coord.offset(TreeT::LeafNodeType::DIM - 1);



        for (iter = idxLeafPt->beginValueOn(); iter; ++iter) {

            if(iter.getValue() != 0) continue;

            iter.setValue(ptnIdx);
            iter.setValueOff();
            offset = iter.pos();
            ijk = iter.getCoord();

            const bool inclusiveCell = ijk[0] < coord[0] && ijk[1] < coord[1] && ijk[2] < coord[2];

            const Int16& flags = mSignLeafs.leaf(n).getValue(offset);
            signs    = SIGNS & flags;
            refSigns = 0;

            if ((flags & SEAM) && refSignLeafPt && refIdxLeafPt) {
                if (refSignLeafPt->isValueOn(offset)) {
                    refSigns = (SIGNS & refSignLeafPt->getValue(offset));
                }
            }


            if (inclusiveCell) collectCornerValues(*leafPt, offset, values);
            else collectCornerValues(mDistAcc, ijk, values);


            points.clear();
            weightedPointMask.clear();

            if (refSigns == 0) {
                computeCellPoints(points, values, signs, mIsovalue);
            } else {

                if (inclusiveCell) collectCornerValues(*refDistLeafPt, offset, refValues);
                else collectCornerValues(*refDistAcc, ijk, refValues);

                computeCellPoints(points, weightedPointMask, values, refValues, signs, refSigns,
                    mIsovalue, refIdxLeafPt->getValue(offset), *mSeamPointsPt);
            }


            for (size_t i = 0, I = points.size(); i < I; ++i) {

                // offset by cell-origin
                points[i][0] += double(ijk[0]);
                points[i][1] += double(ijk[1]);
                points[i][2] += double(ijk[2]);


                points[i] = mTransform.indexToWorld(points[i]);

                mPoints[ptnIdx][0] = float(points[i][0]);
                mPoints[ptnIdx][1] = float(points[i][1]);
                mPoints[ptnIdx][2] = float(points[i][2]);

                if (mSeamPointMaskPt && !weightedPointMask.empty() && weightedPointMask[i]) {
                    (*mSeamPointMaskPt)[ptnIdx] = 1;
                }

                ++ptnIdx;
            }
        }

        // generate collapsed region points
        int onVoxelCount = int(idxLeafPt->onVoxelCount());
        while (onVoxelCount > 0) {

            iter = idxLeafPt->beginValueOn();
            int regionId = iter.getValue(), count = 0;

            Vec3d avg(0.0), point;

            for (; iter; ++iter) {
                if (iter.getValue() != regionId) continue;

                iter.setValue(ptnIdx);
                iter.setValueOff();
                --onVoxelCount;

                ijk = iter.getCoord();
                offset = iter.pos();

                signs = (SIGNS & mSignLeafs.leaf(n).getValue(offset));

                if (ijk[0] < coord[0] && ijk[1] < coord[1] && ijk[2] < coord[2]) {
                    collectCornerValues(*leafPt, offset, values);
                } else {
                    collectCornerValues(mDistAcc, ijk, values);
                }

                points.clear();
                computeCellPoints(points, values, signs, mIsovalue);

                avg[0] += double(ijk[0]) + points[0][0];
                avg[1] += double(ijk[1]) + points[0][1];
                avg[2] += double(ijk[2]) + points[0][2];

                ++count;
            }


            if (count > 1) {
                double w = 1.0 / double(count);
                avg[0] *= w;
                avg[1] *= w;
                avg[2] *= w;
            }

            avg = mTransform.indexToWorld(avg);

            mPoints[ptnIdx][0] = float(avg[0]);
            mPoints[ptnIdx][1] = float(avg[1]);
            mPoints[ptnIdx][2] = float(avg[2]);

            ++ptnIdx;
        }
    }
}


////////////////////////////////////////


template<typename TreeT>
class SeamWeights
{
public:
    typedef tree::ValueAccessor<const TreeT> AccessorT;

    typedef typename TreeT::template ValueConverter<int>::Type IntTreeT;
    typedef tree::ValueAccessor<const IntTreeT> IntAccessorT;

    typedef typename TreeT::template ValueConverter<Int16>::Type Int16TreeT;
    typedef tree::ValueAccessor<const Int16TreeT> Int16AccessorT;

    typedef boost::scoped_array<uint32_t> QuantizedPointList;

    //////////

    SeamWeights(const TreeT& distTree, const Int16TreeT& refSignTree,
        IntTreeT& refIdxTree, QuantizedPointList& points, double iso);

    template <typename LeafNodeType>
    void operator()(LeafNodeType &signLeaf, size_t leafIndex) const;

private:
    AccessorT mDistAcc;
    Int16AccessorT mRefSignAcc;
    IntAccessorT mRefIdxAcc;

    QuantizedPointList& mPoints;
    const double mIsovalue;
};


template<typename TreeT>
SeamWeights<TreeT>::SeamWeights(const TreeT& distTree, const Int16TreeT& refSignTree,
    IntTreeT& refIdxTree, QuantizedPointList& points, double iso)
    : mDistAcc(distTree)
    , mRefSignAcc(refSignTree)
    , mRefIdxAcc(refIdxTree)
    , mPoints(points)
    , mIsovalue(iso)
{
}


template<typename TreeT>
template <typename LeafNodeType>
void
SeamWeights<TreeT>::operator()(LeafNodeType &signLeaf, size_t /*leafIndex*/) const
{
    Coord coord = signLeaf.origin();
    const typename Int16TreeT::LeafNodeType *refSignLeafPt = mRefSignAcc.probeConstLeaf(coord);

    if (!refSignLeafPt) return;

    const typename TreeT::LeafNodeType *distLeafPt = mDistAcc.probeConstLeaf(coord);
    const typename IntTreeT::LeafNodeType *refIdxLeafPt = mRefIdxAcc.probeConstLeaf(coord);

    std::vector<double> values(8);
    unsigned char lhsSigns, rhsSigns;
    Vec3d point;
    Index offset;

    Coord ijk;
    coord.offset(TreeT::LeafNodeType::DIM - 1);

    typename LeafNodeType::ValueOnCIter iter = signLeaf.cbeginValueOn();
    for (; iter; ++iter) {

        offset = iter.pos();
        ijk = iter.getCoord();

        const bool inclusiveCell = ijk[0] < coord[0] && ijk[1] < coord[1] && ijk[2] < coord[2];

        if ((iter.getValue() & SEAM) && refSignLeafPt->isValueOn(offset)) {

            lhsSigns = SIGNS & iter.getValue();
            rhsSigns = SIGNS & refSignLeafPt->getValue(offset);


            if (inclusiveCell) {
                collectCornerValues(*distLeafPt, offset, values);
            } else {
                collectCornerValues(mDistAcc, ijk, values);
            }


            for (size_t n = 1, N = sEdgeGroupTable[lhsSigns][0] + 1; n < N; ++n) {

                int id = matchEdgeGroup(n, lhsSigns, rhsSigns);

                if (id != -1) {

                    uint32_t& data = mPoints[refIdxLeafPt->getValue(offset) + (id - 1)];

                    if (!(data & MASK_DIRTY_BIT)) {

                        int smaples = computeMaskedPoint(point, values, lhsSigns, rhsSigns, n, mIsovalue);

                        if (smaples > 0) data = packPoint(point);
                        else data = MASK_INVALID_BIT;

                        data |= MASK_DIRTY_BIT;
                    }
                }
            }
        }
    }
}


////////////////////////////////////////


template <typename TreeT, typename LeafManagerT>
class MergeVoxelRegions
{
public:
    typedef typename TreeT::ValueType ValueT;
    typedef tree::ValueAccessor<const TreeT> AccessorT;

    typedef typename TreeT::template ValueConverter<int>::Type IntTreeT;
    typedef tree::ValueAccessor<IntTreeT> IntAccessorT;

    typedef typename TreeT::template ValueConverter<bool>::Type BoolTreeT;

    typedef typename LeafManagerT::TreeType::template ValueConverter<Int16>::Type Int16TreeT;
    typedef tree::ValueAccessor<const Int16TreeT> Int16AccessorT;

    typedef typename TreeT::template ValueConverter<float>::Type FloatTreeT;
    typedef Grid<FloatTreeT> FloatGridT;


    //////////

    MergeVoxelRegions(const LeafManagerT& signLeafs, const Int16TreeT& signTree,
        const TreeT& distTree, IntTreeT& idxTree, ValueT iso, ValueT adaptivity);

    void run(bool threaded = true);

    void setSpatialAdaptivity(
        const math::Transform& distGridXForm, const FloatGridT& adaptivityField);

    void setAdaptivityMask(const BoolTreeT* mask);

    void setRefData(const Int16TreeT* signTree, ValueT adaptivity);

    //////////


    void operator()(const tbb::blocked_range<size_t>&) const;

private:

    const LeafManagerT& mSignLeafs;

    const Int16TreeT& mSignTree;
    Int16AccessorT mSignAcc;

    const TreeT& mDistTree;
    AccessorT mDistAcc;

    IntTreeT& mIdxTree;
    ValueT mIsovalue, mSurfaceAdaptivity, mInternalAdaptivity;

    const math::Transform* mTransform;
    const FloatGridT* mAdaptivityGrid;
    const BoolTreeT* mMask;

    const Int16TreeT* mRefSignTree;
};

template <typename TreeT, typename LeafManagerT>
MergeVoxelRegions<TreeT, LeafManagerT>::MergeVoxelRegions(
    const LeafManagerT& signLeafs, const Int16TreeT& signTree,
    const TreeT& distTree, IntTreeT& idxTree, ValueT iso, ValueT adaptivity)
    : mSignLeafs(signLeafs)
    , mSignTree(signTree)
    , mSignAcc(mSignTree)
    , mDistTree(distTree)
    , mDistAcc(mDistTree)
    , mIdxTree(idxTree)
    , mIsovalue(iso)
    , mSurfaceAdaptivity(adaptivity)
    , mInternalAdaptivity(adaptivity)
    , mTransform(NULL)
    , mAdaptivityGrid(NULL)
    , mMask(NULL)
    , mRefSignTree(NULL)
{
}


template <typename TreeT, typename LeafManagerT>
void
MergeVoxelRegions<TreeT, LeafManagerT>::run(bool threaded)
{
    if (threaded) tbb::parallel_for(mSignLeafs.getRange(), *this);
    else (*this)(mSignLeafs.getRange());
}


template <typename TreeT, typename LeafManagerT>
void
MergeVoxelRegions<TreeT, LeafManagerT>::setSpatialAdaptivity(
    const math::Transform& distGridXForm, const FloatGridT& adaptivityField)
{
    mTransform = &distGridXForm;
    mAdaptivityGrid = &adaptivityField;
}


template <typename TreeT, typename LeafManagerT>
void
MergeVoxelRegions<TreeT, LeafManagerT>::setAdaptivityMask(const BoolTreeT* mask)
{
    mMask = mask;
}

template <typename TreeT, typename LeafManagerT>
void
MergeVoxelRegions<TreeT, LeafManagerT>::setRefData(const Int16TreeT* signTree, ValueT adaptivity)
{
    mRefSignTree = signTree;
    mInternalAdaptivity = adaptivity;
}


template <typename TreeT, typename LeafManagerT>
void
MergeVoxelRegions<TreeT, LeafManagerT>::operator()(const tbb::blocked_range<size_t>& range) const
{
    typedef math::Vec3<ValueT> Vec3T;

    typedef typename TreeT::LeafNodeType LeafT;
    typedef typename IntTreeT::LeafNodeType IntLeafT;
    typedef typename BoolTreeT::LeafNodeType BoolLeafT;
    typedef typename LeafT::template ValueConverter<Vec3T>::Type Vec3LeafT;

    const int LeafDim = LeafT::DIM;

    IntAccessorT idxAcc(mIdxTree);

    typename LeafManagerT::TreeType::LeafNodeType::ValueOnCIter iter;

    typedef typename tree::ValueAccessor<const FloatTreeT> FloatTreeCAccessorT;
    boost::scoped_ptr<FloatTreeCAccessorT> adaptivityAcc;
    if (mAdaptivityGrid) {
        adaptivityAcc.reset(new FloatTreeCAccessorT(mAdaptivityGrid->tree()));
    }

    typedef typename tree::ValueAccessor<const Int16TreeT> Int16TreeCAccessorT;
    boost::scoped_ptr<Int16TreeCAccessorT> refAcc;
    if (mRefSignTree) {
        refAcc.reset(new Int16TreeCAccessorT(*mRefSignTree));
    }

    typedef typename tree::ValueAccessor<const BoolTreeT> BoolTreeCAccessorT;
    boost::scoped_ptr<BoolTreeCAccessorT> maskAcc;
    if (mMask) {
        maskAcc.reset(new BoolTreeCAccessorT(*mMask));
    }

    // Allocate reusable leaf buffers
    BoolLeafT mask;
    Vec3LeafT gradientBuffer;
    Coord ijk, nijk, coord, end;

    for (size_t n = range.begin(); n != range.end(); ++n) {

        const Coord& origin = mSignLeafs.leaf(n).origin();

        ValueT adaptivity = mSurfaceAdaptivity;

        if (refAcc && refAcc->probeConstLeaf(origin) == NULL) {
            adaptivity = mInternalAdaptivity;
        }

        IntLeafT& idxLeaf = *idxAcc.probeLeaf(origin);

        end[0] = origin[0] + LeafDim;
        end[1] = origin[1] + LeafDim;
        end[2] = origin[2] + LeafDim;

        mask.setValuesOff();

        // Mask off seam line adjacent voxels
        if (maskAcc) {
            const BoolLeafT* maskLeaf = maskAcc->probeConstLeaf(origin);
            if (maskLeaf != NULL) {
                typename BoolLeafT::ValueOnCIter it;
                for (it = maskLeaf->cbeginValueOn(); it; ++it) {
                    ijk = it.getCoord();
                    coord[0] = ijk[0] - (ijk[0] % 2);
                    coord[1] = ijk[1] - (ijk[1] % 2);
                    coord[2] = ijk[2] - (ijk[2] % 2);
                    mask.setActiveState(coord, true);
                }
            }
        }


        LeafT adaptivityLeaf(origin, adaptivity);

        if (mAdaptivityGrid) {
            for (Index offset = 0; offset < LeafT::NUM_VALUES; ++offset) {
                ijk = adaptivityLeaf.offsetToGlobalCoord(offset);
                Vec3d xyz = mAdaptivityGrid->transform().worldToIndex(
                    mTransform->indexToWorld(ijk));
                ValueT tmpA = ValueT(adaptivityAcc->getValue(util::nearestCoord(xyz)));
                adaptivityLeaf.setValueOnly(offset, tmpA * adaptivity);
            }
        }

        // Mask off ambiguous voxels
        for (iter = mSignLeafs.leaf(n).cbeginValueOn(); iter; ++iter) {
            ijk = iter.getCoord();
            coord[0] = ijk[0] - (ijk[0] % 2);
            coord[1] = ijk[1] - (ijk[1] % 2);
            coord[2] = ijk[2] - (ijk[2] % 2);
            if(mask.isValueOn(coord)) continue;



            int flags = int(iter.getValue());
            unsigned char signs = SIGNS & flags;
            if ((flags & SEAM) || !sAdaptable[signs] || sEdgeGroupTable[signs][0] > 1) {
                mask.setActiveState(coord, true);
                continue;
            }

            for (int i = 0; i < 26; ++i) {
                nijk = ijk + util::COORD_OFFSETS[i];
                signs = SIGNS & mSignAcc.getValue(nijk);
                if (!sAdaptable[signs] || sEdgeGroupTable[signs][0] > 1) {
                    mask.setActiveState(coord, true);
                    break;
                }
            }
        }

        int dim = 2;
        // Mask off topologically ambiguous 2x2x2 voxel sub-blocks
        for (ijk[0] = origin[0]; ijk[0] < end[0]; ijk[0] += dim) {
            for (ijk[1] = origin[1]; ijk[1] < end[1]; ijk[1] += dim) {
                for (ijk[2] = origin[2]; ijk[2] < end[2]; ijk[2] += dim) {
                    if (isNonManifold(mDistAcc, ijk, mIsovalue, dim)) {
                        mask.setActiveState(ijk, true);
                    }
                }
            }
        }

        // Compute the gradient for the remaining voxels
        gradientBuffer.setValuesOff();
        for (iter = mSignLeafs.leaf(n).cbeginValueOn(); iter; ++iter) {

            ijk = iter.getCoord();
            coord[0] = ijk[0] - (ijk[0] % dim);
            coord[1] = ijk[1] - (ijk[1] % dim);
            coord[2] = ijk[2] - (ijk[2] % dim);
            if(mask.isValueOn(coord)) continue;

            Vec3T norm(math::ISGradient<math::CD_2ND>::result(mDistAcc, ijk));
            // Normalize (Vec3's normalize uses isApproxEqual, which uses abs and does more work)
            ValueT length = norm.length();
            if (length > ValueT(1.0e-7)) {
                norm *= ValueT(1.0) / length;
            }
            gradientBuffer.setValue(ijk, norm);
        }

        int regionId = 1, next_dim = dim << 1;

        // Process the first adaptivity level.
        for (ijk[0] = 0; ijk[0] < LeafDim; ijk[0] += dim) {
            coord[0] = ijk[0] - (ijk[0] % next_dim);
            for (ijk[1] = 0; ijk[1] < LeafDim; ijk[1] += dim) {
                coord[1] = ijk[1] - (ijk[1] % next_dim);
                for (ijk[2] = 0; ijk[2] < LeafDim; ijk[2] += dim) {
                    coord[2] = ijk[2] - (ijk[2] % next_dim);
                    adaptivity = adaptivityLeaf.getValue(ijk);
                    if (mask.isValueOn(ijk) || !isMergable(gradientBuffer, ijk, dim, adaptivity)) {
                        mask.setActiveState(coord, true);
                        continue;
                    }
                    mergeVoxels(idxLeaf, ijk, dim, regionId++);
                }
            }
        }


        // Process remaining adaptivity levels
        for (dim = 4; dim < LeafDim; dim = dim << 1) {
            next_dim = dim << 1;
            coord[0] = ijk[0] - (ijk[0] % next_dim);
            for (ijk[0] = origin[0]; ijk[0] < end[0]; ijk[0] += dim) {
                coord[1] = ijk[1] - (ijk[1] % next_dim);
                for (ijk[1] = origin[1]; ijk[1] < end[1]; ijk[1] += dim) {
                    coord[2] = ijk[2] - (ijk[2] % next_dim);
                    for (ijk[2] = origin[2]; ijk[2] < end[2]; ijk[2] += dim) {
                        adaptivity = adaptivityLeaf.getValue(ijk);
                        if (mask.isValueOn(ijk) || isNonManifold(mDistAcc, ijk, mIsovalue, dim) ||
                            !isMergable(gradientBuffer, ijk, dim, adaptivity))
                        {
                            mask.setActiveState(coord, true);
                            continue;
                        }
                        mergeVoxels(idxLeaf, ijk, dim, regionId++);
                    }
                }
            }
        }

        adaptivity = adaptivityLeaf.getValue(origin);
        if (!(mask.isValueOn(origin) || isNonManifold(mDistAcc, origin, mIsovalue, LeafDim))
            && isMergable(gradientBuffer, origin, LeafDim, adaptivity))
        {
            mergeVoxels(idxLeaf, origin, LeafDim, regionId++);
        }
    }
}


////////////////////////////////////////


// Constructs qudas
struct UniformPrimBuilder
{
    UniformPrimBuilder(): mIdx(0), mPolygonPool(NULL) {}

    void init(const size_t upperBound, PolygonPool& quadPool)
    {
        mPolygonPool = &quadPool;
        mPolygonPool->resetQuads(upperBound);
        mIdx = 0;
    }

    void addPrim(const Vec4I& verts, bool reverse, char flags = 0)
    {
        if (!reverse) {
            mPolygonPool->quad(mIdx) = verts;
        } else {
            Vec4I& quad = mPolygonPool->quad(mIdx);
            quad[0] = verts[3];
            quad[1] = verts[2];
            quad[2] = verts[1];
            quad[3] = verts[0];
        }
        mPolygonPool->quadFlags(mIdx) = flags;
        ++mIdx;
    }

    void done()
    {
        mPolygonPool->trimQuads(mIdx);
    }

private:
    size_t mIdx;
    PolygonPool* mPolygonPool;
};


// Constructs qudas and triangles
struct AdaptivePrimBuilder
{
    AdaptivePrimBuilder() : mQuadIdx(0), mTriangleIdx(0), mPolygonPool(NULL) {}

    void init(const size_t upperBound, PolygonPool& polygonPool)
    {
        mPolygonPool = &polygonPool;
        mPolygonPool->resetQuads(upperBound);
        mPolygonPool->resetTriangles(upperBound);

        mQuadIdx = 0;
        mTriangleIdx = 0;
    }

    void addPrim(const Vec4I& verts, bool reverse, char flags = 0)
    {
        if (verts[0] != verts[1] && verts[0] != verts[2] && verts[0] != verts[3]
            && verts[1] != verts[2] && verts[1] != verts[3] && verts[2] != verts[3]) {
            mPolygonPool->quadFlags(mQuadIdx) = flags;
            addQuad(verts, reverse);
        } else if (
            verts[0] == verts[3] &&
            verts[1] != verts[2] &&
            verts[1] != verts[0] &&
            verts[2] != verts[0]) {
            mPolygonPool->triangleFlags(mTriangleIdx) = flags;
            addTriangle(verts[0], verts[1], verts[2], reverse);
        } else if (
            verts[1] == verts[2] &&
            verts[0] != verts[3] &&
            verts[0] != verts[1] &&
            verts[3] != verts[1]) {
            mPolygonPool->triangleFlags(mTriangleIdx) = flags;
            addTriangle(verts[0], verts[1], verts[3], reverse);
        } else if (
            verts[0] == verts[1] &&
            verts[2] != verts[3] &&
            verts[2] != verts[0] &&
            verts[3] != verts[0]) {
            mPolygonPool->triangleFlags(mTriangleIdx) = flags;
            addTriangle(verts[0], verts[2], verts[3], reverse);
        } else if (
            verts[2] == verts[3] &&
            verts[0] != verts[1] &&
            verts[0] != verts[2] &&
            verts[1] != verts[2]) {
            mPolygonPool->triangleFlags(mTriangleIdx) = flags;
            addTriangle(verts[0], verts[1], verts[2], reverse);
        }
    }


    void done()
    {
        mPolygonPool->trimQuads(mQuadIdx, /*reallocate=*/true);
        mPolygonPool->trimTrinagles(mTriangleIdx, /*reallocate=*/true);
    }

private:

    void addQuad(const Vec4I& verts, bool reverse)
    {
        if (!reverse) {
            mPolygonPool->quad(mQuadIdx) = verts;
        } else {
            Vec4I& quad = mPolygonPool->quad(mQuadIdx);
            quad[0] = verts[3];
            quad[1] = verts[2];
            quad[2] = verts[1];
            quad[3] = verts[0];
        }
        ++mQuadIdx;
    }

    void addTriangle(unsigned v0, unsigned v1, unsigned v2, bool reverse)
    {
        Vec3I& prim = mPolygonPool->triangle(mTriangleIdx);

        prim[1] = v1;

        if (!reverse) {
            prim[0] = v0;
            prim[2] = v2;
        } else {
            prim[0] = v2;
            prim[2] = v0;
        }
        ++mTriangleIdx;
    }

    size_t mQuadIdx, mTriangleIdx;
    PolygonPool *mPolygonPool;
};


template<typename SignAccT, typename IdxAccT, typename PrimBuilder>
inline void
constructPolygons(Int16 flags, Int16 refFlags, const Vec4i& offsets, const Coord& ijk,
    const SignAccT& signAcc, const IdxAccT& idxAcc, PrimBuilder& mesher, Index32 pointListSize)
{
    const Index32 v0 = idxAcc.getValue(ijk);
    if (v0 == util::INVALID_IDX) return;

    char tag[2];
    tag[0] = (flags & SEAM) ? POLYFLAG_FRACTURE_SEAM : 0;
    tag[1] = tag[0] | char(POLYFLAG_EXTERIOR);

    const bool isInside = flags & INSIDE;

    Coord coord;
    openvdb::Vec4I quad;
    unsigned char cell;
    Index32 tmpIdx = 0;

    if (flags & XEDGE) {

        quad[0] = v0 + offsets[0];

        // i, j-1, k
        coord[0] = ijk[0];
        coord[1] = ijk[1] - 1;
        coord[2] = ijk[2];

        quad[1] = idxAcc.getValue(coord);
        cell = SIGNS & signAcc.getValue(coord);
        if (sEdgeGroupTable[cell][0] > 1) {
            tmpIdx = quad[1] + Index32(sEdgeGroupTable[cell][5] - 1);
            if (tmpIdx < pointListSize) quad[1] = tmpIdx;
        }

        // i, j-1, k-1
        coord[2] -= 1;

        quad[2] = idxAcc.getValue(coord);
        cell = SIGNS & signAcc.getValue(coord);
        if (sEdgeGroupTable[cell][0] > 1) {
            tmpIdx = quad[2] + Index32(sEdgeGroupTable[cell][7] - 1);
            if (tmpIdx < pointListSize) quad[2] = tmpIdx;
        }

        // i, j, k-1
        coord[1] = ijk[1];

        quad[3] = idxAcc.getValue(coord);
        cell = SIGNS & signAcc.getValue(coord);
        if (sEdgeGroupTable[cell][0] > 1) {
            tmpIdx = quad[3] + Index32(sEdgeGroupTable[cell][3] - 1);
            if (tmpIdx < pointListSize) quad[3] = tmpIdx;
        }

        if (quad[1] != util::INVALID_IDX &&
            quad[2] != util::INVALID_IDX && quad[3] != util::INVALID_IDX) {
            mesher.addPrim(quad, isInside, tag[bool(refFlags & XEDGE)]);
        }
    }


    if (flags & YEDGE) {

        quad[0] = v0 + offsets[1];

        // i, j, k-1
        coord[0] = ijk[0];
        coord[1] = ijk[1];
        coord[2] = ijk[2] - 1;

        quad[1] = idxAcc.getValue(coord);
        cell = SIGNS & signAcc.getValue(coord);
        if (sEdgeGroupTable[cell][0] > 1) {
            tmpIdx = quad[1] + Index32(sEdgeGroupTable[cell][12] - 1);
            if (tmpIdx < pointListSize) quad[1] = tmpIdx;
        }

        // i-1, j, k-1
        coord[0] -= 1;

        quad[2] = idxAcc.getValue(coord);
        cell = SIGNS & signAcc.getValue(coord);
        if (sEdgeGroupTable[cell][0] > 1) {
            tmpIdx = quad[2] + Index32(sEdgeGroupTable[cell][11] - 1);
            if (tmpIdx < pointListSize) quad[2] = tmpIdx;
        }

        // i-1, j, k
        coord[2] = ijk[2];

        quad[3] = idxAcc.getValue(coord);
        cell = SIGNS & signAcc.getValue(coord);
        if (sEdgeGroupTable[cell][0] > 1) {
            tmpIdx = quad[3] + Index32(sEdgeGroupTable[cell][10] - 1);
            if (tmpIdx < pointListSize) quad[3] = tmpIdx;
        }

        if (quad[1] != util::INVALID_IDX &&
            quad[2] != util::INVALID_IDX && quad[3] != util::INVALID_IDX) {
            mesher.addPrim(quad, isInside, tag[bool(refFlags & YEDGE)]);
        }
    }

    if (flags & ZEDGE) {

        quad[0] = v0 + offsets[2];

        // i, j-1, k
        coord[0] = ijk[0];
        coord[1] = ijk[1] - 1;
        coord[2] = ijk[2];

        quad[1] = idxAcc.getValue(coord);
        cell = SIGNS & signAcc.getValue(coord);
        if (sEdgeGroupTable[cell][0] > 1) {
            tmpIdx = quad[1] + Index32(sEdgeGroupTable[cell][8] - 1);
            if (tmpIdx < pointListSize) quad[1] = tmpIdx;
        }

        // i-1, j-1, k
        coord[0] -= 1;

        quad[2] = idxAcc.getValue(coord);
        cell = SIGNS & signAcc.getValue(coord);
        if (sEdgeGroupTable[cell][0] > 1) {
            tmpIdx = quad[2] + Index32(sEdgeGroupTable[cell][6] - 1);
            if (tmpIdx < pointListSize) quad[2] = tmpIdx;
        }

        // i-1, j, k
        coord[1] = ijk[1];

        quad[3] = idxAcc.getValue(coord);
        cell = SIGNS & signAcc.getValue(coord);
        if (sEdgeGroupTable[cell][0] > 1) {
            tmpIdx = quad[3] + Index32(sEdgeGroupTable[cell][2] - 1);
            if (tmpIdx < pointListSize) quad[3] = tmpIdx;
        }

        if (quad[1] != util::INVALID_IDX &&
            quad[2] != util::INVALID_IDX && quad[3] != util::INVALID_IDX) {
            mesher.addPrim(quad, !isInside, tag[bool(refFlags & ZEDGE)]);
        }
    }
}


////////////////////////////////////////


template<typename LeafManagerT, typename PrimBuilder>
class GenPolygons
{
public:
    typedef typename LeafManagerT::TreeType::template ValueConverter<int>::Type IntTreeT;
    typedef typename LeafManagerT::TreeType::template ValueConverter<Int16>::Type Int16TreeT;

    typedef tree::ValueAccessor<const IntTreeT> IntAccessorT;
    typedef tree::ValueAccessor<const Int16TreeT> Int16AccessorT;

    //////////


    GenPolygons(const LeafManagerT& signLeafs, const Int16TreeT& signTree,
        const IntTreeT& idxTree, PolygonPoolList& polygons, Index32 pointListSize);

    void run(bool threaded = true);


    void setRefSignTree(const Int16TreeT *r) { mRefSignTree = r; }

    //////////


    void operator()(const tbb::blocked_range<size_t>&) const;

private:
    const LeafManagerT& mSignLeafs;
    const Int16TreeT& mSignTree;
    const IntTreeT& mIdxTree;
    const PolygonPoolList& mPolygonPoolList;
    const Index32 mPointListSize;

    const Int16TreeT *mRefSignTree;
 };


template<typename LeafManagerT, typename PrimBuilder>
GenPolygons<LeafManagerT, PrimBuilder>::GenPolygons(const LeafManagerT& signLeafs,
    const Int16TreeT& signTree, const IntTreeT& idxTree, PolygonPoolList& polygons,
    Index32 pointListSize)
    : mSignLeafs(signLeafs)
    , mSignTree(signTree)
    , mIdxTree(idxTree)
    , mPolygonPoolList(polygons)
    , mPointListSize(pointListSize)
    , mRefSignTree(NULL)
{
}

template<typename LeafManagerT, typename PrimBuilder>
void
GenPolygons<LeafManagerT, PrimBuilder>::run(bool threaded)
{
    if (threaded) tbb::parallel_for(mSignLeafs.getRange(), *this);
    else (*this)(mSignLeafs.getRange());
}

template<typename LeafManagerT, typename PrimBuilder>
void
GenPolygons<LeafManagerT, PrimBuilder>::operator()(
    const tbb::blocked_range<size_t>& range) const
{
    typename LeafManagerT::TreeType::LeafNodeType::ValueOnCIter iter;
    IntAccessorT idxAcc(mIdxTree);
    Int16AccessorT signAcc(mSignTree);


    PrimBuilder mesher;
    size_t edgeCount;
    Coord ijk, origin;


    // reference data
    boost::scoped_ptr<Int16AccessorT> refSignAcc;
    if (mRefSignTree) refSignAcc.reset(new Int16AccessorT(*mRefSignTree));


    for (size_t n = range.begin(); n != range.end(); ++n) {

        origin = mSignLeafs.leaf(n).origin();

        // Get an upper bound on the number of primitives.
        edgeCount = 0;
        iter = mSignLeafs.leaf(n).cbeginValueOn();
        for (; iter; ++iter) {
            if (iter.getValue() & XEDGE) ++edgeCount;
            if (iter.getValue() & YEDGE) ++edgeCount;
            if (iter.getValue() & ZEDGE) ++edgeCount;
        }

        if(edgeCount == 0) continue;

        mesher.init(edgeCount, mPolygonPoolList[n]);

        const typename Int16TreeT::LeafNodeType *signleafPt = signAcc.probeConstLeaf(origin);
        const typename IntTreeT::LeafNodeType *idxLeafPt = idxAcc.probeConstLeaf(origin);

        if (!signleafPt || !idxLeafPt) continue;


        const typename Int16TreeT::LeafNodeType *refSignLeafPt = NULL;
        if (refSignAcc) refSignLeafPt = refSignAcc->probeConstLeaf(origin);

        Vec4i offsets;

        iter = mSignLeafs.leaf(n).cbeginValueOn();
        for (; iter; ++iter) {
            ijk = iter.getCoord();

            Int16 flags = iter.getValue();

            if (!(flags & 0xE00)) continue;

            Int16 refFlags = 0;
            if (refSignLeafPt) {
                refFlags = refSignLeafPt->getValue(iter.pos());
            }

            offsets[0] = 0;
            offsets[1] = 0;
            offsets[2] = 0;

            const unsigned char cell = (SIGNS & flags);

            if (sEdgeGroupTable[cell][0] > 1) {
                offsets[0] = (sEdgeGroupTable[cell][1] - 1);
                offsets[1] = (sEdgeGroupTable[cell][9] - 1);
                offsets[2] = (sEdgeGroupTable[cell][4] - 1);
            }

            if (ijk[0] > origin[0] && ijk[1] > origin[1] && ijk[2] > origin[2]) {
                constructPolygons(flags, refFlags, offsets, ijk, *signleafPt, *idxLeafPt, mesher, mPointListSize);
            } else {
                constructPolygons(flags, refFlags, offsets, ijk, signAcc, idxAcc, mesher, mPointListSize);
            }
        }

        mesher.done();
    }
}


////////////////////////////////////////

// Masking and mesh partitioning

struct PartOp
{

    PartOp(size_t leafCount, size_t partitions, size_t activePart)
    {
        size_t leafSegments = leafCount / partitions;
        mStart = leafSegments * activePart;
        mEnd = activePart >= (partitions - 1) ? leafCount : mStart + leafSegments;
    }

    template <typename LeafNodeType>
    void operator()(LeafNodeType &leaf, size_t leafIndex) const
    {
        if (leafIndex < mStart || leafIndex >= mEnd) leaf.setValuesOff();
    }

private:
    size_t mStart, mEnd;
};


////////////////////////////////////////


template<typename SrcTreeT>
class PartGen
{
public:
    typedef tree::LeafManager<const SrcTreeT> LeafManagerT;
    typedef typename SrcTreeT::template ValueConverter<bool>::Type BoolTreeT;
    typedef tree::ValueAccessor<BoolTreeT> BoolAccessorT;

    //////////


    PartGen(const LeafManagerT& leafs, size_t partitions, size_t activePart);

    void run(bool threaded = true);

    BoolTreeT&  tree() { return mTree; }


    //////////

    PartGen(PartGen&, tbb::split);
    void operator()(const tbb::blocked_range<size_t>&);
    void join(PartGen& rhs) { mTree.merge(rhs.mTree); }

private:
    const LeafManagerT& mLeafManager;
    BoolTreeT mTree;
    size_t mStart, mEnd;
};

template<typename SrcTreeT>
PartGen<SrcTreeT>::PartGen(const LeafManagerT& leafs, size_t partitions, size_t activePart)
    : mLeafManager(leafs)
    , mTree(false)
    , mStart(0)
    , mEnd(0)
{
    size_t leafCount = leafs.leafCount();
    size_t leafSegments = leafCount / partitions;
    mStart = leafSegments * activePart;
    mEnd = activePart >= (partitions - 1) ? leafCount : mStart + leafSegments;
}

template<typename SrcTreeT>
PartGen<SrcTreeT>::PartGen(PartGen& rhs, tbb::split)
    : mLeafManager(rhs.mLeafManager)
    , mTree(false)
    , mStart(rhs.mStart)
    , mEnd(rhs.mEnd)
{
}


template<typename SrcTreeT>
void
PartGen<SrcTreeT>::run(bool threaded)
{
    if (threaded) tbb::parallel_reduce(mLeafManager.getRange(), *this);
    else (*this)(mLeafManager.getRange());
}


template<typename SrcTreeT>
void
PartGen<SrcTreeT>::operator()(const tbb::blocked_range<size_t>& range)
{
    Coord ijk;
    BoolAccessorT acc(mTree);

    typedef typename BoolTreeT::LeafNodeType BoolLeafT;
    typename SrcTreeT::LeafNodeType::ValueOnCIter iter;

    for (size_t n = range.begin(); n != range.end(); ++n) {
        if (n < mStart || n >= mEnd) continue;
        BoolLeafT* leaf = acc.touchLeaf(mLeafManager.leaf(n).origin());
        leaf->topologyUnion(mLeafManager.leaf(n));
    }
}


////////////////////////////////////////


template<typename TreeT, typename LeafManagerT>
class GenSeamMask
{
public:
    typedef typename TreeT::template ValueConverter<bool>::Type BoolTreeT;

    //////////

    GenSeamMask(const LeafManagerT& leafs, const TreeT& tree);

    void run(bool threaded = true);

    BoolTreeT& mask() { return mMaskTree; }

    //////////

    GenSeamMask(GenSeamMask&, tbb::split);
    void operator()(const tbb::blocked_range<size_t>&);
    void join(GenSeamMask& rhs) { mMaskTree.merge(rhs.mMaskTree); }

private:

    const LeafManagerT& mLeafManager;
    const TreeT& mTree;

    BoolTreeT mMaskTree;
};


template<typename TreeT, typename LeafManagerT>
GenSeamMask<TreeT, LeafManagerT>::GenSeamMask(const LeafManagerT& leafs, const TreeT& tree)
    : mLeafManager(leafs)
    , mTree(tree)
    , mMaskTree(false)
{
}


template<typename TreeT, typename LeafManagerT>
GenSeamMask<TreeT, LeafManagerT>::GenSeamMask(GenSeamMask& rhs, tbb::split)
    : mLeafManager(rhs.mLeafManager)
    , mTree(rhs.mTree)
    , mMaskTree(false)
{
}


template<typename TreeT, typename LeafManagerT>
void
GenSeamMask<TreeT, LeafManagerT>::run(bool threaded)
{
    if (threaded) tbb::parallel_reduce(mLeafManager.getRange(), *this);
    else (*this)(mLeafManager.getRange());
}


template<typename TreeT, typename LeafManagerT>
void
GenSeamMask<TreeT, LeafManagerT>::operator()(const tbb::blocked_range<size_t>& range)
{
    Coord ijk;
    tree::ValueAccessor<const TreeT> acc(mTree);
    tree::ValueAccessor<BoolTreeT> maskAcc(mMaskTree);

    typename LeafManagerT::TreeType::LeafNodeType::ValueOnCIter it;

    for (size_t n = range.begin(); n != range.end(); ++n) {

        it = mLeafManager.leaf(n).cbeginValueOn();

        for (; it; ++it) {

            ijk = it.getCoord();

            unsigned char rhsSigns = acc.getValue(ijk) & SIGNS;

            if (sEdgeGroupTable[rhsSigns][0] > 0) {
                unsigned char lhsSigns = it.getValue() & SIGNS;
                if (rhsSigns != lhsSigns) {
                    maskAcc.setValueOn(ijk);
                }
            }
        }
    }
}


////////////////////////////////////////


template<typename TreeT>
class TagSeamEdges
{
public:
    typedef tree::ValueAccessor<const TreeT> AccessorT;

    TagSeamEdges(const TreeT& tree) : mAcc(tree) {}

    template <typename LeafNodeType>
    void operator()(LeafNodeType &leaf, size_t/*leafIndex*/) const
    {
        const typename TreeT::LeafNodeType *maskLeaf =
            mAcc.probeConstLeaf(leaf.origin());

        if (!maskLeaf) return;

        typename LeafNodeType::ValueOnIter it = leaf.beginValueOn();

        for (; it; ++it) {

            if (maskLeaf->isValueOn(it.pos())) {
                it.setValue(it.getValue() | SEAM);
            }
        }
    }

private:
    AccessorT mAcc;
};



template<typename BoolTreeT>
struct MaskEdges
{
    typedef tree::ValueAccessor<const BoolTreeT> BoolAccessorT;

    MaskEdges(const BoolTreeT& valueMask) : mMaskAcc(valueMask) {}

    template <typename LeafNodeType>
    void operator()(LeafNodeType &leaf, size_t /*leafIndex*/) const
    {
        typename LeafNodeType::ValueOnIter it = leaf.beginValueOn();

        const typename BoolTreeT::LeafNodeType * maskLeaf =
            mMaskAcc.probeConstLeaf(leaf.origin());

        if (maskLeaf) {
            for (; it; ++it) {
                if (!maskLeaf->isValueOn(it.pos())) {
                    it.setValue(0x1FF & it.getValue());
                }
            }
        } else {
            for (; it; ++it) {
                it.setValue(0x1FF & it.getValue());
            }
        }
    }

private:
    BoolAccessorT mMaskAcc;
};


class FlagUsedPoints
{
public:
    //////////

    FlagUsedPoints(const PolygonPoolList& polygons, size_t polyListCount,
        std::vector<unsigned char>& usedPointMask)
        : mPolygons(polygons)
        , mPolyListCount(polyListCount)
        , mUsedPointMask(usedPointMask)
    {
    }

    void run(bool threaded = true)
    {
        if (threaded) {
            tbb::parallel_for(tbb::blocked_range<size_t>(0, mPolyListCount), *this);
        } else {
            (*this)(tbb::blocked_range<size_t>(0, mPolyListCount));
        }
    }

    //////////

    void operator()(const tbb::blocked_range<size_t>& range) const
    {
        // Concurrent writes to same memory address can occur, but
        // all threads are writing the same value and char is atomic.
        for (size_t n = range.begin(); n != range.end(); ++n) {
            const PolygonPool& polygons = mPolygons[n];
            for (size_t i = 0; i < polygons.numQuads(); ++i) {
                const Vec4I& quad = polygons.quad(i);
                mUsedPointMask[quad[0]] = 1;
                mUsedPointMask[quad[1]] = 1;
                mUsedPointMask[quad[2]] = 1;
                mUsedPointMask[quad[3]] = 1;
            }

            for (size_t i = 0; i < polygons.numTriangles(); ++i) {
                const Vec3I& triangle = polygons.triangle(i);
                mUsedPointMask[triangle[0]] = 1;
                mUsedPointMask[triangle[1]] = 1;
                mUsedPointMask[triangle[2]] = 1;
            }
        }
    }


private:
    const PolygonPoolList& mPolygons;
    size_t mPolyListCount;
    std::vector<unsigned char>& mUsedPointMask;
};

class RemapIndices
{
public:
    //////////

    RemapIndices(PolygonPoolList& polygons,
        size_t polyListCount, const std::vector<unsigned>& indexMap)
        : mPolygons(polygons)
        , mPolyListCount(polyListCount)
        , mIndexMap(indexMap)
    {
    }

    void run(bool threaded = true)
    {
        if (threaded) {
            tbb::parallel_for(tbb::blocked_range<size_t>(0, mPolyListCount), *this);
        } else {
            (*this)(tbb::blocked_range<size_t>(0, mPolyListCount));
        }
    }

    //////////

    void operator()(const tbb::blocked_range<size_t>& range) const
    {
        for (size_t n = range.begin(); n != range.end(); ++n) {
            PolygonPool& polygons = mPolygons[n];
            for (size_t i = 0; i < polygons.numQuads(); ++i) {
                Vec4I& quad = polygons.quad(i);
                quad[0] = mIndexMap[quad[0]];
                quad[1] = mIndexMap[quad[1]];
                quad[2] = mIndexMap[quad[2]];
                quad[3] = mIndexMap[quad[3]];
            }

            for (size_t i = 0; i < polygons.numTriangles(); ++i) {
                Vec3I& triangle = polygons.triangle(i);
                triangle[0] = mIndexMap[triangle[0]];
                triangle[1] = mIndexMap[triangle[1]];
                triangle[2] = mIndexMap[triangle[2]];
            }
        }
    }


private:
    PolygonPoolList& mPolygons;
    size_t mPolyListCount;
    const std::vector<unsigned>& mIndexMap;
};


class MovePoints
{
public:
    //////////

    MovePoints(
        internal::UniquePtr<openvdb::Vec3s>::type& newPointList,
        const PointList& oldPointList,
        const std::vector<unsigned>& indexMap,
        const std::vector<unsigned char>& usedPointMask)
        : mNewPointList(newPointList)
        , mOldPointList(oldPointList)
        , mIndexMap(indexMap)
        , mUsedPointMask(usedPointMask)
    {
    }

    void run(bool threaded = true)
    {
        if (threaded) {
            tbb::parallel_for(tbb::blocked_range<size_t>(0, mIndexMap.size()), *this);
        } else {
            (*this)(tbb::blocked_range<size_t>(0, mIndexMap.size()));
        }
    }

    //////////

    void operator()(const tbb::blocked_range<size_t>& range) const
    {
        for (size_t n = range.begin(); n != range.end(); ++n) {
            if (mUsedPointMask[n]) {
                const size_t index = mIndexMap[n];
                mNewPointList.get()[index] = mOldPointList[n];
            }
        }
    }

private:
    internal::UniquePtr<openvdb::Vec3s>::type& mNewPointList;
    const PointList& mOldPointList;
    const std::vector<unsigned>& mIndexMap;
    const std::vector<unsigned char>& mUsedPointMask;
};


////////////////////////////////////////


template<typename SrcTreeT>
class GenTopologyMask
{
public:
    typedef tree::LeafManager<const SrcTreeT> LeafManagerT;
    typedef typename SrcTreeT::template ValueConverter<bool>::Type BoolTreeT;
    typedef tree::ValueAccessor<const SrcTreeT> SrcAccessorT;
    typedef tree::ValueAccessor<BoolTreeT> BoolAccessorT;
    typedef Grid<BoolTreeT> BoolGridT;


    //////////


    GenTopologyMask(const BoolGridT& mask, const LeafManagerT& srcLeafs,
        const math::Transform& srcXForm, bool invertMask);

    void run(bool threaded = true);

    BoolTreeT& tree() { return mTree; }


    //////////

    GenTopologyMask(GenTopologyMask&, tbb::split);

    void operator()(const tbb::blocked_range<size_t>&);

    void join(GenTopologyMask& rhs) { mTree.merge(rhs.mTree); }

private:

    const BoolGridT& mMask;
    const LeafManagerT& mLeafManager;
    const math::Transform& mSrcXForm;
    bool mInvertMask;
    BoolTreeT mTree;
};


template<typename SrcTreeT>
GenTopologyMask<SrcTreeT>::GenTopologyMask(const BoolGridT& mask, const LeafManagerT& srcLeafs,
    const math::Transform& srcXForm, bool invertMask)
    : mMask(mask)
    , mLeafManager(srcLeafs)
    , mSrcXForm(srcXForm)
    , mInvertMask(invertMask)
    , mTree(false)
{
}


template<typename SrcTreeT>
GenTopologyMask<SrcTreeT>::GenTopologyMask(GenTopologyMask& rhs, tbb::split)
    : mMask(rhs.mMask)
    , mLeafManager(rhs.mLeafManager)
    , mSrcXForm(rhs.mSrcXForm)
    , mInvertMask(rhs.mInvertMask)
    , mTree(false)
{
}


template<typename SrcTreeT>
void
GenTopologyMask<SrcTreeT>::run(bool threaded)
{
    if (threaded) {
        tbb::parallel_reduce(mLeafManager.getRange(), *this);
    } else {
        (*this)(mLeafManager.getRange());
    }
}


template<typename SrcTreeT>
void
GenTopologyMask<SrcTreeT>::operator()(const tbb::blocked_range<size_t>& range)
{
    Coord ijk;
    Vec3d xyz;
    typedef typename BoolTreeT::LeafNodeType BoolLeafT;
    const math::Transform& maskXForm = mMask.transform();
    tree::ValueAccessor<const BoolTreeT> maskAcc(mMask.tree());
    tree::ValueAccessor<BoolTreeT> acc(mTree);

    typename SrcTreeT::LeafNodeType::ValueOnCIter iter;
    for (size_t n = range.begin(); n != range.end(); ++n) {

        ijk = mLeafManager.leaf(n).origin();
        BoolLeafT* leaf = new BoolLeafT(ijk, false);
        bool addLeaf = false;

        if (maskXForm == mSrcXForm) {

            const BoolLeafT* maskLeaf = maskAcc.probeConstLeaf(ijk);

            if (maskLeaf) {

                for (iter = mLeafManager.leaf(n).cbeginValueOn(); iter; ++iter) {
                    Index pos = iter.pos();
                    if(maskLeaf->isValueOn(pos) != mInvertMask) {
                        leaf->setValueOn(pos);
                        addLeaf = true;
                    }
                }

            } else if (maskAcc.isValueOn(ijk) != mInvertMask) {
                leaf->topologyUnion(mLeafManager.leaf(n));
                addLeaf = true;
            }

        } else {
            for (iter = mLeafManager.leaf(n).cbeginValueOn(); iter; ++iter) {
                ijk = iter.getCoord();
                xyz = maskXForm.worldToIndex(mSrcXForm.indexToWorld(ijk));
                if(maskAcc.isValueOn(util::nearestCoord(xyz)) != mInvertMask) {
                    leaf->setValueOn(iter.pos());
                    addLeaf = true;
                }
            }
        }

        if (addLeaf) acc.addLeaf(leaf);
        else delete leaf;
    }
}


////////////////////////////////////////


template<typename SrcTreeT>
class GenBoundaryMask
{
public:
    typedef typename SrcTreeT::template ValueConverter<int>::Type IntTreeT;
    typedef typename SrcTreeT::template ValueConverter<bool>::Type BoolTreeT;
    typedef tree::LeafManager<const SrcTreeT> LeafManagerT;

    //////////

    GenBoundaryMask(const LeafManagerT& leafs, const BoolTreeT&, const IntTreeT&);

    void run(bool threaded = true);

    BoolTreeT&  tree() { return mTree; }

    //////////

    GenBoundaryMask(GenBoundaryMask&, tbb::split);
    void operator()(const tbb::blocked_range<size_t>&);
    void join(GenBoundaryMask& rhs) { mTree.merge(rhs.mTree); }

private:
    // This typedef is needed for Windows
    typedef tree::ValueAccessor<const IntTreeT> IntTreeAccessorT;

    bool neighboringLeaf(const Coord&, const IntTreeAccessorT&) const;

    const LeafManagerT& mLeafManager;
    const BoolTreeT& mMaskTree;
    const IntTreeT& mIdxTree;
    BoolTreeT mTree;
    CoordBBox mLeafBBox;
};


template<typename SrcTreeT>
GenBoundaryMask<SrcTreeT>::GenBoundaryMask(const LeafManagerT& leafs,
    const BoolTreeT& maskTree, const IntTreeT& auxTree)
    : mLeafManager(leafs)
    , mMaskTree(maskTree)
    , mIdxTree(auxTree)
    , mTree(false)
{
    mIdxTree.evalLeafBoundingBox(mLeafBBox);
    mLeafBBox.expand(IntTreeT::LeafNodeType::DIM);
}


template<typename SrcTreeT>
GenBoundaryMask<SrcTreeT>::GenBoundaryMask(GenBoundaryMask& rhs, tbb::split)
    : mLeafManager(rhs.mLeafManager)
    , mMaskTree(rhs.mMaskTree)
    , mIdxTree(rhs.mIdxTree)
    , mTree(false)
    , mLeafBBox(rhs.mLeafBBox)
{
}


template<typename SrcTreeT>
void
GenBoundaryMask<SrcTreeT>::run(bool threaded)
{
    if (threaded) {
        tbb::parallel_reduce(mLeafManager.getRange(), *this);
    } else {
        (*this)(mLeafManager.getRange());
    }
}


template<typename SrcTreeT>
bool
GenBoundaryMask<SrcTreeT>::neighboringLeaf(const Coord& ijk, const IntTreeAccessorT& acc) const
{
    if (acc.probeConstLeaf(ijk)) return true;

    const int dim = IntTreeT::LeafNodeType::DIM;

    // face adjacent neghbours
    if (acc.probeConstLeaf(Coord(ijk[0] + dim, ijk[1], ijk[2]))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0] - dim, ijk[1], ijk[2]))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0], ijk[1] + dim, ijk[2]))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0], ijk[1] - dim, ijk[2]))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0], ijk[1], ijk[2] + dim))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0], ijk[1], ijk[2] - dim))) return true;

    // edge adjacent neighbors
    if (acc.probeConstLeaf(Coord(ijk[0] + dim, ijk[1], ijk[2] - dim))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0] - dim, ijk[1], ijk[2] - dim))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0] + dim, ijk[1], ijk[2] + dim))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0] - dim, ijk[1], ijk[2] + dim))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0] + dim, ijk[1] + dim, ijk[2]))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0] - dim, ijk[1] + dim, ijk[2]))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0] + dim, ijk[1] - dim, ijk[2]))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0] - dim, ijk[1] - dim, ijk[2]))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0], ijk[1] - dim, ijk[2] + dim))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0], ijk[1] - dim, ijk[2] - dim))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0], ijk[1] + dim, ijk[2] + dim))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0], ijk[1] + dim, ijk[2] - dim))) return true;

    // corner adjacent neighbors
    if (acc.probeConstLeaf(Coord(ijk[0] - dim, ijk[1] - dim, ijk[2] - dim))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0] - dim, ijk[1] - dim, ijk[2] + dim))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0] + dim, ijk[1] - dim, ijk[2] + dim))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0] + dim, ijk[1] - dim, ijk[2] - dim))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0] - dim, ijk[1] + dim, ijk[2] - dim))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0] - dim, ijk[1] + dim, ijk[2] + dim))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0] + dim, ijk[1] + dim, ijk[2] + dim))) return true;
    if (acc.probeConstLeaf(Coord(ijk[0] + dim, ijk[1] + dim, ijk[2] - dim))) return true;

    return false;
}


template<typename SrcTreeT>
void
GenBoundaryMask<SrcTreeT>::operator()(const tbb::blocked_range<size_t>& range)
{
    Coord ijk;
    tree::ValueAccessor<const BoolTreeT> maskAcc(mMaskTree);
    tree::ValueAccessor<const IntTreeT> idxAcc(mIdxTree);
    tree::ValueAccessor<BoolTreeT> acc(mTree);

    typename SrcTreeT::LeafNodeType::ValueOnCIter iter;

    for (size_t n = range.begin(); n != range.end(); ++n) {

        const typename SrcTreeT::LeafNodeType&
            leaf = mLeafManager.leaf(n);

        ijk = leaf.origin();

        if (!mLeafBBox.isInside(ijk) || !neighboringLeaf(ijk, idxAcc)) continue;

        const typename BoolTreeT::LeafNodeType*
            maskLeaf = maskAcc.probeConstLeaf(ijk);

        if (!maskLeaf || !leaf.hasSameTopology(maskLeaf)) {
            acc.touchLeaf(ijk)->topologyUnion(leaf);
        }
    }
}


////////////////////////////////////////


template<typename TreeT>
class GenTileMask
{
public:
    typedef typename TreeT::template ValueConverter<bool>::Type BoolTreeT;

    typedef typename TreeT::ValueType ValueT;

    //////////

    GenTileMask(const std::vector<Vec4i>& tiles, const TreeT& distTree, ValueT iso);

    void run(bool threaded = true);

    BoolTreeT& tree() { return mTree; }

    //////////

    GenTileMask(GenTileMask&, tbb::split);
    void operator()(const tbb::blocked_range<size_t>&);
    void join(GenTileMask& rhs) { mTree.merge(rhs.mTree); }

private:

    const std::vector<Vec4i>& mTiles;
    const TreeT& mDistTree;
    ValueT mIsovalue;

    BoolTreeT mTree;
};


template<typename TreeT>
GenTileMask<TreeT>::GenTileMask(
    const std::vector<Vec4i>& tiles, const TreeT& distTree, ValueT iso)
    : mTiles(tiles)
    , mDistTree(distTree)
    , mIsovalue(iso)
    , mTree(false)
{
}


template<typename TreeT>
GenTileMask<TreeT>::GenTileMask(GenTileMask& rhs, tbb::split)
    : mTiles(rhs.mTiles)
    , mDistTree(rhs.mDistTree)
    , mIsovalue(rhs.mIsovalue)
    , mTree(false)
{
}


template<typename TreeT>
void
GenTileMask<TreeT>::run(bool threaded)
{
    if (threaded) tbb::parallel_reduce(tbb::blocked_range<size_t>(0, mTiles.size()), *this);
    else (*this)(tbb::blocked_range<size_t>(0, mTiles.size()));
}


template<typename TreeT>
void
GenTileMask<TreeT>::operator()(const tbb::blocked_range<size_t>& range)
{
    tree::ValueAccessor<const TreeT> distAcc(mDistTree);
    CoordBBox region, bbox;
    Coord ijk, nijk;
    bool processRegion = true;
    ValueT value;


    for (size_t n = range.begin(); n != range.end(); ++n) {

        const Vec4i& tile = mTiles[n];

        bbox.min()[0] = tile[0];
        bbox.min()[1] = tile[1];
        bbox.min()[2] = tile[2];

        bbox.max() = bbox.min();
        bbox.max().offset(tile[3]);

        const bool thisInside = (distAcc.getValue(bbox.min()) < mIsovalue);
        const int thisDepth = distAcc.getValueDepth(bbox.min());

        // eval x-edges

        ijk = bbox.max();
        nijk = ijk;
        ++nijk[0];

        processRegion = true;
        if (thisDepth >= distAcc.getValueDepth(nijk)) {
            processRegion = thisInside != (distAcc.getValue(nijk) < mIsovalue);
        }


        if (processRegion) {
            region = bbox;
            region.min()[0] = region.max()[0] = ijk[0];
            mTree.fill(region, true);
        }


        ijk = bbox.min();
        --ijk[0];

        processRegion = true;
        if (thisDepth >= distAcc.getValueDepth(ijk)) {
            processRegion = !distAcc.probeValue(ijk, value) && thisInside != (value < mIsovalue);
        }

        if (processRegion) {
            region = bbox;
            region.min()[0] = region.max()[0] = ijk[0];
            mTree.fill(region, true);
        }


        // eval y-edges

        ijk = bbox.max();
        nijk = ijk;
        ++nijk[1];

        processRegion = true;
        if (thisDepth >= distAcc.getValueDepth(nijk)) {
            processRegion = thisInside != (distAcc.getValue(nijk) < mIsovalue);
        }

        if (processRegion) {
            region = bbox;
            region.min()[1] = region.max()[1] = ijk[1];
            mTree.fill(region, true);
        }


        ijk = bbox.min();
        --ijk[1];

        processRegion = true;
        if (thisDepth >= distAcc.getValueDepth(ijk)) {
            processRegion = !distAcc.probeValue(ijk, value) && thisInside != (value < mIsovalue);
        }

        if (processRegion) {
            region = bbox;
            region.min()[1] = region.max()[1] = ijk[1];
            mTree.fill(region, true);
        }


        // eval z-edges

        ijk = bbox.max();
        nijk = ijk;
        ++nijk[2];

        processRegion = true;
        if (thisDepth >= distAcc.getValueDepth(nijk)) {
            processRegion = thisInside != (distAcc.getValue(nijk) < mIsovalue);
        }

        if (processRegion) {
            region = bbox;
            region.min()[2] = region.max()[2] = ijk[2];
            mTree.fill(region, true);
        }

        ijk = bbox.min();
        --ijk[2];

        processRegion = true;
        if (thisDepth >= distAcc.getValueDepth(ijk)) {
            processRegion = !distAcc.probeValue(ijk, value) && thisInside != (value < mIsovalue);
        }

        if (processRegion) {
            region = bbox;
            region.min()[2] = region.max()[2] = ijk[2];
            mTree.fill(region, true);
        }


        ijk = bbox.min();
        --ijk[1];
        --ijk[2];

        processRegion = true;
        if (thisDepth >= distAcc.getValueDepth(ijk)) {
            processRegion = !distAcc.probeValue(ijk, value) && thisInside != (value < mIsovalue);
        }

        if (processRegion) {
            region = bbox;
            region.min()[1] = region.max()[1] = ijk[1];
            region.min()[2] = region.max()[2] = ijk[2];
            mTree.fill(region, true);
        }


        ijk = bbox.min();
        --ijk[0];
        --ijk[1];

        processRegion = true;
        if (thisDepth >= distAcc.getValueDepth(ijk)) {
            processRegion = !distAcc.probeValue(ijk, value) && thisInside != (value < mIsovalue);
        }

        if (processRegion) {
            region = bbox;
            region.min()[1] = region.max()[1] = ijk[1];
            region.min()[0] = region.max()[0] = ijk[0];
            mTree.fill(region, true);
        }

        ijk = bbox.min();
        --ijk[0];
        --ijk[2];

        processRegion = true;
        if (thisDepth >= distAcc.getValueDepth(ijk)) {
            processRegion = !distAcc.probeValue(ijk, value) && thisInside != (value < mIsovalue);
        }

        if (processRegion) {
            region = bbox;
            region.min()[2] = region.max()[2] = ijk[2];
            region.min()[0] = region.max()[0] = ijk[0];
            mTree.fill(region, true);
        }
    }
}


////////////////////////////////////////


template<class DistTreeT, class SignTreeT, class IdxTreeT>
inline void
tileData(const DistTreeT& distTree, SignTreeT& signTree, IdxTreeT& idxTree, double iso)
{
    typename DistTreeT::ValueOnCIter tileIter(distTree);
    tileIter.setMaxDepth(DistTreeT::ValueOnCIter::LEAF_DEPTH - 1);

    if (!tileIter) return; // volume has no active tiles.

    size_t tileCount = 0;
    for ( ; tileIter; ++tileIter) {
        ++tileCount;
    }

    std::vector<Vec4i> tiles(tileCount);

    tileCount = 0;
    tileIter = distTree.cbeginValueOn();
    tileIter.setMaxDepth(DistTreeT::ValueOnCIter::LEAF_DEPTH - 1);

    CoordBBox bbox;
    for (; tileIter; ++tileIter) {
        Vec4i& tile = tiles[tileCount++];
        tileIter.getBoundingBox(bbox);
        tile[0] = bbox.min()[0];
        tile[1] = bbox.min()[1];
        tile[2] = bbox.min()[2];
        tile[3] = bbox.max()[0] - bbox.min()[0];
    }

    typename DistTreeT::ValueType isovalue = typename DistTreeT::ValueType(iso);

    GenTileMask<DistTreeT> tileMask(tiles, distTree, isovalue);
    tileMask.run();

    typedef typename DistTreeT::template ValueConverter<bool>::Type BoolTreeT;
    typedef tree::LeafManager<BoolTreeT> BoolLeafManagerT;

    BoolLeafManagerT leafs(tileMask.tree());


    internal::SignData<DistTreeT, BoolLeafManagerT> op(distTree, leafs, isovalue);
    op.run();

    signTree.merge(*op.signTree());
    idxTree.merge(*op.idxTree());
}


////////////////////////////////////////


// Utility class for the volumeToMesh wrapper
class PointListCopy
{
public:
    PointListCopy(const PointList& pointsIn, std::vector<Vec3s>& pointsOut)
        : mPointsIn(pointsIn) , mPointsOut(pointsOut)
    {
    }

    void operator()(const tbb::blocked_range<size_t>& range) const
    {
        for (size_t n = range.begin(); n < range.end(); ++n) {
            mPointsOut[n] = mPointsIn[n];
        }
    }

private:
    const PointList& mPointsIn;
    std::vector<Vec3s>& mPointsOut;
};


// Checks if the isovalue is in proximity to the active voxel boundary.
template <typename LeafManagerT>
inline bool
needsActiveVoxePadding(const LeafManagerT& leafs, double iso, double voxelSize)
{
    double interiorWidth = 0.0, exteriorWidth = 0.0;
    {
        typename LeafManagerT::TreeType::LeafNodeType::ValueOffCIter it;
        bool foundInterior = false, foundExterior = false;
        for (size_t n = 0, N = leafs.leafCount(); n < N; ++n) {

            for (it = leafs.leaf(n).cbeginValueOff(); it; ++it) {
                double value = double(it.getValue());
                if (value < 0.0) {
                    interiorWidth = value;
                    foundInterior = true;
                } else if (value > 0.0) {
                    exteriorWidth = value;
                    foundExterior = true;
                }

                if (foundInterior && foundExterior) break;
            }

            if (foundInterior && foundExterior) break;
        }

    }

    double minDist = std::min(std::abs(interiorWidth - iso), std::abs(exteriorWidth - iso));
    return !(minDist > (2.0 * voxelSize));
}


} // end namespace internal


////////////////////////////////////////


inline
PolygonPool::PolygonPool()
    : mNumQuads(0)
    , mNumTriangles(0)
    , mQuads(NULL)
    , mTriangles(NULL)
    , mQuadFlags(NULL)
    , mTriangleFlags(NULL)
{
}


inline
PolygonPool::PolygonPool(const size_t numQuads, const size_t numTriangles)
    : mNumQuads(numQuads)
    , mNumTriangles(numTriangles)
    , mQuads(new openvdb::Vec4I[mNumQuads])
    , mTriangles(new openvdb::Vec3I[mNumTriangles])
    , mQuadFlags(new char[mNumQuads])
    , mTriangleFlags(new char[mNumTriangles])
{
}


inline void
PolygonPool::copy(const PolygonPool& rhs)
{
    resetQuads(rhs.numQuads());
    resetTriangles(rhs.numTriangles());

    for (size_t i = 0; i < mNumQuads; ++i) {
        mQuads[i] = rhs.mQuads[i];
        mQuadFlags[i] = rhs.mQuadFlags[i];
    }

    for (size_t i = 0; i < mNumTriangles; ++i) {
        mTriangles[i] = rhs.mTriangles[i];
        mTriangleFlags[i] = rhs.mTriangleFlags[i];
    }
}


inline void
PolygonPool::resetQuads(size_t size)
{
    mNumQuads = size;
    mQuads.reset(new openvdb::Vec4I[mNumQuads]);
    mQuadFlags.reset(new char[mNumQuads]);
}


inline void
PolygonPool::clearQuads()
{
    mNumQuads = 0;
    mQuads.reset(NULL);
    mQuadFlags.reset(NULL);
}


inline void
PolygonPool::resetTriangles(size_t size)
{
    mNumTriangles = size;
    mTriangles.reset(new openvdb::Vec3I[mNumTriangles]);
    mTriangleFlags.reset(new char[mNumTriangles]);
}


inline void
PolygonPool::clearTriangles()
{
    mNumTriangles = 0;
    mTriangles.reset(NULL);
    mTriangleFlags.reset(NULL);
}


inline bool
PolygonPool::trimQuads(const size_t n, bool reallocate)
{
    if (!(n < mNumQuads)) return false;

    if (reallocate) {

        if (n == 0) {
            mQuads.reset(NULL);
        } else {

            boost::scoped_array<openvdb::Vec4I> quads(new openvdb::Vec4I[n]);
            boost::scoped_array<char> flags(new char[n]);

            for (size_t i = 0; i < n; ++i) {
                quads[i] = mQuads[i];
                flags[i] = mQuadFlags[i];
            }

            mQuads.swap(quads);
            mQuadFlags.swap(flags);
        }
    }

    mNumQuads = n;
    return true;
}


inline bool
PolygonPool::trimTrinagles(const size_t n, bool reallocate)
{
    if (!(n < mNumTriangles)) return false;

    if (reallocate) {

        if (n == 0) {
            mTriangles.reset(NULL);
        } else {

            boost::scoped_array<openvdb::Vec3I> triangles(new openvdb::Vec3I[n]);
            boost::scoped_array<char> flags(new char[n]);

            for (size_t i = 0; i < n; ++i) {
                triangles[i] = mTriangles[i];
                flags[i] = mTriangleFlags[i];
            }

            mTriangles.swap(triangles);
            mTriangleFlags.swap(flags);
        }
    }

    mNumTriangles = n;
    return true;
}


////////////////////////////////////////


inline VolumeToMesh::VolumeToMesh(double isovalue, double adaptivity)
    : mPoints(NULL)
    , mPolygons()
    , mPointListSize(0)
    , mSeamPointListSize(0)
    , mPolygonPoolListSize(0)
    , mIsovalue(isovalue)
    , mPrimAdaptivity(adaptivity)
    , mSecAdaptivity(0.0)
    , mRefGrid(GridBase::ConstPtr())
    , mSurfaceMaskGrid(GridBase::ConstPtr())
    , mAdaptivityGrid(GridBase::ConstPtr())
    , mAdaptivityMaskTree(TreeBase::ConstPtr())
    , mRefSignTree(TreeBase::Ptr())
    , mRefIdxTree(TreeBase::Ptr())
    , mInvertSurfaceMask(false)
    , mPartitions(1)
    , mActivePart(0)
    , mQuantizedSeamPoints(NULL)
    , mPointFlags(0)
{
}


inline PointList&
VolumeToMesh::pointList()
{
    return mPoints;
}


inline const size_t&
VolumeToMesh::pointListSize() const
{
    return mPointListSize;
}


inline PolygonPoolList&
VolumeToMesh::polygonPoolList()
{
    return mPolygons;
}


inline const PolygonPoolList&
VolumeToMesh::polygonPoolList() const
{
    return mPolygons;
}


inline const size_t&
VolumeToMesh::polygonPoolListSize() const
{
    return mPolygonPoolListSize;
}


inline void
VolumeToMesh::setRefGrid(const GridBase::ConstPtr& grid, double secAdaptivity)
{
    mRefGrid = grid;
    mSecAdaptivity = secAdaptivity;

    // Clear out old auxiliary data
    mRefSignTree = TreeBase::Ptr();
    mRefIdxTree = TreeBase::Ptr();
    mSeamPointListSize = 0;
    mQuantizedSeamPoints.reset(NULL);
}


inline void
VolumeToMesh::setSurfaceMask(const GridBase::ConstPtr& mask, bool invertMask)
{
    mSurfaceMaskGrid = mask;
    mInvertSurfaceMask = invertMask;
}


inline void
VolumeToMesh::setSpatialAdaptivity(const GridBase::ConstPtr& grid)
{
    mAdaptivityGrid = grid;
}


inline void
VolumeToMesh::setAdaptivityMask(const TreeBase::ConstPtr& tree)
{
   mAdaptivityMaskTree = tree;
}


inline void
VolumeToMesh::partition(unsigned partitions, unsigned activePart)
{
    mPartitions = std::max(partitions, unsigned(1));
    mActivePart = std::min(activePart, mPartitions-1);
}


inline std::vector<unsigned char>&
VolumeToMesh::pointFlags()
{
    return mPointFlags;
}


inline const std::vector<unsigned char>&
VolumeToMesh::pointFlags() const
{
    return mPointFlags;
}


template<typename GridT>
inline void
VolumeToMesh::operator()(const GridT& distGrid)
{
    typedef typename GridT::TreeType DistTreeT;
    typedef tree::LeafManager<const DistTreeT> DistLeafManagerT;
    typedef typename DistTreeT::ValueType DistValueT;

    typedef typename DistTreeT::template ValueConverter<bool>::Type BoolTreeT;
    typedef tree::LeafManager<BoolTreeT> BoolLeafManagerT;
    typedef Grid<BoolTreeT> BoolGridT;

    typedef typename DistTreeT::template ValueConverter<Int16>::Type Int16TreeT;
    typedef tree::LeafManager<Int16TreeT> Int16LeafManagerT;

    typedef typename DistTreeT::template ValueConverter<int>::Type IntTreeT;
    typedef typename DistTreeT::template ValueConverter<float>::Type FloatTreeT;
    typedef Grid<FloatTreeT> FloatGridT;


    const openvdb::math::Transform& transform = distGrid.transform();
    const DistTreeT& distTree = distGrid.tree();
    const DistValueT isovalue = DistValueT(mIsovalue);

    typename Int16TreeT::Ptr signTreePt;
    typename IntTreeT::Ptr idxTreePt;
    typename BoolTreeT::Ptr pointMask;

    BoolTreeT valueMask(false), seamMask(false);
    const bool adaptive = mPrimAdaptivity > 1e-7 || mSecAdaptivity > 1e-7;
    bool maskEdges = false;


    const BoolGridT * surfaceMask = NULL;
    if (mSurfaceMaskGrid && mSurfaceMaskGrid->type() == BoolGridT::gridType()) {
        surfaceMask = static_cast<const BoolGridT*>(mSurfaceMaskGrid.get());
    }

    const FloatGridT * adaptivityField = NULL;
    if (mAdaptivityGrid && mAdaptivityGrid->type() == FloatGridT::gridType()) {
        adaptivityField = static_cast<const FloatGridT*>(mAdaptivityGrid.get());
    }

    if (mAdaptivityMaskTree && mAdaptivityMaskTree->type() == BoolTreeT::treeType()) {
        const BoolTreeT *adaptivityMaskPt =
            static_cast<const BoolTreeT*>(mAdaptivityMaskTree.get());
        seamMask.topologyUnion(*adaptivityMaskPt);
    }


    // Collect auxiliary data
    {
        DistLeafManagerT distLeafs(distTree);

        // Check if the isovalue is in proximity to the active voxel boundary.
        bool padActiveVoxels = false;
        int padVoxels = 3;

        if (distGrid.getGridClass() != GRID_LEVEL_SET) {
            padActiveVoxels = true;
        } else {
            padActiveVoxels = internal::needsActiveVoxePadding(distLeafs,
                mIsovalue, transform.voxelSize()[0]);
        }

        // always pad the active region for small volumes (the performance hit is neglectable).
        if (!padActiveVoxels) {
            Coord dim;
            distTree.evalActiveVoxelDim(dim);
            int maxDim = std::max(std::max(dim[0], dim[1]), dim[2]);
            if (maxDim < 1000) {
                padActiveVoxels = true;
                padVoxels = 1;
            }
        }

        if (surfaceMask || mPartitions > 1) {

            maskEdges = true;

            if (surfaceMask) {

                { // Mask
                    internal::GenTopologyMask<DistTreeT> masking(
                        *surfaceMask, distLeafs, transform, mInvertSurfaceMask);
                    masking.run();
                    valueMask.merge(masking.tree());
                }

                if (mPartitions > 1) { // Partition
                    tree::LeafManager<BoolTreeT> leafs(valueMask);
                    leafs.foreach(internal::PartOp(leafs.leafCount() , mPartitions, mActivePart));
                    valueMask.pruneInactive();
                }

            } else { // Partition

                internal::PartGen<DistTreeT> partitioner(distLeafs, mPartitions, mActivePart);
                partitioner.run();
                valueMask.merge(partitioner.tree());
            }

            {
                if (padActiveVoxels) tools::dilateVoxels(valueMask, padVoxels);
                BoolLeafManagerT leafs(valueMask);

                internal::SignData<DistTreeT, BoolLeafManagerT>
                    signDataOp(distTree, leafs, isovalue);
                signDataOp.run();

                signTreePt = signDataOp.signTree();
                idxTreePt = signDataOp.idxTree();
            }

            {
                internal::GenBoundaryMask<DistTreeT> boundary(distLeafs, valueMask, *idxTreePt);
                boundary.run();

                BoolLeafManagerT bleafs(boundary.tree());

                internal::SignData<DistTreeT, BoolLeafManagerT>
                    signDataOp(distTree, bleafs, isovalue);
                signDataOp.run();

                signTreePt->merge(*signDataOp.signTree());
                idxTreePt->merge(*signDataOp.idxTree());
            }

        } else {

            // Collect voxel-sign configurations
            if (padActiveVoxels) {

                BoolTreeT regionMask(false);
                regionMask.topologyUnion(distTree);
                tools::dilateVoxels(regionMask, padVoxels);

                BoolLeafManagerT leafs(regionMask);

                internal::SignData<DistTreeT, BoolLeafManagerT>
                    signDataOp(distTree, leafs, isovalue);
                signDataOp.run();

                signTreePt = signDataOp.signTree();
                idxTreePt = signDataOp.idxTree();
            } else {

                internal::SignData<DistTreeT, DistLeafManagerT>
                    signDataOp(distTree, distLeafs, isovalue);
                signDataOp.run();

                signTreePt = signDataOp.signTree();
                idxTreePt = signDataOp.idxTree();
            }
        }

    }


    // Collect auxiliary data from active tiles
    internal::tileData(distTree, *signTreePt, *idxTreePt, isovalue);

    // Optionally collect auxiliary data from a reference level set.
    Int16TreeT *refSignTreePt = NULL;
    IntTreeT *refIdxTreePt = NULL;
    const DistTreeT *refDistTreePt = NULL;

    if (mRefGrid && mRefGrid->type() == GridT::gridType()) {

        const GridT* refGrid = static_cast<const GridT*>(mRefGrid.get());
        refDistTreePt = &refGrid->tree();

        // Collect and cache auxiliary data from the reference grid.
        if (!mRefSignTree && !mRefIdxTree) {

            DistLeafManagerT refDistLeafs(*refDistTreePt);
            internal::SignData<DistTreeT, DistLeafManagerT>
                signDataOp(*refDistTreePt, refDistLeafs, isovalue);

            signDataOp.run();

            mRefSignTree = signDataOp.signTree();
            mRefIdxTree = signDataOp.idxTree();
        }

        // Get cached auxiliary data
        if (mRefSignTree && mRefIdxTree) {
            refSignTreePt = static_cast<Int16TreeT*>(mRefSignTree.get());
            refIdxTreePt = static_cast<IntTreeT*>(mRefIdxTree.get());
        }
    }


    // Process auxiliary data
    Int16LeafManagerT signLeafs(*signTreePt);

    if (maskEdges) {
        signLeafs.foreach(internal::MaskEdges<BoolTreeT>(valueMask));
        valueMask.clear();
    }


    // Generate the seamline mask
    if (refSignTreePt) {
        internal::GenSeamMask<Int16TreeT, Int16LeafManagerT> seamOp(signLeafs, *refSignTreePt);
        seamOp.run();

        tools::dilateVoxels(seamOp.mask(), 3);
        signLeafs.foreach(internal::TagSeamEdges<BoolTreeT>(seamOp.mask()));

        seamMask.merge(seamOp.mask());
    }


    std::vector<size_t> regions(signLeafs.leafCount(), 0);
    if (regions.empty()) return;

    if (adaptive) {

        internal::MergeVoxelRegions<DistTreeT, Int16LeafManagerT> merge(
            signLeafs, *signTreePt, distTree, *idxTreePt, isovalue, DistValueT(mPrimAdaptivity));

        if (adaptivityField) {
            merge.setSpatialAdaptivity(transform, *adaptivityField);
        }

        if (refSignTreePt || mAdaptivityMaskTree) {
            merge.setAdaptivityMask(&seamMask);
        }

        if (refSignTreePt) {
            merge.setRefData(refSignTreePt, DistValueT(mSecAdaptivity));
        }

        merge.run();

        signLeafs.foreach(internal::CountRegions<IntTreeT>(*idxTreePt, regions));

    } else {
        signLeafs.foreach(internal::CountPoints(regions));
    }


    {
        mPointListSize = 0;
        size_t tmp = 0;
        for (size_t n = 0, N = regions.size(); n < N; ++n) {
            tmp = regions[n];
            regions[n] = mPointListSize;
            mPointListSize += tmp;
        }
    }


    // Generate the unique point list
    mPoints.reset(new openvdb::Vec3s[mPointListSize]);
    mPointFlags.clear();

    // Generate seam line sample points
    if (refSignTreePt && refIdxTreePt) {

        if (mSeamPointListSize == 0) {

            std::vector<size_t> pointMap;

            {
                Int16LeafManagerT refSignLeafs(*refSignTreePt);
                pointMap.resize(refSignLeafs.leafCount(), 0);

                refSignLeafs.foreach(internal::CountPoints(pointMap));

                size_t tmp = 0;
                for (size_t n = 0, N = pointMap.size(); n < N; ++n) {
                    tmp = pointMap[n];
                    pointMap[n] = mSeamPointListSize;
                    mSeamPointListSize += tmp;
                }
            }

            if (!pointMap.empty() && mSeamPointListSize != 0) {

                mQuantizedSeamPoints.reset(new uint32_t[mSeamPointListSize]);
                memset(mQuantizedSeamPoints.get(), 0, sizeof(uint32_t) * mSeamPointListSize);

                typedef tree::LeafManager<IntTreeT> IntLeafManagerT;

                IntLeafManagerT refIdxLeafs(*refIdxTreePt);
                refIdxLeafs.foreach(internal::MapPoints<Int16TreeT>(pointMap, *refSignTreePt));
            }
        }

        if (mSeamPointListSize != 0) {
            signLeafs.foreach(internal::SeamWeights<DistTreeT>(
                distTree, *refSignTreePt, *refIdxTreePt, mQuantizedSeamPoints, mIsovalue));
        }
    }


    internal::GenPoints<DistTreeT, Int16LeafManagerT>
        pointOp(signLeafs, distTree, *idxTreePt, mPoints, regions, transform, mIsovalue);


    if (mSeamPointListSize != 0) {
        mPointFlags.resize(mPointListSize);
        pointOp.setRefData(refSignTreePt, refDistTreePt, refIdxTreePt,
            &mQuantizedSeamPoints, &mPointFlags);
    }

    pointOp.run();


    mPolygonPoolListSize = signLeafs.leafCount();
    mPolygons.reset(new PolygonPool[mPolygonPoolListSize]);


    if (adaptive) {

        internal::GenPolygons<Int16LeafManagerT, internal::AdaptivePrimBuilder>
            mesher(signLeafs, *signTreePt, *idxTreePt, mPolygons, Index32(mPointListSize));

        mesher.setRefSignTree(refSignTreePt);
        mesher.run();

    } else {

        internal::GenPolygons<Int16LeafManagerT, internal::UniformPrimBuilder>
            mesher(signLeafs, *signTreePt, *idxTreePt, mPolygons, Index32(mPointListSize));

        mesher.setRefSignTree(refSignTreePt);
        mesher.run();
    }

    // Clean up unused points, only necessary if masking and/or
    // automatic mesh partitioning is enabled.
    if ((surfaceMask || mPartitions > 1) && mPointListSize > 0) {

        // Flag used points
        std::vector<unsigned char> usedPointMask(mPointListSize, 0);

        internal::FlagUsedPoints flagPoints(mPolygons, mPolygonPoolListSize, usedPointMask);
        flagPoints.run();

        // Create index map
        std::vector<unsigned> indexMap(mPointListSize);
        size_t usedPointCount = 0;
        for (size_t p = 0; p < mPointListSize; ++p) {
            if (usedPointMask[p]) indexMap[p] = usedPointCount++;
        }

        if (usedPointCount < mPointListSize) {

            // move points
            internal::UniquePtr<openvdb::Vec3s>::type
                newPointList(new openvdb::Vec3s[usedPointCount]);

            internal::MovePoints movePoints(newPointList, mPoints, indexMap, usedPointMask);
            movePoints.run();

            mPointListSize = usedPointCount;
            mPoints.reset(newPointList.release());

            // update primitives
            internal::RemapIndices remap(mPolygons, mPolygonPoolListSize, indexMap);
            remap.run();
        }
    }


    // Subdivide nonplanar quads near the seamline edges
    // todo: thread and clean up
    if (refSignTreePt || refIdxTreePt || refDistTreePt) {
        std::vector<Vec3s> newPoints;

        for (size_t n = 0; n <  mPolygonPoolListSize; ++n) {

            PolygonPool& polygons = mPolygons[n];

            std::vector<size_t> nonPlanarQuads;
            nonPlanarQuads.reserve(polygons.numQuads());

            for (size_t i = 0; i < polygons.numQuads(); ++i) {

                char& flags = polygons.quadFlags(i);

                if ((flags & POLYFLAG_FRACTURE_SEAM) && !(flags & POLYFLAG_EXTERIOR)) {

                    openvdb::Vec4I& quad = polygons.quad(i);

                    const bool edgePoly = mPointFlags[quad[0]] || mPointFlags[quad[1]]
                        || mPointFlags[quad[2]] || mPointFlags[quad[3]];

                    if (!edgePoly) continue;

                    const Vec3s& p0 = mPoints[quad[0]];
                    const Vec3s& p1 = mPoints[quad[1]];
                    const Vec3s& p2 = mPoints[quad[2]];
                    const Vec3s& p3 = mPoints[quad[3]];

                    if (!internal::isPlanarQuad(p0, p1, p2, p3, 1e-6f)) {
                        nonPlanarQuads.push_back(i);
                    }
                }
            }


            if (!nonPlanarQuads.empty()) {

                PolygonPool tmpPolygons;

                tmpPolygons.resetQuads(polygons.numQuads() - nonPlanarQuads.size());
                tmpPolygons.resetTriangles(polygons.numTriangles() + 4 * nonPlanarQuads.size());

                size_t triangleIdx = 0;
                for (size_t i = 0; i < nonPlanarQuads.size(); ++i) {

                    size_t& quadIdx = nonPlanarQuads[i];

                    openvdb::Vec4I& quad = polygons.quad(quadIdx);
                    char& quadFlags = polygons.quadFlags(quadIdx);
                    //quadFlags |= POLYFLAG_SUBDIVIDED;

                    Vec3s centroid = (mPoints[quad[0]] + mPoints[quad[1]] +
                        mPoints[quad[2]] + mPoints[quad[3]]) * 0.25;

                    size_t pointIdx = newPoints.size() + mPointListSize;

                    newPoints.push_back(centroid);


                    {
                        Vec3I& triangle = tmpPolygons.triangle(triangleIdx);

                        triangle[0] = quad[0];
                        triangle[1] = pointIdx;
                        triangle[2] = quad[3];

                        tmpPolygons.triangleFlags(triangleIdx) = quadFlags;

                        if (mPointFlags[triangle[0]] || mPointFlags[triangle[2]]) {
                            tmpPolygons.triangleFlags(triangleIdx) |= POLYFLAG_SUBDIVIDED;
                        }
                    }

                    ++triangleIdx;

                    {
                        Vec3I& triangle = tmpPolygons.triangle(triangleIdx);

                        triangle[0] = quad[0];
                        triangle[1] = quad[1];
                        triangle[2] = pointIdx;

                        tmpPolygons.triangleFlags(triangleIdx) = quadFlags;

                        if (mPointFlags[triangle[0]] || mPointFlags[triangle[1]]) {
                            tmpPolygons.triangleFlags(triangleIdx) |= POLYFLAG_SUBDIVIDED;
                        }
                    }

                    ++triangleIdx;

                    {
                        Vec3I& triangle = tmpPolygons.triangle(triangleIdx);

                        triangle[0] = quad[1];
                        triangle[1] = quad[2];
                        triangle[2] = pointIdx;

                        tmpPolygons.triangleFlags(triangleIdx) = quadFlags;

                        if (mPointFlags[triangle[0]] || mPointFlags[triangle[1]]) {
                            tmpPolygons.triangleFlags(triangleIdx) |= POLYFLAG_SUBDIVIDED;
                        }
                    }


                    ++triangleIdx;

                    {
                        Vec3I& triangle = tmpPolygons.triangle(triangleIdx);

                        triangle[0] = quad[2];
                        triangle[1] = quad[3];
                        triangle[2] = pointIdx;

                        tmpPolygons.triangleFlags(triangleIdx) = quadFlags;

                        if (mPointFlags[triangle[0]] || mPointFlags[triangle[1]]) {
                            tmpPolygons.triangleFlags(triangleIdx) |= POLYFLAG_SUBDIVIDED;
                        }
                    }

                    ++triangleIdx;

                    quad[0] = util::INVALID_IDX;
                }


                for (size_t i = 0; i < polygons.numTriangles(); ++i) {
                    tmpPolygons.triangle(triangleIdx) = polygons.triangle(i);
                    tmpPolygons.triangleFlags(triangleIdx) = polygons.triangleFlags(i);
                    ++triangleIdx;
                }


                size_t quadIdx = 0;
                for (size_t i = 0; i < polygons.numQuads(); ++i) {
                    openvdb::Vec4I& quad = polygons.quad(i);

                    if (quad[0] != util::INVALID_IDX) {
                        tmpPolygons.quad(quadIdx) = quad;
                        tmpPolygons.quadFlags(quadIdx) = polygons.quadFlags(i);
                        ++quadIdx;
                    }
                }


                polygons.copy(tmpPolygons);
            }

        }


        if (!newPoints.empty()) {

            size_t newPointCount = newPoints.size() + mPointListSize;

            internal::UniquePtr<openvdb::Vec3s>::type
                newPointList(new openvdb::Vec3s[newPointCount]);

            for (size_t i = 0; i < mPointListSize; ++i) {
                newPointList.get()[i] = mPoints[i];
            }

            for (size_t i = mPointListSize; i < newPointCount; ++i) {
                newPointList.get()[i] = newPoints[i - mPointListSize];
            }

            mPointListSize = newPointCount;
            mPoints.reset(newPointList.release());
            mPointFlags.resize(mPointListSize, 0);
        }
    }
}


////////////////////////////////////////


template<typename GridType>
inline void
volumeToMesh(
    const GridType& grid,
    std::vector<Vec3s>& points,
    std::vector<Vec3I>& triangles,
    std::vector<Vec4I>& quads,
    double isovalue,
    double adaptivity)
{
    VolumeToMesh mesher(isovalue, adaptivity);
    mesher(grid);

    // Preallocate the point list
    points.clear();
    points.resize(mesher.pointListSize());

    { // Copy points
        internal::PointListCopy ptnCpy(mesher.pointList(), points);
        tbb::parallel_for(tbb::blocked_range<size_t>(0, points.size()), ptnCpy);
        mesher.pointList().reset(NULL);
    }

    PolygonPoolList& polygonPoolList = mesher.polygonPoolList();

    { // Preallocate primitive lists
        size_t numQuads = 0, numTriangles = 0;
        for (size_t n = 0, N = mesher.polygonPoolListSize(); n < N; ++n) {
            openvdb::tools::PolygonPool& polygons = polygonPoolList[n];
            numTriangles += polygons.numTriangles();
            numQuads += polygons.numQuads();
        }

        triangles.clear();
        triangles.resize(numTriangles);
        quads.clear();
        quads.resize(numQuads);
    }

    // Copy primitives
    size_t qIdx = 0, tIdx = 0;
    for (size_t n = 0, N = mesher.polygonPoolListSize(); n < N; ++n) {
        openvdb::tools::PolygonPool& polygons = polygonPoolList[n];

        for (size_t i = 0, I = polygons.numQuads(); i < I; ++i) {
            quads[qIdx++] = polygons.quad(i);
        }

        for (size_t i = 0, I = polygons.numTriangles(); i < I; ++i) {
            triangles[tIdx++] = polygons.triangle(i);
        }
    }
}


template<typename GridType>
void
volumeToMesh(
    const GridType& grid,
    std::vector<Vec3s>& points,
    std::vector<Vec4I>& quads,
    double isovalue)
{
    std::vector<Vec3I> triangles(0);
    volumeToMesh(grid,points, triangles, quads, isovalue, 0.0);
}


////////////////////////////////////////


} // namespace tools
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb

#endif // OPENVDB_TOOLS_VOLUME_TO_MESH_HAS_BEEN_INCLUDED

// Copyright (c) 2012-2013 DreamWorks Animation LLC
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )