All files / packages/core/src/RenderingEngine StackViewport.ts

68.94% Statements 646/937
53.34% Branches 223/418
68.96% Functions 100/145
68.89% Lines 640/929

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                          1x                                                                                           89x       89x             89x     89x   89x 89x           89x 89x                   89x                                           89x 89x 89x 89x 89x 89x   89x       89x 89x 89x 89x 89x   89x                 173x     89x         89x 89x   89x     2136x     89x           48x                 130x 130x 130x   130x 130x   130x         130x 130x 130x 130x                                                                                                                                                                                                                                                                   89x     36x   36x                       89x             89x             95x   95x       95x       95x 95x 95x                                   1276x   1276x   1276x               9x 9x 9x 9x   53x 53x       53x     68x       68x                                 89x   2340x   2340x 128x       2212x     2212x             2212x           89x                         89x 69x 69x   69x   69x   69x   69x       69x 4x     69x       89x 7x                     93x                 93x         93x   93x 93x 93x   93x 5x     93x 93x 93x   93x 93x   93x 69x     93x                                                     69x 69x 69x 69x 69x   69x 64x     5x 5x 5x         5x                         19x 19x                                                                                                       19x       19x 19x                   19x         19x 4x 4x     19x       19x 2x     19x 18x     19x   3x 3x                     89x                                       89x               3x 3x   3x                             1x 1x 1x   1x   1x       1x   1x         1x               1x     1x   1x   1x   1x 1x     1x 1x         1x   1x 2x 2x     1x 1x   1x                                                                                       3x     3x       3x               3x     3x 3x 3x       157x 157x       471x 471x       157x                         157x           157x       157x 157x   157x   157x                                                                                                                                                                                                                                                                                   89x 4x 4x                   89x         745x     745x             745x           745x               745x   745x         89x 4x   4x       4x         4x   4x                 4x                                                                           4x 4x 4x 4x 4x     4x       4x         4x 4x 4x 4x 4x 4x       22x   22x       22x     22x 22x     22x   22x                                               75x   75x       75x           75x               75x 75x 75x   75x 3x     75x                                                                                                             1x   1x       1x     1x   1x               77x   77x               3x     74x 74x       74x     74x   74x   74x                 74x   74x     74x     74x 69x       69x   69x       69x 69x       74x   74x     74x     74x 74x     74x       74x           74x                 5x 2x         3x   3x   3x 3x     3x 3x     3x                           93x 93x         4x     93x                                 93x       93x 93x     93x         93x         93x         93x 93x   93x   93x         93x 93x 93x 93x           93x 93x     93x         93x                                             207x   207x 69x                                   69x     69x           69x   69x 69x 69x 69x 69x   69x                                 69x                                               86x   86x 86x 86x 86x           86x             86x 86x 86x 86x 86x 86x 86x   86x   86x 24x 24x     86x   86x             86x   86x             91x                                           72x 64x   8x 8x 8x 8x 8x 8x 8x     8x 8x     8x                                         72x 72x   72x       72x       72x                             94x                 24x                   24x       24x         24x 24x     24x     24x                                                                             24x 24x   24x               24x   24x           24x       24x 24x                                           24x   24x               24x 24x 24x 24x               24x           24x   24x                   70x           70x                 70x 70x   70x     70x   70x 62x     70x   70x               70x 70x     70x       70x                                   70x 70x                   70x 70x                           70x             70x   70x       70x   70x 70x                 70x 70x             70x       70x           70x   70x 70x                                       89x 2x   2x       2x     89x 96x 96x       24x   24x             24x 24x   24x 24x     24x   24x                 24x         24x     24x   24x                                                                                                                       72x         72x       72x 72x   3x               3x   3x               3x       3x           3x 3x         3x       3x           3x 3x   3x                   69x         69x 69x                     69x     69x 69x 69x 5x   64x   69x       69x   69x     69x       69x   69x         69x     69x     69x   69x       69x     69x     69x 69x   69x   69x 5x         69x     69x   69x       69x   69x       69x 69x             73x 73x                                       73x 73x 73x             73x 73x                 91x             91x 91x 91x       91x             91x                 91x       24x   24x 24x                                                   208x               208x 208x                       5x   5x 5x   5x 5x   5x     5x           5x   5x   5x           5x 5x               5x           5x 5x                       5x     5x         5x   5x                       3x 3x 3x                           3x     3x   3x 3x         3x           3x   3x     3x         3x         72x               72x   70x           5x   5x                     5x   5x     5x     89x       866x       866x     866x     866x 866x     866x 866x   866x     89x   345x   345x 345x   345x   345x           345x       345x     89x 1881x           1881x 1881x 1881x   1881x     1881x   1881x 1881x   1881x 1881x       1881x           1881x   1881x               1881x   1881x     89x 2483x           2483x 2483x 2483x   2483x     2483x   2483x 2483x 2483x           2483x   2483x           2483x   2483x 2483x         2483x       4x   4x       93x 93x   93x               89x 158x     89x                     123x       123x 123x   123x       123x 123x     123x 123x     123x   3x 3x   123x                   13x 13x                                                         144x 144x     144x                 89x               89x 10x             89x 2519x               89x                 89x 68x 68x 68x 68x                           87x   87x 87x             89x 24x           24x 24x         24x         24x                                                                               1x 1x 1x 1x     1x     1x           1x 1x       1x     1x 1x   1x         1x                     173x   173x 173x       173x         173x         173x       173x       173x       173x           173x     89x                                                                                                     24x 24x     208x 208x                                                                                                      
import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray';
import type { vtkImageData as vtkImageDataType } from '@kitware/vtk.js/Common/DataModel/ImageData';
import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData';
import vtkCamera from '@kitware/vtk.js/Rendering/Core/Camera';
import vtkColorTransferFunction from '@kitware/vtk.js/Rendering/Core/ColorTransferFunction';
import vtkColorMaps from '@kitware/vtk.js/Rendering/Core/ColorTransferFunction/ColorMaps';
import vtkImageMapper from '@kitware/vtk.js/Rendering/Core/ImageMapper';
import vtkImageSlice from '@kitware/vtk.js/Rendering/Core/ImageSlice';
import { mat4, vec2, vec3 } from 'gl-matrix';
import eventTarget from '../eventTarget';
import * as metaData from '../metaData';
import cloneDeep from 'lodash.clonedeep';
import type {
  ActorEntry,
  CPUFallbackColormapData,
  CPUFallbackEnabledElement,
  CPUIImageData,
  ColormapPublic,
  EventTypes,
  FlipDirection,
  ICamera,
  IImage,
  IImageCalibration,
  IImageData,
  IImagesLoader,
  IStackInput,
  IStackViewport,
  ImageLoadListener,
  Mat3,
  PTScaling,
  Point2,
  Point3,
  Scaling,
  StackViewportProperties,
  VOIRange,
  ViewReference,
  ViewPresentation,
  VolumeActor,
} from '../types';
import {
  ViewReferenceSpecifier,
  ReferenceCompatibleOptions,
  ViewportInput,
} from '../types/IViewport';
import {
  actorIsA,
  colormap as colormapUtils,
  createSigmoidRGBTransferFunction,
  imageIdToURI,
  imageRetrieveMetadataProvider,
  invertRgbTransferFunction,
  isEqual,
  isImageActor,
  triggerEvent,
  updateVTKImageDataWithCornerstoneImage,
  windowLevel as windowLevelUtil,
} from '../utilities';
import Viewport from './Viewport';
import { getColormap } from './helpers/cpuFallback/colors/index';
import drawImageSync from './helpers/cpuFallback/drawImageSync';
 
import {
  Events,
  InterpolationType,
  MetadataModules,
  RequestType,
  VOILUTFunctionType,
  ViewportStatus,
} from '../enums';
import { ImageLoaderOptions, loadAndCacheImage } from '../loaders/imageLoader';
import imageLoadPoolManager from '../requestPool/imageLoadPoolManager';
import calculateTransform from './helpers/cpuFallback/rendering/calculateTransform';
import canvasToPixel from './helpers/cpuFallback/rendering/canvasToPixel';
import getDefaultViewport from './helpers/cpuFallback/rendering/getDefaultViewport';
import pixelToCanvas from './helpers/cpuFallback/rendering/pixelToCanvas';
import resize from './helpers/cpuFallback/rendering/resize';
 
import cache from '../cache';
import { getConfiguration, getShouldUseCPURendering } from '../init';
import { createProgressive } from '../loaders/ProgressiveRetrieveImages';
import {
  ImagePixelModule,
  ImagePlaneModule,
  PixelDataTypedArray,
} from '../types';
import {
  StackViewportNewStackEventDetail,
  StackViewportScrollEventDetail,
  VoiModifiedEventDetail,
} from '../types/EventTypes';
import { ImageActor } from '../types/IActor';
import createLinearRGBTransferFunction from '../utilities/createLinearRGBTransferFunction';
import {
  getTransferFunctionNodes,
  setTransferFunctionNodes,
} from '../utilities/transferFunctionUtils';
import correctShift from './helpers/cpuFallback/rendering/correctShift';
import resetCamera from './helpers/cpuFallback/rendering/resetCamera';
import { Transform } from './helpers/cpuFallback/rendering/transform';
import { findMatchingColormap } from '../utilities/colormap';
 
const EPSILON = 1; // Slice Thickness
 
interface ImageDataMetaData {
  bitsAllocated: number;
  numComps: number;
  origin: Point3;
  direction: Mat3;
  dimensions: Point3;
  spacing: Point3;
  numVoxels: number;
  imagePlaneModule: ImagePlaneModule;
  imagePixelModule: ImagePixelModule;
}
// TODO This needs to be exposed as its published to consumers.
type CalibrationEvent = {
  rowScale?: number;
  columnScale?: number;
  scale: number;
  calibration: IImageCalibration;
};
 
type SetVOIOptions = {
  suppressEvents?: boolean;
  forceRecreateLUTFunction?: boolean;
  voiUpdatedWithSetProperties?: boolean;
};
 
/**
 * An object representing a single stack viewport, which is a camera
 * looking into an internal viewport, and an associated target output `canvas`.
 *
 * StackViewports can be rendered using both GPU and a fallback CPU is the GPU
 * is not available (or low performance). Read more about StackViewports in
 * the documentation section of this website.
 */
class StackViewport extends Viewport implements IStackViewport, IImagesLoader {
  private imageIds: Array<string>;
  // current imageIdIndex that is rendered in the viewport
  private currentImageIdIndex: number;
  // the imageIdIndex that is targeted to be loaded with scrolling but has not initiated loading yet
  private targetImageIdIndex: number;
  // setTimeout if the image is debounced to be loaded
  private debouncedTimeout: number;
  /**
   * The progressive retrieval configuration used for this viewport.
   */
  protected imagesLoader: IImagesLoader = this;
 
  // Viewport Properties
  private globalDefaultProperties: StackViewportProperties;
  private perImageIdDefaultProperties = new Map<
    string,
    StackViewportProperties
  >();
 
  private colormap: ColormapPublic | CPUFallbackColormapData;
  private voiRange: VOIRange;
  private voiUpdatedWithSetProperties = false;
  private VOILUTFunction: VOILUTFunctionType;
  //
  private invert = false;
  // The initial invert of the image loaded as opposed to the invert status of the viewport itself (see above).
  private initialInvert = false;
  private initialTransferFunctionNodes = null;
  private interpolationType: InterpolationType;
 
  // Helpers
  private _imageData: vtkImageDataType;
  private cameraFocalPointOnRender: Point3; // we use focalPoint since flip manipulates the position and makes it useless to track
  private stackInvalidated = false; // if true -> new actor is forced to be created for the stack
  private _publishCalibratedEvent = false;
  private _calibrationEvent: CalibrationEvent;
  private _cpuFallbackEnabledElement?: CPUFallbackEnabledElement;
  // CPU fallback
  private useCPURendering: boolean;
  // Since WebGL natively supports 8 bit int and Float32, we should check if
  // extra configuration flags has been set to use native data type
  // which would save a lot of memory and speed up rendering but it is not
  // yet widely supported in all hardwares. This feature can be turned on
  // by setting useNorm16Texture or preferSizeOverAccuracy in the configuration
  private useNativeDataType = false;
  private cpuImagePixelData: PixelDataTypedArray;
  private cpuRenderingInvalidated: boolean;
  private csImage: IImage;
 
  // TODO: These should not be here and will be nuked
  public modality: string; // this is needed for tools
  public scaling: Scaling;
 
  // Camera properties
  private initialViewUp: Point3;
 
  // this flag is used to check
  // if the viewport used the same actor/mapper to render the image
  // or because of the new image inconsistency, a new actor/mapper was created
  public stackActorReInitialized: boolean;
 
  /**
   * Constructor for the StackViewport class
   * @param props - ViewportInput
   */
  constructor(props: ViewportInput) {
    super(props);
    this.scaling = {};
    this.modality = null;
    this.useCPURendering = getShouldUseCPURendering();
    this.useNativeDataType = this._shouldUseNativeDataType();
    this._configureRenderingPipeline();
 
    this.useCPURendering
      ? this._resetCPUFallbackElement()
      : this._resetGPUViewport();
 
    this.imageIds = [];
    this.currentImageIdIndex = 0;
    this.targetImageIdIndex = 0;
    this.cameraFocalPointOnRender = [0, 0, 0];
    this.resetCamera();
 
    this.initializeElementDisabledHandler();
  }
 
  public setUseCPURendering(value: boolean) {
    this.useCPURendering = value;
    this._configureRenderingPipeline(value);
  }
 
  static get useCustomRenderingPipeline(): boolean {
    return getShouldUseCPURendering();
  }
 
  public updateRenderingPipeline = () => {
    this._configureRenderingPipeline();
  };
 
  private _configureRenderingPipeline(value?: boolean) {
    this.useNativeDataType = this._shouldUseNativeDataType();
    this.useCPURendering = value ?? getShouldUseCPURendering();
 
    for (const [funcName, functions] of Object.entries(
      this.renderingPipelineFunctions
    )) {
      this[funcName] = this.useCPURendering ? functions.cpu : functions.gpu;
    }
 
    this.useCPURendering
      ? this._resetCPUFallbackElement()
      : this._resetGPUViewport();
  }
 
  private _resetCPUFallbackElement() {
    this._cpuFallbackEnabledElement = {
      canvas: this.canvas,
      renderingTools: {},
      transform: new Transform(),
      viewport: { rotation: 0 },
    };
  }
 
  private _resetGPUViewport() {
    const renderer = this.getRenderer();
    const camera = vtkCamera.newInstance();
    renderer.setActiveCamera(camera);
 
    const viewPlaneNormal = <Point3>[0, 0, -1];
    this.initialViewUp = <Point3>[0, -1, 0];
 
    camera.setDirectionOfProjection(
      -viewPlaneNormal[0],
      -viewPlaneNormal[1],
      -viewPlaneNormal[2]
    );
    camera.setViewUp(...this.initialViewUp);
    camera.setParallelProjection(true);
    camera.setThicknessFromFocalPoint(0.1);
    camera.setFreezeFocalPoint(true);
  }
 
  /**
   * Returns the image and its properties that is being shown inside the
   * stack viewport. It returns, the image dimensions, image direction,
   * image scalar data, vtkImageData object, metadata, and scaling (e.g., PET suvbw)
   *
   * @returns IImageData: dimensions, direction, scalarData, vtkImageData, metadata, scaling
   */
  public getImageData: () => IImageData | CPUIImageData;
 
  /**
   * If the user has selected CPU rendering, return the CPU camera, otherwise
   * return the default camera
   * @returns The camera object.
   */
  public getCamera: () => ICamera;
 
  /**
   * Set the camera based on the provided camera object.
   * @param cameraInterface - The camera interface that will be used to
   * render the scene.
   */
  public setCamera: (
    cameraInterface: ICamera,
    storeAsInitialCamera?: boolean
  ) => void;
 
  public getRotation: () => number;
 
  /**
   * It sets the colormap to the default colormap.
   */
  public unsetColormap: () => void;
 
  /**
   * Centers Pan and resets the zoom for stack viewport.
   */
  public resetCamera: (resetPan?: boolean, resetZoom?: boolean) => boolean;
 
  /**
   * canvasToWorld Returns the world coordinates of the given `canvasPos`
   * projected onto the plane defined by the `Viewport`'s camera.
   *
   * @param canvasPos - The position in canvas coordinates.
   * @returns The corresponding world coordinates.
   * @public
   */
  public canvasToWorld: (canvasPos: Point2) => Point3;
 
  /**
   * Returns the canvas coordinates of the given `worldPos`
   * projected onto the `Viewport`'s `canvas`.
   *
   * @param worldPos - The position in world coordinates.
   * @returns The corresponding canvas coordinates.
   * @public
   */
  public worldToCanvas: (worldPos: Point3) => Point2;
 
  /**
   * If the renderer is CPU based, throw an error. Otherwise, returns the `vtkRenderer` responsible for rendering the `Viewport`.
   *
   * @returns The `vtkRenderer` for the `Viewport`.
   */
  public getRenderer: () => any;
 
  /**
   * If the renderer is CPU based, throw an error. Otherwise, return the default
   * actor which is the first actor in the renderer.
   * @returns An actor entry.
   */
  public getDefaultActor: () => ActorEntry;
 
  /**
   * If the renderer is CPU based, throw an error. Otherwise, return the actors in the viewport
   * @returns An array of ActorEntry objects.
   */
  public getActors: () => Array<ActorEntry>;
  /**
   * If the renderer is CPU based, throw an error. Otherwise, it returns the actor entry for the given actor UID.
   * @param actorUID - The unique ID of the actor you want to get.
   * @returns An ActorEntry object.
   */
  public getActor: (actorUID: string) => ActorEntry;
 
  /**
   * If the renderer is CPU-based, throw an error; otherwise, set the
   * actors in the viewport.
   * @param actors - An array of ActorEntry objects.
   */
  public setActors: (actors: Array<ActorEntry>) => void;
 
  /**
   * If the renderer is CPU based, throw an error. Otherwise, add a list of actors to the viewport
   * @param actors - An array of ActorEntry objects.
   */
  public addActors: (actors: Array<ActorEntry>) => void;
 
  /**
   * If the renderer is CPU based, throw an error. Otherwise, add the
   * actor to the viewport
   * @param actorEntry - The ActorEntry object that was created by the
   * user.
   */
  public addActor: (actorEntry: ActorEntry) => void;
 
  /**
   * It throws an error if the renderer is CPU based. Otherwise, it removes the actors from the viewport.
   */
  public removeAllActors: () => void;
 
  private setVOI: (voiRange: VOIRange, options?: SetVOIOptions) => void;
 
  protected setInterpolationType: (
    interpolationType: InterpolationType
  ) => void;
 
  private setInvertColor: (invert: boolean) => void;
 
  /**
   * Sets the colormap for the current viewport.
   * @param colormap - The colormap data to use.
   */
  private setColormap: (
    colormap: CPUFallbackColormapData | ColormapPublic
  ) => void;
 
  private initializeElementDisabledHandler() {
    eventTarget.addEventListener(
      Events.ELEMENT_DISABLED,
      function elementDisabledHandler() {
        clearTimeout(this.debouncedTimeout);
 
        eventTarget.removeEventListener(
          Events.ELEMENT_DISABLED,
          elementDisabledHandler
        );
      }
    );
  }
 
  /**
   * Resizes the viewport - only used in CPU fallback for StackViewport. The
   * GPU resizing happens inside the RenderingEngine.
   */
  public resize = (): void => {
    // GPU viewport resize is handled inside the RenderingEngine
    if (this.useCPURendering) {
      this._resizeCPU();
    }
  };
 
  private _resizeCPU = (): void => {
    if (this._cpuFallbackEnabledElement.viewport) {
      resize(this._cpuFallbackEnabledElement);
    }
  };
 
  private getImageDataGPU(): IImageData | undefined {
    const defaultActor = this.getDefaultActor();
 
    Iif (!defaultActor) {
      return;
    }
 
    Iif (!isImageActor(defaultActor)) {
      return;
    }
 
    const { actor } = defaultActor;
    const vtkImageData = actor.getMapper().getInputData();
    return {
      dimensions: vtkImageData.getDimensions(),
      spacing: vtkImageData.getSpacing(),
      origin: vtkImageData.getOrigin(),
      direction: vtkImageData.getDirection(),
      scalarData: vtkImageData.getPointData().getScalars().getData(),
      imageData: actor.getMapper().getInputData(),
      metadata: { Modality: this.modality },
      scaling: this.scaling,
      hasPixelSpacing: this.hasPixelSpacing,
      calibration: { ...this.csImage.calibration, ...this.calibration },
      preScale: {
        ...this.csImage.preScale,
      },
    };
  }
 
  private getImageDataCPU(): CPUIImageData | undefined {
    const { metadata } = this._cpuFallbackEnabledElement;
 
    const spacing = metadata.spacing;
 
    return {
      dimensions: metadata.dimensions,
      spacing,
      origin: metadata.origin,
      direction: metadata.direction,
      metadata: { Modality: this.modality },
      scaling: this.scaling,
      imageData: {
        getDirection: () => metadata.direction,
        getDimensions: () => metadata.dimensions,
        getScalarData: () => this.cpuImagePixelData,
        getSpacing: () => spacing,
        worldToIndex: (point: Point3) => {
          const canvasPoint = this.worldToCanvasCPU(point);
          const pixelCoord = canvasToPixel(
            this._cpuFallbackEnabledElement,
            canvasPoint
          );
          return [pixelCoord[0], pixelCoord[1], 0];
        },
        indexToWorld: (point: Point3, destPoint?: Point3) => {
          const canvasPoint = pixelToCanvas(this._cpuFallbackEnabledElement, [
            point[0],
            point[1],
          ]);
          return this.canvasToWorldCPU(canvasPoint, destPoint);
        },
      },
      scalarData: this.cpuImagePixelData,
      hasPixelSpacing: this.hasPixelSpacing,
      calibration: { ...this.csImage.calibration, ...this.calibration },
      preScale: {
        ...this.csImage.preScale,
      },
    };
  }
 
  /**
   * Returns the frame of reference UID, if the image doesn't have imagePlaneModule
   * metadata, it returns undefined, otherwise, frameOfReferenceUID is returned.
   * @returns frameOfReferenceUID : string representing frame of reference id
   */
  public getFrameOfReferenceUID = (): string | undefined => {
    // Get the current image that is displayed in the viewport
    const imageId = this.getCurrentImageId();
 
    if (!imageId) {
      return;
    }
 
    // Use the metadata provider to grab its imagePlaneModule metadata
    const imagePlaneModule = metaData.get('imagePlaneModule', imageId);
 
    // If nothing exists, return undefined
    Iif (!imagePlaneModule) {
      return;
    }
 
    // Otherwise, provide the FrameOfReferenceUID so we can map
    // annotations made on VolumeViewports back to StackViewports
    // and vice versa
    return imagePlaneModule.frameOfReferenceUID;
  };
 
  /**
   * Returns the raw/loaded image being shown inside the stack viewport.
   */
  public getCornerstoneImage = (): IImage => {
    return this.csImage;
  };
 
  /**
   * Creates imageMapper based on the provided vtkImageData and also creates
   * the imageSliceActor and connects it to the imageMapper.
   * For color stack images, it sets the independent components to be false which
   * is required in vtk.
   *
   * @param imageData - vtkImageData for the viewport
   * @returns actor vtkActor
   */
  private createActorMapper = (imageData) => {
    const mapper = vtkImageMapper.newInstance();
    mapper.setInputData(imageData);
 
    const actor = vtkImageSlice.newInstance();
 
    actor.setMapper(mapper);
 
    const { preferSizeOverAccuracy } = getConfiguration().rendering;
 
    Iif (preferSizeOverAccuracy) {
      mapper.setPreferSizeOverAccuracy(true);
    }
 
    if (imageData.getPointData().getNumberOfComponents() > 1) {
      actor.getProperty().setIndependentComponents(false);
    }
 
    return actor;
  };
 
  /** Gets the number of slices */
  public getNumberOfSlices = (): number => {
    return this.imageIds.length;
  };
 
  /**
   * Retrieves the metadata from the metadata provider, and optionally adds the
   * scaling to the viewport if modality is PET and scaling metadata is provided.
   *
   * @param imageId - a string representing the imageId for the image
   * @returns imagePlaneModule and imagePixelModule containing the metadata for the image
   */
  private buildMetadata(image: IImage) {
    const imageId = image.imageId;
 
    const {
      pixelRepresentation,
      bitsAllocated,
      bitsStored,
      highBit,
      photometricInterpretation,
      samplesPerPixel,
    } = metaData.get('imagePixelModule', imageId);
 
    // we can grab the window center and width from the image object
    // since it the loader already has used the metadata provider
    // to get the values
    const { windowWidth, windowCenter, voiLUTFunction } = image;
 
    const { modality } = metaData.get('generalSeriesModule', imageId);
    const imageIdScalingFactor = metaData.get('scalingModule', imageId);
    const calibration = metaData.get(MetadataModules.CALIBRATION, imageId);
 
    if (modality === 'PT' && imageIdScalingFactor) {
      this._addScalingToViewport(imageIdScalingFactor);
    }
 
    this.modality = modality;
    const voiLUTFunctionEnum = this._getValidVOILUTFunction(voiLUTFunction);
    this.VOILUTFunction = voiLUTFunctionEnum;
 
    this.calibration = calibration;
    let imagePlaneModule = this._getImagePlaneModule(imageId);
 
    if (!this.useCPURendering) {
      imagePlaneModule = this.calibrateIfNecessary(imageId, imagePlaneModule);
    }
 
    return {
      imagePlaneModule,
      imagePixelModule: {
        bitsAllocated,
        bitsStored,
        samplesPerPixel,
        highBit,
        photometricInterpretation,
        pixelRepresentation,
        windowWidth,
        windowCenter,
        modality,
        voiLUTFunction: voiLUTFunctionEnum,
      },
    };
  }
 
  /**
   * Checks the metadataProviders to see if a calibratedPixelSpacing is
   * given. If so, checks the actor to see if it needs to be modified, and
   * set the flags for imageCalibration if a new actor needs to be created
   *
   * @param imageId - imageId
   * @param imagePlaneModule - imagePlaneModule
   * @returns modified imagePlaneModule with the calibrated spacings
   */
  private calibrateIfNecessary(imageId, imagePlaneModule) {
    const calibration = metaData.get('calibratedPixelSpacing', imageId);
    const isUpdated = this.calibration !== calibration;
    const { scale } = calibration || {};
    this.hasPixelSpacing = scale > 0 || imagePlaneModule.rowPixelSpacing > 0;
    imagePlaneModule.calibration = calibration;
 
    if (!isUpdated) {
      return imagePlaneModule;
    }
 
    this.calibration = calibration;
    this._publishCalibratedEvent = true;
    this._calibrationEvent = <CalibrationEvent>{
      scale,
      calibration,
    };
 
    return imagePlaneModule;
  }
 
  /**
   * Update the default properties of the viewport and add properties by imageId if specified
   * @param ViewportProperties - The properties to set
   * @param imageId If given, we set the default properties only for this image index, if not
   * the default properties will be set for all imageIds
   */
  public setDefaultProperties(
    ViewportProperties: StackViewportProperties,
    imageId?: string
  ): void {
    if (imageId == null) {
      this.globalDefaultProperties = ViewportProperties;
    } else E{
      this.perImageIdDefaultProperties.set(imageId, ViewportProperties);
 
      //If the viewport is the same imageIdI, we need to update the viewport
      if (this.getCurrentImageId() === imageId) {
        this.setProperties(ViewportProperties);
      }
    }
  }
 
  /**
   * Remove the global default properties of the viewport or remove default properties for an imageId if specified
   * @param imageId If given, we remove the default properties only for this imageID, if not
   * the global default properties will be removed
   */
  public clearDefaultProperties(imageId?: string): void {
    if (imageId == null) {
      this.globalDefaultProperties = {};
      this.resetProperties();
    } else {
      this.perImageIdDefaultProperties.delete(imageId);
      this.resetToDefaultProperties();
    }
  }
 
  /**
   Configures the properties of the viewport.
   This method allows customization of the viewport by setting attributes like
   VOI (Value of Interest), color inversion, interpolation type, and image rotation.
   If setProperties is called for the first time, the provided properties will
   become the default settings for all images in the stack in case the resetPropertiese need to be called
   @param properties - An object containing the properties to be set.
   @param properties.colormap - Specifies the colormap for the viewport.
   @param properties.voiRange - Defines the lower and upper Value of Interest (VOI) to be applied.
   @param properties.VOILUTFunction - Function to handle the application of a lookup table (LUT) to the VOI.
   @param properties.invert - A boolean value to toggle color inversion (true: inverted, false: not inverted).
   @param properties.interpolationType - Determines the interpolation method to be used (1: linear, 0: nearest-neighbor).
   @param properties.rotation - Specifies the image rotation angle in degrees.
   @param suppressEvents - A boolean value to control event suppression. If true, the related events will not be triggered. Default is false.
   */
  public setProperties(
    {
      colormap,
      voiRange,
      VOILUTFunction,
      invert,
      interpolationType,
      rotation,
    }: StackViewportProperties = {},
    suppressEvents = false
  ): void {
    this.viewportStatus = this.csImage
      ? ViewportStatus.PRE_RENDER
      : ViewportStatus.LOADING;
 
    Eif (this.globalDefaultProperties == null) {
      this.setDefaultProperties({
        colormap,
        voiRange,
        VOILUTFunction,
        invert,
        interpolationType,
        rotation,
      });
    }
 
    Iif (typeof colormap !== 'undefined') {
      this.setColormap(colormap);
    }
    // if voi is not applied for the first time, run the setVOI function
    // which will apply the default voi based on the range
    if (typeof voiRange !== 'undefined') {
      const voiUpdatedWithSetProperties = true;
      this.setVOI(voiRange, { suppressEvents, voiUpdatedWithSetProperties });
    }
 
    Iif (typeof VOILUTFunction !== 'undefined') {
      this.setVOILUTFunction(VOILUTFunction, suppressEvents);
    }
 
    if (typeof invert !== 'undefined') {
      this.setInvertColor(invert);
    }
 
    if (typeof interpolationType !== 'undefined') {
      this.setInterpolationType(interpolationType);
    }
 
    if (typeof rotation !== 'undefined') {
      // TODO: check with VTK about rounding errors here.
      Eif (this.getRotation() !== rotation) {
        this.setRotation(rotation);
      }
    }
  }
 
  /**
   * Retrieve the viewport default properties
   * @param imageId If given, we retrieve the default properties of an image index if it exists
   * If not given,we return the global properties of the viewport
   * @returns viewport properties including voi, invert, interpolation type, rotation, flip
   */
  public getDefaultProperties = (imageId?: string): StackViewportProperties => {
    let imageProperties;
    if (imageId !== undefined) {
      imageProperties = this.perImageIdDefaultProperties.get(imageId);
    }
 
    if (imageProperties !== undefined) {
      return imageProperties;
    }
 
    return {
      ...this.globalDefaultProperties,
      rotation: this.getRotation(),
    };
  };
 
  /**
   * Retrieve the viewport properties
   * @returns viewport properties including voi, invert, interpolation type, rotation, flip
   */
  public getProperties = (): StackViewportProperties => {
    const {
      colormap,
      voiRange,
      VOILUTFunction,
      interpolationType,
      invert,
      voiUpdatedWithSetProperties,
    } = this;
    const rotation = this.getRotation();
 
    return {
      colormap,
      voiRange,
      VOILUTFunction,
      interpolationType,
      invert,
      rotation,
      isComputedVOI: !voiUpdatedWithSetProperties,
    };
  };
 
  /**
   * Reset the viewport properties to the default values
   */
  public resetProperties(): void {
    this.cpuRenderingInvalidated = true;
    this.voiUpdatedWithSetProperties = false;
    this.viewportStatus = ViewportStatus.PRE_RENDER;
 
    this.fillWithBackgroundColor();
 
    Iif (this.useCPURendering) {
      this._cpuFallbackEnabledElement.renderingTools = {};
    }
 
    this._resetProperties();
 
    this.render();
  }
 
  private _resetProperties() {
    let voiRange;
    Iif (this._isCurrentImagePTPrescaled()) {
      // if not set via setProperties; if it is a PT image and is already prescaled,
      // use the default range for PT
      voiRange = this._getDefaultPTPrescaledVOIRange();
    } else {
      // if not set via setProperties; if it is not a PT image or is not prescaled,
      // use the voiRange for the current image from its metadata if found
      // otherwise, use the cached voiRange
      voiRange = this._getVOIRangeForCurrentImage();
    }
 
    this.setVOI(voiRange);
 
    this.setInvertColor(this.initialInvert);
 
    this.setInterpolationType(InterpolationType.LINEAR);
 
    Eif (this.getRotation() !== 0) {
      this.setRotation(0);
    }
 
    const transferFunction = this.getTransferFunction();
    setTransferFunctionNodes(
      transferFunction,
      this.initialTransferFunctionNodes
    );
 
    const nodes = getTransferFunctionNodes(transferFunction);
 
    const RGBPoints = nodes.reduce((acc, node) => {
      acc.push(node[0], node[1], node[2], node[3]);
      return acc;
    }, []);
 
    const defaultActor = this.getDefaultActor();
    const matchedColormap = findMatchingColormap(RGBPoints, defaultActor.actor);
 
    this.setColormap(matchedColormap);
  }
 
  public resetToDefaultProperties(): void {
    this.cpuRenderingInvalidated = true;
    this.viewportStatus = ViewportStatus.PRE_RENDER;
 
    this.fillWithBackgroundColor();
 
    if (this.useCPURendering) {
      this._cpuFallbackEnabledElement.renderingTools = {};
    }
 
    const currentImageId = this.getCurrentImageId();
    const properties =
      this.perImageIdDefaultProperties.get(currentImageId) ||
      this.globalDefaultProperties;
 
    if (properties.colormap?.name) {
      this.setColormap(properties.colormap);
    }
 
    let voiRange;
    if (properties.voiRange == undefined) {
      // if not set via setProperties; if it is not a PT image or is not prescaled,
      // use the voiRange for the current image from its metadata if found
      // otherwise, use the cached voiRange
      voiRange = this._getVOIRangeForCurrentImage();
    } else {
      voiRange = properties.voiRange;
    }
 
    this.setVOI(voiRange);
 
    if (this.getRotation() !== 0) {
      this.setRotation(0);
    }
    this.setInterpolationType(InterpolationType.LINEAR);
    this.setInvertColor(false);
 
    this.render();
  }
 
  private _setPropertiesFromCache(): void {
    const { interpolationType, invert } = this;
 
    let voiRange;
    Iif (this.voiUpdatedWithSetProperties) {
      // use the cached voiRange if the voiRange is locked (if the user has
      // manually set the voi with tools or setProperties api)
      voiRange = this.voiRange;
    } else Iif (this._isCurrentImagePTPrescaled()) {
      // if not set via setProperties; if it is a PT image and is already prescaled,
      // use the default range for PT
      voiRange = this._getDefaultPTPrescaledVOIRange();
    } else {
      // if not set via setProperties; if it is not a PT image or is not prescaled,
      // use the voiRange for the current image from its metadata if found
      // otherwise, use the cached voiRange
      voiRange = this._getVOIRangeForCurrentImage() ?? this.voiRange;
    }
 
    this.setVOI(voiRange);
    this.setInterpolationType(interpolationType);
    this.setInvertColor(invert);
  }
 
  private getCameraCPU(): Partial<ICamera> {
    const { metadata, viewport } = this._cpuFallbackEnabledElement;
    const { direction } = metadata;
 
    // focalPoint and position of CPU camera is just a placeholder since
    // tools need focalPoint to be defined
    const viewPlaneNormal = direction.slice(6, 9).map((x) => -x) as Point3;
    let viewUp = direction.slice(3, 6).map((x) => -x) as Point3;
 
    // If camera is rotated, we need the correct rotated viewUp along the
    // viewPlaneNormal vector
    Iif (viewport.rotation) {
      const rotationMatrix = mat4.fromRotation(
        mat4.create(),
        (viewport.rotation * Math.PI) / 180,
        viewPlaneNormal
      );
      viewUp = vec3.transformMat4(
        vec3.create(),
        viewUp,
        rotationMatrix
      ) as Point3;
    }
 
    const canvasCenter: Point2 = [
      this.element.clientWidth / 2,
      this.element.clientHeight / 2,
    ];
 
    // Focal point is the center of the canvas in world coordinate by construction
    const canvasCenterWorld = this.canvasToWorld(canvasCenter);
 
    // parallel scale is half of the viewport height in the world units (mm)
 
    const topLeftWorld = this.canvasToWorld([0, 0]);
    const bottomLeftWorld = this.canvasToWorld([0, this.element.clientHeight]);
 
    const parallelScale = vec3.distance(topLeftWorld, bottomLeftWorld) / 2;
 
    return {
      parallelProjection: true,
      focalPoint: canvasCenterWorld,
      position: [0, 0, 0],
      parallelScale,
      scale: viewport.scale,
      viewPlaneNormal: [
        viewPlaneNormal[0],
        viewPlaneNormal[1],
        viewPlaneNormal[2],
      ],
      viewUp: [viewUp[0], viewUp[1], viewUp[2]],
      flipHorizontal: this.flipHorizontal,
      flipVertical: this.flipVertical,
    };
  }
 
  private setCameraCPU(cameraInterface: ICamera): void {
    const { viewport, image } = this._cpuFallbackEnabledElement;
    const previousCamera = this.getCameraCPU();
 
    const { focalPoint, parallelScale, scale, flipHorizontal, flipVertical } =
      cameraInterface;
 
    const { clientHeight } = this.element;
 
    if (focalPoint) {
      const focalPointCanvas = this.worldToCanvasCPU(focalPoint);
      const focalPointPixel = canvasToPixel(
        this._cpuFallbackEnabledElement,
        focalPointCanvas
      );
 
      const prevFocalPointCanvas = this.worldToCanvasCPU(
        previousCamera.focalPoint
      );
      const prevFocalPointPixel = canvasToPixel(
        this._cpuFallbackEnabledElement,
        prevFocalPointCanvas
      );
 
      const deltaPixel = vec2.create();
      vec2.subtract(
        deltaPixel,
        vec2.fromValues(focalPointPixel[0], focalPointPixel[1]),
        vec2.fromValues(prevFocalPointPixel[0], prevFocalPointPixel[1])
      );
 
      const shift = correctShift(
        { x: deltaPixel[0], y: deltaPixel[1] },
        viewport
      );
 
      viewport.translation.x -= shift.x;
      viewport.translation.y -= shift.y;
    }
 
    if (parallelScale) {
      // We need to convert he parallelScale which has a physical meaning to
      // camera scale factor (since CPU works with scale). Since parallelScale represents
      // half of the height of the viewport in the world unit (mm), we can use that
      // to compute the scale factor which is the ratio of the viewport height in pixels
      // to the current rendered image height.
      const { rowPixelSpacing } = image;
      const scale = (clientHeight * rowPixelSpacing * 0.5) / parallelScale;
 
      viewport.scale = scale;
      viewport.parallelScale = parallelScale;
    }
 
    if (scale) {
      const { rowPixelSpacing } = image;
      viewport.scale = scale;
      viewport.parallelScale = (clientHeight * rowPixelSpacing * 0.5) / scale;
    }
 
    if (flipHorizontal !== undefined || flipVertical !== undefined) {
      this.setFlipCPU({ flipHorizontal, flipVertical });
    }
 
    // re-calculate the transforms
    this._cpuFallbackEnabledElement.transform = calculateTransform(
      this._cpuFallbackEnabledElement
    );
 
    const eventDetail: EventTypes.CameraModifiedEventDetail = {
      previousCamera,
      camera: this.getCamera(),
      element: this.element,
      viewportId: this.id,
      renderingEngineId: this.renderingEngineId,
      rotation: this.getRotation(),
    };
 
    triggerEvent(this.element, Events.CAMERA_MODIFIED, eventDetail);
  }
 
  private getPanCPU(): Point2 {
    const { viewport } = this._cpuFallbackEnabledElement;
 
    return [viewport.translation.x, viewport.translation.y];
  }
 
  private setPanCPU(pan: Point2): void {
    const camera = this.getCameraCPU();
 
    this.setCameraCPU({
      ...camera,
      focalPoint: [...pan.map((p) => -p), 0] as Point3,
    });
  }
 
  private getZoomCPU(): number {
    const { viewport } = this._cpuFallbackEnabledElement;
 
    return viewport.scale;
  }
 
  private setZoomCPU(zoom: number): void {
    const camera = this.getCameraCPU();
 
    this.setCameraCPU({ ...camera, scale: zoom });
  }
 
  private setFlipCPU({ flipHorizontal, flipVertical }: FlipDirection): void {
    const { viewport } = this._cpuFallbackEnabledElement;
 
    if (flipHorizontal !== undefined) {
      viewport.hflip = flipHorizontal;
      this.flipHorizontal = viewport.hflip;
    }
 
    if (flipVertical !== undefined) {
      viewport.vflip = flipVertical;
      this.flipVertical = viewport.vflip;
    }
  }
 
  private getRotationCPU = (): number => {
    const { viewport } = this._cpuFallbackEnabledElement;
    return viewport.rotation;
  };
 
  /**
   * Gets the rotation resulting from the value set in setRotation AND taking into
   * account any flips that occurred subsequently.
   *
   * @returns the rotation resulting from the value set in setRotation AND taking into
   * account any flips that occurred subsequently.
   */
  private getRotationGPU = (): number => {
    const {
      viewUp: currentViewUp,
      viewPlaneNormal,
      flipVertical,
    } = this.getCamera();
 
    // The initial view up vector without any rotation, but incorporating vertical flip.
    const initialViewUp = flipVertical
      ? vec3.negate(vec3.create(), this.initialViewUp)
      : this.initialViewUp;
 
    // The angle between the initial and current view up vectors.
    // TODO: check with VTK about rounding errors here.
    const initialToCurrentViewUpAngle =
      (vec3.angle(initialViewUp, currentViewUp) * 180) / Math.PI;
 
    // Now determine if initialToCurrentViewUpAngle is positive or negative by comparing
    // the direction of the initial/current view up cross product with the current
    // viewPlaneNormal.
 
    const initialToCurrentViewUpCross = vec3.cross(
      vec3.create(),
      initialViewUp,
      currentViewUp
    );
 
    // The sign of the dot product of the start/end view up cross product and
    // the viewPlaneNormal indicates a positive or negative rotation respectively.
    const normalDot = vec3.dot(initialToCurrentViewUpCross, viewPlaneNormal);
 
    return normalDot >= 0
      ? initialToCurrentViewUpAngle
      : (360 - initialToCurrentViewUpAngle) % 360;
  };
 
  protected setRotation = (rotation: number) => {
    const previousCamera = this.getCamera();
 
    this.useCPURendering
      ? this.setRotationCPU(rotation)
      : this.setRotationGPU(rotation);
 
    Iif (this._suppressCameraModifiedEvents) {
      return;
    }
 
    // New camera after rotation
    const camera = this.getCamera();
 
    const eventDetail: EventTypes.CameraModifiedEventDetail = {
      previousCamera,
      camera,
      element: this.element,
      viewportId: this.id,
      renderingEngineId: this.renderingEngineId,
      rotation,
    };
 
    triggerEvent(this.element, Events.CAMERA_MODIFIED, eventDetail);
  };
 
  private setVOILUTFunction(
    voiLUTFunction: VOILUTFunctionType,
    suppressEvents?: boolean
  ): void {
    if (this.useCPURendering) {
      throw new Error('VOI LUT function is not supported in CPU rendering');
    }
 
    // make sure the VOI LUT function is valid in the VOILUTFunctionType which is enum
    const newVOILUTFunction = this._getValidVOILUTFunction(voiLUTFunction);
 
    let forceRecreateLUTFunction = false;
    if (this.VOILUTFunction !== newVOILUTFunction) {
      forceRecreateLUTFunction = true;
    }
 
    this.VOILUTFunction = newVOILUTFunction;
 
    const { voiRange } = this.getProperties();
    this.setVOI(voiRange, { suppressEvents, forceRecreateLUTFunction });
  }
 
  private setRotationCPU(rotation: number): void {
    const { viewport } = this._cpuFallbackEnabledElement;
    viewport.rotation = rotation;
  }
 
  /**
   * The rotation that is being set is intended to be around the currently
   * display center of the image.  However, the roll operation does it around
   * another point which can result in the image disappearing.  The set/get
   * pan values move the center of rotation to the center of the image as
   * currently actually displayed.
   */
  private setRotationGPU(rotation: number): void {
    const panFit = this.getPan(this.fitToCanvasCamera);
    const pan = this.getPan();
    const panSub = vec2.sub([0, 0], panFit, pan) as Point2;
    this.setPan(panSub, false);
    const { flipVertical } = this.getCamera();
 
    // Moving back to zero rotation, for new scrolled slice rotation is 0 after camera reset
    const initialViewUp = flipVertical
      ? vec3.negate(vec3.create(), this.initialViewUp)
      : this.initialViewUp;
 
    this.setCameraNoEvent({
      viewUp: initialViewUp as Point3,
    });
 
    // rotating camera to the new value
    this.getVtkActiveCamera().roll(-rotation);
    const afterPan = this.getPan();
    const afterPanFit = this.getPan(this.fitToCanvasCamera);
    const newCenter = vec2.sub([0, 0], afterPan, afterPanFit);
    const newOffset = vec2.add([0, 0], panFit, newCenter) as Point2;
    this.setPan(newOffset, false);
  }
 
  private setInterpolationTypeGPU(interpolationType: InterpolationType): void {
    const defaultActor = this.getDefaultActor();
 
    Iif (!defaultActor) {
      return;
    }
 
    Iif (!isImageActor(defaultActor)) {
      return;
    }
    const { actor } = defaultActor;
    const volumeProperty = actor.getProperty();
 
    // @ts-ignore
    volumeProperty.setInterpolationType(interpolationType);
 
    this.interpolationType = interpolationType;
  }
 
  private setInterpolationTypeCPU(interpolationType: InterpolationType): void {
    const { viewport } = this._cpuFallbackEnabledElement;
 
    viewport.pixelReplication =
      interpolationType === InterpolationType.LINEAR ? false : true;
 
    this.interpolationType = interpolationType;
  }
 
  private setInvertColorCPU(invert: boolean): void {
    const { viewport } = this._cpuFallbackEnabledElement;
 
    if (!viewport) {
      return;
    }
 
    viewport.invert = invert;
    this.invert = invert;
  }
 
  private setInvertColorGPU(invert: boolean): void {
    const defaultActor = this.getDefaultActor();
 
    Iif (!defaultActor) {
      return;
    }
 
    Iif (!isImageActor(defaultActor)) {
      return;
    }
 
    // Duplicated logic to make sure typescript stops complaining
    // about vtkActor not having the correct property
    Iif (actorIsA(defaultActor, 'vtkVolume')) {
      const volumeActor = defaultActor.actor as VolumeActor;
      const tfunc = volumeActor.getProperty().getRGBTransferFunction(0);
 
      if ((!this.invert && invert) || (this.invert && !invert)) {
        invertRgbTransferFunction(tfunc);
      }
      this.invert = invert;
    } else Eif (actorIsA(defaultActor, 'vtkImageSlice')) {
      const imageSliceActor = defaultActor.actor as vtkImageSlice;
      const tfunc = imageSliceActor.getProperty().getRGBTransferFunction(0);
 
      if ((!this.invert && invert) || (this.invert && !invert)) {
        invertRgbTransferFunction(tfunc);
      }
 
      this.invert = invert;
    }
  }
 
  private setVOICPU(voiRange: VOIRange, options: SetVOIOptions = {}): void {
    const { suppressEvents = false } = options;
    // TODO: Account for VOILUTFunction
    const { viewport, image } = this._cpuFallbackEnabledElement;
 
    if (!viewport || !image) {
      return;
    }
 
    if (typeof voiRange === 'undefined') {
      const { windowWidth: ww, windowCenter: wc } = image;
 
      const wwToUse = Array.isArray(ww) ? ww[0] : ww;
      const wcToUse = Array.isArray(wc) ? wc[0] : wc;
      viewport.voi = {
        windowWidth: wwToUse,
        windowCenter: wcToUse,
      };
 
      const { lower, upper } = windowLevelUtil.toLowHighRange(wwToUse, wcToUse);
      voiRange = { lower, upper };
    } else {
      const { lower, upper } = voiRange;
      const { windowCenter, windowWidth } = windowLevelUtil.toWindowLevel(
        lower,
        upper
      );
 
      if (!viewport.voi) {
        viewport.voi = {
          windowWidth: 0,
          windowCenter: 0,
        };
      }
 
      viewport.voi.windowWidth = windowWidth;
      viewport.voi.windowCenter = windowCenter;
    }
 
    this.voiRange = voiRange;
    const eventDetail: VoiModifiedEventDetail = {
      viewportId: this.id,
      range: voiRange,
    };
 
    if (!suppressEvents) {
      triggerEvent(this.element, Events.VOI_MODIFIED, eventDetail);
    }
  }
 
  private getTransferFunction() {
    const defaultActor = this.getDefaultActor();
 
    Iif (!defaultActor) {
      return;
    }
 
    Iif (!isImageActor(defaultActor)) {
      return;
    }
    const imageActor = defaultActor.actor as ImageActor;
 
    return imageActor.getProperty().getRGBTransferFunction(0);
  }
 
  private setVOIGPU(voiRange: VOIRange, options: SetVOIOptions = {}): void {
    const {
      suppressEvents = false,
      forceRecreateLUTFunction = false,
      voiUpdatedWithSetProperties = false,
    } = options;
 
    if (
      voiRange &&
      this.voiRange &&
      this.voiRange.lower === voiRange.lower &&
      this.voiRange.upper === voiRange.upper &&
      !forceRecreateLUTFunction &&
      !this.stackInvalidated
    ) {
      return;
    }
 
    const defaultActor = this.getDefaultActor();
    Iif (!defaultActor) {
      return;
    }
 
    Iif (!isImageActor(defaultActor)) {
      return;
    }
    const imageActor = defaultActor.actor as ImageActor;
 
    let voiRangeToUse = voiRange;
 
    Iif (typeof voiRangeToUse === 'undefined') {
      const imageData = imageActor.getMapper().getInputData();
      const range = imageData.getPointData().getScalars().getRange();
      const maxVoiRange = { lower: range[0], upper: range[1] };
      voiRangeToUse = maxVoiRange;
    }
 
    // scaling logic here
    // https://github.com/Kitware/vtk-js/blob/master/Sources/Rendering/OpenGL/ImageMapper/index.js#L540-L549
    imageActor.getProperty().setUseLookupTableScalarRange(true);
 
    let transferFunction = imageActor.getProperty().getRGBTransferFunction(0);
 
    const isSigmoidTFun =
      this.VOILUTFunction === VOILUTFunctionType.SAMPLED_SIGMOID;
 
    // use the old cfun if it exists for linear case
    if (isSigmoidTFun || !transferFunction || forceRecreateLUTFunction) {
      const transferFunctionCreator = isSigmoidTFun
        ? createSigmoidRGBTransferFunction
        : createLinearRGBTransferFunction;
 
      transferFunction = transferFunctionCreator(voiRangeToUse);
 
      Iif (this.invert) {
        invertRgbTransferFunction(transferFunction);
      }
 
      imageActor.getProperty().setRGBTransferFunction(0, transferFunction);
      this.initialTransferFunctionNodes =
        getTransferFunctionNodes(transferFunction);
    }
 
    Eif (!isSigmoidTFun) {
      // @ts-ignore vtk type error
      transferFunction.setRange(voiRangeToUse.lower, voiRangeToUse.upper);
    }
 
    this.voiRange = voiRangeToUse;
 
    // if voiRange is set by setProperties we need to lock it if it is not locked already
    Eif (!this.voiUpdatedWithSetProperties) {
      this.voiUpdatedWithSetProperties = voiUpdatedWithSetProperties;
    }
 
    Iif (suppressEvents) {
      return;
    }
 
    const eventDetail: VoiModifiedEventDetail = {
      viewportId: this.id,
      range: voiRangeToUse,
      VOILUTFunction: this.VOILUTFunction,
    };
 
    triggerEvent(this.element, Events.VOI_MODIFIED, eventDetail);
  }
 
  /**
   * Adds scaling parameters to the viewport to be used along all slices
   *
   * @param imageIdScalingFactor - suvbw, suvlbm, suvbsa
   */
  private _addScalingToViewport(imageIdScalingFactor) {
    if (this.scaling.PT) {
      return;
    }
 
    // if don't exist
    // These ratios are constant across all frames, so only need one.
    const { suvbw, suvlbm, suvbsa } = imageIdScalingFactor;
 
    const ptScaling = <PTScaling>{};
 
    Eif (suvlbm) {
      ptScaling.suvbwToSuvlbm = suvlbm / suvbw;
    }
 
    Eif (suvbsa) {
      ptScaling.suvbwToSuvbsa = suvbsa / suvbw;
    }
 
    this.scaling.PT = ptScaling;
  }
 
  /**
   * Calculates number of components based on the dicom metadata
   *
   * @param photometricInterpretation - string dicom tag
   * @returns number representing number of components
   */
  private _getNumCompsFromPhotometricInterpretation(
    photometricInterpretation: string
  ): number {
    // TODO: this function will need to have more logic later
    // see http://dicom.nema.org/medical/Dicom/current/output/chtml/part03/sect_C.7.6.3.html#sect_C.7.6.3.1.2
    let numberOfComponents = 1;
    if (
      photometricInterpretation === 'RGB' ||
      photometricInterpretation.indexOf('YBR') !== -1 ||
      photometricInterpretation === 'PALETTE COLOR'
    ) {
      numberOfComponents = 3;
    }
 
    return numberOfComponents;
  }
 
  /**
   * Calculates image metadata based on the image object. It calculates normal
   * axis for the images, and output image metadata
   *
   * @param image - stack image containing cornerstone image
   * @returns image metadata: bitsAllocated, number of components, origin,
   *  direction, dimensions, spacing, number of voxels.
   */
  public getImageDataMetadata(image: IImage): ImageDataMetaData {
    // TODO: Creating a single image should probably not require a metadata provider.
    // We should define the minimum we need to display an image and it should live on
    // the Image object itself. Additional stuff (e.g. pixel spacing, direction, origin, etc)
    // should be optional and used if provided through a metadata provider.
 
    const { imagePlaneModule, imagePixelModule } = this.buildMetadata(image);
 
    let rowCosines, columnCosines;
 
    rowCosines = <Point3>imagePlaneModule.rowCosines;
    columnCosines = <Point3>imagePlaneModule.columnCosines;
 
    // if null or undefined
    Iif (rowCosines == null || columnCosines == null) {
      rowCosines = <Point3>[1, 0, 0];
      columnCosines = <Point3>[0, 1, 0];
    }
 
    const rowCosineVec = vec3.fromValues(
      rowCosines[0],
      rowCosines[1],
      rowCosines[2]
    );
    const colCosineVec = vec3.fromValues(
      columnCosines[0],
      columnCosines[1],
      columnCosines[2]
    );
    const scanAxisNormal = vec3.create();
    vec3.cross(scanAxisNormal, rowCosineVec, colCosineVec);
 
    let origin = imagePlaneModule.imagePositionPatient;
    // if null or undefined
    Iif (origin == null) {
      origin = [0, 0, 0];
    }
 
    const xSpacing =
      imagePlaneModule.columnPixelSpacing || image.columnPixelSpacing;
    const ySpacing = imagePlaneModule.rowPixelSpacing || image.rowPixelSpacing;
    const xVoxels = image.columns;
    const yVoxels = image.rows;
 
    // Note: For rendering purposes, we use the EPSILON as the z spacing.
    // This is purely for internal implementation logic since we are still
    // technically rendering 3D objects with vtk.js, but the abstracted intention
    //  of the stack viewport is to render 2D images
    const zSpacing = EPSILON;
    const zVoxels = 1;
 
    const numComps =
      image.numComps ||
      this._getNumCompsFromPhotometricInterpretation(
        imagePixelModule.photometricInterpretation
      );
 
    return {
      bitsAllocated: imagePixelModule.bitsAllocated,
      numComps,
      origin,
      direction: [...rowCosineVec, ...colCosineVec, ...scanAxisNormal] as Mat3,
      dimensions: [xVoxels, yVoxels, zVoxels],
      spacing: [xSpacing, ySpacing, zSpacing],
      numVoxels: xVoxels * yVoxels * zVoxels,
      imagePlaneModule,
      imagePixelModule,
    };
  }
 
  /**
   * Converts the image direction to camera viewUp and viewplaneNormal
   *
   * @param imageDataDirection - vtkImageData direction
   * @returns viewplane normal and viewUp of the camera
   */
  private _getCameraOrientation(imageDataDirection: Mat3): {
    viewPlaneNormal: Point3;
    viewUp: Point3;
  } {
    const viewPlaneNormal = imageDataDirection.slice(6, 9).map((x) => -x);
 
    const viewUp = imageDataDirection.slice(3, 6).map((x) => -x);
    return {
      viewPlaneNormal: [
        viewPlaneNormal[0],
        viewPlaneNormal[1],
        viewPlaneNormal[2],
      ],
      viewUp: [viewUp[0], viewUp[1], viewUp[2]],
    };
  }
 
  createVTKImageData({
    origin,
    direction,
    dimensions,
    spacing,
    numComps,
    pixelArray,
  }) {
    const values = new pixelArray.constructor(pixelArray.length);
 
    // Todo: I guess nothing should be done for use16bit?
    const scalarArray = vtkDataArray.newInstance({
      name: 'Pixels',
      numberOfComponents: numComps,
      values: values,
    });
 
    const imageData = vtkImageData.newInstance();
 
    imageData.setDimensions(dimensions);
    imageData.setSpacing(spacing);
    imageData.setDirection(direction);
    imageData.setOrigin(origin);
    imageData.getPointData().setScalars(scalarArray);
 
    return imageData;
  }
  /**
   * Creates vtkImagedata based on the image object, it creates
   * empty scalar data for the image based on the metadata
   * tags (e.g., bitsAllocated)
   *
   * @param image - cornerstone Image object
   */
  private _createVTKImageData({
    origin,
    direction,
    dimensions,
    spacing,
    numComps,
    pixelArray,
  }): void {
    this._imageData = this.createVTKImageData({
      origin,
      direction,
      dimensions,
      spacing,
      numComps,
      pixelArray,
    });
  }
 
  /**
   * Sets the imageIds to be visualized inside the stack viewport. It accepts
   * list of imageIds, the index of the first imageId to be viewed. It is a
   * asynchronous function that returns a promise resolving to imageId being
   * displayed in the stack viewport.
   *
   *
   * @param imageIds - list of strings, that represents list of image Ids
   * @param currentImageIdIndex - number representing the index of the initial image to be displayed
   */
  public async setStack(
    imageIds: Array<string>,
    currentImageIdIndex = 0
  ): Promise<string> {
    this._throwIfDestroyed();
 
    this.imageIds = imageIds;
    this.currentImageIdIndex = currentImageIdIndex;
    this.targetImageIdIndex = currentImageIdIndex;
    const imageRetrieveConfiguration = metaData.get(
      imageRetrieveMetadataProvider.IMAGE_RETRIEVE_CONFIGURATION,
      imageIds[currentImageIdIndex],
      'stack'
    );
 
    this.imagesLoader = imageRetrieveConfiguration
      ? (imageRetrieveConfiguration.create || createProgressive)(
          imageRetrieveConfiguration
        )
      : this;
 
    // reset the stack
    this.stackInvalidated = true;
    this.flipVertical = false;
    this.flipHorizontal = false;
    this.voiRange = null;
    this.interpolationType = InterpolationType.LINEAR;
    this.invert = false;
    this.viewportStatus = ViewportStatus.LOADING;
 
    this.fillWithBackgroundColor();
 
    if (this.useCPURendering) {
      this._cpuFallbackEnabledElement.renderingTools = {};
      delete this._cpuFallbackEnabledElement.viewport.colormap;
    }
 
    const imageId = await this._setImageIdIndex(currentImageIdIndex);
 
    const eventDetail: StackViewportNewStackEventDetail = {
      imageIds,
      viewportId: this.id,
      element: this.element,
      currentImageIdIndex: currentImageIdIndex,
    };
 
    triggerEvent(eventTarget, Events.STACK_VIEWPORT_NEW_STACK, eventDetail);
 
    return imageId;
  }
 
  /**
   * Throws an error if you are using a destroyed instance of the stack viewport
   */
  private _throwIfDestroyed() {
    Iif (this.isDisabled) {
      throw new Error(
        'The stack viewport has been destroyed and is no longer usable. Renderings will not be performed. If you ' +
          'are using the same viewportId and have re-enabled the viewport, you need to grab the new viewport instance ' +
          'using renderingEngine.getViewport(viewportId), instead of using your lexical scoped reference to the viewport instance.'
      );
    }
  }
 
  /**
   * It checks if the new image object matches the dimensions, spacing,
   * and direction of the previously displayed image in the viewport or not.
   * It returns a boolean
   *
   * @param image - Cornerstone Image object
   * @param imageData - vtkImageData
   * @returns boolean
   */
  private _checkVTKImageDataMatchesCornerstoneImage(
    image: IImage,
    imageData: vtkImageDataType
  ): boolean {
    if (!imageData) {
      return false;
    }
    const [xSpacing, ySpacing] = imageData.getSpacing();
    const [xVoxels, yVoxels] = imageData.getDimensions();
    const imagePlaneModule = this._getImagePlaneModule(image.imageId);
    const direction = imageData.getDirection();
    const rowCosines = direction.slice(0, 3);
    const columnCosines = direction.slice(3, 6);
    const dataType = imageData.getPointData().getScalars().getDataType();
 
    // using epsilon comparison for float numbers comparison.
    const isSameXSpacing = isEqual(xSpacing, image.columnPixelSpacing);
    const isSameYSpacing = isEqual(ySpacing, image.rowPixelSpacing);
 
    // using spacing, size, and direction only for now
    return (
      (isSameXSpacing ||
        (image.columnPixelSpacing === null && xSpacing === 1.0)) &&
      (isSameYSpacing ||
        (image.rowPixelSpacing === null && ySpacing === 1.0)) &&
      xVoxels === image.columns &&
      yVoxels === image.rows &&
      isEqual(imagePlaneModule.rowCosines, <Point3>rowCosines) &&
      isEqual(imagePlaneModule.columnCosines, <Point3>columnCosines) &&
      (!this.useNativeDataType ||
        dataType === image.getPixelData().constructor.name)
    );
  }
 
  /**
   * It Updates the vtkImageData of the viewport with the new pixel data
   * from the provided image object.
   *
   * @param image - Cornerstone Image object
   */
  private _updateVTKImageDataFromCornerstoneImage(image: IImage): void {
    const imagePlaneModule = this._getImagePlaneModule(image.imageId);
    let origin = imagePlaneModule.imagePositionPatient;
 
    Iif (origin == null) {
      origin = [0, 0, 0];
    }
 
    this._imageData.setOrigin(origin);
 
    // Update the pixel data in the vtkImageData object with the pixelData
    // from the loaded Cornerstone image
    updateVTKImageDataWithCornerstoneImage(this._imageData, image);
  }
 
  /**
   * It uses imageLoadPoolManager to add request for the imageId. It loadsAndCache
   * the image and triggers the STACK_NEW_IMAGE when the request successfully retrieves
   * the image. Next, the volume actor gets updated with the new new retrieved image.
   *
   * @param imageId - string representing the imageId
   * @param imageIdIndex - index of the imageId in the imageId list
   */
  private _loadAndDisplayImage(
    imageId: string,
    imageIdIndex: number
  ): Promise<string> {
    return this.useCPURendering
      ? this._loadAndDisplayImageCPU(imageId, imageIdIndex)
      : this._loadAndDisplayImageGPU(imageId, imageIdIndex);
  }
 
  private _loadAndDisplayImageCPU(
    imageId: string,
    imageIdIndex: number
  ): Promise<string> {
    return new Promise((resolve, reject) => {
      // 1. Load the image using the Image Loader
      function successCallback(
        image: IImage,
        imageIdIndex: number,
        imageId: string
      ) {
        // Perform this check after the image has finished loading
        // in case the user has already scrolled away to another image.
        // In that case, do not render this image.
        Iif (this.currentImageIdIndex !== imageIdIndex) {
          return;
        }
 
        const pixelData = image.getPixelData();
 
        // handle the case where the pixelData is a Float32Array
        // CPU path cannot handle it, it should be converted to Uint16Array
        // and via the Modality LUT we can display it properly
        const preScale = image.preScale;
        const scalingParams = preScale?.scalingParameters;
 
        const scaledWithNonIntegers =
          (preScale?.scaled && scalingParams?.rescaleIntercept % 1 !== 0) ||
          scalingParams?.rescaleSlope % 1 !== 0;
 
        Iif (pixelData instanceof Float32Array && scaledWithNonIntegers) {
          const floatMinMax = {
            min: image.maxPixelValue,
            max: image.minPixelValue,
          };
          const floatRange = Math.abs(floatMinMax.max - floatMinMax.min);
          const intRange = 65535;
          const slope = floatRange / intRange;
          const intercept = floatMinMax.min;
          const numPixels = pixelData.length;
          const intPixelData = new Uint16Array(numPixels);
 
          let min = 65535;
 
          let max = 0;
 
          for (let i = 0; i < numPixels; i++) {
            const rescaledPixel = Math.floor(
              (pixelData[i] - intercept) / slope
            );
 
            intPixelData[i] = rescaledPixel;
            min = Math.min(min, rescaledPixel);
            max = Math.max(max, rescaledPixel);
          }
 
          // reset the properties since basically the image has changed
          image.minPixelValue = min;
          image.maxPixelValue = max;
          image.slope = slope;
          image.intercept = intercept;
          image.getPixelData = () => intPixelData;
 
          image.preScale = {
            ...image.preScale,
            scaled: false,
          };
        }
 
        this._setCSImage(image);
        this.viewportStatus = ViewportStatus.PRE_RENDER;
 
        const eventDetail: EventTypes.StackNewImageEventDetail = {
          image,
          imageId,
          imageIdIndex,
          viewportId: this.id,
          renderingEngineId: this.renderingEngineId,
        };
 
        triggerEvent(this.element, Events.STACK_NEW_IMAGE, eventDetail);
 
        this._updateToDisplayImageCPU(image);
 
        // Todo: trigger an event to allow applications to hook into END of loading state
        // Currently we use loadHandlerManagers for this
 
        // Trigger the image to be drawn on the next animation frame
        this.render();
 
        // Update the viewport's currentImageIdIndex to reflect the newly
        // rendered image
        this.currentImageIdIndex = imageIdIndex;
        resolve(imageId);
      }
 
      function errorCallback(
        error: Error,
        imageIdIndex: number,
        imageId: string
      ) {
        const eventDetail = {
          error,
          imageIdIndex,
          imageId,
        };
 
        if (!this.suppressEvents) {
          triggerEvent(eventTarget, Events.IMAGE_LOAD_ERROR, eventDetail);
        }
 
        reject(error);
      }
 
      function sendRequest(imageId, imageIdIndex, options) {
        return loadAndCacheImage(imageId, options).then(
          (image) => {
            successCallback.call(this, image, imageIdIndex, imageId);
          },
          (error) => {
            errorCallback.call(this, error, imageIdIndex, imageId);
          }
        );
      }
 
      const priority = -5;
      const requestType = RequestType.Interaction;
      const additionalDetails = { imageId, imageIdIndex };
      const options = {
        preScale: {
          enabled: true,
        },
        useRGBA: true,
        requestType,
      };
 
      const eventDetail: EventTypes.PreStackNewImageEventDetail = {
        imageId,
        imageIdIndex,
        viewportId: this.id,
        renderingEngineId: this.renderingEngineId,
      };
      triggerEvent(this.element, Events.PRE_STACK_NEW_IMAGE, eventDetail);
 
      imageLoadPoolManager.addRequest(
        sendRequest.bind(this, imageId, imageIdIndex, options),
        requestType,
        additionalDetails,
        priority
      );
    });
  }
 
  public successCallback(imageId, image) {
    const imageIdIndex = this.imageIds.indexOf(imageId);
    // Todo: trigger an event to allow applications to hook into END of loading state
    // Currently we use loadHandlerManagers for this
    // Perform this check after the image has finished loading
    // in case the user has already scrolled away to another image.
    // In that case, do not render this image.
    Iif (this.currentImageIdIndex !== imageIdIndex) {
      return;
    }
 
    // If Photometric Interpretation is not the same for the next image we are trying to load
    // invalidate the stack to recreate the VTK imageData.  Get the PMI from
    // the base csImage if imageFrame isn't defined, which happens when the images
    // come from the volume
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const csImgFrame = (<any>this.csImage)?.imageFrame;
    const imgFrame = image?.imageFrame;
    const photometricInterpretation =
      csImgFrame?.photometricInterpretation ||
      this.csImage?.photometricInterpretation;
    const newPhotometricInterpretation =
      imgFrame?.photometricInterpretation || image?.photometricInterpretation;
 
    if (photometricInterpretation !== newPhotometricInterpretation) {
      this.stackInvalidated = true;
    }
 
    this._setCSImage(image);
 
    const eventDetail: EventTypes.StackNewImageEventDetail = {
      image,
      imageId,
      imageIdIndex,
      viewportId: this.id,
      renderingEngineId: this.renderingEngineId,
    };
 
    this._updateActorToDisplayImageId(image);
    triggerEvent(this.element, Events.STACK_NEW_IMAGE, eventDetail);
 
    // Trigger the image to be drawn on the next animation frame
    this.render();
 
    // Update the viewport's currentImageIdIndex to reflect the newly
    // rendered image
    this.currentImageIdIndex = imageIdIndex;
  }
 
  public errorCallback(imageId, permanent, error) {
    if (!permanent) {
      return;
    }
    const imageIdIndex = this.imageIds.indexOf(imageId);
    const eventDetail = {
      error,
      imageIdIndex,
      imageId,
    };
 
    triggerEvent(eventTarget, Events.IMAGE_LOAD_ERROR, eventDetail);
  }
 
  public getLoaderImageOptions(imageId: string) {
    const imageIdIndex = this.imageIds.indexOf(imageId);
    const { transferSyntaxUID } = metaData.get('transferSyntax', imageId) || {};
 
    /**
     * If use16bittexture is specified, the CSWIL will automatically choose the
     * array type when no targetBuffer is provided. When CSWIL is initialized,
     * the use16bit should match the settings of cornerstone3D (either preferSizeOverAccuracy
     * or norm16 textures need to be enabled)
     *
     * If use16bittexture is not specified, we force the Float32Array for now
     */
    const additionalDetails = { imageId, imageIdIndex };
    const options = {
      targetBuffer: {
        type: this.useNativeDataType ? undefined : 'Float32Array',
      },
      preScale: {
        enabled: true,
      },
      useRGBA: false,
      transferSyntaxUID,
      useNativeDataType: this.useNativeDataType,
      priority: 5,
      requestType: RequestType.Interaction,
      additionalDetails,
    };
    return options;
  }
 
  public async loadImages(
    imageIds: string[],
    listener: ImageLoadListener
  ): Promise<unknown> {
    const resultList = await Promise.allSettled(
      imageIds.map((imageId) => {
        const options = this.getLoaderImageOptions(
          imageId
        ) as ImageLoaderOptions;
 
        return loadAndCacheImage(imageId, options).then(
          (image) => {
            listener.successCallback(imageId, image);
            return imageId;
          },
          (error) => {
            listener.errorCallback(imageId, true, error);
            return imageId;
          }
        );
      })
    );
    const errorList = resultList.filter((item) => item.status === 'rejected');
    Iif (errorList && errorList.length) {
      const event = new CustomEvent(Events.IMAGE_LOAD_ERROR, {
        detail: errorList,
        cancelable: true,
      });
      eventTarget.dispatchEvent(event);
    }
    return resultList;
  }
 
  private _loadAndDisplayImageGPU(imageId: string, imageIdIndex: number) {
    const eventDetail: EventTypes.PreStackNewImageEventDetail = {
      imageId,
      imageIdIndex,
      viewportId: this.id,
      renderingEngineId: this.renderingEngineId,
    };
    triggerEvent(this.element, Events.PRE_STACK_NEW_IMAGE, eventDetail);
 
    return this.imagesLoader.loadImages([imageId], this).then((v) => {
      return imageId;
    });
  }
 
  /**
   * Renders the given Cornerstone image object in the viewport.
   * This method is intended to be used by utilities to render
   * an individual image, rather than by applications that want to display
   * a complete image stack. If you want to load and display a complete
   * image stack, use the setStack method instead of this one.
   *
   * The rendered image will appear in the viewport's element.
   * Use this method if you have other means of loading and the
   * cornerstone image object is already available.
   *
   * If you don't understand the difference between this method and
   * setStack, you probably want to use setStack.
   *
   * @param image - The Cornerstone image object to render.
   */
  public renderImageObject = (image) => {
    this._setCSImage(image);
 
    const renderFn = this.useCPURendering
      ? this._updateToDisplayImageCPU
      : this._updateActorToDisplayImageId;
 
    renderFn.call(this, image);
  };
 
  private _setCSImage = (image) => {
    image.isPreScaled = image.preScale?.scaled;
    this.csImage = image;
  };
 
  private _updateToDisplayImageCPU(image: IImage) {
    const metadata = this.getImageDataMetadata(image) as ImageDataMetaData;
 
    const viewport = getDefaultViewport(
      this.canvas,
      image,
      this.modality,
      this._cpuFallbackEnabledElement.viewport.colormap
    );
 
    const { windowCenter, windowWidth } = viewport.voi;
    this.voiRange = windowLevelUtil.toLowHighRange(windowWidth, windowCenter);
 
    this._cpuFallbackEnabledElement.image = image;
    this._cpuFallbackEnabledElement.metadata = {
      ...metadata,
    };
    this.cpuImagePixelData = image.getPixelData();
 
    const viewportSettingToUse = Object.assign(
      {},
      viewport,
      this._cpuFallbackEnabledElement.viewport
    );
 
    // Important: this.stackInvalidated is different than cpuRenderingInvalidated. The
    // former is being used to maintain the previous state of the viewport
    // in the same stack, the latter is used to trigger drawImageSync
    this._cpuFallbackEnabledElement.viewport = this.stackInvalidated
      ? viewport
      : viewportSettingToUse;
 
    // used the previous state of the viewport, then stackInvalidated is set to false
    this.stackInvalidated = false;
 
    // new viewport is set to the current viewport, then cpuRenderingInvalidated is set to true
    this.cpuRenderingInvalidated = true;
 
    this._cpuFallbackEnabledElement.transform = calculateTransform(
      this._cpuFallbackEnabledElement
    );
  }
 
  /**
   * This method is used to add images to the stack viewport.
   * It takes an array of stack inputs, each containing an imageId and an actor UID.
   * For each stack input, it retrieves the image from the cache and creates a VTK image data object.
   * It then creates an actor mapper for the image data and adds it to the list of actors.
   * Finally, it sets the actors for the stack viewport.
   *
   * @param  stackInputs - An array of stack inputs, each containing an image ID and an actor UID.
   */
  public async addImages(stackInputs: Array<IStackInput>): Promise<void> {
    const actors = this.getActors();
    stackInputs.forEach((stackInput) => {
      const image = cache.getImage(stackInput.imageId);
 
      const { origin, dimensions, direction, spacing, numComps } =
        this.getImageDataMetadata(image);
 
      const imagedata = this.createVTKImageData({
        origin,
        dimensions,
        direction,
        spacing,
        numComps,
        pixelArray: image.getPixelData(),
      });
 
      const imageActor = this.createActorMapper(imagedata);
      if (imageActor) {
        actors.push({ uid: stackInput.actorUID, actor: imageActor });
        if (stackInput.callback) {
          stackInput.callback({ imageActor, imageId: stackInput.imageId });
        }
      }
    });
    this.setActors(actors);
  }
 
  /**
   * It updates the volume actor with the retrieved cornerstone image.
   * It first checks if the new image has the same dimensions, spacings, and
   * dimensions of the previous one: 1) If yes, it updates the pixel data 2) if not,
   * it creates a whole new volume actor for the image.
   * Note: Camera gets reset for both situations. Therefore, each image renders at
   * its exact 3D location in the space, and both image and camera moves while scrolling.
   *
   * @param image - Cornerstone image
   * @returns
   */
  private _updateActorToDisplayImageId(image) {
    // This function should do the following:
    // - Get the existing actor's vtkImageData that is being used to render the current image and check if we can reuse the vtkImageData that is in place (i.e. do the image dimensions and data type match?)
    // - If we can reuse it, replace the scalar data under the hood
    // - If we cannot reuse it, create a new actor, remove the old one, and reset the camera
 
    // 2. Check if we can reuse the existing vtkImageData object, if one is present.
    const sameImageData = this._checkVTKImageDataMatchesCornerstoneImage(
      image,
      this._imageData
    );
 
    const activeCamera = this.getRenderer().getActiveCamera();
 
    // Cache camera props so we can trigger one camera changed event after
    // The full transition.
    const previousCameraProps = cloneDeep(this.getCamera());
    if (sameImageData && !this.stackInvalidated) {
      // 3a. If we can reuse it, replace the scalar data under the hood
      this._updateVTKImageDataFromCornerstoneImage(image);
 
      // Since the 3D location of the imageData is changing as we scroll, we need
      // to modify the camera position to render this properly. However, resetting
      // causes problem related to zoom and pan tools: upon rendering of a new slice
      // the pan and zoom will get reset. To solve this, 1) we store the camera
      // properties related to pan and zoom 2) reset the camera to correctly place
      // it in the space 3) restore the pan, zoom props.
      const cameraProps = this.getCamera();
 
      const panCache = vec3.subtract(
        vec3.create(),
        this.cameraFocalPointOnRender,
        cameraProps.focalPoint
      );
 
      // Reset the camera to point to the new slice location, reset camera doesn't
      // modify the direction of projection and viewUp
      this.resetCameraNoEvent();
 
      // set the flip and view up back to the previous value since the restore camera props
      // rely on the correct flip value
      this.setCameraNoEvent({
        flipHorizontal: previousCameraProps.flipHorizontal,
        flipVertical: previousCameraProps.flipVertical,
        viewUp: previousCameraProps.viewUp,
      });
 
      const { focalPoint } = this.getCamera();
      this.cameraFocalPointOnRender = focalPoint;
 
      // This is necessary to initialize the clipping range and it is not related
      // to our custom slabThickness.
      // @ts-ignore: vtkjs incorrect typing
      activeCamera.setFreezeFocalPoint(true);
 
      // We shouldn't restore the focalPoint, position and parallelScale after reset
      // if it is the first render or we have completely re-created the vtkImageData
      this._restoreCameraProps(
        cameraProps,
        previousCameraProps,
        panCache as Point3
      );
 
      this._setPropertiesFromCache();
      this.stackActorReInitialized = false;
 
      return;
    }
 
    const {
      origin,
      direction,
      dimensions,
      spacing,
      numComps,
      imagePixelModule,
    } = this.getImageDataMetadata(image);
 
    // 3b. If we cannot reuse the vtkImageData object (either the first render
    // or the size has changed), create a new one
 
    const pixelArray = image.getPixelData();
    this._createVTKImageData({
      origin,
      direction,
      dimensions,
      spacing,
      numComps,
      pixelArray,
    });
 
    // Set the scalar data of the vtkImageData object from the Cornerstone
    // Image's pixel data
    this._updateVTKImageDataFromCornerstoneImage(image);
 
    // Create a VTK Image Slice actor to display the vtkImageData object
    const actor = this.createActorMapper(this._imageData);
    const oldActors = this.getActors();
    if (oldActors.length && oldActors[0].uid === this.id) {
      oldActors[0].actor = actor;
    } else {
      oldActors.unshift({ uid: this.id, actor });
    }
    this.setActors(oldActors);
 
    // Adjusting the camera based on slice axis. this is required if stack
    // contains various image orientations (axial ct, sagittal xray)
    const { viewPlaneNormal, viewUp } = this._getCameraOrientation(direction);
 
    this.setCameraNoEvent({ viewUp, viewPlaneNormal });
 
    // Setting this makes the following comment about resetCameraNoEvent not modifying viewUp true.
    this.initialViewUp = viewUp;
 
    // Reset the camera to point to the new slice location, reset camera doesn't
    // modify the direction of projection and viewUp
    this.resetCameraNoEvent();
 
    this.triggerCameraEvent(this.getCamera(), previousCameraProps);
 
    // This is necessary to initialize the clipping range and it is not related
    // to our custom slabThickness.
    // @ts-ignore: vtkjs incorrect typing
    activeCamera.setFreezeFocalPoint(true);
 
    const monochrome1 =
      imagePixelModule.photometricInterpretation === 'MONOCHROME1';
 
    // invalidate the stack so that we can set the voi range
    this.stackInvalidated = true;
 
    this.setVOI(this._getInitialVOIRange(image), {
      forceRecreateLUTFunction: !!monochrome1,
    });
 
    this.initialInvert = !!monochrome1;
 
    // should carry over the invert color from the previous image if has been applied
    this.setInvertColor(this.invert || this.initialInvert);
 
    // Saving position of camera on render, to cache the panning
    this.cameraFocalPointOnRender = this.getCamera().focalPoint;
    this.stackInvalidated = false;
 
    this.stackActorReInitialized = true;
 
    if (this._publishCalibratedEvent) {
      this.triggerCalibrationEvent();
    }
  }
 
  private _getInitialVOIRange(image: IImage) {
    Iif (this.voiRange && this.voiUpdatedWithSetProperties) {
      return this.globalDefaultProperties.voiRange;
    }
    const { windowCenter, windowWidth } = image;
 
    let voiRange = this._getVOIRangeFromWindowLevel(windowWidth, windowCenter);
 
    // Get the range for the PT since if it is prescaled
    // we set a default range of 0-5
    voiRange = this._getPTPreScaledRange() || voiRange;
 
    return voiRange;
  }
 
  private _getPTPreScaledRange() {
    Eif (!this._isCurrentImagePTPrescaled()) {
      return undefined;
    }
 
    return this._getDefaultPTPrescaledVOIRange();
  }
 
  private _isCurrentImagePTPrescaled() {
    Eif (this.modality !== 'PT' || !this.csImage.isPreScaled) {
      return false;
    }
 
    if (!this.csImage.preScale?.scalingParameters?.suvbw) {
      return false;
    }
 
    return true;
  }
 
  private _getDefaultPTPrescaledVOIRange() {
    return { lower: 0, upper: 5 };
  }
 
  private _getVOIRangeFromWindowLevel(
    windowWidth: number | number[],
    windowCenter: number | number[]
  ): { lower: number; upper: number } | undefined {
    let center, width;
 
    if (typeof windowCenter === 'number' && typeof windowWidth === 'number') {
      center = windowCenter;
      width = windowWidth;
    } else Eif (Array.isArray(windowCenter) && Array.isArray(windowWidth)) {
      center = windowCenter[0];
      width = windowWidth[0];
    }
 
    // If center and width are defined, convert them to low-high range
    Eif (center !== undefined && width !== undefined) {
      return windowLevelUtil.toLowHighRange(width, center);
    }
  }
 
  /**
   * Loads the image based on the provided imageIdIndex
   * @param imageIdIndex - number represents imageId index
   */
  private async _setImageIdIndex(imageIdIndex: number): Promise<string> {
    Iif (imageIdIndex >= this.imageIds.length) {
      throw new Error(
        `ImageIdIndex provided ${imageIdIndex} is invalid, the stack only has ${this.imageIds.length} elements`
      );
    }
 
    // Update the state of the viewport to the new imageIdIndex;
    this.currentImageIdIndex = imageIdIndex;
    this.hasPixelSpacing = true;
    this.viewportStatus = ViewportStatus.PRE_RENDER;
 
    // Todo: trigger an event to allow applications to hook into START of loading state
    // Currently we use loadHandlerManagers for this
    const imageId = await this._loadAndDisplayImage(
      this.imageIds[imageIdIndex],
      imageIdIndex
    );
 
    //Check if there is any existing specific options for images if not we don't
    //want to re-render the viewport to its default properties
    Iif (this.perImageIdDefaultProperties.size >= 1) {
      const defaultProperties = this.perImageIdDefaultProperties.get(imageId);
      if (defaultProperties !== undefined) {
        this.setProperties(defaultProperties);
      } else if (this.globalDefaultProperties !== undefined) {
        this.setProperties(this.globalDefaultProperties);
      }
    }
 
    return imageId;
  }
 
  private resetCameraCPU(resetPan, resetZoom) {
    const { image } = this._cpuFallbackEnabledElement;
 
    Eif (!image) {
      return;
    }
 
    resetCamera(this._cpuFallbackEnabledElement, resetPan, resetZoom);
 
    const { scale } = this._cpuFallbackEnabledElement.viewport;
 
    // canvas center is the focal point
    const { clientWidth, clientHeight } = this.element;
    const center: Point2 = [clientWidth / 2, clientHeight / 2];
 
    const centerWorld = this.canvasToWorldCPU(center);
 
    this.setCameraCPU({
      focalPoint: centerWorld,
      scale,
    });
  }
 
  private resetCameraGPU(resetPan, resetZoom): boolean {
    // Todo: we need to make the rotation a camera properties so that
    // we can reset it there, right now it is not possible to reset the rotation
    // without this
 
    // We do not know the ordering of various flips and rotations that have been applied,
    // so the rotation and flip must be reset together.
    this.setCamera({
      flipHorizontal: false,
      flipVertical: false,
      viewUp: this.initialViewUp,
    });
 
    // For stack Viewport we since we have only one slice
    // it should be enough to reset the camera to the center of the image
    const resetToCenter = true;
    return super.resetCamera(resetPan, resetZoom, resetToCenter);
  }
 
  /**
   * It scrolls the stack of imageIds by the delta amount provided. If the debounce
   * flag is set, it will only scroll the stack if the delta is greater than the
   * debounceThreshold which is 40 milliseconds by default.
   * @param delta - number of indices to scroll, it can be positive or negative
   * @param debounce - whether to debounce the scroll event
   * @param loop - whether to loop the stack
   */
  public scroll(delta: number, debounce = true, loop = false): void {
    const imageIds = this.imageIds;
 
    const currentTargetImageIdIndex = this.targetImageIdIndex;
    const numberOfFrames = imageIds.length;
 
    let newTargetImageIdIndex = currentTargetImageIdIndex + delta;
    newTargetImageIdIndex = Math.max(0, newTargetImageIdIndex);
 
    Iif (loop) {
      newTargetImageIdIndex = newTargetImageIdIndex % numberOfFrames;
    } else {
      newTargetImageIdIndex = Math.min(
        numberOfFrames - 1,
        newTargetImageIdIndex
      );
    }
 
    this.targetImageIdIndex = newTargetImageIdIndex;
 
    const targetImageId = imageIds[newTargetImageIdIndex];
 
    const imageAlreadyLoaded = cache.isLoaded(targetImageId);
 
    // If image is already cached we want to scroll right away; however, if it is
    // not cached, we can debounce the scroll event to avoid firing multiple scroll
    // events for the images that might happen to be passing by (as a result of infinite
    // scrolling).
    if (imageAlreadyLoaded || !debounce) {
      this.setImageIdIndex(newTargetImageIdIndex);
    } else E{
      clearTimeout(this.debouncedTimeout);
      this.debouncedTimeout = window.setTimeout(() => {
        this.setImageIdIndex(newTargetImageIdIndex);
      }, 40);
    }
 
    const eventData: StackViewportScrollEventDetail = {
      newImageIdIndex: newTargetImageIdIndex,
      imageId: targetImageId,
      direction: delta,
    };
 
    Eif (newTargetImageIdIndex !== currentTargetImageIdIndex) {
      triggerEvent(this.element, Events.STACK_VIEWPORT_SCROLL, eventData);
    }
  }
 
  /**
   * Loads the image based on the provided imageIdIndex. It is an Async function which
   * returns a promise that resolves to the imageId.
   *
   * @param imageIdIndex - number represents imageId index in the list of
   * provided imageIds in setStack
   */
  public setImageIdIndex(imageIdIndex: number): Promise<string> {
    this._throwIfDestroyed();
 
    // If we are already on this imageId index, stop here
    Iif (this.currentImageIdIndex === imageIdIndex) {
      return Promise.resolve(this.getCurrentImageId());
    }
 
    // Otherwise, get the imageId and attempt to display it
    const imageIdPromise = this._setImageIdIndex(imageIdIndex);
 
    return imageIdPromise;
  }
 
  /**
   * Calibrates the image with new metadata that has been added for imageId. To calibrate
   * a viewport, you should add your calibration data manually to
   * calibratedPixelSpacingMetadataProvider and call viewport.calibrateSpacing
   * for it get applied.
   *
   * @param imageId - imageId to be calibrated
   */
  public calibrateSpacing(imageId: string): void {
    const imageIdIndex = this.getImageIds().indexOf(imageId);
    this.stackInvalidated = true;
    this._loadAndDisplayImage(imageId, imageIdIndex);
  }
 
  /**
   * Restores the camera props such zooming and panning after an image is
   * changed, if needed (after scroll)
   *
   * @param parallelScale - camera parallel scale
   */
  private _restoreCameraProps(
    { parallelScale: prevScale }: ICamera,
    previousCamera: ICamera,
    panCache: Point3
  ): void {
    const renderer = this.getRenderer();
 
    // get the focalPoint and position after the reset
    const { position, focalPoint } = this.getCamera();
 
    const newPosition = vec3.subtract(vec3.create(), position, panCache);
    const newFocal = vec3.subtract(vec3.create(), focalPoint, panCache);
 
    // Restoring previous state x,y and scale, keeping the new z
    // we need to break the flip operations since they also work on the
    // camera position and focal point
    this.setCameraNoEvent({
      parallelScale: prevScale,
      position: newPosition as Point3,
      focalPoint: newFocal as Point3,
    });
 
    const camera = this.getCamera();
 
    this.triggerCameraEvent(camera, previousCamera);
 
    // Invoking render
    const RESET_CAMERA_EVENT = {
      type: 'ResetCameraEvent',
      renderer,
    };
 
    renderer.invokeEvent(RESET_CAMERA_EVENT);
  }
 
  private triggerCameraEvent(camera: ICamera, previousCamera: ICamera) {
    // Finally emit event for the full camera change cause during load image.
    const eventDetail: EventTypes.CameraModifiedEventDetail = {
      previousCamera,
      camera,
      element: this.element,
      viewportId: this.id,
      renderingEngineId: this.renderingEngineId,
    };
 
    if (!this.suppressEvents) {
      // For crosshairs to adapt to new viewport size
      triggerEvent(this.element, Events.CAMERA_MODIFIED, eventDetail);
    }
  }
 
  private triggerCalibrationEvent() {
    // Update the indexToWorld and WorldToIndex for viewport
    const { imageData } = this.getImageData();
    // Finally emit event for the full camera change cause during load image.
    const eventDetail: EventTypes.ImageSpacingCalibratedEventDetail = {
      element: this.element,
      viewportId: this.id,
      renderingEngineId: this.renderingEngineId,
      imageId: this.getCurrentImageId(),
      // Todo: why do we need to pass imageData? isn't' indexToWorld and worldToIndex enough?
      imageData: imageData as vtkImageData,
      worldToIndex: imageData.getWorldToIndex() as mat4,
      ...this._calibrationEvent,
    };
 
    Eif (!this.suppressEvents) {
      // Let the tools know the image spacing has been calibrated
      triggerEvent(this.element, Events.IMAGE_SPACING_CALIBRATED, eventDetail);
    }
 
    this._publishCalibratedEvent = false;
  }
 
  private canvasToWorldCPU = (
    canvasPos: Point2,
    worldPos: Point3 = [0, 0, 0]
  ): Point3 => {
    Iif (!this._cpuFallbackEnabledElement.image) {
      return;
    }
    // compute the pixel coordinate in the image
    const [px, py] = canvasToPixel(this._cpuFallbackEnabledElement, canvasPos);
 
    // convert pixel coordinate to world coordinate
    const { origin, spacing, direction } = this.getImageData();
 
    // Calculate size of spacing vector in normal direction
    const iVector = direction.slice(0, 3) as Point3;
    const jVector = direction.slice(3, 6) as Point3;
 
    // Calculate the world coordinate of the pixel
    vec3.scaleAndAdd(worldPos, origin, iVector, px * spacing[0]);
    vec3.scaleAndAdd(worldPos, worldPos, jVector, py * spacing[1]);
 
    return worldPos;
  };
 
  private worldToCanvasCPU = (worldPos: Point3): Point2 => {
    // world to pixel
    const { spacing, direction, origin } = this.getImageData();
 
    const iVector = direction.slice(0, 3) as Point3;
    const jVector = direction.slice(3, 6) as Point3;
 
    const diff = vec3.subtract(vec3.create(), worldPos, origin);
 
    const worldPoint: Point2 = [
      vec3.dot(diff, iVector) / spacing[0],
      vec3.dot(diff, jVector) / spacing[1],
    ];
 
    // pixel to canvas
    const canvasPoint = pixelToCanvas(
      this._cpuFallbackEnabledElement,
      worldPoint
    );
    return canvasPoint;
  };
 
  private canvasToWorldGPU = (canvasPos: Point2): Point3 => {
    const renderer = this.getRenderer();
 
    // Temporary setting the clipping range to the distance and distance + 0.1
    // in order to calculate the transformations correctly.
    // This is similar to the vtkSlabCamera isPerformingCoordinateTransformations
    // You can read more about it here there.
    const vtkCamera = this.getVtkActiveCamera();
    const crange = vtkCamera.getClippingRange();
    const distance = vtkCamera.getDistance();
 
    vtkCamera.setClippingRange(distance, distance + 0.1);
 
    const offscreenMultiRenderWindow =
      this.getRenderingEngine().offscreenMultiRenderWindow;
    const openGLRenderWindow =
      offscreenMultiRenderWindow.getOpenGLRenderWindow();
    const size = openGLRenderWindow.getSize();
 
    const devicePixelRatio = window.devicePixelRatio || 1;
    const canvasPosWithDPR = [
      canvasPos[0] * devicePixelRatio,
      canvasPos[1] * devicePixelRatio,
    ];
    const displayCoord = [
      canvasPosWithDPR[0] + this.sx,
      canvasPosWithDPR[1] + this.sy,
    ];
 
    // The y axis display coordinates are inverted with respect to canvas coords
    displayCoord[1] = size[1] - displayCoord[1];
 
    const worldCoord = openGLRenderWindow.displayToWorld(
      displayCoord[0],
      displayCoord[1],
      0,
      renderer
    );
 
    // set clipping range back to original to be able
    vtkCamera.setClippingRange(crange[0], crange[1]);
 
    return [worldCoord[0], worldCoord[1], worldCoord[2]];
  };
 
  private worldToCanvasGPU = (worldPos: Point3): Point2 => {
    const renderer = this.getRenderer();
 
    // Temporary setting the clipping range to the distance and distance + 0.1
    // in order to calculate the transformations correctly.
    // This is similar to the vtkSlabCamera isPerformingCoordinateTransformations
    // You can read more about it here there.
    const vtkCamera = this.getVtkActiveCamera();
    const crange = vtkCamera.getClippingRange();
    const distance = vtkCamera.getDistance();
 
    vtkCamera.setClippingRange(distance, distance + 0.1);
 
    const offscreenMultiRenderWindow =
      this.getRenderingEngine().offscreenMultiRenderWindow;
    const openGLRenderWindow =
      offscreenMultiRenderWindow.getOpenGLRenderWindow();
    const size = openGLRenderWindow.getSize();
    const displayCoord = openGLRenderWindow.worldToDisplay(
      ...worldPos,
      renderer
    );
 
    // The y axis display coordinates are inverted with respect to canvas coords
    displayCoord[1] = size[1] - displayCoord[1];
 
    const canvasCoord = <Point2>[
      displayCoord[0] - this.sx,
      displayCoord[1] - this.sy,
    ];
 
    // set clipping range back to original to be able
    vtkCamera.setClippingRange(crange[0], crange[1]);
 
    const devicePixelRatio = window.devicePixelRatio || 1;
    const canvasCoordWithDPR = <Point2>[
      canvasCoord[0] / devicePixelRatio,
      canvasCoord[1] / devicePixelRatio,
    ];
 
    return canvasCoordWithDPR;
  };
 
  private _getVOIRangeForCurrentImage() {
    const { windowCenter, windowWidth } = this.csImage;
 
    return this._getVOIRangeFromWindowLevel(windowWidth, windowCenter);
  }
 
  private _getValidVOILUTFunction(voiLUTFunction: any) {
    Eif (Object.values(VOILUTFunctionType).indexOf(voiLUTFunction) === -1) {
      voiLUTFunction = VOILUTFunctionType.LINEAR;
    }
    return voiLUTFunction;
  }
 
  /**
   * Returns the index of the imageId being renderer
   *
   * @returns currently shown imageId index
   */
  public getCurrentImageIdIndex = (): number => {
    return this.currentImageIdIndex;
  };
 
  public getSliceIndex = (): number => {
    return this.currentImageIdIndex;
  };
 
  /**
   * Checks to see if this target is or could be shown in this viewport
   */
  public isReferenceViewable(
    viewRef: ViewReference,
    options: ReferenceCompatibleOptions = {}
  ): boolean {
    Iif (!super.isReferenceViewable(viewRef, options)) {
      return false;
    }
 
    let { imageURI } = options;
    const { referencedImageId, sliceIndex } = viewRef;
 
    Iif (viewRef.volumeId && !referencedImageId) {
      return options.asVolume === true;
    }
 
    let testIndex = this.getCurrentImageIdIndex();
    Iif (options.withNavigation && typeof sliceIndex === 'number') {
      testIndex = sliceIndex;
    }
    const imageId = this.imageIds[testIndex];
    Iif (!imageId) {
      return false;
    }
    if (!imageURI) {
      // Remove the dataLoader scheme since that can change
      const colonIndex = imageId.indexOf(':');
      imageURI = imageId.substring(colonIndex + 1);
    }
    return referencedImageId?.endsWith(imageURI);
  }
 
  /**
   * Gets a standard target to show this image instance.
   */
  public getViewReference(
    viewRefSpecifier: ViewReferenceSpecifier = {}
  ): ViewReference {
    const { sliceIndex: sliceIndex = this.currentImageIdIndex } =
      viewRefSpecifier;
    return {
      ...super.getViewReference(viewRefSpecifier),
      referencedImageId: `${this.imageIds[sliceIndex as number]}`,
      sliceIndex: sliceIndex,
    };
  }
 
  /**
   * Applies the view reference, which may navigate the slice index and apply
   * other camera modifications
   */
  public setView(viewRef?: ViewReference, viewPres?: ViewPresentation): void {
    const camera = this.getCamera();
    super.setView(viewRef, viewPres);
    if (viewRef) {
      const { viewPlaneNormal, sliceIndex } = viewRef;
      if (
        viewPlaneNormal &&
        !isEqual(viewPlaneNormal, camera.viewPlaneNormal)
      ) {
        return;
      }
      if (sliceIndex || sliceIndex === 0) {
        this.setImageIdIndex(sliceIndex as number);
      }
    }
  }
 
  public getReferenceId(specifier: ViewReferenceSpecifier = {}): string {
    const { sliceIndex: sliceIndex = this.currentImageIdIndex } = specifier;
    Iif (Array.isArray(sliceIndex)) {
      throw new Error('Use of slice ranges for stacks not supported');
    }
    return `imageId:${this.imageIds[sliceIndex]}`;
  }
 
  /**
   *
   * Returns the imageIdIndex that is targeted to be loaded, in case of debounced
   * loading (with scroll), the targetImageIdIndex is the latest imageId
   * index that is requested to be loaded but debounced.
   */
  public getTargetImageIdIndex = (): number => {
    return this.targetImageIdIndex;
  };
 
  /**
   * Returns the list of image Ids for the current viewport
   * @returns list of strings for image Ids
   */
  public getImageIds = (): Array<string> => {
    return this.imageIds;
  };
 
  /**
   * Returns the currently rendered imageId
   * @returns string for imageId
   */
  public getCurrentImageId = (): string => {
    return this.imageIds[this.currentImageIdIndex];
  };
 
  /**
   * Returns true if the viewport contains the given imageId
   * @param imageId - imageId
   * @returns boolean if imageId is in viewport
   */
  public hasImageId = (imageId: string): boolean => {
    return this.imageIds.includes(imageId);
  };
 
  /**
   * Returns true if the viewport contains the given imageURI (no data loader scheme)
   * @param imageURI - imageURI
   * @returns boolean if imageURI is in viewport
   */
  public hasImageURI = (imageURI: string): boolean => {
    const imageIds = this.imageIds;
    for (let i = 0; i < imageIds.length; i++) {
      Eif (imageIdToURI(imageIds[i]) === imageURI) {
        return true;
      }
    }
 
    return false;
  };
 
  private getCPUFallbackError(method: string): Error {
    return new Error(
      `method ${method} cannot be used during CPU Fallback mode`
    );
  }
 
  private fillWithBackgroundColor() {
    const renderingEngine = this.getRenderingEngine();
 
    Eif (renderingEngine) {
      renderingEngine.fillCanvasWithBackgroundColor(
        this.canvas,
        this.options.background
      );
    }
  }
 
  public customRenderViewportToCanvas = () => {
    Iif (!this.useCPURendering) {
      throw new Error(
        'Custom cpu rendering pipeline should only be hit in CPU rendering mode'
      );
    }
 
    if (this._cpuFallbackEnabledElement.image) {
      drawImageSync(
        this._cpuFallbackEnabledElement,
        this.cpuRenderingInvalidated
      );
      // reset flags
      this.cpuRenderingInvalidated = false;
    } else E{
      this.fillWithBackgroundColor();
    }
 
    return {
      canvas: this.canvas,
      element: this.element,
      viewportId: this.id,
      renderingEngineId: this.renderingEngineId,
      viewportStatus: this.viewportStatus,
    };
  };
 
  private unsetColormapCPU() {
    delete this._cpuFallbackEnabledElement.viewport.colormap;
    this._cpuFallbackEnabledElement.renderingTools = {};
 
    this.cpuRenderingInvalidated = true;
 
    this.fillWithBackgroundColor();
 
    this.render();
  }
 
  private setColormapCPU(colormapData: CPUFallbackColormapData) {
    this.colormap = colormapData;
    const colormap = getColormap(colormapData.name, colormapData);
 
    this._cpuFallbackEnabledElement.viewport.colormap = colormap;
    this._cpuFallbackEnabledElement.renderingTools = {};
 
    this.fillWithBackgroundColor();
    this.cpuRenderingInvalidated = true;
 
    this.render();
 
    const eventDetail = {
      viewportId: this.id,
      colormap: colormapData,
    };
    triggerEvent(this.element, Events.COLORMAP_MODIFIED, eventDetail);
  }
 
  private setColormapGPU(colormap: ColormapPublic) {
    const ActorEntry = this.getDefaultActor();
    const actor = ActorEntry.actor as ImageActor;
    const actorProp = actor.getProperty();
    const rgbTransferFunction = actorProp.getRGBTransferFunction();
 
    const colormapObj =
      colormapUtils.getColormap(colormap.name) ||
      vtkColorMaps.getPresetByName(colormap.name);
 
    Iif (!rgbTransferFunction) {
      const cfun = vtkColorTransferFunction.newInstance();
      cfun.applyColorMap(colormapObj);
      cfun.setMappingRange(this.voiRange.lower, this.voiRange.upper);
      actorProp.setRGBTransferFunction(0, cfun);
    } else {
      rgbTransferFunction.applyColorMap(colormapObj);
      rgbTransferFunction.setMappingRange(
        this.voiRange.lower,
        this.voiRange.upper
      );
      actorProp.setRGBTransferFunction(0, rgbTransferFunction);
    }
 
    this.colormap = colormap;
    this.render();
 
    const eventDetail = {
      viewportId: this.id,
      colormap,
    };
 
    triggerEvent(this.element, Events.COLORMAP_MODIFIED, eventDetail);
  }
 
  private unsetColormapGPU() {
    // TODO -> vtk has full colormaps which are piecewise and frankly better?
    // Do we really want a pre defined 256 color map just for the sake of harmonization?
    throw new Error('unsetColormapGPU not implemented.');
  }
 
  // create default values for imagePlaneModule if values are undefined
  private _getImagePlaneModule(imageId: string): ImagePlaneModule {
    const imagePlaneModule = metaData.get(MetadataModules.IMAGE_PLANE, imageId);
 
    this.calibration ||= imagePlaneModule.calibration;
    const newImagePlaneModule: ImagePlaneModule = {
      ...imagePlaneModule,
    };
 
    Iif (!newImagePlaneModule.columnPixelSpacing) {
      newImagePlaneModule.columnPixelSpacing = 1;
      this.hasPixelSpacing = this.calibration?.scale > 0;
    }
 
    Iif (!newImagePlaneModule.rowPixelSpacing) {
      newImagePlaneModule.rowPixelSpacing = 1;
      this.hasPixelSpacing = this.calibration?.scale > 0;
    }
 
    Iif (!newImagePlaneModule.columnCosines) {
      newImagePlaneModule.columnCosines = [0, 1, 0];
    }
 
    Iif (!newImagePlaneModule.rowCosines) {
      newImagePlaneModule.rowCosines = [1, 0, 0];
    }
 
    Iif (!newImagePlaneModule.imagePositionPatient) {
      newImagePlaneModule.imagePositionPatient = [0, 0, 0];
    }
 
    Iif (!newImagePlaneModule.imageOrientationPatient) {
      newImagePlaneModule.imageOrientationPatient = new Float32Array([
        1, 0, 0, 0, 1, 0,
      ]);
    }
 
    return newImagePlaneModule;
  }
 
  private renderingPipelineFunctions = {
    getImageData: {
      cpu: this.getImageDataCPU,
      gpu: this.getImageDataGPU,
    },
    setColormap: {
      cpu: this.setColormapCPU,
      gpu: this.setColormapGPU,
    },
    getCamera: {
      cpu: this.getCameraCPU,
      gpu: super.getCamera,
    },
    setCamera: {
      cpu: this.setCameraCPU,
      gpu: super.setCamera,
    },
    getPan: {
      cpu: this.getPanCPU,
      gpu: super.getPan,
    },
    setPan: {
      cpu: this.setPanCPU,
      gpu: super.setPan,
    },
    getZoom: {
      cpu: this.getZoomCPU,
      gpu: super.getZoom,
    },
    setZoom: {
      cpu: this.setZoomCPU,
      gpu: super.setZoom,
    },
    setVOI: {
      cpu: this.setVOICPU,
      gpu: this.setVOIGPU,
    },
    getRotation: {
      cpu: this.getRotationCPU,
      gpu: this.getRotationGPU,
    },
    setInterpolationType: {
      cpu: this.setInterpolationTypeCPU,
      gpu: this.setInterpolationTypeGPU,
    },
    setInvertColor: {
      cpu: this.setInvertColorCPU,
      gpu: this.setInvertColorGPU,
    },
    resetCamera: {
      cpu: (resetPan = true, resetZoom = true): boolean => {
        this.resetCameraCPU(resetPan, resetZoom);
        return true;
      },
      gpu: (resetPan = true, resetZoom = true): boolean => {
        this.resetCameraGPU(resetPan, resetZoom);
        return true;
      },
    },
    canvasToWorld: {
      cpu: this.canvasToWorldCPU,
      gpu: this.canvasToWorldGPU,
    },
    worldToCanvas: {
      cpu: this.worldToCanvasCPU,
      gpu: this.worldToCanvasGPU,
    },
    getRenderer: {
      cpu: () => this.getCPUFallbackError('getRenderer'),
      gpu: super.getRenderer,
    },
    getDefaultActor: {
      cpu: () => this.getCPUFallbackError('getDefaultActor'),
      gpu: super.getDefaultActor,
    },
    getActors: {
      cpu: () => this.getCPUFallbackError('getActors'),
      gpu: super.getActors,
    },
    getActor: {
      cpu: () => this.getCPUFallbackError('getActor'),
      gpu: super.getActor,
    },
    setActors: {
      cpu: () => this.getCPUFallbackError('setActors'),
      gpu: super.setActors,
    },
    addActors: {
      cpu: () => this.getCPUFallbackError('addActors'),
      gpu: super.addActors,
    },
    addActor: {
      cpu: () => this.getCPUFallbackError('addActor'),
      gpu: super.addActor,
    },
    removeAllActors: {
      cpu: () => this.getCPUFallbackError('removeAllActors'),
      gpu: super.removeAllActors,
    },
    unsetColormap: {
      cpu: this.unsetColormapCPU,
      gpu: this.unsetColormapGPU,
    },
  };
}
 
export default StackViewport;