Robot / llm_panda /geometry /math_utils.py
C2-151's picture
Done
00b6c5e
Raw History Blame Contribute Delete
2.14 kB
import math
def convex_hull(points):
"""2D convex hull (CCW) via Andrew's monotone chain. Returns ordered verts."""
pts = sorted(set((round(x, 5), round(y, 5)) for x, y in points))
if len(pts) <= 2:
return pts
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
lower = []
for p in pts:
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
upper = []
for p in reversed(pts):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
return lower[:-1] + upper[:-1]
def point_to_convex_distance(px, py, poly):
"""Distance from a point to a CCW convex polygon (0 if inside)."""
n = len(poly)
inside = True
min_d = float("inf")
for i in range(n):
ax, ay = poly[i]
bx, by = poly[(i + 1) % n]
if (bx - ax) * (py - ay) - (by - ay) * (px - ax) < 0:
inside = False
ex, ey = bx - ax, by - ay
seg_len2 = ex * ex + ey * ey
t = 0.0 if seg_len2 < 1e-12 else max(0.0, min(1.0, ((px - ax) * ex + (py - ay) * ey) / seg_len2))
dx, dy = px - (ax + t * ex), py - (ay + t * ey)
min_d = min(min_d, (dx * dx + dy * dy) ** 0.5)
return 0.0 if inside else min_d
def rasterize_footprint(grid, x_min, y_min, cell_x, cell_y, poly, margin, value):
"""Mark cells whose centre lies within ``margin`` of the convex polygon."""
ny, nx = grid.shape
pxs = [p[0] for p in poly]
pys = [p[1] for p in poly]
i0 = max(0, int(math.floor((min(pxs) - margin - x_min) / cell_x)))
i1 = min(nx, int(math.ceil((max(pxs) + margin - x_min) / cell_x)))
j0 = max(0, int(math.floor((min(pys) - margin - y_min) / cell_y)))
j1 = min(ny, int(math.ceil((max(pys) + margin - y_min) / cell_y)))
for j in range(j0, j1):
cyc = y_min + (j + 0.5) * cell_y
for i in range(i0, i1):
cxc = x_min + (i + 0.5) * cell_x
if point_to_convex_distance(cxc, cyc, poly) <= margin:
grid[j, i] = value