Algorithm Search⌘K

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
Properties
deterministicexactonlineiterative
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 AA and BB with nn and mm 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 p,qp, q with ∣p−q∣=d(A,B)>0|p - q| = d(A, B) > 0, 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 vv is the wedge between the two lines through vv 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 e=[e0,e1]e = [e_0, e_1] 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 ee, has the polygon behind it.

The algorithm

  1. V-CLIP(A, B, fA, fB)
  2. 1loop
  3. 2if fA and fB are vertices a and b then
  4. 3if b violates a plane of VR(a) then fA ← the neighbor edge; continue
  5. 4if a violates a plane of VR(b) then fB ← the neighbor edge; continue
  6. 5if a = b then return PENETRATION(a, b) else return DISJOINT(a, b)
  7. 6if fA and fB are edges then
  8. 7if they intersect then return PENETRATION(fA, fB)
  9. 8replace the pair by the vertex-edge pair with the smallest end distance; continue
  10. 9let v be the vertex and e the edge, with e(λ) = e0 + λ(e1 - e0)
  11. 10if v is beyond an end plane of VR(e) then e ← the end vertex; continue
  12. 11if v is behind the line of e or on it then e ← HANDLE-LOCAL-MIN(v, polygon of e); continue
  13. 12clip e against the planes of VR(v): the interval [λl, λu] with the neighbors Nl, Nu
  14. 13if one plane excludes all of e then v ← the neighbor of that plane; continue
  15. 14if λl > λu then v ← the neighbor of a plane that the closest point of e to v violates; continue
  16. 15if Nl exists and D'(λl) > 0 then v ← Nl; continue
  17. 16if Nu exists and D'(λu) < 0 then v ← Nu; continue
  18. 17return DISJOINT(v, the closest point of e to v)

Here D(λ)=∣e(λ)−v∣2D(\lambda) = |e(\lambda) - v|^2, so D′(λ)=2(e(λ)−v)⋅(e1−e0)D'(\lambda) = 2 (e(\lambda) - v) \cdot (e_1 - e_0). If DD still decreases at the upper clip point λu\lambda_u, the closest point of ee to vv is past the clip, outside the wedge of vv, on the side of the plane NuN_u. 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 ee is outside a different plane.

  1. HANDLE-LOCAL-MIN(v, Q)
  2. 1k ← the edge of Q with the largest signed distance to v
  3. 2if that distance ≤ 0 then return PENETRATION(v, Q)
  4. 3return 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 QQ to vv when vv is outside QQ. In 3D, Mirtich's handler does the same with the faces of the polyhedron.

Example

Use the polygons of the Lin-Canny example: AA is the rectangle a0=(0,0)a_0 = (0, 0), a1=(4,0)a_1 = (4, 0), a2=(4,3)a_2 = (4, 3), a3=(0,3)a_3 = (0, 3), and BB is the triangle b0=(7,1)b_0 = (7, 1), b1=(10,2)b_1 = (10, 2), b2=(8,5)b_2 = (8, 5). Edge ii goes from vertex ii to vertex i+1i + 1, so e1e_1 of AA is the side x=4x = 4 and e2e_2 of BB is the segment from b2b_2 to b0b_0. Start from the pair (a2a_2, e2e_2 of BB).

Move 1. The vertex a2=(4,3)a_2 = (4, 3) passes the end planes of VR(e2)VR(e_2), with (a2−b2)⋅(b0−b2)=12≥0(a_2 - b_2) \cdot (b_0 - b_2) = 12 \ge 0 and (a2−b0)⋅(b0−b2)=−5≤0(a_2 - b_0) \cdot (b_0 - b_2) = -5 \le 0, and it is on the outer side of e2e_2. Line L12 clips e2e_2 against VR(a2)VR(a_2). The plane toward a1a_1 has direction u=a1−a2=(0,−3)u = a_1 - a_2 = (0, -3), and f(λ)=(e2(λ)−a2)⋅uf(\lambda) = (e_2(\lambda) - a_2) \cdot u goes from −6-6 at λ=0\lambda = 0 to 66 at λ=1\lambda = 1, so it cuts at λu=1/2\lambda_u = 1/2, with NuN_u = edge e1e_1 of AA. The plane toward a3a_3 gives −16-16 and −12-12, so it does not cut. At λu=1/2\lambda_u = 1/2 the point is (7.5,3)(7.5, 3), and D′(1/2)=2 (3.5,0)⋅(−1,−4)=−7<0D'(1/2) = 2\,(3.5, 0) \cdot (-1, -4) = -7 < 0. So line L16 fires: the distance still decreases past the cut, and fA←e1f_A \leftarrow e_1. The feature distance drops from 14/17≈3.4014/\sqrt{17} \approx 3.40 to 3.

Move 2. Now both features are edges. They do not meet. The four end distances are 10\sqrt{10} for a1a_1, 196/17≈3.40\sqrt{196/17} \approx 3.40 for a2a_2, 20\sqrt{20} for b2b_2 and 33 for b0b_0, so line L8 goes to (e1e_1 of AA, b0b_0). The feature distance stays 3, and the dimension drops.

Move 3. The vertex b0=(7,1)b_0 = (7, 1) is in the half strip of e1e_1 of AA. Line L12 clips e1e_1, from (4,0)(4, 0) to (4,3)(4, 3), against VR(b0)VR(b_0). The plane toward b2b_2 has direction (1,4)(1, 4) and values −7-7 and 55 at the ends, so it cuts at λu=7/12\lambda_u = 7/12, the point (4,7/4)(4, 7/4). The plane toward b1b_1 does not cut. At the cut, D′(7/12)=2 (−3,3/4)⋅(0,3)=9/2>0D'(7/12) = 2\,(-3, 3/4) \cdot (0, 3) = 9/2 > 0, so the distance increases past the cut and line L16 does not fire. Line L17 returns DISJOINT with the vertex (7,1)(7, 1) and the point (4,1)(4, 1) of e1e_1, at λ=1/3∈[0,7/12]\lambda = 1/3 \in [0, 7/12]. The distance is 3, which a brute force over all vertex-edge pairs confirms.

From the start pair (a0a_0, b1b_1), the walk takes 5 moves. At the state (e1e_1 of AA, b1b_1) both ends of e1e_1 are outside the plane of VR(b1)VR(b_1) toward b0b_0, with values 20 and 17. This is a simple exclusion, and line L13 moves b1b_1 to the edge e0e_0 of BB.

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 λl\lambda_l is violated on all of [0,λl)[0, \lambda_l). With the convexity of DD, 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 4nm4nm 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 AA and BB be strictly convex polygons with vertices in counterclockwise order, and use exact arithmetic. Features are vertices and closed edges. For a closed convex set CC, πC(x)\pi_C(x) is the point of CC closest to xx. For an edge e=[e0,e1]e = [e_0, e_1] with direction d=e1−e0d = e_1 - e_0 and outward unit normal nen_e, se(x)=ne⋅(x−e0)s_e(x) = n_e \cdot (x - e_0), and e(λ)=e0+λde(\lambda) = e_0 + \lambda d for λ∈[0,1]\lambda \in [0, 1]. Strict convexity gives se(y)≤0s_e(y) \le 0 on the polygon of ee, with equality only on ee.

The Voronoi region of a vertex aa with neighbors a−a^-, a+a^+ is VR(a)={x:(x−a)⋅(a±−a)≤0}VR(a) = \{x : (x - a) \cdot (a^\pm - a) \le 0\}, two half-planes, each with the edge [a,a±][a, a^\pm] as its neighbor. The Voronoi region of an edge is VR(e)={x:(x−e0)⋅d≥0, (x−e1)⋅d≤0, se(x)≥0}VR(e) = \{x : (x - e_0) \cdot d \ge 0,\ (x - e_1) \cdot d \le 0,\ s_e(x) \ge 0\}.

We use four facts. Their proofs are on the page of the Lin-Canny algorithm, in its correctness proof.

  • (F1) If x∈VR(f)x \in VR(f), then πP(x)=πf(x)\pi_P(x) = \pi_f(x) for the polygon PP of ff.
  • (F2) If p=πA(q)p = \pi_A(q) and q=πB(p)q = \pi_B(p), then ∣p−q∣=d(A,B)|p - q| = d(A, B), and A∩B=∅A \cap B = \emptyset if p≠qp \ne q.
  • (F3) If kk maximizes sk(v)s_k(v) over the edges of QQ, then v∈Qv \in Q when sk(v)≤0s_k(v) \le 0, and πQ(v)∈k\pi_Q(v) \in k when sk(v)>0s_k(v) > 0.
  • (F4) If (c−a)⋅(a′−a)>0(c - a) \cdot (a' - a) > 0 for a neighbor a′a' of the vertex aa, then the edge [a,a′][a, a'] has a point closer to cc than aa.

Lemma 1 (the clip). Let vv be a vertex of PP and ee an edge of QQ. For a plane of VR(v)VR(v) with direction uu, let f(λ)=(e(λ)−v)⋅uf(\lambda) = (e(\lambda) - v) \cdot u, an affine function. CLIP returns:

  1. a plane with f(0)>0f(0) > 0 and f(1)>0f(1) > 0 (simple exclusion), if one exists; otherwise
  2. λl=max⁡\lambda_l = \max of the roots of ff over the planes with f(0)>0f(0) > 0 (or 0), with NlN_l the plane that gives it, and λu=min⁡\lambda_u = \min of the roots over the planes with f(1)>0f(1) > 0 (or 1), with NuN_u.

Then e(λ)∈VR(v)e(\lambda) \in VR(v) exactly for λ∈[λl,λu]\lambda \in [\lambda_l, \lambda_u], and the plane NlN_l is violated by e(λ)e(\lambda) for all λ∈[0,λl)\lambda \in [0, \lambda_l), and NuN_u for all λ∈(λu,1]\lambda \in (\lambda_u, 1].

Proof. Each half-plane f≤0f \le 0 meets the segment in an interval: [0,1][0, 1] if f(0),f(1)≤0f(0), f(1) \le 0, [root,1][\text{root}, 1] if f(0)>0≥f(1)f(0) > 0 \ge f(1), [0,root][0, \text{root}] if f(0)≤0<f(1)f(0) \le 0 < f(1), and the empty set if both are positive. The intersection of the intervals of the two planes is [λl,λu][\lambda_l, \lambda_u] when no plane excludes all. The plane that gives λl\lambda_l has f(0)>0f(0) > 0 and f(λl)=0f(\lambda_l) = 0, so f>0f > 0 on [0,λl)[0, \lambda_l) by linearity. The same holds for λu\lambda_u. □\square

Lemma 2 (the derivative tests). Let g(λ)=∣e(λ)−v∣2g(\lambda) = |e(\lambda) - v|^2 and λ∗=arg⁡min⁡[0,1]g\lambda^* = \arg\min_{[0, 1]} g, so e(λ∗)=πe(v)e(\lambda^*) = \pi_e(v). Then g′(λ)=2(e(λ)−v)⋅dg'(\lambda) = 2 (e(\lambda) - v) \cdot d, and:

  • if λl>0\lambda_l > 0 and g′(λl)>0g'(\lambda_l) > 0, then λ∗<λl\lambda^* < \lambda_l;
  • if λu<1\lambda_u < 1 and g′(λu)<0g'(\lambda_u) < 0, then λ∗>λu\lambda^* > \lambda_u;
  • if [λl,λu][\lambda_l, \lambda_u] is not empty and neither test fires, then λ∗∈[λl,λu]\lambda^* \in [\lambda_l, \lambda_u].

Proof. gg is a convex quadratic with g′′=2∣d∣2>0g'' = 2|d|^2 > 0, so it has one minimizer λ∗\lambda^* on [0,1][0, 1], and g′<0g' < 0 before the unconstrained minimizer and g′>0g' > 0 after it. The first two claims follow. For the third, suppose λ∗<λl\lambda^* < \lambda_l. Then λl>0\lambda_l > 0, and gg is increasing on [λ∗,1][\lambda^*, 1], so g′(λl)>0g'(\lambda_l) > 0 unless λl\lambda_l is the unconstrained minimizer, which would give λ∗=λl\lambda^* = \lambda_l. So the first test fires, a contradiction. The case λ∗>λu\lambda^* > \lambda_u is symmetric. □\square

The potential. As for Lin-Canny, let Φ=d(fA,fB)\Phi = d(f_A, f_B), let δ\delta be the sum of the dimensions, and order (Φ,δ)(\Phi, \delta) 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 (Φ,δ)(\Phi, \delta).

Proof.

  • L3 and L4: by (F4), Φ\Phi 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 Φ\Phi is unchanged and δ\delta drops from 2 to 1.
  • L10: if (v−e0)⋅d<0(v - e_0) \cdot d < 0, then gg increases on [0,1][0, 1] and πe(v)=e0\pi_e(v) = e_0. So Φ\Phi is unchanged and δ\delta drops. The same holds for e1e_1.
  • L11: vv is in the slab of ee with se(v)≤0s_e(v) \le 0. If HANDLE-LOCAL-MIN returns kk, then sk(v)>0s_k(v) > 0, so v∉Qv \notin Q and by (F3) d(v,k)=d(v,Q)≤d(v,e)d(v, k) = d(v, Q) \le d(v, e). Equality would put πQ(v)\pi_Q(v) on ee at the foot of the perpendicular, with v−πQ(v)=se(v)nev - \pi_Q(v) = s_e(v) n_e and se(v)<0s_e(v) < 0, which has a positive dot product with y−πQ(v)y - \pi_Q(v) for inner points yy of QQ. This contradicts the projection property. So Φ\Phi drops.
  • L13: every point of ee violates the plane, in particular πe(v)\pi_e(v). By (F4) the new edge has a point closer to πe(v)\pi_e(v) than vv, so Φ\Phi drops.
  • L14: the clipped interval is empty, so no point of ee is in VR(v)VR(v), and πe(v)\pi_e(v) violates some plane. By (F4), Φ\Phi drops.
  • L15 and L16: by Lemma 2, λ∗<λl\lambda^* < \lambda_l, and by Lemma 1 the plane NlN_l is violated by e(λ∗)=πe(v)e(\lambda^*) = \pi_e(v). By (F4), Φ\Phi drops. L16 is symmetric. □\square

Theorem. V-CLIP ends after at most 4∣A∣∣B∣4|A||B| 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 d(A,B)>0d(A, B) > 0. It returns PENETRATION exactly when A∩B≠∅A \cap B \ne \emptyset, 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 4∣A∣∣B∣4|A||B| states.

L5 with a≠ba \ne b: b∈VR(a)b \in VR(a) and a∈VR(b)a \in VR(b), so by (F1) the points are mutual closest points, and (F2) gives the claim. With a=ba = b the return is PENETRATION with a common vertex.

L17: the vertex passed L10 and L11, so v∈VR(e)v \in VR(e) with se(v)>0s_e(v) > 0, and by (F1) q=πe(v)q = \pi_e(v) is the closest point of the polygon of ee to vv. By Lemma 2, q=e(λ∗)q = e(\lambda^*) with λ∗∈[λl,λu]\lambda^* \in [\lambda_l, \lambda_u], so by Lemma 1, q∈VR(v)q \in VR(v), and by (F1) vv is the closest point of its polygon to qq. By (F2) the answer is right, and ∣v−q∣≥se(v)>0|v - q| \ge s_e(v) > 0.

L7 returns two edges that intersect. L19 returns a vertex with all signed distances ≤0\le 0, which is inside the other polygon by (F3). So every PENETRATION answer has a witness and is right. Conversely, if A∩B≠∅A \cap B \ne \emptyset, then (F2) rules out a DISJOINT answer, and since the walk ends, it returns PENETRATION. ■\blacksquare

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 O(1)O(1), except the handler of lines L18 to L20, which looks at all edges of one polygon. A call with ss moves costs O(s(n+m))O(s(n + m)) in the worst case and O(s)O(s) without the handler. The proof bounds ss by 4nm4nm. 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 O(1)O(1), 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 ee 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 λl\lambda_l or λu\lambda_u, not to any violated plane. Keep the plane with the clip value.
  • The derivative at the ends. If λl=0\lambda_l = 0 because no plane cut the start, there is no NlN_l 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.

v_clip.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.call
  • a full proof of time.moves_worst
  • a full proof of time.step
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example