All files / tools/src/stateManagement/segmentation/labelmapModel labelmapImageReferenceResolver.ts

48.36% Statements 89/184
35.45% Branches 39/110
57.69% Functions 15/26
48.63% Lines 89/183

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                                                128x       128x       128x               128x           128x                                                     2466x 2466x 2466x 22x 22x   2466x       1008x     1008x       1008x 1008x   1008x 970x     38x 38x               1008x                                                             970x 970x       970x 22x     970x 970x       970x 970x 970x       970x 970x 970x 947x     23x           23x 23x     23x                       970x     970x     970x           970x                 947x                   23x 23x 22x 22x   23x             2443x   2443x       2443x 2443x   2443x             2443x     2443x 2443x       2443x   2443x 2443x 2443x   2443x   2443x   2443x         2443x 2443x 2443x                                     2443x 2443x       2443x   2443x       2443x 2443x   2443x         2443x       2443x                                                                                                                                                                     23x   23x 23x 294x         294x 23x 23x     23x               23x   23x                                                                                                                                                                         23x   23x 23x 23x                 2466x          
import {
  cache,
  getEnabledElementByViewportId,
  type Types,
} from '@cornerstonejs/core';
import type {
  RepresentationsData,
  Segmentation,
} from '../../../types/SegmentationStateTypes';
import type {
  LabelmapSegmentationDataStack,
  LabelmapSegmentationDataVolume,
} from '../../../types/LabelmapTypes';
import getViewportLabelmapRenderMode from '../helpers/getViewportLabelmapRenderMode';
import { ensureLabelmapState } from './normalizeLabelmapSegmentationData';
import { getLabelmaps } from './labelmapLayerStore';
import { getLabelmapForSegment } from './labelmapSegmentBindings';
import { getReferencedImageIdToCurrentImageIdMap } from './labelmapLegacyAdapter';
import { getLabelmapImageIdsForReferencedImageId } from './labelmapImageIdMapping';
 
type GetSegmentation = (segmentationId: string) => Segmentation | undefined;
 
class LabelmapImageReferenceResolver {
  private readonly getSegmentation: GetSegmentation;
  private readonly stackLabelmapImageIdReferenceMap = new Map<
    string,
    Map<string, string>
  >();
  private readonly labelmapImageIdReferenceMap = new Map<string, string[]>();
  // Index mapping each segmentationId to the set of keys it owns in
  // labelmapImageIdReferenceMap, so removeSegmentation can purge entries in
  // O(k) without scanning the whole map.
  private readonly keysBySegmentationId = new Map<string, Set<string>>();
  // Memo of already-performed isReferenceViewable scans. Each scan resolves
  // every labelmap imageId against the viewport's current image via full
  // metadata resolution (image plane, slice basis), which costs tens of ms
  // for multi-layer labelmaps - and the segmentation data-modified pipeline
  // re-enters this on EVERY brush/erase drag event. Scan keys include the
  // viewport id and a signature of the labelmap imageId set, so adding/removing
  // a layer (which changes the set) naturally forces a fresh scan.
  private readonly completedScanResultsBySegmentationId = new Map<
    string,
    Map<string, string | undefined>
  >();
 
  constructor(getSegmentation: GetSegmentation) {
    this.getSegmentation = getSegmentation;
  }
 
  reset(): void {
    this.stackLabelmapImageIdReferenceMap.clear();
    this.labelmapImageIdReferenceMap.clear();
    this.keysBySegmentationId.clear();
    this.completedScanResultsBySegmentationId.clear();
  }
 
  removeSegmentation(segmentationId: string): void {
    this.stackLabelmapImageIdReferenceMap.delete(segmentationId);
    this.completedScanResultsBySegmentationId.delete(segmentationId);
    const keys = this.keysBySegmentationId.get(segmentationId);
    if (keys) {
      for (const key of keys) {
        this.labelmapImageIdReferenceMap.delete(key);
      }
      this.keysBySegmentationId.delete(segmentationId);
    }
  }
 
  private setLabelmapImageIds(
    segmentationId: string,
    key: string,
    labelmapImageIds: string[]
  ): void {
    this.labelmapImageIdReferenceMap.set(key, labelmapImageIds);
    let keys = this.keysBySegmentationId.get(segmentationId);
    if (!keys) {
      keys = new Set();
      this.keysBySegmentationId.set(segmentationId, keys);
    }
    keys.add(key);
  }
 
  getLabelmapImageIds(representationData: RepresentationsData) {
    const labelmapData = representationData.Labelmap;
    let labelmapImageIds;
 
    Iif (!labelmapData) {
      return;
    }
 
    Eif (labelmapData?.labelmaps) {
      const imageIds = Object.values(labelmapData.labelmaps).flatMap(
        (layer) => {
          if (layer.imageIds?.length) {
            return layer.imageIds;
          }
 
          Eif (layer.volumeId) {
            return (cache.getVolume(layer.volumeId) as Types.IImageVolume)
              ?.imageIds;
          }
 
          return [];
        }
      );
 
      return Array.from(new Set(imageIds.filter(Boolean)));
    }
 
    if ((labelmapData as LabelmapSegmentationDataStack).imageIds) {
      labelmapImageIds = (labelmapData as LabelmapSegmentationDataStack)
        .imageIds;
    } else if ((labelmapData as LabelmapSegmentationDataVolume).volumeId) {
      const volumeId = (labelmapData as LabelmapSegmentationDataVolume)
        .volumeId;
 
      const volume = cache.getVolume(volumeId) as Types.IImageVolume;
      labelmapImageIds = volume.imageIds;
    }
 
    return labelmapImageIds;
  }
 
  getLabelmapImageIdsForImageId(imageId: string, segmentationId: string) {
    const segmentation = this.getSegmentation(segmentationId);
    if (!segmentation?.representationData?.Labelmap) {
      return;
    }
 
    ensureLabelmapState(segmentation);
    return getReferencedImageIdToCurrentImageIdMap(segmentation).get(imageId);
  }
 
  updateLabelmapSegmentationImageReferences(
    viewportId: string,
    segmentationId: string
  ): string | undefined {
    const segmentation = this.getSegmentation(segmentationId);
    Iif (!segmentation) {
      return;
    }
 
    if (!this.stackLabelmapImageIdReferenceMap.has(segmentationId)) {
      this.stackLabelmapImageIdReferenceMap.set(segmentationId, new Map());
    }
 
    const { representationData } = segmentation;
    Iif (!representationData.Labelmap) {
      return;
    }
 
    const labelmapImageIds = this.getLabelmapImageIds(representationData);
    const enabledElement = getEnabledElementByViewportId(viewportId);
    Iif (!enabledElement || !labelmapImageIds?.length) {
      return;
    }
 
    const viewport = enabledElement.viewport as Types.IStackViewport;
    const scanKey = this.generateScanKey('current', viewport, labelmapImageIds);
    if (scanKey && this.hasCompletedScan(segmentationId, scanKey)) {
      return this.getCompletedScanResult(segmentationId, scanKey);
    }
 
    const result = this.updateLabelmapSegmentationReferences(
      segmentationId,
      viewport,
      labelmapImageIds
    );
 
    Eif (scanKey) {
      this.markCompletedScan(segmentationId, scanKey, result);
    }
 
    return result;
  }
 
  /** Signature of one isReferenceViewable scan: the viewport's current image
   *  plus a cheap fingerprint of the labelmap imageId set (count + endpoints),
   *  so layer additions/removals invalidate naturally. */
  private generateScanKey(
    kind: 'current' | 'all',
    viewport: Types.IStackViewport,
    labelmapImageIds: string[]
  ): string | undefined {
    const referenceImageId =
      typeof viewport.getCurrentImageId === 'function'
        ? viewport.getCurrentImageId()
        : undefined;
    Iif (!referenceImageId) {
      return;
    }
    return `${kind}|${viewport.id}|${referenceImageId}|${
      labelmapImageIds.length
    }|${labelmapImageIds[0]}|${labelmapImageIds[labelmapImageIds.length - 1]}`;
  }
 
  private hasCompletedScan(segmentationId: string, scanKey: string): boolean {
    return !!this.completedScanResultsBySegmentationId
      .get(segmentationId)
      ?.has(scanKey);
  }
 
  private getCompletedScanResult(
    segmentationId: string,
    scanKey: string
  ): string | undefined {
    return this.completedScanResultsBySegmentationId
      .get(segmentationId)
      ?.get(scanKey);
  }
 
  private markCompletedScan(
    segmentationId: string,
    scanKey: string,
    result?: string
  ): void {
    let results = this.completedScanResultsBySegmentationId.get(segmentationId);
    if (!results) {
      results = new Map();
      this.completedScanResultsBySegmentationId.set(segmentationId, results);
    }
    results.set(scanKey, result);
  }
 
  getCurrentLabelmapImageIdsForViewport(
    viewportId: string,
    segmentationId: string
  ): string[] | undefined {
    const enabledElement = getEnabledElementByViewportId(viewportId);
 
    Iif (!enabledElement) {
      return;
    }
 
    const { viewport } = enabledElement;
    const viewportRenderMode = getViewportLabelmapRenderMode(viewport);
 
    Iif (
      viewportRenderMode !== 'image' ||
      typeof (viewport as Types.IStackViewport).getCurrentImageId !== 'function'
    ) {
      return;
    }
 
    const referenceImageId = (
      viewport as Types.IStackViewport
    ).getCurrentImageId();
    const segmentation = this.getSegmentation(segmentationId);
    Iif (!segmentation) {
      return;
    }
 
    ensureLabelmapState(segmentation);
 
    const viewportImageIds = (viewport as Types.IStackViewport).getImageIds();
    const currentIndex = viewportImageIds.indexOf(referenceImageId);
    const labelmapImageIds: string[] = [];
 
    getLabelmaps(segmentation).forEach((layer) => {
      const referencedLabelmapImageIds =
        getLabelmapImageIdsForReferencedImageId(layer, referenceImageId);
 
      Iif (referencedLabelmapImageIds.length) {
        labelmapImageIds.push(...referencedLabelmapImageIds);
        return;
      }
 
      Eif (currentIndex !== -1 && layer.imageIds?.[currentIndex]) {
        labelmapImageIds.push(layer.imageIds[currentIndex]);
        return;
      }
 
      layer.imageIds?.some((candidateImageId) => {
        const viewableImageId = (
          viewport as Types.IStackViewport
        ).isReferenceViewable(
          { referencedImageId: candidateImageId },
          { asOverlay: true }
        );
 
        if (viewableImageId) {
          labelmapImageIds.push(candidateImageId);
        }
 
        return !!viewableImageId;
      });
    });
 
    const resolvedImageIds = Array.from(new Set(labelmapImageIds));
    const key = this.generateMapKey({
      segmentationId,
      referenceImageId,
    });
    this.setLabelmapImageIds(segmentationId, key, resolvedImageIds);
 
    Iif (!this.stackLabelmapImageIdReferenceMap.has(segmentationId)) {
      this.stackLabelmapImageIdReferenceMap.set(segmentationId, new Map());
    }
 
    const activeSegmentIndex = Object.keys(segmentation.segments).find(
      (segmentIndex) => segmentation.segments[segmentIndex].active
    );
    const activeImageId = activeSegmentIndex
      ? getLabelmapForSegment(segmentation, Number(activeSegmentIndex))
          ?.imageIds?.[currentIndex]
      : undefined;
 
    this.stackLabelmapImageIdReferenceMap
      .get(segmentationId)
      .set(referenceImageId, activeImageId ?? resolvedImageIds[0]);
 
    return resolvedImageIds;
  }
 
  getCurrentLabelmapImageIdForViewport(
    viewportId: string,
    segmentationId: string
  ): string | undefined {
    const enabledElement = getEnabledElementByViewportId(viewportId);
 
    if (!enabledElement) {
      return;
    }
 
    const { viewport } = enabledElement;
    const viewportRenderMode = getViewportLabelmapRenderMode(viewport);
 
    if (
      viewportRenderMode !== 'image' ||
      typeof (viewport as Types.IStackViewport).getCurrentImageId !== 'function'
    ) {
      return;
    }
 
    const currentImageId = (
      viewport as Types.IStackViewport
    ).getCurrentImageId();
    const currentImageIds = this.getCurrentLabelmapImageIdsForViewport(
      viewportId,
      segmentationId
    );
    if (!currentImageIds?.length) {
      return;
    }
 
    const segmentation = this.getSegmentation(segmentationId);
    const currentIndex = (viewport as Types.IStackViewport)
      .getImageIds()
      .indexOf(currentImageId);
    const activeSegmentIndex = segmentation
      ? Object.keys(segmentation.segments).find(
          (segmentIndex) => segmentation.segments[segmentIndex].active
        )
      : undefined;
    const activeImageId =
      segmentation && activeSegmentIndex
        ? getLabelmapForSegment(segmentation, Number(activeSegmentIndex))
            ?.imageIds?.[currentIndex]
        : undefined;
 
    return activeImageId ?? currentImageIds[0];
  }
 
  getStackSegmentationImageIdsForViewport(
    viewportId: string,
    segmentationId: string
  ): string[] {
    const segmentation = this.getSegmentation(segmentationId);
 
    if (!segmentation) {
      return [];
    }
 
    this.updateAllLabelmapSegmentationImageReferences(
      viewportId,
      segmentationId
    );
    const enabledElement = getEnabledElementByViewportId(viewportId);
    const imageIds = enabledElement?.viewport.getImageIds?.() ?? [];
    const imageIdMap = getReferencedImageIdToCurrentImageIdMap(segmentation);
 
    return imageIds.flatMap((imageId) => imageIdMap.get(imageId) ?? []);
  }
 
  private updateLabelmapSegmentationReferences(
    segmentationId: string,
    viewport: Types.IStackViewport,
    labelmapImageIds: string[],
    updateCallback?: (
      viewport: Types.IStackViewport,
      segmentationId: string,
      labelmapImageIds: string[]
    ) => void
  ): string | undefined {
    const referenceImageId = viewport.getCurrentImageId();
 
    let viewableLabelmapImageIdFound = false;
    for (const labelmapImageId of labelmapImageIds) {
      const viewableImageId = viewport.isReferenceViewable(
        { referencedImageId: labelmapImageId },
        { asOverlay: true }
      );
 
      if (viewableImageId) {
        viewableLabelmapImageIdFound = true;
        this.stackLabelmapImageIdReferenceMap
          .get(segmentationId)
          .set(referenceImageId, labelmapImageId);
        this.updateLabelmapImageIdReferenceMap({
          segmentationId,
          referenceImageId,
          labelmapImageId,
        });
      }
    }
 
    updateCallback?.(viewport, segmentationId, labelmapImageIds);
 
    return viewableLabelmapImageIdFound
      ? this.stackLabelmapImageIdReferenceMap
          .get(segmentationId)
          .get(referenceImageId)
      : undefined;
  }
 
  /**
   * @deprecated Compatibility path for the old stack-labelmap API. New labelmap
   * layers should carry referencedImageIds so callers can use
   * getReferencedImageIdToCurrentImageIdMap without scanning every stack image
   * against every labelmap image.
   */
  private updateAllLabelmapSegmentationImageReferences(
    viewportId: string,
    segmentationId: string
  ): void {
    const segmentation = this.getSegmentation(segmentationId);
    if (!segmentation) {
      return;
    }
 
    if (!this.stackLabelmapImageIdReferenceMap.has(segmentationId)) {
      this.stackLabelmapImageIdReferenceMap.set(segmentationId, new Map());
    }
 
    const { representationData } = segmentation;
    if (!representationData.Labelmap) {
      return;
    }
 
    const labelmapImageIds = this.getLabelmapImageIds(representationData);
    const enabledElement = getEnabledElementByViewportId(viewportId);
    if (!enabledElement || !labelmapImageIds?.length) {
      return;
    }
 
    const stackViewport = enabledElement.viewport as Types.IStackViewport;
 
    const scanKey = this.generateScanKey(
      'all',
      stackViewport,
      labelmapImageIds
    );
    if (scanKey && this.hasCompletedScan(segmentationId, scanKey)) {
      return;
    }
    if (scanKey) {
      this.markCompletedScan(segmentationId, scanKey);
    }
 
    this.updateLabelmapSegmentationReferences(
      segmentationId,
      stackViewport,
      labelmapImageIds,
      (stackViewport, segmentationId, labelmapImageIds) => {
        const imageIds = stackViewport.getImageIds();
        imageIds.forEach((referenceImageId, index) => {
          for (const labelmapImageId of labelmapImageIds) {
            const viewableImageId = stackViewport.isReferenceViewable(
              { referencedImageId: labelmapImageId, sliceIndex: index },
              { asOverlay: true, withNavigation: true }
            );
 
            if (viewableImageId) {
              this.stackLabelmapImageIdReferenceMap
                .get(segmentationId)
                .set(referenceImageId, labelmapImageId);
              this.updateLabelmapImageIdReferenceMap({
                segmentationId,
                referenceImageId,
                labelmapImageId,
              });
            }
          }
        });
      }
    );
  }
 
  private updateLabelmapImageIdReferenceMap({
    segmentationId,
    referenceImageId,
    labelmapImageId,
  }): void {
    const key = this.generateMapKey({ segmentationId, referenceImageId });
 
    Eif (!this.labelmapImageIdReferenceMap.has(key)) {
      this.setLabelmapImageIds(segmentationId, key, [labelmapImageId]);
      return;
    }
 
    const currentValues = this.labelmapImageIdReferenceMap.get(key) ?? [];
    const newValues = Array.from(new Set([...currentValues, labelmapImageId]));
    this.setLabelmapImageIds(segmentationId, key, newValues);
  }
 
  private generateMapKey({ segmentationId, referenceImageId }) {
    return `${segmentationId}-${referenceImageId}`;
  }
}
 
export default LabelmapImageReferenceResolver;