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

61.32% Statements 287/468
44.93% Branches 102/227
65.57% Functions 40/61
60.99% Lines 283/464

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                                                                                                                                                    91x 91x           91x           91x     91x   91x 91x   91x           91x   91x 91x   91x   90x 90x   1x 1x               91x       228x             91x 91x 91x         91x 91x   91x       91x 91x     547x   547x       547x   547x 280x     267x       120x   120x 55x     65x         65x         65x     91x       91x         91x             183x   183x 183x                                                                                               1x 1x       1x   1x 1x   1x   1x 1x     1x       1x         1x 1x 1x         1x   1x 1x         1x                                                                                                               1x   1x       1x   1x 1x   1x   1x 1x         1x             4x   4x       4x   4x       4x   4x 4x   4x                               92x   92x 15x     77x   77x       77x 77x                                                                               4x   4x 1x     3x 3x   3x 3x             3x       3x                     3x 3x           3x 3x       3x     3x     91x                                                                                                                       3x 3x                                                       1x 1x 1x       1x                                                                                                                           4x 3x                           4x 1x   4x       4x 4x     4x       4x       4x 1x     4x       4x           4x                                                                                                                                                                                           91x                                           91x 336x 336x                       336x   336x   440x 440x 440x 440x 104x   336x   336x     336x       336x 7x     336x     336x   336x                                                 91x 340x   340x       340x 340x 340x 340x 680x 680x     340x   340x                                 69x   69x           69x   69x   69x   69x     69x 69x   69x                         69x 69x               69x 69x   69x   69x         69x                                 22x   22x         22x   22x           22x   22x   22x               22x                 22x 22x                         22x   22x   22x                                                                                       91x   91x   91x 69x             778x 15x     763x   763x 1x         762x 99x       762x 663x 663x     762x             91x     91x                                   91x                   91x         543x     543x       543x             543x           543x               543x     543x       543x                                       91x 1377x                     9x 9x 9x                               595x 595x 277x     318x 318x   318x   318x 3x     315x 315x   315x 315x                                                   69x 69x   69x                       91x 1111x                                               1111x   1111x   1111x   1111x 1111x 1111x 1111x       1111x           1111x   1111x             1111x   1111x                     91x 629x                                               629x   629x   629x   629x 629x 629x           629x   629x         629x 629x         629x   629x                         91x                                         91x 3x 3x           88x       88x 88x                             256x 256x 256x 256x         256x                                                                       91x                                             1x 1x 1x       1x 1x             17x 17x 17x 17x       17x 17x       17x 17x 17x 17x                                        
import vtkVolume from '@kitware/vtk.js/Rendering/Core/Volume';
import vtkColorTransferFunction from '@kitware/vtk.js/Rendering/Core/ColorTransferFunction';
import vtkColorMaps from '@kitware/vtk.js/Rendering/Core/ColorTransferFunction/ColorMaps';
import vtkPiecewiseFunction from '@kitware/vtk.js/Common/DataModel/PiecewiseFunction';
 
import { vec2, vec3 } from 'gl-matrix';
 
import cache from '../cache';
import {
  MPR_CAMERA_VALUES,
  RENDERING_DEFAULTS,
  VIEWPORT_PRESETS,
} from '../constants';
import {
  BlendModes,
  Events,
  InterpolationType,
  OrientationAxis,
  ViewportStatus,
  VOILUTFunctionType,
} from '../enums';
import ViewportType from '../enums/ViewportType';
import eventTarget from '../eventTarget';
import { getShouldUseCPURendering } from '../init';
import { loadVolume } from '../loaders/volumeLoader';
import type {
  ActorEntry,
  ColormapPublic,
  FlipDirection,
  IImageData,
  IVolumeInput,
  OrientationVectors,
  Point2,
  Point3,
  VOIRange,
  EventTypes,
  VolumeViewportProperties,
  ViewReferenceSpecifier,
  ReferenceCompatibleOptions,
} from '../types';
import { VoiModifiedEventDetail } from '../types/EventTypes';
import type { ViewportInput } from '../types/IViewport';
import type IVolumeViewport from '../types/IVolumeViewport';
import type { ViewReference } from '../types/IViewport';
import {
  actorIsA,
  applyPreset,
  createSigmoidRGBTransferFunction,
  getVoiFromSigmoidRGBTransferFunction,
  imageIdToURI,
  invertRgbTransferFunction,
  triggerEvent,
  colormap as colormapUtils,
} from '../utilities';
import { createVolumeActor } from './helpers';
import volumeNewImageEventDispatcher, {
  resetVolumeNewImageState,
} from './helpers/volumeNewImageEventDispatcher';
import Viewport from './Viewport';
import type { vtkSlabCamera as vtkSlabCameraType } from './vtkClasses/vtkSlabCamera';
import vtkSlabCamera from './vtkClasses/vtkSlabCamera';
import transformWorldToIndex from '../utilities/transformWorldToIndex';
import { findMatchingColormap } from '../utilities/colormap';
import { getTransferFunctionNodes } from '../utilities/transferFunctionUtils';
/**
 * Abstract base class for volume viewports. VolumeViewports are used to render
 * 3D volumes from which various orientations can be viewed. Since VolumeViewports
 * use SharedVolumeMappers behind the scene, memory footprint of visualizations
 * of the same volume in different orientations is very small.
 *
 * For setting volumes on viewports you need to use {@link addVolumesToViewports}
 * which will add volumes to the specified viewports.
 */
abstract class BaseVolumeViewport extends Viewport implements IVolumeViewport {
  useCPURendering = false;
  useNativeDataType = false;
  private _FrameOfReferenceUID: string;
 
  protected initialTransferFunctionNodes: any;
  // Viewport Properties
  private globalDefaultProperties: VolumeViewportProperties;
  private perVolumeIdDefaultProperties = new Map<
    string,
    VolumeViewportProperties
  >();
  // Camera properties
  protected initialViewUp: Point3;
  protected viewportProperties: VolumeViewportProperties = {};
 
  constructor(props: ViewportInput) {
    super(props);
 
    this.useCPURendering = getShouldUseCPURendering();
    this.useNativeDataType = this._shouldUseNativeDataType();
 
    Iif (this.useCPURendering) {
      throw new Error(
        'VolumeViewports cannot be used whilst CPU Fallback Rendering is enabled.'
      );
    }
 
    const renderer = this.getRenderer();
 
    const camera = vtkSlabCamera.newInstance();
    renderer.setActiveCamera(camera);
 
    switch (this.type) {
      case ViewportType.ORTHOGRAPHIC:
        camera.setParallelProjection(true);
        break;
      case ViewportType.VOLUME_3D:
        camera.setParallelProjection(true);
        break;
      case ViewportType.PERSPECTIVE:
        camera.setParallelProjection(false);
        break;
      default:
        throw new Error(`Unrecognized viewport type: ${this.type}`);
    }
 
    this.initializeVolumeNewImageEventDispatcher();
  }
 
  static get useCustomRenderingPipeline(): boolean {
    return false;
  }
 
  protected applyViewOrientation(
    orientation: OrientationAxis | OrientationVectors
  ) {
    const { viewPlaneNormal, viewUp } =
      this._getOrientationVectors(orientation);
    const camera = this.getVtkActiveCamera();
    camera.setDirectionOfProjection(
      -viewPlaneNormal[0],
      -viewPlaneNormal[1],
      -viewPlaneNormal[2]
    );
    camera.setViewUpFrom(viewUp);
    this.initialViewUp = viewUp;
 
    this.resetCamera();
  }
 
  private initializeVolumeNewImageEventDispatcher(): void {
    const volumeNewImageHandlerBound = volumeNewImageHandler.bind(this);
    const volumeNewImageCleanUpBound = volumeNewImageCleanUp.bind(this);
 
    function volumeNewImageHandler(cameraEvent) {
      const { viewportId } = cameraEvent.detail;
 
      Iif (viewportId !== this.id || this.isDisabled) {
        return;
      }
 
      const viewportImageData = this.getImageData();
 
      if (!viewportImageData) {
        return;
      }
 
      volumeNewImageEventDispatcher(cameraEvent);
    }
 
    function volumeNewImageCleanUp(evt) {
      const { viewportId } = evt.detail;
 
      if (viewportId !== this.id) {
        return;
      }
 
      this.element.removeEventListener(
        Events.CAMERA_MODIFIED,
        volumeNewImageHandlerBound
      );
 
      eventTarget.removeEventListener(
        Events.ELEMENT_DISABLED,
        volumeNewImageCleanUpBound
      );
 
      resetVolumeNewImageState(viewportId);
    }
 
    this.element.removeEventListener(
      Events.CAMERA_MODIFIED,
      volumeNewImageHandlerBound
    );
    this.element.addEventListener(
      Events.CAMERA_MODIFIED,
      volumeNewImageHandlerBound
    );
 
    eventTarget.addEventListener(
      Events.ELEMENT_DISABLED,
      volumeNewImageCleanUpBound
    );
  }
 
  protected resetVolumeViewportClippingRange() {
    const activeCamera = this.getVtkActiveCamera();
 
    if (activeCamera.getParallelProjection()) {
      activeCamera.setClippingRange(
        -RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE,
        RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE
      );
    } else E{
      activeCamera.setClippingRange(
        RENDERING_DEFAULTS.MINIMUM_SLAB_THICKNESS,
        RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE
      );
    }
  }
 
  /**
   * Sets the properties for the volume viewport on the volume
   * Sets the VOILUTFunction property for the volume viewport on the volume
   *
   * @param VOILUTFunction - Sets the voi mode (LINEAR or SAMPLED_SIGMOID)
   * @param volumeId - The volume id to set the properties for (if undefined, the first volume)
   * @param suppressEvents - If true, the viewport will not emit events
   */
  private setVOILUTFunction(
    voiLUTFunction: VOILUTFunctionType,
    volumeId?: string,
    suppressEvents?: boolean
  ): void {
    // make sure the VOI LUT function is valid in the VOILUTFunctionType which is enum
    if (Object.values(VOILUTFunctionType).indexOf(voiLUTFunction) === -1) {
      voiLUTFunction = VOILUTFunctionType.LINEAR;
    }
    const { voiRange } = this.getProperties();
    this.setVOI(voiRange, volumeId, suppressEvents);
    this.viewportProperties.VOILUTFunction = voiLUTFunction;
  }
 
  /**
   * Sets the colormap for the volume with the given ID and optionally suppresses events.
   *
   * @param colormap - The colormap to apply (e.g., "hsv").
   * @param volumeId - The ID of the volume to set the colormap for.
   * @param suppressEvents - If `true`, events will not be emitted during the colormap a
   *
   * @returns void
   */
  private setColormap(
    colormap: ColormapPublic,
    volumeId: string,
    suppressEvents?: boolean
  ) {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
    Iif (!applicableVolumeActorInfo) {
      return;
    }
 
    const { volumeActor } = applicableVolumeActorInfo;
 
    const cfun = vtkColorTransferFunction.newInstance();
    let colormapObj = colormapUtils.getColormap(colormap.name);
 
    const { name } = colormap;
 
    Eif (!colormapObj) {
      colormapObj = vtkColorMaps.getPresetByName(name);
    }
 
    Iif (!colormapObj) {
      throw new Error(`Colormap ${colormap} not found`);
    }
 
    const range = volumeActor
      .getProperty()
      .getRGBTransferFunction(0)
      .getRange();
 
    cfun.applyColorMap(colormapObj);
    cfun.setMappingRange(range[0], range[1]);
    volumeActor.getProperty().setRGBTransferFunction(0, cfun);
 
    // This configures the viewport to use the most recently applied colormap.
    // However, this approach is not optimal when dealing with two volumes, as it prevents retrieval of the
    // colormap for Volume A if Volume B's colormap was the last one applied.
    this.viewportProperties.colormap = colormap;
 
    Eif (!suppressEvents) {
      const eventDetail = {
        viewportId: this.id,
        colormap,
        volumeId,
      };
      triggerEvent(this.element, Events.COLORMAP_MODIFIED, eventDetail);
    }
  }
 
  /**
   * Sets the opacity for the volume with the given ID.
   *
   * @param colormap - An object containing opacity that can be a number or an array of OpacityMapping
   * @param volumeId - The ID of the volume to set the opacity for.
   *
   * @returns void
   */
  private setOpacity(colormap: ColormapPublic, volumeId: string) {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
    if (!applicableVolumeActorInfo) {
      return;
    }
    const { volumeActor } = applicableVolumeActorInfo;
 
    const ofun = vtkPiecewiseFunction.newInstance();
    if (typeof colormap.opacity === 'number') {
      const range = volumeActor
        .getProperty()
        .getRGBTransferFunction(0)
        .getRange();
 
      ofun.addPoint(range[0], colormap.opacity);
      ofun.addPoint(range[1], colormap.opacity);
    } else {
      colormap.opacity.forEach(({ opacity, value }) => {
        ofun.addPoint(value, opacity);
      });
    }
    volumeActor.getProperty().setScalarOpacity(0, ofun);
 
    if (!this.viewportProperties.colormap) {
      this.viewportProperties.colormap = {};
    }
 
    this.viewportProperties.colormap.opacity = colormap.opacity;
  }
 
  /**
   * Sets the inversion for the volume transfer function
   *
   * @param inverted - Should the transfer function be inverted?
   * @param volumeId - volumeId
   * @param suppressEvents - If `true`, events will not be published
   *
   * @returns void
   */
  private setInvert(
    inverted: boolean,
    volumeId?: string,
    suppressEvents?: boolean
  ) {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
 
    Iif (!applicableVolumeActorInfo) {
      return;
    }
 
    const volumeIdToUse = applicableVolumeActorInfo.volumeId;
 
    const cfun = this._getOrCreateColorTransferFunction(volumeIdToUse);
    invertRgbTransferFunction(cfun);
 
    this.viewportProperties.invert = inverted;
 
    Eif (!suppressEvents) {
      const eventDetail: VoiModifiedEventDetail = {
        ...this.getVOIModifiedEventDetail(volumeIdToUse),
        invertStateChanged: true,
      };
 
      triggerEvent(this.element, Events.VOI_MODIFIED, eventDetail);
    }
  }
 
  protected getVOIModifiedEventDetail(
    volumeId: string
  ): VoiModifiedEventDetail {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
 
    Iif (!applicableVolumeActorInfo) {
      throw new Error(`No actor found for the given volumeId: ${volumeId}`);
    }
 
    const volumeActor = applicableVolumeActorInfo.volumeActor;
 
    const transferFunction = volumeActor
      .getProperty()
      .getRGBTransferFunction(0);
 
    const range = transferFunction.getMappingRange();
 
    const matchedColormap = this.getColormap(volumeId);
    const { VOILUTFunction, invert } = this.getProperties(volumeId);
 
    return {
      viewportId: this.id,
      range: {
        lower: range[0],
        upper: range[1],
      },
      volumeId: applicableVolumeActorInfo.volumeId,
      VOILUTFunction: VOILUTFunction,
      colormap: matchedColormap,
      invert,
    };
  }
 
  private _getOrCreateColorTransferFunction(
    volumeId: string
  ): vtkColorTransferFunction {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
 
    if (!applicableVolumeActorInfo) {
      return null;
    }
 
    const { volumeActor } = applicableVolumeActorInfo;
 
    const rgbTransferFunction = volumeActor
      .getProperty()
      .getRGBTransferFunction(0);
 
    Eif (rgbTransferFunction) {
      return rgbTransferFunction;
    }
 
    const newRGBTransferFunction = vtkColorTransferFunction.newInstance();
    volumeActor.getProperty().setRGBTransferFunction(0, newRGBTransferFunction);
 
    return newRGBTransferFunction;
  }
 
  protected setInterpolationType(
    interpolationType: InterpolationType,
    volumeId?: string
  ) {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
 
    if (!applicableVolumeActorInfo) {
      return;
    }
 
    const { volumeActor } = applicableVolumeActorInfo;
    const volumeProperty = volumeActor.getProperty();
 
    // @ts-ignore
    volumeProperty.setInterpolationType(interpolationType);
    this.viewportProperties.interpolationType = interpolationType;
  }
 
  /**
   * Sets the properties for the volume viewport on the volume
   * (if fusion, it sets it for the first volume in the fusion)
   *
   * @param voiRange - Sets the lower and upper voi
   * @param volumeId - The volume id to set the properties for (if undefined, the first volume)
   * @param suppressEvents - If true, the viewport will not emit events
   */
  private setVOI(
    voiRange: VOIRange,
    volumeId?: string,
    suppressEvents = false
  ): void {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
 
    if (!applicableVolumeActorInfo) {
      return;
    }
 
    const { volumeActor } = applicableVolumeActorInfo;
    const volumeIdToUse = applicableVolumeActorInfo.volumeId;
 
    let voiRangeToUse = voiRange;
    Iif (typeof voiRangeToUse === 'undefined') {
      const imageData = volumeActor.getMapper().getInputData();
      const range = imageData.getPointData().getScalars().getRange();
      const maxVoiRange = { lower: range[0], upper: range[1] };
      voiRangeToUse = maxVoiRange;
    }
 
    const { VOILUTFunction } = this.getProperties(volumeIdToUse);
 
    // scaling logic here
    // https://github.com/Kitware/vtk-js/blob/c6f2e12cddfe5c0386a73f0793eb6d9ab20d573e/Sources/Rendering/OpenGL/VolumeMapper/index.js#L957-L972
    Iif (VOILUTFunction === VOILUTFunctionType.SAMPLED_SIGMOID) {
      const cfun = createSigmoidRGBTransferFunction(voiRangeToUse);
      volumeActor.getProperty().setRGBTransferFunction(0, cfun);
    } else {
      // TODO: refactor and make it work for PET series (inverted/colormap)
      // const cfun = createLinearRGBTransferFunction(voiRangeToUse);
      // volumeActor.getProperty().setRGBTransferFunction(0, cfun);
 
      // Todo: Moving from LINEAR to SIGMOID and back to LINEAR will not
      // work until we implement it in a different way because the
      // LINEAR transfer function is not recreated.
      const { lower, upper } = voiRangeToUse;
      volumeActor
        .getProperty()
        .getRGBTransferFunction(0)
        .setRange(lower, upper);
    }
 
    Eif (!suppressEvents) {
      const eventDetail: VoiModifiedEventDetail = {
        ...this.getVOIModifiedEventDetail(volumeIdToUse),
      };
 
      triggerEvent(this.element, Events.VOI_MODIFIED, eventDetail);
    }
 
    this.viewportProperties.voiRange = voiRangeToUse;
  }
 
  protected setRotation = (rotation: number) => {
    const panFit = this.getPan(this.fitToCanvasCamera);
    const pan = this.getPan();
    const previousCamera = this.getCamera();
    const panSub = vec2.sub([0, 0], panFit, pan) as Point2;
    this.setPan(panSub, false);
    const { flipVertical } = this.getCamera();
 
    // Moving back to zero rotation, for new scrolled slice rotation is 0 after camera reset
    const initialViewUp = flipVertical
      ? vec3.negate([0, 0, 0], this.initialViewUp)
      : this.initialViewUp;
 
    this.setCameraNoEvent({
      viewUp: initialViewUp as Point3,
    });
 
    // rotating camera to the new value
    this.rotateCamera(rotation);
    const afterPan = this.getPan();
    const afterPanFit = this.getPan(this.fitToCanvasCamera);
    const newCenter = vec2.sub([0, 0], afterPan, afterPanFit);
    const newOffset = vec2.add([0, 0], panFit, newCenter) as Point2;
    this.setPan(newOffset, false);
 
    if (this._suppressCameraModifiedEvents) {
      return;
    }
 
    // New camera after rotation
    const camera = this.getCamera();
 
    const eventDetail: EventTypes.CameraModifiedEventDetail = {
      previousCamera,
      camera,
      element: this.element,
      viewportId: this.id,
      renderingEngineId: this.renderingEngineId,
      rotation,
    };
 
    triggerEvent(this.element, Events.CAMERA_MODIFIED, eventDetail);
    this.viewportProperties.rotation = rotation;
  };
 
  private rotateCamera(rotation: number): void {
    const rotationToApply = rotation - this.getRotation();
    // rotating camera to the new value
    this.getVtkActiveCamera().roll(-rotationToApply);
  }
 
  /**
   * Update the default properties for the volume viewport on the volume
   * @param ViewportProperties - The properties to set
   * @param volumeId - The volume id to set the default properties for (if undefined, we set the global default viewport properties)
   */
  public setDefaultProperties(
    ViewportProperties: VolumeViewportProperties,
    volumeId?: string
  ): void {
    if (volumeId == null) {
      this.globalDefaultProperties = ViewportProperties;
    } else E{
      this.perVolumeIdDefaultProperties.set(volumeId, ViewportProperties);
    }
  }
 
  /**
   * Remove the global default properties of the viewport or remove default properties for a volumeId if specified
   * @param volumeId If given, we remove the default properties only for this volumeId, if not
   * the global default properties will be removed
   */
  public clearDefaultProperties(volumeId?: string): void {
    if (volumeId == null) {
      this.globalDefaultProperties = {};
      this.resetProperties();
    } else {
      this.perVolumeIdDefaultProperties.delete(volumeId);
      this.resetToDefaultProperties(volumeId);
    }
  }
 
  /**
   * Gets a view target, allowing comparison between view positions as well
   * as restoring views later.
   */
  public getViewReference(
    viewRefSpecifier: ViewReferenceSpecifier = {}
  ): ViewReference {
    const target = super.getViewReference(viewRefSpecifier);
    Eif (viewRefSpecifier?.forFrameOfReference !== false) {
      target.volumeId = this.getVolumeId(viewRefSpecifier);
    }
    // TODO - add referencedImageId as a base URL for an image to allow a generic
    // method to specify which volumes this should apply to.
    return {
      ...target,
      sliceIndex: this.getCurrentImageIdIndex(),
    };
  }
 
  /**
   * Find out if this viewport would show this view
   *
   * @param options - allows specifying whether the view COULD display this with
   *                  some modification - either navigation or displaying as volume.
   * @returns true if the target is compatible with this view
   */
  public isReferenceViewable(
    viewRef: ViewReference,
    options?: ReferenceCompatibleOptions
  ): boolean {
    if (!super.isReferenceViewable(viewRef, options)) {
      return false;
    }
    if (options?.withNavigation) {
      return true;
    }
    const currentSliceIndex = this.getCurrentImageIdIndex();
    const { sliceIndex } = viewRef;
    if (Array.isArray(sliceIndex)) {
      return (
        sliceIndex[0] <= currentSliceIndex && currentSliceIndex <= sliceIndex[1]
      );
    }
    return sliceIndex === undefined || sliceIndex === currentSliceIndex;
  }
 
  /**
   * Sets the properties for the volume viewport on the volume
   * and if setProperties is called for the first time, the properties will also become the default one.
   * (if fusion, it sets it for the first volume in the fusion)
   *
   * @param VolumeViewportProperties - The properties to set
   * @param [VolumeViewportProperties.voiRange] - Sets the lower and upper voi
   * @param [VolumeViewportProperties.VOILUTFunction] - Sets the voi mode (LINEAR, or SAMPLED_SIGMOID)
   * @param [VolumeViewportProperties.invert] - Inverts the color transfer function
   * @param [VolumeViewportProperties.colormap] - Sets the colormap
   * @param [VolumeViewportProperties.preset] - Sets the colormap preset
   * @param volumeId - The volume id to set the properties for (if undefined, the first volume)
   * @param suppressEvents - If true, the viewport will not emit events
   */
  public setProperties(
    {
      voiRange,
      VOILUTFunction,
      invert,
      colormap,
      preset,
      interpolationType,
      slabThickness,
      rotation,
    }: VolumeViewportProperties = {},
    volumeId?: string,
    suppressEvents = false
  ): void {
    //If the viewport hasn't been initialized, we need to set the default properties
    if (this.globalDefaultProperties == null) {
      this.setDefaultProperties({
        voiRange,
        VOILUTFunction,
        invert,
        colormap,
        preset,
        slabThickness,
        rotation,
      });
    }
 
    // Note: colormap should always be done first, since we can then
    // modify the voiRange
 
    if (colormap?.name) {
      this.setColormap(colormap, volumeId, suppressEvents);
    }
    Iif (colormap?.opacity != null) {
      this.setOpacity(colormap, volumeId);
    }
 
    Eif (voiRange !== undefined) {
      this.setVOI(voiRange, volumeId, suppressEvents);
    }
 
    Iif (typeof interpolationType !== 'undefined') {
      this.setInterpolationType(interpolationType);
    }
 
    Iif (VOILUTFunction !== undefined) {
      this.setVOILUTFunction(VOILUTFunction, volumeId, suppressEvents);
    }
 
    if (invert !== undefined && this.viewportProperties.invert !== invert) {
      this.setInvert(invert, volumeId, suppressEvents);
    }
 
    Iif (preset !== undefined) {
      this.setPreset(preset, volumeId, suppressEvents);
    }
 
    Iif (slabThickness !== undefined) {
      this.setSlabThickness(slabThickness);
      //We need to set the current slab thickness here since setSlabThickness is define in VolumeViewport
      this.viewportProperties.slabThickness = slabThickness;
    }
 
    Iif (rotation !== undefined) {
      this.setRotation(rotation);
    }
  }
 
  /**
   * Reset the viewport properties to the default values
   */
  public resetToDefaultProperties(volumeId: string): void {
    const properties = this.globalDefaultProperties;
 
    if (properties.colormap?.name) {
      this.setColormap(properties.colormap, volumeId);
    }
    if (properties.colormap?.opacity != null) {
      this.setOpacity(properties.colormap, volumeId);
    }
 
    if (properties.voiRange !== undefined) {
      this.setVOI(properties.voiRange, volumeId);
    }
 
    if (properties.VOILUTFunction !== undefined) {
      this.setVOILUTFunction(properties.VOILUTFunction, volumeId);
    }
 
    if (properties.invert !== undefined) {
      this.setInvert(properties.invert, volumeId);
    }
 
    if (properties.slabThickness !== undefined) {
      this.setSlabThickness(properties.slabThickness);
      //We need to set the current slabThickness here since setSlabThickness is define in VolumeViewport
      this.viewportProperties.slabThickness = properties.slabThickness;
    }
 
    if (properties.rotation !== undefined) {
      this.setRotation(properties.rotation);
    }
 
    this.render();
  }
 
  /**
   * Sets the specified preset for the volume with the given ID
   *
   * @param presetName - The name of the preset to apply (e.g., "CT-Bone").
   * @param volumeId - The ID of the volume to set the preset for.
   * @param suppressEvents - If `true`, events will not be emitted during the preset application.
   *
   * @returns void
   */
  private setPreset(presetNameOrObj, volumeId, suppressEvents) {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
 
    if (!applicableVolumeActorInfo) {
      return;
    }
 
    const { volumeActor } = applicableVolumeActorInfo;
 
    let preset = presetNameOrObj;
 
    if (typeof preset === 'string') {
      preset = VIEWPORT_PRESETS.find((preset) => {
        return preset.name === presetNameOrObj;
      });
    }
 
    if (!preset) {
      return;
    }
 
    applyPreset(volumeActor, preset);
 
    this.viewportProperties.preset = preset;
    this.render();
 
    if (!suppressEvents) {
      triggerEvent(this.element, Events.PRESET_MODIFIED, {
        viewportId: this.id,
        volumeId: applicableVolumeActorInfo.volumeId,
        actor: volumeActor,
        presetName: preset.name,
      });
    }
  }
 
  /**
   * Retrieve the viewport default properties
   * @param volumeId If given, we retrieve the default properties of a volumeId if it exists
   * If not given,we return the global properties of the viewport
   * @returns default viewport properties including voi, invert, interpolation type, colormap
   */
  public getDefaultProperties = (
    volumeId?: string
  ): VolumeViewportProperties => {
    let volumeProperties;
    if (volumeId !== undefined) {
      volumeProperties = this.perVolumeIdDefaultProperties.get(volumeId);
    }
 
    if (volumeProperties !== undefined) {
      return volumeProperties;
    }
 
    return {
      ...this.globalDefaultProperties,
    };
  };
 
  /**
   * Retrieve the viewport properties
   * @param volumeId - The volume id to get the properties for (if undefined, the first volume)
   * @returns viewport properties including voi, interpolation type: TODO: slabThickness, invert, rotation, flip
   */
  public getProperties = (volumeId?: string): VolumeViewportProperties => {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
    Iif (!applicableVolumeActorInfo) {
      return;
    }
 
    const {
      colormap: latestColormap,
      VOILUTFunction,
      interpolationType,
      invert,
      slabThickness,
      rotation,
      preset,
    } = this.viewportProperties;
 
    const voiRanges = this.getActors()
      .map((actorEntry) => {
        const volumeActor = actorEntry.actor as vtkVolume;
        const volumeId = actorEntry.uid;
        const volume = cache.getVolume(volumeId);
        if (!volume) {
          return null;
        }
        const cfun = volumeActor.getProperty().getRGBTransferFunction(0);
        const [lower, upper] =
          this.viewportProperties?.VOILUTFunction === 'SIGMOID'
            ? getVoiFromSigmoidRGBTransferFunction(cfun)
            : cfun.getRange();
        return { volumeId, voiRange: { lower, upper } };
      })
      .filter(Boolean);
 
    const voiRange = volumeId
      ? voiRanges.find((range) => range.volumeId === volumeId)?.voiRange
      : voiRanges[0]?.voiRange;
 
    const volumeColormap = this.getColormap(volumeId);
 
    const colormap =
      volumeId && volumeColormap ? volumeColormap : latestColormap;
 
    return {
      colormap: colormap,
      voiRange: voiRange,
      VOILUTFunction: VOILUTFunction,
      interpolationType: interpolationType,
      invert: invert,
      slabThickness: slabThickness,
      rotation: rotation,
      preset,
    };
  };
 
  /**
   * This function extracts the nodes from the RGB Transfer Function, transforming each node's x, r, g, b properties
   * into a unified array "RGB Points." Then, it compares these RGB Points—specifically the r, g, b values—with
   * those in the predefined vtk colormap presets. Upon finding a matching set of r, g, b values, the function identifies and selects the
   * corresponding colormap.
   *
   * Next, the function extracts an array of opacity points, formatted as a sequence of [x,y] pairs, where 'x' represents a value and
   * 'y' represents its opacity. It iterates through this array to construct an opacity object that maps each value to its opacity.
   *
   * The function returns an object that includes the name of the identified colormap and the constructed opacity object.
   * @param applicableVolumeActorInfo  - The volume actor information for the volume
   * @returns colormap information for the volume if identified
   */
  private getColormap = (volumeId) => {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
 
    Iif (!applicableVolumeActorInfo) {
      return;
    }
 
    const { volumeActor } = applicableVolumeActorInfo;
    const cfun = volumeActor.getProperty().getRGBTransferFunction(0);
    const { nodes } = cfun.getState();
    const RGBPoints = nodes.reduce((acc, node) => {
      acc.push(node.x, node.r, node.g, node.b);
      return acc;
    }, []);
 
    const matchedColormap = findMatchingColormap(RGBPoints, volumeActor);
 
    return matchedColormap;
  };
 
  /**
   * Creates volume actors for all volumes defined in the `volumeInputArray`.
   * For each entry, if a `callback` is supplied, it will be called with the new volume actor as input.
   * For each entry, if a `blendMode` and/or `slabThickness` is defined, this will be set on the actor's
   * `VolumeMapper`.
   *
   * @param volumeInputArray - The array of `VolumeInput`s which define the volumes to add.
   * @param immediate - Whether the `Viewport` should be rendered as soon as volumes are added.
   */
  public async setVolumes(
    volumeInputArray: Array<IVolumeInput>,
    immediate = false,
    suppressEvents = false
  ): Promise<void> {
    const firstImageVolume = cache.getVolume(volumeInputArray[0].volumeId);
 
    Iif (!firstImageVolume) {
      throw new Error(
        `imageVolume with id: ${firstImageVolume.volumeId} does not exist`
      );
    }
 
    const FrameOfReferenceUID = firstImageVolume.metadata.FrameOfReferenceUID;
 
    await this._isValidVolumeInputArray(volumeInputArray, FrameOfReferenceUID);
 
    this._FrameOfReferenceUID = FrameOfReferenceUID;
 
    const volumeActors = [];
 
    // One actor per volume
    for (let i = 0; i < volumeInputArray.length; i++) {
      const { volumeId, actorUID, slabThickness } = volumeInputArray[i];
 
      const actor = await createVolumeActor(
        volumeInputArray[i],
        this.element,
        this.id,
        suppressEvents,
        this.useNativeDataType
      );
 
      // We cannot use only volumeId since then we cannot have for instance more
      // than one representation of the same volume (since actors would have the
      // same name, and we don't allow that) AND We cannot use only any uid, since
      // we rely on the volume in the cache for mapper. So we prefer actorUID if
      // it is defined, otherwise we use volumeId for the actor name.
      const uid = actorUID || volumeId;
      volumeActors.push({
        uid,
        actor,
        slabThickness,
        referenceId: volumeId,
      });
    }
 
    this._setVolumeActors(volumeActors);
    this.viewportStatus = ViewportStatus.PRE_RENDER;
 
    this.initializeColorTransferFunction(volumeInputArray);
 
    triggerEvent(this.element, Events.VOLUME_VIEWPORT_NEW_VOLUME, {
      viewportId: this.id,
      volumeActors,
    });
 
    Iif (immediate) {
      this.render();
    }
  }
 
  /**
   * Creates and adds volume actors for all volumes defined in the `volumeInputArray`.
   * For each entry, if a `callback` is supplied, it will be called with the new volume actor as input.
   *
   * @param volumeInputArray - The array of `VolumeInput`s which define the volumes to add.
   * @param immediate - Whether the `Viewport` should be rendered as soon as volumes are added.
   */
  public async addVolumes(
    volumeInputArray: Array<IVolumeInput>,
    immediate = false,
    suppressEvents = false
  ): Promise<void> {
    const firstImageVolume = cache.getVolume(volumeInputArray[0].volumeId);
 
    Iif (!firstImageVolume) {
      throw new Error(
        `imageVolume with id: ${firstImageVolume.volumeId} does not exist`
      );
    }
    const volumeActors = [];
 
    await this._isValidVolumeInputArray(
      volumeInputArray,
      this._FrameOfReferenceUID
    );
 
    // One actor per volume
    for (let i = 0; i < volumeInputArray.length; i++) {
      const { volumeId, visibility, actorUID, slabThickness } =
        volumeInputArray[i];
 
      const actor = await createVolumeActor(
        volumeInputArray[i],
        this.element,
        this.id,
        suppressEvents,
        this.useNativeDataType
      );
 
      Iif (visibility === false) {
        actor.setVisibility(false);
      }
 
      // We cannot use only volumeId since then we cannot have for instance more
      // than one representation of the same volume (since actors would have the
      // same name, and we don't allow that) AND We cannot use only any uid, since
      // we rely on the volume in the cache for mapper. So we prefer actorUID if
      // it is defined, otherwise we use volumeId for the actor name.
      const uid = actorUID || volumeId;
      volumeActors.push({
        uid,
        actor,
        slabThickness,
        // although the actor UID is defined, we need to use the volumeId for the
        // referenceId, since the actor UID is used to reference the actor in the
        // viewport, however, the actor is created from its volumeId
        // and if later we need to grab the referenced volume from cache,
        // we can use the referenceId to get the volume from the cache
        referenceId: volumeId,
      });
    }
 
    this.addActors(volumeActors);
 
    this.initializeColorTransferFunction(volumeInputArray);
 
    Iif (immediate) {
      // render
      this.render();
    }
  }
 
  /**
   * It removes the volume actor from the Viewport. If the volume actor is not in
   * the viewport, it does nothing.
   * @param actorUIDs - Array of actor UIDs to remove. In case of simple volume it will
   * be the volume Id, but in case of Segmentation it will be `{volumeId}-{representationType}`
   * since the same volume can be rendered in multiple representations.
   * @param immediate - If true, the Viewport will be rendered immediately
   */
  public removeVolumeActors(actorUIDs: Array<string>, immediate = false): void {
    // Todo: This is actually removeActors
    this.removeActors(actorUIDs);
 
    if (immediate) {
      this.render();
    }
  }
 
  /**
   * It sets the orientation for the camera, the orientation can be one of the
   * following: axial, sagittal, coronal, default. Use the Enums.OrientationAxis
   * to set the orientation. The "default" orientation is the orientation that
   * the volume was acquired in (scan axis)
   *
   * @param orientation - The orientation to set the camera to.
   * @param immediate - Whether the `Viewport` should be rendered as soon as the camera is set.
   */
  public setOrientation(orientation: OrientationAxis, immediate = true): void {
    console.warn('Method "setOrientation" needs implementation');
  }
 
  /**
   * Initializes the color transfer function nodes for a given volume.
   *
   * @param volumeInputArray - Array of volume inputs.
   * @param getTransferFunctionNodes - Function to get the transfer function nodes.
   * @returns void
   */
  private initializeColorTransferFunction(volumeInputArray) {
    const selectedVolumeId = volumeInputArray[0].volumeId;
    const colorTransferFunction =
      this._getOrCreateColorTransferFunction(selectedVolumeId);
 
    if (!this.initialTransferFunctionNodes) {
      this.initialTransferFunctionNodes = getTransferFunctionNodes(
        colorTransferFunction
      );
    }
  }
 
  private _getApplicableVolumeActor(volumeId?: string) {
    if (volumeId !== undefined && !this.getActor(volumeId)) {
      return;
    }
 
    const actorEntries = this.getActors();
 
    if (!actorEntries.length) {
      return;
    }
 
    let volumeActor;
 
    if (volumeId) {
      volumeActor = this.getActor(volumeId)?.actor as vtkVolume;
    }
 
    // // set it for the first volume (if there are more than one - fusion)
    if (!volumeActor) {
      volumeActor = actorEntries[0].actor as vtkVolume;
      volumeId = actorEntries[0].uid;
    }
 
    return { volumeActor, volumeId };
  }
 
  private async _isValidVolumeInputArray(
    volumeInputArray: Array<IVolumeInput>,
    FrameOfReferenceUID: string
  ): Promise<boolean> {
    const numVolumes = volumeInputArray.length;
 
    // Check all other volumes exist and have the same FrameOfReference
    for (let i = 1; i < numVolumes; i++) {
      const volumeInput = volumeInputArray[i];
 
      const imageVolume = await loadVolume(volumeInput.volumeId);
 
      if (!imageVolume) {
        throw new Error(
          `imageVolume with id: ${imageVolume.volumeId} does not exist`
        );
      }
 
      if (FrameOfReferenceUID !== imageVolume.metadata.FrameOfReferenceUID) {
        throw new Error(
          `Volumes being added to viewport ${this.id} do not share the same FrameOfReferenceUID. This is not yet supported`
        );
      }
    }
 
    return true;
  }
 
  /**
   * Gets the rotation resulting from the value set in setRotation AND taking into
   * account any flips that occurred subsequently from the camera provided or the viewport.
   *
   * @returns the rotation resulting from the value set in setRotation AND taking into
   * account any flips that occurred subsequently.
   */
  public getRotation = (): number => {
    const {
      viewUp: currentViewUp,
      viewPlaneNormal,
      flipVertical,
    } = this.getCamera();
 
    // The initial view up vector without any rotation, but incorporating vertical flip.
    const initialViewUp = flipVertical
      ? vec3.negate([0, 0, 0], this.initialViewUp)
      : this.initialViewUp;
 
    Iif (!initialViewUp) {
      return 0;
    }
 
    // The angle between the initial and current view up vectors.
    // TODO: check with VTK about rounding errors here.
    const initialToCurrentViewUpAngle =
      (vec3.angle(initialViewUp, currentViewUp) * 180) / Math.PI;
 
    // Now determine if initialToCurrentViewUpAngle is positive or negative by comparing
    // the direction of the initial/current view up cross product with the current
    // viewPlaneNormal.
 
    const initialToCurrentViewUpCross = vec3.cross(
      [0, 0, 0],
      initialViewUp,
      currentViewUp
    );
 
    // The sign of the dot product of the start/end view up cross product and
    // the viewPlaneNormal indicates a positive or negative rotation respectively.
    const normalDot = vec3.dot(initialToCurrentViewUpCross, viewPlaneNormal);
 
    const value =
      normalDot >= 0
        ? initialToCurrentViewUpAngle
        : (360 - initialToCurrentViewUpAngle) % 360;
 
    return value;
  };
 
  /**
   * gets the visible bounds of the viewport in the world coordinate system
   */
  public getBounds(): number[] {
    const renderer = this.getRenderer();
    const bounds = renderer.computeVisiblePropBounds();
    return bounds;
  }
 
  /**
   * Flip the viewport along the desired axis
   * @param flipDirection - FlipDirection
   */
  public flip(flipDirection: FlipDirection): void {
    super.flip(flipDirection);
  }
 
  public getFrameOfReferenceUID = (): string => {
    return this._FrameOfReferenceUID;
  };
 
  /**
   * Checks if the viewport has a volume actor with the given volumeId
   * @param volumeId - the volumeId to look for
   * @returns Boolean indicating if the volume is present in the viewport
   */
  public hasVolumeId(volumeId: string): boolean {
    // Note: this assumes that the uid of the volume is the same as the volumeId
    // which is not guaranteed to be the case for SEG.
    const actorEntries = this.getActors();
    return actorEntries.some((actorEntry) => {
      return actorEntry.uid === volumeId;
    });
  }
 
  /**
   * Returns the image and its properties that is being shown inside the
   * stack viewport. It returns, the image dimensions, image direction,
   * image scalar data, vtkImageData object, metadata, and scaling (e.g., PET suvbw)
   * Note: since the volume viewport supports fusion, to get the
   * image data for a specific volume, use the optional volumeId
   * argument.
   *
   * @param volumeId - The volumeId of the volume to get the image for.
   * @returns IImageData: {dimensions, direction, scalarData, vtkImageData, metadata, scaling}
   */
  public getImageData(volumeId?: string): IImageData | undefined {
    const defaultActor = this.getDefaultActor();
    if (!defaultActor) {
      return;
    }
 
    const { uid: defaultActorUID } = defaultActor;
    volumeId = volumeId ?? defaultActorUID;
 
    const actorEntry = this.getActor(volumeId);
 
    if (!actorIsA(actorEntry, 'vtkVolume')) {
      return;
    }
 
    const actor = actorEntry.actor;
    const volume = cache.getVolume(volumeId);
 
    const vtkImageData = actor.getMapper().getInputData();
    return {
      dimensions: vtkImageData.getDimensions(),
      spacing: vtkImageData.getSpacing(),
      origin: vtkImageData.getOrigin(),
      direction: vtkImageData.getDirection(),
      scalarData: vtkImageData.getPointData().getScalars().isDeleted()
        ? null
        : vtkImageData.getPointData().getScalars().getData(),
      imageData: actor.getMapper().getInputData(),
      metadata: {
        Modality: volume?.metadata?.Modality,
      },
      scaling: volume?.scaling,
      hasPixelSpacing: true,
    };
  }
 
  /**
   * Attaches the volume actors to the viewport.
   *
   * @param volumeActorEntries - The volume actors to add the viewport.
   *
   */
  private _setVolumeActors(volumeActorEntries: Array<ActorEntry>): void {
    // New volume actors implies resetting the inverted flag (i.e. like starting from scratch).
 
    for (let i = 0; i < volumeActorEntries.length; i++) {
      this.viewportProperties.invert = false;
    }
    this.setActors(volumeActorEntries);
  }
 
  /**
   * canvasToWorld Returns the world coordinates of the given `canvasPos`
   * projected onto the plane defined by the `Viewport`'s `vtkCamera`'s focal point
   * and the direction of projection.
   *
   * @param canvasPos - The position in canvas coordinates.
   * @returns The corresponding world coordinates.
   * @public
   */
  public canvasToWorld = (canvasPos: Point2): Point3 => {
    const vtkCamera = this.getVtkActiveCamera() as vtkSlabCameraType;
 
    /**
     * NOTE: this is necessary because we want the coordinate transformation
     * respect to the view plane (plane orthogonal to the camera and passing to
     * the focal point).
     *
     * When vtk.js computes the coordinate transformations, it simply uses the
     * camera matrix (no ray casting).
     *
     * However for the volume viewport the clipping range is set to be
     * (-RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE, RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE).
     * The clipping range is used in the camera method getProjectionMatrix().
     * The projection matrix is used then for viewToWorld/worldToView methods of
     * the renderer. This means that vkt.js will not return the coordinates of
     * the point on the view plane (i.e. the depth coordinate will correspond
     * to the focal point).
     *
     * Therefore the clipping range has to be set to (distance, distance + 0.01),
     * where now distance is the distance between the camera position and focal
     * point. This is done internally, in our camera customization when the flag
     * isPerformingCoordinateTransformation is set to true.
     */
 
    vtkCamera.setIsPerformingCoordinateTransformation?.(true);
 
    const renderer = this.getRenderer();
    const offscreenMultiRenderWindow =
      this.getRenderingEngine().offscreenMultiRenderWindow;
    const openGLRenderWindow =
      offscreenMultiRenderWindow.getOpenGLRenderWindow();
    const size = openGLRenderWindow.getSize();
    const devicePixelRatio = window.devicePixelRatio || 1;
    const canvasPosWithDPR = [
      canvasPos[0] * devicePixelRatio,
      canvasPos[1] * devicePixelRatio,
    ];
    const displayCoord = [
      canvasPosWithDPR[0] + this.sx,
      canvasPosWithDPR[1] + this.sy,
    ];
 
    // The y axis display coordinates are inverted with respect to canvas coords
    displayCoord[1] = size[1] - displayCoord[1];
 
    const worldCoord = openGLRenderWindow.displayToWorld(
      displayCoord[0],
      displayCoord[1],
      0,
      renderer
    );
 
    vtkCamera.setIsPerformingCoordinateTransformation?.(false);
 
    return [worldCoord[0], worldCoord[1], worldCoord[2]];
  };
 
  /**
   * Returns the canvas coordinates of the given `worldPos`
   * projected onto the `Viewport`'s `canvas`.
   *
   * @param worldPos - The position in world coordinates.
   * @returns The corresponding canvas coordinates.
   * @public
   */
  public worldToCanvas = (worldPos: Point3): Point2 => {
    const vtkCamera = this.getVtkActiveCamera() as vtkSlabCameraType;
 
    /**
     * NOTE: this is necessary because we want the coordinate trasformation
     * respect to the view plane (plane orthogonal to the camera and passing to
     * the focal point).
     *
     * When vtk.js computes the coordinate transformations, it simply uses the
     * camera matrix (no ray casting).
     *
     * However for the volume viewport the clipping range is set to be
     * (-RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE, RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE).
     * The clipping range is used in the camera method getProjectionMatrix().
     * The projection matrix is used then for viewToWorld/worldToView methods of
     * the renderer. This means that vkt.js will not return the coordinates of
     * the point on the view plane (i.e. the depth coordinate will corresponded
     * to the focal point).
     *
     * Therefore the clipping range has to be set to (distance, distance + 0.01),
     * where now distance is the distance between the camera position and focal
     * point. This is done internally, in our camera customization when the flag
     * isPerformingCoordinateTransformation is set to true.
     */
 
    vtkCamera.setIsPerformingCoordinateTransformation?.(true);
 
    const renderer = this.getRenderer();
    const offscreenMultiRenderWindow =
      this.getRenderingEngine().offscreenMultiRenderWindow;
    const openGLRenderWindow =
      offscreenMultiRenderWindow.getOpenGLRenderWindow();
    const size = openGLRenderWindow.getSize();
    const displayCoord = openGLRenderWindow.worldToDisplay(
      ...worldPos,
      renderer
    );
 
    // The y axis display coordinates are inverted with respect to canvas coords
    displayCoord[1] = size[1] - displayCoord[1];
 
    const canvasCoord = <Point2>[
      displayCoord[0] - this.sx,
      displayCoord[1] - this.sy,
    ];
 
    const devicePixelRatio = window.devicePixelRatio || 1;
    const canvasCoordWithDPR = <Point2>[
      canvasCoord[0] / devicePixelRatio,
      canvasCoord[1] / devicePixelRatio,
    ];
 
    vtkCamera.setIsPerformingCoordinateTransformation?.(false);
 
    return canvasCoordWithDPR;
  };
 
  /*
   * Checking if the imageURI is in the volumes that are being
   * rendered by the viewport. imageURI is the imageId without the schema
   * for instance for the imageId of wadors:http://..., the http://... is the imageURI.
   * Why we don't check the imageId is because the same image can be shown in
   * another viewport (StackViewport) with a different schema
   *
   * @param imageURI - The imageURI to check
   * @returns True if the imageURI is in the volumes that are being rendered by the viewport
   */
  public hasImageURI = (imageURI: string): boolean => {
    const volumeActors = this.getActors().filter((actorEntry) =>
      actorIsA(actorEntry, 'vtkVolume')
    );
 
    return volumeActors.some(({ uid }) => {
      const volume = cache.getVolume(uid);
 
      if (!volume || !volume.imageIds) {
        return false;
      }
 
      const volumeImageURIs = volume.imageIds.map(imageIdToURI);
 
      return volumeImageURIs.includes(imageURI);
    });
  };
 
  protected _getOrientationVectors(
    orientation: OrientationAxis | OrientationVectors
  ): OrientationVectors {
    if (typeof orientation === 'object') {
      if (orientation.viewPlaneNormal && orientation.viewUp) {
        return orientation;
      } else E{
        throw new Error(
          'Invalid orientation object. It must contain viewPlaneNormal and viewUp'
        );
      }
    } else if (
      typeof orientation === 'string' &&
      MPR_CAMERA_VALUES[orientation]
    ) {
      this.viewportProperties.orientation = orientation;
      return MPR_CAMERA_VALUES[orientation];
    } else E{
      throw new Error(
        `Invalid orientation: ${orientation}. Valid orientations are: ${Object.keys(
          MPR_CAMERA_VALUES
        ).join(', ')}`
      );
    }
  }
  /**
   * Gets the largest slab thickness from all actors in the viewport.
   *
   * @returns slabThickness - The slab thickness.
   */
  public getSlabThickness(): number {
    const actors = this.getActors();
    let slabThickness = RENDERING_DEFAULTS.MINIMUM_SLAB_THICKNESS;
    actors.forEach((actor) => {
      Iif (actor.slabThickness > slabThickness) {
        slabThickness = actor.slabThickness;
      }
    });
 
    return slabThickness;
  }
  /**
   * Given a point in world coordinates, return the intensity at that point
   * @param point - The point in world coordinates to get the intensity
   * from.
   * @returns The intensity value of the voxel at the given point.
   */
  public getIntensityFromWorld(point: Point3): number {
    const actorEntry = this.getDefaultActor();
    if (!actorIsA(actorEntry, 'vtkVolume')) {
      return;
    }
 
    const { actor, uid } = actorEntry;
    const imageData = actor.getMapper().getInputData();
 
    const volume = cache.getVolume(uid);
    const { dimensions } = volume;
 
    const index = transformWorldToIndex(imageData, point);
 
    const voxelIndex =
      index[2] * dimensions[0] * dimensions[1] +
      index[1] * dimensions[0] +
      index[0];
 
    return volume.getScalarData()[voxelIndex];
  }
 
  /**
   * Returns the list of image Ids for the current viewport
   *
   * @param volumeId - volumeId
   * @returns list of strings for image Ids
   */
  public getImageIds = (volumeId?: string): Array<string> => {
    const applicableVolumeActorInfo = this._getApplicableVolumeActor(volumeId);
 
    if (!applicableVolumeActorInfo) {
      throw new Error(`No actor found for the given volumeId: ${volumeId}`);
    }
 
    const volumeIdToUse = applicableVolumeActorInfo.volumeId;
 
    const imageVolume = cache.getVolume(volumeIdToUse);
    if (!imageVolume) {
      throw new Error(
        `imageVolume with id: ${volumeIdToUse} does not exist in cache`
      );
    }
 
    return imageVolume.imageIds;
  };
 
  abstract getCurrentImageId(): string;
 
  /** Gets the volumeId to use for references */
  protected getVolumeId(specifier: ViewReferenceSpecifier) {
    Eif (!specifier?.volumeId) {
      const actorEntries = this.getActors();
      Iif (!actorEntries) {
        return;
      }
      // find the first image actor of instance type vtkVolume
      return actorEntries.find(
        (actorEntry) => actorEntry.actor.getClassName() === 'vtkVolume'
      )?.uid;
    }
    return specifier.volumeId;
  }
 
  public getReferenceId(specifier: ViewReferenceSpecifier = {}): string {
    let { volumeId, sliceIndex: sliceIndex } = specifier;
    Eif (!volumeId) {
      const actorEntries = this.getActors();
      Iif (!actorEntries) {
        return;
      }
      // find the first image actor of instance type vtkVolume
      volumeId = actorEntries.find(
        (actorEntry) => actorEntry.actor.getClassName() === 'vtkVolume'
      )?.uid;
    }
 
    sliceIndex ??= this.getCurrentImageIdIndex();
    const { viewPlaneNormal, focalPoint } = this.getCamera();
    const querySeparator = volumeId.indexOf('?') > -1 ? '&' : '?';
    return `volumeId:${volumeId}${querySeparator}sliceIndex=${sliceIndex}&viewPlaneNormal=${viewPlaneNormal.join(
      ','
    )}&focalPoint=${focalPoint.join(',')}`;
  }
 
  abstract setBlendMode(
    blendMode: BlendModes,
    filterActorUIDs?: Array<string>,
    immediate?: boolean
  ): void;
 
  abstract setSlabThickness(
    slabThickness: number,
    filterActorUIDs?: Array<string>
  ): void;
 
  abstract resetProperties(volumeId?: string): void;
}
 
export default BaseVolumeViewport;