All files / core/src/RenderingEngine BaseVolumeViewport.ts

48.28% Statements 323/669
32.74% Branches 111/339
53.33% Functions 48/90
48.03% Lines 318/662

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                                                                                                                                                                                      214x           214x           214x 214x     214x   214x   214x           214x   214x   214x 214x   214x   210x 210x   4x 4x               214x       12440x                                     678x 678x     678x 678x         678x 678x   678x 210x 210x         214x 214x     2558x   2558x       2558x   2558x 622x     1936x                                             214x       214x         214x                                                                                                                                                                                                                                                                                                                                                   24x   24x       24x   24x       24x   24x 24x   24x                               3980x   3980x       3980x   3980x       3980x 3980x                                                                               24x   24x       24x 24x   24x   24x           24x       24x                     24x 24x           24x 24x       24x     24x     214x 174x 174x 174x 174x 174x 174x     174x       174x         174x 174x 174x 174x 174x 174x   174x         174x   174x               174x       174x   174x                       24x 24x                                                       392x 392x 392x 392x   392x 392x                                                                                                                                                                                                                                                                                                                                                     170x     170x               170x 170x   170x       170x   170x       170x     170x             170x           170x 170x       170x 170x               170x                                                                                                                                                                                                                                                                             24x 24x                       24x           24x     24x     24x       24x 24x     24x       24x       24x       24x     24x                                                                                                                                                                                                     214x                                           214x 3572x 3572x                     3572x   3572x 3572x   3572x       3572x 3572x     3572x       3572x 3572x   3572x       3572x   3572x     3572x   3572x                                               214x 3596x   3596x       3596x 3596x   3596x 3596x 7300x 7300x     3596x   3596x 3596x   3596x 3596x   3596x                                 214x 214x   214x           214x   214x   214x 214x 214x     214x     214x   214x   214x                       214x 214x                 214x 214x   214x   214x         214x                                 170x   170x         170x   170x   170x 170x       170x   170x   170x             170x                 170x 170x                         170x   170x   170x                                                                                             384x   384x   384x 214x             11292x   11292x       11292x 7648x 7854x     7648x       7648x             3644x   3644x                     384x     384x                   384x                   214x         20998x     20998x       20998x             20998x           20998x               20998x     20998x       20998x                                       214x 45472x                     10080x                                                             2937x 2937x 622x     2315x   2315x 2315x     2315x       2315x 2315x   2315x   2315x                                                             2890x     2890x                       214x 214x   214x                         214x                                                                                         214x 10611x                                               10611x   10611x 10611x 10611x 10611x     10611x           10611x             10611x         10611x           10611x           10611x   10611x                   214x                                         214x                                               214x                                                                                                                 214x 21806x                                               21806x   21806x 21806x 21806x     21806x             21806x               21806x             21806x 21806x   21806x 21806x         21806x   21806x             118508x 118508x                                                 214x                                                                                                     678x 8x 8x                   670x 670x   670x       72x     598x 598x 598x                                                                                           1228x 1228x 1228x 1228x         1228x                                                         214x 96x   96x       96x   96x 96x           96x                   6513x 6513x     6513x   6513x 6513x     6513x                                               443x 443x 443x 443x       443x 443x       443x 443x 443x 443x     1329x 443x       384x                                               16x       214x   214x 856x           856x   856x         214x                                                    
import type vtkVolume from '@kitware/vtk.js/Rendering/Core/Volume';
import vtkColorTransferFunction from '@kitware/vtk.js/Rendering/Core/ColorTransferFunction';
import vtkColorMaps from '@kitware/vtk.js/Rendering/Core/ColorTransferFunction/ColorMaps';
import vtkPiecewiseFunction from '@kitware/vtk.js/Common/DataModel/PiecewiseFunction';
 
import { vec2, vec3 } from 'gl-matrix';
import type { mat4 } from 'gl-matrix';
import cache from '../cache/cache';
import {
  MPR_CAMERA_VALUES,
  RENDERING_DEFAULTS,
  VIEWPORT_PRESETS,
} from '../constants';
import type { BlendModes, InterpolationType, OrientationAxis } from '../enums';
import {
  Events,
  MetadataModules,
  ViewportStatus,
  VOILUTFunctionType,
} from '../enums';
import ViewportType from '../enums/ViewportType';
import eventTarget from '../eventTarget';
import { getShouldUseCPURendering } from '../init';
import type {
  ActorEntry,
  ColormapPublic,
  FlipDirection,
  IImageData,
  IVolumeInput,
  OrientationVectors,
  Point2,
  Point3,
  VOIRange,
  EventTypes,
  VolumeViewportProperties,
  ViewReferenceSpecifier,
  ReferenceCompatibleOptions,
  ViewReference,
  IVolumeViewport,
  ICamera,
} from '../types';
import type { VoiModifiedEventDetail } from '../types/EventTypes';
import type { PlaneRestriction, ViewportInput } from '../types/IViewport';
import triggerEvent from '../utilities/triggerEvent';
import * as colormapUtils from '../utilities/colormap';
import invertRgbTransferFunction from '../utilities/invertRgbTransferFunction';
import createSigmoidRGBTransferFunction from '../utilities/createSigmoidRGBTransferFunction';
import transformWorldToIndex from '../utilities/transformWorldToIndex';
import {
  findMatchingColormap,
  updateOpacity as colormapUpdateOpacity,
  updateThreshold as colormapUpdateThreshold,
  getThresholdValue,
  getMaxOpacity,
} from '../utilities/colormap';
import { getTransferFunctionNodes } from '../utilities/transferFunctionUtils';
import type { TransferFunctionNodes } from '../types/ITransferFunctionNode';
import type vtkCamera from '@kitware/vtk.js/Rendering/Core/Camera';
 
import createVolumeActor from './helpers/createVolumeActor';
import volumeNewImageEventDispatcher, {
  resetVolumeNewImageState,
} from './helpers/volumeNewImageEventDispatcher';
import Viewport from './Viewport';
import type { vtkSlabCamera as vtkSlabCameraType } from './vtkClasses/vtkSlabCamera';
import vtkSlabCamera from './vtkClasses/vtkSlabCamera';
import getVolumeViewportScrollInfo from '../utilities/getVolumeViewportScrollInfo';
import { actorIsA, isImageActor } from '../utilities/actorCheck';
import snapFocalPointToSlice from '../utilities/snapFocalPointToSlice';
import getVoiFromSigmoidRGBTransferFunction from '../utilities/getVoiFromSigmoidRGBTransferFunction';
import isEqual, { isEqualAbs, isEqualNegative } from '../utilities/isEqual';
import applyPreset from '../utilities/applyPreset';
import imageIdToURI from '../utilities/imageIdToURI';
import uuidv4 from '../utilities/uuidv4';
import * as metaData from '../metaData';
import { getCameraVectors } from './helpers/getCameraVectors';
import { isContextPoolRenderingEngine } from './helpers/isContextPoolRenderingEngine';
import type vtkRenderer from '@kitware/vtk.js/Rendering/Core/Renderer';
import mprCameraValues from '../constants/mprCameraValues';
import { setConfiguration, getConfiguration } from '@cornerstonejs/core';
import type { Types } from '@cornerstonejs/core';
/**
 * Abstract base class for volume viewports. VolumeViewports are used to render
 * 3D volumes from which various orientations can be viewed. Since VolumeViewports
 * use SharedVolumeMappers behind the scene, memory footprint of visualizations
 * of the same volume in different orientations is very small.
 *
 * For setting volumes on viewports you need to use addVolumesToViewports
 * which will add volumes to the specified viewports.
 */
abstract class BaseVolumeViewport extends Viewport {
  useCPURendering = false;
  private _FrameOfReferenceUID: string;
 
  protected initialTransferFunctionNodes: TransferFunctionNodes;
  // Viewport Properties
  private globalDefaultProperties: VolumeViewportProperties;
  private perVolumeIdDefaultProperties = new Map<
    string,
    VolumeViewportProperties
  >();
  // Camera properties
  protected initialViewUp: Point3;
  protected viewportProperties: VolumeViewportProperties = {};
  private volumeIds = new Set<string>();
 
  constructor(props: ViewportInput) {
    super(props);
 
    this.useCPURendering = getShouldUseCPURendering();
 
    Iif (this.useCPURendering) {
      throw new Error(
        'VolumeViewports cannot be used whilst CPU Fallback Rendering is enabled.'
      );
    }
 
    this._configureRenderingPipeline();
 
    const renderer = this.getRenderer();
 
    const camera = vtkSlabCamera.newInstance();
    renderer.setActiveCamera(camera as unknown as vtkCamera);
 
    switch (this.type) {
      case ViewportType.ORTHOGRAPHIC:
        camera.setParallelProjection(true);
        break;
      case ViewportType.VOLUME_3D:
        camera.setParallelProjection(true);
        break;
      case ViewportType.PERSPECTIVE:
        camera.setParallelProjection(false);
        break;
      default:
        throw new Error(`Unrecognized viewport type: ${this.type}`);
    }
 
    this.initializeVolumeNewImageEventDispatcher();
  }
 
  static get useCustomRenderingPipeline(): boolean {
    return false;
  }
 
  public getSliceViewInfo(): {
    width: number;
    height: number;
    sliceIndex: number;
    slicePlane: number;
    sliceToIndexMatrix: mat4;
    indexToSliceMatrix: mat4;
  } {
    throw new Error('Method not implemented.');
  }
 
  protected applyViewOrientation(
    orientation: OrientationAxis | OrientationVectors,
    resetCamera = true
  ) {
    const { viewPlaneNormal, viewUp } =
      this._getOrientationVectors(orientation) || {};
    Iif (!viewPlaneNormal || !viewUp) {
      return;
    }
    const camera = this.getVtkActiveCamera();
    camera.setDirectionOfProjection(
      -viewPlaneNormal[0],
      -viewPlaneNormal[1],
      -viewPlaneNormal[2]
    );
    camera.setViewUpFrom(viewUp);
    this.initialViewUp = viewUp;
 
    if (resetCamera) {
      const t = this as unknown as IVolumeViewport;
      t.resetCamera({ resetOrientation: false, resetRotation: false });
    }
  }
 
  private initializeVolumeNewImageEventDispatcher(): void {
    const volumeNewImageHandlerBound = volumeNewImageHandler.bind(this);
    const volumeNewImageCleanUpBound = volumeNewImageCleanUp.bind(this);
 
    function volumeNewImageHandler(cameraEvent) {
      const { viewportId } = cameraEvent.detail;
 
      Iif (viewportId !== this.id || this.isDisabled) {
        return;
      }
 
      const viewportImageData = this.getImageData();
 
      if (!viewportImageData) {
        return;
      }
 
      volumeNewImageEventDispatcher(cameraEvent);
    }
 
    function volumeNewImageCleanUp(evt) {
      const { viewportId } = evt.detail;
 
      if (viewportId !== this.id) {
        return;
      }
 
      this.element.removeEventListener(
        Events.CAMERA_MODIFIED,
        volumeNewImageHandlerBound
      );
 
      eventTarget.removeEventListener(
        Events.ELEMENT_DISABLED,
        volumeNewImageCleanUpBound
      );
 
      resetVolumeNewImageState(viewportId);
    }
 
    this.element.removeEventListener(
      Events.CAMERA_MODIFIED,
      volumeNewImageHandlerBound
    );
    this.element.addEventListener(
      Events.CAMERA_MODIFIED,
      volumeNewImageHandlerBound
    );
 
    eventTarget.addEventListener(
      Events.ELEMENT_DISABLED,
      volumeNewImageCleanUpBound
    );
  }
 
  /**
   * Sets the properties for the volume viewport on the volume
   * Sets the VOILUTFunction property for the volume viewport on the volume
   *
   * @param VOILUTFunction - Sets the voi mode (LINEAR or SAMPLED_SIGMOID)
   * @param volumeId - The volume id to set the properties for (if `undefined`, the first volume)
   * @param suppressEvents - If `true`, the viewport will not emit events
   */
  private setVOILUTFunction(
    voiLUTFunction: VOILUTFunctionType,
    volumeId?: string,
    suppressEvents?: boolean
  ): void {
    // make sure the VOI LUT function is valid in the VOILUTFunctionType which is enum
    if (!Object.values(VOILUTFunctionType).includes(voiLUTFunction)) {
      voiLUTFunction = VOILUTFunctionType.LINEAR;
    }
    const { voiRange } = this.getProperties();
    this.setVOI(voiRange, volumeId, suppressEvents);
    this.viewportProperties.VOILUTFunction = voiLUTFunction;
  }
 
  /**
   * Sets the colormap for the volume with the given ID and optionally suppresses events.
   *
   * @param colormap - The colormap to apply (e.g., "hsv").
   * @param volumeId - The ID of the volume to set the colormap for.
   * @param suppressEvents - If `true`, events will not be emitted during the colormap a
   *
   * @returns void
   */
  private setColormap(
    colormap: ColormapPublic,
    volumeId: string,
    suppressEvents?: boolean
  ) {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
    if (!applicableVolumeActorInfo) {
      return;
    }
 
    const { volumeActor } = applicableVolumeActorInfo;
 
    const cfun = vtkColorTransferFunction.newInstance();
    let colormapObj = colormapUtils.getColormap(colormap.name);
 
    const { name } = colormap;
 
    if (!colormapObj) {
      colormapObj = vtkColorMaps.getPresetByName(name);
    }
 
    if (!colormapObj) {
      throw new Error(`Colormap ${colormap} not found`);
    }
 
    const range = volumeActor
      .getProperty()
      .getRGBTransferFunction(0)
      .getRange();
 
    cfun.applyColorMap(colormapObj);
    cfun.setMappingRange(range[0], range[1]);
    volumeActor.getProperty().setRGBTransferFunction(0, cfun);
 
    // This configures the viewport to use the most recently applied colormap.
    // However, this approach is not optimal when dealing with two volumes, as it prevents retrieval of the
    // colormap for Volume A if Volume B's colormap was the last one applied.
    this.viewportProperties.colormap = colormap;
 
    if (!suppressEvents) {
      const completeColormap = this.getColormap(volumeId);
 
      const eventDetail = {
        viewportId: this.id,
        colormap: completeColormap,
        volumeId,
      };
      triggerEvent(this.element, Events.VOI_MODIFIED, eventDetail);
      triggerEvent(this.element, Events.COLORMAP_MODIFIED, eventDetail);
    }
  }
 
  /**
   * Sets the opacity for the volume with the given ID.
   *
   * @param colormap - An object containing opacity that can be a number or an array of OpacityMapping
   * @param volumeId - The ID of the volume to set the opacity for.
   *
   * @returns void
   */
  private setOpacity(colormap: ColormapPublic, volumeId: string) {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
    if (!applicableVolumeActorInfo) {
      return;
    }
    const { volumeActor } = applicableVolumeActorInfo;
 
    const ofun = vtkPiecewiseFunction.newInstance();
    if (typeof colormap.opacity === 'number') {
      // Use the new utility to update opacity while preserving threshold
      colormapUpdateOpacity(volumeActor, colormap.opacity);
    } else {
      colormap.opacity.forEach(({ opacity, value }) => {
        ofun.addPoint(value, opacity);
      });
      volumeActor.getProperty().setScalarOpacity(0, ofun);
    }
 
    if (!this.viewportProperties.colormap) {
      this.viewportProperties.colormap = {};
    }
 
    this.viewportProperties.colormap.opacity = colormap.opacity;
 
    const matchedColormap = this.getColormap(volumeId);
    const eventDetail = {
      viewportId: this.id,
      colormap: matchedColormap,
      volumeId,
    };
    triggerEvent(this.element, Events.COLORMAP_MODIFIED, eventDetail);
  }
 
  /**
   * Sets the inversion for the volume transfer function
   *
   * @param inverted - Should the transfer function be inverted?
   * @param volumeId - volumeId
   * @param suppressEvents - If `true`, events will not be published
   *
   * @returns void
   */
  private setInvert(
    inverted: boolean,
    volumeId?: string,
    suppressEvents?: boolean
  ) {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
 
    if (!applicableVolumeActorInfo) {
      return;
    }
 
    const volumeIdToUse = applicableVolumeActorInfo.volumeId;
 
    const cfun = this._getOrCreateColorTransferFunction(volumeIdToUse);
    invertRgbTransferFunction(cfun);
 
    this.viewportProperties.invert = inverted;
 
    if (!suppressEvents) {
      const eventDetail: VoiModifiedEventDetail = {
        ...this.getVOIModifiedEventDetail(volumeIdToUse),
        invertStateChanged: true,
      };
 
      triggerEvent(this.element, Events.VOI_MODIFIED, eventDetail);
    }
  }
 
  protected getVOIModifiedEventDetail(
    volumeId: string
  ): VoiModifiedEventDetail {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
 
    Iif (!applicableVolumeActorInfo) {
      throw new Error(`No actor found for the given volumeId: ${volumeId}`);
    }
 
    const volumeActor = applicableVolumeActorInfo.volumeActor;
 
    const transferFunction = volumeActor
      .getProperty()
      .getRGBTransferFunction(0);
 
    const range = transferFunction.getMappingRange();
 
    const matchedColormap = this.getColormap(volumeId);
    const { VOILUTFunction, invert } = this.getProperties(volumeId);
 
    return {
      viewportId: this.id,
      range: {
        lower: range[0],
        upper: range[1],
      },
      volumeId: applicableVolumeActorInfo.volumeId,
      VOILUTFunction: VOILUTFunction,
      colormap: matchedColormap,
      invert,
    };
  }
 
  private _getOrCreateColorTransferFunction(
    volumeId?: string
  ): vtkColorTransferFunction {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
 
    Iif (!applicableVolumeActorInfo) {
      return null;
    }
 
    const { volumeActor } = applicableVolumeActorInfo;
 
    const rgbTransferFunction = volumeActor
      .getProperty()
      .getRGBTransferFunction(0);
 
    Eif (rgbTransferFunction) {
      return rgbTransferFunction;
    }
 
    const newRGBTransferFunction = vtkColorTransferFunction.newInstance();
    volumeActor.getProperty().setRGBTransferFunction(0, newRGBTransferFunction);
 
    return newRGBTransferFunction;
  }
 
  protected setInterpolationType(
    interpolationType: InterpolationType,
    volumeId?: string
  ) {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
 
    if (!applicableVolumeActorInfo) {
      return;
    }
 
    const { volumeActor } = applicableVolumeActorInfo;
    const volumeProperty = volumeActor.getProperty();
 
    // @ts-ignore
    volumeProperty.setInterpolationType(interpolationType);
    this.viewportProperties.interpolationType = interpolationType;
  }
 
  /**
   * Sets the properties for the volume viewport on the volume
   * (if fusion, it sets it for the first volume in the fusion)
   *
   * @param voiRange - Sets the lower and upper voi
   * @param volumeId - The volume id to set the properties for (if undefined, the first volume)
   * @param suppressEvents - If true, the viewport will not emit events
   */
  private setVOI(
    voiRange: VOIRange,
    volumeId?: string,
    suppressEvents = false
  ): void {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
 
    Iif (!applicableVolumeActorInfo) {
      return;
    }
 
    const { volumeActor } = applicableVolumeActorInfo;
    const volumeIdToUse = applicableVolumeActorInfo.volumeId;
 
    const voiRangeToUse = voiRange;
    // Todo: not sure why this is needed, in the new model this will not work for sure
    Iif (typeof voiRangeToUse === 'undefined') {
      throw new Error(
        'voiRangeToUse is undefined, need to implement this in the new volume model'
      );
    }
 
    const { VOILUTFunction } = this.getProperties(volumeIdToUse);
 
    // scaling logic here
    // https://github.com/Kitware/vtk-js/blob/c6f2e12cddfe5c0386a73f0793eb6d9ab20d573e/Sources/Rendering/OpenGL/VolumeMapper/index.js#L957-L972
    Iif (VOILUTFunction === VOILUTFunctionType.SAMPLED_SIGMOID) {
      const cfun = createSigmoidRGBTransferFunction(voiRangeToUse);
      volumeActor.getProperty().setRGBTransferFunction(0, cfun);
    } else {
      // TODO: refactor and make it work for PET series (inverted/colormap)
      // const cfun = createLinearRGBTransferFunction(voiRangeToUse);
      // volumeActor.getProperty().setRGBTransferFunction(0, cfun);
 
      // Todo: Moving from LINEAR to SIGMOID and back to LINEAR will not
      // work until we implement it in a different way because the
      // LINEAR transfer function is not recreated.
      const { lower, upper } = voiRangeToUse;
      volumeActor
        .getProperty()
        .getRGBTransferFunction(0)
        .setRange(lower, upper);
    }
 
    Eif (!suppressEvents) {
      const eventDetail: VoiModifiedEventDetail = {
        ...this.getVOIModifiedEventDetail(volumeIdToUse),
      };
 
      triggerEvent(this.element, Events.VOI_MODIFIED, eventDetail);
    }
 
    this.viewportProperties.voiRange = voiRangeToUse;
  }
 
  protected setRotation = (rotation: number) => {
    const panFit = this.getPan(this.fitToCanvasCamera);
    const pan = this.getPan();
    const previousCamera = this.getCamera();
    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([0, 0, 0], this.initialViewUp)
      : this.initialViewUp;
 
    this.setCameraNoEvent({
      viewUp: initialViewUp as Point3,
    });
 
    // rotating camera to the new value
    this.rotateCamera(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);
 
    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,
    };
 
    triggerEvent(this.element, Events.CAMERA_MODIFIED, eventDetail);
  };
 
  private rotateCamera(rotation: number): void {
    const rotationToApply = rotation - this.getRotation();
    // rotating camera to the new value
    this.getVtkActiveCamera().roll(-rotationToApply);
  }
 
  /**
   * Update the default properties for the volume viewport on the volume
   * @param ViewportProperties - The properties to set
   * @param volumeId - The volume id to set the default properties for (if `undefined`, we set the global default viewport properties)
   */
  public setDefaultProperties(
    ViewportProperties: VolumeViewportProperties,
    volumeId?: string
  ): void {
    if (volumeId == null) {
      this.globalDefaultProperties = ViewportProperties;
    } else E{
      this.perVolumeIdDefaultProperties.set(volumeId, ViewportProperties);
    }
  }
 
  /**
   * Remove the global default properties of the viewport or remove default properties for a volumeId if specified
   * @param volumeId If given, we remove the default properties only for this volumeId, if not
   * the global default properties will be removed
   */
  public clearDefaultProperties(volumeId?: string): void {
    if (volumeId == null) {
      this.globalDefaultProperties = {};
      this.resetProperties();
    } else {
      this.perVolumeIdDefaultProperties.delete(volumeId);
      this.resetToDefaultProperties(volumeId);
    }
  }
 
  /**
   * Gets a view target, allowing comparison between view positions as well
   * as restoring views later.
   */
  public getViewReference(
    viewRefSpecifier: ViewReferenceSpecifier = {}
  ): ViewReference {
    const target = super.getViewReference(viewRefSpecifier);
    const volumeId = this.getVolumeId(viewRefSpecifier);
    Eif (viewRefSpecifier?.forFrameOfReference !== false) {
      target.volumeId = volumeId;
    }
    Eif (typeof viewRefSpecifier?.sliceIndex !== 'number') {
      return target;
    }
    const { viewPlaneNormal } = target;
    const delta = viewRefSpecifier?.sliceIndex - this.getSliceIndex();
    // Calculate a camera focal point and position
    const { sliceRangeInfo } = getVolumeViewportScrollInfo(
      this as unknown as IVolumeViewport,
      volumeId,
      true
    );
 
    const { sliceRange, spacingInNormalDirection, camera } = sliceRangeInfo;
    const { focalPoint, position } = camera;
    const { newFocalPoint } = snapFocalPointToSlice(
      focalPoint,
      position,
      sliceRange,
      viewPlaneNormal,
      spacingInNormalDirection,
      delta
    );
    target.cameraFocalPoint = newFocalPoint;
 
    return target;
  }
 
  /**
   * Find out if this viewport would show this view
   *
   * @param options - allows specifying whether the view COULD display this with
   *                  some modification - either navigation or displaying as volume.
   * @returns true if the target is compatible with this view
   */
  public isReferenceViewable(
    viewRef: ViewReference,
    options?: ReferenceCompatibleOptions
  ): boolean {
    if (!viewRef.FrameOfReferenceUID) {
      return false;
    }
    if (!super.isReferenceViewable(viewRef, options)) {
      return false;
    }
    if (options?.withNavigation) {
      const { referencedImageId } = viewRef;
      return !referencedImageId || this.hasImageURI(referencedImageId);
    }
    const currentSliceIndex = this.getSliceIndex();
    const { sliceIndex } = viewRef;
    if (Array.isArray(sliceIndex)) {
      return (
        sliceIndex[0] <= currentSliceIndex && currentSliceIndex <= sliceIndex[1]
      );
    }
    return sliceIndex === undefined || sliceIndex === currentSliceIndex;
  }
 
  /**
   * Scrolls the viewport in the given direction/amount
   */
  public scroll(delta = 1) {
    const volumeId = this.getVolumeId();
    const { sliceRangeInfo } = getVolumeViewportScrollInfo(
      this as unknown as IVolumeViewport,
      volumeId,
      true
    );
 
    if (!sliceRangeInfo) {
      return;
    }
 
    const { sliceRange, spacingInNormalDirection, camera } = sliceRangeInfo;
    const { focalPoint, viewPlaneNormal, position } = camera;
 
    const { newFocalPoint, newPosition } = snapFocalPointToSlice(
      focalPoint,
      position,
      sliceRange,
      viewPlaneNormal,
      spacingInNormalDirection,
      delta
    );
 
    this.setCamera({
      focalPoint: newFocalPoint,
      position: newPosition,
    });
    this.render();
  }
 
  abstract isInAcquisitionPlane(): boolean;
 
  /**
   * This will apply a camera orientation that is compatible with inPlaneVector1 and 2
   *
   * 1. If inPlaneVector1 and inPlaneVector2 are compatible with, no change.
   * 2. If dot products of the current view plane normal and inPlaneVector 1 and 2 are zero, no change
   *
   */
  public setBestOrentation(inPlaneVector1, inPlaneVector2) {
    if (!inPlaneVector1 && !inPlaneVector2) {
      // Any view is compatible with a point position
      return;
    }
    const { viewPlaneNormal } = this.getCamera();
    if (
      isCompatible(viewPlaneNormal, inPlaneVector2) &&
      isCompatible(viewPlaneNormal, inPlaneVector1)
    ) {
      // Orthogonal view to the current view, so no change.
      return;
    }
 
    const acquisition = this._getAcquisitionPlaneOrientation();
    if (
      isCompatible(acquisition.viewPlaneNormal, inPlaneVector2) &&
      isCompatible(acquisition.viewPlaneNormal, inPlaneVector1)
    ) {
      // Orthogonal view to the current view, so no change.
      this.setOrientation(acquisition);
      return;
    }
    for (const orientation of <{ viewPlaneNormal: Point3 }[]>(
      Object.values(mprCameraValues)
    )) {
      if (
        isCompatible(orientation.viewPlaneNormal, inPlaneVector2) &&
        isCompatible(orientation.viewPlaneNormal, inPlaneVector1)
      ) {
        // Orthogonal view to the current view, so no change.
        this.setOrientation(orientation);
        return;
      }
    }
 
    const planeNormal = <Point3>(
      vec3.cross(
        vec3.create(),
        inPlaneVector2 || acquisition.viewPlaneNormal,
        inPlaneVector1
      )
    );
    vec3.normalize(planeNormal, planeNormal);
    this.setOrientation({ viewPlaneNormal: planeNormal });
  }
 
  /**
   * Sets the view reference given a referenced plane and the current
   * view plane normal being applied.
   * This will use the existing normal if compatible, otherwise will calculate
   * a new view plane normal as the referenced plane normal, or else the
   * cross product of the existing view plane normal and the inPlaneVector1
   */
  public setViewPlane(planeRestriction: PlaneRestriction) {
    const { point, inPlaneVector1, inPlaneVector2, FrameOfReferenceUID } =
      planeRestriction;
 
    this.setBestOrentation(inPlaneVector1, inPlaneVector2);
 
    this.setViewReference({
      FrameOfReferenceUID,
      cameraFocalPoint: point,
      viewPlaneNormal: this.getCamera().viewPlaneNormal,
    });
  }
 
  /**
   * Navigates to the specified view reference.
   */
  public setViewReference(viewRef: ViewReference): void {
    Iif (!viewRef) {
      return;
    }
    const volumeId = this.getVolumeId();
    const {
      FrameOfReferenceUID: refFrameOfReference,
      cameraFocalPoint,
      referencedImageId,
      planeRestriction,
      viewPlaneNormal: refViewPlaneNormal,
      viewUp,
    } = viewRef;
    let { sliceIndex } = viewRef;
 
    Iif (planeRestriction && !refViewPlaneNormal) {
      return this.setViewPlane(planeRestriction);
    }
 
    const { focalPoint, viewPlaneNormal, position } = this.getCamera();
 
    const isNegativeNormal = isEqualNegative(
      viewPlaneNormal,
      refViewPlaneNormal
    );
    const isSameNormal = isEqual(viewPlaneNormal, refViewPlaneNormal);
 
    // Handle slices
    if (
      typeof sliceIndex === 'number' &&
      volumeId !== undefined &&
      viewRef.volumeId === volumeId &&
      (isNegativeNormal || isSameNormal)
    ) {
      const { currentStepIndex, sliceRangeInfo, numScrollSteps } =
        getVolumeViewportScrollInfo(
          this as unknown as IVolumeViewport,
          volumeId,
          true
        );
 
      const { sliceRange, spacingInNormalDirection } = sliceRangeInfo;
      Iif (isNegativeNormal) {
        // Convert opposite orientation view refs to normal orientation
        sliceIndex = numScrollSteps - sliceIndex - 1;
      }
      const delta = sliceIndex - currentStepIndex;
      const { newFocalPoint, newPosition } = snapFocalPointToSlice(
        focalPoint,
        position,
        sliceRange,
        viewPlaneNormal,
        spacingInNormalDirection,
        delta
      );
      this.setCamera({ focalPoint: newFocalPoint, position: newPosition });
    } else Eif (refFrameOfReference === this.getFrameOfReferenceUID()) {
      // Handle same frame of reference navigation
 
      if (refViewPlaneNormal && !isNegativeNormal && !isSameNormal) {
        // Need to update the orientation vectors correctly for this case
        // this.setCameraNoEvent({ viewPlaneNormal: refViewPlaneNormal, viewUp });
        this.setOrientation({ viewPlaneNormal: refViewPlaneNormal, viewUp });
        this.setViewReference(viewRef);
        return;
      }
      if (referencedImageId && this.isInAcquisitionPlane()) {
        // we can't simply use the scroll function since the order of image
        // ids is not guaranteed to be the same as the order of the slices
        // so we just need to get the referencedImageId origin from the cache
        // and align it with the current focal point and then set cameraFocalPoint
        const imagePlaneModule = metaData.get(
          MetadataModules.IMAGE_PLANE,
          referencedImageId
        );
 
        const { imagePositionPatient } = imagePlaneModule;
        const { focalPoint } = this.getCamera();
        // move the imagePositionPatient in the direction of the viewPlaneNormal
        // to the focalPoint
        const diffVector = vec3.subtract(
          vec3.create(),
          focalPoint,
          imagePositionPatient
        );
        // projected distance
        const projectedDistance = vec3.dot(diffVector, viewPlaneNormal);
        const newImagePositionPatient = vec3.scaleAndAdd(
          vec3.create(),
          focalPoint,
          [-viewPlaneNormal[0], -viewPlaneNormal[1], -viewPlaneNormal[2]],
          projectedDistance
        );
        // this.setViewReference({
        //   ...viewRef,
        //   cameraFocalPoint: newImagePositionPatient as Point3,
        // });
        this.setCamera({
          focalPoint: newImagePositionPatient as Point3,
        });
        this.render();
        return;
      }
      if (cameraFocalPoint) {
        const focalDelta = vec3.subtract(
          [0, 0, 0],
          cameraFocalPoint,
          focalPoint
        );
        const useNormal = refViewPlaneNormal ?? viewPlaneNormal;
        const normalDot = vec3.dot(focalDelta, useNormal);
        if (!isEqual(normalDot, 0)) {
          // Gets the portion of the focal point in the normal direction
          vec3.scale(focalDelta, useNormal, normalDot);
        }
        const newFocal = vec3.add([0, 0, 0], focalPoint, focalDelta) as Point3;
        const newPosition = vec3.add([0, 0, 0], position, focalDelta) as Point3;
        this.setCamera({ focalPoint: newFocal, position: newPosition });
      }
    } else {
      throw new Error(
        `Incompatible view refs: ${refFrameOfReference}!==${this.getFrameOfReferenceUID()}`
      );
    }
  }
 
  /**
   * Sets the opacity threshold for a volume with the given ID.
   * Values below the threshold will be transparent.
   *
   * @param colormap - An object containing threshold property
   * @param volumeId - The ID of the volume to set the threshold for.
   *
   * @returns void
   */
  private setThreshold(colormap: ColormapPublic, volumeId: string) {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
    if (!applicableVolumeActorInfo) {
      return;
    }
    const { volumeActor } = applicableVolumeActorInfo;
 
    // Use the new utility to update threshold while preserving opacity
    colormapUpdateThreshold(volumeActor, colormap.threshold);
 
    if (!this.viewportProperties.colormap) {
      this.viewportProperties.colormap = {};
    }
 
    this.viewportProperties.colormap.threshold = colormap.threshold;
 
    // Trigger COLORMAP_MODIFIED event with threshold information
    const matchedColormap = this.getColormap(volumeId);
    const eventDetail = {
      viewportId: this.id,
      colormap: matchedColormap,
      volumeId,
    };
    triggerEvent(this.element, Events.COLORMAP_MODIFIED, eventDetail);
  }
 
  /**
   * Sets the properties for the volume viewport on the volume
   * and if setProperties is called for the first time, the properties will also become the default one.
   * (if fusion, it sets it for the first volume in the fusion)
   *
   * @param VolumeViewportProperties - The properties to set
   * @param [VolumeViewportProperties.voiRange] - Sets the lower and upper voi
   * @param [VolumeViewportProperties.VOILUTFunction] - Sets the voi mode (LINEAR, or SAMPLED_SIGMOID)
   * @param [VolumeViewportProperties.invert] - Inverts the color transfer function
   * @param [VolumeViewportProperties.colormap] - Sets the colormap
   * @param [VolumeViewportProperties.preset] - Sets the colormap preset
   * @param volumeId - The volume id to set the properties for (if undefined, the first volume)
   * @param suppressEvents - If true, the viewport will not emit events
   */
  public setProperties(
    {
      voiRange,
      VOILUTFunction,
      invert,
      colormap,
      preset,
      interpolationType,
      slabThickness,
      sampleDistanceMultiplier,
    }: VolumeViewportProperties = {},
    volumeId?: string,
    suppressEvents = false
  ): void {
    //If the viewport hasn't been initialized, we need to set the default properties
    Eif (this.globalDefaultProperties == null) {
      this.setDefaultProperties({
        voiRange,
        VOILUTFunction,
        invert,
        colormap,
        preset,
        slabThickness,
      });
    }
 
    // invert should be set first, since if we set colormap then we invert
    // we basically are doing a reset which is not what we want
    Iif (invert !== undefined && this.viewportProperties.invert !== invert) {
      this.setInvert(invert, volumeId, suppressEvents);
    }
 
    // Note: colormap should always be done first, since we can then
    // modify the voiRange
    Iif (colormap?.name) {
      this.setColormap(colormap, volumeId, suppressEvents);
    }
    Iif (colormap?.opacity != null) {
      this.setOpacity(colormap, volumeId);
    }
    Iif (colormap?.threshold != null) {
      this.setThreshold(colormap, volumeId);
    }
 
    Eif (voiRange !== undefined) {
      this.setVOI(voiRange, volumeId, suppressEvents);
    }
 
    Iif (typeof interpolationType !== 'undefined') {
      this.setInterpolationType(interpolationType);
    }
 
    Iif (VOILUTFunction !== undefined) {
      this.setVOILUTFunction(VOILUTFunction, volumeId, suppressEvents);
    }
 
    Iif (preset !== undefined) {
      this.setPreset(preset, volumeId, suppressEvents);
    }
 
    Iif (slabThickness !== undefined) {
      this.setSlabThickness(slabThickness);
    }
    Iif (sampleDistanceMultiplier !== undefined) {
      this.setSampleDistanceMultiplier(sampleDistanceMultiplier);
    }
  }
 
  /**
   * Reset the viewport properties to the default values
   */
  public resetToDefaultProperties(volumeId: string): void {
    const properties = this.globalDefaultProperties;
 
    if (properties.colormap?.name) {
      this.setColormap(properties.colormap, volumeId);
    }
    if (properties.colormap?.opacity != null) {
      this.setOpacity(properties.colormap, volumeId);
    }
 
    if (properties.voiRange !== undefined) {
      this.setVOI(properties.voiRange, volumeId);
    }
 
    if (properties.VOILUTFunction !== undefined) {
      this.setVOILUTFunction(properties.VOILUTFunction, volumeId);
    }
 
    if (properties.invert !== undefined) {
      this.setInvert(properties.invert, volumeId);
    }
 
    if (properties.slabThickness !== undefined) {
      this.setSlabThickness(properties.slabThickness);
      //We need to set the current slabThickness here since setSlabThickness is define in VolumeViewport
      this.viewportProperties.slabThickness = properties.slabThickness;
    }
 
    if (properties.sampleDistanceMultiplier !== undefined) {
      this.setSampleDistanceMultiplier(properties.sampleDistanceMultiplier);
    }
 
    if (properties.preset !== undefined) {
      this.setPreset(properties.preset, volumeId, false);
    }
    this.render();
  }
 
  /**
   * Sets the specified preset for the volume with the given ID
   *
   * @param presetName - The name of the preset to apply (e.g., "CT-Bone").
   * @param volumeId - The ID of the volume to set the preset for.
   * @param suppressEvents - If `true`, events will not be emitted during the preset application.
   *
   * @returns void
   */
  private setPreset(presetNameOrObj, volumeId, suppressEvents) {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
 
    if (!applicableVolumeActorInfo) {
      return;
    }
 
    const { volumeActor } = applicableVolumeActorInfo;
 
    let preset = presetNameOrObj;
 
    if (typeof preset === 'string') {
      preset = VIEWPORT_PRESETS.find((preset) => {
        return preset.name === presetNameOrObj;
      });
    }
 
    if (!preset) {
      return;
    }
 
    applyPreset(volumeActor, preset);
 
    this.viewportProperties.preset = preset;
    this.render();
 
    if (!suppressEvents) {
      triggerEvent(this.element, Events.PRESET_MODIFIED, {
        viewportId: this.id,
        volumeId: applicableVolumeActorInfo.volumeId,
        actor: volumeActor,
        presetName: preset.name,
      });
    }
  }
 
  public setSampleDistanceMultiplier(multiplier: number): void {}
 
  /**
   * Retrieve the viewport default properties
   * @param volumeId If given, we retrieve the default properties of a volumeId if it exists
   * If not given,we return the global properties of the viewport
   * @returns default viewport properties including voi, invert, interpolation type, colormap
   */
  public getDefaultProperties = (
    volumeId?: string
  ): VolumeViewportProperties => {
    let volumeProperties;
    if (volumeId !== undefined) {
      volumeProperties = this.perVolumeIdDefaultProperties.get(volumeId);
    }
 
    if (volumeProperties !== undefined) {
      return volumeProperties;
    }
 
    return {
      ...this.globalDefaultProperties,
    };
  };
 
  /**
   * Retrieve the viewport properties
   * @param volumeId - The volume id to get the properties for (if undefined, the first volume)
   * @returns viewport properties including voi, interpolation type: TODO: slabThickness, invert
   */
  public getProperties = (volumeId?: string): VolumeViewportProperties => {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
    Iif (!applicableVolumeActorInfo) {
      return;
    }
 
    const {
      colormap: latestColormap,
      VOILUTFunction,
      interpolationType,
      invert,
      slabThickness,
      preset,
    } = this.viewportProperties;
 
    volumeId ||= this.getVolumeId();
    const volume = cache.getVolume(volumeId);
 
    Iif (!volume) {
      return null;
    }
 
    const volumeActorEntry = this.getActors().find((actorEntry) => {
      return actorEntry.referencedId === volumeId;
    });
 
    Iif (!volumeActorEntry) {
      return;
    }
 
    const volumeActor = volumeActorEntry.actor as vtkVolume;
    const cfun = volumeActor.getProperty().getRGBTransferFunction(0);
    const [lower, upper] =
      this.viewportProperties?.VOILUTFunction === 'SIGMOID'
        ? getVoiFromSigmoidRGBTransferFunction(cfun)
        : cfun.getRange();
 
    const voiRange = { lower, upper };
 
    const volumeColormap = this.getColormap(volumeId);
 
    const colormap =
      volumeId && volumeColormap ? volumeColormap : latestColormap;
 
    return {
      colormap: colormap,
      voiRange: voiRange,
      VOILUTFunction: VOILUTFunction,
      interpolationType: interpolationType,
      invert: invert,
      slabThickness: slabThickness,
      preset,
    };
  };
 
  /**
   * This function extracts the nodes from the RGB Transfer Function, transforming each node's x, r, g, b properties
   * into a unified array "RGB Points." Then, it compares these RGB Points—specifically the r, g, b values—with
   * those in the predefined vtk colormap presets. Upon finding a matching set of r, g, b values, the function identifies and selects the
   * corresponding colormap.
   *
   * Next, the function extracts an array of opacity points, formatted as a sequence of `[x,y]` pairs, where `x` represents a value and
   * `y` represents its opacity. It iterates through this array to construct an opacity object that maps each value to its opacity.
   *
   * The function returns an object that includes the name of the identified colormap and the constructed opacity object.
   * @param applicableVolumeActorInfo  - The volume actor information for the volume
   * @returns colormap information for the volume if identified
   */
  private getColormap = (volumeId) => {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
 
    Iif (!applicableVolumeActorInfo) {
      return;
    }
 
    const { volumeActor } = applicableVolumeActorInfo;
    const cfun = this._getOrCreateColorTransferFunction(volumeId);
    // @ts-expect-error vtkColorTransferFunction is not typed
    const { nodes } = cfun.getState();
    const RGBPoints = nodes.reduce((acc, node) => {
      acc.push(node.x, node.r, node.g, node.b);
      return acc;
    }, []);
 
    const matchedColormap = findMatchingColormap(RGBPoints, volumeActor) || {};
 
    const threshold = getThresholdValue(volumeActor);
    const opacity = getMaxOpacity(volumeActor);
 
    matchedColormap.threshold = threshold;
    matchedColormap.opacity = opacity;
 
    return matchedColormap;
  };
 
  /**
   * Creates volume actors for all volumes defined in the `volumeInputArray`.
   * For each entry, if a `callback` is supplied, it will be called with the new volume actor as input.
   * For each entry, if a `blendMode` and/or `slabThickness` is defined, this will be set on the actor's
   * `VolumeMapper`.
   *
   * @param volumeInputArray - The array of `VolumeInput`s which define the volumes to add.
   * @param immediate - Whether the `Viewport` should be rendered as soon as volumes are added.
   */
  public async setVolumes(
    volumeInputArray: IVolumeInput[],
    immediate = false,
    suppressEvents = false
  ): Promise<void> {
    const volumeId = volumeInputArray[0].volumeId;
    const firstImageVolume = cache.getVolume(volumeId);
 
    Iif (!firstImageVolume) {
      throw new Error(
        `imageVolume with id: ${volumeId} does not exist, you need to create/allocate the volume first`
      );
    }
 
    const FrameOfReferenceUID = firstImageVolume.metadata.FrameOfReferenceUID;
 
    this._isValidVolumeInputArray(volumeInputArray, FrameOfReferenceUID);
 
    this._FrameOfReferenceUID = FrameOfReferenceUID;
    volumeInputArray.forEach((volumeInput) => {
      this._addVolumeId(volumeInput.volumeId);
    });
 
    const volumeActors = [];
 
    // One actor per volume
    for (let i = 0; i < volumeInputArray.length; i++) {
      const { volumeId, actorUID, slabThickness, ...rest } =
        volumeInputArray[i];
 
      const actor = await createVolumeActor(
        volumeInputArray[i],
        this.element,
        this.id,
        suppressEvents
      );
 
      // We cannot use only volumeId since then we cannot have for instance more
      // than one representation of the same volume (since actors would have the
      // same name, and we don't allow that) AND We cannot use only any uid, since
      // we rely on the volume in the cache for mapper. So we prefer actorUID if
      // it is defined, otherwise we use volumeId for the actor name.
      const uid = actorUID || uuidv4();
      volumeActors.push({
        uid,
        actor,
        slabThickness,
        referencedId: volumeId,
        ...rest,
      });
    }
 
    this._setVolumeActors(volumeActors);
    this.viewportStatus = ViewportStatus.PRE_RENDER;
 
    this.initializeColorTransferFunction(volumeInputArray);
 
    triggerEvent(this.element, Events.VOLUME_VIEWPORT_NEW_VOLUME, {
      viewportId: this.id,
      volumeActors,
    });
 
    Iif (immediate) {
      this.render();
    }
  }
 
  /**
   * Creates and adds volume actors for all volumes defined in the `volumeInputArray`.
   * For each entry, if a `callback` is supplied, it will be called with the new volume actor as input.
   *
   * @param volumeInputArray - The array of `VolumeInput`s which define the volumes to add.
   * @param immediate - Whether the `Viewport` should be rendered as soon as volumes are added.
   */
  public async addVolumes(
    volumeInputArray: IVolumeInput[],
    immediate = false,
    suppressEvents = false
  ): Promise<void> {
    const firstImageVolume = cache.getVolume(volumeInputArray[0].volumeId);
 
    Iif (!firstImageVolume) {
      throw new Error(
        `imageVolume with id: ${firstImageVolume.volumeId} does not exist`
      );
    }
    const volumeActors = [];
 
    this._isValidVolumeInputArray(volumeInputArray, this._FrameOfReferenceUID);
 
    volumeInputArray.forEach((volumeInput) => {
      this._addVolumeId(volumeInput.volumeId);
    });
 
    // One actor per volume
    for (let i = 0; i < volumeInputArray.length; i++) {
      const { volumeId, visibility, actorUID, slabThickness, ...rest } =
        volumeInputArray[i];
 
      const actor = await createVolumeActor(
        volumeInputArray[i],
        this.element,
        this.id,
        suppressEvents
      );
 
      Iif (!visibility) {
        actor.setVisibility(false);
      }
 
      // We cannot use only volumeId since then we cannot have for instance more
      // than one representation of the same volume (since actors would have the
      // same name, and we don't allow that) AND We cannot use only any uid, since
      // we rely on the volume in the cache for mapper. So we prefer actorUID if
      // it is defined, otherwise we use volumeId for the actor name.
      const uid = actorUID || uuidv4();
      volumeActors.push({
        uid,
        actor,
        slabThickness,
        // although the actor UID is defined, we need to use the volumeId for the
        // referencedId, since the actor is created from its volumeId
        // and if later we need to grab the referenced volume from cache,
        // we can use the referencedId to get the volume from the cache
        referencedId: volumeId,
        ...rest,
      });
    }
 
    this.addActors(volumeActors);
 
    this.initializeColorTransferFunction(volumeInputArray);
 
    Iif (immediate) {
      // render
      this.render();
    }
  }
 
  /**
   * It removes the volume actor from the Viewport. If the volume actor is not in
   * the viewport, it does nothing.
   * @param actorUIDs - Array of actor UIDs to remove. In case of simple volume it will
   * be the volume Id, but in case of Segmentation it will be `{volumeId}-{representationType}`
   * since the same volume can be rendered in multiple representations.
   * @param immediate - If true, the Viewport will be rendered immediately
   */
  public removeVolumeActors(actorUIDs: string[], immediate = false): void {
    // Todo: This is actually removeActors
    this.removeActors(actorUIDs);
 
    if (immediate) {
      this.render();
    }
  }
 
  /**
   * It sets the orientation for the camera, the orientation can be one of the
   * following: axial, sagittal, coronal, acquisition. Use the `Enums.OrientationAxis`
   * to set the orientation. The "acquisition" orientation is the orientation that
   * the volume was acquired in (scan axis).
   *
   * @param orientation - The orientation to set the camera to.
   * @param immediate - Whether the `Viewport` should be rendered as soon as the camera is set.
   */
  public setOrientation(
    _orientation: OrientationAxis | OrientationVectors,
    _immediate = true
  ): void {
    console.warn('Method "setOrientation" needs implementation');
  }
 
  /**
   * Initializes the color transfer function nodes for a given volume.
   *
   * @param volumeInputArray - Array of volume inputs.
   * @param getTransferFunctionNodes - Function to get the transfer function nodes.
   * @returns void
   */
  private initializeColorTransferFunction(volumeInputArray) {
    const selectedVolumeId = volumeInputArray[0].volumeId;
    const colorTransferFunction =
      this._getOrCreateColorTransferFunction(selectedVolumeId);
 
    if (!this.initialTransferFunctionNodes && colorTransferFunction) {
      this.initialTransferFunctionNodes = getTransferFunctionNodes(
        colorTransferFunction
      );
    }
  }
 
  private _getApplicableVolumeActor(volumeId?: string) {
    const actorEntries = this.getActors();
 
    Iif (!actorEntries?.length) {
      return;
    }
 
    if (volumeId) {
      const actorEntry = actorEntries.find(
        (actor) => actor.referencedId === volumeId
      );
 
      Iif (!actorEntry) {
        return;
      }
 
      return {
        volumeActor: actorEntry.actor as vtkVolume,
        volumeId,
        actorUID: actorEntry.uid,
      };
    }
 
    const defaultActorEntry = actorEntries[0];
 
    return {
      volumeActor: defaultActorEntry.actor as vtkVolume,
      volumeId: defaultActorEntry.referencedId,
      actorUID: defaultActorEntry.uid,
    };
  }
 
  private async _isValidVolumeInputArray(
    volumeInputArray: IVolumeInput[],
    FrameOfReferenceUID: string
  ): Promise<boolean> {
    const numVolumes = volumeInputArray.length;
 
    // Check all other volumes exist and have the same FrameOfReference
    for (let i = 1; i < numVolumes; i++) {
      const imageVolume = cache.getVolume(volumeInputArray[i].volumeId);
 
      if (FrameOfReferenceUID !== imageVolume.metadata.FrameOfReferenceUID) {
        throw new Error(
          `Volumes being added to viewport ${this.id} do not share the same FrameOfReferenceUID. This is not yet supported`
        );
      }
    }
 
    return true;
  }
 
  /**
   * Gets the rotation resulting from the value set in setRotation AND taking into
   * account any flips that occurred subsequently from the camera provided or the viewport.
   *
   * @returns the rotation resulting from the value set in setRotation AND taking into
   * account any flips that occurred subsequently.
   */
  public getRotation = (): number => {
    const {
      viewUp: currentViewUp,
      viewPlaneNormal,
      flipVertical,
    } = this.getCameraNoRotation();
 
    // The initial view up vector without any rotation, but incorporating vertical flip.
    const initialViewUp = flipVertical
      ? vec3.negate([0, 0, 0], this.initialViewUp)
      : this.initialViewUp;
 
    Iif (!initialViewUp) {
      return 0;
    }
 
    // 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(
      [0, 0, 0],
      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);
 
    const value =
      normalDot >= 0
        ? initialToCurrentViewUpAngle
        : (360 - initialToCurrentViewUpAngle) % 360;
 
    return value;
  };
 
  /**
   * gets the visible bounds of the viewport in the world coordinate system
   */
  public getBounds(): number[] {
    const renderer = this.getRenderer();
    const bounds = renderer.computeVisiblePropBounds();
    return bounds;
  }
 
  /**
   * Flip the viewport along the desired axis
   * @param flipDirection - FlipDirection
   */
  public flip(flipDirection: FlipDirection): void {
    super.flip(flipDirection);
  }
 
  public getFrameOfReferenceUID = (): string => {
    return this._FrameOfReferenceUID;
  };
 
  /**
   * Checks if the viewport has a volume actor with the given volumeId
   * @param volumeId - the volumeId to look for
   * @returns Boolean indicating if the volume is present in the viewport
   */
  public hasVolumeId(volumeId: string): boolean {
    // Note: this assumes that the uid of the volume is the same as the volumeId
    // which is not guaranteed to be the case for SEG.
    return this.volumeIds.has(volumeId);
  }
 
  /**
   * Checks if the viewport has a volume with the given volumeURI.
   *
   * @param volumeURI - The URI of the volume to check for.
   * @returns A boolean indicating whether the viewport contains a volume with the given URI.
   */
  public hasVolumeURI(volumeURI: string): boolean {
    // loop through this.volumeIds and check if any volumeId contains the volumeURI
    for (const volumeId of this.volumeIds) {
      if (volumeId.includes(volumeURI)) {
        return true;
      }
    }
    return false;
  }
 
  /**
   * 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)
   * Note: since the volume viewport supports fusion, to get the
   * image data for a specific volume, use the optional volumeId
   * argument.
   *
   * @param volumeId - The volumeId of the volume to get the image for.
   * @returns IImageData
   */
  public getImageData(volumeId?: string): IImageData | undefined {
    const defaultActor = this.getDefaultActor();
    if (!defaultActor) {
      return;
    }
 
    volumeId ||= this.getVolumeId();
 
    const actorEntry = this.getActors()?.find(
      (actor) => actor.referencedId === volumeId
    );
 
    Iif (!actorIsA(actorEntry, 'vtkVolume')) {
      return;
    }
 
    const actor = actorEntry.actor;
    const volume = cache.getVolume(volumeId);
 
    const vtkImageData = actor.getMapper().getInputData();
 
    return {
      dimensions: vtkImageData.getDimensions(),
      spacing: vtkImageData.getSpacing(),
      origin: vtkImageData.getOrigin(),
      direction: vtkImageData.getDirection(),
      imageData: actor.getMapper().getInputData(),
      metadata: {
        Modality: volume?.metadata?.Modality,
        FrameOfReferenceUID: volume?.metadata?.FrameOfReferenceUID,
      },
      get scalarData() {
        return volume?.voxelManager?.getScalarData();
      },
      scaling: volume?.scaling,
      hasPixelSpacing: true,
      voxelManager: volume?.voxelManager,
    };
  }
 
  protected setCameraClippingRange() {
    throw new Error('Method not implemented.');
  }
 
  public getSliceIndex(): number {
    throw new Error('Method not implemented.');
  }
 
  public setCamera(
    cameraInterface: ICamera,
    storeAsInitialCamera?: boolean
  ): void {
    super.setCamera(cameraInterface, storeAsInitialCamera);
    // This is very important to set the clipping range for the camera
    // for volume viewport, since we are doing slab rendering
    this.setCameraClippingRange();
  }
 
  /**
   * Attaches the volume actors to the viewport.
   *
   * @param volumeActorEntries - The volume actors to add the viewport.
   *
   */
  private _setVolumeActors(volumeActorEntries: ActorEntry[]): void {
    // New volume actors implies resetting the inverted flag (i.e. like starting from scratch).
 
    for (let i = 0; i < volumeActorEntries.length; i++) {
      this.viewportProperties.invert = false;
    }
    this.setActors(volumeActorEntries);
  }
 
  /**
   * canvasToWorld Returns the world coordinates of the given `canvasPos`
   * projected onto the plane defined by the `Viewport`'s `vtkCamera`'s focal point
   * and the direction of projection.
   *
   * @param canvasPos - The position in canvas coordinates.
   * @returns The corresponding world coordinates.
   * @public
   */
 
  public canvasToWorldTiled = (canvasPos: Point2): Point3 => {
    const vtkCamera = this.getVtkActiveCamera() as vtkSlabCameraType;
 
    /**
     * NOTE: this is necessary because we want the coordinate transformation
     * respect to the view plane (plane orthogonal to the camera and passing to
     * the focal point).
     *
     * When vtk.js computes the coordinate transformations, it simply uses the
     * camera matrix (no ray casting).
     *
     * However for the volume viewport the clipping range is set to be
     * (-RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE, RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE).
     * The clipping range is used in the camera method getProjectionMatrix().
     * The projection matrix is used then for viewToWorld/worldToView methods of
     * the renderer. This means that vkt.js will not return the coordinates of
     * the point on the view plane (i.e. the depth coordinate will correspond
     * to the focal point).
     *
     * Therefore the clipping range has to be set to (distance, distance + 0.01),
     * where now distance is the distance between the camera position and focal
     * point. This is done internally, in our camera customization when the flag
     * isPerformingCoordinateTransformation is set to true.
     */
 
    vtkCamera.setIsPerformingCoordinateTransformation?.(true);
 
    const renderer = this.getRenderer();
    const displayCoords = this.getVtkDisplayCoordsTiled(canvasPos);
    const offscreenMultiRenderWindow =
      this.getRenderingEngine().offscreenMultiRenderWindow;
    const openGLRenderWindow =
      offscreenMultiRenderWindow.getOpenGLRenderWindow();
    const worldCoord = openGLRenderWindow.displayToWorld(
      displayCoords[0],
      displayCoords[1],
      displayCoords[2],
      renderer
    );
 
    vtkCamera.setIsPerformingCoordinateTransformation?.(false);
 
    return [worldCoord[0], worldCoord[1], worldCoord[2]];
  };
 
  public canvasToWorldContextPool = (canvasPos: Point2): Point3 => {
    const vtkCamera = this.getVtkActiveCamera() as vtkSlabCameraType;
 
    /**
     * NOTE: this is necessary because we want the coordinate transformation
     * respect to the view plane (plane orthogonal to the camera and passing to
     * the focal point).
     *
     * When vtk.js computes the coordinate transformations, it simply uses the
     * camera matrix (no ray casting).
     *
     * However for the volume viewport the clipping range is set to be
     * (-RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE, RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE).
     * The clipping range is used in the camera method getProjectionMatrix().
     * The projection matrix is used then for viewToWorld/worldToView methods of
     * the renderer. This means that vkt.js will not return the coordinates of
     * the point on the view plane (i.e. the depth coordinate will correspond
     * to the focal point).
     *
     * Therefore the clipping range has to be set to (distance, distance + 0.01),
     * where now distance is the distance between the camera position and focal
     * point. This is done internally, in our camera customization when the flag
     * isPerformingCoordinateTransformation is set to true.
     */
 
    vtkCamera.setIsPerformingCoordinateTransformation?.(true);
 
    const renderer = this.getRenderer();
    const devicePixelRatio = window.devicePixelRatio || 1;
    const { width, height } = this.canvas;
    const aspectRatio = width / height;
 
    // Convert canvas coordinates to normalized display coordinates
    const canvasPosWithDPR = [
      canvasPos[0] * devicePixelRatio,
      canvasPos[1] * devicePixelRatio,
    ];
 
    // Normalize to [0,1] range
    const normalizedDisplay = [
      canvasPosWithDPR[0] / width,
      1 - canvasPosWithDPR[1] / height, // Flip Y axis
      0,
    ];
 
    // Transform from normalized display to world coordinates
    const projCoords = renderer.normalizedDisplayToProjection(
      normalizedDisplay[0],
      normalizedDisplay[1],
      normalizedDisplay[2]
    );
    const viewCoords = renderer.projectionToView(
      projCoords[0],
      projCoords[1],
      projCoords[2],
      aspectRatio
    );
    const worldCoord = renderer.viewToWorld(
      viewCoords[0],
      viewCoords[1],
      viewCoords[2]
    );
 
    vtkCamera.setIsPerformingCoordinateTransformation?.(false);
 
    return [worldCoord[0], worldCoord[1], worldCoord[2]];
  };
 
  /**
   * Returns the VTK.js display coordinates of the given `canvasPos` projected onto the
   * `Viewport`'s `vtkCamera`'s focal point and the direction of projection.
   * @param canvasPos - The position in canvas coordinates.
   * @returns The corresponding display coordinates.
   *
   */
  public getVtkDisplayCoordsTiled = (canvasPos: Point2): Point3 => {
    const devicePixelRatio = window.devicePixelRatio || 1;
    const canvasPosWithDPR = [
      canvasPos[0] * devicePixelRatio,
      canvasPos[1] * devicePixelRatio,
    ];
    const offscreenMultiRenderWindow =
      this.getRenderingEngine().offscreenMultiRenderWindow;
    const openGLRenderWindow =
      offscreenMultiRenderWindow.getOpenGLRenderWindow();
    const size = openGLRenderWindow.getSize();
    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];
    return [displayCoord[0], displayCoord[1], 0];
  };
 
  public getVtkDisplayCoordsContextPool = (canvasPos: Point2): Point3 => {
    const devicePixelRatio = window.devicePixelRatio || 1;
    const canvasPosWithDPR = [
      canvasPos[0] * devicePixelRatio,
      canvasPos[1] * devicePixelRatio,
    ];
 
    const { height } = this.canvas;
 
    // Canvas coordinates with origin at top-left
    // VTK display coordinates have origin at bottom-left
    const displayCoord = [canvasPosWithDPR[0], height - canvasPosWithDPR[1]];
 
    return [displayCoord[0], displayCoord[1], 0];
  };
 
  /**
   * 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 worldToCanvasTiled = (worldPos: Point3): Point2 => {
    const vtkCamera = this.getVtkActiveCamera() as vtkSlabCameraType;
 
    /**
     * NOTE: this is necessary because we want the coordinate transformation
     * respect to the view plane (plane orthogonal to the camera and passing to
     * the focal point).
     *
     * When vtk.js computes the coordinate transformations, it simply uses the
     * camera matrix (no ray casting).
     *
     * However for the volume viewport the clipping range is set to be
     * (-RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE, RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE).
     * The clipping range is used in the camera method getProjectionMatrix().
     * The projection matrix is used then for viewToWorld/worldToView methods of
     * the renderer. This means that vkt.js will not return the coordinates of
     * the point on the view plane (i.e. the depth coordinate will corresponded
     * to the focal point).
     *
     * Therefore the clipping range has to be set to (distance, distance + 0.01),
     * where now distance is the distance between the camera position and focal
     * point. This is done internally, in our camera customization when the flag
     * isPerformingCoordinateTransformation is set to true.
     */
 
    vtkCamera.setIsPerformingCoordinateTransformation?.(true);
 
    const renderer = this.getRenderer();
    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 = [
      displayCoord[0] - this.sx,
      displayCoord[1] - this.sy,
    ] as Point2;
 
    const devicePixelRatio = window.devicePixelRatio || 1;
    const canvasCoordWithDPR = [
      canvasCoord[0] / devicePixelRatio,
      canvasCoord[1] / devicePixelRatio,
    ] as Point2;
 
    vtkCamera.setIsPerformingCoordinateTransformation(false);
 
    return canvasCoordWithDPR;
  };
 
  public worldToCanvasContextPool = (worldPos: Point3): Point2 => {
    const vtkCamera = this.getVtkActiveCamera() as vtkSlabCameraType;
 
    /**
     * NOTE: this is necessary because we want the coordinate transformation
     * respect to the view plane (plane orthogonal to the camera and passing to
     * the focal point).
     *
     * When vtk.js computes the coordinate transformations, it simply uses the
     * camera matrix (no ray casting).
     *
     * However for the volume viewport the clipping range is set to be
     * (-RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE, RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE).
     * The clipping range is used in the camera method getProjectionMatrix().
     * The projection matrix is used then for viewToWorld/worldToView methods of
     * the renderer. This means that vkt.js will not return the coordinates of
     * the point on the view plane (i.e. the depth coordinate will corresponded
     * to the focal point).
     *
     * Therefore the clipping range has to be set to (distance, distance + 0.01),
     * where now distance is the distance between the camera position and focal
     * point. This is done internally, in our camera customization when the flag
     * isPerformingCoordinateTransformation is set to true.
     */
 
    vtkCamera.setIsPerformingCoordinateTransformation?.(true);
 
    const renderer = this.getRenderer();
    const { width, height } = this.canvas;
    const aspectRatio = width / height;
 
    // Transform from world to view coordinates
    const viewCoords = renderer.worldToView(
      worldPos[0],
      worldPos[1],
      worldPos[2]
    );
 
    // Transform from view to projection coordinates
    const projCoords = renderer.viewToProjection(
      viewCoords[0],
      viewCoords[1],
      viewCoords[2],
      aspectRatio
    );
 
    // Transform from projection to normalized display coordinates
    const normalizedDisplay = renderer.projectionToNormalizedDisplay(
      projCoords[0],
      projCoords[1],
      projCoords[2]
    );
 
    // Convert normalized display [0,1] to canvas pixels
    const canvasX = normalizedDisplay[0] * width;
    const canvasY = (1 - normalizedDisplay[1]) * height; // Flip Y axis
 
    const devicePixelRatio = window.devicePixelRatio || 1;
    const canvasCoordWithDPR = [
      canvasX / devicePixelRatio,
      canvasY / devicePixelRatio,
    ] as Point2;
 
    vtkCamera.setIsPerformingCoordinateTransformation(false);
 
    return canvasCoordWithDPR;
  };
 
  /**
   * Get the renderer for this viewport - handles ContextPoolRenderingEngine
   */
  public getRendererContextPool(): vtkRenderer {
    const renderingEngine = this.getRenderingEngine();
    return renderingEngine.getRenderer(this.id);
  }
 
  /**
   * Returns the `vtkRenderer` responsible for rendering the `Viewport`.
   *
   * @returns The `vtkRenderer` for the `Viewport`.
   */
  public getRendererTiled(): vtkRenderer {
    const renderingEngine = this.getRenderingEngine();
 
    if (!renderingEngine || renderingEngine.hasBeenDestroyed) {
      throw new Error('Rendering engine has been destroyed');
    }
 
    return renderingEngine.offscreenMultiRenderWindow?.getRenderer(this.id);
  }
 
  /*
   * Checking if the imageURI (as a URI or an ID) is in the volumes that are being
   * rendered by the viewport.
   *
   * @param imageURI - The imageURI or imageID to check
   * @returns True if the image is in the volumes that are being rendered by the viewport
   */
  public hasImageURI = (imageURI: string): boolean => {
    const volumeActors = this.getActors().filter((actorEntry) =>
      actorIsA(actorEntry, 'vtkVolume')
    );
 
    return volumeActors.some(({ uid, referencedId }) => {
      const volume = cache.getVolume(referencedId || uid);
 
      if (!volume?.getImageIdIndex) {
        return false;
      }
 
      return (
        volume.getImageIdIndex(imageURI) !== undefined ||
        volume.getImageURIIndex(imageURI) !== undefined
      );
    });
  };
 
  /**
   * Gets a view up given a view plane normal and the current orientation
   * Chooses the current view up if orthogonal, otherwise the default view ups
   * for axial, sagittal and coronal
   * Otherwise runs the Gram-Schmidt algorithm with the current viewUp
   */
  protected _getViewUp(viewPlaneNormal): Point3 {
    const { viewUp } = this.getCamera();
    const dot = vec3.dot(viewUp, viewPlaneNormal);
    if (isEqual(dot, 0)) {
      // Don't change the view up if not needed
      return viewUp;
    }
    if (isEqualAbs(viewPlaneNormal[0], 1)) {
      return [0, 0, 1];
    }
    if (isEqualAbs(viewPlaneNormal[1], 1)) {
      return [0, 0, 1];
    }
    if (isEqualAbs(viewPlaneNormal[2], 1)) {
      return [0, -1, 0];
    }
    const vupOrthogonal = <Point3>(
      vec3.scaleAndAdd(vec3.create(), viewUp, viewPlaneNormal, -dot)
    );
    vec3.normalize(vupOrthogonal, vupOrthogonal);
    return vupOrthogonal;
  }
 
  protected _getOrientationVectors(
    orientation: OrientationAxis | OrientationVectors
  ): OrientationVectors {
    if (typeof orientation === 'object') {
      if (orientation.viewPlaneNormal) {
        return {
          ...orientation,
          viewUp:
            orientation.viewUp || this._getViewUp(orientation.viewPlaneNormal),
        };
      } else E{
        throw new Error(
          'Invalid orientation object. It must contain viewPlaneNormal'
        );
      }
    } else Eif (typeof orientation === 'string') {
      Iif (orientation === 'acquisition') {
        return this._getAcquisitionPlaneOrientation();
      } else if (
        orientation === 'reformat' ||
        (orientation as string).includes('_reformat')
      ) {
        return getCameraVectors(this, {
          useViewportNormal: true,
        });
      } else Eif (MPR_CAMERA_VALUES[orientation]) {
        this.viewportProperties.orientation = orientation;
        return MPR_CAMERA_VALUES[orientation];
      }
    }
 
    throw new Error(
      `Invalid orientation: ${orientation}. Valid orientations are: ${Object.keys(
        MPR_CAMERA_VALUES
      ).join(', ')}`
    );
  }
 
  protected _getAcquisitionPlaneOrientation(): OrientationVectors {
    const actorEntry = this.getDefaultActor();
 
    if (!actorEntry) {
      return;
    }
 
    // Todo: fix this after we add the volumeId reference to actorEntry later
    // in the segmentation refactor
    const volumeId = this.getVolumeId();
 
    const imageVolume = cache.getVolume(volumeId);
 
    if (!imageVolume) {
      throw new Error(
        `imageVolume with id: ${volumeId} does not exist in cache`
      );
    }
 
    const { direction } = imageVolume;
    const viewPlaneNormal = direction.slice(6, 9).map((x) => -x) as Point3;
    const viewUp = (direction.slice(3, 6) as Point3).map((x) => -x) as Point3;
 
    return {
      viewPlaneNormal,
      viewUp,
    };
  }
 
  /**
   * Gets the largest slab thickness from all actors in the viewport.
   *
   * @returns slabThickness - The slab thickness.
   */
  public getSlabThickness(): number {
    const actors = this.getActors();
    let slabThickness = RENDERING_DEFAULTS.MINIMUM_SLAB_THICKNESS;
    actors.forEach((actor) => {
      Iif (actor.slabThickness > slabThickness) {
        slabThickness = actor.slabThickness;
      }
    });
 
    return slabThickness;
  }
  /**
   * Given a point in world coordinates, return the intensity at that point
   * @param point - The point in world coordinates to get the intensity
   * from.
   * @returns The intensity value of the voxel at the given point.
   */
  public getIntensityFromWorld(point: Point3): number {
    const actorEntry = this.getDefaultActor();
    if (!actorIsA(actorEntry, 'vtkVolume')) {
      return;
    }
 
    const { actor } = actorEntry;
    const imageData = actor.getMapper().getInputData();
 
    const volume = cache.getVolume(this.getVolumeId());
    const index = transformWorldToIndex(imageData, point);
 
    return volume.voxelManager.getAtIJKPoint(index) as number;
  }
 
  /**
   * Returns the list of image Ids for the current viewport
   *
   * @param volumeId - volumeId
   * @returns list of strings for image Ids
   */
  public getImageIds = (volumeId?: string): string[] => {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
 
    Iif (!applicableVolumeActorInfo) {
      throw new Error(`No actor found for the given volumeId: ${volumeId}`);
    }
 
    const volumeIdToUse = applicableVolumeActorInfo.volumeId;
 
    const imageVolume = cache.getVolume(volumeIdToUse);
    Iif (!imageVolume) {
      throw new Error(
        `imageVolume with id: ${volumeIdToUse} does not exist in cache`
      );
    }
 
    return imageVolume.imageIds;
  };
 
  abstract getCurrentImageId(): string | undefined;
 
  /**
   * Gets the volumeId to use for references.
   * Returns undefined if the specified volume is NOT in this viewport.
   */
  public getVolumeId(specifier?: ViewReferenceSpecifier) {
    const actorEntries = this.getActors();
    Iif (!actorEntries) {
      return;
    }
    Eif (!specifier?.volumeId) {
      // find the first image actor of instance type vtkVolume
      const found = actorEntries.find(
        (actorEntry) => actorEntry.actor.getClassName() === 'vtkVolume'
      );
 
      return found?.referencedId || found?.uid;
    }
 
    // See if this volumeId can be found in one of the actors for this
    // viewport.  This check will cause undefined to be returned when the
    // volumeId isn't currently shown in this viewport.
    const found = actorEntries.find(
      (actorEntry) =>
        actorEntry.actor.getClassName() === 'vtkVolume' &&
        actorEntry.referencedId === specifier?.volumeId
    );
 
    return found?.referencedId || found?.uid;
  }
 
  /**
   * For a volume viewport, the reference id will be a URN starting with
   * `volumeId:<volumeId>`, followed by additional arguments to specify
   * the view orientation.  This will end up being a unique string that
   * identifies the view reference being shown.  It is different from the
   * view reference in that the values are all incorporated into a string to
   * allow using it as a parameter key.
   */
  public getViewReferenceId(specifier: ViewReferenceSpecifier = {}): string {
    let { volumeId, sliceIndex: sliceIndex } = specifier;
    Eif (!volumeId) {
      const actorEntries = this.getActors();
      Iif (!actorEntries) {
        return;
      }
      // find the first image actor of instance type vtkVolume
      volumeId = actorEntries.find(
        (actorEntry) => actorEntry.actor.getClassName() === 'vtkVolume'
      )?.referencedId;
    }
 
    const currentIndex = this.getSliceIndex();
    sliceIndex ??= currentIndex;
    const { viewPlaneNormal, focalPoint } = this.getCamera();
    const querySeparator = volumeId.includes('?') ? '&' : '?';
    // Format each element of viewPlaneNormal to 3 decimal places
    // to avoid floating point precision issues
    const formattedNormal = viewPlaneNormal.map((v) => v.toFixed(3)).join(',');
    return `volumeId:${volumeId}${querySeparator}sliceIndex=${sliceIndex}&viewPlaneNormal=${formattedNormal}`;
  }
 
  private _addVolumeId(volumeId: string): void {
    this.volumeIds.add(volumeId);
  }
 
  abstract setBlendMode(
    blendMode: BlendModes,
    filterActorUIDs?: string[],
    immediate?: boolean
  ): void;
 
  abstract setSlabThickness(
    slabThickness: number,
    filterActorUIDs?: string[]
  ): void;
 
  abstract resetSlabThickness(): void;
 
  abstract resetProperties(volumeId?: string): void;
 
  /**
   * Returns an array of all volumeIds currently in the viewport.
   *
   * @returns An array of strings representing all volumeIds.
   */
  public getAllVolumeIds(): string[] {
    return Array.from(this.volumeIds);
  }
 
  private _configureRenderingPipeline() {
    const isContextPool = isContextPoolRenderingEngine();
 
    for (const key in this.renderingPipelineFunctions) {
      Eif (
        Object.prototype.hasOwnProperty.call(
          this.renderingPipelineFunctions,
          key
        )
      ) {
        const functions = this.renderingPipelineFunctions[key];
 
        this[key] = isContextPool ? functions.contextPool : functions.tiled;
      }
    }
  }
 
  protected renderingPipelineFunctions = {
    worldToCanvas: {
      tiled: this.worldToCanvasTiled,
      contextPool: this.worldToCanvasContextPool,
    },
    canvasToWorld: {
      tiled: this.canvasToWorldTiled,
      contextPool: this.canvasToWorldContextPool,
    },
    getVtkDisplayCoords: {
      tiled: this.getVtkDisplayCoordsTiled,
      contextPool: this.getVtkDisplayCoordsContextPool,
    },
    getRenderer: {
      tiled: this.getRendererTiled,
      contextPool: this.getRendererContextPool,
    },
  };
}
 
/** Checks of a vector is compatible with the view plane normal */
function isCompatible(viewPlaneNormal, vector) {
  return !vector || isEqual(vec3.dot(viewPlaneNormal, vector), 0);
}
 
export default BaseVolumeViewport;