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

0% Statements 0/105
0% Branches 0/34
0% Functions 0/12
0% Lines 0/97

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import { Types } from '@cornerstonejs/core';
import * as mathPoint from '../point';
import getLineSegmentIntersectionsIndexes from './getLineSegmentIntersectionsIndexes';
import containsPoint from './containsPoint';
import getNormal2 from './getNormal2';
import { glMatrix, vec3 } from 'gl-matrix';
import getLinesIntersection from './getLinesIntersection';
 
enum PolylinePointType {
  Vertex,
  Intersection,
}
 
// Position of the point related to the intersection region
enum PolylinePointPosition {
  Outside = -1,
  Edge = 0,
  Inside = 1,
}
 
// Direction from last point to the intersection point to know if it is entering
// or exiting the intersection region
enum PolylinePointDirection {
  Exiting = -1,
  Unknown = 0,
  Entering = 1,
}
 
type PolylinePoint = {
  type: PolylinePointType;
  coordinates: Types.Point2;
  position?: PolylinePointPosition;
  visited: boolean;
  next: PolylinePoint;
};
 
type PolylineIntersectionPoint = PolylinePoint & {
  direction: PolylinePointDirection;
  cloned?: boolean;
};
 
/**
 * Ensure all polyline point objects are pointing to the next object in case
 * it is still not point to anyone.
 * @param polylinePoints - Array that contains all polyline points (vertices and intersections)
 */
function ensuresNextPointers(polylinePoints: PolylinePoint[]) {
  // Make sure all nodes point to a valid node
  for (let i = 0, len = polylinePoints.length; i < len; i++) {
    const currentPoint = polylinePoints[i];
 
    if (!currentPoint.next) {
      currentPoint.next = polylinePoints[i === len - 1 ? 0 : i + 1];
    }
  }
}
 
/**
 * Creates one linked list per polyline that contains all vertices and intersections
 * found while walking along the edges.
 *
 * @param targetPolyline - Target polyline
 * @param sourcePolyline - Source polyline
 * @returns Two linked lists with all vertices and intersections.
 */
function getSourceAndTargetPointsList(
  targetPolyline: Types.Point2[],
  sourcePolyline: Types.Point2[]
) {
  const targetPolylinePoints: PolylinePoint[] = [];
  const sourcePolylinePoints: PolylinePoint[] = [];
  const sourceIntersectionsCache = new Map<
    number,
    PolylineIntersectionPoint[]
  >();
 
  const isFirstPointInside = containsPoint(sourcePolyline, targetPolyline[0]);
 
  let intersectionPointDirection = isFirstPointInside
    ? PolylinePointDirection.Exiting
    : PolylinePointDirection.Entering;
 
  // Store all vertices and intersection for target contour
  for (let i = 0, len = targetPolyline.length; i < len; i++) {
    const p1 = targetPolyline[i];
    const pointInside = containsPoint(sourcePolyline, p1);
    const vertexPoint: PolylinePoint = {
      type: PolylinePointType.Vertex,
      coordinates: p1,
      position: pointInside
        ? PolylinePointPosition.Inside
        : PolylinePointPosition.Outside,
      visited: false,
      next: null,
    };
 
    targetPolylinePoints.push(vertexPoint);
 
    const q1 = targetPolyline[i === len - 1 ? 0 : i + 1];
    const intersectionsInfo = getLineSegmentIntersectionsIndexes(
      sourcePolyline,
      p1,
      q1
    ).map((intersectedLineSegment) => {
      const sourceLineSegmentId: number = intersectedLineSegment[0];
      const p2 = sourcePolyline[intersectedLineSegment[0]];
      const q2 = sourcePolyline[intersectedLineSegment[1]];
 
      // lineSegment.intersectLine returns the midpoint of the four points
      // when the lines are parallel or co-incident.  Otherwise it will return
      // an extension of the line.
      const intersectionCoordinate = getLinesIntersection(
        p1,
        q1,
        p2,
        q2
      ) as Types.Point2;
 
      const targetStartPointDistSquared = mathPoint.distanceToPointSquared(
        p1,
        intersectionCoordinate
      );
 
      return {
        sourceLineSegmentId,
        coordinate: intersectionCoordinate,
        targetStartPointDistSquared,
      };
    });
 
    intersectionsInfo.sort(
      (left, right) =>
        left.targetStartPointDistSquared - right.targetStartPointDistSquared
    );
 
    intersectionsInfo.forEach((intersectionInfo) => {
      const { sourceLineSegmentId, coordinate: intersectionCoordinate } =
        intersectionInfo;
 
      // Intersection point to be added to the target polyline list
      const targetEdgePoint: PolylineIntersectionPoint = {
        type: PolylinePointType.Intersection,
        coordinates: intersectionCoordinate,
        position: PolylinePointPosition.Edge,
        direction: intersectionPointDirection,
        visited: false,
        next: null,
      };
 
      // Intersection point to be added to the source polyline list.
      // At this point there is no way to know if the point is entering or
      // exiting the intersection region but that is not going to be used
      // hence it is set to "unknown".
      const sourceEdgePoint: PolylineIntersectionPoint = {
        ...targetEdgePoint,
        direction: PolylinePointDirection.Unknown,
        cloned: true,
      };
 
      if (intersectionPointDirection === PolylinePointDirection.Entering) {
        targetEdgePoint.next = sourceEdgePoint;
      } else {
        sourceEdgePoint.next = targetEdgePoint;
      }
 
      let sourceIntersectionPoints =
        sourceIntersectionsCache.get(sourceLineSegmentId);
 
      if (!sourceIntersectionPoints) {
        sourceIntersectionPoints = [];
        sourceIntersectionsCache.set(
          sourceLineSegmentId,
          sourceIntersectionPoints
        );
      }
 
      targetPolylinePoints.push(targetEdgePoint);
      sourceIntersectionPoints.push(sourceEdgePoint);
 
      // Switches from "exiting" to "entering" and vice-versa
      intersectionPointDirection *= -1;
    });
  }
 
  // Store all vertices and intersections for source contour
  for (let i = 0, len = sourcePolyline.length; i < len; i++) {
    const lineSegmentId: number = i;
    const p1 = sourcePolyline[i];
    const vertexPoint: PolylinePoint = {
      type: PolylinePointType.Vertex,
      coordinates: p1,
      visited: false,
      next: null,
    };
 
    sourcePolylinePoints.push(vertexPoint);
 
    const sourceIntersectionPoints =
      sourceIntersectionsCache.get(lineSegmentId);
 
    if (!sourceIntersectionPoints?.length) {
      continue;
    }
 
    // Calculate the distance between each intersection point to the start point
    // of the line segment, sort them by distance and return a sorted array that
    // contains all intersection points.
    sourceIntersectionPoints
      .map((intersectionPoint) => ({
        intersectionPoint,
        lineSegStartDistSquared: mathPoint.distanceToPointSquared(
          p1,
          intersectionPoint.coordinates
        ),
      }))
      .sort(
        (left, right) =>
          left.lineSegStartDistSquared - right.lineSegStartDistSquared
      )
      .map(({ intersectionPoint }) => intersectionPoint)
      .forEach((intersectionPoint) =>
        sourcePolylinePoints.push(intersectionPoint)
      );
  }
 
  ensuresNextPointers(targetPolylinePoints);
  ensuresNextPointers(sourcePolylinePoints);
 
  return { targetPolylinePoints, sourcePolylinePoints };
}
 
/**
 * Get the next unvisited polyline points that is outside the intersection region.
 * @param polylinePoints - All polyline points (vertices and intersections)
 * @returns Any unvisited point that is outside the intersection region if it
 * exists or `undefined` otherwise
 */
function getUnvisitedOutsidePoint(polylinePoints: PolylinePoint[]) {
  for (let i = 0, len = polylinePoints.length; i < len; i++) {
    const point = polylinePoints[i];
 
    if (!point.visited && point.position === PolylinePointPosition.Outside) {
      return point;
    }
  }
}
 
/**
 * Merge two planar polylines (2D)
 */
function mergePolylines(
  targetPolyline: Types.Point2[],
  sourcePolyline: Types.Point2[]
) {
  const targetNormal = getNormal2(targetPolyline);
  const sourceNormal = getNormal2(sourcePolyline);
  const dotNormals = vec3.dot(sourceNormal, targetNormal);
 
  // Both polylines need to be CW or CCW to be merged and one of them needs to
  // be reversed if theirs orientation are not the same
  if (!glMatrix.equals(1, dotNormals)) {
    sourcePolyline = sourcePolyline.slice().reverse();
  }
 
  const { targetPolylinePoints } = getSourceAndTargetPointsList(
    targetPolyline,
    sourcePolyline
  );
  const startPoint: PolylinePoint =
    getUnvisitedOutsidePoint(targetPolylinePoints);
 
  // Source polyline contains target polyline
  if (!startPoint) {
    return targetPolyline.slice();
  }
 
  const mergedPolyline = [startPoint.coordinates];
  let currentPoint = startPoint.next;
 
  while (currentPoint !== startPoint) {
    if (
      currentPoint.type === PolylinePointType.Intersection &&
      (<PolylineIntersectionPoint>currentPoint).cloned
    ) {
      currentPoint = currentPoint.next;
      continue;
    }
 
    mergedPolyline.push(currentPoint.coordinates);
    currentPoint = currentPoint.next;
  }
 
  return mergedPolyline;
}
 
/**
 * Subtract two planar polylines (2D)
 */
function subtractPolylines(
  targetPolyline: Types.Point2[],
  sourcePolyline: Types.Point2[]
): Types.Point2[][] {
  const targetNormal = getNormal2(targetPolyline);
  const sourceNormal = getNormal2(sourcePolyline);
  const dotNormals = vec3.dot(sourceNormal, targetNormal);
 
  // The polylines need to have different orientation (CW+CCW or CCW+CW) to be
  // subtracted and one of them needs to be reversed if theirs orientation are
  // the same
  if (!glMatrix.equals(-1, dotNormals)) {
    sourcePolyline = sourcePolyline.slice().reverse();
  }
 
  const { targetPolylinePoints } = getSourceAndTargetPointsList(
    targetPolyline,
    sourcePolyline
  );
  let startPoint: PolylinePoint = null;
  const subtractedPolylines = [];
 
  while ((startPoint = getUnvisitedOutsidePoint(targetPolylinePoints))) {
    const subtractedPolyline = [startPoint.coordinates];
    let currentPoint = startPoint.next;
 
    startPoint.visited = true;
 
    while (currentPoint !== startPoint) {
      currentPoint.visited = true;
 
      if (
        currentPoint.type === PolylinePointType.Intersection &&
        (<PolylineIntersectionPoint>currentPoint).cloned
      ) {
        currentPoint = currentPoint.next;
        continue;
      }
 
      subtractedPolyline.push(currentPoint.coordinates);
      currentPoint = currentPoint.next;
    }
 
    subtractedPolylines.push(subtractedPolyline);
  }
 
  return subtractedPolylines;
}
 
export { mergePolylines, subtractPolylines };