All files / packages/tools/src/utilities/math/line distanceToPointSquaredInfo.ts

90.9% Statements 10/11
80% Branches 8/10
100% Functions 1/1
90.9% Lines 10/11

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                                                105x       105x       105x   105x       105x 39x 66x 5x   61x             105x          
import type { Types } from '@cornerstonejs/core';
import * as math from '../';
 
/**
 * Calculate the closest point and the squared distance between a reference point and a line segment.
 *
 * It projects the reference point onto the line segment but it shall be bounded by the
 * start/end points since this is a line segment and not a line which could be extended.
 *
 * @param lineStart - Start point of the line segment
 * @param lineEnd - End point of the line segment
 * @param point - Reference point
 * @returns Closest point and the squared distance between a `point` and a line
 *   segment defined by `lineStart` and `lineEnd` points
 */
export default function distanceToPointSquaredInfo(
  lineStart: Types.Point2,
  lineEnd: Types.Point2,
  point: Types.Point2
): {
  point: Types.Point2;
  distanceSquared: number;
} {
  let closestPoint: Types.Point2;
  const distanceSquared = math.point.distanceToPointSquared(lineStart, lineEnd);
 
  // Check if lineStart equal to the lineEnd which means the closest point
  // is any of these two points
  Iif (lineStart[0] === lineEnd[0] && lineStart[1] === lineEnd[1]) {
    closestPoint = lineStart;
  }
 
  Eif (!closestPoint) {
    const dotProduct =
      ((point[0] - lineStart[0]) * (lineEnd[0] - lineStart[0]) +
        (point[1] - lineStart[1]) * (lineEnd[1] - lineStart[1])) /
      distanceSquared;
 
    if (dotProduct < 0) {
      closestPoint = lineStart;
    } else if (dotProduct > 1) {
      closestPoint = lineEnd;
    } else {
      closestPoint = [
        lineStart[0] + dotProduct * (lineEnd[0] - lineStart[0]),
        lineStart[1] + dotProduct * (lineEnd[1] - lineStart[1]),
      ];
    }
  }
 
  return {
    point: [...closestPoint],
    distanceSquared: math.point.distanceToPointSquared(point, closestPoint),
  };
}