All files / src/core/grid grid-search.ts

5.88% Statements 3/51
100% Branches 0/0
0% Functions 0/2
5.88% Lines 3/51

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 601x       1x                                                       1x                                                      
import { EdgeInfo, Point } from "../../types";
import { distanceToLineSegment } from "../utils/geometry";
import { scanCellWindow } from "./grid-scan";
 
export function findClosestEdgeInWindow(
  pixel: Point,
  threshold: number,
  gridWidth: number,
  gridHeight: number,
  approxCol: number,
  approxRow: number,
  colRadius: number,
  rowRadius: number,
  getCellEdges: (cell: { col: number; row: number }) => EdgeInfo[]
): EdgeInfo | null {
  let minDist = Infinity;
  let closestEdge: EdgeInfo | null = null;
 
  scanCellWindow(gridWidth, gridHeight, approxCol, approxRow, colRadius, rowRadius, (c, r) => {
    const edges = getCellEdges({ col: c, row: r });
    for (const edge of edges) {
      const dist = distanceToLineSegment(pixel, edge.points[0], edge.points[1]);
      if (dist < minDist) {
        minDist = dist;
        closestEdge = edge;
      }
    }
  });
 
  return closestEdge && minDist < threshold ? closestEdge : null;
}
 
export function findClosestVertexInWindow(
  pixel: Point,
  threshold: number,
  gridWidth: number,
  gridHeight: number,
  approxCol: number,
  approxRow: number,
  colRadius: number,
  rowRadius: number,
  getCellPolygon: (cell: { col: number; row: number }) => Point[]
): Point | null {
  let minDistSq = Infinity;
  let closestVertex: Point | null = null;
 
  scanCellWindow(gridWidth, gridHeight, approxCol, approxRow, colRadius, rowRadius, (c, r) => {
    const poly = getCellPolygon({ col: c, row: r });
    for (const v of poly) {
      const distSq = (pixel.x - v.x) ** 2 + (pixel.y - v.y) ** 2;
      if (distSq < minDistSq) {
        minDistSq = distSq;
        closestVertex = v;
      }
    }
  });
 
  return closestVertex && minDistSq < threshold ** 2 ? closestVertex : null;
}