All files / Sources/Widgets/Widgets3D/ResliceCursorWidget behavior.js

22.27% Statements 47/211
1.36% Branches 1/73
8.57% Functions 3/35
22.38% Lines 47/210

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                                            3x 3x     3x           3x             3x         3x         3x                                                 3x           3x               3x                       3x                           3x               3x         3x                                           3x                                                       3x                               3x               3x                 3x                 3x       3x                           3x       3x                 3x                 3x                   3x               3x             3x                                                           3x                                                                                                                                                     3x                     3x                                     3x                                                                                     3x 9x 9x 9x 9x   9x 9x 9x 9x           9x                         3x 18x 18x 18x   18x                    
import macro from 'vtk.js/Sources/macros';
import vtkBoundingBox from 'vtk.js/Sources/Common/DataModel/BoundingBox';
import vtkLine from 'vtk.js/Sources/Common/DataModel/Line';
import * as vtkMath from 'vtk.js/Sources/Common/Core/Math';
 
import {
  boundPointOnPlane,
  rotateVector,
  updateState,
  getOtherLineName,
  getLinePlaneName,
  getLineInPlaneName,
  getLineNames,
} from 'vtk.js/Sources/Widgets/Widgets3D/ResliceCursorWidget/helpers';
 
import {
  ScrollingMethods,
  InteractionMethodsName,
  planeNameToViewType,
} from 'vtk.js/Sources/Widgets/Widgets3D/ResliceCursorWidget/Constants';
 
export default function widgetBehavior(publicAPI, model) {
  model._isDragging = false;
  let isScrolling = false;
  let previousPosition;
 
  macro.setGet(publicAPI, model, [
    'keepOrthogonality',
    { type: 'object', name: 'cursorStyles' },
  ]);
 
  // Set default value for cursorStyles
  publicAPI.setCursorStyles({
    [InteractionMethodsName.TranslateCenter]: 'move',
    [InteractionMethodsName.RotateLine]: 'alias',
    [InteractionMethodsName.TranslateAxis]: 'pointer',
    default: 'default',
  });
 
  publicAPI.setEnableTranslation = (enable) => {
    model.representations[0].setPickable(enable); // line handle
    model.representations[2].setPickable(enable); // center handle
  };
 
  publicAPI.setEnableRotation = (enable) => {
    model.representations[1].setPickable(enable); // rotation handle
  };
 
  // FIXME: label information should be accessible from activeState instead of parent state.
  publicAPI.getActiveInteraction = () => {
    if (
      model.widgetState
        .getStatesWithLabel('rotation')
        .includes(model.activeState)
    ) {
      return InteractionMethodsName.RotateLine;
    }
    if (
      model.widgetState.getStatesWithLabel('line').includes(model.activeState)
    ) {
      return InteractionMethodsName.TranslateAxis;
    }
    if (
      model.widgetState.getStatesWithLabel('center').includes(model.activeState)
    ) {
      return InteractionMethodsName.TranslateCenter;
    }
    return null;
  };
 
  /**
   * ActiveState can be RotationHandle or a LineHandle
   * @returns 'YinX', 'ZinX', 'XinY', 'ZinY', 'XinZ' or 'YinZ'
   */
  publicAPI.getActiveLineName = () =>
    getLineNames(model.widgetState).find((lineName) =>
      model.widgetState.getStatesWithLabel(lineName).includes(model.activeState)
    );
 
  // FIXME: label information should be accessible from activeState instead of parent state.
  publicAPI.getActiveLineHandle = () =>
    model.widgetState[`getAxis${publicAPI.getActiveLineName()}`]?.();
 
  /**
   * Return the line handle of the other line in the same view.
   * @param {string} lineName name of the line (YinX, ZinX, XinY, ZinY, XinZ, YinZ)
   * @returns ZinX if lineName == YinX, YinX if lineName == ZinX, ZinY if lineName == XinY...
   */
  publicAPI.getOtherLineHandle = (lineName) =>
    model.widgetState[
      `getAxis${getOtherLineName(model.widgetState, lineName)}`
    ]?.();
 
  // FIXME: label information should be accessible from activeState instead of parent state.
  /**
   * There are 2 rotation handles per axis: 'point0' and 'point1'.
   * This function returns which rotation handle (point0 or point1) is currently active.
   * ActiveState must be a RotationHandle.
   * @returns 'point0', 'point1' or null if no point is active (e.g. line is being rotated)
   */
  publicAPI.getActiveRotationPointName = () => {
    if (
      model.widgetState.getStatesWithLabel('point0').includes(model.activeState)
    ) {
      return 'point0';
    }
    if (
      model.widgetState.getStatesWithLabel('point1').includes(model.activeState)
    ) {
      return 'point1';
    }
    return null;
  };
 
  publicAPI.startScrolling = (newPosition) => {
    if (newPosition) {
      previousPosition = newPosition;
    }
    isScrolling = true;
    publicAPI.startInteraction();
  };
 
  publicAPI.endScrolling = () => {
    isScrolling = false;
    publicAPI.endInteraction();
  };
 
  publicAPI.updateCursor = () => {
    const cursorStyles = publicAPI.getCursorStyles();
    if (cursorStyles) {
      switch (publicAPI.getActiveInteraction()) {
        case InteractionMethodsName.TranslateCenter:
          model._apiSpecificRenderWindow.setCursor(
            cursorStyles.translateCenter
          );
          break;
        case InteractionMethodsName.RotateLine:
          model._apiSpecificRenderWindow.setCursor(cursorStyles.rotateLine);
          break;
        case InteractionMethodsName.TranslateAxis:
          model._apiSpecificRenderWindow.setCursor(cursorStyles.translateAxis);
          break;
        default:
          model._apiSpecificRenderWindow.setCursor(cursorStyles.default);
          break;
      }
    }
  };
 
  publicAPI.handleLeftButtonPress = (callData) => {
    if (model.activeState && model.activeState.getActive()) {
      model._isDragging = true;
      const viewType = model.viewType;
      const currentPlaneNormal = model.widgetState.getPlanes()[viewType].normal;
      const manipulator =
        model.activeState?.getManipulator?.() ?? model.manipulator;
      manipulator.setWidgetOrigin(model.widgetState.getCenter());
      manipulator.setWidgetNormal(currentPlaneNormal);
      const { worldCoords } = manipulator.handleEvent(
        callData,
        model._apiSpecificRenderWindow
      );
      previousPosition = worldCoords;
 
      publicAPI.startInteraction();
    } else if (
      model.widgetState.getScrollingMethod() ===
      ScrollingMethods.LEFT_MOUSE_BUTTON
    ) {
      publicAPI.startScrolling(callData.position);
    } else {
      return macro.VOID;
    }
 
    return macro.EVENT_ABORT;
  };
 
  publicAPI.handleMouseMove = (callData) => {
    if (model._isDragging) {
      return publicAPI.handleEvent(callData);
    }
    if (isScrolling) {
      if (previousPosition.y !== callData.position.y) {
        const step = previousPosition.y - callData.position.y;
        publicAPI.translateCenterOnPlaneDirection(step);
        previousPosition = callData.position;
 
        publicAPI.invokeInteractionEvent(publicAPI.getActiveInteraction());
      }
    }
    return macro.VOID;
  };
 
  publicAPI.handleLeftButtonRelease = () => {
    if (model._isDragging || isScrolling) {
      publicAPI.endScrolling();
    }
    model._isDragging = false;
    model.widgetState.deactivate();
  };
 
  publicAPI.handleRightButtonPress = (calldata) => {
    if (
      model.widgetState.getScrollingMethod() ===
      ScrollingMethods.RIGHT_MOUSE_BUTTON
    ) {
      publicAPI.startScrolling(calldata.position);
    }
  };
 
  publicAPI.handleRightButtonRelease = () => {
    if (
      model.widgetState.getScrollingMethod() ===
      ScrollingMethods.RIGHT_MOUSE_BUTTON
    ) {
      publicAPI.endScrolling();
    }
  };
 
  publicAPI.handleStartMouseWheel = () => {
    publicAPI.startInteraction();
  };
 
  publicAPI.handleMouseWheel = (calldata) => {
    const step = calldata.spinY;
    isScrolling = true;
    publicAPI.translateCenterOnPlaneDirection(step);
 
    publicAPI.invokeInteractionEvent(
      // Force interaction mode because mouse cursor could be above rotation handle
      InteractionMethodsName.TranslateCenter
    );
    isScrolling = false;
 
    return macro.EVENT_ABORT;
  };
 
  publicAPI.handleEndMouseWheel = () => {
    publicAPI.endScrolling();
  };
 
  publicAPI.handleMiddleButtonPress = (calldata) => {
    if (
      model.widgetState.getScrollingMethod() ===
      ScrollingMethods.MIDDLE_MOUSE_BUTTON
    ) {
      publicAPI.startScrolling(calldata.position);
    }
  };
 
  publicAPI.handleMiddleButtonRelease = () => {
    if (
      model.widgetState.getScrollingMethod() ===
      ScrollingMethods.MIDDLE_MOUSE_BUTTON
    ) {
      publicAPI.endScrolling();
    }
  };
 
  publicAPI.handleEvent = (callData) => {
    if (model.activeState.getActive()) {
      const methodName = publicAPI.getActiveInteraction();
      publicAPI[methodName](callData);
      publicAPI.invokeInteractionEvent(methodName);
      return macro.EVENT_ABORT;
    }
    return macro.VOID;
  };
 
  publicAPI.startInteraction = () => {
    publicAPI.invokeStartInteractionEvent();
    // When interacting, plane actor and lines must be re-rendered on other views
    publicAPI.getViewWidgets().forEach((viewWidget) => {
      viewWidget.getInteractor().requestAnimation(publicAPI);
    });
  };
 
  publicAPI.endInteraction = () => {
    publicAPI.invokeEndInteractionEvent();
    publicAPI.getViewWidgets().forEach((viewWidget) => {
      viewWidget.getInteractor().cancelAnimation(publicAPI);
    });
  };
 
  publicAPI.translateCenterOnPlaneDirection = (nbSteps) => {
    const dirProj = model.widgetState.getPlanes()[model.viewType].normal;
 
    const oldCenter = model.widgetState.getCenter();
    const image = model.widgetState.getImage();
    const imageSpacing = image.getSpacing();
 
    // Use Chebyshev norm
    // https://math.stackexchange.com/questions/71423/what-is-the-term-for-the-projection-of-a-vector-onto-the-unit-cube
    const absDirProj = dirProj.map((value) => Math.abs(value));
    const index = absDirProj.indexOf(Math.max(...absDirProj));
    const movingFactor =
      (nbSteps * imageSpacing[index]) / Math.abs(dirProj[index]);
 
    // Define the potentially new center
    let newCenter = [
      oldCenter[0] + movingFactor * dirProj[0],
      oldCenter[1] + movingFactor * dirProj[1],
      oldCenter[2] + movingFactor * dirProj[2],
    ];
    newCenter = publicAPI.getBoundedCenter(newCenter);
 
    model.widgetState.setCenter(newCenter);
    updateState(
      model.widgetState,
      model._factory.getScaleInPixels(),
      model._factory.getRotationHandlePosition()
    );
  };
 
  publicAPI[InteractionMethodsName.TranslateAxis] = (calldata) => {
    const lineHandle = publicAPI.getActiveLineHandle();
    const lineName = publicAPI.getActiveLineName();
    const pointOnLine = vtkMath.add(
      lineHandle.getOrigin(),
      lineHandle.getDirection(),
      []
    );
    const currentLineVector = lineHandle.getDirection();
    vtkMath.normalize(currentLineVector);
 
    // Translate the current line along the other line
    const otherLineHandle = publicAPI.getOtherLineHandle(lineName);
    const center = model.widgetState.getCenter();
    const manipulator =
      model.activeState?.getManipulator?.() ?? model.manipulator;
    let worldCoords = null;
    let newOrigin = [];
    if (model.activeState?.getManipulator?.()) {
      worldCoords = manipulator.handleEvent(
        calldata,
        model._apiSpecificRenderWindow
      ).worldCoords;
      const translation = vtkMath.subtract(worldCoords, previousPosition, []);
      vtkMath.add(center, translation, newOrigin);
    } else if (otherLineHandle) {
      const otherLineVector = otherLineHandle.getDirection();
      vtkMath.normalize(otherLineVector);
      const axisTranslation = otherLineVector;
 
      const dot = vtkMath.dot(currentLineVector, otherLineVector);
      // lines are colinear, translate along perpendicular axis from current line
      if (dot === 1 || dot === -1) {
        vtkMath.cross(
          currentLineVector,
          manipulator.getWidgetNormal(),
          axisTranslation
        );
      }
 
      const closestPoint = [];
      worldCoords = manipulator.handleEvent(
        calldata,
        model._apiSpecificRenderWindow
      ).worldCoords;
      vtkLine.distanceToLine(
        worldCoords,
        lineHandle.getOrigin(),
        pointOnLine,
        closestPoint
      );
 
      const translationVector = vtkMath.subtract(worldCoords, closestPoint, []);
      const translationDistance = vtkMath.dot(
        translationVector,
        axisTranslation
      );
 
      newOrigin = vtkMath.multiplyAccumulate(
        center,
        axisTranslation,
        translationDistance,
        newOrigin
      );
    }
    newOrigin = publicAPI.getBoundedCenter(newOrigin);
    model.widgetState.setCenter(newOrigin);
    updateState(
      model.widgetState,
      model._factory.getScaleInPixels(),
      model._factory.getRotationHandlePosition()
    );
    previousPosition = worldCoords;
  };
 
  publicAPI.getBoundedCenter = (newCenter) => {
    const oldCenter = model.widgetState.getCenter();
    const imageBounds = model.widgetState.getImage().getBounds();
 
    if (vtkBoundingBox.containsPoint(imageBounds, ...newCenter)) {
      return newCenter;
    }
 
    return boundPointOnPlane(newCenter, oldCenter, imageBounds);
  };
 
  publicAPI[InteractionMethodsName.TranslateCenter] = (calldata) => {
    const manipulator =
      model.activeState?.getManipulator?.() ?? model.manipulator;
    const { worldCoords } = manipulator.handleEvent(
      calldata,
      model._apiSpecificRenderWindow
    );
    const translation = vtkMath.subtract(worldCoords, previousPosition, []);
    previousPosition = worldCoords;
    let newCenter = vtkMath.add(model.widgetState.getCenter(), translation, []);
    newCenter = publicAPI.getBoundedCenter(newCenter);
    model.widgetState.setCenter(newCenter);
    updateState(
      model.widgetState,
      model._factory.getScaleInPixels(),
      model._factory.getRotationHandlePosition()
    );
  };
 
  publicAPI[InteractionMethodsName.RotateLine] = (calldata) => {
    const activeLineHandle = publicAPI.getActiveLineHandle();
    const manipulator =
      model.activeState?.getManipulator?.() ?? model.manipulator;
    const planeNormal = manipulator.getWidgetNormal();
    const { worldCoords } = manipulator.handleEvent(
      calldata,
      model._apiSpecificRenderWindow
    );
 
    if (!worldCoords || !worldCoords.length) {
      return;
    }
    const center = model.widgetState.getCenter();
    const currentVectorToOrigin = [0, 0, 0];
    vtkMath.subtract(worldCoords, center, currentVectorToOrigin);
    vtkMath.normalize(currentVectorToOrigin);
 
    const previousLineDirection = activeLineHandle.getDirection();
    vtkMath.normalize(previousLineDirection);
    const activePointName = publicAPI.getActiveRotationPointName();
    if (
      activePointName === 'point1' ||
      (!activePointName &&
        vtkMath.dot(currentVectorToOrigin, previousLineDirection) < 0)
    ) {
      vtkMath.multiplyScalar(previousLineDirection, -1);
    }
 
    const radianAngle = vtkMath.signedAngleBetweenVectors(
      previousLineDirection,
      currentVectorToOrigin,
      planeNormal
    );
 
    publicAPI.rotateLineInView(publicAPI.getActiveLineName(), radianAngle);
  };
 
  /**
   * Rotate a line by a specified angle
   * @param {string} lineName The line name to rotate (e.g. YinX, ZinX, XinY, ZinY, XinZ, YinZ)
   * @param {Number} radianAngle Applied angle in radian
   */
  publicAPI.rotateLineInView = (lineName, radianAngle) => {
    const viewType = planeNameToViewType[getLinePlaneName(lineName)];
    const inViewType = planeNameToViewType[getLineInPlaneName(lineName)];
    const planeNormal = model.widgetState.getPlanes()[inViewType].normal;
    publicAPI.rotatePlane(viewType, radianAngle, planeNormal);
 
    if (publicAPI.getKeepOrthogonality()) {
      const otherLineName = getOtherLineName(model.widgetState, lineName);
      const otherPlaneName = getLinePlaneName(otherLineName);
      publicAPI.rotatePlane(
        planeNameToViewType[otherPlaneName],
        radianAngle,
        planeNormal
      );
    }
    updateState(
      model.widgetState,
      model._factory.getScaleInPixels(),
      model._factory.getRotationHandlePosition()
    );
  };
 
  /**
   * Rotate a specified plane around an other specified plane.
   * @param {ViewTypes} viewType Define which plane will be rotated
   * @param {Number} radianAngle Applied angle in radian
   * @param {vec3} planeNormal Define the axis to rotate around
   */
  publicAPI.rotatePlane = (viewType, radianAngle, planeNormal) => {
    const { normal, viewUp } = model.widgetState.getPlanes()[viewType];
    const newNormal = rotateVector(normal, planeNormal, radianAngle);
    const newViewUp = rotateVector(viewUp, planeNormal, radianAngle);
 
    model.widgetState.getPlanes()[viewType] = {
      normal: newNormal,
      viewUp: newViewUp,
    };
  };
 
  // --------------------------------------------------------------------------
  // initialization
  // --------------------------------------------------------------------------
}