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 | 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 204x 318x 204x 12x 9635x 11139x 441x 441x 441x 441x 174x 174x 174x 441x 441x 336074x 336074x 232845x 336074x 21x 21x 21x 21x 21x 21x 21x 21x 204x 476x 476x 476x 81x 476x 476x 476x 476x 476x 476x 476x 476x 141x 141x 141x 141x 1x 476x 476x 476x 19x 41x 60x 60x 60x 60x 60x 60x 60x 5234x 60x 60x 60x 60x 60x 60x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 2814x 2814x 27x 27x 27x 2814x 2814x 2814x 45819524x 27x 27x 27x 27x 27x 27x 393x 393x 393x 393x 393x 393x 393x 393x 27x 27x 27x 27x 27x 27x 27x 27x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 164x 27752x 55x 55x 55x 876x 378x 55x 55x 55x 55x 55x 378x 378x 378x 378x 378x 378x 378x 378x 378x 378x 378x 378x 55x 55x 55x 55x 55x 55x 55x 160x 160x 160x 19x 141x 141x 111x 61608x 11x 11x 11x 11x 24x 11x 11x 11x 5x 5x 204x 277x 277x 204x 37x 37x 37x 20x 20x 20x 20x 11x 20x 17x 20x 20x 20x 20x 20x 20x 44x 44x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 259x 4x 4x 30x 30x 2x 2x 2x 2x 11x 3x 80x 3282x 2x 2x 45x 45x 47x 204x 18x 204x 85x 85x 204x 890x 8x 12x 946x 60x 60x 186x 186x 186x 186x 186x 186x 186x 177x 177x 9x 9x 9x 9x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 476x 476x 476x 18x 18x 18x 18x 476x 476x 476x 476x 8x 8x 8x 8x 8x 8x 468x 60x 35x 25x 25x 25x 25x 25x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 6x 6x 6x 6x 6x 6x 6x 141x 19x 232845x 232845x 232845x 232845x 232845x 232845x 232845x 1064672x 1064672x 1064672x 1064672x 232845x 232845x 232845x 204x 204x 204x 204x 204x 204x 204x 204x 242x 5x 5x 5x 5x 5x 5x 44x 5x 44x 44x 44x 44x 44x 40x 4x 5x 172x 172x 172x 172x 172x 1748x 1748x 148x 148x 1600x 1600x 1600x 1600x 172x 18x 18x 18x 204x 80x 186x 186x 186x 186x 186x 177x 177x 9x 263x 30x 3x 3x 3x 3x 2946x 2946x 204x 2379x 2379x 204x 124x 124x 204x 1164x 1164x 204x 141x 141x 204x 16x 16x 204x 38x 38x 9x 9x 9x 9x 9x 7x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 8x 1x 204x | import {
cache,
Enums as csEnums,
eventTarget,
geometryLoader,
getEnabledElementByViewportId,
imageLoader,
Types as csTypes,
utilities as csUtils,
metaData,
} from '@cornerstonejs/core';
import { ViewportType } from '@cornerstonejs/core/enums';
import { isVolume3DViewportType } from '../../utils/getLegacyViewportType';
import {
Enums as csToolsEnums,
segmentation as cstSegmentation,
Types as cstTypes,
annotation as cstAnnotation,
} from '@cornerstonejs/tools';
import { PubSubService, Types as OHIFTypes } from '@ohif/core';
import i18n from '@ohif/i18n';
import { VOLUME_LOADER_SCHEME } from '../../constants';
import { mapROIContoursToRTStructData } from './RTSTRUCT/mapROIContoursToRTStructData';
import { SegmentationPresentation, SegmentationPresentationItem } from '../../types/Presentation';
import { EasingFunctionEnum, EasingFunctionMap } from '../../utils/transitions';
import { ViewReference } from '@cornerstonejs/core/types';
import {
LegacySegmentationBackend,
NextSegmentationBackend,
type ISegmentationBackend,
type ISegmentationServiceInternals,
} from './backends';
// Sanctioned flag read: the SEG data shape (single- vs multi-layer) is fixed at
// load time, before any target viewport exists, so this one seg-backend dispatch
// cannot use a per-viewport capability check and reads the session flag instead.
import { isNextViewportsEnabled } from '../../utils/nextViewports';
import { isNextViewport } from '../ViewportService/adapter';
const { DefaultHistoryMemo } = csUtils.HistoryMemo;
const {
Labelmap: LABELMAP,
Contour: CONTOUR,
Surface: SURFACE,
} = csToolsEnums.SegmentationRepresentations;
const {
getLabelmapImageIds,
helpers: { convertStackToVolumeLabelmap },
state: { addColorLUT },
triggerSegmentationEvents: { triggerSegmentationRepresentationModified },
} = cstSegmentation;
export type SegmentRepresentation = {
segmentIndex: number;
color: csTypes.Color;
opacity: number;
visible: boolean;
};
export type SegmentationData = cstTypes.Segmentation;
export type SegmentationRepresentation = cstTypes.SegmentationRepresentation & {
viewportId: string;
id: string;
label: string;
fallbackLabel?: string;
styles: cstTypes.RepresentationStyle;
segments: {
[key: number]: SegmentRepresentation;
};
};
export type SegmentationInfo = {
segmentation: SegmentationData;
representation?: SegmentationRepresentation;
};
const EVENTS = {
SEGMENTATION_MODIFIED: 'event::segmentation_modified',
// fired when the segmentation is added
SEGMENTATION_ADDED: 'event::segmentation_added',
//
SEGMENTATION_DATA_MODIFIED: 'event::segmentation_data_modified',
// fired when the segmentation is removed
SEGMENTATION_REMOVED: 'event::segmentation_removed',
//
// fired when segmentation representation is added
SEGMENTATION_REPRESENTATION_MODIFIED: 'event::segmentation_representation_modified',
// fired when segmentation representation is removed
SEGMENTATION_REPRESENTATION_REMOVED: 'event::segmentation_representation_removed',
//
// LOADING EVENTS
// fired when the active segment is loaded in SEG or RTSTRUCT
SEGMENT_LOADING_COMPLETE: 'event::segment_loading_complete',
// loading completed for all segments
SEGMENTATION_LOADING_COMPLETE: 'event::segmentation_loading_complete',
// fired when a contour annotation cut merge process is completed
SEGMENTATION_ANNOTATION_CUT_MERGE_PROCESS_COMPLETED:
'event::annotation_cut_merge_process_completed',
SEGMENTATION_STYLE_MODIFIED: 'event::segmentation_style_modified',
};
const VALUE_TYPES = {};
class SegmentationService extends PubSubService implements ISegmentationServiceInternals {
static REGISTRATION = {
name: 'segmentationService',
altName: 'SegmentationService',
create: ({ servicesManager }: OHIFTypes.Extensions.ExtensionParams): SegmentationService => {
return new SegmentationService({ servicesManager });
},
};
private _segmentationIdToColorLUTIndexMap: Map<string, number>;
private _segmentationGroupStatsMap: Map<string, any>;
private readonly _legacySegBackend: ISegmentationBackend;
private readonly _nextSegBackend: ISegmentationBackend;
readonly servicesManager: AppTypes.ServicesManager;
highlightIntervalId = null;
readonly EVENTS = EVENTS;
constructor({ servicesManager }) {
super(EVENTS);
this._segmentationIdToColorLUTIndexMap = new Map();
this.servicesManager = servicesManager;
this._segmentationGroupStatsMap = new Map();
// Segmentation backend twins (mirror the viewport backend family). Routed PER
// VIEWPORT via _segBackend() using the adapter's isNextViewport predicate,
// because a flag-on session can mix native and legacy viewports. Both are
// constructed eagerly:
// per-viewport dispatch has no per-session flag to defer on, and the twins read
// state at call time (post-init), not at construction.
this._legacySegBackend = new LegacySegmentationBackend(this);
this._nextSegBackend = new NextSegmentationBackend();
}
/**
* Picks the segmentation backend lane for a specific viewport: the native
* ("next") twin for a raw GenericViewport (PlanarViewport), the legacy twin
* otherwise. Mirrors viewportOperations' per-viewport dispatch.
*/
private _segBackend(viewport: csTypes.IViewport): ISegmentationBackend {
return isNextViewport(viewport) ? this._nextSegBackend : this._legacySegBackend;
}
public onModeEnter(): void {
this._initSegmentationService();
}
public onModeExit(): void {
this.destroy();
}
/**
* Retrieves a segmentation by its ID.
*
* @param segmentationId - The unique identifier of the segmentation to retrieve.
* @returns The segmentation object if found, or undefined if not found.
*
* @remarks
* This method directly accesses the cornerstone tools segmentation state to fetch
* the segmentation data. It's useful when you need to access specific properties
* or perform operations on a particular segmentation.
*/
public getSegmentation(segmentationId: string): cstTypes.Segmentation | undefined {
return cstSegmentation.state.getSegmentation(segmentationId);
}
/**
* Retrieves all segmentations from the cornerstone tools segmentation state.
*
* @returns An array of all segmentations currently stored in the state
*
* @remarks
* This is a convenience method that directly accesses the cornerstone tools
* segmentation state to get all available segmentations. It returns the raw
* segmentation objects without any additional processing or filtering.
*/
public getSegmentations(): cstTypes.Segmentation[] | [] {
return cstSegmentation.state.getSegmentations();
}
public getPresentation(viewportId: string): SegmentationPresentation {
const segmentationPresentations: SegmentationPresentation = [];
const segmentationsMap = new Map<string, SegmentationPresentationItem>();
const representations = this.getSegmentationRepresentations(viewportId);
for (const representation of representations) {
Iif (!representation) {
continue;
}
const { segmentationId, type } = representation;
segmentationsMap.set(segmentationId, {
segmentationId,
type,
hydrated: true,
config: representation.config || {},
});
}
// Check inside the removedDisplaySetAndRepresentationMaps to see if any of the representations are not hydrated
// const hydrationMap = this._segmentationRepresentationHydrationMaps.get(presentationId);
// if (hydrationMap) {
// hydrationMap.forEach(rep => {
// segmentationsMap.set(rep.segmentationId, {
// segmentationId: rep.segmentationId,
// type: rep.type,
// hydrated: rep.hydrated,
// config: rep.config || {},
// });
// });
// }
// // Convert the Map to an array
segmentationPresentations.push(...segmentationsMap.values());
return segmentationPresentations;
}
public getRepresentationsForSegmentation(
segmentationId: string
): { viewportId: string; representations: any[] }[] {
const representations =
cstSegmentation.state.getSegmentationRepresentationsBySegmentationId(segmentationId);
return representations;
}
/**
* Retrieves segmentation representations (labelmap, contour, surface) based on specified criteria.
*
* @param viewportId - The ID of the viewport.
* @param specifier - An object containing optional `segmentationId` and `type` to filter the representations.
* @returns An array of `SegmentationRepresentation` matching the criteria, or an empty array if none are found.
*
* @remarks
* This method filters the segmentation representations according to the provided `specifier`:
* - **No `segmentationId` or `type` provided**: Returns all representations associated with the given `viewportId`.
* - **Only `segmentationId` provided**: Returns all representations with that `segmentationId`, regardless of `viewportId`.
* - **Only `type` provided**: Returns all representations of that `type` associated with the given `viewportId`.
* - **Both `segmentationId` and `type` provided**: Returns representations matching both criteria, regardless of `viewportId`.
*/
public getSegmentationRepresentations(
viewportId: string,
specifier: {
segmentationId?: string;
type?: csToolsEnums.SegmentationRepresentations;
} = {}
): SegmentationRepresentation[] {
// Get all representations for the viewportId
const representations = cstSegmentation.state.getSegmentationRepresentations(
viewportId,
specifier
);
// Map to our SegmentationRepresentation type
const ohifRepresentations = representations.map(repr =>
this._toOHIFSegmentationRepresentation(viewportId, repr)
);
return ohifRepresentations;
}
public destroy = () => {
eventTarget.removeEventListener(
csToolsEnums.Events.SEGMENTATION_MODIFIED,
this._onSegmentationModifiedFromSource
);
eventTarget.removeEventListener(
csToolsEnums.Events.SEGMENTATION_REMOVED,
this._onSegmentationRemovedFromSource
);
eventTarget.removeEventListener(
csToolsEnums.Events.SEGMENTATION_DATA_MODIFIED,
this._onSegmentationDataModifiedFromSource
);
eventTarget.removeEventListener(
csToolsEnums.Events.SEGMENTATION_REPRESENTATION_MODIFIED,
this._onSegmentationRepresentationModifiedFromSource
);
eventTarget.removeEventListener(
csToolsEnums.Events.SEGMENTATION_REPRESENTATION_ADDED,
this._onSegmentationRepresentationModifiedFromSource
);
eventTarget.removeEventListener(
csToolsEnums.Events.SEGMENTATION_REPRESENTATION_REMOVED,
this._onSegmentationRepresentationRemovedFromSource
);
eventTarget.removeEventListener(
csToolsEnums.Events.SEGMENTATION_ADDED,
this._onSegmentationAddedFromSource
);
this.reset();
};
public async addSegmentationRepresentation(
viewportId: string,
{
segmentationId,
predecessorImageId,
type,
config,
suppressEvents = false,
}: {
segmentationId: string;
predecessorImageId?: string;
type?: csToolsEnums.SegmentationRepresentations;
config?: {
blendMode?: csEnums.BlendModes;
useSliceRendering?: boolean;
};
suppressEvents?: boolean;
}
): Promise<void> {
const segmentation = this.getSegmentation(segmentationId);
Iif (!segmentation) {
console.warn(
`addSegmentationRepresentation: segmentation "${segmentationId}" is not in state yet`
);
return;
}
if (!segmentation.predecessorImageId && predecessorImageId) {
segmentation.predecessorImageId = predecessorImageId;
}
const csViewport = this.getAndValidateViewport(viewportId);
Iif (!csViewport) {
return;
}
// A stale/invalid segmentationId yields no segmentation; fail fast with a clear
// message instead of dereferencing representationData deep inside the backend
// classification below.
Iif (!segmentation) {
throw new Error(
`SegmentationService: cannot add representation - segmentation "${segmentationId}" not found.`
);
}
const colorLUTIndex = this._segmentationIdToColorLUTIndexMap.get(segmentationId);
let isConverted = false;
const defaultRepresentationType: csToolsEnums.SegmentationRepresentations =
isVolume3DViewportType(csViewport) ? SURFACE : LABELMAP;
let representationTypeToUse = type || defaultRepresentationType;
if (representationTypeToUse === LABELMAP) {
({ representationTypeToUse, isConverted } = await this._segBackend(
csViewport
).classifyAndPrepareLabelmapAdd(
csViewport,
segmentation,
viewportId,
segmentationId,
representationTypeToUse
));
// Overlap precondition: an overlapping SEG is registered as multiple labelmap
// layers, but cornerstone only stacks them (slice rendering) when the viewport
// renders as a volume slice (VTK_VOLUME_SLICE) — i.e. an MPR/volume viewport. On
// a stack/acquisition viewport the render plan falls back to a single layer, so
// only the primary group is visible. Warn rather than fail silently.
const labelmapLayers = segmentation?.representationData?.[LABELMAP]?.labelmaps;
const isOverlapping = labelmapLayers && Object.keys(labelmapLayers).length > 1;
if (
isOverlapping &&
isNextViewport(csViewport) &&
!csUtils.viewportIsInVolumeMode(csViewport)
) {
console.warn(
`Overlapping segmentation ${segmentationId} has multiple labelmap layers, but ` +
`viewport ${viewportId} does not render as a volume slice (VTK_VOLUME_SLICE); ` +
`only the primary layer will be visible. Display the segmentation in an ` +
`MPR/volume layout to see all overlapping segments.`
);
}
}
await this._addSegmentationRepresentation(
viewportId,
segmentationId,
representationTypeToUse,
colorLUTIndex,
isConverted,
config
);
if (!suppressEvents) {
this._broadcastEvent(this.EVENTS.SEGMENTATION_REPRESENTATION_MODIFIED, { segmentationId });
}
}
/**
* Creates an labelmap segmentation for a given display set
*
* @param displaySet - The display set to create the segmentation for.
* @param options - Optional parameters for creating the segmentation.
* @param options.segmentationId - Custom segmentation ID. If not provided, a UUID will be generated.
* @param options.FrameOfReferenceUID - Frame of reference UID for the segmentation.
* @param options.label - Label for the segmentation.
* @returns A promise that resolves to the created segmentation ID.
*/
public async createLabelmapForDisplaySet(
displaySet: AppTypes.DisplaySet,
options?: {
segmentationId?: string;
segments?: { [segmentIndex: number]: Partial<cstTypes.Segment> };
FrameOfReferenceUID?: string;
label?: string;
/** The caller invented the label, so the user has not chosen a name. */
labelIsGenerated?: boolean;
}
): Promise<string> {
return this._createSegmentationForDisplaySet(displaySet, LABELMAP, options);
}
public async createContourForDisplaySet(
displaySet: AppTypes.DisplaySet,
options?: {
segmentationId?: string;
segments?: { [segmentIndex: number]: Partial<cstTypes.Segment> };
FrameOfReferenceUID?: string;
label?: string;
/** The caller invented the label, so the user has not chosen a name. */
labelIsGenerated?: boolean;
}
): Promise<string> {
return this._createSegmentationForDisplaySet(displaySet, CONTOUR, options);
}
/**
* Private method to create segmentation for a display set with the specified type
*
* @param displaySet - The display set to create the segmentation for
* @param segmentationType - The type of segmentation (SegmentationRepresentations enum)
* @param options - Optional parameters for creating the segmentation
* @returns A promise that resolves to the created segmentation ID
*/
private async _createSegmentationForDisplaySet(
displaySet: AppTypes.DisplaySet,
segmentationType: SegmentationRepresentations,
options?: {
segmentationId?: string;
segments?: { [segmentIndex: number]: Partial<cstTypes.Segment> };
FrameOfReferenceUID?: string;
label?: string;
/** The caller invented the label, so the user has not chosen a name. */
labelIsGenerated?: boolean;
}
): Promise<string> {
// Todo: random does not makes sense, make this better, like
// labelmap 1, 2, 3 etc
const segmentationId = options?.segmentationId ?? `${csUtils.uuidv4()}`;
const isDynamicVolume = displaySet.isDynamicVolume;
let referenceImageIds = displaySet.imageIds;
Iif (isDynamicVolume) {
// get the middle timepoint for referenceImageIds
const timePoints = displaySet.dynamicVolumeInfo.timePoints;
const middleTimePoint = timePoints[Math.floor(timePoints.length / 2)];
referenceImageIds = middleTimePoint;
}
const derivedImages = await imageLoader.createAndCacheDerivedLabelmapImages(referenceImageIds);
const segs = this.getSegmentations();
const label = options?.label || `Segmentation ${segs.length + 1}`;
const segImageIds = derivedImages.map(image => image.imageId);
const segmentationPublicInput: cstTypes.SegmentationPublicInput = {
segmentationId,
representation: {
type: segmentationType,
data: {
imageIds: segImageIds,
// referencedVolumeId: this._getVolumeIdForDisplaySet(displaySet),
referencedImageIds: referenceImageIds,
},
},
config: {
label,
// Explicit, because `label` below always has a value by this point.
labelIsGenerated: options?.labelIsGenerated ?? !options?.label,
fallbackLabel: `S:${displaySet.SeriesNumber} ${displaySet.Modality}`,
segments:
options?.segments && Object.keys(options.segments).length > 0
? options.segments
: {
1: {
label: `${i18n.t('Segment')} 1`,
active: true,
},
},
cachedStats: {
info: `S${displaySet.SeriesNumber}: ${displaySet.SeriesDescription}`,
},
},
};
// Create a dedicated color LUT up front and remember its index so that every
// representation of this segmentation (one per viewport) reuses the same LUT.
// Otherwise each viewport would get its own default LUT copy and editing a
// segment color on one viewport would not be reflected on the others (the
// segment color appears to revert to the default when interacting elsewhere).
// The caller may pass the id of an existing segmentation, which this method
// updates rather than replaces; keep its LUT so representations already
// rendering it don't diverge from the ones created afterwards.
if (!this._segmentationIdToColorLUTIndexMap.has(segmentationId)) {
const colorLUTIndex = addColorLUT([[0, 0, 0, 0]] as csTypes.ColorLUT);
this._segmentationIdToColorLUTIndexMap.set(segmentationId, colorLUTIndex);
}
this.addOrUpdateSegmentation(segmentationPublicInput);
return segmentationId;
}
public async createSegmentationForSEGDisplaySet(
segDisplaySet,
options: {
segmentationId?: string;
type: csToolsEnums.SegmentationRepresentations;
} = {
type: LABELMAP,
}
): Promise<string> {
const { type } = options;
let { segmentationId } = options;
const { labelMapImages } = segDisplaySet;
Iif (type !== LABELMAP) {
throw new Error('Only labelmap type is supported for SEG display sets right now');
}
Iif (!labelMapImages || !labelMapImages.length) {
throw new Error('SEG reading failed');
}
segmentationId = segmentationId ?? segDisplaySet.displaySetInstanceUID;
const referencedDisplaySetInstanceUID = segDisplaySet.referencedDisplaySetInstanceUID;
const referencedDisplaySet = this.servicesManager.services.displaySetService.getDisplaySetByUID(
referencedDisplaySetInstanceUID
);
const images = referencedDisplaySet.instances;
Iif (!images.length) {
throw new Error('No instances were provided for the referenced display set of the SEG');
}
// Use the same imageIds as SEG parse (_loadSegments stores these on segDisplaySet).
const imageIds =
segDisplaySet.referencedImageIds ||
(referencedDisplaySet.imageIds as string[] | undefined) ||
images.map(image => image.imageId);
Iif (!imageIds?.length) {
throw new Error('referencedDisplaySet has no imageIds for SEG');
}
const derivedImages = labelMapImages?.flat();
const derivedImageIds = derivedImages.map(image => image.imageId);
// Note: instance runtime props (frameNumber, imageId, url, ...) are
// intentionally non-enumerable, so this spread deliberately does NOT copy
// them — frameNumber must not be carried onto these derived image entries.
// Read such props off the original instance, never off a copy.
segDisplaySet.images = derivedImages.map(image => ({
...image,
...metaData.get('instance', image.referencedImageId),
}));
segDisplaySet.imageIds = derivedImageIds;
// We should parse the segmentation as separate slices to support overlapping segments.
// This parsing should occur in the CornerstoneJS library adapters.
// For now, we use the volume returned from the library and chop it here.
let firstSegmentedSliceImageId = null;
for (let i = 0; i < derivedImages.length; i++) {
const voxelManager = derivedImages[i].voxelManager as csTypes.IVoxelManager<number>;
const scalarData = voxelManager.getScalarData();
voxelManager.setScalarData(scalarData);
// Check if this slice has any non-zero voxels and we haven't found one yet
if (!firstSegmentedSliceImageId && scalarData.some(value => value !== 0)) {
firstSegmentedSliceImageId = derivedImages[i].referencedImageId;
}
}
// assign the first non zero voxel image id to the segDisplaySet
segDisplaySet.firstSegmentedSliceImageId = firstSegmentedSliceImageId;
const segmentsInfo = segDisplaySet.segMetadata.data;
const segments: { [segmentIndex: string]: cstTypes.Segment } = {};
const colorLUT = [];
segmentsInfo.forEach((segmentInfo, index) => {
Iif (index === 0) {
colorLUT.push([0, 0, 0, 0]);
return;
}
const {
SegmentedPropertyCategoryCodeSequence,
SegmentNumber,
SegmentLabel,
SegmentAlgorithmType,
SegmentAlgorithmName,
SegmentedPropertyTypeCodeSequence,
rgba,
} = segmentInfo;
colorLUT.push(rgba);
const segmentIndex = Number(SegmentNumber);
const centroid = segDisplaySet.centroids?.get(index);
const imageCentroidXYZ = centroid?.image || { x: 0, y: 0, z: 0 };
const worldCentroidXYZ = centroid?.world || { x: 0, y: 0, z: 0 };
segments[segmentIndex] = {
segmentIndex,
label: SegmentLabel || `Segment ${SegmentNumber}`,
locked: false,
active: false,
cachedStats: {
center: {
image: [imageCentroidXYZ.x, imageCentroidXYZ.y, imageCentroidXYZ.z],
world: [worldCentroidXYZ.x, worldCentroidXYZ.y, worldCentroidXYZ.z],
},
modifiedTime: segDisplaySet.SeriesDate,
category: SegmentedPropertyCategoryCodeSequence
? SegmentedPropertyCategoryCodeSequence.CodeMeaning
: '',
type: SegmentedPropertyTypeCodeSequence
? SegmentedPropertyTypeCodeSequence.CodeMeaning
: '',
algorithmType: SegmentAlgorithmType,
algorithmName: SegmentAlgorithmName,
},
};
});
const colorLUTIndex = addColorLUT(colorLUT);
this._segmentationIdToColorLUTIndexMap.set(segmentationId, colorLUTIndex);
// Build the segmentation input via the backend twin. At SEG-load there is no
// target viewport yet, so the lane is chosen by the session flag (the one
// viewport-less seg-backend dispatch): the next twin registers overlapping SEGs
// as multiple labelmap layers (slice rendering); the legacy twin keeps the single
// flattened layer (byte-identical).
const segBackend = isNextViewportsEnabled() ? this._nextSegBackend : this._legacySegBackend;
const seg = segBackend.assembleSegmentationDataForSEG({
segmentationId,
segDisplaySet,
derivedImageIds,
referencedImageIds: imageIds as string[],
label: segDisplaySet.SeriesDescription,
fallbackLabel: `S:${segDisplaySet.SeriesNumber} ${segDisplaySet.Modality}`,
segments,
});
segDisplaySet.isLoaded = true;
// Add the segmentation to cornerstone state BEFORE broadcasting that loading is
// complete. Subscribers (e.g. CornerstoneViewportService) react synchronously and
// call addSegmentationRepresentation, which now early-returns when the segmentation
// is not yet in cornerstone state. Broadcasting first would make that guard always
// fire on initial load, silently preventing the representation from being attached.
this.addOrUpdateSegmentation(seg);
this._broadcastEvent(EVENTS.SEGMENTATION_LOADING_COMPLETE, {
segmentationId,
segDisplaySet,
});
return segmentationId;
}
public async createSegmentationForRTDisplaySet(
rtDisplaySet,
options: {
segmentationId?: string;
type: csToolsEnums.SegmentationRepresentations;
} = {
type: CONTOUR,
}
): Promise<string> {
const { type } = options;
let { segmentationId } = options;
// Currently, only contour representation is supported for RT display
Iif (type !== CONTOUR) {
throw new Error('Only contour type is supported for RT display sets right now');
}
// Assign segmentationId if not provided
segmentationId = segmentationId ?? rtDisplaySet.displaySetInstanceUID;
const { structureSet } = rtDisplaySet;
Iif (!structureSet) {
throw new Error(
'To create the contours from RT displaySet, the displaySet should be loaded first. You can perform rtDisplaySet.load() before calling this method.'
);
}
const rtDisplaySetUID = rtDisplaySet.displaySetInstanceUID;
const referencedDisplaySet = this.servicesManager.services.displaySetService.getDisplaySetByUID(
rtDisplaySet.referencedDisplaySetInstanceUID
);
const referencedImageIdsWithGeometry = Array.from(structureSet.ReferencedSOPInstanceUIDsSet);
const referencedImageIds = referencedDisplaySet.imageIds;
// find the first image id that contains a referenced SOP instance UID
const firstSegmentedSliceImageId =
referencedImageIds?.find(imageId =>
referencedImageIdsWithGeometry.some(referencedId =>
imageId.includes(referencedId as string)
)
) || null;
rtDisplaySet.firstSegmentedSliceImageId = firstSegmentedSliceImageId;
Iif (!structureSet.ROIContours?.length) {
throw new Error(
'The structureSet does not contain any ROIContours. Please ensure the structureSet is loaded first.'
);
}
// Map ROI contours to RT Struct Data
const allRTStructData = mapROIContoursToRTStructData(structureSet, rtDisplaySetUID);
// Sort by segmentIndex for consistency
allRTStructData.sort((a, b) => a.segmentIndex - b.segmentIndex);
const geometryIds = allRTStructData.map(({ geometryId }) => geometryId);
// Initialize SegmentationPublicInput similar to SEG function
const segmentation: cstTypes.SegmentationPublicInput = {
segmentationId,
representation: {
type: CONTOUR,
data: {
geometryIds,
},
},
config: {
label: rtDisplaySet.SeriesDescription,
fallbackLabel: `S:${rtDisplaySet.SeriesNumber} ${rtDisplaySet.Modality}`,
},
};
const segments: { [segmentIndex: string]: cstTypes.Segment } = {};
let segmentsCachedStats = {};
// Create colorLUT array for RT structures
const colorLUT = [[0, 0, 0, 0]]; // First entry is transparent for index 0
// Process each segment similarly to the SEG function
for (let i = 0; i < allRTStructData.length; i++) {
const rtStructData = allRTStructData[i];
const { data, id, color, segmentIndex, geometryId, group } = rtStructData;
// Add the color to the colorLUT array
colorLUT.push(color);
try {
const geometry = await geometryLoader.createAndCacheGeometry(geometryId, {
geometryData: {
data,
id,
color,
frameOfReferenceUID: structureSet.frameOfReferenceUID,
segmentIndex,
},
type: csEnums.GeometryType.CONTOUR,
});
const contourSet = geometry.data as csTypes.IContourSet;
const centroid = contourSet.centroid;
segmentsCachedStats = {
center: { world: centroid },
modifiedTime: rtDisplaySet.SeriesDate, // Using SeriesDate as modifiedTime
};
segments[segmentIndex] = {
label: id,
segmentIndex,
cachedStats: segmentsCachedStats,
locked: false,
active: false,
group,
};
// Broadcast segment loading progress
const numInitialized = Object.keys(segmentsCachedStats).length;
const percentComplete = Math.round((numInitialized / allRTStructData.length) * 100);
this._broadcastEvent(EVENTS.SEGMENT_LOADING_COMPLETE, {
percentComplete,
numSegments: allRTStructData.length,
});
} catch (e) {
console.warn(`Error initializing contour for segment ${segmentIndex}:`, e);
continue; // Continue processing other segments even if one fails
}
}
// Create and register the colorLUT
const colorLUTIndex = addColorLUT(colorLUT);
this._segmentationIdToColorLUTIndexMap.set(segmentationId, colorLUTIndex);
// Assign processed segments to segmentation config
segmentation.config.segments = segments;
// Broadcast segmentation loading complete event
this._broadcastEvent(EVENTS.SEGMENTATION_LOADING_COMPLETE, {
segmentationId,
rtDisplaySet,
});
// Mark the RT display set as loaded
rtDisplaySet.isLoaded = true;
// Add or update the segmentation in the state
this.addOrUpdateSegmentation(segmentation);
return segmentationId;
}
/**
* Adds or updates a segmentation in the state
* @param segmentationId - The ID of the segmentation to add or update
* @param data - The data to add or update the segmentation with
*
* @remarks
* This method handles the addition or update of a segmentation in the state.
* If the segmentation already exists, it updates the existing segmentation.
* If the segmentation does not exist, it adds a new segmentation.
*/
public addOrUpdateSegmentation(
data: cstTypes.SegmentationPublicInput | Partial<cstTypes.Segmentation>
) {
const segmentationId = data.segmentationId;
const existingSegmentation = cstSegmentation.state.getSegmentation(segmentationId);
if (existingSegmentation) {
// Update the existing segmentation
this.updateSegmentationInSource(segmentationId, data as Partial<cstTypes.Segmentation>);
} else if (
'representation' in data &&
(data as cstTypes.SegmentationPublicInput).representation
) {
// Add a new segmentation
this.addSegmentationToSource(data as cstTypes.SegmentationPublicInput);
} else E{
console.warn(
`addOrUpdateSegmentation: skipping add for ${segmentationId} — missing representation`
);
}
}
public setActiveSegmentation(viewportId: string, segmentationId: string): void {
cstSegmentation.activeSegmentation.setActiveSegmentation(viewportId, segmentationId);
}
/**
* Gets the active segmentation for a viewport
* @param viewportId - The ID of the viewport to get the active segmentation for
* @returns The active segmentation object, or null if no segmentation is active
*
* @remarks
* This method retrieves the currently active segmentation for the specified viewport.
* The active segmentation is the one that is currently selected for editing operations.
* Returns null if no segmentation is active in the viewport.
*/
public getActiveSegmentation(viewportId: string): cstTypes.Segmentation | null {
return cstSegmentation.activeSegmentation.getActiveSegmentation(viewportId);
}
/**
* Gets the active segment from the active segmentation in a viewport
* @param viewportId - The ID of the viewport to get the active segment from
* @returns The active segment object, or undefined if no segment is active
*
* @remarks
* This method retrieves the currently active segment from the active segmentation
* in the specified viewport. The active segment is the one that is currently
* selected for editing operations. Returns undefined if no segment is active or
* if there is no active segmentation.
*/
public getActiveSegment(viewportId: string): cstTypes.Segment | undefined {
const activeSegmentation = this.getActiveSegmentation(viewportId);
Iif (!activeSegmentation) {
return;
}
const { segments } = activeSegmentation;
let activeSegment;
for (const segment of Object.values(segments)) {
if (segment.active) {
activeSegment = segment;
break;
}
}
return activeSegment;
}
public hasCustomStyles(specifier: {
viewportId: string;
segmentationId: string;
type: csToolsEnums.SegmentationRepresentations;
}): boolean {
return cstSegmentation.config.style.hasCustomStyle(specifier);
}
public getStyle = (specifier: {
viewportId: string;
segmentationId: string;
type: csToolsEnums.SegmentationRepresentations;
segmentIndex?: number;
}) => {
const style = cstSegmentation.config.style.getStyle(specifier);
return style;
};
public setStyle = (
specifier: {
type: csToolsEnums.SegmentationRepresentations;
viewportId?: string;
segmentationId?: string;
segmentIndex?: number;
},
style: cstTypes.LabelmapStyle | cstTypes.ContourStyle | cstTypes.SurfaceStyle,
merge: boolean = true
) => {
cstSegmentation.config.style.setStyle(specifier, style, merge);
this._broadcastEvent(EVENTS.SEGMENTATION_STYLE_MODIFIED, {
specifier,
style,
merge,
});
};
public resetToGlobalStyle = () => {
cstSegmentation.config.style.resetToGlobalStyle();
};
public getNextAvailableSegmentIndex(segmentationId: string): number {
const csSegmentation = this.getCornerstoneSegmentation(segmentationId);
// grab the next available segment index based on the object keys,
// so basically get the highest segment index value + 1
const segmentKeys = Object.keys(csSegmentation.segments);
return segmentKeys.length === 0 ? 1 : Math.max(...segmentKeys.map(Number)) + 1;
}
/**
* Adds a new segment to the specified segmentation.
* @param segmentationId - The ID of the segmentation to add the segment to.
* @param viewportId: The ID of the viewport to add the segment to, it is used to get the representation, if it is not
* provided, the first available representation for the segmentationId will be used.
* @param config - An object containing the configuration options for the new segment.
* - segmentIndex: (optional) The index of the segment to add. If not provided, the next available index will be used.
* - properties: (optional) An object containing the properties of the new segment.
* - label: (optional) The label of the new segment. If not provided, a default label will be used.
* - color: (optional) The color of the new segment in RGB format. If not provided, a default color will be used.
* - visibility: (optional) Whether the new segment should be visible. If not provided, the segment will be visible by default.
* - isLocked: (optional) Whether the new segment should be locked for editing. If not provided, the segment will not be locked by default.
* - active: (optional) Whether the new segment should be the active segment to be edited. If not provided, the segment will not be active by default.
*/
public addSegment(
segmentationId: string,
config: {
segmentIndex?: number;
label?: string;
isLocked?: boolean;
active?: boolean;
color?: csTypes.Color; // Add color type
visibility?: boolean; // Add visibility option
cachedStats?: Record<string, unknown>;
} = {}
): void {
Iif (config?.segmentIndex === 0) {
throw new Error(i18n.t('Segment') + ' index 0 is reserved for "no label"');
}
const csSegmentation = this.getCornerstoneSegmentation(segmentationId);
let segmentIndex = config.segmentIndex;
if (!segmentIndex) {
segmentIndex = this.getNextAvailableSegmentIndex(segmentationId);
}
// update the segmentation
if (!config.label) {
config.label = `${i18n.t('Segment')} ${segmentIndex}`;
}
const currentSegments = csSegmentation.segments;
cstSegmentation.updateSegmentations([
{
segmentationId,
payload: {
segments: {
...currentSegments,
[segmentIndex]: {
...currentSegments[segmentIndex],
segmentIndex,
cachedStats: {},
locked: false,
...config,
},
},
},
},
]);
this.setActiveSegment(segmentationId, segmentIndex);
// Apply additional configurations
Iif (config.isLocked !== undefined) {
this._setSegmentLockedStatus(segmentationId, segmentIndex, config.isLocked);
}
// Get all viewports that have this segmentation
const viewportIds = this.getViewportIdsWithSegmentation(segmentationId);
viewportIds.forEach(viewportId => {
// Set color if provided
Iif (config.color !== undefined) {
this.setSegmentColor(viewportId, segmentationId, segmentIndex, config.color);
}
// Set visibility if provided
Iif (config.visibility !== undefined) {
this.setSegmentVisibility(viewportId, segmentationId, segmentIndex, config.visibility);
}
});
}
/**
* Creates a memo that records the current state of a segment (segmentationId/segmentIndex)
* so that undo can restore it via addSegment and redo can call removeSegment again
* without recording history.
*
* @param segmentationId - The ID of the segmentation.
* @param segmentIndex - The index of the segment (must still exist when called).
* @param _options - Reserved (e.g. deleting) for future use.
* @returns A Memo with restoreMemo(undo): undo => addSegment, redo => removeSegment (skipRecordingHistory).
*/
public createSegmentIndexMemo(
segmentationId: string,
segmentIndex: number,
_options?: { deleting?: boolean }
): csTypes.Memo | null {
const csSegmentation = this.getCornerstoneSegmentation(segmentationId);
const segment = csSegmentation?.segments?.[segmentIndex];
Iif (!segment) {
return null;
}
let color: csTypes.Color | undefined;
let visibility: boolean | undefined;
const viewportIds = this.getViewportIdsWithSegmentation(segmentationId);
if (viewportIds.length > 0) {
const firstViewportId = viewportIds[0];
const representations = this.getSegmentationRepresentations(firstViewportId, {
segmentationId,
});
const repType = representations[0]?.type ?? LABELMAP;
color = this.getSegmentColor(firstViewportId, segmentationId, segmentIndex);
visibility = cstSegmentation.config.visibility.getSegmentIndexVisibility(
firstViewportId,
{ segmentationId, type: repType },
segmentIndex
);
}
const segmentState = {
segmentIndex,
label: segment.label,
isLocked: segment.locked,
active: segment.active,
color,
visibility,
};
const service = this;
const memo: csTypes.Memo = {
id: csUtils.uuidv4(),
operationType: 'segmentIndex',
restoreMemo(undo?: boolean) {
if (undo === true) {
service.addSegment(segmentationId, segmentState);
} else {
// Redo: remove the segment via cornerstone without recording history
cstSegmentation.removeSegment(segmentationId, segmentIndex, { recordHistory: false });
}
},
};
return memo;
}
/**
* Removes a segment from a segmentation and updates the active segment index if necessary.
*
* @param segmentationId - The ID of the segmentation containing the segment to remove.
* @param segmentIndex - The index of the segment to remove.
* @param options - Optional. skipRecordingHistory: if true, do not push undo memo (used when redoing).
*
* @remarks
* This method performs the following actions:
* 1. Clears the segment value in the Cornerstone segmentation.
* 2. Updates all related segmentation representations to remove the segment.
* 3. If the removed segment was the active segment, it updates the active segment index.
*
*/
public removeSegment(
segmentationId: string,
segmentIndex: number,
options?: { skipRecordingHistory?: boolean }
): void {
let memo;
if (!options?.skipRecordingHistory) {
memo = this.createSegmentIndexMemo(segmentationId, segmentIndex, { deleting: true });
DefaultHistoryMemo.startGroupRecording();
cstSegmentation.removeSegment(segmentationId, segmentIndex, { recordHistory: true });
DefaultHistoryMemo.push(memo);
DefaultHistoryMemo.endGroupRecording();
} else E{
cstSegmentation.removeSegment(segmentationId, segmentIndex, { recordHistory: false });
}
}
public setSegmentVisibility(
viewportId: string,
segmentationId: string,
segmentIndex: number,
isVisible: boolean,
type?: csToolsEnums.SegmentationRepresentations
): void {
this._setSegmentVisibility(viewportId, segmentationId, segmentIndex, isVisible, type);
}
/**
* Sets the locked status of a segment in a segmentation.
*
* @param segmentationId - The ID of the segmentation containing the segment.
* @param segmentIndex - The index of the segment to set the locked status for.
* @param isLocked - The new locked status of the segment.
*
* @remarks
* This method updates the locked status of a specific segment within a segmentation.
* A locked segment cannot be modified or edited.
*/
public setSegmentLocked(segmentationId: string, segmentIndex: number, isLocked: boolean): void {
this._setSegmentLockedStatus(segmentationId, segmentIndex, isLocked);
}
/**
* Toggles the locked state of a segment in a segmentation.
* @param segmentationId - The ID of the segmentation.
* @param segmentIndex - The index of the segment to toggle.
*/
public toggleSegmentLocked(segmentationId: string, segmentIndex: number): void {
const isLocked = cstSegmentation.segmentLocking.isSegmentIndexLocked(
segmentationId,
segmentIndex
);
this._setSegmentLockedStatus(segmentationId, segmentIndex, !isLocked);
}
public toggleSegmentVisibility(
viewportId: string,
segmentationId: string,
segmentIndex: number,
type: csToolsEnums.SegmentationRepresentations
): void {
const isVisible = cstSegmentation.config.visibility.getSegmentIndexVisibility(
viewportId,
{
segmentationId,
type,
},
segmentIndex
);
this._setSegmentVisibility(viewportId, segmentationId, segmentIndex, !isVisible, type);
}
/**
* Sets the color of a specific segment in a segmentation.
*
* @param viewportId - The ID of the viewport containing the segmentation
* @param segmentationId - The ID of the segmentation containing the segment
* @param segmentIndex - The index of the segment to set the color for
* @param color - The new color to apply to the segment as an array of RGBA values
*
* @remarks
* This method updates the color of a specific segment within a segmentation.
* The color parameter should be an array of 4 numbers representing RGBA values.
*/
public setSegmentColor(
viewportId: string,
segmentationId: string,
segmentIndex: number,
color: csTypes.Color
): void {
const segmentationRepresentations = this.getSegmentationRepresentations(viewportId, {
segmentationId,
});
const { colorLUTIndex } = segmentationRepresentations[0];
this._segmentationIdToColorLUTIndexMap.set(segmentationId, colorLUTIndex);
cstSegmentation.config.color.setSegmentIndexColor(
viewportId,
segmentationId,
segmentIndex,
color
);
}
/**
* Gets the current color of a specific segment in a segmentation.
*
* @param viewportId - The ID of the viewport containing the segmentation
* @param segmentationId - The ID of the segmentation containing the segment
* @param segmentIndex - The index of the segment to get the color for
* @returns An array of 4 numbers representing the RGBA color values of the segment
*
* @remarks
* This method retrieves the current color of a specific segment within a segmentation.
* The returned color is an array of 4 numbers representing RGBA values.
*/
public getSegmentColor(viewportId: string, segmentationId: string, segmentIndex: number) {
return cstSegmentation.config.color.getSegmentIndexColor(
viewportId,
segmentationId,
segmentIndex
);
}
/**
* Gets the labelmap volume for a segmentation
* @param segmentationId - The ID of the segmentation to get the labelmap volume for
* @returns The labelmap volume for the segmentation, or null if not found
*
* @remarks
* This method retrieves the labelmap volume data for a specific segmentation.
* The labelmap volume contains the actual segmentation data in the form of a 3D volume.
* Returns null if the segmentation does not have valid labelmap volume data.
*/
public getLabelmapVolume(segmentationId: string) {
const csSegmentation = cstSegmentation.state.getSegmentation(segmentationId);
const labelmapData = csSegmentation.representationData[
LABELMAP
] as cstTypes.LabelmapToolOperationDataVolume;
Iif (!labelmapData || !labelmapData.volumeId) {
return null;
}
const { volumeId } = labelmapData;
const labelmapVolume = cache.getVolume(volumeId);
return labelmapVolume;
}
/**
* Sets the label for a specific segment in a segmentation
* @param segmentationId - The ID of the segmentation containing the segment
* @param segmentIndex - The index of the segment to set the label for
* @param label - The new label to apply to the segment
*
* @remarks
* This method updates the text label of a specific segment within a segmentation.
* The label is used to identify and describe the segment in the UI.
*/
public setSegmentLabel(segmentationId: string, segmentIndex: number, label: string) {
this._setSegmentLabel(segmentationId, segmentIndex, label);
}
/**
* Sets the active segment for a segmentation
* @param segmentationId - The ID of the segmentation containing the segment
* @param segmentIndex - The index of the segment to set as active
*
* @remarks
* This method updates which segment is considered "active" within a segmentation.
* The active segment is typically highlighted and available for editing operations.
*/
public setActiveSegment(segmentationId: string, segmentIndex: number): void {
this._setActiveSegment(segmentationId, segmentIndex);
}
/**
* Controls whether inactive segmentations should be rendered in a viewport
* @param viewportId - The ID of the viewport to update
* @param renderInactive - Whether inactive segmentations should be rendered
*
* @remarks
* This method configures if segmentations that are not currently active
* should still be visible in the specified viewport. This can be useful
* for comparing or viewing multiple segmentations simultaneously.
*/
public setRenderInactiveSegmentations(viewportId: string, renderInactive: boolean): void {
cstSegmentation.config.style.setRenderInactiveSegmentations(viewportId, renderInactive);
}
/**
* Gets whether inactive segmentations are being rendered for a viewport
* @param viewportId - The ID of the viewport to check
* @returns boolean indicating if inactive segmentations are rendered
*
* @remarks
* This method retrieves the current rendering state for inactive segmentations
* in the specified viewport. Returns true if inactive segmentations are visible.
*/
public getRenderInactiveSegmentations(viewportId: string): boolean {
return cstSegmentation.config.style.getRenderInactiveSegmentations(viewportId);
}
/**
* Sets statistics for a group of segmentations
* @param segmentationIds - Array of segmentation IDs that form the group
* @param stats - Statistics object containing metrics for the segmentation group
*
* @remarks
* This method stores statistical data for a group of related segmentations.
* The stats are stored using a composite key created from the sorted and joined
*/
public setSegmentationGroupStats(segmentationIds: string[], stats: any) {
const groupId = this.getGroupId(segmentationIds);
this._segmentationGroupStatsMap.set(groupId, stats);
}
/**
* Gets statistics for a group of segmentations
* @param segmentationIds - Array of segmentation IDs that form the group
* @returns The stored statistics object for the segmentation group if found, undefined otherwise
*/
public getSegmentationGroupStats(segmentationIds: string[]) {
const groupId = this.getGroupId(segmentationIds);
return this._segmentationGroupStatsMap.get(groupId);
}
private getGroupId(segmentationIds: string[]) {
return segmentationIds.sort().join(',');
}
/**
* Toggles the visibility of a segmentation in the state, and broadcasts the event.
* Note: this method does not update the segmentation state in the source. It only
* updates the state, and there should be separate listeners for that.
* @param ids segmentation ids
*/
public toggleSegmentationRepresentationVisibility = (
viewportId: string,
{
segmentationId,
type,
}: { segmentationId: string; type: csToolsEnums.SegmentationRepresentations }
): void => {
this._toggleSegmentationRepresentationVisibility(viewportId, segmentationId, type);
};
public getViewportIdsWithSegmentation = (segmentationId: string): string[] => {
const viewportIds = cstSegmentation.state.getViewportIdsWithSegmentation(segmentationId);
return viewportIds;
};
/**
* Clears segmentation representations from the viewport.
* Unlike removeRepresentationsFromViewport, this doesn't update
* removed display set and representation maps.
* We track removed segmentations manually to avoid re-adding them
* when the display set is added again.
* @param viewportId - The viewport ID to clear segmentation representations from.
*/
public clearSegmentationRepresentations(viewportId: string): void {
this.removeRepresentationsFromViewport(viewportId);
}
/**
* Completely removes a segmentation from the state
* @param segmentationId - The ID of the segmentation to remove.
*/
public remove(segmentationId: string): void {
cstSegmentation.state.removeSegmentation(segmentationId);
}
public removeAllSegmentations(): void {
cstSegmentation.state.removeAllSegmentations();
}
/**
* Removes segmentation representations from the viewport.
* @param viewportId - The viewport id to remove the segmentation representations from.
* @param specifier - The specifier to remove the segmentation representations.
*
* @remarks
* If no specifier is provided, all segmentation representations for the viewport are removed.
* If a segmentationId specifier is provided, only the segmentation representation with the specified segmentationId and type are removed.
* If a type specifier is provided, only the segmentation representation with the specified type are removed.
* If both a segmentationId and type specifier are provided, only the segmentation representation with the specified segmentationId and type are removed.
*/
public removeRepresentationsFromViewport(
viewportId: string,
specifier: {
segmentationId?: string;
type?: csToolsEnums.SegmentationRepresentations;
} = {}
): void {
cstSegmentation.removeSegmentationRepresentations(viewportId, specifier);
}
/**
* Jumps to the next slice that contains the specified segment in the viewport.
* For labelmaps, it jumps to the segment center. For contours, it cycles through
* all slices that contain contour data for the segment.
*
* @param segmentationId - The ID of the segmentation
* @param segmentIndex - The index of the segment to jump to
* @param viewportId - Optional viewport ID. If not provided, applies to all viewports with this segmentation
* @param highlightAlpha - Alpha value for highlighting (0-1)
* @param highlightSegment - Whether to highlight the segment after jumping
* @param animationLength - Length of highlight animation in milliseconds
* @param highlightHideOthers - Whether to hide other segments during highlight
* @param animationFunctionType - The easing function to use for animation
*/
public jumpToSegmentNext(
segmentationId: string,
segmentIndex: number,
forViewportId?: string,
direction = 1,
highlightAlpha = 0.9,
highlightSegment = true,
animationLength = 750,
highlightHideOthers = false,
animationFunctionType: EasingFunctionEnum = EasingFunctionEnum.EASE_IN_OUT
): void {
const viewportIds = forViewportId
? [forViewportId]
: this.getViewportIdsWithSegmentation(segmentationId);
viewportIds.forEach(viewportId => {
const representations = this.getSegmentationRepresentations(viewportId, {
segmentationId,
});
Iif (!representations || representations.length === 0) {
return;
}
const representation = representations[0];
const { type } = representation;
// For contours, check if we have a segment center.
const center =
type === CONTOUR ? this._getSegmentCenter(segmentationId, segmentIndex) : undefined;
const canUseSegmentCenter = type !== CONTOUR || !!center;
if (canUseSegmentCenter) {
this.jumpToSegmentCenter(
segmentationId,
segmentIndex,
viewportId,
highlightAlpha,
highlightSegment,
animationLength,
highlightHideOthers,
animationFunctionType,
center
);
return;
}
const { viewport } = getEnabledElementByViewportId(viewportId);
Iif (!viewport) {
return;
}
const viewRefs = this._getContourViewReferences(segmentationId, viewport, segmentIndex);
if (!viewRefs) {
return;
}
// Get the current slice index
const currentSliceIndex = viewport.getCurrentImageIdIndex();
let nearestSliceIndex = null;
let loopSliceIndex = null;
for (const [sliceIndex] of viewRefs.entries()) {
// Track loop index for wraparound (smallest for forward, largest for backward)
if (direction > 0) {
if (loopSliceIndex === null || sliceIndex < loopSliceIndex) {
loopSliceIndex = sliceIndex;
}
} else E{
Iif (loopSliceIndex === null || sliceIndex > loopSliceIndex) {
loopSliceIndex = sliceIndex;
}
}
if (direction > 0) {
// Forward direction: find nearest slice after current
if (sliceIndex <= currentSliceIndex) {
continue;
}
Iif (nearestSliceIndex === null || sliceIndex < nearestSliceIndex) {
nearestSliceIndex = sliceIndex;
}
} else E{
// Backward direction: find nearest slice before current
Iif (sliceIndex >= currentSliceIndex) {
continue;
}
Iif (nearestSliceIndex === null || sliceIndex > nearestSliceIndex) {
nearestSliceIndex = sliceIndex;
}
}
}
// Wraparound: if no slice found in direction, use loop index
nearestSliceIndex = nearestSliceIndex ?? loopSliceIndex;
Iif (nearestSliceIndex === null) {
return;
}
const viewRef = viewRefs.get(nearestSliceIndex);
viewport.setViewReference(viewRef);
viewport.render();
});
}
/**
* Jumps the viewport to the center of hte given segment.
* Only works for labelmaps, and may result in not showing any contours.
*/
public jumpToSegmentCenter(
segmentationId: string,
segmentIndex: number,
viewportId?: string,
highlightAlpha = 0.9,
highlightSegment = true,
animationLength = 750,
highlightHideOthers = false,
animationFunctionType: EasingFunctionEnum = EasingFunctionEnum.EASE_IN_OUT,
center?: { image?: csTypes.Point3; world: csTypes.Point3 }
): void {
const resolvedCenter = center ?? this._getSegmentCenter(segmentationId, segmentIndex);
Iif (!resolvedCenter) {
console.warn('No center found for segmentation', segmentationId, segmentIndex);
return;
}
const { world } = resolvedCenter as { world: csTypes.Point3 };
// need to find which viewports are displaying the segmentation
const viewportIds = viewportId
? [viewportId]
: this.getViewportIdsWithSegmentation(segmentationId);
viewportIds.forEach(viewportId => {
const { viewport } = getEnabledElementByViewportId(viewportId);
Iif (!viewport) {
return;
}
// Recenter via the backend twin: legacy jumpToWorld, or native setViewReference
// (a native PlanarViewport has no jumpToWorld). Skip the highlight when the
// recenter did not happen, matching the previous guarded behavior.
const didJump = this._segBackend(viewport).jumpToSegmentCenter(viewport, world);
didJump &&
highlightSegment &&
this.highlightSegment(
segmentationId,
segmentIndex,
viewportId,
highlightAlpha,
animationLength,
highlightHideOthers,
animationFunctionType
);
});
}
public highlightSegment(
segmentationId: string,
segmentIndex: number,
viewportId?: string,
alpha = 0.9,
animationLength = 750,
hideOthers = true,
animationFunctionType: EasingFunctionEnum = EasingFunctionEnum.EASE_IN_OUT
): void {
Iif (this.highlightIntervalId) {
clearInterval(this.highlightIntervalId);
}
const csSegmentation = this.getCornerstoneSegmentation(segmentationId);
const viewportIds = viewportId
? [viewportId]
: this.getViewportIdsWithSegmentation(segmentationId);
viewportIds.forEach(viewportId => {
const segmentationRepresentation = this.getSegmentationRepresentations(viewportId, {
segmentationId,
});
const representation = segmentationRepresentation[0];
const { type } = representation;
const segments = csSegmentation.segments;
const highlightFn =
type === LABELMAP ? this._highlightLabelmap.bind(this) : this._highlightContour.bind(this);
const adjustedAlpha = type === LABELMAP ? alpha : 1 - alpha;
highlightFn(
segmentIndex,
adjustedAlpha,
hideOthers,
segments,
viewportId,
animationLength,
representation,
animationFunctionType
);
});
}
private getAndValidateViewport(viewportId: string) {
const csViewport =
this.servicesManager.services.cornerstoneViewportService.getCornerstoneViewport(viewportId);
Iif (!csViewport) {
console.warn(`Viewport with id ${viewportId} not found.`);
return null;
}
return csViewport;
}
/**
* Sets the visibility of a segmentation representation.
*
* @param viewportId - The ID of the viewport.
* @param segmentationId - The ID of the segmentation.
* @param isVisible - The new visibility state.
*/
private _setSegmentationRepresentationVisibility(
viewportId: string,
segmentationId: string,
type: csToolsEnums.SegmentationRepresentations,
isVisible: boolean
): void {
const representations = this.getSegmentationRepresentations(viewportId, {
segmentationId,
type,
});
const representation = representations[0];
Iif (!representation) {
console.debug(
'No segmentation representation found for the given viewportId and segmentationId'
);
return;
}
cstSegmentation.config.visibility.setSegmentationRepresentationVisibility(
viewportId,
{
segmentationId,
type,
},
isVisible
);
}
// Labelmap-add classification (determineViewportAndSegmentationType +
// handleViewportConversion + the stack/volume case handlers) now lives in the
// segmentation backend twins (backends/{Legacy,Next}SegmentationBackend), routed
// per viewport via _segBackend(). The legacy twin reaches the viewport-recreation
// and data-volume-conversion helpers below through ISegmentationServiceInternals.
private async _addSegmentationRepresentation(
viewportId: string,
segmentationId: string,
representationType: csToolsEnums.SegmentationRepresentations,
colorLUTIndex: number,
isConverted: boolean,
config?: {
blendMode?: csEnums.BlendModes;
useSliceRendering?: boolean;
}
): Promise<void> {
const representation = {
type: representationType,
segmentationId,
config: { colorLUTOrIndex: colorLUTIndex, ...config },
};
const addRepresentation = () =>
cstSegmentation.addSegmentationRepresentations(viewportId, [representation]);
if (isConverted) {
const { viewportGridService } = this.servicesManager.services;
await new Promise<void>(resolve => {
const { unsubscribe } = viewportGridService.subscribe(
viewportGridService.EVENTS.GRID_STATE_CHANGED,
() => {
addRepresentation();
unsubscribe();
resolve();
}
);
});
} else {
addRepresentation();
}
}
public async handleVolumeViewport(
viewport: csTypes.IVolumeViewport,
segmentation: SegmentationData,
isVolumeSegmentation: boolean
): Promise<void> {
if (isVolumeSegmentation) {
return; // Volume Labelmap on Volume Viewport is natively supported
}
const frameOfReferenceUID = viewport.getFrameOfReferenceUID();
const imageIds = getLabelmapImageIds(segmentation.segmentationId);
const segImage = cache.getImage(imageIds[0]);
if (segImage?.FrameOfReferenceUID === frameOfReferenceUID) {
await convertStackToVolumeLabelmap(segmentation);
}
}
public async convertStackToVolumeViewport(viewport: csTypes.IViewport): Promise<boolean> {
const { viewportGridService, cornerstoneViewportService } = this.servicesManager.services;
const state = viewportGridService.getState();
const gridViewport = state.viewports.get(viewport.id);
const prevViewPresentation = viewport.getViewPresentation();
const prevViewReference = viewport.getViewReference();
const stackViewport = cornerstoneViewportService.getCornerstoneViewport(viewport.id);
const { element } = stackViewport;
const volumeViewportNewVolumeHandler = () => {
const volumeViewport = cornerstoneViewportService.getCornerstoneViewport(viewport.id);
volumeViewport.setViewPresentation(prevViewPresentation);
volumeViewport.setViewReference(prevViewReference);
volumeViewport.render();
element.removeEventListener(
csEnums.Events.VOLUME_VIEWPORT_NEW_VOLUME,
volumeViewportNewVolumeHandler
);
};
element.addEventListener(
csEnums.Events.VOLUME_VIEWPORT_NEW_VOLUME,
volumeViewportNewVolumeHandler
);
viewportGridService.setDisplaySetsForViewport({
viewportId: viewport.id,
displaySetInstanceUIDs: gridViewport.displaySetInstanceUIDs,
viewportOptions: {
...gridViewport.viewportOptions,
viewportType: ViewportType.ORTHOGRAPHIC,
},
});
return true;
}
public async attemptStackToVolumeConversion(
viewport: csTypes.IStackViewport,
segmentation: SegmentationData,
viewportId: string,
segmentationId: string
): Promise<boolean> {
const imageIds = getLabelmapImageIds(segmentation.segmentationId);
const frameOfReferenceUID = viewport.getFrameOfReferenceUID();
const segImage = cache.getImage(imageIds[0]);
if (
segImage?.FrameOfReferenceUID &&
frameOfReferenceUID &&
segImage.FrameOfReferenceUID === frameOfReferenceUID
) {
const isConverted = await this.convertStackToVolumeViewport(viewport);
triggerSegmentationRepresentationModified(viewportId, segmentationId, LABELMAP);
return isConverted;
}
// Frame-of-reference mismatch (or missing): no conversion happened. Return an
// explicit boolean so the Promise<boolean> contract holds for callers.
return false;
}
private addSegmentationToSource(segmentationPublicInput: cstTypes.SegmentationPublicInput) {
cstSegmentation.addSegmentations([segmentationPublicInput]);
}
private updateSegmentationInSource(
segmentationId: string,
payload: Partial<cstTypes.Segmentation>
) {
cstSegmentation.updateSegmentations([{ segmentationId, payload }]);
}
private _toOHIFSegmentationRepresentation(
viewportId: string,
csRepresentation: cstTypes.SegmentationRepresentation
): SegmentationRepresentation {
const { segmentationId, type, active, visible } = csRepresentation;
const { colorLUTIndex } = csRepresentation;
const segmentsRepresentations: { [segmentIndex: number]: SegmentRepresentation } = {};
const segmentation = cstSegmentation.state.getSegmentation(segmentationId);
Iif (!segmentation) {
throw new Error(`Segmentation with ID ${segmentationId} not found.`);
}
const segmentIds = Object.keys(segmentation.segments);
for (const segmentId of segmentIds) {
const segmentIndex = parseInt(segmentId, 10);
const color = cstSegmentation.config.color.getSegmentIndexColor(
viewportId,
segmentationId,
segmentIndex
);
const isVisible = cstSegmentation.config.visibility.getSegmentIndexVisibility(
viewportId,
{
segmentationId,
type,
},
segmentIndex
);
segmentsRepresentations[segmentIndex] = {
color,
segmentIndex,
opacity: color[3],
visible: isVisible,
};
}
const styles = cstSegmentation.config.style.getStyle({
viewportId,
segmentationId,
type,
});
const id = `${segmentationId}-${type}-${viewportId}`;
return {
id: id,
segmentationId,
label: segmentation.label,
fallbackLabel: segmentation.fallbackLabel,
active,
type,
visible,
segments: segmentsRepresentations,
styles,
viewportId,
colorLUTIndex,
config: {},
};
}
private _initSegmentationService() {
eventTarget.addEventListener(
csToolsEnums.Events.SEGMENTATION_MODIFIED,
this._onSegmentationModifiedFromSource
);
eventTarget.addEventListener(
csToolsEnums.Events.SEGMENTATION_REMOVED,
this._onSegmentationRemovedFromSource
);
eventTarget.addEventListener(
csToolsEnums.Events.SEGMENTATION_DATA_MODIFIED,
this._onSegmentationDataModifiedFromSource
);
eventTarget.addEventListener(
csToolsEnums.Events.SEGMENTATION_REPRESENTATION_MODIFIED,
this._onSegmentationRepresentationModifiedFromSource
);
eventTarget.addEventListener(
csToolsEnums.Events.SEGMENTATION_REPRESENTATION_ADDED,
this._onSegmentationRepresentationModifiedFromSource
);
eventTarget.addEventListener(
csToolsEnums.Events.SEGMENTATION_REPRESENTATION_REMOVED,
this._onSegmentationRepresentationRemovedFromSource
);
eventTarget.addEventListener(
csToolsEnums.Events.SEGMENTATION_ADDED,
this._onSegmentationAddedFromSource
);
eventTarget.addEventListener(
csToolsEnums.Events.ANNOTATION_CUT_MERGE_PROCESS_COMPLETED,
this._onAnnotationCutMergeProcessCompletedFromSource
);
}
private getCornerstoneSegmentation(segmentationId: string) {
return cstSegmentation.state.getSegmentation(segmentationId);
}
private _highlightLabelmap(
segmentIndex: number,
alpha: number,
hideOthers: boolean,
segments: cstTypes.Segment[],
viewportId: string,
animationLength: number,
representation: cstTypes.SegmentationRepresentation,
animationFunctionType: EasingFunctionEnum
) {
const { segmentationId } = representation;
const newSegmentSpecificConfig = {
fillAlpha: alpha,
};
Iif (hideOthers) {
throw new Error('hideOthers is not working right now');
}
const { fillAlpha } = this.getStyle({
viewportId,
segmentationId,
type: LABELMAP,
segmentIndex,
}) as cstTypes.LabelmapStyle;
let startTime: number = null;
const animation = (timestamp: number) => {
if (startTime === null) {
startTime = timestamp;
}
const elapsed = timestamp - startTime;
const progress = Math.min(elapsed / animationLength, 1);
const easingFunction = EasingFunctionMap.get(animationFunctionType);
cstSegmentation.config.style.setStyle(
{
segmentationId,
segmentIndex,
type: LABELMAP,
},
{
fillAlpha: easingFunction(progress, fillAlpha),
}
);
if (progress < 1) {
requestAnimationFrame(animation);
} else {
cstSegmentation.config.style.setStyle(
{
segmentationId,
segmentIndex,
type: LABELMAP,
},
{},
false
);
}
};
requestAnimationFrame(animation);
}
private _highlightContour(
segmentIndex: number,
alpha: number,
hideOthers: boolean,
segments: cstTypes.Segment[],
viewportId: string,
animationLength: number,
representation: cstTypes.SegmentationRepresentation,
animationFunctionType: EasingFunctionEnum
) {
const { segmentationId } = representation;
const startTime = performance.now();
const prevStyle = cstSegmentation.config.style.getStyle({
type: CONTOUR,
}) as cstTypes.ContourStyle;
const prevOutlineWidth = prevStyle.outlineWidth;
const animate = (currentTime: number) => {
const progress = (currentTime - startTime) / animationLength;
if (progress >= 1) {
cstSegmentation.config.style.resetToGlobalStyle();
return;
}
const OUTLINE_ANIMATION_SCALE_FACTOR = 5;
const easingFunction = EasingFunctionMap.get(animationFunctionType);
cstSegmentation.config.style.setStyle(
{
segmentationId,
segmentIndex,
type: CONTOUR,
},
{
outlineWidth: easingFunction(progress, prevOutlineWidth, OUTLINE_ANIMATION_SCALE_FACTOR),
}
);
requestAnimationFrame(animate);
};
requestAnimationFrame(animate);
}
private _toggleSegmentationRepresentationVisibility = (
viewportId: string,
segmentationId: string,
type: csToolsEnums.SegmentationRepresentations
): void => {
const segmentsHidden = cstSegmentation.config.visibility.getHiddenSegmentIndices(viewportId, {
segmentationId,
type,
});
const currentVisibility = segmentsHidden.size === 0;
this._setSegmentationRepresentationVisibility(
viewportId,
segmentationId,
type,
!currentVisibility
);
};
private _setActiveSegment(segmentationId: string, segmentIndex: number) {
cstSegmentation.segmentIndex.setActiveSegmentIndex(segmentationId, segmentIndex);
}
private _getVolumeIdForDisplaySet(displaySet) {
const volumeLoaderSchema = displaySet.volumeLoaderSchema ?? VOLUME_LOADER_SCHEME;
return `${volumeLoaderSchema}:${displaySet.displaySetInstanceUID}`;
}
private _getSegmentCenter(
segmentationId: string,
segmentIndex: number
): { image?: csTypes.Point3; world: csTypes.Point3 } | undefined {
const segmentation = this.getSegmentation(segmentationId);
Iif (!segmentation) {
return;
}
const { segments } = segmentation;
const { cachedStats } = segments[segmentIndex];
if (cachedStats?.center) {
const { center } = cachedStats;
return center as { image: csTypes.Point3; world: csTypes.Point3 };
}
Iif (cachedStats?.namedStats?.center) {
return {
world: cachedStats.namedStats.center.value,
};
}
}
private _setSegmentLockedStatus(segmentationId: string, segmentIndex: number, isLocked: boolean) {
cstSegmentation.segmentLocking.setSegmentIndexLocked(segmentationId, segmentIndex, isLocked);
}
private _setSegmentVisibility(
viewportId: string,
segmentationId: string,
segmentIndex: number,
isVisible: boolean,
type?: csToolsEnums.SegmentationRepresentations
) {
cstSegmentation.config.visibility.setSegmentIndexVisibility(
viewportId,
{
segmentationId,
type,
},
segmentIndex,
isVisible
);
}
private _setSegmentLabel(segmentationId: string, segmentIndex: number, segmentLabel: string) {
const segmentation = this.getCornerstoneSegmentation(segmentationId);
const { segments } = segmentation;
segments[segmentIndex].label = segmentLabel;
cstSegmentation.updateSegmentations([
{
segmentationId,
payload: {
segments,
},
},
]);
}
private _onSegmentationDataModifiedFromSource = evt => {
const { segmentationId } = evt.detail;
this._broadcastEvent(this.EVENTS.SEGMENTATION_DATA_MODIFIED, {
segmentationId,
});
};
private _onSegmentationRepresentationModifiedFromSource = evt => {
const { segmentationId, viewportId } = evt.detail;
this._broadcastEvent(this.EVENTS.SEGMENTATION_REPRESENTATION_MODIFIED, {
segmentationId,
viewportId,
});
};
private _onSegmentationRepresentationRemovedFromSource = evt => {
const { segmentationId, viewportId } = evt.detail;
this._broadcastEvent(this.EVENTS.SEGMENTATION_REPRESENTATION_REMOVED, {
segmentationId,
viewportId,
});
};
private _onSegmentationModifiedFromSource = (
evt: cstTypes.EventTypes.SegmentationModifiedEventType
) => {
const { segmentationId } = evt.detail;
this._broadcastEvent(this.EVENTS.SEGMENTATION_MODIFIED, {
segmentationId,
});
};
private _onSegmentationAddedFromSource = (
evt: cstTypes.EventTypes.SegmentationAddedEventType
) => {
const { segmentationId } = evt.detail;
this._broadcastEvent(this.EVENTS.SEGMENTATION_ADDED, {
segmentationId,
});
};
private _onSegmentationRemovedFromSource = (
evt: cstTypes.EventTypes.SegmentationRemovedEventType
) => {
const { segmentationId } = evt.detail;
this._broadcastEvent(this.EVENTS.SEGMENTATION_REMOVED, {
segmentationId,
});
};
private _onAnnotationCutMergeProcessCompletedFromSource = evt => {
const { segmentationId } = evt.detail;
this._broadcastEvent(this.EVENTS.SEGMENTATION_ANNOTATION_CUT_MERGE_PROCESS_COMPLETED, {
segmentationId,
});
};
/**
* Gets slice indices for contour segmentations by checking view references from annotation metadata
* @private
*/
protected _getContourViewReferences(
segmentationId: string,
viewport: csTypes.IViewport,
segmentIndex?: number
): Map<number, ViewReference> | undefined {
const segmentation = cstSegmentation.state.getSegmentation(segmentationId);
const contourData = segmentation.representationData[CONTOUR];
Iif (!contourData || !contourData.annotationUIDsMap) {
return;
}
const viewReferences = new Map<number, ViewReference>();
// Iterate through the annotationUIDsMap
contourData.annotationUIDsMap.forEach((annotationUIDs, currentSegmentIndex) => {
// Filter by segment index if specified
if (segmentIndex !== undefined && currentSegmentIndex !== segmentIndex) {
return;
}
// Process each annotation UID
annotationUIDs.forEach(annotationUID => {
const annotation = cstAnnotation.state.getAnnotation(annotationUID);
Iif (!annotation?.metadata) {
return;
}
const { metadata } = annotation;
// Check if the viewport can view this annotation's view reference with navigation
const isViewable = viewport.isReferenceViewable(metadata, {
withNavigation: true,
});
Iif (!isViewable) {
return;
}
const { sliceIndex } = metadata;
Iif (sliceIndex === undefined) {
console.warn("Can't find slice index:", metadata);
return;
}
viewReferences.set(sliceIndex, metadata);
});
});
if (viewReferences.size === 0) {
return;
}
return viewReferences;
}
}
export default SegmentationService;
export { EVENTS, VALUE_TYPES };
|