All files / Sources/Proxy/Core/View2DProxy index.js

45.69% Statements 85/186
25.8% Branches 24/93
45% Functions 9/20
45.85% Lines 83/181

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              1x                                                     2x     2x 2x     2x 2x 2x 2x 2x 2x     2x       2x 2x 2x 2x 2x           2x     2x 2x 2x 16x     2x                 2x   2x                                       2x 2x                               2x 2x 1x 1x     1x     2x 2x                                 2x           2x   2x 2x         2x 2x       2x     2x   2x     2x         2x 2x 2x   2x 16x 16x 16x       2x 2x 2x 2x 2x 2x     2x     2x     2x 2x         2x 2x 2x 2x 2x 2x   2x         2x         2x             2x             2x       2x                                                                             2x 1x 1x 1x                                                                                                                                                                       1x                       2x   2x 2x 2x     2x       1x          
import macro from 'vtk.js/Sources/macros';
import vtkMouseRangeManipulator from 'vtk.js/Sources/Interaction/Manipulators/MouseRangeManipulator';
import vtkViewProxy from 'vtk.js/Sources/Proxy/Core/ViewProxy';
import * as vtkMath from 'vtk.js/Sources/Common/Core/Math';
import { vec3, mat4 } from 'gl-matrix';
import vtkBoundingBox from 'vtk.js/Sources/Common/DataModel/BoundingBox';
 
const DEFAULT_STEP_WIDTH = 512;
 
function formatAnnotationValue(value) {
  if (Array.isArray(value)) {
    return value.map(formatAnnotationValue).join(', ');
  }
  if (Number.isInteger(value)) {
    return value;
  }
  if (Number.isFinite(value)) {
    if (Math.abs(value) < 0.01) {
      return '0';
    }
    return value.toFixed(2);
  }
  return value;
}
 
/**
 * Returns an array of points in world coordinates creating a coarse hull
 * around the prop given in argument
 * The returned array is empty if the prop is not visible or doesn't use bounds
 *
 * How it works: if possible, combine the mapper bounds corners with the prop matrix
 * otherwise, returns the prop bounds corners
 */
function getPropCoarseHull(prop) {
  Iif (!prop.getVisibility() || !prop.getUseBounds()) {
    return [];
  }
  let finestBounds = prop.getBounds();
  let finestMatrix = null;
 
  // Better bounds using mapper bounds and prop matrix
  const mapper = prop?.getMapper?.();
  const mapperBounds = mapper?.getBounds?.();
  if (vtkBoundingBox.isValid(mapperBounds) && prop.getMatrix) {
    finestBounds = mapperBounds;
    finestMatrix = prop.getMatrix().slice();
    mat4.transpose(finestMatrix, finestMatrix);
 
    // Better bounds using the image data matrix and prop matrix + imageData matrix
    if (
      mapper.isA('vtkImageMapper') &&
      mapper.getInputData()?.isA('vtkImageData')
    ) {
      prop.computeMatrix();
      const imageData = mapper.getInputData();
      finestBounds = imageData.getSpatialExtent();
      const imageDataMatrix = imageData.getIndexToWorld();
      mat4.mul(finestMatrix, finestMatrix, imageDataMatrix);
    }
  }
 
  // Compute corners and transform them if needed
  // It gives a more accurate hull than computing the corners of a transformed bounding box
  Iif (!vtkBoundingBox.isValid(finestBounds)) {
    return [];
  }
  const corners = [];
  vtkBoundingBox.getCorners(finestBounds, corners);
  if (finestMatrix) {
    corners.forEach((pt) => vec3.transformMat4(pt, pt, finestMatrix));
  }
 
  return corners;
}
 
// ----------------------------------------------------------------------------
// vtkView2DProxy methods
// ----------------------------------------------------------------------------
 
function vtkView2DProxy(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkView2DProxy');
 
  publicAPI.updateWidthHeightAnnotation = () => {
    const { ijkOrientation, dimensions } = model.cornerAnnotation.getMetadata();
    if (ijkOrientation && dimensions) {
      let realDimensions = dimensions;
      if (dimensions.length > 3) {
        // the dimensions is a string
        realDimensions = dimensions.split(',').map(Number);
      }
      const dop = model.camera.getDirectionOfProjection();
      const viewUp = model.camera.getViewUp();
      const viewRight = [0, 0, 0];
      vtkMath.cross(dop, viewUp, viewRight);
      const wIdx = vtkMath.getMajorAxisIndex(viewRight);
      const hIdx = vtkMath.getMajorAxisIndex(viewUp);
      const sliceWidth = realDimensions['IJK'.indexOf(ijkOrientation[wIdx])];
      const sliceHeight = realDimensions['IJK'.indexOf(ijkOrientation[hIdx])];
      publicAPI.updateCornerAnnotation({ sliceWidth, sliceHeight });
    }
  };
 
  const superUpdateOrientation = publicAPI.updateOrientation;
  publicAPI.updateOrientation = (axisIndex, orientation, viewUp) => {
    const promise = superUpdateOrientation(axisIndex, orientation, viewUp);
 
    let count = model.representations.length;
    while (count--) {
      const rep = model.representations[count];
      const slicingMode = 'XYZ'[axisIndex];
      if (rep.setSlicingMode) {
        rep.setSlicingMode(slicingMode);
      }
    }
 
    publicAPI.updateCornerAnnotation({ axis: 'XYZ'[axisIndex] });
    return promise;
  };
 
  const superAddRepresentation = publicAPI.addRepresentation;
  publicAPI.addRepresentation = (rep) => {
    superAddRepresentation(rep);
    Iif (rep.setSlicingMode) {
      rep.setSlicingMode('XYZ'[model.axis]);
    }
    publicAPI.bindRepresentationToManipulator(rep);
  };
 
  const superRemoveRepresentation = publicAPI.removeRepresentation;
  publicAPI.removeRepresentation = (rep) => {
    superRemoveRepresentation(rep);
    if (rep === model.sliceRepresentation) {
      publicAPI.bindRepresentationToManipulator(null);
      let count = model.representations.length;
      while (count--) {
        if (
          publicAPI.bindRepresentationToManipulator(
            model.representations[count]
          )
        ) {
          count = 0;
        }
      }
    }
  };
 
  const superInternalResetCamera = model._resetCamera;
  /**
   * If fitProps is true, calling resetCamera will exactly fit the bounds in the view
   * Exact fitting requires useParallelRendering, and an active camera
   * Otherwise, the default renderer.resetCamera is used and it uses a larger bounding box
   */
  model._resetCamera = (bounds = null) => {
    // Always reset camera first to set physicalScale, physicalTranslation and trigger events
    const initialReset = superInternalResetCamera(bounds);
    Iif (!model.fitProps || !model.useParallelRendering || !initialReset) {
      return initialReset;
    }
 
    // For each visible prop get the smallest possible convex hull using bounds corners
    const visiblePoints = [];
    Iif (bounds) {
      // Bounds are given as argument, use their corners
      vtkBoundingBox.getCorners(bounds, visiblePoints);
    } else {
      publicAPI
        .getRepresentations()
        .forEach((representationProxy) =>
          [representationProxy.getActors(), representationProxy.getVolumes()]
            .flat()
            .forEach((prop) => visiblePoints.push(...getPropCoarseHull(prop)))
        );
    }
    Iif (!visiblePoints) {
      return initialReset;
    }
 
    // Get the bounds in view coordinates
    const viewBounds = vtkBoundingBox.reset([]);
    const viewMatrix = model.camera.getViewMatrix();
    mat4.transpose(viewMatrix, viewMatrix);
 
    for (let i = 0; i < visiblePoints.length; ++i) {
      const point = visiblePoints[i];
      vec3.transformMat4(point, point, viewMatrix);
      vtkBoundingBox.addPoint(viewBounds, ...point);
    }
 
    // Compute parallel scale
    const view = model.renderer.getRenderWindow().getViews()[0];
    const dims = view.getViewportSize(model.renderer);
    const aspect = dims[1] && dims[0] ? dims[0] / dims[1] : 1;
    const xLength = vtkBoundingBox.getLength(viewBounds, 0);
    const yLength = vtkBoundingBox.getLength(viewBounds, 1);
    const parallelScale = 0.5 * Math.max(yLength, xLength / aspect);
 
    // Compute focal point and position
    const viewFocalPoint = vtkBoundingBox.getCenter(viewBounds);
    // Camera position in view coordinates is the center of the bounds in XY
    // and is (the maximum bound) + (the distance to see the bounds in perspective) in Z
    const perspectiveAngle = vtkMath.radiansFromDegrees(
      model.camera.getViewAngle()
    );
    const distance = parallelScale / Math.tan(perspectiveAngle * 0.5);
    const viewPosition = [
      viewFocalPoint[0],
      viewFocalPoint[1],
      viewBounds[5] + distance,
    ];
    const inverseViewMatrix = new Float64Array(16);
    const worldFocalPoint = new Float64Array(3);
    const worldPosition = new Float64Array(3);
    mat4.invert(inverseViewMatrix, viewMatrix);
    vec3.transformMat4(worldFocalPoint, viewFocalPoint, inverseViewMatrix);
    vec3.transformMat4(worldPosition, viewPosition, inverseViewMatrix);
 
    Iif (parallelScale <= 0) {
      return initialReset;
    }
 
    // Compute bounds in world coordinates
    const worldBounds = vtkBoundingBox.transformBounds(
      viewBounds,
      inverseViewMatrix
    );
 
    publicAPI.setCameraParameters({
      position: worldPosition,
      focalPoint: worldFocalPoint,
      bounds: worldBounds,
      parallelScale,
    });
 
    return true;
  };
 
  // --------------------------------------------------------------------------
  // Range Manipulator setup
  // -------------------------------------------------------------------------
 
  model.rangeManipulator = vtkMouseRangeManipulator.newInstance({
    button: 1,
    scrollEnabled: true,
  });
  model.interactorStyle2D.addMouseManipulator(model.rangeManipulator);
 
  function setWindowWidth(windowWidth) {
    publicAPI.updateCornerAnnotation({ windowWidth });
    if (model.sliceRepresentation && model.sliceRepresentation.setWindowWidth) {
      model.sliceRepresentation.setWindowWidth(windowWidth);
    }
  }
 
  function setWindowLevel(windowLevel) {
    publicAPI.updateCornerAnnotation({ windowLevel });
    if (model.sliceRepresentation && model.sliceRepresentation.setWindowLevel) {
      model.sliceRepresentation.setWindowLevel(windowLevel);
    }
  }
 
  function setSlice(sliceRaw) {
    const numberSliceRaw = Number(sliceRaw);
    const slice = Number.isInteger(numberSliceRaw)
      ? sliceRaw
      : numberSliceRaw.toFixed(2);
 
    // add 'slice' in annotation
    const annotation = { slice };
    if (model.sliceRepresentation && model.sliceRepresentation.setSlice) {
      model.sliceRepresentation.setSlice(numberSliceRaw);
    }
 
    // extend annotation
    if (model.sliceRepresentation && model.sliceRepresentation.getAnnotations) {
      const addOn = model.sliceRepresentation.getAnnotations();
      Object.keys(addOn).forEach((key) => {
        annotation[key] = formatAnnotationValue(addOn[key]);
      });
    }
 
    publicAPI.updateCornerAnnotation(annotation);
  }
 
  publicAPI.bindRepresentationToManipulator = (representation) => {
    let nbListeners = 0;
    if (!representation.getProxyId) {
      return nbListeners;
    }
    model.rangeManipulator.removeAllListeners();
    model.sliceRepresentation = representation;
    while (model.sliceRepresentationSubscriptions.length) {
      model.sliceRepresentationSubscriptions.pop().unsubscribe();
    }
    if (representation) {
      model.sliceRepresentationSubscriptions.push(
        model.camera.onModified(publicAPI.updateWidthHeightAnnotation)
      );
      if (representation.getWindowWidth) {
        const update = () => setWindowWidth(representation.getWindowWidth());
        const windowWidth =
          representation.getPropertyDomainByName('windowWidth');
        const { min, max } = windowWidth;
 
        let { step } = windowWidth;
        if (!step || step === 'any') {
          step = 1 / DEFAULT_STEP_WIDTH;
        }
 
        model.rangeManipulator.setVerticalListener(
          min,
          max,
          step,
          representation.getWindowWidth,
          setWindowWidth
        );
        model.sliceRepresentationSubscriptions.push(
          representation.onModified(update)
        );
        update();
        nbListeners++;
      }
      if (representation.getWindowLevel) {
        const update = () => setWindowLevel(representation.getWindowLevel());
        const windowLevel =
          representation.getPropertyDomainByName('windowLevel');
        const { min, max } = windowLevel;
 
        let { step } = windowLevel;
        if (!step || step === 'any') {
          step = 1 / DEFAULT_STEP_WIDTH;
        }
 
        model.rangeManipulator.setHorizontalListener(
          min,
          max,
          step,
          representation.getWindowLevel,
          setWindowLevel
        );
        model.sliceRepresentationSubscriptions.push(
          representation.onModified(update)
        );
        update();
        nbListeners++;
      }
      const domain = representation.getPropertyDomainByName('slice');
      if (representation.getSlice && domain) {
        const update = () => setSlice(representation.getSlice());
        model.rangeManipulator.setScrollListener(
          domain.min,
          domain.max,
          domain.step,
          representation.getSlice,
          setSlice
        );
        model.sliceRepresentationSubscriptions.push(
          representation.onModified(update)
        );
        update();
        nbListeners++;
      }
    }
    return nbListeners;
  };
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
const DEFAULT_VALUES = {
  axis: 2,
  orientation: -1,
  viewUp: [0, 1, 0],
  useParallelRendering: true,
  sliceRepresentationSubscriptions: [],
  fitProps: false,
};
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);
 
  vtkViewProxy.extend(publicAPI, model, initialValues);
  macro.get(publicAPI, model, ['axis']);
  macro.setGet(publicAPI, model, ['fitProps']);
 
  // Object specific methods
  vtkView2DProxy(publicAPI, model);
}
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(extend, 'vtkView2DProxy');
 
// ----------------------------------------------------------------------------
 
export default { newInstance, extend };