---
id: wiki-2026-0508-computational-geometry
title: Computational Geometry (Frontend)
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [2D Geometry, Geometric Algorithms]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [geometry, algorithms, canvas, frontend, math]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: TypeScript
  framework: Canvas / SVG / WebGL
---

# Computational Geometry (Frontend)

## 매 한 줄
> **"매 pixel 의 math 가 geometry 다"**. Hit-testing, polygon clipping, convex hull, spatial index — 매 canvas/SVG/Figma-style editor 의 core, 매 numerical robustness + spatial accel structure 가 핵심.

## 매 핵심

### 매 fundamental ops
- Point-in-polygon (ray casting / winding number).
- Line-line / segment-segment intersection.
- Polygon-polygon clipping (Sutherland-Hodgman, Weiler-Atherton).
- Convex hull (Graham scan, Andrew's monotone chain).
- Bounding box / sphere.
- Distance: point-segment, point-polygon.

### 매 spatial accel
- Quadtree — 2D static/dynamic.
- R-tree — bbox-based, dynamic insert/delete (rbush lib).
- Spatial hash — uniform grid.
- BVH — for raycasting in 2D/3D.

### 매 numerical pitfalls
- Floating-point cross product near zero → epsilon checks.
- Robust orientation predicates (Shewchuk).
- 매 SVG path parsing → degenerate cubic 처리.

### 매 응용
1. Figma-style hit-testing.
2. Map polygon labeling / clipping.
3. Drag-select rectangle vs many shapes.
4. Snap-to-grid / snap-to-edge.
5. Boolean ops on shapes (union/intersect/difference).

## 💻 패턴

### Point-in-polygon (ray casting)
```ts
type Pt = { x: number; y: number };

export function pointInPolygon(p: Pt, poly: Pt[]): boolean {
  let inside = false;
  for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
    const a = poly[i], b = poly[j];
    const intersect =
      (a.y > p.y) !== (b.y > p.y) &&
      p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y) + a.x;
    if (intersect) inside = !inside;
  }
  return inside;
}
```

### Segment-segment intersection
```ts
export function segIntersect(p1: Pt, p2: Pt, p3: Pt, p4: Pt): Pt | null {
  const d = (p2.x - p1.x) * (p4.y - p3.y) - (p2.y - p1.y) * (p4.x - p3.x);
  if (Math.abs(d) < 1e-10) return null; // parallel
  const t = ((p3.x - p1.x) * (p4.y - p3.y) - (p3.y - p1.y) * (p4.x - p3.x)) / d;
  const u = ((p3.x - p1.x) * (p2.y - p1.y) - (p3.y - p1.y) * (p2.x - p1.x)) / d;
  if (t < 0 || t > 1 || u < 0 || u > 1) return null;
  return { x: p1.x + t * (p2.x - p1.x), y: p1.y + t * (p2.y - p1.y) };
}
```

### Convex hull (Andrew's monotone chain)
```ts
export function convexHull(pts: Pt[]): Pt[] {
  const p = [...pts].sort((a, b) => a.x - b.x || a.y - b.y);
  const cross = (o: Pt, a: Pt, b: Pt) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
  const lower: Pt[] = [];
  for (const pt of p) {
    while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], pt) <= 0) lower.pop();
    lower.push(pt);
  }
  const upper: Pt[] = [];
  for (let i = p.length - 1; i >= 0; i--) {
    const pt = p[i];
    while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], pt) <= 0) upper.pop();
    upper.push(pt);
  }
  upper.pop(); lower.pop();
  return lower.concat(upper);
}
```

### Bounding box
```ts
export function bbox(pts: Pt[]): { min: Pt; max: Pt } {
  let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
  for (const { x, y } of pts) {
    if (x < minX) minX = x; if (y < minY) minY = y;
    if (x > maxX) maxX = x; if (y > maxY) maxY = y;
  }
  return { min: { x: minX, y: minY }, max: { x: maxX, y: maxY } };
}
```

### R-tree spatial index (rbush)
```ts
import RBush from 'rbush';

type Item = { minX: number; minY: number; maxX: number; maxY: number; id: string };
const tree = new RBush<Item>();
tree.load(items);

const hits = tree.search({ minX: 0, minY: 0, maxX: 100, maxY: 100 });
```

### Point-segment distance
```ts
export function distPtSeg(p: Pt, a: Pt, b: Pt): number {
  const dx = b.x - a.x, dy = b.y - a.y;
  const lenSq = dx * dx + dy * dy;
  if (lenSq === 0) return Math.hypot(p.x - a.x, p.y - a.y);
  let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / lenSq;
  t = Math.max(0, Math.min(1, t));
  return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));
}
```

### Polygon clipping (using martinez-polygon-clipping)
```ts
import * as martinez from 'martinez-polygon-clipping';

const subject = [[[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]];
const clip = [[[5, 5], [15, 5], [15, 15], [5, 15], [5, 5]]];
const intersection = martinez.intersection(subject, clip);
```

### Snap-to-grid
```ts
export const snap = (v: number, grid: number) => Math.round(v / grid) * grid;
export const snapPt = (p: Pt, g: number): Pt => ({ x: snap(p.x, g), y: snap(p.y, g) });
```

## 매 결정 기준
| 상황 | Approach |
|---|---|
| 1k+ shape hit-test | R-tree (rbush) |
| Static map polygons | Quadtree pre-built |
| Boolean ops on polygons | martinez-polygon-clipping |
| Hull / triangulation | d3-delaunay, earcut |
| Robust numerics | Shewchuk predicates |

**기본값**: bbox pre-filter → exact test. Spatial index 매 N>500.

## 🔗 Graph
- 부모: [[Algorithms]] · [[Graphics]]
- 변형: [[Computer-Graphics]] · [[GIS]]
- 응용: [[Canvas-API]] · [[SVG]] · [[WebGL]] · [[Map-Rendering]]
- Adjacent: [[Spatial-Indexing]] · [[Collision-Detection]]

## 🤖 LLM 활용
**언제**: canvas editor, map UI, drag-select, snapping, boolean ops on shapes.
**언제 X**: 매 trivial fixed UI — 매 CSS layout 으로 충분.

## ❌ 안티패턴
- **Naive O(N) hit-test on 10k shapes**: 매 lag — spatial index 필수.
- **No epsilon in cross product**: 매 collinear 매 wrong branch.
- **Re-building spatial tree per frame**: 매 only on data change, drag 매 incremental update.

## 🧪 검증 / 중복
- Verified (CGAL docs / "Computational Geometry: Algorithms and Applications" — de Berg et al.).
- 신뢰도 A.

## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — 2D geometry algorithms + spatial index patterns |
