All files / packages/tools/src/tools/displayTools/Labelmap labelmapDisplay.ts

70.89% Statements 95/134
59.49% Branches 47/79
90% Functions 9/10
70.45% Lines 93/132

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                                                          1x 1x     17x 17x 17x 17x           1x                             17x       17x         17x                                             31x 31x                                                                                 31x   31x   31x         31x   31x   31x                                                         31x       31x 31x       31x   31x   31x       31x       31x   22x             31x                                                       31x       31x     31x   31x                                                     31x     31x       31x 31x 31x         31x                 31x 7905x 7905x     7905x     7905x               7905x                 7905x 5610x               7905x 5610x 5610x       5610x 5610x             31x   31x   31x   31x 31x 31x     31x   31x               31x   31x   7874x   7874x         7874x           31x         31x 31x                 7936x   7936x           7936x     7936x       7936x       7936x   7936x       7936x                                                         7905x 7905x   7905x 5610x                 5610x                         2295x     2295x         2295x               2295x                 2295x                   17x   17x       17x   17x 22x 22x       22x                       22x                                    
import vtkPiecewiseFunction from '@kitware/vtk.js/Common/DataModel/PiecewiseFunction';
import vtkColorTransferFunction from '@kitware/vtk.js/Rendering/Core/ColorTransferFunction';
 
import {
  cache,
  getEnabledElementByIds,
  StackViewport,
  Types,
  VolumeViewport,
} from '@cornerstonejs/core';
 
import Representations from '../../../enums/SegmentationRepresentations';
import * as SegmentationState from '../../../stateManagement/segmentation/segmentationState';
import { getToolGroup } from '../../../store/ToolGroupManager';
import type {
  LabelmapConfig,
  LabelmapRenderingConfig,
  LabelmapSegmentationData,
} from '../../../types/LabelmapTypes';
import {
  SegmentationRepresentationConfig,
  ToolGroupSpecificRepresentation,
} from '../../../types/SegmentationStateTypes';
 
import addLabelmapToElement from './addLabelmapToElement';
import removeLabelmapFromElement from './removeLabelmapFromElement';
import { isVolumeSegmentation } from '../../segmentation/strategies/utils/stackVolumeCheck';
import { polySeg } from '../../../stateManagement/segmentation';
 
const MAX_NUMBER_COLORS = 255;
const labelMapConfigCache = new Map();
 
function getRepresentationRenderingConfig() {
  const cfun = vtkColorTransferFunction.newInstance();
  const ofun = vtkPiecewiseFunction.newInstance();
  ofun.addPoint(0, 0);
  return {
    ofun,
    cfun,
  };
}
 
let polySegConversionInProgress = false;
 
/**
 * For each viewport, and for each segmentation, set the segmentation for the viewport's enabled element
 * Initializes the global and viewport specific state for the segmentation in the
 * SegmentationStateManager.
 * @param toolGroup - the tool group that contains the viewports
 * @param segmentationRepresentationUID - The uid of the segmentation representation
 * @param renderImmediate - If true, there will be a render call after the labelmap is removed
 */
function removeSegmentationRepresentation(
  toolGroupId: string,
  segmentationRepresentationUID: string,
  renderImmediate = false
): void {
  _removeLabelmapFromToolGroupViewports(
    toolGroupId,
    segmentationRepresentationUID
  );
  SegmentationState.removeSegmentationRepresentation(
    toolGroupId,
    segmentationRepresentationUID
  );
 
  Iif (renderImmediate) {
    const viewportsInfo = getToolGroup(toolGroupId).getViewportsInfo();
    viewportsInfo.forEach(({ viewportId, renderingEngineId }) => {
      const enabledElement = getEnabledElementByIds(
        viewportId,
        renderingEngineId
      );
      enabledElement.viewport.render();
    });
  }
}
 
/**
 * Checks if a segmentation data have the same frameOfReference as the series
 * displayed in a given viewport
 * @param viewport
 * @param referencedVolumeId volume id of the segmentation reference series
 * @returns
 */
function isSameFrameOfReference(viewport, referencedVolumeId) {
  // if the referencedVolumeId is not defined, we acted as before to not break
  // applications as referencedVolumeId is inserted in this change
  // Can modify that in the future commits
  Eif (!referencedVolumeId) {
    return true;
  }
  const defaultActor = viewport.getDefaultActor();
  if (!defaultActor) {
    return false;
  }
  const { uid: defaultActorUID } = defaultActor;
  const volume = cache.getVolume(defaultActorUID);
 
  if (volume) {
    const referencedVolume = cache.getVolume(referencedVolumeId);
    if (
      referencedVolume &&
      volume.metadata.FrameOfReferenceUID ===
        referencedVolume.metadata.FrameOfReferenceUID
    ) {
      return true;
    }
  }
  return false;
}
 
/**
 * It takes the enabled element, the segmentation Id, and the configuration, and
 * it sets the segmentation for the enabled element as a labelmap
 * @param enabledElement - The cornerstone enabled element
 * @param segmentationId - The id of the segmentation to be rendered.
 * @param configuration - The configuration object for the labelmap.
 */
async function render(
  viewport: Types.IVolumeViewport | Types.IStackViewport,
  representation: ToolGroupSpecificRepresentation,
  toolGroupConfig: SegmentationRepresentationConfig
): Promise<void> {
  const {
    colorLUTIndex,
    active,
    segmentationId,
    segmentationRepresentationUID,
    segmentsHidden,
    config: renderingConfig,
  } = representation;
 
  const segmentation = SegmentationState.getSegmentation(segmentationId);
 
  Iif (!segmentation) {
    console.warn('No segmentation found for segmentationId: ', segmentationId);
    return;
  }
 
  let labelmapData = segmentation.representationData[Representations.Labelmap];
 
  let actorEntry = viewport.getActor(segmentationRepresentationUID);
 
  Iif (
    !labelmapData &&
    polySeg.canComputeRequestedRepresentation(segmentationRepresentationUID) &&
    !polySegConversionInProgress
  ) {
    // meaning the requested segmentation representationUID does not have
    // labelmap data, BUT we might be able to request a conversion from
    // another representation to labelmap
    // we need to check if we can request polySEG to convert the other
    // underlying representations to Surface
    polySegConversionInProgress = true;
 
    labelmapData = await polySeg.computeAndAddLabelmapRepresentation(
      segmentationId,
      {
        segmentationRepresentationUID,
        viewport,
      }
    );
 
    if (!labelmapData) {
      throw new Error(
        `No labelmap data found for segmentationId ${segmentationId}.`
      );
    }
 
    polySegConversionInProgress = false;
  }
 
  Iif (!labelmapData) {
    return;
  }
 
  if (isVolumeSegmentation(labelmapData, viewport)) {
    Iif (viewport instanceof StackViewport) {
      return;
    }
 
    const { volumeId: labelmapUID } = labelmapData;
 
    const labelmap = cache.getVolume(labelmapUID);
 
    Iif (!labelmap) {
      throw new Error(`No Labelmap found for volumeId: ${labelmapUID}`);
    }
 
    Iif (!isSameFrameOfReference(viewport, labelmapData?.referencedVolumeId)) {
      return;
    }
 
    if (!actorEntry) {
      // only add the labelmap to ToolGroup viewports if it is not already added
      await _addLabelmapToViewport(
        viewport,
        labelmapData,
        segmentationRepresentationUID
      );
    }
 
    actorEntry = viewport.getActor(segmentationRepresentationUID);
  } else E{
    if (viewport instanceof VolumeViewport) {
      return;
    }
 
    // stack segmentation
    const imageId = viewport.getCurrentImageId();
    const { imageIdReferenceMap } = labelmapData;
 
    // if the stack labelmap is not built for the current imageId that is
    // rendered at the viewport then return
    if (!imageIdReferenceMap.has(imageId)) {
      return;
    }
 
    if (!actorEntry) {
      // only add the labelmap to ToolGroup viewports if it is not already added
      await _addLabelmapToViewport(
        viewport,
        labelmapData,
        segmentationRepresentationUID
      );
    }
 
    actorEntry = viewport.getActor(segmentationRepresentationUID);
  }
 
  Iif (!actorEntry) {
    return;
  }
 
  const { cfun, ofun } = renderingConfig as LabelmapRenderingConfig;
 
  const renderInactiveSegmentations =
    toolGroupConfig.renderInactiveSegmentations;
 
  _setLabelmapColorAndOpacity(
    viewport.id,
    actorEntry,
    cfun,
    ofun,
    colorLUTIndex,
    toolGroupConfig.representations[Representations.Labelmap],
    representation,
    active,
    renderInactiveSegmentations,
    segmentsHidden
  );
}
 
function _setLabelmapColorAndOpacity(
  viewportId: string,
  actorEntry: Types.ActorEntry,
  cfun: vtkColorTransferFunction,
  ofun: vtkPiecewiseFunction,
  colorLUTIndex: number,
  toolGroupLabelmapConfig: LabelmapConfig,
  segmentationRepresentation: ToolGroupSpecificRepresentation,
  isActiveLabelmap: boolean,
  renderInactiveSegmentations: boolean,
  segmentsHidden: Set<number>
): void {
  const { segmentSpecificConfig, segmentationRepresentationSpecificConfig } =
    segmentationRepresentation;
 
  const segmentationRepresentationLabelmapConfig =
    segmentationRepresentationSpecificConfig[Representations.Labelmap];
 
  // Note: MAX_NUMBER_COLORS = 256 is needed because the current method to generate
  // the default color table uses RGB.
  const colorLUT = SegmentationState.getColorLUT(colorLUTIndex);
  const numColors = Math.min(256, colorLUT.length);
  const { uid: actorUID } = actorEntry;
 
  // Note: right now outlineWidth and renderOutline are not configurable
  // at the segment level, so we don't need to check for segment specific
  // configuration in the loop, Todo: make them configurable at the segment level
  const { outlineWidth, renderOutline, outlineOpacity } = _getLabelmapConfig(
    toolGroupLabelmapConfig,
    segmentationRepresentationLabelmapConfig,
    isActiveLabelmap
  );
 
  // Todo: the below loop probably can be optimized so that we don't hit it
  // unless a config has changed. Right now we get into the following loop
  // even for brush drawing which does not makes sense
  for (let i = 0; i < numColors; i++) {
    const segmentIndex = i;
    const segmentColor = colorLUT[segmentIndex];
 
    const segmentSpecificLabelmapConfig =
      segmentSpecificConfig[segmentIndex]?.[Representations.Labelmap];
 
    const { fillAlpha, outlineWidth, renderFill, renderOutline } =
      _getLabelmapConfig(
        toolGroupLabelmapConfig,
        segmentationRepresentationLabelmapConfig,
        isActiveLabelmap,
        segmentSpecificLabelmapConfig
      );
 
    const { forceOpacityUpdate, forceColorUpdate } =
      _needsTransferFunctionUpdate(viewportId, actorUID, segmentIndex, {
        fillAlpha,
        renderFill,
        renderOutline,
        segmentColor,
        outlineWidth,
        segmentsHidden,
      });
 
    if (forceColorUpdate) {
      cfun.addRGBPoint(
        segmentIndex,
        segmentColor[0] / MAX_NUMBER_COLORS,
        segmentColor[1] / MAX_NUMBER_COLORS,
        segmentColor[2] / MAX_NUMBER_COLORS
      );
    }
 
    if (forceOpacityUpdate) {
      if (renderFill) {
        const segmentOpacity = segmentsHidden.has(segmentIndex)
          ? 0
          : (segmentColor[3] / 255) * fillAlpha;
 
        ofun.removePoint(segmentIndex);
        ofun.addPointLong(segmentIndex, segmentOpacity, 0.5, 1.0);
      } else E{
        ofun.addPointLong(segmentIndex, 0.01, 0.5, 1.0);
      }
    }
  }
 
  const actor = actorEntry.actor as Types.VolumeActor;
 
  actor.getProperty().setRGBTransferFunction(0, cfun);
 
  ofun.setClamping(false);
 
  actor.getProperty().setScalarOpacity(0, ofun);
  actor.getProperty().setInterpolationTypeToNearest();
  actor.getProperty().setUseLabelOutline(renderOutline);
 
  // @ts-ignore - fix type in vtk
  actor.getProperty().setLabelOutlineOpacity(outlineOpacity);
 
  const { activeSegmentIndex } = SegmentationState.getSegmentation(
    segmentationRepresentation.segmentationId
  );
 
  // create an array that contains all the segment indices and for the active
  // segment index, use the activeSegmentOutlineWidthDelta, otherwise use the
  // outlineWidth
  // Pre-allocate the array with the required size to avoid dynamic resizing.
  const outlineWidths = new Array(numColors - 1);
 
  for (let i = 1; i < numColors; i++) {
    // Start from 1 to skip the background segment index.
    const isHidden = segmentsHidden.has(i);
 
    Iif (isHidden) {
      outlineWidths[i - 1] = 0;
      continue;
    }
 
    outlineWidths[i - 1] =
      i === activeSegmentIndex
        ? outlineWidth + toolGroupLabelmapConfig.activeSegmentOutlineWidthDelta
        : outlineWidth;
  }
 
  actor.getProperty().setLabelOutlineThickness(outlineWidths);
 
  // Set visibility based on whether actor visibility is specifically asked
  // to be turned on/off (on by default) AND whether is is in active but
  // we are rendering inactive labelmap
  const visible = isActiveLabelmap || renderInactiveSegmentations;
  actor.setVisibility(visible);
}
 
function _getLabelmapConfig(
  toolGroupLabelmapConfig: LabelmapConfig,
  segmentationRepresentationLabelmapConfig: LabelmapConfig,
  isActiveLabelmap: boolean,
  segmentsLabelmapConfig?: LabelmapConfig
) {
  const segmentLabelmapConfig = segmentsLabelmapConfig || {};
 
  const configToUse = {
    ...toolGroupLabelmapConfig,
    ...segmentationRepresentationLabelmapConfig,
    ...segmentLabelmapConfig,
  };
 
  const fillAlpha = isActiveLabelmap
    ? configToUse.fillAlpha
    : configToUse.fillAlphaInactive;
  const outlineWidth = isActiveLabelmap
    ? configToUse.outlineWidthActive
    : configToUse.outlineWidthInactive;
 
  const renderFill = isActiveLabelmap
    ? configToUse.renderFill
    : configToUse.renderFillInactive;
 
  const renderOutline = configToUse.renderOutline;
 
  const outlineOpacity = isActiveLabelmap
    ? configToUse.outlineOpacity
    : configToUse.outlineOpacityInactive;
 
  return {
    fillAlpha,
    outlineWidth,
    renderFill,
    renderOutline,
    outlineOpacity,
  };
}
 
function _needsTransferFunctionUpdate(
  viewportId: string,
  actorUID: string,
  segmentIndex: number,
  {
    fillAlpha,
    renderFill,
    renderOutline,
    segmentColor,
    outlineWidth,
    segmentsHidden,
  }: {
    fillAlpha: number;
    renderFill: boolean;
    renderOutline: boolean;
    outlineWidth: number;
    segmentColor: number[];
    segmentsHidden: Set<number>;
  }
) {
  const cacheUID = `${viewportId}-${actorUID}-${segmentIndex}`;
  const oldConfig = labelMapConfigCache.get(cacheUID);
 
  if (!oldConfig) {
    labelMapConfigCache.set(cacheUID, {
      fillAlpha,
      renderFill,
      renderOutline,
      outlineWidth,
      segmentColor: segmentColor.slice(), // Create a copy
      segmentsHidden: new Set(segmentsHidden), // Create a copy
    });
 
    return {
      forceOpacityUpdate: true,
      forceColorUpdate: true,
    };
  }
 
  const {
    fillAlpha: oldFillAlpha,
    renderFill: oldRenderFill,
    renderOutline: oldRenderOutline,
    outlineWidth: oldOutlineWidth,
    segmentColor: oldSegmentColor,
    segmentsHidden: oldSegmentsHidden,
  } = oldConfig;
 
  const forceColorUpdate =
    oldSegmentColor[0] !== segmentColor[0] ||
    oldSegmentColor[1] !== segmentColor[1] ||
    oldSegmentColor[2] !== segmentColor[2];
 
  const forceOpacityUpdate =
    oldSegmentColor[3] !== segmentColor[3] ||
    oldFillAlpha !== fillAlpha ||
    oldRenderFill !== renderFill ||
    oldRenderOutline !== renderOutline ||
    oldOutlineWidth !== outlineWidth ||
    oldSegmentsHidden.has(segmentIndex) !== segmentsHidden.has(segmentIndex);
 
  // update the cache
  labelMapConfigCache.set(cacheUID, {
    fillAlpha,
    renderFill,
    renderOutline,
    outlineWidth,
    segmentColor: segmentColor.slice(), // Create a copy
    segmentsHidden: new Set(segmentsHidden), // Create a copy
  });
 
  return {
    forceOpacityUpdate,
    forceColorUpdate,
  };
}
 
function _removeLabelmapFromToolGroupViewports(
  toolGroupId: string,
  segmentationRepresentationUID: string
): void {
  const toolGroup = getToolGroup(toolGroupId);
 
  Iif (toolGroup === undefined) {
    throw new Error(`ToolGroup with ToolGroupId ${toolGroupId} does not exist`);
  }
 
  const { viewportsInfo } = toolGroup;
 
  for (const viewportInfo of viewportsInfo) {
    const { viewportId, renderingEngineId } = viewportInfo;
    const enabledElement = getEnabledElementByIds(
      viewportId,
      renderingEngineId
    );
    removeLabelmapFromElement(
      enabledElement.viewport.element,
      segmentationRepresentationUID
    );
  }
}
 
async function _addLabelmapToViewport(
  viewport: Types.IVolumeViewport | Types.IStackViewport,
  labelmapData: LabelmapSegmentationData,
  segmentationRepresentationUID
): Promise<void> {
  await addLabelmapToElement(
    viewport.element,
    labelmapData,
    segmentationRepresentationUID
  );
}
 
export default {
  getRepresentationRenderingConfig,
  render,
  removeSegmentationRepresentation,
};
 
export {
  getRepresentationRenderingConfig,
  render,
  removeSegmentationRepresentation,
};