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 | 178x 178x 178x 178x 153x 153x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 7046x 174x 7046x 178x 178x 178x 178x 178x 178x 178x 555x 555x 555x 392073x 392073x 391899x 391899x 174x 174x 174x 494x 494x 494x 494x 494x 1603x 494x 1603x 494x 494x 464x 464x 464x 464x 30x 9x 9x 9x 9x 9x 9x 9x 9x 176x 176x 176x 176x 2023x 2023x 83x 1940x 1940x 1940x 1940x 884x 884x 884x 884x 555x 329x 329x 329x 329x 329x 329x 329x 329x 329x 329x 329x 329x 329x 199x 329x 198x 228x 98x 98x 98x 98x 884x 884x 884x 1759x 1759x 1759x 1759x 427x 427x 427x 439x 365x 365x 439x 67x 439x 427x 427x 59x 59x 71x 71x 427x 427x 427x 427x 427x 611x 611x 454x 611x 611x 611x 611x 611x 611x 611x 611x 611x 611x 611x 611x 611x 611x 611x 611x 611x 611x 611x 611x 611x 611x 611x 291200x 291200x 35369x 255831x 255831x 327914x 17x 17x 13x 13x 13x 7x 6x 9x 9x 1x 5x 5x 7x 7x 5x 5x 5x 5x 5x 5x 7x 7x 7x 7x 7x 3x 3x 3x 4x 7x 5x 5x 5x 5x 5x 5x 5x 5x 4x 1x 1x 1x 5x 5x 5x 5x 4x 5x 5x 1x 4x 4x 4x 4x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 456x 532x 456x 456x 456x 456x 456x 456x 420x 420x 420x 420x 456x 485x 485x 485x 456x 456x 456x 142x 456x 314x 456x 442x 442x 356x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 9x 77x 77x 77x 154x 154x 154x 154x 154x 154x 154x 184x 184x 184x 184x 1283x 184x 184x 10x 10x 174x 174x 174x 174x 154x 174x 154x 137x 38x 99x 115x 56x 116x 154x 154x 154x 154x 154x 154x 162x 154x 174x 174x 174x 154x 163x 163x 163x 163x 21x 21x 163x 12x 163x 9x 163x 8x 163x 154x 154x 154x 1x 1x 153x 162x 162x 153x 153x 153x 153x 153x 153x 153x 153x 153x 153x 162x 162x 162x 153x 153x 153x 128x 128x 86x 153x 610x 610x 610x 716x 610x 520x 90x 97x 97x 9634x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 39x 39x 58x 610x 520x 90x 97x 97x 611x 9x 174x 174x 171x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 30x 30x 30x 3x 30x 3x 3x 3x 467x 467x 467x 467x 1332x 1332x 1332x 467x 467x 466x 466x 1414x 466x 466x 1x 464x 464x 247x 1940x 1940x 1940x 1766x 174x 174x 108x 108x 108x 108x 108x 108x 178x | import { vec3 } from 'gl-matrix';
import { PubSubService } from '@ohif/core';
import { Types as OhifTypes } from '@ohif/core';
import {
RenderingEngine,
Types,
getRenderingEngine,
utilities as csUtils,
cache,
Enums as csEnums,
metaData,
} from '@cornerstonejs/core';
import { utilities as csToolsUtils, Enums as csToolsEnums } from '@cornerstonejs/tools';
import { IViewportService } from './IViewportService';
import { RENDERING_ENGINE_ID } from './constants';
import ViewportInfo, {
DisplaySetOptions,
PublicViewportOptions,
ViewportOptions,
} from './Viewport';
import { StackViewportData, VolumeViewportData } from '../../types/CornerstoneCacheService';
import {
LutPresentation,
PositionPresentation,
Presentations,
SegmentationPresentation,
SegmentationPresentationItem,
} from '../../types/Presentation';
import JumpPresets from '../../utils/JumpPresets';
import { ViewportProperties } from '@cornerstonejs/core/types';
import { useLutPresentationStore } from '../../stores/useLutPresentationStore';
import { usePositionPresentationStore } from '../../stores/usePositionPresentationStore';
import { useSynchronizersStore } from '../../stores/useSynchronizersStore';
import { useSegmentationPresentationStore } from '../../stores/useSegmentationPresentationStore';
import getClosestOrientationFromIOP from '../../utils/isReferenceViewable';
import { getViewportAdapter } from './adapter';
import { viewportOperations } from './backends/viewportOperations';
import {
getLegacyViewportType,
isVolume3DViewportType,
isVolumeViewportType,
} from '../../utils/getLegacyViewportType';
import { BlendModes } from '@cornerstonejs/core/enums';
import { isNextViewportsEnabled } from '../../utils/nextViewports';
import type { IViewportBackend } from './backends/IViewportBackend';
import type { IViewportServiceInternals } from './backends/IViewportServiceInternals';
import { LegacyViewportBackend } from './backends/LegacyViewportBackend';
import { NextViewportBackend } from './backends/NextViewportBackend';
const EVENTS = {
VIEWPORT_DATA_CHANGED: 'event::cornerstoneViewportService:viewportDataChanged',
VIEWPORT_VOLUMES_CHANGED: 'event::cornerstoneViewportService:viewportVolumesChanged',
};
const MIN_STACK_VIEWPORTS_TO_ENQUEUE_RESIZE = 12;
const MIN_VOLUME_VIEWPORTS_TO_ENQUEUE_RESIZE = 6;
// Actor class names that represent a primary volume binding in a viewport.
// Legacy ORTHOGRAPHIC / VOLUME_3D render the source volume as a 'vtkVolume'
// actor. Under the GenericViewport-backed compat path (useGenericViewport),
// the MPR slice render path emits 'vtkImageSlice' actors instead, so the
// volume-set-vs-add optimization below must recognize both. (3D still uses
// 'vtkVolume'.) Without this, the optimization silently no-ops and a full
// setVolumes() teardown blanks MPR during SEG hydration.
const VOLUME_ACTOR_CLASS_NAMES = new Set(['vtkVolume', 'vtkImageSlice']);
function getVolumeActorReferencedIds(viewport: Types.IVolumeViewport): string[] {
const actors = viewport.getActors?.() ?? [];
return actors
.filter(ac => VOLUME_ACTOR_CLASS_NAMES.has(ac.actor?.getClassName?.() ?? ''))
.map(ac => ac.referencedId)
.filter(Boolean) as string[];
}
function volumeIdPrefixesMatch(
existingIds: string[],
prefixLen: number,
targetIds: string[]
): boolean {
Iif (prefixLen > targetIds.length) {
return false;
}
for (let i = 0; i < prefixLen; i++) {
Iif (existingIds[i] !== targetIds[i]) {
return false;
}
}
return true;
}
/**
* Returns true when the viewport type matches a volume-based presentation (ORTHOGRAPHIC or VOLUME_3D).
*/
function viewportMatchesDesiredVolumePresentation(
viewport: Types.IViewport,
desiredViewportInfo: ViewportInfo
): boolean {
const desiredType = desiredViewportInfo.getViewportType();
Iif (getLegacyViewportType(viewport) !== desiredType) {
return false;
}
return (
desiredType === csEnums.ViewportType.ORTHOGRAPHIC ||
desiredType === csEnums.ViewportType.VOLUME_3D
);
}
export const WITH_NAVIGATION = { withNavigation: true, withOrientation: false };
export const WITH_ORIENTATION = { withNavigation: true, withOrientation: true };
/**
* Handles cornerstone viewport logic including enabling, disabling, and
* updating the viewport.
*/
class CornerstoneViewportService
extends PubSubService
implements IViewportService, IViewportServiceInternals
{
static REGISTRATION = {
name: 'cornerstoneViewportService',
altName: 'CornerstoneViewportService',
create: ({
servicesManager,
}: OhifTypes.Extensions.ExtensionParams): CornerstoneViewportService => {
return new CornerstoneViewportService(servicesManager);
},
};
renderingEngine: Types.IRenderingEngine | null;
viewportsById: Map<string, ViewportInfo> = new Map();
viewportGridResizeObserver: ResizeObserver | null;
viewportsDisplaySets: Map<string, string[]> = new Map();
beforeResizePositionPresentations: Map<string, PositionPresentation> = new Map();
// Some configs
servicesManager: AppTypes.ServicesManager = null;
resizeQueue = [];
viewportResizeTimer = null;
gridResizeDelay = 50;
gridResizeTimeOut = null;
// Resolved once, lazily, on first use. Forked viewport concerns (mount dispatch +
// native dataId lifecycle) route through it.
private _backend: IViewportBackend | null = null;
constructor(servicesManager: AppTypes.ServicesManager) {
super(EVENTS);
this.renderingEngine = null;
this.viewportGridResizeObserver = null;
this.servicesManager = servicesManager;
}
/**
* Sanctioned flag read (the exhaustive list lives in backends/README.md): pick
* the viewport backend once, on first use. Resolved lazily (not in the
* constructor) because the service singleton is constructed during extension
* registration, BEFORE init.tsx runs setNextViewportsEnabled — the first mount
* (when this is first read) always happens after init, so the flag is settled.
*/
private get backend(): IViewportBackend {
if (!this._backend) {
this._backend = isNextViewportsEnabled()
? new NextViewportBackend(this)
: new LegacyViewportBackend(this);
}
return this._backend;
}
hangingProtocolService: unknown;
viewportsInfo: unknown;
sceneVolumeInputs: unknown;
viewportDivElements: unknown;
ViewportPropertiesMap: unknown;
volumeUIDs: unknown;
displaySetsNeedRerendering: unknown;
viewportDisplaySets: unknown;
/**
* Adds the HTML element to the viewportService
* @param {*} viewportId
* @param {*} elementRef
*/
public enableViewport(viewportId: string, elementRef: HTMLDivElement): void {
const viewportInfo = new ViewportInfo(viewportId);
viewportInfo.setElement(elementRef);
this.viewportsById.set(viewportId, viewportInfo);
}
public getViewportIds(): string[] {
return Array.from(this.viewportsById.keys());
}
/**
* It retrieves the renderingEngine if it does exist, or creates one otherwise
* @returns {RenderingEngine} rendering engine
*/
public getRenderingEngine() {
// get renderingEngine from cache if it exists
const renderingEngine = getRenderingEngine(RENDERING_ENGINE_ID);
if (renderingEngine) {
this.renderingEngine = renderingEngine;
return this.renderingEngine;
}
if (!renderingEngine || renderingEngine.hasBeenDestroyed) {
this.renderingEngine = new RenderingEngine(RENDERING_ENGINE_ID);
}
return this.renderingEngine;
}
/**
* It triggers the resize on the rendering engine, and renders the viewports
*
*/
public resize() {
// https://stackoverflow.com/a/26279685
// This resize() call, among other things, rerenders the viewports. But when the entire viewer is
// display: none'd, it makes the size of all hidden elements 0, including the viewport canvas and its containers.
// Even if the viewer is later displayed again, trying to render when the size is 0 permanently "breaks" the
// viewport, making it fully black even after the size is normal again. So just ignore resize events when hidden:
const areViewportsHidden = Array.from(this.viewportsById.values()).every(viewportInfo => {
const element = viewportInfo.getElement();
return element.clientWidth === 0 && element.clientHeight === 0;
});
Iif (areViewportsHidden) {
console.warn('Ignoring resize when viewports have size 0');
return;
}
const numStackViewportsInViewportGrid = Array.from(this.viewportsById.values()).filter(
viewportInfo => viewportInfo.getViewportType() === csEnums.ViewportType.STACK
).length;
const numVolumeViewportsInViewportGrid = Array.from(this.viewportsById.values()).filter(
viewportInfo => viewportInfo.getViewportType() === csEnums.ViewportType.ORTHOGRAPHIC
).length;
const isEasyResize =
numStackViewportsInViewportGrid <= MIN_STACK_VIEWPORTS_TO_ENQUEUE_RESIZE &&
numVolumeViewportsInViewportGrid <= MIN_VOLUME_VIEWPORTS_TO_ENQUEUE_RESIZE;
// if there is a grid resize happening, it means the viewport grid
// has been manipulated (e.g., panels closed, added, etc.) and we need
// to resize all viewports, so we will add a timeout here to make sure
// we don't double resize the viewports when viewports in the grid are
// resized individually
if (isEasyResize) {
this.performResize();
this.resetGridResizeTimeout();
this.resizeQueue = [];
clearTimeout(this.viewportResizeTimer);
} else {
this.enqueueViewportResizeRequest();
}
}
/**
* Removes the viewport from cornerstone, and destroys the rendering engine
*/
public destroy() {
this._removeResizeObserver();
this.viewportGridResizeObserver = null;
// Flush any native dataId registrations the backend owns (§4.7); no-op for legacy.
this.backend.destroy();
try {
this.renderingEngine?.destroy?.();
} catch (e) {
console.warn('Rendering engine not destroyed', e);
}
this.viewportsDisplaySets.clear();
this.renderingEngine = null;
cache.purgeCache();
}
/**
* Disables the viewport inside the renderingEngine, if no viewport is left
* it destroys the renderingEngine.
*
* This is called when the element goes away entirely - with new viewportId's
* created for every new viewport, this will be called whenever the set of
* viewports is changed, but NOT when the viewport position changes only.
*
* @param viewportId - The viewportId to disable
*/
public disableElement(viewportId: string): void {
// Release native dataId registrations BEFORE the viewport bookkeeping is
// deleted (§4.7 ref-counted GC); no-op for the legacy backend.
this.backend.onViewportDisabled(viewportId);
this.renderingEngine?.disableElement(viewportId);
// clean up
this.viewportsById.delete(viewportId);
this.viewportsDisplaySets.delete(viewportId);
}
/**
* Sets the presentations for a given viewport. Presentations is an object
* that can define the lut or position for a viewport.
*
* @param viewportId - The ID of the viewport.
* @param presentations - The presentations to apply to the viewport.
* @param viewportInfo - Contains a view reference for immediate application
*/
// Public so the viewport backends (IViewportServiceInternals) can record which
// display sets a viewport shows from their mount bodies.
_trackViewportDisplaySets(viewportId: string, displaySetInstanceUIDs: string[]): void {
this.viewportsDisplaySets.set(viewportId, displaySetInstanceUIDs);
}
public setPresentations(viewportId: string, presentations: Presentations): void {
const viewport = this.getCornerstoneViewport(viewportId) as
| Types.IStackViewport
| Types.IVolumeViewport;
if (!viewport || !presentations) {
return;
}
const { lutPresentation, positionPresentation, segmentationPresentation } = presentations;
// Always set the segmentation presentation first, since there might be some
// lutpresentation states that need to be set on the segmentation
// Todo: i think we should even await this
this._setSegmentationPresentation(viewport, segmentationPresentation);
this._setLutPresentation(viewport, lutPresentation);
this._setPositionPresentation(viewport, { ...positionPresentation, viewportId });
}
/**
* Stores the presentation state for a given viewport inside the
* each store. This is used to persist the presentation state
* across different scenarios e.g., when the viewport is changing the
* display set, or when the viewport is moving to a different layout.
*
* @param viewportId The ID of the viewport.
*/
public storePresentation({ viewportId }) {
const presentationIds = this.getPresentationIds(viewportId);
const { syncGroupService } = this.servicesManager.services;
const synchronizers = syncGroupService.getSynchronizersForViewport(viewportId);
if (!presentationIds || Object.keys(presentationIds).length === 0) {
return null;
}
const { lutPresentationId, positionPresentationId, segmentationPresentationId } =
presentationIds;
const positionPresentation = this._getPositionPresentation(viewportId);
const lutPresentation = this._getLutPresentation(viewportId);
const segmentationPresentation = this._getSegmentationPresentation(viewportId);
const { setLutPresentation } = useLutPresentationStore.getState();
const { setPositionPresentation } = usePositionPresentationStore.getState();
const { setSynchronizers } = useSynchronizersStore.getState();
const { setSegmentationPresentation } = useSegmentationPresentationStore.getState();
if (lutPresentationId) {
setLutPresentation(lutPresentationId, lutPresentation);
}
if (positionPresentationId) {
setPositionPresentation(positionPresentationId, positionPresentation);
}
if (segmentationPresentationId) {
setSegmentationPresentation(segmentationPresentationId, segmentationPresentation);
}
if (synchronizers?.length) {
setSynchronizers(
viewportId,
synchronizers.map(synchronizer => ({
id: synchronizer.id,
sourceViewports: [...synchronizer.getSourceViewports()],
targetViewports: [...synchronizer.getTargetViewports()],
}))
);
}
}
/**
* Retrieves the presentations for a given viewport.
* @param viewportId - The ID of the viewport.
* @returns The presentations for the viewport.
*/
public getPresentations(viewportId: string): Presentations {
const positionPresentation = this._getPositionPresentation(viewportId);
const lutPresentation = this._getLutPresentation(viewportId);
const segmentationPresentation = this._getSegmentationPresentation(viewportId);
return {
positionPresentation,
lutPresentation,
segmentationPresentation,
};
}
private getPresentationIds(viewportId: string): AppTypes.PresentationIds | null {
const viewportInfo = this.viewportsById.get(viewportId);
Iif (!viewportInfo) {
return null;
}
return viewportInfo.getPresentationIds();
}
private _getPositionPresentation(viewportId: string): PositionPresentation {
const csViewport = this.getCornerstoneViewport(viewportId);
Iif (!csViewport) {
return;
}
const viewportInfo = this.viewportsById.get(viewportId);
// Forked per backend (§4.3 presentation read): legacy reads getViewPresentation
// (pan/zoom); native omits it (a PLANAR_NEXT viewport has no getViewPresentation).
return this.backend.getPositionPresentation(csViewport, viewportInfo, viewportId);
}
private _getLutPresentation(viewportId: string): LutPresentation {
const csViewport = this.getCornerstoneViewport(viewportId) as
| Types.IStackViewport
| Types.IVolumeViewport;
Iif (!csViewport) {
return;
}
const cleanProperties = properties => {
if (properties?.isComputedVOI) {
delete properties?.voiRange;
delete properties?.VOILUTFunction;
}
if (properties?.colormap) {
Iif (properties.colormap?.opacity?.length === 0) {
delete properties.colormap.opacity;
}
}
return properties;
};
const properties = isVolumeViewportType(csViewport)
? new Map()
: cleanProperties(getViewportAdapter(csViewport).getPresentation());
if (properties instanceof Map) {
const volumeIds = (csViewport as Types.IBaseVolumeViewport).getAllVolumeIds();
volumeIds?.forEach(volumeId => {
const csProps = cleanProperties(csViewport.getProperties(volumeId));
properties.set(volumeId, csProps);
});
}
const viewportInfo = this.viewportsById.get(viewportId);
return {
viewportType: viewportInfo.getViewportType(),
properties,
};
}
private _getSegmentationPresentation(viewportId: string): SegmentationPresentation {
const { segmentationService } = this.servicesManager.services;
const presentation = segmentationService.getPresentation(viewportId);
return presentation;
}
/**
* Sets the viewport data for a viewport.
* @param viewportId - The ID of the viewport to set the data for.
* @param viewportData - The viewport data to set.
* @param publicViewportOptions - The public viewport options.
* @param publicDisplaySetOptions - The public display set options.
* @param presentations - The presentations to set.
*/
public setViewportData(
viewportId: string,
viewportData: StackViewportData | VolumeViewportData,
publicViewportOptions: PublicViewportOptions,
publicDisplaySetOptions: DisplaySetOptions[],
presentations?: Presentations
): void {
const renderingEngine = this.getRenderingEngine();
// if not valid viewportData then return early
if (viewportData.viewportType === csEnums.ViewportType.STACK) {
// check if imageIds is valid
Iif (!viewportData.data[0].imageIds?.length) {
return;
}
}
// This is the old viewportInfo, which may have old options but we might be
// using its viewport (same viewportId as the new viewportInfo)
const viewportInfo = this.viewportsById.get(viewportId);
// We should store the presentation for the current viewport since we can't only
// rely to store it WHEN the viewport is disabled since we might keep around the
// same viewport/element and just change the viewportData for it (drag and drop etc.)
// the disableElement storePresentation handle would not be called in this case
// and we would lose the presentation.
this.storePresentation({ viewportId: viewportInfo.getViewportId() });
// Todo: i don't like this here, move it
this.servicesManager.services.segmentationService.clearSegmentationRepresentations(
viewportInfo.getViewportId()
);
Iif (!viewportInfo) {
throw new Error('element is not enabled for the given viewportId');
}
// override the viewportOptions and displaySetOptions with the public ones
// since those are the newly set ones, we set them here so that it handles defaults
const displaySetOptions = viewportInfo.setPublicDisplaySetOptions(publicDisplaySetOptions);
// Specify an over-ride for the viewport type, even though it is in the public
// viewport options, because the one in the viewportData is a requirement based on the
// type of data being displayed.
const viewportOptions = viewportInfo.setPublicViewportOptions(
publicViewportOptions,
viewportData.viewportType
);
const element = viewportInfo.getElement();
const type = viewportInfo.getViewportType();
const background = viewportInfo.getBackground();
const orientation = viewportInfo.getOrientation();
const displayArea = viewportInfo.getDisplayArea();
const viewportInput: Types.PublicViewportInput = {
viewportId,
element,
type,
defaultOptions: {
background,
orientation,
displayArea,
},
};
// Rendering Engine Id set should happen before enabling the element
// since there are callbacks that depend on the renderingEngine id
// Todo: however, this is a limitation which means that we can't change
// the rendering engine id for a given viewport which might be a super edge
// case
viewportInfo.setRenderingEngineId(renderingEngine.id);
// Todo: this is not optimal at all, we are re-enabling the already enabled
// element which is not what we want. But enabledElement as part of the
// renderingEngine is designed to be used like this. This will trigger
// ENABLED_ELEMENT again and again, which will run onEnableElement callbacks
renderingEngine.enableElement(viewportInput);
viewportInfo.setViewportOptions(viewportOptions);
viewportInfo.setDisplaySetOptions(displaySetOptions);
viewportInfo.setViewportData(viewportData);
viewportInfo.setViewportId(viewportId);
this.viewportsById.set(viewportId, viewportInfo);
const viewport = renderingEngine.getViewport(viewportId);
const displaySetPromise = this._setDisplaySets(
viewport,
viewportData,
viewportInfo,
presentations
);
// The broadcast event here ensures that listeners have a valid, up to date
// viewport to access. Doing it too early can result in exceptions or
// invalid data.
displaySetPromise.then(() => {
this._broadcastEvent(this.EVENTS.VIEWPORT_DATA_CHANGED, {
viewportData,
viewportId,
});
});
}
public getViewportOptions(viewportId: string): ViewportOptions {
return this.viewportsById.get(viewportId).getViewportOptions();
}
/**
* Retrieves the Cornerstone viewport with the specified ID.
*
* @param viewportId - The ID of the viewport.
* @returns The Cornerstone viewport object if found, otherwise null.
*/
public getCornerstoneViewport(viewportId: string): Types.IViewport | null {
const viewportInfo = this.getViewportInfo(viewportId);
if (!viewportInfo || !this.renderingEngine || this.renderingEngine.hasBeenDestroyed) {
return null;
}
const viewport = this.renderingEngine.getViewport(viewportId);
return viewport;
}
/**
* Retrieves the viewport information for a given viewport ID. The viewport information
* is the OHIF construct that holds different options and data for a given viewport and
* is different from the cornerstone viewport.
*
* @param viewportId The ID of the viewport.
* @returns The viewport information.
*/
public getViewportInfo(viewportId: string): ViewportInfo {
return this.viewportsById.get(viewportId);
}
public getOrientation(viewportId: string): string {
const viewportInfo = this.getViewportInfo(viewportId);
return viewportInfo.getOrientation();
}
/**
* Looks through the viewports to see if the specified measurement can be
* displayed in one of the viewports. This function tries to get a "best fit"
* viewport to display the image in where it matches, in order:
* * Active viewport that can be navigated to the given image without orientation change
* * Other viewport that can be navigated to the given image without orientation change
* * Best-aligned viewport that can display the image with an orientation change
*
* It returns `null` otherwise, indicating that a viewport needs display set/type
* changes in order to display the image.
*
* Notes:
* * If the display set is displayed in multiple viewports all needing orientation change,
* then the active one or first one listed will be modified. This can create unexpected
* behaviour for MPR views.
* * If the image is contained in multiple display sets, then the first one
* found will be navigated (active first, followed by first found)
*
* @param measurement - The measurement that is desired to view.
* @param activeViewportId - the index that was active at the time the jump
* was initiated.
* @return the viewportId that the measurement should be displayed in.
*/
public findNavigationCompatibleViewportId(activeViewportId: string, metadata): string {
// First check if the active viewport can just be navigated to show the given item
const activeViewport = this.getCornerstoneViewport(activeViewportId);
Iif (!activeViewport) {
console.warn('No active viewport found for', activeViewportId);
}
if (activeViewport?.isReferenceViewable(metadata, WITH_NAVIGATION)) {
return activeViewportId;
}
// Next, see if any viewport could be navigated to show the given item,
// without considering orientation changes.
for (const id of this.viewportsById.keys()) {
const viewport = this.getCornerstoneViewport(id);
if (viewport?.isReferenceViewable(metadata, WITH_NAVIGATION)) {
return id;
}
}
// Compute view-plane alignment scores for all viewports to prefer the one
// requiring the least orientation change when navigation-only is not possible.
const viewportAlignmentData = this.getViewportAlignmentData(metadata);
// See if any viewport could show this with an orientation change
for (const { viewportId: id } of viewportAlignmentData) {
const viewport = this.getCornerstoneViewport(id);
Iif (viewport?.isReferenceViewable(metadata, WITH_ORIENTATION)) {
return id;
}
}
// No luck, need to update the viewport itself
return null;
}
/**
* Given a metadata instance containing a planeRestriction, returns the
* ordered list of best orientation match viewport ids.
*
* This uses the planeRestriction preferentially as that one is more reliably
* filled than the viewport normal since it is created from data points on
* rehydration.
*/
public getViewportAlignmentData(metadata) {
const viewportAlignmentData = [];
const { viewPlaneNormal: refViewPlaneNormal, planeRestriction } = metadata;
const inPlaneVector1 = planeRestriction?.inPlaneVector1;
const inPlaneVector2 = planeRestriction?.inPlaneVector2;
for (const id of this.viewportsById.keys()) {
const viewport = this.getCornerstoneViewport(id);
// Lane-appropriate view-plane normal (legacy getCamera vs native getViewReference).
const viewPlaneNormal = viewportOperations.getViewPlaneNormal(viewport);
Iif (!viewPlaneNormal) {
continue;
}
let alignmentScore = 0;
if (inPlaneVector1 || inPlaneVector2) {
const inPlane1Score = inPlaneVector1
? -Math.abs(vec3.dot(viewPlaneNormal, inPlaneVector1))
: 0;
const inPlane2Score = inPlaneVector2
? -Math.abs(vec3.dot(viewPlaneNormal, inPlaneVector2))
: 0;
alignmentScore = inPlane1Score + inPlane2Score;
} else Iif (refViewPlaneNormal) {
alignmentScore = Math.abs(vec3.dot(viewPlaneNormal, refViewPlaneNormal));
}
viewportAlignmentData.push({ viewportId: id, alignmentScore });
}
// Try best-aligned viewports first
viewportAlignmentData.sort((a, b) => b.alignmentScore - a.alignmentScore);
return viewportAlignmentData;
}
/**
* Figures out which viewport to update when the viewport type needs to change.
* Orchestrates the search strategies in order of preference.
*/
public findUpdateableViewportConfiguration(activeViewportId: string, measurement) {
const { metadata, displaySetInstanceUID } = measurement;
const { displaySetService } = this.servicesManager.services;
const displaySet = displaySetService.getDisplaySetByUID(displaySetInstanceUID);
// 1. Determine the target Viewport Type (Stack vs Volume)
const viewportType = this.determineTargetViewportType(displaySet, metadata);
// 2. Strategy: Find viewport already showing this volume
const volumeMatch = this.findViewportShowingVolume(
metadata,
displaySetInstanceUID,
viewportType
);
if (volumeMatch) {
return volumeMatch;
}
// 3. Strategy: Find viewport with compatible orientation (even if different display set)
const compatibleMatch = this.findViewportConvertibleToVolume(
metadata,
displaySetInstanceUID,
viewportType
);
if (compatibleMatch) {
return compatibleMatch;
}
// 4. Strategy: Find viewport with matching orientation via IOP
const orientationMatch = this.findViewportWithMatchingOrientation(
metadata,
displaySetInstanceUID,
viewportType
);
Iif (orientationMatch) {
return orientationMatch;
}
// 5. Fallback: Use the active viewport
return {
viewportId: activeViewportId,
displaySetInstanceUID,
viewportOptions: { viewportType },
};
}
/**
* Determines if the viewport should be what is specified in
* the viewportType of the display set, or stack if the display
* set isn't reconstructable and there is a referenced image id, otherwise
* volume.
*
* Expect there to be more rules in the future for different types of annotations/settings
* such as 3d annotations.
*/
public determineTargetViewportType(displaySet, metadata): string {
let { viewportType } = displaySet;
if (!viewportType) {
Iif (metadata.referencedImageId && !displaySet.isReconstructable) {
viewportType = csEnums.ViewportType.STACK;
} else if (metadata.volumeId) {
viewportType = 'volume';
}
}
return viewportType;
}
/**
* Find viewports that could be updated to be volumes to show this view.
* Prefers a viewport already showing the right display set.
*/
public findViewportShowingVolume(metadata, displaySetInstanceUID, viewportType) {
if (!metadata.volumeId) {
return null;
}
for (const id of this.viewportsById.keys()) {
const viewport = this.getCornerstoneViewport(id);
if (viewport?.isReferenceViewable(metadata, { asVolume: true, withNavigation: true })) {
return {
viewportId: id,
displaySetInstanceUID,
viewportOptions: { viewportType },
};
}
}
return null;
}
/**
* Find a viewport that could be converted to a volume to show this annotation,
* already showing the right display set.
*/
public findViewportConvertibleToVolume(metadata, displaySetInstanceUID, viewportType) {
const { viewportGridService } = this.servicesManager.services;
const altMetadata = { ...metadata, volumeId: null, referencedImageId: null };
for (const id of this.viewportsById.keys()) {
const viewport = this.getCornerstoneViewport(id);
const viewportDisplaySetUID = viewportGridService.getDisplaySetsUIDsForViewport(id)?.[0];
Iif (!viewportDisplaySetUID || !viewport) {
continue;
}
Iif (metadata.volumeId) {
altMetadata.volumeId = viewportDisplaySetUID;
}
altMetadata.FrameOfReferenceUID = this._getFrameOfReferenceUID(viewportDisplaySetUID);
if (viewport.isReferenceViewable(altMetadata, { asVolume: true, withNavigation: true })) {
return {
viewportId: id,
displaySetInstanceUID,
viewportOptions: { viewportType },
};
}
}
return null;
}
/**
* Find a viewport with the closest orientation but on a different display set.
*/
public findViewportWithMatchingOrientation(metadata, displaySetInstanceUID, viewportType) {
const viewportAlignmentData = this.getViewportAlignmentData(metadata);
Iif (viewportAlignmentData?.length) {
return {
...viewportAlignmentData[0],
displaySetInstanceUID,
viewportOptions: { viewportType },
};
}
return null;
}
/**
* Sets the image data for the given viewport.
*/
// Public so the viewport backends (IViewportServiceInternals) can dispatch to it.
async _setEcgViewport(
viewport: Types.IECGViewport,
viewportData: StackViewportData
): Promise<void> {
const [displaySet] = viewportData.data;
const imageId = displaySet.imageIds?.[0];
Iif (!imageId) {
console.error('[CornerstoneViewportService] ECG display set has no imageId');
return;
}
return this.backend.mountEcg(viewport, displaySet, imageId);
}
// Public so the viewport backends (IViewportServiceInternals) can dispatch to it.
async _setOtherViewport(
viewport: Types.IStackViewport,
viewportData: StackViewportData,
viewportInfo: ViewportInfo,
_presentations: Presentations = {}
): Promise<void> {
const [displaySet] = viewportData.data;
await this.backend.mountOther(viewport, displaySet);
const viewReference = viewportInfo.getViewReference();
Iif (viewReference) {
viewport.setViewReference(viewReference);
}
}
// Public so the viewport backends (IViewportServiceInternals) can dispatch to it.
async _setStackViewport(
viewport: Types.IStackViewport,
viewportData: StackViewportData,
viewportInfo: ViewportInfo,
presentations: Presentations = {}
): Promise<void> {
const displaySetOptions = viewportInfo.getDisplaySetOptions();
const displaySetInstanceUIDs = viewportData.data.map(data => data.displaySetInstanceUID);
// based on the cache service construct always the first one is the non-overlay
// and the rest are overlays
this.viewportsDisplaySets.set(viewport.id, [...displaySetInstanceUIDs]);
const { initialImageIndex, imageIds } = viewportData.data[0];
// Use the slice index from any provided view reference, as the view reference
// is being used to navigate to the initial view position for measurement
// navigation and other navigation forcing specific views.
let initialImageIndexToUse =
presentations?.positionPresentation?.initialImageIndex ?? (initialImageIndex as number);
const { rotation, flipHorizontal, displayArea } = viewportInfo.getViewportOptions();
const properties = { ...presentations.lutPresentation?.properties };
if (!presentations.lutPresentation?.properties) {
const { voi, voiInverted, colormap } = displaySetOptions[0];
Iif (voi && (voi.windowWidth || voi.windowCenter)) {
const { lower, upper } = csUtils.windowLevel.toLowHighRange(
voi.windowWidth,
voi.windowCenter
);
properties.voiRange = { lower, upper };
}
properties.invert = voiInverted ?? properties.invert;
properties.colormap = colormap ?? properties.colormap;
}
viewport.element.addEventListener(csEnums.Events.VIEWPORT_NEW_IMAGE_SET, evt => {
const { element } = evt.detail;
Iif (element !== viewport.element) {
return;
}
csToolsUtils.stackContextPrefetch.enable(element);
});
const overlayProcessingResults = this._processExtraDisplaySetsForViewport(viewport);
const referencedImageId = presentations?.positionPresentation?.viewReference?.referencedImageId;
if (referencedImageId && imageIds) {
initialImageIndexToUse = imageIds.indexOf(referencedImageId);
}
if (
initialImageIndexToUse === undefined ||
initialImageIndexToUse === null ||
initialImageIndexToUse < 0
) {
initialImageIndexToUse = this._getInitialImageIndexForViewport(viewportInfo, imageIds) || 0;
}
// The lane-specific mount (legacy setStack/setProperties vs native
// setDisplaySets/setDisplaySetPresentation/setViewState) lives in the backend.
return this.backend.mountStack(viewport, {
displaySetInstanceUIDs,
imageIds,
initialImageIndex: initialImageIndexToUse,
properties,
displayArea,
rotation,
flipHorizontal,
presentations,
viewportInfo,
overlayProcessingResults,
});
}
private _getInitialImageIndexForViewport(
viewportInfo: ViewportInfo,
imageIds?: string[]
): number {
const initialImageOptions = viewportInfo.getInitialImageOptions();
if (!initialImageOptions) {
return;
}
const { index, preset } = initialImageOptions;
const viewportType = viewportInfo.getViewportType();
let numberOfSlices;
Iif (viewportType === csEnums.ViewportType.STACK) {
numberOfSlices = imageIds.length;
} else if (viewportType === csEnums.ViewportType.ORTHOGRAPHIC) {
const viewport = this.getCornerstoneViewport(viewportInfo.getViewportId());
const imageSliceData = csUtils.getImageSliceDataForVolumeViewport(viewport);
Iif (!imageSliceData) {
return;
}
({ numberOfSlices } = imageSliceData);
} else E{
return;
}
return this._getInitialImageIndex(numberOfSlices, index, preset);
}
_getInitialImageIndex(numberOfSlices: number, imageIndex?: number, preset?: JumpPresets): number {
const lastSliceIndex = numberOfSlices - 1;
Iif (imageIndex !== undefined) {
return csUtils.clip(imageIndex, 0, lastSliceIndex);
}
if (preset === JumpPresets.First) {
return 0;
}
Iif (preset === JumpPresets.Last) {
return lastSliceIndex;
}
if (preset === JumpPresets.Middle) {
// Note: this is a simple but yet very important formula.
// since viewport reset works with the middle slice
// if the below formula is not correct, on a viewport reset
// it will jump to a different slice than the middle one which
// was the initial slice, and we have some tools such as Crosshairs
// which rely on a relative camera modifications and those will break.
return lastSliceIndex % 2 === 0 ? lastSliceIndex / 2 : (lastSliceIndex + 1) / 2;
}
return 0;
}
async _setVolumeViewport(
viewport: Types.IVolumeViewport,
viewportData: VolumeViewportData,
viewportInfo: ViewportInfo,
presentations: Presentations = {}
): Promise<void> {
// TODO: We need to overhaul the way data sources work so requests can be made
// async. I think we should follow the image loader pattern which is async and
// has a cache behind it.
// The problem is that to set this volume, we need the metadata, but the request is
// already in-flight, and the promise is not cached, so we have no way to wait for
// it and know when it has fully arrived.
// loadStudyMetadata(StudyInstanceUID) => Promise([instances for study])
// loadSeriesMetadata(StudyInstanceUID, SeriesInstanceUID) => Promise([instances for series])
// If you call loadStudyMetadata and it's not in the DicomMetadataStore cache, it should fire
// a request through the data source?
// (This call may or may not create sub-requests for series metadata)
const { displaySetService } = this.servicesManager.services;
const volumeInputArray = [];
const displaySetOptionsArray = viewportInfo.getDisplaySetOptions();
const { hangingProtocolService } = this.servicesManager.services;
const volumeToLoad = [];
const displaySetInstanceUIDs = [];
for (const [index, data] of viewportData.data.entries()) {
const { imageIds, displaySetInstanceUID } = data;
let volume = data.volume;
const displaySet = displaySetService.getDisplaySetByUID(displaySetInstanceUID);
if (!volume && displaySet.images) {
volume = csToolsUtils.getOrCreateImageVolume(displaySet.images.map(image => image.imageId));
}
displaySetInstanceUIDs.push(displaySetInstanceUID);
if (!volume) {
console.log('Volume display set not found');
continue;
}
volumeToLoad.push(volume);
const displaySetOptions = displaySetOptionsArray[index];
const { volumeId } = volume;
volumeInputArray.push({
imageIds,
volumeId,
modality: displaySet.Modality,
displaySetInstanceUID,
blendMode: displaySetOptions.blendMode,
slabThickness: this._getSlabThickness(displaySetOptions, volumeId),
});
}
this.viewportsDisplaySets.set(viewport.id, displaySetInstanceUIDs);
const volumesNotLoaded = volumeToLoad.filter(volume => !volume.loadStatus?.loaded);
if (volumesNotLoaded.length) {
if (hangingProtocolService.getShouldPerformCustomImageLoad()) {
// delegate the volume loading to the hanging protocol service if it has a custom image load strategy
return hangingProtocolService.runImageLoadStrategy({
viewportId: viewport.id,
volumeInputArray,
});
}
volumesNotLoaded.forEach(volume => {
if (!volume.loadStatus?.loading && volume.load instanceof Function) {
volume.load();
}
});
}
// It's crucial not to return here because the volume may be loaded,
// but the viewport also needs to set the volume.
// if (!volumesNotLoaded.length) {
// return;
// }
// This returns the async continuation only
return this.setVolumesForViewport(viewport, volumeInputArray, presentations);
}
public async setVolumesForViewport(viewport, volumeInputArray, presentations) {
const { displaySetService, viewportGridService } = this.servicesManager.services;
const viewportInfo = this.getViewportInfo(viewport.id);
const displaySetOptions = viewportInfo.getDisplaySetOptions();
const displaySetUIDs = viewportGridService.getDisplaySetsUIDsForViewport(viewport.id);
const displaySet = displaySetService.getDisplaySetByUID(displaySetUIDs[0]);
const displaySetModality = displaySet?.Modality;
// seems like a hack but we need the actor to be ready first before
// we set the properties
const timeoutViewportCallback = (callback: () => void) => setTimeout(callback, 0);
// filter overlay display sets (e.g. segmentation) since they will get handled below via the segmentation service
const filteredVolumeInputArray = volumeInputArray
.map((volumeInput, index) => {
return { volumeInput, displaySetOptions: displaySetOptions[index] };
})
.filter(({ volumeInput }) => {
const displaySet = displaySetService.getDisplaySetByUID(volumeInput.displaySetInstanceUID);
return !displaySet?.isOverlayDisplaySet;
});
// Todo: use presentations states
const volumesProperties = filteredVolumeInputArray.map(({ volumeInput, displaySetOptions }) => {
const { volumeId } = volumeInput;
const { voi, voiInverted, colormap, displayPreset } = displaySetOptions;
const properties = {} as ViewportProperties;
if (voi && (voi.windowWidth || voi.windowCenter)) {
const { lower, upper } = csUtils.windowLevel.toLowHighRange(
voi.windowWidth,
voi.windowCenter
);
properties.voiRange = { lower, upper };
}
if (voiInverted !== undefined) {
properties.invert = voiInverted;
}
if (colormap !== undefined) {
properties.colormap = colormap;
}
if (displayPreset !== undefined) {
properties.preset = displayPreset[displaySetModality] || displayPreset.default;
}
return { properties, volumeId };
});
// For SEG and RT viewports
const overlayProcessingResults = this._processExtraDisplaySetsForViewport(viewport) || [];
// Lane-specific volume mount: the native backend mounts registered dataIds via
// setDisplaySets + per-binding presentations and reports the mount handled;
// legacy reports unhandled and runs the shared setVolumes tail below (which a
// native overlay-only mount also traverses — its legacy-surface steps are
// lane-guarded via mountOverlayOnlyVolumes).
const handledByBackend = await this.backend.mountVolumes(viewport, {
filteredVolumeInputArray,
volumesProperties,
viewportInfo,
overlayProcessingResults,
presentations,
});
if (handledByBackend) {
this._broadcastEvent(this.EVENTS.VIEWPORT_VOLUMES_CHANGED, { viewportInfo });
return;
}
Iif (!filteredVolumeInputArray.length && overlayProcessingResults?.length) {
overlayProcessingResults.forEach(({ imageIds, addOverlayFn }) => {
Iif (addOverlayFn) {
// if there is no volume input array, and there is an addOverlayFn, means we need to take
// care of the background overlay display set first then the addOverlayFn will add the
// SEG displaySet
const sampleImageId = imageIds[0];
const backgroundDisplaySet = displaySetService.getDisplaySetsBy(
displaySet =>
!displaySet.isOverlayDisplaySet &&
displaySet.images?.some(image => image.imageId === sampleImageId)
);
Iif (backgroundDisplaySet.length !== 1) {
throw new Error('Background display set not found');
}
Iif (isVolume3DViewportType(viewport)) {
timeoutViewportCallback(() => {
viewportGridService.setDisplaySetsForViewport({
viewportId: viewport.id,
displaySetInstanceUIDs: [backgroundDisplaySet[0].displaySetInstanceUID],
});
});
}
}
});
}
const baseVolumeInputs = filteredVolumeInputArray.map(({ volumeInput }) => volumeInput);
const nextBaseVolumeIds = baseVolumeInputs.map(v => v.volumeId);
const existingVolumeIds = getVolumeActorReferencedIds(viewport);
let skippedIdenticalBaseVolumes = false;
if (baseVolumeInputs.length) {
const singleBaseViewport = nextBaseVolumeIds.length === 1;
// Only skip setVolumes() when the viewport type already matches the desired OHIF type
// (ORTHOGRAPHIC / VOLUME_3D); otherwise a stack → MPR switch with the same volumeId
// would incorrectly skip rebuilding the viewport.
Iif (
singleBaseViewport &&
existingVolumeIds.length >= nextBaseVolumeIds.length &&
volumeIdPrefixesMatch(existingVolumeIds, nextBaseVolumeIds.length, nextBaseVolumeIds) &&
viewportMatchesDesiredVolumePresentation(viewport, viewportInfo)
) {
// Same primary volume already loaded (e.g. labelmap / extra actors after it) — avoid
// setVolumes(), which tears down all actors and blanks MPR during SEG hydrate.
skippedIdenticalBaseVolumes = true;
} else Iif (
existingVolumeIds.length &&
nextBaseVolumeIds.length > existingVolumeIds.length &&
volumeIdPrefixesMatch(existingVolumeIds, existingVolumeIds.length, nextBaseVolumeIds) &&
typeof viewport.addVolumes === 'function'
) {
const toAdd = baseVolumeInputs.slice(existingVolumeIds.length);
Iif (toAdd.length) {
await viewport.addVolumes(toAdd);
}
} else {
await viewport.setVolumes(baseVolumeInputs);
}
} else IEif (volumeInputArray.length) {
// Every volume input is an overlay display set. Legacy still mounts them via
// setVolumes; the native backend no-ops (its overlays are added via
// _addOverlayRepresentations below).
await this.backend.mountOverlayOnlyVolumes(viewport, volumeInputArray);
}
await this._addOverlayRepresentations(overlayProcessingResults);
viewport.render();
volumesProperties.forEach(({ properties, volumeId }) => {
timeoutViewportCallback(() => {
viewport.setProperties(properties, volumeId);
viewport.render();
});
});
this.setPresentations(viewport.id, presentations);
// Presentations apply segmentation (hydrated labelmap etc.) after the render above — redraw so
// every orthographic/3D tile shows the updated scene (fixes MPR siblings blank after SEG hydrate).
viewport.render();
if (!presentations.positionPresentation && !skippedIdenticalBaseVolumes) {
const imageIndex = this._getInitialImageIndexForViewport(viewportInfo);
if (imageIndex !== undefined) {
csUtils.jumpToSlice(viewport.element, {
imageIndex,
});
}
}
this._broadcastEvent(this.EVENTS.VIEWPORT_VOLUMES_CHANGED, {
viewportInfo,
});
}
private _processExtraDisplaySetsForViewport(
viewport: Types.IStackViewport | Types.IVolumeViewport
) {
const { displaySetService } = this.servicesManager.services;
// load any secondary displaySets
const displaySetInstanceUIDs = this.viewportsDisplaySets.get(viewport.id);
// Find overlay display sets (e.g. SEG, RTSTRUCT)
const overlayDisplaySets = displaySetInstanceUIDs
.map(displaySetService.getDisplaySetByUID)
.filter(displaySet => displaySet?.isOverlayDisplaySet);
// if it is only the overlay displaySet, then we need to get the reference
// displaySet imageIds and set them as the imageIds for the viewport,
// here we can do some logic if the reference is missing
// then find the most similar match of displaySet instead
if (!overlayDisplaySets?.length) {
return;
}
return overlayDisplaySets.map(overlayDisplaySet => {
let imageIds;
if (overlayDisplaySet.referencedDisplaySetInstanceUID) {
const referenceDisplaySet = displaySetService.getDisplaySetByUID(
overlayDisplaySet.referencedDisplaySetInstanceUID
);
imageIds = referenceDisplaySet.images.map(image => image.imageId);
}
return {
imageIds,
addOverlayFn: () => this.addOverlayRepresentationForDisplaySet(overlayDisplaySet, viewport),
};
});
}
private addOverlayRepresentationForDisplaySet(
displaySet: OhifTypes.DisplaySet,
viewport: Types.IViewport
): Promise<void> {
const { segmentationService } = this.servicesManager.services;
const segmentationId = displaySet.displaySetInstanceUID;
const representationType =
displaySet.Modality === 'SEG'
? csToolsEnums.SegmentationRepresentations.Labelmap
: csToolsEnums.SegmentationRepresentations.Contour;
const applyRepresentation = () => {
const { predecessorImageId } = displaySet;
const segmentationRepresentationPromise =
segmentationService.addSegmentationRepresentation(viewport.id, {
segmentationId,
predecessorImageId,
type: representationType,
config: {
blendMode:
viewport?.getBlendMode?.() === 1
? BlendModes.LABELMAP_EDGE_PROJECTION_BLEND
: undefined,
},
});
this.storePresentation({ viewportId: viewport.id });
return segmentationRepresentationPromise;
};
// SEG overlay is registered during stack setup, but cornerstone segmentation state
// is created in displaySet.load() (async). Wait until it exists before adding representation.
if (displaySet.Modality === 'SEG') {
if (segmentationService.getSegmentation(segmentationId)) {
return applyRepresentation();
}
// Bound the wait so a failed/aborted SEG load (where SEGMENTATION_LOADING_COMPLETE
// never fires) cannot leave this promise — and the viewport setup awaiting it —
// hanging indefinitely.
const SEG_LOADING_TIMEOUT_MS = 120000;
return new Promise<void>(resolve => {
let settled = false;
let timeoutId;
// Final resolution — extra calls are harmless (resolve is a no-op after
// the first), which lets the timeout stay armed while a representation
// apply is in flight and still bound it.
const finish = () => {
clearTimeout(timeoutId);
resolve();
};
// Give up without applying (load failure / timeout before the event).
const settleWithoutApply = () => {
settled = true;
unsubscribe();
finish();
};
const { unsubscribe } = segmentationService.subscribe(
segmentationService.EVENTS.SEGMENTATION_LOADING_COMPLETE,
async (evt: { segDisplaySet?: OhifTypes.DisplaySet }) => {
Iif (settled || evt.segDisplaySet?.displaySetInstanceUID !== segmentationId) {
return;
}
// Dedupe immediately, but resolve only after the representation is
// applied: awaiters continue into rotation/flip/render and broadcast
// VIEWPORT_DATA_CHANGED (hanging-protocol callbacks, toolbar, e2e
// readiness), which must not observe a viewport whose overlay
// doesn't exist yet. applyRepresentation can be genuinely async
// (stack→volume viewport conversion). The timeout is deliberately
// NOT cleared here — a hung apply stays bounded.
settled = true;
unsubscribe();
try {
await applyRepresentation();
} catch (error) {
console.warn(
`Failed to apply segmentation representation for "${segmentationId}":`,
error
);
} finally {
finish();
}
}
);
// Stop waiting immediately if the SEG load itself fails — otherwise the
// loading-complete event never fires and we would idle until the timeout.
const loadingPromise = (displaySet as { loadingPromise?: Promise<unknown> })
.loadingPromise;
loadingPromise?.catch(error => {
Iif (settled) {
return;
}
console.warn(
`Segmentation "${segmentationId}" failed to load; skipping representation setup.`,
error
);
settleWithoutApply();
});
timeoutId = setTimeout(() => {
Iif (settled) {
// The load completed but applyRepresentation is hung — resolve so
// viewport setup is never blocked past the bound (best-effort
// semantics; the apply may still land later).
console.warn(
`Timed out applying segmentation representation for "${segmentationId}"; resolving viewport readiness anyway.`
);
resolve();
return;
}
console.warn(
`Timed out waiting for segmentation "${segmentationId}" to load; skipping representation setup.`
);
settleWithoutApply();
}, SEG_LOADING_TIMEOUT_MS);
});
}
return applyRepresentation();
}
// Public so the viewport backends (IViewportServiceInternals) can run the
// pending overlay adds from their mount bodies.
async _addOverlayRepresentations(
overlayProcessingResults?: Array<{ addOverlayFn?: () => Promise<void> }>
): Promise<void> {
if (!overlayProcessingResults?.length) {
return;
}
for (const overlayProcessingResult of overlayProcessingResults) {
if (overlayProcessingResult?.addOverlayFn) {
await overlayProcessingResult.addOverlayFn();
}
}
}
// Todo: keepCamera is an interim solution until we have a better solution for
// keeping the camera position when the viewport data is changed
public updateViewport(viewportId: string, viewportData, keepCamera = false) {
const viewportInfo = this.getViewportInfo(viewportId);
const viewport = this.getCornerstoneViewport(viewportId);
// The camera snapshot/restore surface is forked per lane (legacy
// getCamera/setCamera vs native view state), so the backend owns the re-mount.
const displaySetPromise = this.backend.remount(
viewport,
viewportData,
viewportInfo,
keepCamera
);
// remount() returns undefined for viewport families with no re-mount path
// (matching legacy behavior); nothing changed, so skip the event broadcast.
Iif (!displaySetPromise) {
return;
}
displaySetPromise.then(() => {
this._broadcastEvent(this.EVENTS.VIEWPORT_DATA_CHANGED, {
viewportData,
viewportId,
});
});
}
_setDisplaySets(
viewport: Types.IViewport,
viewportData: StackViewportData | VolumeViewportData,
viewportInfo: ViewportInfo,
presentations: Presentations = {}
): Promise<void> {
// The backend (legacy vs native, selected once in the constructor) owns the
// per-family routing: legacy dispatches by the runtime cornerstone viewport
// type; native dispatches by the bound data shape, because native stack and
// volume content both report a single PLANAR_NEXT type (§4.4).
return this.backend.dispatchMount(viewport, viewportData, viewportInfo, presentations);
}
/**
* Removes the resize observer from the viewport element
*/
_removeResizeObserver() {
Iif (this.viewportGridResizeObserver) {
this.viewportGridResizeObserver.disconnect();
}
}
_getSlabThickness(displaySetOptions, volumeId) {
const { blendMode } = displaySetOptions;
if (blendMode === undefined || displaySetOptions.slabThickness === undefined) {
return;
}
// if there is a slabThickness set as a number then use it
Iif (typeof displaySetOptions.slabThickness === 'number') {
return displaySetOptions.slabThickness;
}
if (displaySetOptions.slabThickness.toLowerCase() === 'fullvolume') {
// calculate the slab thickness based on the volume dimensions
const imageVolume = cache.getVolume(volumeId);
const { dimensions, spacing } = imageVolume;
const slabThickness = Math.sqrt(
Math.pow(dimensions[0] * spacing[0], 2) +
Math.pow(dimensions[1] * spacing[1], 2) +
Math.pow(dimensions[2] * spacing[2], 2)
);
return slabThickness;
}
}
_getFrameOfReferenceUID(displaySetInstanceUID) {
const { displaySetService } = this.servicesManager.services;
const displaySet = displaySetService.getDisplaySetByUID(displaySetInstanceUID);
Iif (!displaySet) {
return;
}
if (displaySet.FrameOfReferenceUID) {
return displaySet.FrameOfReferenceUID;
}
Iif (displaySet.Modality === 'SEG') {
const { instance } = displaySet;
return instance.FrameOfReferenceUID;
}
Iif (displaySet.Modality === 'RTSTRUCT') {
const { instance } = displaySet;
return instance.ReferencedFrameOfReferenceSequence.FrameOfReferenceUID;
}
const { images } = displaySet;
Iif (images && images.length) {
return images[0].FrameOfReferenceUID;
}
}
private enqueueViewportResizeRequest() {
this.resizeQueue.push(false); // false indicates viewport resize
clearTimeout(this.viewportResizeTimer);
this.viewportResizeTimer = setTimeout(() => {
this.processViewportResizeQueue();
}, this.gridResizeDelay);
}
private processViewportResizeQueue() {
const isGridResizeInQueue = this.resizeQueue.some(isGridResize => isGridResize);
if (this.resizeQueue.length > 0 && !isGridResizeInQueue && !this.gridResizeTimeOut) {
this.performResize();
}
// Clear the queue after processing viewport resizes
this.resizeQueue = [];
}
private performResize() {
const isImmediate = false;
try {
const viewports = this.getRenderingEngine().getViewports();
// Store the current position presentations for each viewport.
viewports.forEach(({ id: viewportId }) => {
const presentation = this._getPositionPresentation(viewportId);
// During a resize, the slice index should remain unchanged. This is a temporary fix for
// a larger issue regarding the definition of slice index with slab thickness.
// We need to revisit this to make it more robust and understandable.
delete presentation.viewReference?.sliceIndex;
this.beforeResizePositionPresentations.set(viewportId, presentation);
});
// Resize the rendering engine and render.
const renderingEngine = this.renderingEngine;
renderingEngine.resize(isImmediate);
renderingEngine.render();
// Reset the camera for all viewports using position presentation to maintain relative size/position
// which means only those viewports that have a zoom level of 1.
this.beforeResizePositionPresentations.forEach((positionPresentation, viewportId) => {
this.setPresentations(viewportId, {
positionPresentation,
});
});
// Resize and render the rendering engine again.
renderingEngine.resize(isImmediate);
renderingEngine.render();
} catch (e) {
// This can happen if the resize is too close to navigation or shutdown
console.warn('Caught resize exception', e);
}
}
private resetGridResizeTimeout() {
clearTimeout(this.gridResizeTimeOut);
this.gridResizeTimeOut = setTimeout(() => {
this.gridResizeTimeOut = null;
}, this.gridResizeDelay);
}
private _setLutPresentation(
viewport: Types.IStackViewport | Types.IVolumeViewport,
lutPresentation: LutPresentation
): void {
// Forked per backend (§4.3 presentation write): legacy applies via setProperties;
// native via setDisplaySetPresentation (a PLANAR_NEXT viewport has no setProperties),
// so setPresentations no longer throws on the native path.
this.backend.setLutPresentation(viewport, lutPresentation);
}
private _setPositionPresentation(
viewport: Types.IStackViewport | Types.IVolumeViewport,
positionPresentation: PositionPresentation
): void {
// Forked per backend (§4.3 presentation write): both apply the view reference;
// legacy then applies getViewPresentation pan/zoom via setViewPresentation, native
// omits it for now (a PLANAR_NEXT viewport has no setViewPresentation).
this.backend.setPositionPresentation(viewport, positionPresentation);
}
private _setSegmentationPresentation(
viewport: Types.IStackViewport | Types.IVolumeViewport,
segmentationPresentation: SegmentationPresentation
): void {
if (!segmentationPresentation) {
return;
}
const { segmentationService } = this.servicesManager.services;
segmentationPresentation.forEach((presentationItem: SegmentationPresentationItem) => {
const { segmentationId, type, hydrated } = presentationItem;
const { Labelmap, Surface } = csToolsEnums.SegmentationRepresentations;
const isVolume3D = isVolume3DViewportType(viewport);
// Determine the appropriate segmentation representation for the viewport.
// If the current type is Surface but the viewport is not 3D, fallback to Labelmap.
// Otherwise, use the existing type.
const representationType = type === Surface && !isVolume3D ? Labelmap : type;
if (hydrated) {
segmentationService.addSegmentationRepresentation(viewport.id, {
segmentationId,
type: representationType,
config: {
blendMode:
viewport?.getBlendMode?.() === 1
? BlendModes.LABELMAP_EDGE_PROJECTION_BLEND
: undefined,
},
});
}
});
}
/**
* Gets the display sets for a given viewport
* @param viewportId - The ID of the viewport to get display sets for
* @returns Array of display sets for the viewport
*/
public getViewportDisplaySets(viewportId: string): OhifTypes.DisplaySet[] {
const { displaySetService } = this.servicesManager.services;
const displaySetInstanceUIDs = this.viewportsDisplaySets.get(viewportId) || [];
return displaySetInstanceUIDs
.map(uid => displaySetService.getDisplaySetByUID(uid))
.filter(Boolean);
}
}
export default CornerstoneViewportService;
|