class_name Pathfinding extends RefCounted # Fixed ordering is part of the replay contract: equal-length routes always # resolve identically without consuming random state. const CARDINAL_DIRECTIONS: Array[Vector2i] = [Vector2i.LEFT, Vector2i.DOWN, Vector2i.RIGHT, Vector2i.UP] static func find_path(map: GridMapState, start: Vector2i, goal: Vector2i, blocked_cells: Dictionary = {}) -> Array[Vector2i]: return find_path_to_any(map, start, [goal], blocked_cells) static func find_path_to_any(map: GridMapState, start: Vector2i, goals: Array[Vector2i], blocked_cells: Dictionary = {}) -> Array[Vector2i]: var goal_cells: Dictionary[Vector2i, bool] = {} for goal in goals: goal_cells[goal] = true if goal_cells.has(start): return [] var frontier: Array[Vector2i] = [start] var previous: Dictionary[Vector2i, Vector2i] = {start: start} while not frontier.is_empty(): var current: Vector2i = frontier.pop_front() for direction: Vector2i in CARDINAL_DIRECTIONS: var next_cell: Vector2i = current + direction if previous.has(next_cell) or not map.is_walkable(next_cell) or blocked_cells.has(next_cell): continue previous[next_cell] = current if goal_cells.has(next_cell): return _reconstruct_path(previous, start, next_cell) frontier.append(next_cell) return [] static func has_line_of_sight(map: GridMapState, origin: Vector2i, target: Vector2i) -> bool: var current := origin var delta_x: int = abs(target.x - origin.x) var step_x: int = 1 if origin.x < target.x else -1 var delta_y: int = -abs(target.y - origin.y) var step_y: int = 1 if origin.y < target.y else -1 var error: int = delta_x + delta_y while current != target: var doubled_error: int = 2 * error if doubled_error >= delta_y: error += delta_y current.x += step_x if doubled_error <= delta_x: error += delta_x current.y += step_y if current != target and map.is_opaque(current): return false return true static func _reconstruct_path(previous: Dictionary[Vector2i, Vector2i], start: Vector2i, goal: Vector2i) -> Array[Vector2i]: var reversed: Array[Vector2i] = [] var current := goal while current != start: reversed.append(current) current = previous[current] reversed.reverse() return reversed