All files / packages/tools/src/utilities/math/polyline intersectPolyline.ts

90% Statements 9/10
75% Branches 3/4
100% Functions 1/1
87.5% Lines 7/8

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                                1x 5x 5x 5x   5x           5x         1x    
import { Types } from '@cornerstonejs/core';
import getFirstLineSegmentIntersectionIndexes from './getFirstLineSegmentIntersectionIndexes';
 
/**
 * Check if two polylines intersect comparing line segment by line segment.
 * @param sourcePolyline - Source polyline
 * @param targetPolyline - Target polyline
 * @returns True if the polylines intersect or false otherwise
 */
export default function intersectPolyline(
  sourcePolyline: Types.Point2[],
  targetPolyline: Types.Point2[]
): boolean {
  // Naive way to detect intersection between polylines in O(n^2).
  // TODO: Implement Bentley Ottmann sweep line algorithm or maybe some
  // algorithm that uses r-tree may make it run faster
  for (let i = 0, sourceLen = sourcePolyline.length; i < sourceLen; i++) {
    const sourceP1 = sourcePolyline[i];
    const sourceP2Index = i === sourceLen - 1 ? 0 : i + 1;
    const sourceP2 = sourcePolyline[sourceP2Index];
 
    const intersectionPointIndexes = getFirstLineSegmentIntersectionIndexes(
      targetPolyline,
      sourceP1,
      sourceP2
    );
 
    Iif (intersectionPointIndexes?.length === 2) {
      return true;
    }
  }
 
  return false;
}