import { axialToPixel, hexDistance, hexLine, type AxialCoord, type HexCell, type PixelCoord, } from "./hex.ts"; export type ConnectorRoutingMode = "straight" | "axial" | "obstacle-aware"; export type ConnectorRoutingStatus = "routed" | "fallback"; export interface ConnectorRoutingOptions { mode: ConnectorRoutingMode; cells: Pick[]; from: AxialCoord; to: AxialCoord; radius: number; blocked?: AxialCoord[]; offset?: PixelCoord; bendPenalty?: number; proximityPenalty?: number; maxVisited?: number; } export interface RoutedConnector { mode: ConnectorRoutingMode; status: ConnectorRoutingStatus; cells: AxialCoord[]; waypoints: AxialCoord[]; points: PixelCoord[]; d: string; bends: number; visited: number; } interface SearchState extends AxialCoord { direction: number; g: number; h: number; bends: number; } const AXIAL_DIRECTIONS: readonly AxialCoord[] = [ { q: 1, r: 0 }, { q: 1, r: -1 }, { q: 0, r: -1 }, { q: -1, r: 0 }, { q: -1, r: 1 }, { q: 0, r: 1 }, ]; function coordinateKey(coordinate: AxialCoord) { return `${coordinate.q},${coordinate.r}`; } function stateKey(coordinate: AxialCoord, direction: number) { return `${coordinateKey(coordinate)}:${direction}`; } function directionBetween(from: AxialCoord, to: AxialCoord) { const q = to.q - from.q; const r = to.r - from.r; return AXIAL_DIRECTIONS.findIndex( (direction) => direction.q === q && direction.r === r, ); } function countBends(coordinates: AxialCoord[]) { let bends = 0; let previousDirection = -1; for (let index = 1; index < coordinates.length; index += 1) { const direction = directionBetween(coordinates[index - 1], coordinates[index]); if (previousDirection >= 0 && direction !== previousDirection) bends += 1; previousDirection = direction; } return bends; } export function compressConnectorRoute(coordinates: AxialCoord[]) { if (coordinates.length <= 2) return [...coordinates]; const waypoints = [coordinates[0]]; let previousDirection = directionBetween(coordinates[0], coordinates[1]); for (let index = 2; index < coordinates.length; index += 1) { const direction = directionBetween(coordinates[index - 1], coordinates[index]); if (direction !== previousDirection) { waypoints.push(coordinates[index - 1]); previousDirection = direction; } } waypoints.push(coordinates[coordinates.length - 1]); return waypoints; } function pointsToPath(points: PixelCoord[]) { return points .map( (point, index) => `${index === 0 ? "M" : "L"} ${point.x.toFixed(3)} ${point.y.toFixed(3)}`, ) .join(" "); } function createRouteResult( mode: ConnectorRoutingMode, status: ConnectorRoutingStatus, cells: AxialCoord[], radius: number, offset: PixelCoord, visited: number, ): RoutedConnector { const waypoints = compressConnectorRoute(cells); const points = waypoints.map((coordinate) => axialToPixel(coordinate, radius, offset), ); return { mode, status, cells, waypoints, points, d: pointsToPath(points), bends: countBends(cells), visited, }; } function reconstructRoute( finalKey: string, states: Map, previous: Map, ) { const coordinates: AxialCoord[] = []; let key: string | undefined = finalKey; while (key) { const state = states.get(key); if (!state) break; coordinates.push({ q: state.q, r: state.r }); key = previous.get(key); } return coordinates.reverse(); } function compareSearchStates(first: SearchState, second: SearchState) { const firstScore = first.g + first.h; const secondScore = second.g + second.h; if (firstScore !== secondScore) return firstScore - secondScore; if (first.h !== second.h) return first.h - second.h; if (first.bends !== second.bends) return first.bends - second.bends; if (first.q !== second.q) return first.q - second.q; if (first.r !== second.r) return first.r - second.r; return first.direction - second.direction; } function obstacleProximity( coordinate: AxialCoord, blocked: Set, ) { return AXIAL_DIRECTIONS.reduce((count, direction) => { const neighbor = { q: coordinate.q + direction.q, r: coordinate.r + direction.r, }; return count + (blocked.has(coordinateKey(neighbor)) ? 1 : 0); }, 0); } function findObstacleAwareRoute({ cells, from, to, blocked = [], bendPenalty = 0.35, proximityPenalty = 0.18, maxVisited = 5000, }: Pick< ConnectorRoutingOptions, | "cells" | "from" | "to" | "blocked" | "bendPenalty" | "proximityPenalty" | "maxVisited" >) { const allowed = new Set(cells.map((cell) => coordinateKey(cell))); const blockedKeys = new Set(blocked.map((coordinate) => coordinateKey(coordinate))); blockedKeys.delete(coordinateKey(from)); blockedKeys.delete(coordinateKey(to)); if (!allowed.has(coordinateKey(from)) || !allowed.has(coordinateKey(to))) { return { coordinates: null, visited: 0 }; } const start: SearchState = { ...from, direction: -1, g: 0, h: hexDistance(from, to), bends: 0, }; const open = [start]; const states = new Map([[stateKey(start, start.direction), start]]); const previous = new Map(); const bestCost = new Map([[stateKey(start, start.direction), 0]]); let visited = 0; while (open.length > 0 && visited < maxVisited) { open.sort(compareSearchStates); const current = open.shift(); if (!current) break; visited += 1; if (current.q === to.q && current.r === to.r) { return { coordinates: reconstructRoute( stateKey(current, current.direction), states, previous, ), visited, }; } for (let direction = 0; direction < AXIAL_DIRECTIONS.length; direction += 1) { const step = AXIAL_DIRECTIONS[direction]; const next = { q: current.q + step.q, r: current.r + step.r }; const nextCoordinateKey = coordinateKey(next); if (!allowed.has(nextCoordinateKey) || blockedKeys.has(nextCoordinateKey)) { continue; } const changedDirection = current.direction >= 0 && current.direction !== direction; const bends = current.bends + (changedDirection ? 1 : 0); const g = current.g + 1 + (changedDirection ? bendPenalty : 0) + obstacleProximity(next, blockedKeys) * proximityPenalty; const nextState: SearchState = { ...next, direction, g, h: hexDistance(next, to), bends, }; const nextStateKey = stateKey(nextState, direction); if (g >= (bestCost.get(nextStateKey) ?? Number.POSITIVE_INFINITY)) { continue; } bestCost.set(nextStateKey, g); states.set(nextStateKey, nextState); previous.set(nextStateKey, stateKey(current, current.direction)); open.push(nextState); } } return { coordinates: null, visited }; } export function routeConnector(options: ConnectorRoutingOptions): RoutedConnector { const offset = options.offset ?? { x: 0, y: 0 }; if (options.mode === "straight") { return createRouteResult( options.mode, "routed", [options.from, options.to], options.radius, offset, 0, ); } if (options.mode === "axial") { return createRouteResult( options.mode, "routed", hexLine(options.from, options.to), options.radius, offset, 0, ); } const result = findObstacleAwareRoute(options); const coordinates = result.coordinates ?? hexLine(options.from, options.to); return createRouteResult( options.mode, result.coordinates ? "routed" : "fallback", coordinates, options.radius, offset, result.visited, ); }