| 22 | } |
| 23 | |
| 24 | export function findNearest( |
| 25 | placed: PlacedPoint[], |
| 26 | grid: Map<string, number[]>, |
| 27 | bx: number, |
| 28 | by: number, |
| 29 | radius: number, |
| 30 | ): PlacedPoint | null { |
| 31 | const c0 = Math.floor((bx - radius) / GRID_CELL); |
| 32 | const c1 = Math.floor((bx + radius) / GRID_CELL); |
| 33 | const r0 = Math.floor((by - radius) / GRID_CELL); |
| 34 | const r1 = Math.floor((by + radius) / GRID_CELL); |
| 35 | let best: PlacedPoint | null = null; |
| 36 | let bestD = radius * radius; |
| 37 | for (let cx = c0; cx <= c1; cx++) { |
| 38 | for (let cy = r0; cy <= r1; cy++) { |
| 39 | const cell = grid.get(`${cx},${cy}`); |
| 40 | if (!cell) continue; |
| 41 | for (const i of cell) { |
| 42 | const p = placed[i]; |
| 43 | const dx = p.x - bx; |
| 44 | const dy = p.y - by; |
| 45 | const d = dx * dx + dy * dy; |
| 46 | if (d <= bestD) { |
| 47 | bestD = d; |
| 48 | best = p; |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | return best; |
| 54 | } |