def getSqSegDist(px, py, x, y, bx, by):
    """square distance from a point to a segment"""
    dx = bx - x
    dy = by - y
    if dx != 0 or dy != 0:
        t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy)
        if t > 1:
            x = bx
            y = by
        elif t > 0:
            x += dx * t
            y += dy * t
    dx = px - x
    dy = py - y
    return dx * dx + dy * dy
