All files / packages/tools/src/tools/segmentation/strategies BrushStrategy.ts

67.56% Statements 50/74
52.94% Branches 18/34
61.11% Functions 11/18
66.66% Lines 48/72

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                            1x                                                                                                                                       1x   1x                                                                                 6x 6x   6x     6x 6x 6x   38x 38x     38x 66x     66x     6x 1x   6x 66x                 6x       1x           1x         1x     1x     1x     1x           1x   1x           1x 1x                     1x 1x   1x                 1x   1x   1x 1x   1x                             3x   1x               6x                                                                                                                                                             7x 7x 52x 52x 52x                                             3x 14x     14x                    
import type { Types } from '@cornerstonejs/core';
import { cache, utilities as csUtils } from '@cornerstonejs/core';
 
import { triggerSegmentationDataModified } from '../../../stateManagement/segmentation/triggerSegmentationEvents';
import compositions from './compositions';
import { getStrategyData } from './utils/getStrategyData';
import { isVolumeSegmentation } from './utils/stackVolumeCheck';
import { StrategyCallbacks } from '../../../enums';
import type {
  LabelmapToolOperationDataAny,
  LabelmapToolOperationDataVolume,
} from '../../../types/LabelmapToolOperationData';
import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData';
 
const { VoxelManager } = csUtils;
 
export type InitializedOperationData = LabelmapToolOperationDataAny & {
  // Allow initialization that is operation specific by keying on the name
  operationName?: string;
 
  // Additional data for performing the strategy
  enabledElement: Types.IEnabledElement;
  centerIJK?: Types.Point3;
  centerWorld: Types.Point3;
  viewport: Types.IViewport;
  imageVoxelManager:
    | csUtils.VoxelManager<number>
    | csUtils.VoxelManager<Types.RGB>;
  segmentationVoxelManager: csUtils.VoxelManager<number>;
  segmentationImageData: vtkImageData;
  previewVoxelManager: csUtils.VoxelManager<number>;
  // The index to use for the preview segment.  Currently always undefined or 255
  // but define it here for future expansion of LUT tables
  previewSegmentIndex?: number;
 
  brushStrategy: BrushStrategy;
  configuration?: Record<string, any>;
};
 
export type StrategyFunction = (
  operationData: InitializedOperationData,
  ...args
) => unknown;
 
export type CompositionInstance = {
  [callback in StrategyCallbacks]?: StrategyFunction;
};
 
export type CompositionFunction = () => CompositionInstance;
 
export type Composition = CompositionFunction | CompositionInstance;
 
/**
 * A brush strategy is a composition of individual parts which together form
 * the strategy for a brush tool.
 *
 * Parts of a strategy:
 * 1. Fill strategy - how the fill gets done (left/right, 3d, paint fill etc)
 * 2. Set value strategy - can clear values or set them, or something else?
 * 3. In object strategy - how to tell if a point is contained in the object
 *    * Bounding box getter for the object strategy
 * 4. threshold - how to determine if a point is within a threshold value
 * 5. preview - how to display preview information
 * 6. Various strategy customizations such as erase
 *
 * These combine to form an actual brush:
 *
 * Circle - convexFill, defaultSetValue, inEllipse/boundingbox ellipse, empty threshold
 * Rectangle - - convexFill, defaultSetValue, inRectangle/boundingbox rectangle, empty threshold
 * might also get parameter values from input,  init for setup of convexFill
 *
 * The pieces are combined to generate a strategyFunction, which performs
 * the actual strategy operation, as well as various callbacks for the strategy
 * to allow more control over behaviour in the specific strategy (such as displaying
 * preview)
 */
 
export default class BrushStrategy {
  /**
   * Provide some default initializers for various situations, mostly for
   * external use to allow defining new brushes
   */
  public static COMPOSITIONS = compositions;
 
  protected static childFunctions = {
    [StrategyCallbacks.OnInteractionStart]: addListMethod(
      StrategyCallbacks.OnInteractionStart,
      StrategyCallbacks.Initialize
    ),
    [StrategyCallbacks.OnInteractionEnd]: addListMethod(
      StrategyCallbacks.OnInteractionEnd,
      StrategyCallbacks.Initialize
    ),
    [StrategyCallbacks.Fill]: addListMethod(StrategyCallbacks.Fill),
    [StrategyCallbacks.Initialize]: addListMethod(StrategyCallbacks.Initialize),
    [StrategyCallbacks.CreateIsInThreshold]: addSingletonMethod(
      StrategyCallbacks.CreateIsInThreshold
    ),
    [StrategyCallbacks.AcceptPreview]: addListMethod(
      StrategyCallbacks.AcceptPreview,
      StrategyCallbacks.Initialize
    ),
    [StrategyCallbacks.RejectPreview]: addListMethod(
      StrategyCallbacks.RejectPreview,
      StrategyCallbacks.Initialize
    ),
    [StrategyCallbacks.INTERNAL_setValue]: addSingletonMethod(
      StrategyCallbacks.INTERNAL_setValue
    ),
    [StrategyCallbacks.Preview]: addSingletonMethod(
      StrategyCallbacks.Preview,
      false
    ),
    [StrategyCallbacks.ComputeInnerCircleRadius]: addListMethod(
      StrategyCallbacks.ComputeInnerCircleRadius
    ),
    // Add other exposed fields below
    // initializers is exposed on the function to allow extension of the composition object
    compositions: null,
  };
 
  public compositions: Composition[];
  public strategyFunction: (enabledElement, operationData) => unknown;
 
  protected configurationName: string;
  protected _initialize = [];
  protected _fill = [];
  protected _acceptPreview: [];
  protected _onInteractionStart = [];
 
  constructor(name, ...initializers: Composition[]) {
    this.configurationName = name;
    this.compositions = initializers;
    initializers.forEach((initializer) => {
      const result =
        typeof initializer === 'function' ? initializer() : initializer;
      Iif (!result) {
        return;
      }
      for (const key in result) {
        Iif (!BrushStrategy.childFunctions[key]) {
          throw new Error(`Didn't find ${key} as a brush strategy`);
        }
        BrushStrategy.childFunctions[key](this, result[key]);
      }
    });
    this.strategyFunction = (enabledElement, operationData) =>
      this.fill(enabledElement, operationData);
 
    for (const key of Object.keys(BrushStrategy.childFunctions)) {
      this.strategyFunction[key] = this[key];
    }
  }
 
  /**
   * Performs a fill of the given region.
   * Returns the preview data if the fill performs a preview, and otherwise
   * returns null.
   */
  public fill = (
    enabledElement: Types.IEnabledElement,
    operationData: LabelmapToolOperationDataAny
  ) => {
    const initializedData = this.initialize(
      enabledElement,
      operationData,
      StrategyCallbacks.Fill
    );
 
    Iif (!initializedData) {
      // Happens when there is no label map
      return;
    }
 
    const { strategySpecificConfiguration = {}, centerIJK } = initializedData;
    // Store the center IJK location so that we can skip an immediate same-point update
    // TODO - move this to the BrushTool
    Iif (csUtils.isEqual(centerIJK, strategySpecificConfiguration.centerIJK)) {
      return operationData.preview;
    } else {
      strategySpecificConfiguration.centerIJK = centerIJK;
    }
 
    this._fill.forEach((func) => func(initializedData));
 
    const {
      segmentationVoxelManager,
      previewVoxelManager,
      previewSegmentIndex,
    } = initializedData;
 
    triggerSegmentationDataModified(
      initializedData.segmentationId,
      segmentationVoxelManager.getArrayOfSlices()
    );
    // We are only previewing if there is a preview index, and there is at
    // least one slice modified
    Eif (!previewSegmentIndex || !previewVoxelManager.modifiedSlices.size) {
      return null;
    }
    // Use the original initialized data set to preserve preview info
    return initializedData.preview || initializedData;
  };
 
  protected initialize(
    enabledElement: Types.IEnabledElement,
    operationData: LabelmapToolOperationDataAny,
    operationName?: string
  ): InitializedOperationData {
    const { viewport } = enabledElement;
    const data = getStrategyData({ operationData, viewport });
 
    Iif (!data) {
      console.warn('No data found for BrushStrategy');
      return operationData.preview;
    }
 
    const {
      imageVoxelManager,
      segmentationVoxelManager,
      segmentationImageData,
    } = data;
    const previewVoxelManager =
      operationData.preview?.previewVoxelManager ||
      VoxelManager.createHistoryVoxelManager(segmentationVoxelManager);
    const previewEnabled = !!operationData.previewColors;
    const previewSegmentIndex = previewEnabled ? 255 : undefined;
 
    const initializedData: InitializedOperationData = {
      operationName,
      previewSegmentIndex,
      ...operationData,
      enabledElement,
      imageVoxelManager,
      segmentationVoxelManager,
      segmentationImageData,
      previewVoxelManager,
      viewport,
 
      centerWorld: null,
      brushStrategy: this,
    };
 
    this._initialize.forEach((func) => func(initializedData));
 
    return initializedData;
  }
 
  /**
   * Function called to initialize the start of the strategy.  Often this is
   * on mouse down, so calling this initDown.
   * Over-written by the strategy composition.
   */
  public onInteractionStart = (
    enabledElement: Types.IEnabledElement,
    operationData: LabelmapToolOperationDataAny
  ) => {
    const { preview } = operationData;
    // Need to skip the init down if it has already occurred in teh preview
    // That prevents resetting values which were used to determine the preview
    if (preview?.isPreviewFromHover) {
      preview.isPreviewFromHover = false;
      return;
    }
    const initializedData = this.initialize(enabledElement, operationData);
    if (!initializedData) {
      // Happens if there isn't a labelmap to apply to
      return;
    }
    this._onInteractionStart.forEach((func) =>
      func.call(this, initializedData)
    );
  };
 
  /**
   * Function called when a strategy is complete in some way.
   * Often called on mouse up, hence the name.
   *
   * Over-written by the strategy composition.
   */
  public onInteractionEnd: (
    enabledElement: Types.IEnabledElement,
    operationData: LabelmapToolOperationDataAny
  ) => void;
 
  /**
   * Reject the preview.
   * Over-written by the strategy composition.
   */
  public rejectPreview: (
    enabledElement: Types.IEnabledElement,
    operationData: LabelmapToolOperationDataAny
  ) => void;
 
  /**
   * Accept the preview, making it part of the overall segmentation
   *
   * Over-written by the strategy composition.
   */
  public acceptPreview: (
    enabledElement: Types.IEnabledElement,
    operationData: LabelmapToolOperationDataAny
  ) => void;
 
  /**
   * Display a preview at the current position.  This will typically
   * using the onInteractionStart, fill and onInteractionEnd methods,
   * plus optional use of a preview.
   *
   * Over-written by the strategy composition.
   * @returns preview data if a preview is displayed.
   */
  public preview: (
    enabledElement: Types.IEnabledElement,
    operationData: LabelmapToolOperationDataAny
  ) => unknown;
 
  /**
   * Over-written by the strategy composition.
   */
  public setValue: (operationData: InitializedOperationData, data) => void;
 
  /**
   * Over-written by the strategy composition.
   */
  public createIsInThreshold: (operationData: InitializedOperationData) => any;
}
 
/**
 * Adds a list method to the set of defined methods.
 */
function addListMethod(name: string, createInitialized?: string) {
  const listName = `_${name}`;
  return (brushStrategy, func) => {
    brushStrategy[listName] ||= [];
    brushStrategy[listName].push(func);
    brushStrategy[name] ||= createInitialized
      ? (enabledElement, operationData) => {
          const initializedData = brushStrategy[createInitialized](
            enabledElement,
            operationData,
            name
          );
          brushStrategy[listName].forEach((func) =>
            func.call(brushStrategy, initializedData)
          );
        }
      : (operationData) => {
          brushStrategy[listName].forEach((func) =>
            func.call(brushStrategy, operationData)
          );
        };
  };
}
 
/**
 * Adds a singleton method, throwing an exception if it is already defined
 */
function addSingletonMethod(name: string, isInitialized = true) {
  return (brushStrategy, func) => {
    Iif (brushStrategy[name]) {
      throw new Error(`The singleton method ${name} already exists`);
    }
    brushStrategy[name] = isInitialized
      ? func
      : (enabledElement, operationData) => {
          // Store the enabled element in the operation data so we can use single
          // argument calls
          operationData.enabledElement = enabledElement;
          return func.call(brushStrategy, operationData);
        };
  };
}