inire/inire/router/visibility.py
Jan Petykiewicz a6b0b9216a Query exact corner visibility on demand
Cache local queries at indexed corners and preserve exact distance limits. Keep the legacy counters available and report corner-index builds in the performance summary.
2026-11-29 16:37:41 -08:00

178 lines
6.9 KiB
Python

from __future__ import annotations
from math import hypot
from typing import TYPE_CHECKING
import rtree
if TYPE_CHECKING:
from inire.geometry.collision import RoutingWorld
from inire.geometry.primitives import Port
class VisibilityManager:
"""Index static obstacle corners and query them for sparse A* moves."""
__slots__ = (
"collision_engine",
"corners",
"_exact_corners",
"corner_index",
"_point_visibility_cache",
"_corner_index_version",
)
def __init__(self, collision_engine: RoutingWorld) -> None:
self.collision_engine = collision_engine
self.corners: list[tuple[float, float]] = []
self._exact_corners: list[tuple[float, float]] = []
self.corner_index = rtree.index.Index()
self._point_visibility_cache: dict[tuple[float, float, float], list[tuple[float, float, float]]] = {}
self._corner_index_version = -1
def clear_cache(self) -> None:
"""
Reset all static visibility data.
"""
self.corners = []
self._exact_corners = []
self.corner_index = rtree.index.Index()
self._point_visibility_cache = {}
self._corner_index_version = -1
def ensure_corner_index_current(self) -> None:
if self._corner_index_version != self.collision_engine.get_static_version():
self._build_corner_index()
def _build_corner_index(self) -> None:
if self.collision_engine.metrics is not None:
self.collision_engine.metrics.total_visibility_corner_index_builds += 1
self.corners = []
self._exact_corners = []
self.corner_index = rtree.index.Index()
self._point_visibility_cache = {}
self._corner_index_version = self.collision_engine.get_static_version()
raw_corners = []
for poly in self.collision_engine.iter_static_dilated_geometries():
coords = list(poly.exterior.coords)
if coords[0] == coords[-1]:
coords = coords[:-1]
raw_corners.extend(coords)
for ring in poly.interiors:
coords = list(ring.coords)
if coords[0] == coords[-1]:
coords = coords[:-1]
raw_corners.extend(coords)
if not raw_corners:
return
seen = set()
for x, y in raw_corners:
sx, sy = round(x, 3), round(y, 3)
if (sx, sy) not in seen:
seen.add((sx, sy))
self.corners.append((sx, sy))
self._exact_corners.append((x, y))
for i, (x, y) in enumerate(self.corners):
self.corner_index.insert(i, (x, y, x, y))
def _corner_idx_at(self, origin: Port) -> int | None:
self.ensure_corner_index_current()
ox, oy = round(origin.x, 3), round(origin.y, 3)
nearby = list(self.corner_index.intersection((ox - 0.001, oy - 0.001, ox + 0.001, oy + 0.001)))
for idx in nearby:
cx, cy = self.corners[idx]
if abs(cx - ox) < 1e-4 and abs(cy - oy) < 1e-4:
return idx
return None
def get_tangent_corner_candidates(
self,
origin: Port,
*,
min_forward: float,
max_forward: float,
radii: tuple[float, ...],
tolerance: float = 2.0,
) -> list[int]:
self.ensure_corner_index_current()
if max_forward <= min_forward or not radii or not self.corners:
return []
candidate_ids: set[int] = set()
x0 = float(origin.x)
y0 = float(origin.y)
def _add_hits(bounds: tuple[float, float, float, float]) -> None:
min_x, min_y, max_x, max_y = bounds
if min_x > max_x or min_y > max_y:
return
candidate_ids.update(self.corner_index.intersection(bounds))
for radius in radii:
if origin.r == 0:
x_bounds = (x0 + min_forward, x0 + max_forward)
_add_hits((x_bounds[0], y0 + radius - tolerance, x_bounds[1], y0 + radius + tolerance))
_add_hits((x_bounds[0], y0 - radius - tolerance, x_bounds[1], y0 - radius + tolerance))
elif origin.r == 180:
x_bounds = (x0 - max_forward, x0 - min_forward)
_add_hits((x_bounds[0], y0 + radius - tolerance, x_bounds[1], y0 + radius + tolerance))
_add_hits((x_bounds[0], y0 - radius - tolerance, x_bounds[1], y0 - radius + tolerance))
elif origin.r == 90:
y_bounds = (y0 + min_forward, y0 + max_forward)
_add_hits((x0 + radius - tolerance, y_bounds[0], x0 + radius + tolerance, y_bounds[1]))
_add_hits((x0 - radius - tolerance, y_bounds[0], x0 - radius + tolerance, y_bounds[1]))
else:
y_bounds = (y0 - max_forward, y0 - min_forward)
_add_hits((x0 + radius - tolerance, y_bounds[0], x0 + radius + tolerance, y_bounds[1]))
_add_hits((x0 - radius - tolerance, y_bounds[0], x0 - radius + tolerance, y_bounds[1]))
return sorted(candidate_ids)
def get_corner_visibility(self, origin: Port, max_dist: float = 1000.0) -> list[tuple[float, float, float]]:
"""Return visible neighbors when the origin is at an indexed corner."""
metrics = self.collision_engine.metrics
if metrics is not None:
metrics.total_visibility_corner_queries_exact += 1
if max_dist < 0:
return []
corner_idx = self._corner_idx_at(origin)
if corner_idx is None:
return []
if metrics is not None:
metrics.total_visibility_corner_hits_exact += 1
metrics.total_visibility_point_queries += 1
start = self._exact_corners[corner_idx]
cache_key = (*start, max_dist)
if cache_key in self._point_visibility_cache:
if metrics is not None:
metrics.total_visibility_point_cache_hits += 1
return self._point_visibility_cache[cache_key]
if metrics is not None:
metrics.total_visibility_point_cache_misses += 1
# The index stores rounded corner coordinates. Filter by exact distance below.
reach = max_dist + 0.001
x, y = start
bounds = (x - reach, y - reach, x + reach, y + reach)
candidates = sorted(self.corner_index.intersection(bounds))
visible = []
for i in candidates:
end = self._exact_corners[i]
dist = hypot(end[0] - x, end[1] - y)
if dist == 0 or dist > max_dist:
continue
if self.collision_engine.corner_segment_visible(start, end):
cx, cy = self.corners[i]
visible.append((cx, cy, dist))
if len(self._point_visibility_cache) >= 4096:
self._point_visibility_cache.clear()
self._point_visibility_cache[cache_key] = visible
return visible