All files / src/core/utils geometry.ts

74.13% Statements 43/58
85.71% Branches 12/14
57.14% Functions 4/7
74.13% Lines 43/58

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    1x 2x 2x 2x 2x 2x 2x   1x       1x 21802x 21802x   1x               1x 600x 600x 600x 600x 600x 600x   600x 100x   600x   1x               1x 101x 101x 101x 101x 101x 1212x 1212x 1212x 3636x 1212x 3030x 1010x 1212x 1212x 606x 606x 1212x 101x 101x  
import { EdgeInfo, Point } from "../../types";
 
export function distanceToSegment(p: Point, v: Point, w: Point): number {
  const l2 = (v.x - w.x) ** 2 + (v.y - w.y) ** 2;
  if (l2 === 0) return Math.hypot(p.x - v.x, p.y - v.y);
  let t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
  t = Math.max(0, Math.min(1, t));
  return Math.hypot(p.x - (v.x + t * (w.x - v.x)), p.y - (v.y + t * (w.y - v.y)));
}
 
export function distanceToLineSegment(p: Point, v: Point, w: Point): number {
  return distanceToSegment(p, v, w);
}
 
export function pointsClose(p1: Point, p2: Point, epsilon: number): boolean {
  return Math.abs(p1.x - p2.x) < epsilon && Math.abs(p1.y - p2.y) < epsilon;
}
 
export function pointsCloseEuclidean(
  p1: Point,
  p2: Point,
  epsilon: number
): boolean {
  return Math.hypot(p1.x - p2.x, p1.y - p2.y) <= epsilon;
}
 
export function edgesEqual(
  a: EdgeInfo,
  b: EdgeInfo,
  epsilon: number = 0.01
): boolean {
  return (
    (pointsClose(a.points[0], b.points[0], epsilon) &&
      pointsClose(a.points[1], b.points[1], epsilon)) ||
    (pointsClose(a.points[0], b.points[1], epsilon) &&
      pointsClose(a.points[1], b.points[0], epsilon))
  );
}
 
export function getOtherPoint(
  edge: EdgeInfo,
  vertex: Point,
  epsilon: number = 0.01
): Point {
  return pointsClose(vertex, edge.points[0], epsilon) ? edge.points[1] : edge.points[0];
}
 
export function removeDuplicateEdges(
  edges: EdgeInfo[],
  epsilon: number = 0.1
): EdgeInfo[] {
  const unique: EdgeInfo[] = [];
  for (const edge of edges) {
    if (
      !unique.some(
        (u) =>
          (pointsClose(edge.points[0], u.points[0], epsilon) &&
            pointsClose(edge.points[1], u.points[1], epsilon)) ||
          (pointsClose(edge.points[0], u.points[1], epsilon) &&
            pointsClose(edge.points[1], u.points[0], epsilon))
      )
    ) {
      unique.push(edge);
    }
  }
  return unique;
}