Algorithmadvanced
V-Clip
Also called Voronoi-clip algorithm.
A robust closest-feature algorithm for convex polyhedra that clips edges against Voronoi regions and also handles penetration.
- Time
- O(s (n + m)) callO(n m) moves_worstO(1) step
- Space
- O(1) extra
- Where
- m = the number of vertices of B; n = the number of vertices of A; s = the number of moves of one call
- Model
- Real RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Brian Mirtich, 1998
V-Clip finds the closest pair of features of two convex polyhedra, or reports that they penetrate. Like the Lin-Canny algorithm, it keeps a pair of features (vertices, edges or faces) and moves to a neighbor while a Voronoi region test fails, and it starts from the pair of the last time step. The difference is in the tests. V-Clip clips an edge against the Voronoi region of the other feature and uses the sign of the derivative of the distance at the clip points to choose the next feature. A vertex that lies behind a face goes to a special handler, which finds a closer face or reports penetration. The method needs no tolerances, and it cannot cycle.
In plain words
Two convex objects are near each other. Each corner, side and face owns a zone of space: the points that are closest to it. You keep one part of each object and check if each part sits in the zone of the other.
V-Clip cuts a side where it leaves the zone of the other part. At a cut point it asks: does the side come closer to the other part past the cut? If yes, the neighbor past that wall is a better part. If no, you are done.
If a corner is behind a face of the other object, it may be inside the object. Then V-Clip looks at all faces. If the corner is behind all of them, the objects overlap, and V-Clip says so.
The problem
The input is two convex polygons and with and vertices, strictly convex and counterclockwise, and a start pair of features. This page works in 2D: the features are vertices and closed edges, and each edge plays the role of a face of 3D, with the polygon behind it. The 1998 method is for convex polyhedra in 3D, with face states and clipping against face regions in addition. The output is either DISJOINT with a pair of features and points with , or PENETRATION with features that witness an intersection. Touching counts as penetration here. V-Clip does not compute a penetration depth; for that, use the expanding polytope algorithm.
The Voronoi region of a vertex is the wedge between the two lines through perpendicular to its edges. Each of the two planes (lines, in 2D) has the edge on its other side as its neighbor. The region of an edge is the half strip on its outer side. Its two end planes have the end vertices as neighbors, and its base plane, the line of , has the polygon behind it.
The algorithm
V-CLIP(A, B, fA, fB)- 1
loop - 2
if fA and fB are vertices a and b then - 3
if b violates a plane of VR(a) then fA ← the neighbor edge; continue - 4
if a violates a plane of VR(b) then fB ← the neighbor edge; continue - 5
if a = b then return PENETRATION(a, b) else return DISJOINT(a, b) - 6
if fA and fB are edges then - 7
if they intersect then return PENETRATION(fA, fB) - 8
replace the pair by the vertex-edge pair with the smallest end distance; continue - 9
let v be the vertex and e the edge, with e(λ) = e0 + λ(e1 - e0) - 10
if v is beyond an end plane of VR(e) then e ← the end vertex; continue - 11
if v is behind the line of e or on it then e ← HANDLE-LOCAL-MIN(v, polygon of e); continue - 12
clip e against the planes of VR(v): the interval [λl, λu] with the neighbors Nl, Nu - 13
if one plane excludes all of e then v ← the neighbor of that plane; continue - 14
if λl > λu then v ← the neighbor of a plane that the closest point of e to v violates; continue - 15
if Nl exists and D'(λl) > 0 then v ← Nl; continue - 16
if Nu exists and D'(λu) < 0 then v ← Nu; continue - 17
return DISJOINT(v, the closest point of e to v)
Here , so . If still decreases at the upper clip point , the closest point of to is past the clip, outside the wedge of , on the side of the plane . Line L13 is a simple exclusion and line L14 a compound exclusion, where each plane removes part of the edge and nothing is left. In 2D a compound exclusion means that each end of is outside a different plane.
HANDLE-LOCAL-MIN(v, Q)- 1
k ← the edge of Q with the largest signed distance to v - 2
if that distance ≤ 0 then return PENETRATION(v, Q) - 3
return k
The handler is the only step that looks at more than the neighbors. In 2D the edge with the largest signed distance holds the closest point of to when is outside . In 3D, Mirtich's handler does the same with the faces of the polyhedron.
Example
Use the polygons of the Lin-Canny example: is the rectangle , , , , and is the triangle , , . Edge goes from vertex to vertex , so of is the side and of is the segment from to . Start from the pair (, of ).
Move 1. The vertex passes the end planes of , with and , and it is on the outer side of . Line L12 clips against . The plane toward has direction , and goes from at to at , so it cuts at , with = edge of . The plane toward gives and , so it does not cut. At the point is , and . So line L16 fires: the distance still decreases past the cut, and . The feature distance drops from to 3.
Move 2. Now both features are edges. They do not meet. The four end distances are for , for , for and for , so line L8 goes to ( of , ). The feature distance stays 3, and the dimension drops.
Move 3. The vertex is in the half strip of of . Line L12 clips , from to , against . The plane toward has direction and values and at the ends, so it cuts at , the point . The plane toward does not cut. At the cut, , so the distance increases past the cut and line L16 does not fire. Line L17 returns DISJOINT with the vertex and the point of , at . The distance is 3, which a brute force over all vertex-edge pairs confirms.
From the start pair (, ), the walk takes 5 moves. At the state ( of , ) both ends of are outside the plane of toward , with values 20 and 17. This is a simple exclusion, and line L13 moves to the edge of .
Correctness
The proof is in proofs/correctness.md. It uses the same potential as for Lin-Canny: the distance between the two current features, and then the sum of their dimensions. The clip lemma says that the clipped interval is exactly the part of the edge in the Voronoi region of the vertex, and that the plane that sets is violated on all of . With the convexity of , the derivative tests at lines L15 and L16 fire exactly when the closest point of the edge to the vertex is outside the clipped interval, and then the neighbor of the plane is strictly closer. So every move lowers the potential, no state repeats, and the walk ends after at most moves for every input and every start pair, also when the polygons overlap. A DISJOINT answer has mutual closest points, so it is the distance. A PENETRATION answer has a witness: two edges that meet, or a vertex inside the other polygon.
Proof: The 2D V-Clip walk always terminates, with a closest pair of features or a witness of penetrationfull
Let and be strictly convex polygons with vertices in counterclockwise order, and use exact arithmetic. Features are vertices and closed edges. For a closed convex set , is the point of closest to . For an edge with direction and outward unit normal , , and for . Strict convexity gives on the polygon of , with equality only on .
The Voronoi region of a vertex with neighbors , is , two half-planes, each with the edge as its neighbor. The Voronoi region of an edge is .
We use four facts. Their proofs are on the page of the Lin-Canny algorithm, in its correctness proof.
- (F1) If , then for the polygon of .
- (F2) If and , then , and if .
- (F3) If maximizes over the edges of , then when , and when .
- (F4) If for a neighbor of the vertex , then the edge has a point closer to than .
Lemma 1 (the clip). Let be a vertex of and an edge of . For a plane of with direction , let , an affine function. CLIP returns:
- a plane with and (simple exclusion), if one exists; otherwise
- of the roots of over the planes with (or 0), with the plane that gives it, and of the roots over the planes with (or 1), with .
Then exactly for , and the plane is violated by for all , and for all .
Proof. Each half-plane meets the segment in an interval: if , if , if , and the empty set if both are positive. The intersection of the intervals of the two planes is when no plane excludes all. The plane that gives has and , so on by linearity. The same holds for .
Lemma 2 (the derivative tests). Let and , so . Then , and:
- if and , then ;
- if and , then ;
- if is not empty and neither test fires, then .
Proof. is a convex quadratic with , so it has one minimizer on , and before the unconstrained minimizer and after it. The first two claims follow. For the third, suppose . Then , and is increasing on , so unless is the unconstrained minimizer, which would give . So the first test fires, a contradiction. The case is symmetric.
The potential. As for Lin-Canny, let , let be the sum of the dimensions, and order lexicographically.
Lemma 3 (each move lowers the potential). Every move of lines L3, L4, L8, L10, L11, L13, L14, L15 and L16 gives a state with a smaller .
Proof.
- L3 and L4: by (F4), drops.
- L8: two disjoint segments have a closest pair with an end point of one of them (the squared distance is a convex quadratic on the parameter square whose minimum is on the boundary). So is unchanged and drops from 2 to 1.
- L10: if , then increases on and . So is unchanged and drops. The same holds for .
- L11: is in the slab of with . If HANDLE-LOCAL-MIN returns , then , so and by (F3) . Equality would put on at the foot of the perpendicular, with and , which has a positive dot product with for inner points of . This contradicts the projection property. So drops.
- L13: every point of violates the plane, in particular . By (F4) the new edge has a point closer to than , so drops.
- L14: the clipped interval is empty, so no point of is in , and violates some plane. By (F4), drops.
- L15 and L16: by Lemma 2, , and by Lemma 1 the plane is violated by . By (F4), drops. L16 is symmetric.
Theorem. V-CLIP ends after at most moves, for every input pair of strictly convex polygons and every start pair of features. If it returns DISJOINT, the returned points are a closest pair, they lie on the returned features, and their distance is . It returns PENETRATION exactly when , and then the returned features meet: two edges that intersect, or a vertex inside the other polygon, or two equal vertices.
Proof. By Lemma 3 no state repeats, and there are states.
L5 with : and , so by (F1) the points are mutual closest points, and (F2) gives the claim. With the return is PENETRATION with a common vertex.
L17: the vertex passed L10 and L11, so with , and by (F1) is the closest point of the polygon of to . By Lemma 2, with , so by Lemma 1, , and by (F1) is the closest point of its polygon to . By (F2) the answer is right, and .
L7 returns two edges that intersect. L19 returns a vertex with all signed distances , which is inside the other polygon by (F3). So every PENETRATION answer has a witness and is right. Conversely, if , then (F2) rules out a DISJOINT answer, and since the walk ends, it returns PENETRATION.
Remark. No step of the proof uses a tolerance. Each test is a sign of a polynomial in the input, with a strict or a weak inequality, and the proof holds for each choice that the code makes at a tie. This is the 2D form of the robustness claim of Mirtich (1998): the walk needs no tolerances and cannot cycle, also on degenerate input. In floating point a sign can be wrong, and then this proof does not apply. The implementation bounds the number of moves, so that it stops with an error instead of a loop.
Complexity
A move costs , except the handler of lines L18 to L20, which looks at all edges of one polygon. A call with moves costs in the worst case and without the handler. The proof bounds by . Under coherent motion a call takes few moves, and the handler is rare. This is an observed behavior, as for Lin-Canny, not a proved bound. The extra space is , plus the feature graph of each polytope.
Properties
- No tolerances. Each test is a sign of a dot product or cross product, and the proof holds for any choice at a tie. In 3D, Mirtich's method also has no tolerances. In his analysis, Lin-Canny needs tolerances and can cycle in degenerate cases.
- Penetration. The walk always ends, and it reports penetration with a witness instead of failing.
- Exact with exact input. With integer or rational coordinates the answer is exact, as the tests of this page check.
- The same interface as Lin-Canny. It needs the feature graph and returns closest features, which a simulator can use for contacts.
Variants and improvements
- 3D. The full method has the states vertex-vertex, vertex-edge, vertex-face, edge-edge and edge-face. Edges are clipped against vertex, edge and face regions, and the local minimum handler works on the face planes of the polyhedron.
- Nonconvex objects. Split each object into convex pieces, for example with approximate convex decomposition, and run V-Clip on the pairs of pieces that the broad phase reports.
- Penetration depth. V-Clip gives a witness but no depth. For the depth of convex objects, use the expanding polytope algorithm on the Minkowski difference.
- GJK. The GJK algorithm solves the same distance problem with a support function and no feature graph, and is the usual choice in game engines.
When to use it
Use V-Clip when you need exact closest features of convex polyhedra under coherent motion and the objects can touch or penetrate, for example in rigid body simulation with distance based contacts. Prefer it to Lin-Canny in all new code. Prefer GJK when the shapes are curved or given by support functions, or when you need the distance only.
Pitfalls
- The handler is not local. HANDLE-LOCAL-MIN looks at all faces. A version that only looks at the neighbors of can stop at a false local minimum behind a face.
- Wrong neighbors in the clip. Lines L15 and L16 must move to the neighbor of the plane that set or , not to any violated plane. Keep the plane with the clip value.
- The derivative at the ends. If because no plane cut the start, there is no and no test at that end. A test at an end that was not cut moves to a wrong feature.
- Touching. A distance of 0 is a contact. Decide if your simulator wants it as penetration or as distance 0, and keep the closest features in both cases.
- Orientation and convexity. As for Lin-Canny, clockwise input or collinear vertices break the regions. Clean the input once.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/v-clip/. The authors are listed in prov/D7J6QE.jsonl.
"""V-Clip for two convex polygons in the plane.
A polygon is a list of vertices in counterclockwise order, strictly convex. Its features are
the vertices ("v", i) and the edges ("e", i), where edge i goes from vertex i to vertex i + 1.
The walk is the one of Mirtich's V-Clip in 2D: in a vertex-edge state the edge is clipped
against the Voronoi region of the vertex, and the sign of the derivative of the distance at the
clip points chooses the next feature. A vertex behind an edge goes to the local minimum handler,
which either finds a closer edge or reports penetration. There are no tolerances: with integer or
Fraction input every test is exact, and the walk always ends, after at most (2n)(2m) moves.
The result is either "disjoint" with a closest pair of features and points, or "penetration"
with a pair of features that witness the intersection (touching counts as penetration).
"""
from __future__ import annotations
from dataclasses import dataclass
Feature = tuple[str, int]
@dataclass
class Result:
status: str # "disjoint" or "penetration"
fa: Feature | None # None for the whole polygon A
fb: Feature | None
dist2: object
pa: tuple | None
pb: tuple | None
steps: int
def _sub(p, q):
return (p[0] - q[0], p[1] - q[1])
def _dot(u, v):
return u[0] * v[0] + u[1] * v[1]
def _cross(u, v):
return u[0] * v[1] - u[1] * v[0]
def _point(e0, e1, t):
return (e0[0] + t * (e1[0] - e0[0]), e0[1] + t * (e1[1] - e0[1]))
def closest_on_segment(p, a, b):
d = _sub(b, a)
t = _dot(_sub(p, a), d) / _dot(d, d)
if t <= 0:
return a
if t >= 1:
return b
return _point(a, b, t)
def segments_intersect(p1, p2, q1, q2) -> bool:
d1 = _cross(_sub(q2, q1), _sub(p1, q1))
d2 = _cross(_sub(q2, q1), _sub(p2, q1))
d3 = _cross(_sub(p2, p1), _sub(q1, p1))
d4 = _cross(_sub(p2, p1), _sub(q2, p1))
if ((d1 > 0 > d2) or (d1 < 0 < d2)) and ((d3 > 0 > d4) or (d3 < 0 < d4)):
return True
def on(a, b, c):
return min(a[0], b[0]) <= c[0] <= max(a[0], b[0]) and min(a[1], b[1]) <= c[1] <= max(a[1], b[1])
return (
(d1 == 0 and on(q1, q2, p1))
or (d2 == 0 and on(q1, q2, p2))
or (d3 == 0 and on(p1, p2, q1))
or (d4 == 0 and on(p1, p2, q2))
)
def _vertex_planes(P, i):
"""The two planes of the Voronoi region of vertex i: (direction to the neighbor, edge index)."""
n = len(P)
a = P[i]
return [(_sub(P[i - 1], a), (i - 1) % n), (_sub(P[(i + 1) % n], a), i)]
def _vertex_violation(P, i, x):
for u, k in _vertex_planes(P, i):
if _dot(_sub(x, P[i]), u) > 0:
return k
return None
def _signed_key(P, k, x):
"""Has the sign and the order of the signed distance of x to the line of edge k."""
a, b = P[k], P[(k + 1) % len(P)]
d = _sub(b, a)
s = _cross(d, _sub(x, a))
return -s * abs(s) / _dot(d, d)
def handle_local_min(Q, v):
"""The edge of Q with the largest signed distance to v, or None if v is in Q."""
k = max(range(len(Q)), key=lambda k: _signed_key(Q, k, v)) # @line L18
if _signed_key(Q, k, v) <= 0: # @line L19
return None
return k # @line L20
def clip_edge(P, i, e0, e1):
"""Clip the segment e0e1 against the Voronoi region of vertex i of P.
Returns (lam_l, lam_u, n_l, n_u, simple) where n_l and n_u are the edges behind the
clipping planes (or None) and simple is the edge whose plane excludes the whole segment.
"""
lam_l, lam_u, n_l, n_u = 0, 1, None, None
a = P[i]
for u, k in _vertex_planes(P, i):
f0 = _dot(_sub(e0, a), u) # > 0 means outside this plane
f1 = _dot(_sub(e1, a), u)
if f0 > 0 and f1 > 0:
return lam_l, lam_u, n_l, n_u, k
if f0 > 0:
t = f0 / (f0 - f1)
if t > lam_l:
lam_l, n_l = t, k
elif f1 > 0:
t = f0 / (f0 - f1)
if t < lam_u:
lam_u, n_u = t, k
return lam_l, lam_u, n_l, n_u, None
def _vertex_edge(P, i, Q, j):
"""One step of the state (vertex i of P, edge j of Q). See V-CLIP lines L10 to L17."""
m = len(Q)
v = P[i]
e0, e1 = Q[j], Q[(j + 1) % m]
d = _sub(e1, e0)
if _dot(_sub(v, e0), d) < 0: # @line L10
return "edge", ("v", j)
if _dot(_sub(v, e1), d) > 0:
return "edge", ("v", (j + 1) % m)
if _cross(d, _sub(v, e0)) >= 0: # @line L11
k = handle_local_min(Q, v)
if k is None:
return "penetration", None
return "edge", ("e", k)
lam_l, lam_u, n_l, n_u, simple = clip_edge(P, i, e0, e1) # @line L12
if simple is not None: # @line L13
return "vertex", ("e", simple)
if lam_l > lam_u: # @line L14
return "vertex", ("e", _vertex_violation(P, i, closest_on_segment(v, e0, e1)))
if n_l is not None and _dot(_sub(_point(e0, e1, lam_l), v), d) > 0: # @line L15
return "vertex", ("e", n_l)
if n_u is not None and _dot(_sub(_point(e0, e1, lam_u), v), d) < 0: # @line L16
return "vertex", ("e", n_u)
return "done", closest_on_segment(v, e0, e1) # @line L17
def v_clip(A: list, B: list, fa: Feature = ("v", 0), fb: Feature = ("v", 0)) -> Result:
"""Walk from (fa, fb) to a closest pair of features, or to a witness of penetration."""
limit = 4 * len(A) * len(B) + 1
steps = 0
while True: # @line L1
steps += 1
if steps > limit:
raise RuntimeError("no progress; the input is not strictly convex and counterclockwise")
if fa[0] == "v" and fb[0] == "v": # @line L2
a, b = A[fa[1]], B[fb[1]]
k = _vertex_violation(A, fa[1], b) # @line L3
if k is not None:
fa = ("e", k)
continue
k = _vertex_violation(B, fb[1], a) # @line L4
if k is not None:
fb = ("e", k)
continue
d2 = _dot(_sub(a, b), _sub(a, b)) # @line L5
return Result("disjoint" if d2 > 0 else "penetration", fa, fb, d2, a, b, steps)
if fa[0] == "e" and fb[0] == "e": # @line L6
i, j = fa[1], fb[1]
a0, a1 = A[i], A[(i + 1) % len(A)]
b0, b1 = B[j], B[(j + 1) % len(B)]
if segments_intersect(a0, a1, b0, b1): # @line L7
return Result("penetration", fa, fb, 0, None, None, steps)
cands = [] # @line L8
for k, p in ((i, a0), ((i + 1) % len(A), a1)):
c = closest_on_segment(p, b0, b1)
cands.append((_dot(_sub(p, c), _sub(p, c)), ("v", k), fb))
for k, p in ((j, b0), ((j + 1) % len(B), b1)):
c = closest_on_segment(p, a0, a1)
cands.append((_dot(_sub(p, c), _sub(p, c)), fa, ("v", k)))
_, fa, fb = cands[min(range(4), key=lambda t: cands[t][0])]
continue
vertex_is_a = fa[0] == "v" # @line L9
if vertex_is_a:
kind, f = _vertex_edge(A, fa[1], B, fb[1])
else:
kind, f = _vertex_edge(B, fb[1], A, fa[1])
if kind == "penetration":
if vertex_is_a:
return Result("penetration", fa, None, 0, None, None, steps)
return Result("penetration", None, fb, 0, None, None, steps)
if kind == "done":
if vertex_is_a:
pa, pb = A[fa[1]], f
else:
pa, pb = f, B[fb[1]]
return Result("disjoint", fa, fb, _dot(_sub(pa, pb), _sub(pa, pb)), pa, pb, steps)
if (kind == "edge") == vertex_is_a: # the edge side is B when the vertex is in A
fb = f
else:
fa = f
test_v_clip.py 179 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/v-clip/. The authors are listed in prov/D7J6QE.jsonl.
import random
from fractions import Fraction
from v_clip import clip_edge, closest_on_segment, handle_local_min, segments_intersect, v_clip
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def hull(points):
pts = sorted(set(points))
if len(pts) < 3:
return pts
lower, upper = [], []
for p in pts:
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
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 random_polygon(rng, cx, cy, r):
while True:
pts = [(cx + rng.randint(-r, r), cy + rng.randint(-r, r)) for _ in range(rng.randint(3, 9))]
h = hull(pts)
if len(h) >= 3:
return [(Fraction(x), Fraction(y)) for x, y in h]
def d2(p, q):
return (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2
def inside(P, x):
return all(cross(P[i], P[(i + 1) % len(P)], x) >= 0 for i in range(len(P)))
def brute(A, B):
for i in range(len(A)):
for j in range(len(B)):
if segments_intersect(A[i], A[(i + 1) % len(A)], B[j], B[(j + 1) % len(B)]):
return True, 0
if inside(B, A[0]) or inside(A, B[0]):
return True, 0
best = None
for P, Q in ((A, B), (B, A)):
for p in P:
for k in range(len(Q)):
v = d2(p, closest_on_segment(p, Q[k], Q[(k + 1) % len(Q)]))
best = v if best is None or v < best else best
return False, best
def points_of(P, f):
if f[0] == "v":
return [P[f[1]]]
return [P[f[1]], P[(f[1] + 1) % len(P)]]
def on_feature(P, f, x):
pts = points_of(P, f)
if len(pts) == 1:
return x == pts[0]
return closest_on_segment(x, pts[0], pts[1]) == x
def F(x, y):
return (Fraction(x), Fraction(y))
def page_example():
A = [F(0, 0), F(4, 0), F(4, 3), F(0, 3)]
B = [F(7, 1), F(10, 2), F(8, 5)]
return A, B
def test_clip_of_the_page_example():
A, B = page_example()
# edge e2 of B against VR(a2): clipped to [0, 1/2] by the plane of edge e1 of A
assert clip_edge(A, 2, B[2], B[0]) == (0, Fraction(1, 2), None, 1, None)
# edge e1 of A against VR(b0): clipped to [0, 7/12] by the plane of edge e2 of B
assert clip_edge(B, 0, A[1], A[2]) == (0, Fraction(7, 12), None, 2, None)
# edge e1 of A against VR(b1): excluded by the plane of edge e0 of B
assert clip_edge(B, 1, A[1], A[2])[4] == 0
def test_page_example():
A, B = page_example()
res = v_clip(A, B, ("v", 2), ("e", 2))
assert res.status == "disjoint"
assert res.dist2 == 9
assert (res.fa, res.fb) == (("e", 1), ("v", 0))
assert res.pa == F(4, 1) and res.pb == F(7, 1)
assert res.steps == 3
assert v_clip(A, B, ("v", 0), ("v", 1)).steps == 5
def test_penetration_is_reported():
A = [F(0, 0), F(4, 0), F(4, 4), F(0, 4)]
B = [F(1, 1), F(2, 1), F(2, 2)]
for fa in [("v", k) for k in range(4)] + [("e", k) for k in range(4)]:
for fb in [("v", k) for k in range(3)] + [("e", k) for k in range(3)]:
res = v_clip(A, B, fa, fb)
assert res.status == "penetration"
assert handle_local_min(A, F(1, 1)) is None
assert handle_local_min(A, F(5, 1)) == 1
crossing = [F(3, -1), F(6, 2), F(3, 2)]
assert v_clip(A, crossing).status == "penetration"
touching = [F(4, 4), F(6, 5), F(5, 6)] # a common vertex
assert v_clip(A, touching).status == "penetration"
def test_degenerate_but_disjoint_configurations():
sq = [F(0, 0), F(2, 0), F(2, 2), F(0, 2)]
for other in (
[F(4, 0), F(6, 0), F(6, 2), F(4, 2)], # parallel faces
[F(4, 2), F(6, 4), F(4, 4)], # vertex on the boundary of a vertex region
[F(3, 3), F(5, 3), F(5, 5), F(3, 5)], # vertex-vertex
[F(1, 4), F(3, 4), F(2, 6)], # parallel edges that overlap in part
):
hit, dist = brute(sq, other)
assert not hit
for fa in [("v", k) for k in range(4)] + [("e", k) for k in range(4)]:
for fb in [("v", k) for k in range(len(other))] + [("e", k) for k in range(len(other))]:
res = v_clip(sq, other, fa, fb)
assert res.status == "disjoint" and res.dist2 == dist
def test_random_pairs_against_brute_force():
rng = random.Random(1998)
disjoint = 0
for _ in range(700):
A = random_polygon(rng, 0, 0, 6)
B = random_polygon(rng, rng.randint(-14, 14), rng.randint(-14, 14), 6)
hit, dist = brute(A, B)
fa = (rng.choice("ve"), rng.randrange(len(A)))
fb = (rng.choice("ve"), rng.randrange(len(B)))
res = v_clip(A, B, fa, fb)
assert (res.status == "penetration") == hit
if not hit:
disjoint += 1
assert res.dist2 == dist == d2(res.pa, res.pb)
assert on_feature(A, res.fa, res.pa) and on_feature(B, res.fb, res.pb)
else:
# the witness features really meet the other polygon
if res.fa is not None and res.fb is not None and res.fa[0] == "e" and res.fb[0] == "e":
pa, pb = points_of(A, res.fa), points_of(B, res.fb)
assert segments_intersect(pa[0], pa[1], pb[0], pb[1])
elif res.fb is None:
assert inside(B, A[res.fa[1]])
elif res.fa is None:
assert inside(A, B[res.fb[1]])
assert disjoint >= 300
def test_coherent_motion():
rng = random.Random(3)
A = random_polygon(rng, 0, 0, 5)
B0 = random_polygon(rng, 0, 0, 3)
fa, fb = ("v", 0), ("v", 0)
for step in range(120):
ox, oy = Fraction(30 - step, 4), Fraction(step % 7, 3)
B = [(x + ox, y + oy) for x, y in B0]
hit, dist = brute(A, B)
res = v_clip(A, B, fa, fb)
assert (res.status == "penetration") == hit
if not hit:
assert res.dist2 == dist
fa, fb = res.fa, res.fb
else:
fa, fb = ("v", 0), ("v", 0)
History
Mirtich developed V-Clip at MERL and published it as a technical report in 1997 and in ACM Transactions on Graphics in 1998. He kept the closest feature walk of Lin and Canny (1991) but replaced its point tests by the clipping of edges against Voronoi regions, added the derivative checks and the local minimum handler, and showed that the walk needs no tolerances and terminates also for penetrating objects. Later engines mostly moved to GJK, which needs no feature graph, but V-Clip remains the standard example of a robust closest feature walk.
References
- Brian Mirtich, V-Clip, fast and robust polyhedral collision detection, ACM Transactions on Graphics 17(3), 1998, 177 to 208, the feature states, the clipping of edges against Voronoi regions, the derivative checks, the local minimum handler, and the termination and robustness claims
- Ming C. Lin and John F. Canny, A fast algorithm for incremental distance calculation, Proceedings of the 1991 IEEE International Conference on Robotics and Automation, 1008 to 1014, the closest feature walk that V-Clip refines
- Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann, 2005, Chapter 9, Convex-based Methods (the closest-features algorithms and V-Clip)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag D7J6QE Edit this page History Report an error Markdown