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
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkVolumeShaderComposer.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#ifndef vtkVolumeShaderComposer_h
#define vtkVolumeShaderComposer_h
#include <vtkCamera.h>
#include <vtkImplicitFunction.h>
#include <vtkOpenGLGPUVolumeRayCastMapper.h>
#include <vtkRectilinearGrid.h>
#include <vtkRenderer.h>
#include <vtkUniformGrid.h>
#include <vtkVolume.h>
#include <vtkVolumeInputHelper.h>
#include <vtkVolumeMapper.h>
#include <vtkVolumeProperty.h>
#include <vtkVolumeTexture.h>
#include <map>
#include <sstream>
#include <string>
namespace
{
bool HasGradientOpacity(vtkOpenGLGPUVolumeRayCastMapper::VolumeInputMap& inputs)
{
for (auto& item : inputs)
{
vtkVolumeProperty* volProp = item.second.Volume->GetProperty();
const bool gradOp = (volProp->HasGradientOpacity() || volProp->HasLabelGradientOpacity()) &&
!volProp->GetDisableGradientOpacity();
if (gradOp)
return true;
}
return false;
}
bool HasLighting(vtkOpenGLGPUVolumeRayCastMapper::VolumeInputMap& inputs)
{
for (auto& item : inputs)
{
vtkVolumeProperty* volProp = item.second.Volume->GetProperty();
const bool lighting = volProp->GetShade() == 1;
if (lighting)
return true;
}
return false;
}
bool UseClippedVoxelIntensity(vtkOpenGLGPUVolumeRayCastMapper::VolumeInputMap& inputs)
{
for (auto& item : inputs)
{
vtkVolumeProperty* volProp = item.second.Volume->GetProperty();
const bool useClippedVoxelIntensity = volProp->GetUseClippedVoxelIntensity() == 1;
if (useClippedVoxelIntensity)
{
return true;
}
}
return false;
}
const std::string ArrayBaseName(const std::string& arrayName)
{
const std::string base = arrayName.substr(0, arrayName.length() - 3);
return base;
}
}
// NOTE:
// In this code, we referred to various spaces described below:
// Object space: Raw coordinates in space defined by volume matrix
// Dataset space: Raw coordinates
// Eye space: Coordinates in eye space (as referred in computer graphics)
namespace vtkvolume
{
VTK_ABI_NAMESPACE_BEGIN
//--------------------------------------------------------------------------
std::string ComputeClipPositionImplementation(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string(
" //Transform vertex (data coordinates) to clip coordinates\n"
" // p_clip = T_ProjViewModel * T_dataToWorld * p_data\n"
" vec4 pos = in_projectionMatrix * in_modelViewMatrix * in_volumeMatrix[0] *\n"
" vec4(in_vertexPos.xyz, 1.0);\n"
" gl_Position = pos;\n");
}
//--------------------------------------------------------------------------
std::string ComputeTextureCoordinates(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string(
" // Transform vertex (data coordinates) to texture coordinates.\n"
" // p_texture = T_dataToTex * p_data\n"
" vec3 uvx = sign(in_cellSpacing[0]) * (in_inverseTextureDatasetMatrix[0] *\n"
" vec4(in_vertexPos, 1.0)).xyz;\n"
"\n"
" // For point dataset, we offset the texture coordinate\n"
" // to account for OpenGL treating voxel at the center of the cell.\n"
" // Transform cell tex-coordinates to point tex-coordinates (cellToPoint\n"
" // is an identity matrix in the case of cell data).\n"
" ip_textureCoords = (in_cellToPoint[0] * vec4(uvx, 1.0)).xyz;\n"
" ip_inverseTextureDataAdjusted = in_cellToPoint[0] * in_inverseTextureDatasetMatrix[0];\n");
}
//--------------------------------------------------------------------------
std::string BaseDeclarationVertex(vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* mapper,
vtkVolume* vtkNotUsed(vol), bool multipleInputs)
{
auto gpuMapper = vtkGPUVolumeRayCastMapper::SafeDownCast(mapper);
const int numInputs = gpuMapper->GetInputCount();
std::ostringstream ss;
ss << "uniform vec3 in_cellSpacing[" << numInputs
<< "];\n"
"uniform mat4 in_modelViewMatrix;\n"
"uniform mat4 in_projectionMatrix;\n";
const int numTransf = multipleInputs ? numInputs + 1 : 1;
ss << "uniform mat4 in_volumeMatrix[" << numTransf
<< "];\n"
"uniform mat4 in_inverseTextureDatasetMatrix["
<< numTransf
<< "];\n"
"uniform mat4 in_cellToPoint["
<< numTransf
<< "];\n"
"\n"
"//This variable could be 'invariant varying' but it is declared\n"
"//as 'varying' to avoid compiler compatibility issues.\n"
"out mat4 ip_inverseTextureDataAdjusted;\n";
return ss.str();
}
//--------------------------------------------------------------------------
std::string BaseDeclarationFragment(vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* mapper,
vtkOpenGLGPUVolumeRayCastMapper::VolumeInputMap& inputs, int totalNumberOfLights,
int numberPositionalLights, bool defaultLighting, int noOfComponents, int independentComponents)
{
const int numInputs = static_cast<int>(inputs.size());
std::ostringstream toShaderStr;
toShaderStr << "uniform sampler3D in_volume[" << numInputs << "];\n";
toShaderStr << "uniform vec4 in_volume_scale[" << numInputs
<< "];\n"
"uniform vec4 in_volume_bias["
<< numInputs << "];\n";
if (vtkRectilinearGrid::SafeDownCast(mapper->GetInput()))
{
toShaderStr << "uniform sampler1D in_coordTexs;\n";
toShaderStr << "uniform vec3 in_coordTexSizes;\n";
toShaderStr << "uniform vec3 in_coordsScale;\n";
toShaderStr << "uniform vec3 in_coordsBias;\n";
}
if (mapper->GetInput()->GetPointGhostArray() || mapper->GetInput()->GetCellGhostArray())
{
toShaderStr << "uniform sampler3D in_blanking;\n";
}
toShaderStr << "uniform int in_noOfComponents;\n"
"\n"
"uniform sampler2D in_depthSampler;\n"
"\n"
"// Camera position\n"
"uniform vec3 in_cameraPos;\n";
vtkOpenGLGPUVolumeRayCastMapper* glMapper = vtkOpenGLGPUVolumeRayCastMapper::SafeDownCast(mapper);
if (glMapper->GetUseJittering())
{
toShaderStr << "uniform sampler2D in_noiseSampler;\n";
}
// For multiple inputs (numInputs > 1), an additional transformation is
// needed for the bounding-box.
const int numTransf = (numInputs > 1) ? numInputs + 1 : 1;
toShaderStr << "uniform mat4 in_volumeMatrix[" << numTransf
<< "];\n"
"uniform mat4 in_inverseVolumeMatrix["
<< numTransf
<< "];\n"
"uniform mat4 in_textureDatasetMatrix["
<< numTransf
<< "];\n"
"uniform mat4 in_inverseTextureDatasetMatrix["
<< numTransf
<< "];\n"
"uniform mat4 in_textureToEye["
<< numTransf
<< "];\n"
"uniform vec3 in_texMin["
<< numTransf
<< "];\n"
"uniform vec3 in_texMax["
<< numTransf
<< "];\n"
"uniform mat4 in_cellToPoint["
<< numTransf << "];\n";
toShaderStr << "// view and model matrices\n"
"uniform mat4 in_projectionMatrix;\n"
"uniform mat4 in_inverseProjectionMatrix;\n"
"uniform mat4 in_modelViewMatrix;\n"
"uniform mat4 in_inverseModelViewMatrix;\n"
"in mat4 ip_inverseTextureDataAdjusted;\n"
"\n"
"// Ray step size\n"
"uniform vec3 in_cellStep["
<< numInputs << "];\n";
if (glMapper->GetVolumetricScatteringBlending() > 0.0)
{
toShaderStr << "mat4 g_eyeToTexture = in_inverseTextureDatasetMatrix[0] *"
" in_inverseVolumeMatrix[0] * in_inverseModelViewMatrix;\n";
}
if (inputs[0].Volume->GetProperty() && inputs[0].Volume->GetProperty()->GetShade() &&
!defaultLighting && totalNumberOfLights > 0)
{
toShaderStr << "mat4 g_texToView = in_modelViewMatrix * in_volumeMatrix[0] *"
"in_textureDatasetMatrix[0];\n";
}
toShaderStr << "uniform vec2 in_scalarsRange[" << numInputs * 4
<< "];\n"
"uniform vec3 in_cellSpacing["
<< numInputs
<< "];\n"
"\n"
"// Sample distance\n"
"uniform float in_sampleDistance;\n"
"\n"
"// Scales\n"
"uniform vec2 in_windowLowerLeftCorner;\n"
"uniform vec2 in_inverseOriginalWindowSize;\n"
"uniform vec2 in_inverseWindowSize;\n"
"uniform vec3 in_textureExtentsMax;\n"
"uniform vec3 in_textureExtentsMin;\n"
"\n"
"// Material and lighting\n"
"uniform vec3 in_diffuse[4];\n"
"uniform vec3 in_ambient[4];\n"
"uniform vec3 in_specular[4];\n"
"uniform float in_shininess[4];\n"
"\n"
"// Others\n"
"vec3 g_rayJitter = vec3(0.0);\n"
"\n"
"uniform vec2 in_averageIPRange;\n";
toShaderStr << "vec4 g_eyePosObjs[" << numInputs << "];\n";
const bool hasGradientOpacity = HasGradientOpacity(inputs);
if (totalNumberOfLights > 0 || hasGradientOpacity)
{
toShaderStr << "uniform bool in_twoSidedLighting;\n";
}
if (glMapper->GetVolumetricScatteringBlending() > 0.0)
{
toShaderStr << R"***(
uniform float in_giReach;
uniform float in_anisotropy;
uniform float in_volumetricScatteringBlending;
)***";
}
if (totalNumberOfLights > 0)
{
std::string totalLights = std::to_string(totalNumberOfLights);
std::string positionalLights = std::to_string(numberPositionalLights);
if (!defaultLighting)
{
toShaderStr << "#define TOTAL_NUMBER_LIGHTS " << totalLights
<< "\n"
"#define NUMBER_POS_LIGHTS "
<< positionalLights
<< "\n"
"vec4 g_fragWorldPos;\n"
"uniform vec3 in_lightAmbientColor[TOTAL_NUMBER_LIGHTS];\n"
"uniform vec3 in_lightDiffuseColor[TOTAL_NUMBER_LIGHTS];\n"
"uniform vec3 in_lightSpecularColor[TOTAL_NUMBER_LIGHTS];\n"
"uniform vec3 in_lightDirection[TOTAL_NUMBER_LIGHTS];\n";
if (numberPositionalLights > 0)
{
toShaderStr << "uniform vec3 in_lightPosition[NUMBER_POS_LIGHTS];\n"
"uniform vec3 in_lightAttenuation[NUMBER_POS_LIGHTS];\n"
"uniform float in_lightConeAngle[NUMBER_POS_LIGHTS];\n"
"uniform float in_lightExponent[NUMBER_POS_LIGHTS];\n";
}
if (glMapper->GetVolumetricScatteringBlending() > 0.0)
{
toShaderStr << "vec3 g_lightDirectionTex[TOTAL_NUMBER_LIGHTS];\n";
if (numberPositionalLights > 0)
{
toShaderStr << "vec3 g_lightPositionTex[NUMBER_POS_LIGHTS];\n";
}
}
}
else
{
toShaderStr << "uniform vec3 in_lightAmbientColor[1];\n"
"uniform vec3 in_lightDiffuseColor[1];\n"
"uniform vec3 in_lightSpecularColor[1];\n"
"vec4 g_lightPosObj["
<< numInputs
<< "];\n"
"vec3 g_ldir["
<< numInputs
<< "];\n"
"vec3 g_vdir["
<< numInputs
<< "];\n"
"vec3 g_h["
<< numInputs << "];\n";
}
}
if (noOfComponents > 1 && independentComponents)
{
toShaderStr << "uniform vec4 in_componentWeight;\n";
}
if (glMapper->GetCurrentPass() != vtkOpenGLGPUVolumeRayCastMapper::DepthPass &&
glMapper->GetUseDepthPass())
{
toShaderStr << "uniform sampler2D in_depthPassSampler;\n";
}
if (glMapper->GetBlendMode() == vtkVolumeMapper::ISOSURFACE_BLEND)
{
toShaderStr << "#if NUMBER_OF_CONTOURS\n"
"uniform float in_isosurfacesValues[NUMBER_OF_CONTOURS];\n"
"\n"
"int findIsoSurfaceIndex(float scalar, float array[NUMBER_OF_CONTOURS+2])\n"
"{\n"
" int index = NUMBER_OF_CONTOURS >> 1;\n"
" while (scalar > array[index]) ++index;\n"
" while (scalar < array[index]) --index;\n"
" return index;\n"
"}\n"
"#endif\n";
}
else if (glMapper->GetBlendMode() == vtkVolumeMapper::SLICE_BLEND)
{
vtkVolume* vol = inputs.begin()->second.Volume;
vtkImplicitFunction* func = vol->GetProperty()->GetSliceFunction();
if (func && func->IsA("vtkPlane"))
{
toShaderStr
<< "uniform vec3 in_slicePlaneOrigin;\n"
"uniform vec3 in_slicePlaneNormal;\n"
"vec3 g_intersection;\n"
"\n"
"float intersectRayPlane(vec3 rayOrigin, vec3 rayDir)\n"
"{\n"
" vec4 planeNormal = in_inverseVolumeMatrix[0] * vec4(in_slicePlaneNormal, 0.0);\n"
" float denom = dot(planeNormal.xyz, rayDir);\n"
" if (abs(denom) > 1e-6)\n"
" {\n"
" vec4 planeOrigin = in_inverseVolumeMatrix[0] * vec4(in_slicePlaneOrigin, 1.0);\n"
" return dot(planeOrigin.xyz - rayOrigin, planeNormal.xyz) / denom;\n"
" }\n"
" return -1.0;\n"
"}\n";
}
}
return toShaderStr.str();
}
//--------------------------------------------------------------------------
std::string BaseInit(vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* mapper,
vtkOpenGLGPUVolumeRayCastMapper::VolumeInputMap& inputs, bool defaultLighting)
{
vtkOpenGLGPUVolumeRayCastMapper* glMapper = vtkOpenGLGPUVolumeRayCastMapper::SafeDownCast(mapper);
vtkVolume* vol = inputs.begin()->second.Volume;
const int numInputs = static_cast<int>(inputs.size());
std::ostringstream shaderStr;
if (glMapper->GetCurrentPass() != vtkOpenGLGPUVolumeRayCastMapper::DepthPass &&
glMapper->GetUseDepthPass() && glMapper->GetBlendMode() == vtkVolumeMapper::COMPOSITE_BLEND)
{
shaderStr << "\
\n //\
\n vec2 fragTexCoord2 = (gl_FragCoord.xy - in_windowLowerLeftCorner) *\
\n in_inverseWindowSize;\
\n vec4 depthValue = texture2D(in_depthPassSampler, fragTexCoord2);\
\n vec4 rayOrigin = WindowToNDC(gl_FragCoord.x, gl_FragCoord.y, depthValue.x);\
\n\
\n // From normalized device coordinates to eye coordinates.\
\n // in_projectionMatrix is inversed because of way VT\
\n // From eye coordinates to texture coordinates\
\n rayOrigin = in_inverseTextureDatasetMatrix[0] *\
\n in_inverseVolumeMatrix[0] *\
\n in_inverseModelViewMatrix *\
\n in_inverseProjectionMatrix *\
\n rayOrigin;\
\n rayOrigin /= rayOrigin.w;\
\n g_rayOrigin = rayOrigin.xyz;";
}
else
{
shaderStr << "\
\n // Get the 3D texture coordinates for lookup into the in_volume dataset\
\n g_rayOrigin = ip_textureCoords.xyz;";
}
shaderStr << "\
\n\
\n // Eye position in dataset space\
\n g_eyePosObj = in_inverseVolumeMatrix[0] * vec4(in_cameraPos, 1.0);";
for (int i = 0; i < numInputs; ++i)
{
// In multi-volume case the first volume matrix is of the bounding box
shaderStr << "\
\n g_eyePosObjs["
<< i << "] = in_inverseVolumeMatrix[" << (numInputs > 1 ? i + 1 : i)
<< "] * vec4(in_cameraPos, 1.0);";
}
shaderStr << "\n\
\n // Getting the ray marching direction (in dataset space)\
\n vec3 rayDir = computeRayDirection();\
\n\
\n // 2D Texture fragment coordinates [0,1] from fragment coordinates.\
\n // The frame buffer texture has the size of the plain buffer but \
\n // we use a fraction of it. The texture coordinate is less than 1 if\
\n // the reduction factor is less than 1.\
\n // Device coordinates are between -1 and 1. We need texture\
\n // coordinates between 0 and 1. The in_depthSampler\
\n // buffer has the original size buffer.\
\n vec2 fragTexCoord = (gl_FragCoord.xy - in_windowLowerLeftCorner) *\
\n in_inverseWindowSize;\
\n\
\n // Multiply the raymarching direction with the step size to get the\
\n // sub-step size we need to take at each raymarching step\
\n g_dirStep = (ip_inverseTextureDataAdjusted *\
\n vec4(rayDir, 0.0)).xyz * in_sampleDistance;\
\n g_lengthStep = length(g_dirStep);\
\n";
shaderStr << "\
\n float jitterValue = 0.0;\
\n";
if (glMapper->GetBlendMode() != vtkVolumeMapper::SLICE_BLEND)
{
// Intersection is computed with g_rayOrigin, so we should not modify it with Slice mode
if (glMapper->GetUseJittering())
{
shaderStr << "\
\n jitterValue = texture2D(in_noiseSampler, gl_FragCoord.xy /\
vec2(textureSize(in_noiseSampler, 0))).x;\
\n g_rayJitter = g_dirStep * jitterValue;\
\n";
}
else
{
shaderStr << "\
\n g_rayJitter = g_dirStep;\
\n";
}
shaderStr << "\
\n g_rayOrigin += g_rayJitter;\
\n";
}
shaderStr << "\
\n // Flag to determine if voxel should be considered for the rendering\
\n g_skip = false;";
if (vol->GetProperty()->GetShade() && defaultLighting)
{
shaderStr << "\
\n // Light position in dataset space";
for (int i = 0; i < numInputs; ++i)
{
// In multi-volume case the first volume matrix is of the bounding box
shaderStr << "\
\n g_lightPosObj["
<< i << "] = (in_inverseVolumeMatrix[" << (numInputs > 1 ? i + 1 : i) << "] *\
\n vec4(in_cameraPos, 1.0));\
\n g_ldir["
<< i << "] = normalize(g_lightPosObj[" << i << "].xyz - ip_vertexPos);\
\n g_vdir["
<< i << "] = normalize(g_eyePosObjs[" << i << "].xyz - ip_vertexPos);\
\n g_h["
<< i << "] = normalize(g_ldir[" << i << "] + g_vdir[" << i << "]);";
}
}
return shaderStr.str();
}
//--------------------------------------------------------------------------
std::string BaseImplementation(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* mapper, vtkVolume* vtkNotUsed(vol))
{
vtkOpenGLGPUVolumeRayCastMapper* glMapper = vtkOpenGLGPUVolumeRayCastMapper::SafeDownCast(mapper);
std::string str("\
\n g_skip = false;");
// Blanking support
vtkSmartPointer<vtkDataSet> dataSet = vtkDataSet::SafeDownCast(mapper->GetInput());
bool blankCells = (dataSet->GetCellGhostArray() != nullptr);
bool blankPoints = (dataSet->GetPointGhostArray() != nullptr);
if (blankPoints || blankCells)
{
str += std::string("\
\n // Check whether the neighboring points/cells are blank.\
\n // Note the half cellStep because texels are point centered.\
\n vec3 xvec = vec3(in_cellStep[0].x/2.0, 0.0, 0.0);\
\n vec3 yvec = vec3(0.0, in_cellStep[0].y/2.0, 0.0);\
\n vec3 zvec = vec3(0.0, 0.0, in_cellStep[0].z/2.0);\
\n vec3 texPosPVec[3];\
\n texPosPVec[0] = g_dataPos + xvec;\
\n texPosPVec[1] = g_dataPos + yvec;\
\n texPosPVec[2] = g_dataPos + zvec;\
\n vec3 texPosNVec[3];\
\n texPosNVec[0] = g_dataPos - xvec;\
\n texPosNVec[1] = g_dataPos - yvec;\
\n texPosNVec[2] = g_dataPos - zvec;\
\n vec4 blankValue = texture3D(in_blanking, g_dataPos);\
\n vec4 blankValueXP = texture3D(in_blanking, texPosPVec[0]);\
\n vec4 blankValueYP = texture3D(in_blanking, texPosPVec[1]);\
\n vec4 blankValueZP = texture3D(in_blanking, texPosPVec[2]);\
\n vec4 blankValueXN = texture3D(in_blanking, texPosNVec[0]);\
\n vec4 blankValueYN = texture3D(in_blanking, texPosNVec[1]);\
\n vec4 blankValueZN = texture3D(in_blanking, texPosNVec[2]);\
\n vec3 blankValuePx;\
\n blankValuePx[0] = blankValueXP.x;\
\n blankValuePx[1] = blankValueYP.x;\
\n blankValuePx[2] = blankValueZP.x;\
\n vec3 blankValuePy;\
\n blankValuePy[0] = blankValueXP.y;\
\n blankValuePy[1] = blankValueYP.y;\
\n blankValuePy[2] = blankValueZP.y;\
\n vec3 blankValueNx;\
\n blankValueNx[0] = blankValueXN.x;\
\n blankValueNx[1] = blankValueYN.x;\
\n blankValueNx[2] = blankValueZN.x;\
\n vec3 blankValueNy;\
\n blankValueNy[0] = blankValueXN.y;\
\n blankValueNy[1] = blankValueYN.y;\
\n blankValueNy[2] = blankValueZN.y;\
\n");
if (blankPoints)
{
str += std::string("\
\n // If the current or neighboring points\
\n // (that belong to cells that share this texel) are blanked,\
\n // skip the texel. In other words, if point 1 were blank,\
\n // texels 0, 1 and 2 would have to be skipped.\
\n if (blankValue.x > 0.0 ||\
\n any(greaterThan(blankValueNx, vec3(0.0))) ||\
\n any(greaterThan(blankValuePx, vec3(0.0))))\
\n {\
\n // skip this texel\
\n g_skip = true;\
\n }\
\n");
if (blankCells)
{
str += std::string("\
\n // If the current or previous cells (that share this texel)\
\n // are blanked, skip the texel. In other words, if cell 1\
\n // is blanked, texels 1 and 2 would have to be skipped.\
\n else if (blankValue.y > 0.0 ||\
\n any(greaterThan(blankValuePy, vec3(0.0))) ||\
\n any(greaterThan(blankValueNy, vec3(0.0))))\
\n {\
\n // skip this texel\
\n g_skip = true;\
\n }\
\n");
}
}
else if (blankCells)
{
str += std::string("\
\n // If the current or previous cells (that share this texel)\
\n // are blanked, skip the texel. In other words, if cell 1\
\n // is blanked, texels 1 and 2 would have to be skipped.\
\n if (blankValue.x > 0.0 ||\
\n any(greaterThan(blankValueNx, vec3(0.0))) ||\
\n any(greaterThan(blankValuePx, vec3(0.0))))\
\n {\
\n // skip this texel\
\n g_skip = true;\
\n }\
\n");
}
}
if (glMapper->GetBlendMode() == vtkVolumeMapper::SLICE_BLEND)
{
str += std::string("\
\n g_dataPos = g_intersection;\
\n");
}
return str;
}
//--------------------------------------------------------------------------
std::string BaseExit(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string();
}
//--------------------------------------------------------------------------
std::string ComputeGradientOpacity1DDecl(vtkVolume* vol, int noOfComponents,
int independentComponents, std::map<int, std::string> gradientTableMap)
{
auto volProperty = vol->GetProperty();
std::ostringstream ss;
if (volProperty->HasGradientOpacity())
{
ss << "uniform sampler2D " << ArrayBaseName(gradientTableMap[0]) << "[" << noOfComponents
<< "];\n";
}
bool useLabelGradientOpacity =
(volProperty->HasLabelGradientOpacity() && (noOfComponents == 1 || !independentComponents));
if (useLabelGradientOpacity)
{
ss << "uniform sampler2D in_labelMapGradientOpacity;\n";
}
std::string shaderStr = ss.str();
if (volProperty->HasGradientOpacity() && noOfComponents > 0)
{
if (noOfComponents == 1 || !independentComponents)
{
shaderStr += std::string("\
\nfloat computeGradientOpacity(vec4 grad)\
\n {\
\n return texture2D(" +
gradientTableMap[0] + ", vec2(grad.w, 0.0)).r;\
\n }");
}
else
{
shaderStr += std::string("\
\nfloat computeGradientOpacity(vec4 grad, int component)\
\n {");
for (int i = 0; i < noOfComponents; ++i)
{
std::ostringstream toString;
toString << i;
shaderStr += std::string("\
\n if (component == " +
toString.str() + ")");
shaderStr += std::string("\
\n {\
\n return texture2D(" +
gradientTableMap[i] + ", vec2(grad.w, 0.0)).r;\
\n }");
}
shaderStr += std::string("\
\n }");
}
}
if (useLabelGradientOpacity)
{
shaderStr += std::string("\
\nfloat computeGradientOpacityForLabel(vec4 grad, float label)\
\n {\
\n return texture2D(in_labelMapGradientOpacity, vec2(grad.w, label)).r;\
\n }");
}
return shaderStr;
}
//--------------------------------------------------------------------------
std::string ComputeGradientDeclaration(
vtkOpenGLGPUVolumeRayCastMapper* mapper, vtkOpenGLGPUVolumeRayCastMapper::VolumeInputMap& inputs)
{
const bool hasLighting = HasLighting(inputs);
const bool hasGradientOp = HasGradientOpacity(inputs);
std::string shaderStr;
if (hasLighting || hasGradientOp)
{
shaderStr += std::string(
"// c is short for component\n"
"vec4 computeGradient(in vec3 texPos, in int c, in sampler3D volume,in int index)\n"
"{\n"
" // Approximate Nabla(F) derivatives with central differences.\n"
" vec3 g1; // F_front\n"
" vec3 g2; // F_back\n"
" vec3 xvec = vec3(in_cellStep[index].x, 0.0, 0.0);\n"
" vec3 yvec = vec3(0.0, in_cellStep[index].y, 0.0);\n"
" vec3 zvec = vec3(0.0, 0.0, in_cellStep[index].z);\n"
" vec3 texPosPvec[3];\n"
" texPosPvec[0] = texPos + xvec;\n"
" texPosPvec[1] = texPos + yvec;\n"
" texPosPvec[2] = texPos + zvec;\n"
" vec3 texPosNvec[3];\n"
" texPosNvec[0] = texPos - xvec;\n"
" texPosNvec[1] = texPos - yvec;\n"
" texPosNvec[2] = texPos - zvec;\n"
" g1.x = texture3D(volume, vec3(texPosPvec[0]))[c];\n"
" g1.y = texture3D(volume, vec3(texPosPvec[1]))[c];\n"
" g1.z = texture3D(volume, vec3(texPosPvec[2]))[c];\n"
" g2.x = texture3D(volume, vec3(texPosNvec[0]))[c];\n"
" g2.y = texture3D(volume, vec3(texPosNvec[1]))[c];\n"
" g2.z = texture3D(volume, vec3(texPosNvec[2]))[c];\n"
"\n");
if (UseClippedVoxelIntensity(inputs) && mapper->GetClippingPlanes())
{
shaderStr +=
std::string(" vec4 g1ObjDataPos[3], g2ObjDataPos[3];\n"
" for (int i = 0; i < 3; ++i)\n"
" {\n"
" g1ObjDataPos[i] = clip_texToObjMat * vec4(texPosPvec[i], 1.0);\n"
" if (g1ObjDataPos[i].w != 0.0)\n"
" {\n"
" g1ObjDataPos[i] /= g1ObjDataPos[i].w;\n"
" }\n"
" g2ObjDataPos[i] = clip_texToObjMat * vec4(texPosNvec[i], 1.0);\n"
" if (g2ObjDataPos[i].w != 0.0)\n"
" {\n"
" g2ObjDataPos[i] /= g2ObjDataPos[i].w;\n"
" }\n"
" }\n"
"\n"
" for (int i = 0; i < clip_numPlanes && !g_skip; i = i + 6)\n"
" {\n"
" vec3 planeOrigin = vec3(in_clippingPlanes[i + 1],\n"
" in_clippingPlanes[i + 2],\n"
" in_clippingPlanes[i + 3]);\n"
" vec3 planeNormal = normalize(vec3(in_clippingPlanes[i + 4],\n"
" in_clippingPlanes[i + 5],\n"
" in_clippingPlanes[i + 6]));\n"
" for (int j = 0; j < 3; ++j)\n"
" {\n"
" if (dot(vec3(planeOrigin - g1ObjDataPos[j].xyz), planeNormal) > 0)\n"
" {\n"
" g1[j] = in_clippedVoxelIntensity;\n"
" }\n"
" if (dot(vec3(planeOrigin - g2ObjDataPos[j].xyz), planeNormal) > 0)\n"
" {\n"
" g2[j] = in_clippedVoxelIntensity;\n"
" }\n"
" }\n"
" }\n"
"\n");
}
shaderStr += std::string(" // Apply scale and bias to the fetched values.\n"
" g1 = g1 * in_volume_scale[index][c] + in_volume_bias[index][c];\n"
" g2 = g2 * in_volume_scale[index][c] + in_volume_bias[index][c];\n"
"\n");
if (!hasGradientOp)
{
shaderStr +=
std::string(" // Central differences: (F_front - F_back) / 2h\n"
" // This version of computeGradient() is only used for lighting\n"
" // calculations (only direction matters), hence the difference is\n"
" // not scaled by 2h and a dummy gradient mag is returned (-1.).\n"
" return vec4((g1 - g2) / in_cellSpacing[index], -1.0);\n"
"}\n");
}
else
{
shaderStr += std::string(
" // Scale values the actual scalar range.\n"
" float range = in_scalarsRange[4*index+c][1] - in_scalarsRange[4*index+c][0];\n"
" g1 = in_scalarsRange[4*index+c][0] + range * g1;\n"
" g2 = in_scalarsRange[4*index+c][0] + range * g2;\n"
"\n"
" // Central differences: (F_front - F_back) / 2h\n"
" g2 = g1 - g2;\n"
"\n"
" float avgSpacing = (in_cellSpacing[index].x +\n"
" in_cellSpacing[index].y + in_cellSpacing[index].z) / 3.0;\n"
" vec3 aspect = in_cellSpacing[index] * 2.0 / avgSpacing;\n"
" g2 /= aspect;\n"
" float grad_mag = length(g2);\n"
"\n"
" // Handle normalizing with grad_mag == 0.0\n"
" g2 = grad_mag > 0.0 ? normalize(g2) : vec3(0.0);\n"
"\n"
" // Since the actual range of the gradient magnitude is unknown,\n"
" // assume it is in the range [0, 0.25 * dataRange].\n"
" range = range != 0 ? range : 1.0;\n"
" grad_mag = grad_mag / (0.25 * range);\n"
" grad_mag = clamp(grad_mag, 0.0, 1.0);\n"
"\n"
" return vec4(g2.xyz, grad_mag);\n"
"}\n");
}
}
else
{
shaderStr += std::string(
"vec4 computeGradient(in vec3 texPos, in int c, in sampler3D volume, in int index)\n"
"{\n"
" return vec4(0.0);\n"
"}\n");
}
return shaderStr;
}
//---------------------------------------------------------------------------
std::string ComputeMatricesInit(
vtkOpenGLGPUVolumeRayCastMapper* vtkNotUsed(mapper), int numberPositionalLights)
{
std::string resStr;
resStr += R"***(
for(int i=0; i<TOTAL_NUMBER_LIGHTS; i++)
{
g_lightDirectionTex[i] = (g_eyeToTexture * vec4(-in_lightDirection[i], 0.0)).xyz;
}
)***";
if (numberPositionalLights > 0)
{
resStr += R"***(
for(int i=0; i<NUMBER_POS_LIGHTS; i++)
{
g_lightPositionTex[i] = (g_eyeToTexture * vec4(in_lightPosition[i], 1.0)).xyz;
}
)***";
}
return resStr;
}
//--------------------------------------------------------------------------
std::string ComputeRGBA2DWithGradientDeclaration(vtkRenderer* vtkNotUsed(ren),
vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol), int noOfComponents,
int independentComponents, std::map<int, std::string> opacityTableMap, int useGradient)
{
std::string resStr;
std::string functionBody;
bool severalIndpt = noOfComponents > 1 && independentComponents;
std::string functionSignature = severalIndpt
? "vec4 computeRGBAWithGrad(vec4 scalar, vec4 grad, int component)\n"
: "vec4 computeRGBAWithGrad(vec4 scalar, vec4 grad)\n";
if (severalIndpt)
{
// Multiple independent components
if (!useGradient)
{
functionBody +=
"vec4 yscalar = texture3D(in_transfer2DYAxis, g_dataPos);\n"
"for (int i = 0; i < 4; ++i)\n"
"{\n"
" yscalar[i] = yscalar[i] * in_transfer2DYAxis_scale[i] + in_transfer2DYAxis_bias[i];\n"
"}\n";
}
for (int i = 0; i < noOfComponents; ++i)
{
std::string secondAxis(useGradient
// we take the same grad for all components so we have to be sure that
// the one given as a parameter is computed wrt the right component
? "grad.w"
: std::string("yscalar[") + std::to_string(i) + "]");
functionBody += " if(component == " + std::to_string(i) +
")\n"
" {\n"
" return texture2D(" +
opacityTableMap[i] + ",\n" + " vec2(scalar[" + std::to_string(i) + "], " + secondAxis +
"))\n" + " }\n";
}
}
else if (noOfComponents == 2 && !independentComponents)
{
std::string secondAxis(useGradient ? "grad.w" : "yscalar.y");
functionBody += " return texture2D(" + opacityTableMap[0] +
",\n"
" vec2(scalar.y, " +
secondAxis + "));\n";
}
else
{
if (useGradient)
{
// Dependent components (RGBA) || Single component
functionBody += " return texture2D(" + opacityTableMap[0] +
",\n"
" vec2(scalar.a, grad.w));\n";
}
else
{
// Dependent compoennts (RGBA) || Single component
functionBody +=
" vec4 yscalar = texture3D(in_transfer2DYAxis, g_dataPos);\n"
" yscalar.r = yscalar.r * in_transfer2DYAxis_scale.r + in_transfer2DYAxis_bias.r;\n"
" yscalar = vec4(yscalar.r);\n"
" return texture2D(" +
opacityTableMap[0] +
",\n"
" vec2(scalar.a, yscalar.w));\n";
}
}
resStr = functionSignature + "{\n" + functionBody + "}\n";
return resStr;
}
//-----------------------------------------------------------------------
std::string ComputeOpacityEvaluationCall(vtkOpenGLGPUVolumeRayCastMapper* vtkNotUsed(mapper),
vtkOpenGLGPUVolumeRayCastMapper::VolumeInputMap& inputs, int noOfComponents,
int independentComponents, int useGradYAxis, std::string position, bool requestColor = false)
{
// relies on the declaration of variables opacity, gradient, c, volume, index, scalar, gradTF,
// opacityTF, label in the scope
std::string resStr;
if (inputs.size() > 1)
{
// Multi Volume
const bool hasGradOp = ::HasGradientOpacity(inputs);
resStr += " opacity = computeOpacity(vec4(scalar), opacityTF);\n";
// either all volumes have a TF either none have one, so we can have
// the same opacity call for all volumes
if (hasGradOp)
{
resStr += std::string(" gradient = computeGradient(") + position + ", c, volume, index);\n";
resStr += " opacity *= computeGradientOpacity(gradient, gradTF);\n";
}
// ignore request color for now, but given the actual architecture, it should be a
// succession of 'if' comparing the volume idx
if (requestColor)
{
vtkGenericWarningMacro(<< "ComputeOpacityEvaluationCall was called with requestColor, but "
"MultiVolume does not support this option yet.");
}
}
else
{
// Single Volume
vtkVolumeProperty* volProp = inputs[0].Volume->GetProperty();
const bool hasGradOp = volProp->HasGradientOpacity() && !volProp->GetDisableGradientOpacity();
const bool useLabelGradientOpacity = (volProp->HasLabelGradientOpacity() &&
(noOfComponents == 1 || !independentComponents) && !volProp->GetDisableGradientOpacity());
const int tfMode = volProp->GetTransferFunctionMode();
bool indpComps = (noOfComponents > 1 && independentComponents);
std::string compArgument = (indpComps) ? std::string(", c") : std::string();
const bool needGrad = (tfMode == vtkVolumeProperty::TF_2D && useGradYAxis); // to be sure
if (tfMode == vtkVolumeProperty::TF_1D)
{
std::string compWeights = indpComps ? std::string(" * in_componentWeight[c]") : std::string();
resStr += std::string(" opacity = computeOpacity(vec4(scalar)") + compArgument +
std::string(")") + compWeights + ";\n";
if (hasGradOp || useLabelGradientOpacity)
{
resStr += std::string(" gradient = computeGradient(") + position +
std::string(", c, volume, index);\n"
" if(gradient.w >= 0.0) {\n") +
(hasGradOp ? (std::string(" opacity *= computeGradientOpacity(gradient") +
compArgument + ")" + compWeights + ";\n")
: std::string())
+ (useLabelGradientOpacity
? (std::string(" opacity *= computeGradientOpacityForLabel(gradient, label);\n"))
: std::string())
+ std::string(" }\n");
}
if (requestColor)
{
resStr +=
" color = texture2D(" + inputs[0].RGBTablesMap[0] + ", vec2(scalar, 0.0)).xyz;\n";
}
}
else
{
// 2D TF
if (needGrad)
{
resStr +=
std::string(" gradient = computeGradient(") + position + ", c, volume, index);\n";
}
resStr += std::string(" vec4 lutRes = computeRGBAWithGrad(vec4(scalar), gradient") +
compArgument + std::string(");\n");
resStr += " opacity = lutRes.a;\n";
if (requestColor)
{
resStr += " color = lutRes.xyz;\n";
}
}
}
return resStr;
}
//--------------------------------------------------------------------------
std::string ComputeDensityGradientDeclaration(vtkOpenGLGPUVolumeRayCastMapper* mapper,
vtkOpenGLGPUVolumeRayCastMapper::VolumeInputMap& inputs, int noOfComponents,
int independentComponents, int useGradYAxis)
{
const bool hasLighting = ::HasLighting(inputs);
const bool hasGradientOp = ::HasGradientOpacity(inputs);
std::string functionSignature;
if (inputs.size() > 1)
{
if (hasGradientOp)
{
functionSignature = std::string(
"vec4 computeDensityGradient(in vec3 texPos, in int c, in sampler3D volume, "
"const in sampler2D opacityTF, const in sampler2D gradTF, in int index, float label)\n");
}
else
{
functionSignature =
std::string("vec4 computeDensityGradient(in vec3 texPos, in int c, in sampler3D volume, "
"const in sampler2D opacityTF, in int index, float label)\n");
}
}
else
{
functionSignature = std::string("vec4 computeDensityGradient(in vec3 texPos, in int c, in "
"sampler3D volume, in int index, float label)\n");
}
std::string shaderStr;
if (hasLighting || hasGradientOp)
{
std::string opacityTFcall;
std::string gradComput;
// this table remembers the correspondence results <-> texture coordinates
static const std::array<std::pair<const char*, const char*>, 6> results_texPos = { {
{ " g1.x", "texPosPvec[0]" },
{ " g1.y", "texPosPvec[1]" },
{ " g1.z", "texPosPvec[2]" },
{ " g2.x", "texPosNvec[0]" },
{ " g2.y", "texPosNvec[1]" },
{ " g2.z", "texPosNvec[2]" },
} };
shaderStr += std::string("// c is short for component\n") + functionSignature +
std::string("{\n"
" // Approximate Nabla(F) derivatives with central differences.\n"
" vec3 g1; // F_front\n"
" vec3 g2; // F_back\n"
" vec3 xvec = vec3(in_cellStep[index].x, 0.0, 0.0);\n"
" vec3 yvec = vec3(0.0, in_cellStep[index].y, 0.0);\n"
" vec3 zvec = vec3(0.0, 0.0, in_cellStep[index].z);\n"
" vec3 texPosPvec[3];\n"
" texPosPvec[0] = texPos + xvec;\n"
" texPosPvec[1] = texPos + yvec;\n"
" texPosPvec[2] = texPos + zvec;\n"
" vec3 texPosNvec[3];\n"
" texPosNvec[0] = texPos - xvec;\n"
" texPosNvec[1] = texPos - yvec;\n"
" texPosNvec[2] = texPos - zvec;\n"
" float scalar;\n"
" float opacity;\n"
" vec4 gradient;\n"
"\n");
for (auto& gradComp : results_texPos)
{
// opacityTFcall corresponds to code snippet used to compute the opacity
opacityTFcall = ComputeOpacityEvaluationCall(
mapper, inputs, noOfComponents, independentComponents, useGradYAxis, gradComp.second);
shaderStr += std::string(" scalar = texture3D(volume,") + gradComp.second +
std::string(")[c];\n"
" scalar = scalar * in_volume_scale[index][c] + in_volume_bias[index][c];\n") +
opacityTFcall + gradComp.first + " = opacity;\n";
}
if (::UseClippedVoxelIntensity(inputs) && mapper->GetClippingPlanes())
{
shaderStr +=
std::string(" vec4 g1ObjDataPos[3], g2ObjDataPos[3];\n"
" for (int i = 0; i < 3; ++i)\n"
" {\n"
" g1ObjDataPos[i] = clip_texToObjMat * vec4(texPosPvec[i], 1.0);\n"
" if (g1ObjDataPos[i].w != 0.0)\n"
" {\n"
" g1ObjDataPos[i] /= g1ObjDataPos[i].w;\n"
" }\n"
" g2ObjDataPos[i] = clip_texToObjMat * vec4(texPosNvec[i], 1.0);\n"
" if (g2ObjDataPos[i].w != 0.0)\n"
" {\n"
" g2ObjDataPos[i] /= g2ObjDataPos[i].w;\n"
" }\n"
" }\n"
"\n"
" for (int i = 0; i < clip_numPlanes && !g_skip; i = i + 6)\n"
" {\n"
" vec3 planeOrigin = vec3(in_clippingPlanes[i + 1],\n"
" in_clippingPlanes[i + 2],\n"
" in_clippingPlanes[i + 3]);\n"
" vec3 planeNormal = normalize(vec3(in_clippingPlanes[i + 4],\n"
" in_clippingPlanes[i + 5],\n"
" in_clippingPlanes[i + 6]));\n"
" for (int j = 0; j < 3; ++j)\n"
" {\n"
" if (dot(vec3(planeOrigin - g1ObjDataPos[j].xyz), planeNormal) > 0)\n"
" {\n"
" g1[j] = in_clippedVoxelIntensity;\n"
" }\n"
" if (dot(vec3(planeOrigin - g2ObjDataPos[j].xyz), planeNormal) > 0)\n"
" {\n"
" g2[j] = in_clippedVoxelIntensity;\n"
" }\n"
" }\n"
" }\n"
"\n");
}
if (!hasGradientOp)
{
shaderStr +=
std::string(" // Central differences: (F_front - F_back) / 2h\n"
" // This version of computeGradient() is only used for lighting\n"
" // calculations (only direction matters), hence the difference is\n"
" // not scaled by 2h and a dummy gradient mag is returned (-1.).\n"
" return vec4((g1 - g2) / in_cellSpacing[index], -1.0);\n"
"}\n");
}
else
{
shaderStr += std::string(
" // Scale values the actual scalar range.\n"
" float range = in_scalarsRange[4*index+c][1] - in_scalarsRange[4*index+c][0];\n"
" g1 = in_scalarsRange[4*index+c][0] + range * g1;\n"
" g2 = in_scalarsRange[4*index+c][0] + range * g2;\n"
"\n"
" // Central differences: (F_front - F_back) / 2h\n"
" g2 = g1 - g2;\n"
"\n"
" float avgSpacing = (in_cellSpacing[index].x +\n"
" in_cellSpacing[index].y + in_cellSpacing[index].z) / 3.0;\n"
" vec3 aspect = in_cellSpacing[index] * 2.0 / avgSpacing;\n"
" g2 /= aspect;\n"
" float grad_mag = length(g2);\n"
"\n"
" // Handle normalizing with grad_mag == 0.0\n"
" g2 = grad_mag > 0.0 ? normalize(g2) : vec3(0.0);\n"
"\n"
" // Since the actual range of the gradient magnitude is unknown,\n"
" // assume it is in the range [0, 0.25 * dataRange].\n"
" range = range != 0 ? range : 1.0;\n"
" grad_mag = grad_mag / (0.25 * range);\n"
" grad_mag = clamp(grad_mag, 0.0, 1.0);\n"
"\n"
" return vec4(g2.xyz, grad_mag);\n"
"}\n");
}
}
else
{
shaderStr += functionSignature +
std::string("{\n"
" return vec4(0.0);\n"
"}\n");
}
return shaderStr;
}
std::string PhaseFunctionDeclaration(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vol)
{
std::string resStr;
// to be compatible with the surface shading model,
// the phase function should be normalized to 4pi instead of 1
// that's why the isotropic phase function returns 1 and not 1/4pi for example
if (std::abs(vol->GetProperty()->GetScatteringAnisotropy()) < 0.01)
{
resStr += R"***(
float phase_function(float cos_angle)
{
return 1.0;
}
)***";
}
else
{
resStr += R"***(
float g_anisotropy2 = in_anisotropy * in_anisotropy;
float phase_function(float cos_angle)
{
float d = 1.0 + g_anisotropy2 - 2.0 * in_anisotropy * cos_angle;
return (1.0 - g_anisotropy2) / (d * sqrt(d));
}
)***";
}
return resStr;
}
//--------------------------------------------------------------------------
std::string ComputeLightingDeclaration(vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* mapper,
vtkVolume* vol, int noOfComponents, int independentComponents, int totalNumberOfLights,
int numberPositionalLights, bool defaultLighting)
{
auto glMapper = vtkOpenGLGPUVolumeRayCastMapper::SafeDownCast(mapper);
vtkVolumeProperty* volProperty = vol->GetProperty();
std::string shaderStr = std::string("\
\nvec4 computeLighting(vec4 color, int component, float label)\
\n{\
\n vec4 finalColor = vec4(0.0);\n");
// Shading for composite blending only
int const shadeReqd = volProperty->GetShade() &&
(mapper->GetBlendMode() == vtkVolumeMapper::COMPOSITE_BLEND ||
mapper->GetBlendMode() == vtkVolumeMapper::ISOSURFACE_BLEND ||
mapper->GetBlendMode() == vtkVolumeMapper::SLICE_BLEND);
int const transferMode = volProperty->GetTransferFunctionMode();
bool const volumetricShadow = glMapper->GetVolumetricScatteringBlending() > 0.0;
std::string volumetricCall = volumetricShadow
? "\n vol_shadow = volumeShadow(g_dataPos, tex_light.xyz, 0.0, component, in_volume[0], "
"0, label);"
: "";
std::string volumetricDeclarations =
volumetricShadow ? "\n float vol_shadow = 1.0;\n vec4 tex_light = vec4(0.0);\n" : "\n";
// If shading is required, we compute a shading gradient (used for the shading model)
if (shadeReqd)
{
if (glMapper->GetComputeNormalFromOpacity())
{
// we compute the gradienty according to the volume's opacity !
shaderStr +=
std::string(" vec4 shading_gradient = computeDensityGradient(g_dataPos, component, "
"in_volume[0], 0, label);\n");
}
else
{
// otherwise we take the scalar gradient directly
shaderStr += std::string(
" vec4 shading_gradient = computeGradient(g_dataPos, component, in_volume[0], 0);\n");
}
}
// If we need the scalar gradient (typically to sample a transfer function)
if (volProperty->HasGradientOpacity() || volProperty->HasLabelGradientOpacity())
{
// If we didn't compute it before, we compute it
if (!shadeReqd || glMapper->GetComputeNormalFromOpacity())
{
shaderStr +=
std::string(" vec4 gradient = computeGradient(g_dataPos, component, in_volume[0], 0);\n");
}
// otherwise, we use what we already computed
else
{
shaderStr += std::string(" vec4 gradient = shading_gradient;\n");
}
}
if (shadeReqd)
{
if (defaultLighting)
{
shaderStr += R"***(
vec3 diffuse = vec3(0.0);
vec3 specular = vec3(0.0);
vec3 normal = shading_gradient.xyz;
float normalLength = length(normal);
if (normalLength > 0.0)
{
normal = normalize(normal);
}
else
{
normal = vec3(0.0, 0.0, 0.0);
}
// XXX: normal is oriented inside the volume, so we take -g_ldir/-g_vdir
float nDotL = dot(normal, -g_ldir[0]);
vec3 r = normalize(2.0 * nDotL * normal + g_ldir[0]);
float vDotR = dot(r, -g_vdir[0]);
if (nDotL < 0.0 && in_twoSidedLighting)
{
nDotL = -nDotL;
}
if (nDotL > 0.0)
{
diffuse = nDotL * in_diffuse[component] *
in_lightDiffuseColor[0] * color.rgb;
vDotR = max(vDotR, 0.0);
specular = pow(vDotR, in_shininess[component]) *
in_specular[component] *
in_lightSpecularColor[0];
}
// For the headlight, ignore the light's ambient color
// for now as it is causing the old mapper tests to fail
finalColor.xyz = in_ambient[component] * color.rgb +
diffuse + specular;
)***";
}
else if (totalNumberOfLights > 0)
{
shaderStr += R"***(
g_fragWorldPos = g_texToView * vec4(g_dataPos, 1.0);
if (g_fragWorldPos.w != 0.0)
{
g_fragWorldPos /= g_fragWorldPos.w;
}
vec3 viewDirection = normalize(-g_fragWorldPos.xyz);
vec3 ambient = vec3(0,0,0);
vec3 diffuse = vec3(0,0,0);
vec3 specular = vec3(0,0,0);
vec3 vertLightDirection;
vec3 normal = normalize((in_textureToEye[0] * vec4(shading_gradient.xyz, 0.0)).xyz);
vec3 lightDir;
)***";
if (numberPositionalLights > 0)
{
shaderStr += R"***(
for (int posNum = 0; posNum < NUMBER_POS_LIGHTS; posNum++)
{
float attenuation = 1.0;
lightDir = in_lightDirection[posNum];
vertLightDirection = (g_fragWorldPos.xyz - in_lightPosition[posNum]);
float distance = length(vertLightDirection);
vertLightDirection = normalize(vertLightDirection);
attenuation = 1.0 /
(in_lightAttenuation[posNum].x
+ in_lightAttenuation[posNum].y * distance
+ in_lightAttenuation[posNum].z * distance * distance);
// per OpenGL standard cone angle is 90 or less for a spot light
if (in_lightConeAngle[posNum] <= 90.0)
{
float coneDot = dot(vertLightDirection, lightDir);
// if inside the cone
if (coneDot >= cos(radians(in_lightConeAngle[posNum])))
{
attenuation = attenuation * pow(coneDot, in_lightExponent[posNum]);
}
else
{
attenuation = 0.0;
}
}
float nDotL = dot(normal, vertLightDirection);
if (nDotL < 0.0 && in_twoSidedLighting)
{
nDotL = -nDotL;
}
if (nDotL > 0.0)
{
float df = max(0.0, attenuation * nDotL);
diffuse += (df * in_lightDiffuseColor[posNum]);
vec3 r = normalize(2.0 * nDotL * normal - vertLightDirection);
float rDotV = dot(-viewDirection, r);
if (rDotV < 0.0 && in_twoSidedLighting)
{
rDotV = -rDotV;
}
if (rDotV > 0.0)
{
float sf = attenuation * pow(rDotV, in_shininess[component]);
specular += (sf * in_lightSpecularColor[posNum]);
}
}
ambient += in_lightAmbientColor[posNum];
}
)***";
}
shaderStr += R"***(
for (int dirNum = NUMBER_POS_LIGHTS; dirNum < TOTAL_NUMBER_LIGHTS; dirNum++)
{
vertLightDirection = in_lightDirection[dirNum];
float nDotL = dot(normal, vertLightDirection);
if (nDotL < 0.0 && in_twoSidedLighting)
{
nDotL = -nDotL;
}
if (nDotL > 0.0)
{
float df = max(0.0, nDotL);
diffuse += (df * in_lightDiffuseColor[dirNum]);
vec3 r = normalize(2.0 * nDotL * normal - vertLightDirection);
float rDotV = dot(-viewDirection, r);
if (rDotV > 0.0)
{
float sf = pow(rDotV, in_shininess[component]);
specular += (sf * in_lightSpecularColor[dirNum]);
}
}
ambient += in_lightAmbientColor[dirNum];
}
finalColor.xyz = in_ambient[component] * ambient +
in_diffuse[component] * diffuse * color.rgb +
in_specular[component] * specular;
)***";
}
}
else
{
shaderStr += std::string("\n finalColor = vec4(color.rgb, 0.0);");
}
if (glMapper->GetVolumetricScatteringBlending() > 0.0 && totalNumberOfLights > 0)
{
float vsBlend = glMapper->GetVolumetricScatteringBlending();
std::string blendingFormula = std::string(" float vol_coef = ") +
(vsBlend < 1.0 ? "2.0 * in_volumetricScatteringBlending * exp( - 2.0 * "
"in_volumetricScatteringBlending * shading_gradient.w * color.a)"
: "2.0 * (1.0 - in_volumetricScatteringBlending) * exp( - 2.0 * "
"in_volumetricScatteringBlending * shading_gradient.w * color.a) + 2.0 * "
"in_volumetricScatteringBlending - 1.0") +
";\n";
shaderStr +=
(defaultLighting
? std::string()
: std::string(
"vec3 view_tdir = normalize((g_eyeToTexture * vec4(viewDirection, 0.0)).xyz);\n")) +
R"***(
vec3 secondary_contrib = vec3(0.0);
vec3 tex_light = vec3(0.0);
shading_gradient.w = length(shading_gradient.xyz);
vec3 diffuse_light = vec3(0.0);
float attenuation = 0.0;
float vol_shadow = 0.0;
float phase = 1.0;
)***";
if (defaultLighting)
{
shaderStr += R"***(
tex_light = (in_inverseTextureDatasetMatrix[0] * in_inverseVolumeMatrix[0] * vec4(in_cameraPos, 1.0)).xyz;
phase = phase_function(-1); // always angle of pi
vol_shadow = volumeShadow(g_dataPos, tex_light, 1.0, component, in_volume[0], 0, label);
secondary_contrib += vol_shadow * phase * color.rgb * in_diffuse[component] * in_lightDiffuseColor[0];
secondary_contrib += in_ambient[component] * in_lightAmbientColor[0];
)***";
}
else
{
if (numberPositionalLights > 0)
{
shaderStr += R"***(
float dist_light = 0.0;
for(int posNum = 0; posNum < NUMBER_POS_LIGHTS; posNum++)
{
tex_light = g_lightPositionTex[posNum];
vec3 light_vert = g_fragWorldPos.xyz - in_lightPosition[posNum];
dist_light = length(light_vert);
float light_angle = dot(normalize(light_vert), normalize(in_lightDirection[posNum]));
phase = phase_function(dot(normalize(g_dataPos - tex_light), view_tdir));
attenuation = 1.0 /
(in_lightAttenuation[posNum].x
+ in_lightAttenuation[posNum].y * dist_light
+ in_lightAttenuation[posNum].z * dist_light * dist_light);
attenuation *= max(0.0, sign(light_angle - cos(radians(in_lightConeAngle[posNum]))))
* pow(light_angle, in_lightExponent[posNum]);
vol_shadow = volumeShadow(g_dataPos, tex_light, 1.0, component, in_volume[0], 0, label);
secondary_contrib += vol_shadow * phase * attenuation * color.rgb * in_diffuse[component] * in_lightDiffuseColor[posNum];
secondary_contrib += in_ambient[component] * in_lightAmbientColor[posNum];
}
)***";
}
shaderStr += R"***(
for(int dirNum = NUMBER_POS_LIGHTS; dirNum < TOTAL_NUMBER_LIGHTS; dirNum++)
{
tex_light = g_lightDirectionTex[dirNum];
phase = phase_function(dot(normalize(-tex_light), view_tdir));
vol_shadow = volumeShadow(g_dataPos, tex_light, 0.0, component, in_volume[0], 0, label);
secondary_contrib += vol_shadow * phase * color.rgb * in_diffuse[component] * in_lightDiffuseColor[dirNum];
secondary_contrib += in_ambient[component] * in_lightAmbientColor[dirNum];
}
)***";
}
shaderStr += blendingFormula +
R"***(
finalColor.xyz = (1.0 - vol_coef) * finalColor.xyz + vol_coef * secondary_contrib;
)***";
}
// For 1D transfers only (2D transfer functions hold scalar and
// gradient-magnitude opacities combined in the same table).
// For multiple inputs, a different computeGradientOpacity() signature
// is defined.
if (transferMode == vtkVolumeProperty::TF_1D && glMapper->GetInputCount() == 1)
{
if (noOfComponents == 1 || !independentComponents)
{
if (volProperty->HasGradientOpacity())
{
shaderStr += std::string("\
\n if (gradient.w >= 0.0 && label == 0.0)\
\n {\
\n color.a *= computeGradientOpacity(gradient);\
\n }");
}
if (volProperty->HasLabelGradientOpacity())
{
shaderStr += std::string("\
\n if (gradient.w >= 0.0 && label > 0.0)\
\n {\
\n color.a *= computeGradientOpacityForLabel(gradient, label);\
\n }");
}
}
else if (noOfComponents > 1 && independentComponents && volProperty->HasGradientOpacity())
{
shaderStr += std::string("\
\n if (gradient.w >= 0.0)\
\n {\
\n for (int i = 0; i < in_noOfComponents; ++i)\
\n {\
\n color.a = color.a *\
\n computeGradientOpacity(gradient, i) * in_componentWeight[i];\
\n }\
\n }");
}
}
shaderStr += std::string("\
\n finalColor.a = color.a;\
\n return finalColor;\
\n }");
return shaderStr;
}
//--------------------------------------------------------------------------
std::string ComputeLightingMultiDeclaration(vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* mapper,
vtkVolume* vol, int noOfComponents, int independentComponents,
int vtkNotUsed(totalNumberOfLights), bool defaultLighting)
{
auto glMapper = vtkOpenGLGPUVolumeRayCastMapper::SafeDownCast(mapper);
vtkVolumeProperty* volProperty = vol->GetProperty();
std::string shaderStr = std::string();
// if no gradient TF is needed, don't add it into the function signature
if (volProperty->HasGradientOpacity())
{
shaderStr += std::string("\
\nvec4 computeLighting(vec3 texPos, vec4 color, const in sampler2D gradientTF, const in sampler3D volume, const in sampler2D opacityTF, const int volIdx, int component)\
\n {\
\n vec4 finalColor = vec4(0.0);\n");
}
else
{
shaderStr += std::string("\
\nvec4 computeLighting(vec3 texPos, vec4 color, const in sampler3D volume, const in sampler2D opacityTF, const int volIdx, int component)\
\n {\
\n vec4 finalColor = vec4(0.0);\n");
}
// Shading for composite blending only
int const shadeReqd = volProperty->GetShade() &&
(mapper->GetBlendMode() == vtkVolumeMapper::COMPOSITE_BLEND ||
mapper->GetBlendMode() == vtkVolumeMapper::ISOSURFACE_BLEND);
int const transferMode = volProperty->GetTransferFunctionMode();
// If shading is required, we compute a shading gradient (used for the shading model)
if (shadeReqd)
{
/*
We compute the gradient every time, because the alternative would be to test whether
the volume has gradient cache or not. But as both branches will be evaluated anyway
on GPU, we might as well compute the gradient every time.
*/
if (glMapper->GetComputeNormalFromOpacity())
{
if (volProperty->HasGradientOpacity())
{
shaderStr += " vec4 shading_gradient = computeDensityGradient(texPos, component, volume, "
"opacityTF, gradientTF, volIdx, 0.0);\n";
}
else
{
shaderStr += " vec4 shading_gradient = computeDensityGradient(texPos, component, volume, "
"opacityTF, volIdx, 0.0);\n";
}
}
else
{
shaderStr +=
" vec4 shading_gradient = computeGradient(texPos, component, volume, volIdx);\n";
}
}
// If we need the scalar gradient (typically to sample a transfer function)
if (volProperty->HasGradientOpacity())
{
if (!shadeReqd || glMapper->GetComputeNormalFromOpacity())
{
shaderStr += " vec4 gradient = computeGradient(texPos, component, volume, volIdx);\n";
}
else
{
// if we already computed it
shaderStr += " vec4 gradient = shading_gradient;\n";
}
}
if (shadeReqd && defaultLighting)
{
shaderStr += std::string("\
\n vec3 diffuse = vec3(0.0);\
\n vec3 specular = vec3(0.0);\
\n vec3 normal = shading_gradient.xyz;\
\n float normalLength = length(normal);\
\n if (normalLength > 0.0)\
\n {\
\n normal = normalize(normal);\
\n }\
\n else\
\n {\
\n normal = vec3(0.0, 0.0, 0.0);\
\n }\
\n // normal is oriented inside the volume (because normal = gradient, oriented inside the volume)\
\n // thus we have to take minus everything\
\n float nDotL = dot(normal, -g_ldir[volIdx]);\
\n vec3 r = normalize(2.0 * nDotL * normal + g_ldir[volIdx]);\
\n float vDotR = dot(r, -g_vdir[volIdx]);\
\n if (nDotL < 0.0 && in_twoSidedLighting)\
\n {\
\n nDotL = -nDotL;\
\n }\
\n if (nDotL > 0.0)\
\n {\
\n diffuse = nDotL * in_diffuse[component] *\
\n in_lightDiffuseColor[0] * color.rgb;\
\n vDotR = max(vDotR, 0.0);\
\n specular = pow(vDotR, in_shininess[component]) *\
\n in_specular[component] *\
\n in_lightSpecularColor[0];\
\n }\
\n finalColor.xyz = in_ambient[component] * color.rgb * in_lightAmbientColor[0] +\
\n diffuse + specular;\
\n");
}
else
{
shaderStr += std::string("\n finalColor = vec4(color.rgb, 0.0);");
}
// For 1D transfers only (2D transfer functions hold scalar and
// gradient-magnitude opacities combined in the same table).
if (transferMode == vtkVolumeProperty::TF_1D)
{
if (volProperty->HasGradientOpacity() && (noOfComponents == 1 || !independentComponents))
{
shaderStr += std::string("\
\n if (gradient.w >= 0.0)\
\n {\
\n color.a = color.a *\
\n computeGradientOpacity(gradient, gradientTF);\
\n }");
}
}
shaderStr += std::string("\
\n finalColor.a = color.a;\
\n return clamp(finalColor, 0.0, 1.0);\
\n }");
return shaderStr;
}
//--------------------------------------------------------------------------
std::string ComputeRayDirectionDeclaration(vtkRenderer* ren, vtkVolumeMapper* vtkNotUsed(mapper),
vtkVolume* vtkNotUsed(vol), int vtkNotUsed(noOfComponents))
{
if (!ren->GetActiveCamera()->GetParallelProjection())
{
return std::string("\
\nvec3 computeRayDirection()\
\n {\
\n return normalize(ip_vertexPos.xyz - g_eyePosObj.xyz);\
\n }");
}
else
{
return std::string("\
\nuniform vec3 in_projectionDirection;\
\nvec3 computeRayDirection()\
\n {\
\n return normalize((in_inverseVolumeMatrix[0] *\
\n vec4(in_projectionDirection, 0.0)).xyz);\
\n }");
}
}
//--------------------------------------------------------------------------
std::string ComputeColorUniforms(vtkOpenGLGPUVolumeRayCastMapper::VolumeInputMap& inputs,
int noOfComponents, vtkVolumeProperty* volProp)
{
std::string resStr;
if (inputs.size() > 1)
{
// multi volume
for (auto& item : inputs)
{
const auto& prop = item.second.Volume->GetProperty();
if (prop->GetTransferFunctionMode() != vtkVolumeProperty::TF_1D)
continue;
auto& map = item.second.RGBTablesMap;
const auto numComp = map.size();
resStr +=
"uniform sampler2D " + ArrayBaseName(map[0]) + "[" + std::to_string(numComp) + "];\n";
}
}
else
{
// single volume
if (volProp->GetTransferFunctionMode() == vtkVolumeProperty::TF_1D)
{
resStr += "uniform sampler2D " + ArrayBaseName(inputs[0].RGBTablesMap[0]) + "[" +
std::to_string(noOfComponents) + "];\n";
}
// in case of TF_2D, the texture needed is defined with computeOpacity
}
return resStr;
}
//--------------------------------------------------------------------------
std::string ComputeColorDeclaration(vtkRenderer* vtkNotUsed(ren),
vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol), int noOfComponents,
int independentComponents, std::map<int, std::string> colorTableMap)
{
std::ostringstream ss;
std::string shaderStr = ss.str();
if (noOfComponents == 1)
{
shaderStr += std::string("\
\nvec4 computeColor(vec4 scalar, float opacity)\
\n {\
\n return clamp(computeLighting(vec4(texture2D(" +
colorTableMap[0] + ",\
\n vec2(scalar.w, 0.0)).xyz, opacity), 0, 0.0), 0.0, 1.0);\
\n }");
return shaderStr;
}
else if (noOfComponents > 1 && independentComponents)
{
std::ostringstream toString;
shaderStr += std::string("\
\nvec4 computeColor(vec4 scalar, float opacity, int component)\
\n {");
for (int i = 0; i < noOfComponents; ++i)
{
toString << i;
shaderStr += std::string("\
\n if (component == " +
toString.str() + ")");
shaderStr += std::string("\
\n {\
\n return clamp(computeLighting(vec4(texture2D(\
\n " +
colorTableMap[i]);
shaderStr += std::string(", vec2(\
\n scalar[" +
toString.str() + "],0.0)).xyz,\
\n opacity)," +
toString.str() + ", 0.0), 0.0, 1.0);\
\n }");
// Reset
toString.str("");
toString.clear();
}
shaderStr += std::string("\n }");
return shaderStr;
}
else if (noOfComponents == 2 && !independentComponents)
{
shaderStr += std::string("\
\nvec4 computeColor(vec4 scalar, float opacity)\
\n {\
\n return clamp(computeLighting(vec4(texture2D(" +
colorTableMap[0] + ",\
\n vec2(scalar.x, 0.0)).xyz,\
\n opacity), 0, 0.0), 0.0, 1.0);\
\n }");
return shaderStr;
}
else
{
shaderStr += std::string("\
\nvec4 computeColor(vec4 scalar, float opacity)\
\n {\
\n return clamp(computeLighting(vec4(scalar.xyz, opacity), 0, 0.0), 0.0, 1.0);\
\n }");
return shaderStr;
}
}
//--------------------------------------------------------------------------
std::string ComputeColorMultiDeclaration(
vtkOpenGLGPUVolumeRayCastMapper::VolumeInputMap& inputs, bool useGradientTF)
{
std::ostringstream ss;
int lastComponentMode = vtkVolumeInputHelper::INVALID;
std::map<int, std::string> lastColorTableMap;
for (auto& item : inputs)
{
auto prop = item.second.Volume->GetProperty();
if (prop->GetTransferFunctionMode() != vtkVolumeProperty::TF_1D)
continue;
auto& map = item.second.RGBTablesMap;
lastComponentMode = item.second.ComponentMode;
lastColorTableMap = map;
}
if (lastComponentMode == vtkVolumeInputHelper::LA)
{
ss << "vec4 computeColor(vec4 scalar, const in sampler2D colorTF)\
\n {\
\n return clamp(computeLighting(vec4(texture2D(colorTF,\
\n vec2(scalar.w, 0.0)).xyz, opacity), 0), 0.0, 1.0);\
\n }\n";
}
else
{
if (useGradientTF)
{
ss
<< "vec4 computeColor(vec3 texPos, vec4 scalar, float opacity, const in sampler2D colorTF, "
"const in sampler2D gradientTF, const in sampler3D volume, const in sampler2D "
"opacityTF, const int volIdx)\n\n"
"{\n"
" return clamp(computeLighting(texPos, vec4(texture2D(colorTF,\n"
" vec2(scalar.w, 0.0)).xyz, opacity), gradientTF, volume, "
"opacityTF,"
"volIdx, 0), 0.0, 1.0);\n"
"}\n";
}
else
{
ss
<< "vec4 computeColor(vec3 texPos, vec4 scalar, float opacity, const in sampler2D colorTF, "
"const in sampler3D volume, const in sampler2D opacityTF, const int volIdx)\n\n"
"{\n"
" return clamp(computeLighting(texPos, vec4(texture2D(colorTF,\n"
" vec2(scalar.w, 0.0)).xyz, opacity), volume, opacityTF,"
"volIdx, 0), 0.0, 1.0);\n"
"}\n";
}
}
return ss.str();
}
//--------------------------------------------------------------------------
std::string ComputeOpacityMultiDeclaration(vtkOpenGLGPUVolumeRayCastMapper::VolumeInputMap& inputs)
{
std::ostringstream ss;
int i = 0;
for (auto& item : inputs)
{
auto prop = item.second.Volume->GetProperty();
if (prop->GetTransferFunctionMode() != vtkVolumeProperty::TF_1D)
continue;
auto& map = item.second.OpacityTablesMap;
const auto numComp = map.size();
ss << "uniform sampler2D " << ArrayBaseName(map[0]) << "[" << numComp << "];\n";
i++;
}
ss << "float computeOpacity(vec4 scalar, const in sampler2D opacityTF)\n"
"{\n"
" return texture2D(opacityTF, vec2(scalar.w, 0)).r;\n"
"}\n";
return ss.str();
}
//--------------------------------------------------------------------------
std::string ComputeGradientOpacityMulti1DDecl(
vtkOpenGLGPUVolumeRayCastMapper::VolumeInputMap& inputs)
{
std::ostringstream ss;
int i = 0;
for (auto& item : inputs)
{
auto prop = item.second.Volume->GetProperty();
if (prop->GetTransferFunctionMode() != vtkVolumeProperty::TF_1D || !prop->HasGradientOpacity())
continue;
auto& map = item.second.GradientOpacityTablesMap;
const auto numComp = map.size();
ss << "uniform sampler2D " << ArrayBaseName(map[0]) << "[" << numComp << "];\n";
i++;
}
ss << "float computeGradientOpacity(vec4 grad, const in sampler2D gradientTF)\n"
"{\n"
" return texture2D(gradientTF, vec2(grad.w, 0.0)).r;\n"
"}\n";
return ss.str();
}
//--------------------------------------------------------------------------
std::string ComputeOpacityDeclaration(vtkRenderer* vtkNotUsed(ren),
vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol), int noOfComponents,
int independentComponents, std::map<int, std::string> opacityTableMap)
{
std::ostringstream ss;
ss << "uniform sampler2D " << ArrayBaseName(opacityTableMap[0]) << "[" << noOfComponents
<< "];\n";
std::string shaderStr = ss.str();
if (noOfComponents > 1 && independentComponents)
{
shaderStr += std::string("\
\nfloat computeOpacity(vec4 scalar, int component)\
\n{");
for (int i = 0; i < noOfComponents; ++i)
{
std::ostringstream toString;
toString << i;
shaderStr += std::string("\
\n if (component == " +
toString.str() + ")");
shaderStr += std::string("\
\n {\
\n return texture2D(" +
opacityTableMap[i]);
shaderStr += std::string(",vec2(scalar[" + toString.str() + "], 0)).r;\
\n }");
}
shaderStr += std::string("\n}");
return shaderStr;
}
else if (noOfComponents == 2 && !independentComponents)
{
shaderStr += std::string("\
\nfloat computeOpacity(vec4 scalar)\
\n{\
\n return texture2D(" +
opacityTableMap[0] + ", vec2(scalar.y, 0)).r;\
\n}");
return shaderStr;
}
else
{
shaderStr += std::string("\
\nfloat computeOpacity(vec4 scalar)\
\n{\
\n return texture2D(" +
opacityTableMap[0] + ", vec2(scalar.w, 0)).r;\
\n}");
return shaderStr;
}
}
//--------------------------------------------------------------------------
std::string ComputeColor2DYAxisDeclaration(int noOfComponents,
int vtkNotUsed(independentComponents), std::map<int, std::string> colorTableMap)
{
if (noOfComponents == 1)
{
// Single component
return std::string(
"vec4 computeColor(vec4 scalar, float opacity)\n"
"{\n"
" vec4 yscalar = texture3D(in_transfer2DYAxis, g_dataPos);\n"
" yscalar.r = yscalar.r * in_transfer2DYAxis_scale.r + in_transfer2DYAxis_bias.r;\n"
" yscalar = vec4(yscalar.r);\n"
" vec4 color = texture2D(" +
colorTableMap[0] +
",\n"
" vec2(scalar.w, yscalar.w));\n"
" return computeLighting(color, 0, 0);\n"
"}\n");
}
return std::string("vec4 computeColor(vec4 scalar, float opacity)\n"
"{\n"
" return vec4(0, 0, 0, 0)\n"
"}\n");
}
//--------------------------------------------------------------------------
std::string ComputeColor2DDeclaration(vtkRenderer* vtkNotUsed(ren),
vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol), int noOfComponents,
int independentComponents, std::map<int, std::string> colorTableMap, int useGradient)
{
if (!useGradient)
{
return ComputeColor2DYAxisDeclaration(noOfComponents, independentComponents, colorTableMap);
}
if (noOfComponents == 1)
{
// Single component
return std::string("vec4 computeColor(vec4 scalar, float opacity)\n"
"{\n"
" vec4 color = texture2D(" +
colorTableMap[0] +
",\n"
" vec2(scalar.w, g_gradients_0[0].w));\n"
" return computeLighting(color, 0, 0);\n"
"}\n");
}
else if (noOfComponents > 1 && independentComponents)
{
// Multiple independent components
std::string shaderStr;
shaderStr += std::string("vec4 computeColor(vec4 scalar, float opacity, int component)\n"
"{\n");
for (int i = 0; i < noOfComponents; ++i)
{
std::ostringstream toString;
toString << i;
std::string const num = toString.str();
shaderStr += std::string(" if (component == " + num +
")\n"
" {\n"
" vec4 color = texture2D(" +
colorTableMap[i] +
",\n"
" vec2(scalar[" +
num + "], g_gradients_0[" + num +
"].w));\n"
" return computeLighting(color, " +
num +
", 0.0);\n"
" }\n");
}
shaderStr += std::string("}\n");
return shaderStr;
}
else if (noOfComponents == 2 && !independentComponents)
{
// Dependent components (Luminance/ Opacity)
return std::string("vec4 computeColor(vec4 scalar, float opacity)\n"
"{\n"
" vec4 color = texture2D(" +
colorTableMap[0] +
",\n"
" vec2(scalar.x, g_gradients_0[0].w));\n"
" return computeLighting(color, 0, 0.0);\n"
"}\n");
}
else
{
return std::string("vec4 computeColor(vec4 scalar, float opacity)\n"
"{\n"
" return computeLighting(vec4(scalar.xyz, opacity), 0, 0.0);\n"
"}\n");
}
}
//--------------------------------------------------------------------------
std::string Transfer2DDeclaration(vtkOpenGLGPUVolumeRayCastMapper::VolumeInputMap& inputs)
{
std::ostringstream ss;
int i = 0;
for (auto& item : inputs)
{
auto prop = item.second.Volume->GetProperty();
if (prop->GetTransferFunctionMode() != vtkVolumeProperty::TF_2D)
continue;
auto& map = item.second.TransferFunctions2DMap;
const auto numComp = map.size();
ss << "uniform sampler2D " << ArrayBaseName(map[0]) << "[" << numComp << "];\n";
i++;
}
std::string result = ss.str() +
std::string("uniform sampler3D in_transfer2DYAxis;\n"
"uniform vec4 in_transfer2DYAxis_scale;\n"
"uniform vec4 in_transfer2DYAxis_bias;\n");
return result;
}
//--------------------------------------------------------------------------
std::string ComputeOpacity2DDeclaration(vtkRenderer* vtkNotUsed(ren),
vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol), int noOfComponents,
int independentComponents, std::map<int, std::string> opacityTableMap, int useGradient)
{
std::ostringstream toString;
if (noOfComponents > 1 && independentComponents)
{
// Multiple independent components
toString << "float computeOpacity(vec4 scalar, int component)\n"
"{\n";
if (!useGradient)
{
toString
<< "vec4 yscalar = texture3D(in_transfer2DYAxis, g_dataPos);\n"
"for (int i = 0; i < 4; ++i)\n"
"{\n"
" yscalar[i] = yscalar[i] * in_transfer2DYAxis_scale[i] + in_transfer2DYAxis_bias[i];\n"
"}\n";
if (noOfComponents == 1)
{
toString << "yscalar = vec4(yscalar.r);\n";
}
}
for (int i = 0; i < noOfComponents; ++i)
{
if (useGradient)
{
toString << " if (component == " << i
<< ")\n"
" {\n"
" return texture2D("
<< opacityTableMap[i]
<< ",\n"
" vec2(scalar["
<< i << "], g_gradients_0[" << i
<< "].w)).a;\n"
" }\n";
}
else
{
toString << " if (component == " << i
<< ")\n"
" {\n"
" return texture2D("
<< opacityTableMap[i]
<< ",\n"
" vec2(scalar["
<< i << "], yscalar[" << i
<< "])).a;\n"
" }\n";
}
}
toString << "}\n";
}
else if (noOfComponents == 2 && !independentComponents)
{
if (useGradient)
{
// Dependent components (Luminance/ Opacity)
toString << "float computeOpacity(vec4 scalar)\n"
"{\n"
" return texture2D(" +
opacityTableMap[0] +
",\n"
" vec2(scalar.y, g_gradients_0[0].w)).a;\n"
"}\n";
}
else
{
// Dependent components (Luminance/ Opacity)
toString << "float computeOpacity(vec4 scalar)\n"
"{\n"
" return texture2D(" +
opacityTableMap[0] +
",\n"
" vec2(scalar.y, yscalar.y)).a;\n"
"}\n";
}
}
else
{
if (useGradient)
{
// Dependent compoennts (RGBA) || Single component
toString << "float computeOpacity(vec4 scalar)\n"
"{\n"
" return texture2D(" +
opacityTableMap[0] +
",\n"
" vec2(scalar.a, g_gradients_0[0].w)).a;\n"
"}\n";
}
else
{
// Dependent compoennts (RGBA) || Single component
toString
<< "float computeOpacity(vec4 scalar)\n"
"{\n"
" vec4 yscalar = texture3D(in_transfer2DYAxis, g_dataPos);\n"
" yscalar.r = yscalar.r * in_transfer2DYAxis_scale.r + in_transfer2DYAxis_bias.r;\n"
" yscalar = vec4(yscalar.r);\n"
" return texture2D(" +
opacityTableMap[0] +
",\n"
" vec2(scalar.a, yscalar.w)).a;\n"
"}\n";
}
}
return toString.str();
}
//--------------------------------------------------------------------------
std::string ComputeVolumetricShadowDec(vtkOpenGLGPUVolumeRayCastMapper* mapper,
vtkVolume* vtkNotUsed(vol), int noOfComponents, int independentComponents,
vtkOpenGLGPUVolumeRayCastMapper::VolumeInputMap& inputs, int useGradYAxis)
{
std::string resStr;
std::string declarations;
std::string functionSignature;
std::string opacityEval;
std::string rayInit;
const size_t numInputs = inputs.size();
const bool hasGradOp = ::HasGradientOpacity(inputs);
// for now, shadow is mono-chromatic (we only sample opacity)
// it could be RGB
functionSignature = "float volumeShadow(vec3 sample_position, vec3 light_pos_dir, float is_Pos, "
" in int c, in sampler3D volume, " +
(numInputs > 1 ? std::string("in sampler2D opacityTF, ") : std::string()) +
(numInputs > 1 && hasGradOp ? std::string("in sampler2D gradTF, ") : std::string()) +
"int index, float label)\n";
declarations +=
R"***(
float shadow = 1.0;
vec3 direction = vec3(0.0);
vec3 norm_dir = vec3(0.0);
float maxdist = 0.0;
float scalar;
vec4 gradient;
float opacity = 0.0;
vec3 color;
Ray ray;
Hit hit;
float sampled_dist = 0.0;
vec3 sampled_point = vec3(0.0);
)***";
rayInit +=
R"***(
// direction is light_pos_dir when light is directional
// and light_pos_dir - sample_position when positional
direction = light_pos_dir - is_Pos * sample_position;
norm_dir = normalize(direction);
// introduce little offset to avoid sampling shadows at the exact
// sample position
sample_position += g_lengthStep * norm_dir;
direction = light_pos_dir - is_Pos * sample_position;
ray.origin = sample_position;
ray.dir = norm_dir;
safe_0_vector(ray);
ray.invDir = 1.0/ray.dir;
if(!BBoxIntersect(vec3(0.0), vec3(1.0), ray, hit))
{
// it can happen around the bounding box
return 1.0;
}
if(hit.tmax < g_lengthStep)
{
// if we're too close to the bounding box
return 1.0;
}
// in case of directional light, we want direction not to be normalized but to go
// all the way to the bbox
direction *= pow(hit.tmax / length(direction), 1.0 - is_Pos);
maxdist = min(hit.tmax, length(direction));
maxdist = min(in_giReach, maxdist);
if(maxdist < EPSILON) return 1.0;
)***";
// slight imprecision for the last sample : it can be something else (less) than g_lengthStep
// because the last step is clamped to the end of the ray
opacityEval += " scalar = texture3D(volume, sampled_point)[c];\n"
" scalar = scalar * in_volume_scale[index][c] + in_volume_bias[index][c];\n";
opacityEval += ComputeOpacityEvaluationCall(
mapper, inputs, noOfComponents, independentComponents, useGradYAxis, "sampled_point", true);
resStr += functionSignature + "{\n" + declarations + rayInit +
R"***(
float current_dist = 0.0;
float current_step = g_lengthStep;
float clamped_step = 0.0;
while(current_dist < maxdist)
{
clamped_step = min(maxdist - current_dist, current_step);
sampled_dist = current_dist + clamped_step * g_jitterValue;
sampled_point = sample_position + sampled_dist * norm_dir;
)***" +
opacityEval +
R"***(
shadow *= 1.0 - opacity;
current_dist += current_step;
}
return shadow;
}
)***";
return resStr;
}
//--------------------------------------------------------------------------
std::string ShadingDeclarationVertex(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string();
}
//--------------------------------------------------------------------------
std::string ShadingDeclarationFragment(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* mapper, vtkVolume* vtkNotUsed(vol))
{
if (mapper->GetBlendMode() == vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND)
{
return std::string("\
\n bool l_firstValue;\
\n vec4 l_maxValue;");
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::MINIMUM_INTENSITY_BLEND)
{
return std::string("\
\n bool l_firstValue;\
\n vec4 l_minValue;");
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::AVERAGE_INTENSITY_BLEND)
{
return std::string("\
\n uvec4 l_numSamples;\
\n vec4 l_avgValue;");
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::ADDITIVE_BLEND)
{
return std::string("\
\n vec4 l_sumValue;");
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::ISOSURFACE_BLEND)
{
return std::string("\
\n int l_initialIndex = 0;\
\n float l_normValues[NUMBER_OF_CONTOURS + 2];");
}
else
{
return std::string();
}
}
//--------------------------------------------------------------------------
std::string ShadingInit(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* mapper, vtkVolume* vtkNotUsed(vol))
{
if (mapper->GetBlendMode() == vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND)
{
return std::string("\
\n // We get data between 0.0 - 1.0 range\
\n l_firstValue = true;\
\n l_maxValue = vec4(0.0);");
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::MINIMUM_INTENSITY_BLEND)
{
return std::string("\
\n //We get data between 0.0 - 1.0 range\
\n l_firstValue = true;\
\n l_minValue = vec4(1.0);");
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::AVERAGE_INTENSITY_BLEND)
{
return std::string("\
\n //We get data between 0.0 - 1.0 range\
\n l_avgValue = vec4(0.0);\
\n // Keep track of number of samples\
\n l_numSamples = uvec4(0);");
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::ADDITIVE_BLEND)
{
return std::string("\
\n //We get data between 0.0 - 1.0 range\
\n l_sumValue = vec4(0.0);");
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::ISOSURFACE_BLEND)
{
return std::string("\
\n#if NUMBER_OF_CONTOURS\
\n l_normValues[0] = -1e20; //-infinity\
\n l_normValues[NUMBER_OF_CONTOURS+1] = +1e20; //+infinity\
\n for (int i = 0; i < NUMBER_OF_CONTOURS; i++)\
\n {\
\n l_normValues[i+1] = (in_isosurfacesValues[i] - in_scalarsRange[0].x) / \
\n (in_scalarsRange[0].y - in_scalarsRange[0].x);\
\n }\
\n#endif\
");
}
else
{
return std::string();
}
}
//--------------------------------------------------------------------------
std::string GradientCacheDec(vtkRenderer* vtkNotUsed(ren), vtkVolume* vtkNotUsed(vol),
vtkOpenGLGPUVolumeRayCastMapper::VolumeInputMap& inputs, int independentComponents = 0)
{
const int numInputs = static_cast<int>(inputs.size());
const int comp = numInputs == 1 ?
// Dependent components use a single opacity lut.
(!independentComponents ? 1 : numInputs)
:
// Independent components not supported with multiple-inputs
1;
std::ostringstream toShader;
for (const auto& item : inputs)
{
auto& input = item.second;
if (input.Volume->GetProperty()->HasGradientOpacity())
{
toShader << "vec4 " << input.GradientCacheName << "[" << comp << "];\n";
}
}
return toShader.str();
}
//--------------------------------------------------------------------------
std::string PreComputeGradientsImpl(vtkRenderer* vtkNotUsed(ren), vtkVolume* vtkNotUsed(vol),
int noOfComponents = 1, int independentComponents = 0)
{
std::ostringstream shader;
if (independentComponents)
{
if (noOfComponents == 1)
{
shader << "g_gradients_0[0] = computeGradient(g_dataPos, 0, in_volume[0], 0);\n";
}
else
{
// Multiple components
shader << "for (int comp = 0; comp < in_noOfComponents; comp++)\n"
"{\n"
" g_gradients_0[comp] = computeGradient(g_dataPos, comp, in_volume[0], 0);\n"
"}\n";
}
}
else
{
shader << "g_gradients_0[0] = computeGradient(g_dataPos, 0, in_volume[0], 0);\n";
}
return shader.str();
}
//--------------------------------------------------------------------------
std::string ShadingMultipleInputs(
vtkVolumeMapper* mapper, vtkOpenGLGPUVolumeRayCastMapper::VolumeInputMap& inputs)
{
std::ostringstream toShaderStr;
toShaderStr << " if (!g_skip)\n"
" {\n"
" vec3 texPos;\n";
switch (mapper->GetBlendMode())
{
case vtkVolumeMapper::COMPOSITE_BLEND:
default:
{
int i = 0;
for (auto& item : inputs)
{
auto& input = item.second;
auto property = input.Volume->GetProperty();
// Transformation index. Index 0 refers to the global bounding-box.
const auto idx = i + 1;
toShaderStr <<
// From global texture coordinates (bbox) to volume_i texture coords.
// texPos = T * g_dataPos
// T = T_dataToTex1 * T_worldToData * T_bboxTexToWorld;
" texPos = (in_cellToPoint[" << idx << "] * in_inverseTextureDatasetMatrix[" << idx
<< "] * in_inverseVolumeMatrix[" << idx
<< "] *\n"
" in_volumeMatrix[0] * in_textureDatasetMatrix[0] * "
"vec4(g_dataPos.xyz, 1.0)).xyz;\n"
" if ((all(lessThanEqual(texPos, vec3(1.0))) &&\n"
" all(greaterThanEqual(texPos, vec3(0.0)))))\n"
" {\n"
" vec4 scalar = texture3D(in_volume["
<< i
<< "], texPos);\n"
" scalar = scalar * in_volume_scale["
<< i << "] + in_volume_bias[" << i
<< "];\n"
" scalar = vec4(scalar.r);\n"
" g_srcColor = vec4(0.0);\n";
if (property->GetTransferFunctionMode() == vtkVolumeProperty::TF_1D)
{
std::string gradientopacity_param = (property->HasGradientOpacity())
? input.GradientOpacityTablesMap[0] + std::string(", ")
: std::string();
toShaderStr << " g_srcColor.a = computeOpacity(scalar,"
<< input.OpacityTablesMap[0]
<< ");\n"
" if (g_srcColor.a > 0.0)\n"
" {\n"
" g_srcColor = computeColor(texPos, scalar, g_srcColor.a, "
<< input.RGBTablesMap[0] << ", " << gradientopacity_param << "in_volume[" << i
<< "], " << input.OpacityTablesMap[0] << ", " << i << ");\n";
if (property->HasGradientOpacity())
{
const auto& grad = input.GradientCacheName;
toShaderStr << " " << grad << "[0] = computeGradient(texPos, 0, "
<< "in_volume[" << i << "], " << i
<< ");\n"
" if ("
<< grad
<< "[0].w >= 0.0)\n"
" {\n"
" g_srcColor.a *= computeGradientOpacity("
<< grad << "[0], " << input.GradientOpacityTablesMap[0]
<< ");\n"
" }\n";
}
}
else if (property->GetTransferFunctionMode() == vtkVolumeProperty::TF_2D)
{
const auto& grad = input.GradientCacheName;
toShaderStr <<
// Sample 2DTF directly
" " << grad << "[0] = computeGradient(texPos, 0, "
<< "in_volume[" << i << "], " << i
<< ");\n"
" g_srcColor = texture2D("
<< input.TransferFunctions2DMap[0] << ", vec2(scalar.r, "
<< input.GradientCacheName
<< "[0].w));\n"
" if (g_srcColor.a > 0.0)\n"
" {\n";
}
toShaderStr
<< " g_srcColor.rgb *= g_srcColor.a;\n"
" g_fragColor = (1.0f - g_fragColor.a) * g_srcColor + g_fragColor;\n"
" }\n"
" }\n\n";
i++;
}
}
break;
}
toShaderStr << " }\n";
return toShaderStr.str();
}
//--------------------------------------------------------------------------
std::string ShadingSingleInput(vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* mapper,
vtkVolume* vtkNotUsed(vol), vtkImageData* maskInput, vtkVolumeTexture* mask, int maskType,
int noOfComponents, int independentComponents = 0)
{
auto glMapper = vtkOpenGLGPUVolumeRayCastMapper::SafeDownCast(mapper);
std::string shaderStr;
shaderStr += std::string("\
\n if (!g_skip)\
\n {\
\n vec4 scalar;\
\n");
if (vtkRectilinearGrid::SafeDownCast(mapper->GetInput()))
{
shaderStr += std::string("\
\n // Compute IJK vertex position for current sample in the rectilinear grid\
\n vec4 dataPosWorld = in_volumeMatrix[0] * in_textureDatasetMatrix[0] * vec4(g_dataPos, 1.0);\
\n dataPosWorld = dataPosWorld / dataPosWorld.w;\
\n dataPosWorld.w = 1.0;\
\n ivec3 ijk = ivec3(0);\
\n vec3 ijkTexCoord = vec3(0.0);\
\n vec3 pCoords = vec3(0.0);\
\n vec3 xPrev, xNext, tmp;\
\n int sz = textureSize(in_coordTexs, 0);\
\n vec4 dataPosWorldScaled = dataPosWorld * vec4(in_coordsScale, 1.0) +\
\n vec4(in_coordsBias, 1.0);\
\n for (int j = 0; j < 3; ++j)\
\n {\
\n xPrev = texture1D(in_coordTexs, 0.0).xyz;\
\n xNext = texture1D(in_coordTexs, (in_coordTexSizes[j] - 1) / sz).xyz;\
\n if (xNext[j] < xPrev[j])\
\n {\
\n tmp = xNext;\
\n xNext = xPrev;\
\n xPrev = tmp;\
\n }\
\n for (int i = 0; i < int(in_coordTexSizes[j]); i++)\
\n {\
\n xNext = texture1D(in_coordTexs, (i + 0.5) / sz).xyz;\
\n if (dataPosWorldScaled[j] >= xPrev[j] && dataPosWorldScaled[j] < xNext[j])\
\n {\
\n ijk[j] = i - 1;\
\n pCoords[j] = (dataPosWorldScaled[j] - xPrev[j]) / (xNext[j] - xPrev[j]);\
\n break;\
\n }\
\n else if (dataPosWorldScaled[j] == xNext[j])\
\n {\
\n ijk[j] = i - 1;\
\n pCoords[j] = 1.0;\
\n break;\
\n }\
\n xPrev = xNext;\
\n }\
\n ijkTexCoord[j] = (ijk[j] + pCoords[j]) / in_coordTexSizes[j];\
\n }\
\n scalar = texture3D(in_volume[0], sign(in_cellSpacing[0]) * ijkTexCoord);\
\n");
}
else
{
shaderStr += std::string("\
\n scalar = texture3D(in_volume[0], g_dataPos);\
\n");
}
// simulate old intensity textures
if (noOfComponents == 1)
{
shaderStr += std::string("\
\n scalar.r = scalar.r * in_volume_scale[0].r + in_volume_bias[0].r;\
\n scalar = vec4(scalar.r);");
}
else
{
// handle bias and scale
shaderStr += std::string("\
\n scalar = scalar * in_volume_scale[0] + in_volume_bias[0];");
}
if (mapper->GetBlendMode() == vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND)
{
if (noOfComponents > 1)
{
if (!independentComponents)
{
shaderStr += std::string("\
\n if (l_maxValue.w < scalar.w || l_firstValue)\
\n {\
\n l_maxValue = scalar;\
\n }\
\n\
\n if (l_firstValue)\
\n {\
\n l_firstValue = false;\
\n }");
}
else
{
shaderStr += std::string("\
\n for (int i = 0; i < in_noOfComponents; ++i)\
\n {\
\n if (l_maxValue[i] < scalar[i] || l_firstValue)\
\n {\
\n l_maxValue[i] = scalar[i];\
\n }\
\n }\
\n if (l_firstValue)\
\n {\
\n l_firstValue = false;\
\n }");
}
}
else
{
shaderStr += std::string("\
\n if (l_maxValue.w < scalar.x || l_firstValue)\
\n {\
\n l_maxValue.w = scalar.x;\
\n }\
\n\
\n if (l_firstValue)\
\n {\
\n l_firstValue = false;\
\n }");
}
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::MINIMUM_INTENSITY_BLEND)
{
if (noOfComponents > 1)
{
if (!independentComponents)
{
shaderStr += std::string("\
\n if (l_minValue.w > scalar.w || l_firstValue)\
\n {\
\n l_minValue = scalar;\
\n }\
\n\
\n if (l_firstValue)\
\n {\
\n l_firstValue = false;\
\n }");
}
else
{
shaderStr += std::string("\
\n for (int i = 0; i < in_noOfComponents; ++i)\
\n {\
\n if (l_minValue[i] < scalar[i] || l_firstValue)\
\n {\
\n l_minValue[i] = scalar[i];\
\n }\
\n }\
\n if (l_firstValue)\
\n {\
\n l_firstValue = false;\
\n }");
}
}
else
{
shaderStr += std::string("\
\n if (l_minValue.w > scalar.x || l_firstValue)\
\n {\
\n l_minValue.w = scalar.x;\
\n }\
\n\
\n if (l_firstValue)\
\n {\
\n l_firstValue = false;\
\n }");
}
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::AVERAGE_INTENSITY_BLEND)
{
if (noOfComponents > 1 && independentComponents)
{
shaderStr += std::string("\
\n for (int i = 0; i < in_noOfComponents; ++i)\
\n {\
\n // Get the intensity in volume scalar range\
\n float intensity = in_scalarsRange[i][0] +\
\n (in_scalarsRange[i][1] -\
\n in_scalarsRange[i][0]) * scalar[i];\
\n if (in_averageIPRange.x <= intensity &&\
\n intensity <= in_averageIPRange.y)\
\n {\
\n l_avgValue[i] += computeOpacity(scalar, i) * scalar[i];\
\n ++l_numSamples[i];\
\n }\
\n }");
}
else
{
shaderStr += std::string("\
\n // Get the intensity in volume scalar range\
\n float intensity = in_scalarsRange[0][0] +\
\n (in_scalarsRange[0][1] -\
\n in_scalarsRange[0][0]) * scalar.x;\
\n if (in_averageIPRange.x <= intensity &&\
\n intensity <= in_averageIPRange.y)\
\n {\
\n l_avgValue.x += computeOpacity(scalar) * scalar.x;\
\n ++l_numSamples.x;\
\n }");
}
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::ADDITIVE_BLEND)
{
if (noOfComponents > 1 && independentComponents)
{
shaderStr += std::string("\
\n for (int i = 0; i < in_noOfComponents; ++i)\
\n {\
\n float opacity = computeOpacity(scalar, i);\
\n l_sumValue[i] = l_sumValue[i] + opacity * scalar[i];\
\n }");
}
else
{
shaderStr += std::string("\
\n float opacity = computeOpacity(scalar);\
\n l_sumValue.x = l_sumValue.x + opacity * scalar.x;");
}
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::ISOSURFACE_BLEND)
{
shaderStr += std::string("\
\n#if NUMBER_OF_CONTOURS\
\n int maxComp = 0;");
std::string compParamStr = "";
if (noOfComponents > 1 && independentComponents)
{
shaderStr += std::string("\
\n for (int i = 1; i < in_noOfComponents; ++i)\
\n {\
\n if (in_componentWeight[i] > in_componentWeight[maxComp])\
\n maxComp = i;\
\n }");
compParamStr = ", maxComp";
}
shaderStr += std::string("\
\n if (g_currentT == 0)\
\n {\
\n l_initialIndex = findIsoSurfaceIndex(scalar[maxComp], l_normValues);\
\n }\
\n else\
\n {\
\n float s;\
\n bool shade = false;\
\n l_initialIndex = clamp(l_initialIndex, 0, NUMBER_OF_CONTOURS);\
\n if (scalar[maxComp] < l_normValues[l_initialIndex])\
\n {\
\n s = l_normValues[l_initialIndex];\
\n l_initialIndex--;\
\n shade = true;\
\n }\
\n if (scalar[maxComp] > l_normValues[l_initialIndex+1])\
\n {\
\n s = l_normValues[l_initialIndex+1];\
\n l_initialIndex++;\
\n shade = true;\
\n }\
\n if (shade == true)\
\n {\
\n vec4 vs = vec4(s);\
\n g_srcColor.a = computeOpacity(vs " +
compParamStr + ");\
\n g_srcColor = computeColor(vs, g_srcColor.a " +
compParamStr + ");\
\n g_srcColor.rgb *= g_srcColor.a;\
\n g_fragColor = (1.0f - g_fragColor.a) * g_srcColor + g_fragColor;\
\n }\
\n }\
\n#endif");
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::SLICE_BLEND)
{
shaderStr += std::string("\
\n // test if the intersection is inside the volume bounds\
\n if (any(greaterThan(g_dataPos, vec3(1.0))) || any(lessThan(g_dataPos, vec3(0.0))))\
\n {\
\n discard;\
\n }\
\n float opacity = computeOpacity(scalar);\
\n g_fragColor = computeColor(scalar, opacity);\
\n g_fragColor.rgb *= opacity;\
\n g_exit = true;");
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::COMPOSITE_BLEND)
{
if (noOfComponents > 1 && independentComponents)
{
shaderStr += std::string("\
\n vec4 color[4]; vec4 tmp = vec4(0.0);\
\n float totalAlpha = 0.0;\
\n for (int i = 0; i < in_noOfComponents; ++i)\
\n {\
");
if (glMapper->GetUseDepthPass() &&
glMapper->GetCurrentPass() == vtkOpenGLGPUVolumeRayCastMapper::DepthPass)
{
shaderStr += std::string("\
\n // Data fetching from the red channel of volume texture\
\n float opacity = computeOpacity(scalar, i);\
\n if (opacity > 0.0)\
\n {\
\n g_srcColor.a = opacity;\
\n }\
\n }");
}
else if (!mask || !maskInput || maskType != vtkGPUVolumeRayCastMapper::LabelMapMaskType)
{
shaderStr += std::string("\
\n // Data fetching from the red channel of volume texture\
\n color[i][3] = computeOpacity(scalar, i);\
\n color[i] = computeColor(scalar, color[i][3], i);\
\n totalAlpha += color[i][3] * in_componentWeight[i];\
\n }\
\n if (totalAlpha > 0.0)\
\n {\
\n for (int i = 0; i < in_noOfComponents; ++i)\
\n {\
\n // Only let visible components contribute to the final color\
\n if (in_componentWeight[i] <= 0) continue;\
\n\
\n tmp.x += color[i].x * color[i].w * in_componentWeight[i];\
\n tmp.y += color[i].y * color[i].w * in_componentWeight[i];\
\n tmp.z += color[i].z * color[i].w * in_componentWeight[i];\
\n tmp.w += ((color[i].w * color[i].w)/totalAlpha);\
\n }\
\n }\
\n g_fragColor = (1.0f - g_fragColor.a) * tmp + g_fragColor;");
}
}
else if (glMapper->GetUseDepthPass() &&
glMapper->GetCurrentPass() == vtkOpenGLGPUVolumeRayCastMapper::DepthPass)
{
shaderStr += std::string("\
\n g_srcColor = vec4(0.0);\
\n g_srcColor.a = computeOpacity(scalar);");
}
else
{
if (!mask || !maskInput || maskType != vtkGPUVolumeRayCastMapper::LabelMapMaskType)
{
shaderStr += std::string("\
\n g_srcColor = vec4(0.0);\
\n g_srcColor.a = computeOpacity(scalar);\
\n if (g_srcColor.a > 0.0)\
\n {\
\n g_srcColor = computeColor(scalar, g_srcColor.a);");
}
shaderStr += std::string("\
\n // Opacity calculation using compositing:\
\n // Here we use front to back compositing scheme whereby\
\n // the current sample value is multiplied to the\
\n // currently accumulated alpha and then this product\
\n // is subtracted from the sample value to get the\
\n // alpha from the previous steps. Next, this alpha is\
\n // multiplied with the current sample colour\
\n // and accumulated to the composited colour. The alpha\
\n // value from the previous steps is then accumulated\
\n // to the composited colour alpha.\
\n g_srcColor.rgb *= g_srcColor.a;\
\n g_fragColor = (1.0f - g_fragColor.a) * g_srcColor + g_fragColor;");
if (!mask || !maskInput || maskType != vtkGPUVolumeRayCastMapper::LabelMapMaskType)
{
shaderStr += std::string("\
\n }");
}
}
}
else
{
shaderStr += std::string();
}
shaderStr += std::string("\
\n }");
return shaderStr;
}
//--------------------------------------------------------------------------
std::string PickingActorPassExit(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string("\
\n // Special coloring mode which renders the Prop Id in fragments that\
\n // have accumulated certain level of opacity. Used during the selection\
\n // pass vtkHardwareSelection::ACTOR_PASS.\
\n if (g_fragColor.a > 3.0/ 255.0)\
\n {\
\n gl_FragData[0] = vec4(in_propId, 1.0);\
\n }\
\n else\
\n {\
\n gl_FragData[0] = vec4(0.0);\
\n }\
\n return;");
};
//--------------------------------------------------------------------------
std::string PickingIdLow24PassExit(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string("\
\n // Special coloring mode which renders the voxel index in fragments that\
\n // have accumulated certain level of opacity. Used during the selection\
\n // pass vtkHardwareSelection::ID_LOW24.\
\n if (g_fragColor.a > 3.0/ 255.0)\
\n {\
\n uvec3 volumeDim = uvec3(in_textureExtentsMax - in_textureExtentsMin);\
\n uvec3 voxelCoords = uvec3(volumeDim * g_dataPos);\
\n // vtkHardwareSelector assumes index 0 to be empty space, so add uint(1).\
\n uint idx = volumeDim.x * volumeDim.y * voxelCoords.z +\
\n volumeDim.x * voxelCoords.y + voxelCoords.x + uint(1);\
\n gl_FragData[0] = vec4(float(idx % uint(256)) / 255.0,\
\n float((idx / uint(256)) % uint(256)) / 255.0,\
\n float((idx / uint(65536)) % uint(256)) / 255.0, 1.0);\
\n }\
\n else\
\n {\
\n gl_FragData[0] = vec4(0.0);\
\n }\
\n return;");
};
//--------------------------------------------------------------------------
std::string PickingIdHigh24PassExit(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string("\
\n // Special coloring mode which renders the voxel index in fragments that\
\n // have accumulated certain level of opacity. Used during the selection\
\n // pass vtkHardwareSelection::ID_MID24.\
\n if (g_fragColor.a > 3.0/ 255.0)\
\n {\
\n uvec3 volumeDim = uvec3(in_textureExtentsMax - in_textureExtentsMin);\
\n uvec3 voxelCoords = uvec3(volumeDim * g_dataPos);\
\n // vtkHardwareSelector assumes index 0 to be empty space, so add uint(1).\
\n uint idx = volumeDim.x * volumeDim.y * voxelCoords.z +\
\n volumeDim.x * voxelCoords.y + voxelCoords.x + uint(1);\
\n idx = ((idx & 0xff000000) >> 24);\
\n gl_FragData[0] = vec4(float(idx % uint(256)) / 255.0,\
\n float((idx / uint(256)) % uint(256)) / 255.0,\
\n float(idx / uint(65536)) / 255.0, 1.0);\
\n }\
\n else\
\n {\
\n gl_FragData[0] = vec4(0.0);\
\n }\
\n return;");
};
//--------------------------------------------------------------------------
std::string ShadingExit(vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* mapper,
vtkVolume* vtkNotUsed(vol), int noOfComponents, int independentComponents = 0)
{
vtkOpenGLGPUVolumeRayCastMapper* glMapper = vtkOpenGLGPUVolumeRayCastMapper::SafeDownCast(mapper);
if (glMapper->GetUseDepthPass() &&
glMapper->GetCurrentPass() == vtkOpenGLGPUVolumeRayCastMapper::DepthPass &&
mapper->GetBlendMode() == vtkVolumeMapper::COMPOSITE_BLEND)
{
return std::string();
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND)
{
if (noOfComponents > 1 && independentComponents)
{
return std::string("\
\n g_srcColor = vec4(0);\
\n for (int i = 0; i < in_noOfComponents; ++i)\
\n {\
\n vec4 tmp = computeColor(l_maxValue, computeOpacity(l_maxValue, i), i);\
\n g_srcColor[0] += tmp[0] * tmp[3] * in_componentWeight[i];\
\n g_srcColor[1] += tmp[1] * tmp[3] * in_componentWeight[i];\
\n g_srcColor[2] += tmp[2] * tmp[3] * in_componentWeight[i];\
\n g_srcColor[3] += tmp[3] * in_componentWeight[i];\
\n }\
\n g_fragColor = g_srcColor;");
}
else
{
return std::string("\
\n g_srcColor = computeColor(l_maxValue,\
\n computeOpacity(l_maxValue));\
\n g_fragColor.rgb = g_srcColor.rgb * g_srcColor.a;\
\n g_fragColor.a = g_srcColor.a;");
}
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::MINIMUM_INTENSITY_BLEND)
{
if (noOfComponents > 1 && independentComponents)
{
return std::string("\
\n g_srcColor = vec4(0);\
\n for (int i = 0; i < in_noOfComponents; ++i)\
\n {\
\n vec4 tmp = computeColor(l_minValue, computeOpacity(l_minValue, i), i);\
\n g_srcColor[0] += tmp[0] * tmp[3] * in_componentWeight[i];\
\n g_srcColor[1] += tmp[1] * tmp[3] * in_componentWeight[i];\
\n g_srcColor[2] += tmp[2] * tmp[3] * in_componentWeight[i];\
\n g_srcColor[2] += tmp[3] * tmp[3] * in_componentWeight[i];\
\n }\
\n g_fragColor = g_srcColor;");
}
else
{
return std::string("\
\n g_srcColor = computeColor(l_minValue,\
\n computeOpacity(l_minValue));\
\n g_fragColor.rgb = g_srcColor.rgb * g_srcColor.a;\
\n g_fragColor.a = g_srcColor.a;");
}
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::AVERAGE_INTENSITY_BLEND)
{
if (noOfComponents > 1 && independentComponents)
{
return std::string("\
\n for (int i = 0; i < in_noOfComponents; ++i)\
\n {\
\n if (l_numSamples[i] == uint(0))\
\n {\
\n continue;\
\n }\
\n l_avgValue[i] = l_avgValue[i] * in_componentWeight[i] /\
\n l_numSamples[i];\
\n if (i > 0)\
\n {\
\n l_avgValue[0] += l_avgValue[i];\
\n }\
\n }\
\n l_avgValue[0] = clamp(l_avgValue[0], 0.0, 1.0);\
\n g_fragColor = vec4(vec3(l_avgValue[0]), 1.0);");
}
else
{
return std::string("\
\n if (l_numSamples.x == uint(0))\
\n {\
\n discard;\
\n }\
\n else\
\n {\
\n l_avgValue.x /= l_numSamples.x;\
\n l_avgValue.x = clamp(l_avgValue.x, 0.0, 1.0);\
\n g_fragColor = vec4(vec3(l_avgValue.x), 1.0);\
\n }");
}
}
else if (mapper->GetBlendMode() == vtkVolumeMapper::ADDITIVE_BLEND)
{
if (noOfComponents > 1 && independentComponents)
{
// Add all the components to get final color
return std::string("\
\n l_sumValue.x *= in_componentWeight.x;\
\n for (int i = 1; i < in_noOfComponents; ++i)\
\n {\
\n l_sumValue.x += l_sumValue[i] * in_componentWeight[i];\
\n }\
\n l_sumValue.x = clamp(l_sumValue.x, 0.0, 1.0);\
\n g_fragColor = vec4(vec3(l_sumValue.x), 1.0);");
}
else
{
return std::string("\
\n l_sumValue.x = clamp(l_sumValue.x, 0.0, 1.0);\
\n g_fragColor = vec4(vec3(l_sumValue.x), 1.0);");
}
}
else
{
return std::string();
}
}
//--------------------------------------------------------------------------
std::string TerminationDeclarationVertex(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string();
}
//--------------------------------------------------------------------------
std::string TerminationDeclarationFragment(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string("\
\n const float g_opacityThreshold = 1.0 - 1.0 / 255.0;");
}
//--------------------------------------------------------------------------
std::string PickingActorPassDeclaration(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string("\
\n uniform vec3 in_propId;");
};
//--------------------------------------------------------------------------
std::string TerminationInit(vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* mapper, vtkVolume* vol)
{
std::string shaderStr;
shaderStr += std::string("\
\n // Flag to indicate if the raymarch loop should terminate \
\n bool stop = false;\
\n\
\n g_terminatePointMax = 0.0;\
\n\
\n vec4 l_depthValue = texture2D(in_depthSampler, fragTexCoord);\
\n // Depth test\
\n if(gl_FragCoord.z >= l_depthValue.x)\
\n {\
\n discard;\
\n }\
\n\
\n // color buffer or max scalar buffer have a reduced size.\
\n fragTexCoord = (gl_FragCoord.xy - in_windowLowerLeftCorner) *\
\n in_inverseOriginalWindowSize;\
\n");
if (mapper->GetBlendMode() == vtkVolumeMapper::SLICE_BLEND)
{
vtkImplicitFunction* sliceFunc = vol->GetProperty()->GetSliceFunction();
if (sliceFunc)
{
if (sliceFunc->IsA("vtkPlane"))
{
shaderStr += std::string("\
\n\
\n // Intersection with plane\
\n float t = intersectRayPlane(ip_vertexPos, rayDir);\
\n vec4 intersection = vec4(ip_vertexPos + t * rayDir, 1.0);\
\n g_intersection = (in_inverseTextureDatasetMatrix[0] * intersection).xyz;\
\n vec4 intersDC = in_projectionMatrix * in_modelViewMatrix * in_volumeMatrix[0] * intersection;\
\n intersDC.xyz /= intersDC.w;\
\n vec4 intersWin = NDCToWindow(intersDC.x, intersDC.y, intersDC.z);\
\n if(intersWin.z >= l_depthValue.x)\
\n {\
\n discard;\
\n }\
\n");
}
else
{
vtkErrorWithObjectMacro(
sliceFunc, "Implicit function type is not supported by this mapper.");
}
}
}
shaderStr += std::string("\
\n // Compute max number of iterations it will take before we hit\
\n // the termination point\
\n\
\n // Abscissa of the point on the depth buffer along the ray.\
\n // point in texture coordinates\
\n vec4 rayTermination = WindowToNDC(gl_FragCoord.x, gl_FragCoord.y, l_depthValue.x);\
\n\
\n // From normalized device coordinates to eye coordinates.\
\n // in_projectionMatrix is inversed because of way VT\
\n // From eye coordinates to texture coordinates\
\n rayTermination = ip_inverseTextureDataAdjusted *\
\n in_inverseVolumeMatrix[0] *\
\n in_inverseModelViewMatrix *\
\n in_inverseProjectionMatrix *\
\n rayTermination;\
\n g_rayTermination = rayTermination.xyz / rayTermination.w;\
\n\
\n // Setup the current segment:\
\n g_dataPos = g_rayOrigin;\
\n g_terminatePos = g_rayTermination;\
\n\
\n g_terminatePointMax = length(g_terminatePos.xyz - g_dataPos.xyz) /\
\n length(g_dirStep);\
\n g_currentT = 0.0;");
return shaderStr;
}
//--------------------------------------------------------------------------
std::string TerminationImplementation(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string("\
\n if(any(greaterThan(max(g_dirStep, vec3(0.0))*(g_dataPos - in_texMax[0]),vec3(0.0))) ||\
\n any(greaterThan(min(g_dirStep, vec3(0.0))*(g_dataPos - in_texMin[0]),vec3(0.0))))\
\n {\
\n break;\
\n }\
\n\
\n // Early ray termination\
\n // if the currently composited colour alpha is already fully saturated\
\n // we terminated the loop or if we have hit an obstacle in the\
\n // direction of they ray (using depth buffer) we terminate as well.\
\n if((g_fragColor.a > g_opacityThreshold) || \
\n g_currentT >= g_terminatePointMax)\
\n {\
\n break;\
\n }\
\n ++g_currentT;");
}
//--------------------------------------------------------------------------
std::string TerminationExit(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string();
}
//--------------------------------------------------------------------------
std::string CroppingDeclarationVertex(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string();
}
//--------------------------------------------------------------------------
std::string CroppingDeclarationFragment(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* mapper, vtkVolume* vtkNotUsed(vol))
{
if (!mapper->GetCropping())
{
return std::string();
}
return std::string("\
\nuniform float in_croppingPlanes[6];\
\nuniform int in_croppingFlags [32];\
\nfloat croppingPlanesTexture[6];\
\n\
\n// X: axis = 0, Y: axis = 1, Z: axis = 2\
\n// cp Cropping plane bounds (minX, maxX, minY, maxY, minZ, maxZ)\
\nint computeRegionCoord(float cp[6], vec3 pos, int axis)\
\n {\
\n int cpmin = axis * 2;\
\n int cpmax = cpmin + 1;\
\n\
\n if (pos[axis] < cp[cpmin])\
\n {\
\n return 1;\
\n }\
\n else if (pos[axis] >= cp[cpmin] &&\
\n pos[axis] < cp[cpmax])\
\n {\
\n return 2;\
\n }\
\n else if (pos[axis] >= cp[cpmax])\
\n {\
\n return 3;\
\n }\
\n return 0;\
\n }\
\n\
\nint computeRegion(float cp[6], vec3 pos)\
\n {\
\n return (computeRegionCoord(cp, pos, 0) +\
\n (computeRegionCoord(cp, pos, 1) - 1) * 3 +\
\n (computeRegionCoord(cp, pos, 2) - 1) * 9);\
\n }");
}
//--------------------------------------------------------------------------
std::string CroppingInit(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* mapper, vtkVolume* vtkNotUsed(vol))
{
if (!mapper->GetCropping())
{
return std::string();
}
return std::string("\
\n // Convert cropping region to texture space\
\n mat4 datasetToTextureMat = in_inverseTextureDatasetMatrix[0];\
\n\
\n vec4 tempCrop = vec4(in_croppingPlanes[0], 0.0, 0.0, 1.0);\
\n tempCrop = datasetToTextureMat * tempCrop;\
\n if (tempCrop[3] != 0.0)\
\n {\
\n tempCrop[0] /= tempCrop[3];\
\n }\
\n croppingPlanesTexture[0] = tempCrop[0];\
\n\
\n tempCrop = vec4(in_croppingPlanes[1], 0.0, 0.0, 1.0);\
\n tempCrop = datasetToTextureMat * tempCrop;\
\n if (tempCrop[3] != 0.0)\
\n {\
\n tempCrop[0] /= tempCrop[3];\
\n }\
\n croppingPlanesTexture[1] = tempCrop[0];\
\n\
\n tempCrop = vec4(0.0, in_croppingPlanes[2], 0.0, 1.0);\
\n tempCrop = datasetToTextureMat * tempCrop;\
\n if (tempCrop[3] != 0.0)\
\n {\
\n tempCrop[1] /= tempCrop[3];\
\n }\
\n croppingPlanesTexture[2] = tempCrop[1];\
\n\
\n tempCrop = vec4(0.0, in_croppingPlanes[3], 0.0, 1.0);\
\n tempCrop = datasetToTextureMat * tempCrop;\
\n if (tempCrop[3] != 0.0)\
\n {\
\n tempCrop[1] /= tempCrop[3];\
\n }\
\n croppingPlanesTexture[3] = tempCrop[1];\
\n\
\n tempCrop = vec4(0.0, 0.0, in_croppingPlanes[4], 1.0);\
\n tempCrop = datasetToTextureMat * tempCrop;\
\n if (tempCrop[3] != 0.0)\
\n {\
\n tempCrop[2] /= tempCrop[3];\
\n }\
\n croppingPlanesTexture[4] = tempCrop[2];\
\n\
\n tempCrop = vec4(0.0, 0.0, in_croppingPlanes[5], 1.0);\
\n tempCrop = datasetToTextureMat * tempCrop;\
\n if (tempCrop[3] != 0.0)\
\n {\
\n tempCrop[2] /= tempCrop[3];\
\n }\
\n croppingPlanesTexture[5] = tempCrop[2];");
}
//--------------------------------------------------------------------------
std::string CroppingImplementation(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* mapper, vtkVolume* vtkNotUsed(vol))
{
if (!mapper->GetCropping())
{
return std::string();
}
return std::string("\
\n // Determine region\
\n int regionNo = computeRegion(croppingPlanesTexture, g_dataPos);\
\n\
\n // Do & operation with cropping flags\
\n // Pass the flag that its Ok to sample or not to sample\
\n if (in_croppingFlags[regionNo] == 0)\
\n {\
\n // Skip this voxel\
\n g_skip = true;\
\n }");
}
//--------------------------------------------------------------------------
std::string CroppingExit(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string();
}
//--------------------------------------------------------------------------
std::string ClippingDeclarationVertex(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string();
}
//--------------------------------------------------------------------------
std::string ClippingDeclarationFragment(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* mapper, vtkVolume* vtkNotUsed(vol))
{
if (!mapper->GetClippingPlanes())
{
return std::string();
}
return std::string("\
\n /// We support only 8 clipping planes for now\
\n /// The first value is the size of the data array for clipping\
\n /// planes (origin, normal)\
\n uniform float in_clippingPlanes[49];\
\n uniform float in_clippedVoxelIntensity;\
\n\
\n int clip_numPlanes;\
\n vec3 clip_rayDirObj;\
\n mat4 clip_texToObjMat;\
\n mat4 clip_objToTexMat;\
\n\
\n// Tighten the sample range as needed to account for clip planes. \
\n// Arguments are in texture coordinates. \
\n// Returns true if the range is at all valid after clipping. If not, \
\n// the fragment should be discarded. \
\nbool AdjustSampleRangeForClipping(inout vec3 startPosTex, inout vec3 stopPosTex) \
\n{ \
\n vec4 startPosObj = vec4(0.0);\
\n {\
\n startPosObj = clip_texToObjMat * vec4(startPosTex - g_rayJitter, 1.0);\
\n startPosObj = startPosObj / startPosObj.w;\
\n startPosObj.w = 1.0;\
\n }\
\n\
\n vec4 stopPosObj = vec4(0.0);\
\n {\
\n stopPosObj = clip_texToObjMat * vec4(stopPosTex, 1.0);\
\n stopPosObj = stopPosObj / stopPosObj.w;\
\n stopPosObj.w = 1.0;\
\n }\
\n\
\n for (int i = 0; i < clip_numPlanes; i = i + 6)\
\n {\
\n vec3 planeOrigin = vec3(in_clippingPlanes[i + 1],\
\n in_clippingPlanes[i + 2],\
\n in_clippingPlanes[i + 3]);\
\n vec3 planeNormal = normalize(vec3(in_clippingPlanes[i + 4],\
\n in_clippingPlanes[i + 5],\
\n in_clippingPlanes[i + 6]));\
\n\
\n // Abort if the entire segment is clipped:\
\n // (We can do this before adjusting the term point, since it'll \
\n // only move further into the clipped area)\
\n float startDistance = dot(planeNormal, planeOrigin - startPosObj.xyz);\
\n float stopDistance = dot(planeNormal, planeOrigin - stopPosObj.xyz);\
\n bool startClipped = startDistance > 0.0;\
\n bool stopClipped = stopDistance > 0.0;\
\n if (startClipped && stopClipped)\
\n {\
\n return false;\
\n }\
\n\
\n float rayDotNormal = dot(clip_rayDirObj, planeNormal);\
\n bool frontFace = rayDotNormal > 0.0;\
\n\
\n // Move the start position further from the eye if needed:\
\n if (frontFace && // Observing from the clipped side (plane's front face)\
\n startDistance > 0.0) // Ray-entry lies on the clipped side.\
\n {\
\n // Scale the point-plane distance to the ray direction and update the\
\n // entry point.\
\n float rayScaledDist = startDistance / rayDotNormal;\
\n startPosObj = vec4(startPosObj.xyz + rayScaledDist * clip_rayDirObj, 1.0);\
\n vec4 newStartPosTex = clip_objToTexMat * vec4(startPosObj.xyz, 1.0);\
\n newStartPosTex /= newStartPosTex.w;\
\n startPosTex = newStartPosTex.xyz;\
\n startPosTex += g_rayJitter;\
\n }\
\n\
\n // Move the end position closer to the eye if needed:\
\n if (!frontFace && // Observing from the unclipped side (plane's back face)\
\n stopDistance > 0.0) // Ray-entry lies on the unclipped side.\
\n {\
\n // Scale the point-plane distance to the ray direction and update the\
\n // termination point.\
\n float rayScaledDist = stopDistance / rayDotNormal;\
\n stopPosObj = vec4(stopPosObj.xyz + rayScaledDist * clip_rayDirObj, 1.0);\
\n vec4 newStopPosTex = clip_objToTexMat * vec4(stopPosObj.xyz, 1.0);\
\n newStopPosTex /= newStopPosTex.w;\
\n stopPosTex = newStopPosTex.xyz;\
\n }\
\n }\
\n\
\n if (any(greaterThan(startPosTex, in_texMax[0])) ||\
\n any(lessThan(startPosTex, in_texMin[0])))\
\n {\
\n return false;\
\n }\
\n\
\n return true;\
\n}\
\n");
}
//--------------------------------------------------------------------------
std::string ClippingInit(vtkRenderer* ren, vtkVolumeMapper* mapper, vtkVolume* vtkNotUsed(vol))
{
if (!mapper->GetClippingPlanes())
{
return std::string();
}
std::string shaderStr;
if (!ren->GetActiveCamera()->GetParallelProjection())
{
shaderStr = std::string("\
\n vec4 tempClip = in_volumeMatrix[0] * vec4(rayDir, 0.0);\
\n if (tempClip.w != 0.0)\
\n {\
\n tempClip = tempClip/tempClip.w;\
\n tempClip.w = 1.0;\
\n }\
\n clip_rayDirObj = normalize(tempClip.xyz);");
}
else
{
shaderStr = std::string("\
clip_rayDirObj = normalize(in_projectionDirection);");
}
shaderStr += std::string("\
\n clip_numPlanes = int(in_clippingPlanes[0]);\
\n clip_texToObjMat = in_volumeMatrix[0] * in_textureDatasetMatrix[0];\
\n clip_objToTexMat = in_inverseTextureDatasetMatrix[0] * in_inverseVolumeMatrix[0];\
\n\
\n // Adjust for clipping.\
\n if (!AdjustSampleRangeForClipping(g_rayOrigin, g_rayTermination))\
\n { // entire ray is clipped.\
\n discard;\
\n }\
\n\
\n // Update the segment post-clip:\
\n g_dataPos = g_rayOrigin;\
\n g_terminatePos = g_rayTermination;\
\n g_terminatePointMax = length(g_terminatePos.xyz - g_dataPos.xyz) /\
\n length(g_dirStep);\
\n");
return shaderStr;
}
//--------------------------------------------------------------------------
std::string ClippingImplementation(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string();
}
//--------------------------------------------------------------------------
std::string ClippingExit(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string();
}
//--------------------------------------------------------------------------
std::string BinaryMaskDeclaration(vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper),
vtkVolume* vtkNotUsed(vol), vtkImageData* maskInput, vtkVolumeTexture* mask,
int vtkNotUsed(maskType))
{
if (!mask || !maskInput)
{
return std::string();
}
else
{
return std::string("uniform sampler3D in_mask;");
}
}
//--------------------------------------------------------------------------
std::string BinaryMaskImplementation(vtkRenderer* vtkNotUsed(ren),
vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol), vtkImageData* maskInput,
vtkVolumeTexture* mask, int maskType)
{
if (!mask || !maskInput || maskType == vtkGPUVolumeRayCastMapper::LabelMapMaskType)
{
return std::string();
}
else
{
return std::string("\
\nvec4 maskValue = texture3D(in_mask, g_dataPos);\
\nif(maskValue.r <= 0.0)\
\n {\
\n g_skip = true;\
\n }");
}
}
//--------------------------------------------------------------------------
std::string CompositeMaskDeclarationFragment(vtkRenderer* vtkNotUsed(ren),
vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol), vtkImageData* maskInput,
vtkVolumeTexture* mask, int maskType)
{
if (!mask || !maskInput || maskType != vtkGPUVolumeRayCastMapper::LabelMapMaskType)
{
return std::string();
}
else
{
return std::string("\
\nuniform float in_maskBlendFactor;\
\nuniform sampler2D in_labelMapTransfer;\
\nuniform float in_mask_scale;\
\nuniform float in_mask_bias;\
\nuniform int in_labelMapNumLabels;\
\n");
}
}
//--------------------------------------------------------------------------
std::string CompositeMaskImplementation(vtkRenderer* vtkNotUsed(ren),
vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol), vtkImageData* maskInput,
vtkVolumeTexture* mask, int maskType, int noOfComponents)
{
if (!mask || !maskInput || maskType != vtkGPUVolumeRayCastMapper::LabelMapMaskType)
{
return std::string();
}
else
{
std::string shaderStr = std::string("\
\nvec4 scalar = texture3D(in_volume[0], g_dataPos);");
// simulate old intensity textures
if (noOfComponents == 1)
{
shaderStr += std::string("\
\n scalar.r = scalar.r * in_volume_scale[0].r + in_volume_bias[0].r;\
\n scalar = vec4(scalar.r);");
}
else
{
// handle bias and scale
shaderStr += std::string("\
\n scalar = scalar * in_volume_scale[0] + in_volume_bias[0];");
}
// Assumeing single component scalar for label texture lookup.
// This can be extended to composite color obtained from all components
// in the scalar array.
return shaderStr + std::string("\
\nif (in_maskBlendFactor == 0.0)\
\n {\
\n g_srcColor.a = computeOpacity(scalar);\
\n if (g_srcColor.a > 0)\
\n {\
\n g_srcColor = computeColor(scalar, g_srcColor.a);\
\n }\
\n }\
\nelse\
\n {\
\n float opacity = computeOpacity(scalar);\
\n // Get the mask value at this same location\
\n vec4 maskValue = texture3D(in_mask, g_dataPos);\
\n maskValue.r = maskValue.r * in_mask_scale + in_mask_bias;\
\n // Quantize the height of the labelmap texture over number of labels\
\n if (in_labelMapNumLabels > 0)\
\n {\
\n maskValue.r =\
\n floor(maskValue.r * in_labelMapNumLabels) /\
\n in_labelMapNumLabels;\
\n }\
\n else\
\n {\
\n maskValue.r = 0.0;\
\n }\
\n if(maskValue.r == 0.0)\
\n {\
\n g_srcColor.a = opacity;\
\n if (g_srcColor.a > 0)\
\n {\
\n g_srcColor = computeColor(scalar, g_srcColor.a);\
\n }\
\n }\
\n else\
\n {\
\n g_srcColor = texture2D(in_labelMapTransfer,\
\n vec2(scalar.r, maskValue.r));\
\n if (g_srcColor.a > 0)\
\n {\
\n g_srcColor = computeLighting(g_srcColor, 0, maskValue.r);\
\n }\
\n if (in_maskBlendFactor < 1.0)\
\n {\
\n vec4 color = opacity > 0 ? computeColor(scalar, opacity) : vec4(0);\
\n g_srcColor = (1.0 - in_maskBlendFactor) * color +\
\n in_maskBlendFactor * g_srcColor;\
\n }\
\n }\
\n }");
}
}
//--------------------------------------------------------------------------
std::string RenderToImageDeclarationFragment(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string("uniform bool in_clampDepthToBackface;\n"
"vec3 l_opaqueFragPos;\n"
"bool l_updateDepth;\n");
}
//--------------------------------------------------------------------------
std::string RenderToImageInit(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string("\
\n l_opaqueFragPos = vec3(-1.0);\
\n if(in_clampDepthToBackface)\
\n {\
\n l_opaqueFragPos = g_dataPos;\
\n }\
\n l_updateDepth = true;");
}
//--------------------------------------------------------------------------
std::string RenderToImageImplementation(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string("\
\n if(!g_skip && g_srcColor.a > 0.0 && l_updateDepth)\
\n {\
\n l_opaqueFragPos = g_dataPos;\
\n l_updateDepth = false;\
\n }");
}
//--------------------------------------------------------------------------
std::string RenderToImageExit(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string("\
\n if (l_opaqueFragPos == vec3(-1.0))\
\n {\
\n gl_FragData[1] = vec4(1.0);\
\n }\
\n else\
\n {\
\n vec4 depthValue = in_projectionMatrix * in_modelViewMatrix *\
\n in_volumeMatrix[0] * in_textureDatasetMatrix[0] *\
\n vec4(l_opaqueFragPos, 1.0);\
\n depthValue /= depthValue.w;\
\n gl_FragData[1] = vec4(vec3(0.5 * (gl_DepthRange.far -\
\n gl_DepthRange.near) * depthValue.z + 0.5 *\
\n (gl_DepthRange.far + gl_DepthRange.near)), 1.0);\
\n }");
}
//--------------------------------------------------------------------------
std::string DepthPassInit(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string("\
\n vec3 l_isoPos = g_dataPos;");
}
//--------------------------------------------------------------------------
std::string DepthPassImplementation(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string("\
\n if(!g_skip && g_srcColor.a > 0.0)\
\n {\
\n l_isoPos = g_dataPos;\
\n g_exit = true; g_skip = true;\
\n }");
}
//--------------------------------------------------------------------------
std::string DepthPassExit(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string("\
\n vec4 depthValue = in_projectionMatrix * in_modelViewMatrix *\
\n in_volumeMatrix[0] * in_textureDatasetMatrix[0] *\
\n vec4(l_isoPos, 1.0);\
\n gl_FragData[0] = vec4(l_isoPos, 1.0);\
\n gl_FragData[1] = vec4(vec3((depthValue.z/depthValue.w) * 0.5 + 0.5),\
\n 1.0);");
}
//---------------------------------------------------------------------------
std::string WorkerImplementation(
vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol))
{
return std::string("\
\n initializeRayCast();\
\n castRay(-1.0, -1.0);\
\n finalizeRayCast();");
}
//---------------------------------------------------------------------------
std::string ImageSampleDeclarationFrag(
const std::vector<std::string>& varNames, const size_t usedNames)
{
std::string shader = "\n";
for (size_t i = 0; i < usedNames; i++)
{
shader += "uniform sampler2D " + varNames[i] + ";\n";
}
return shader;
}
//---------------------------------------------------------------------------
std::string ImageSampleImplementationFrag(
const std::vector<std::string>& varNames, const size_t usedNames)
{
std::string shader = "\n";
for (size_t i = 0; i < usedNames; i++)
{
std::stringstream ss;
ss << i;
shader += " gl_FragData[" + ss.str() + "] = texture2D(" + varNames[i] + ", texCoord);\n";
}
shader += " return;\n";
return shader;
}
VTK_ABI_NAMESPACE_END
}
#endif // vtkVolumeShaderComposer_h
// VTK-HeaderTest-Exclude: vtkVolumeShaderComposer.h
|