Algorithmcore
Expanding polytope algorithm
Also called EPA.
Find the penetration depth and normal of two overlapping convex shapes by growing a polytope inside their Minkowski difference from the final GJK simplex.
- Solves
- Penetration depth
- Time
- O(k (k + n + m)) callO(k log k + k (n + m)) heap_callO(n m) rounds_worst
- Space
- O(k) extra
- Where
- k = the number of rounds; m = the number of vertices of B; n = the number of vertices of A
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Gino van den Bergen, 2001
The expanding polytope algorithm (EPA) computes the penetration depth of two convex shapes that overlap: the length of the shortest translation that separates them, and its direction. It works on the Minkowski difference , which contains the origin when the shapes overlap. The depth is the distance from the origin to the boundary of . EPA starts from the simplex in which the GJK algorithm found the origin, and it grows this polytope inside toward the boundary face that is closest to the origin. It only needs the support functions of the shapes, so it works for polytopes and for curved convex shapes. It needs a tolerance, and it is not exact.
In plain words
Two convex objects overlap. You want the shortest push that separates them.
Build a new shape from all the differences of a point of one object and a point of the other. The objects overlap when this shape covers the center point. The shortest push is the distance from the center to the edge of this shape.
You cannot build the whole shape, but you can ask for its farthest point in any direction. Start from a small triangle inside it that covers the center. Take the side of the triangle that is nearest to the center. Ask for the farthest point of the shape in the outward direction of that side. If that point is far past the side, add it, and the inner shape grows. If it is almost on the side, that side is part of the edge, and its distance is the push.
The problem
The input is two convex shapes and , given by support functions and that return a point of the shape that is extreme in the direction , and a tolerance . The support function of is . If and overlap, the output is a depth and a unit normal, such that moving by about along the normal makes the shapes touch, and two witness points on and . This page works in 2D, where the polytope is a polygon and its faces are edges. In 3D the polytope has triangle faces, and an insertion replaces all faces that the new point can see.
The algorithm
EPA(sA, sB, ε)- 1
P ← the GJK triangle of support points of A - B that contains the origin, counterclockwise - 2
loop - 3
for each edge of P, compute its outward unit normal n and its distance r = n · p from the origin - 4
let [p, q] be the edge with the smallest r, with the normal n - 5
t ← sA(n) - sB(-n) - 6
if n · t - r ≤ ε then return the depth r, the normal -n and the witness points on [p, q] - 7
insert t between p and q in P
Each vertex of keeps the two points and that gave it, with . At the end, the foot of the perpendicular from the origin to the edge is of the way from to , and the same between and , and between and , gives the witness points. The GJK stage is the boolean form of GJK in 2D: it returns no triangle if the origin is outside or on its boundary, and then the shapes are disjoint or only touch.
Example
Let be the rectangle with corners , , , , and the triangle , , . The corner of is inside .
The GJK stage returns the counterclockwise triangle , , . For example, is the support point in the direction .
Round 1. The edges have the distances for , for with the normal , and for with the normal . The closest edge is . The support point in its normal direction is , at the distance . That is far past the edge, so line L7 inserts it, and is , , , .
Round 2. The new edges have the distances and . Now the closest edge is , the line , at the distance 1. The support point in the direction is again, so the gain is 0, and line L6 stops. The depth is 1 with the normal : move one unit to the left, and its right side touches the corner of . The foot of the perpendicular is , at from to , which gives the witness points on and on .
The tests of this page compare the result with the hull of all vertex differences on 500 random pairs. For two discs, which have no vertices, the number of rounds grows with the precision. With the radii 2 and 1.5 at the distance 1, the implementation took 10, 16, 24, 30 and 36 rounds for , , , and .
Correctness
The proof is in proofs/correctness.md. The invariant is that is a convex polygon that contains the origin, and that its vertices are support points of , so . An inserted point cannot be past the line of a neighbor edge, because the neighbor vertex is a support point for a direction in its normal cone. So the polygon stays convex. Since , the smallest edge distance is at most the depth. At the stop, the support value in the direction is at most , and the depth is the smallest support value over all directions, so . For polygons, each round adds a new difference of two vertices, so EPA stops after at most rounds, also with .
Proof: The 2D expanding polytope algorithm brackets the penetration depth and terminates on polygonsfull
Let and be convex polygons and , a convex polygon. The support function of is , and a support point of in the direction is . Use exact arithmetic. The penetration depth is . Since exactly when , is the distance from the origin to the boundary of when the origin is in .
Lemma 1 (the depth is the smallest support value). If , then , and moved by touches without overlap.
Proof. Let be a point of closest to the origin, so . There is a supporting line of at with a unit normal , so . Conversely, the open disc of radius about the origin is inside , so for each unit the point is in the closure of and . For the second claim, , and with every point of it has , with equality on a face. So the origin is on the boundary of .
The start. The GJK stage returns a triangle with three properties. Its vertices are support points of for nonzero directions. It is counterclockwise and not degenerate. It contains the origin. The last two are the exit tests of the GJK stage: the code returns the triangle only when the cross product is not zero (it reorders it to counterclockwise), and when the origin is on the inner side of the two new edges, and on the inner side of the old edge, because the new vertex and the origin are on the same side of the old edge with respect to the search direction. The termination of the GJK stage is a property of GJK and is not proved here. The code also stops it after a fixed number of rounds.
Invariant. Let be the polygon of EPA at the start of a round. Then:
- is a convex polygon in counterclockwise order, possibly with collinear vertices, and no two of its vertices are equal;
- each vertex of is a support point of for a nonzero direction ;
- .
Proof. The start triangle has the three properties. Suppose has them, line L4 picks the edge with the outward unit normal and the distance , and line L5 gets the support point with . Line L7 puts between and . Property 2 holds for with , and , so by the convexity of , and . It remains to show that is convex.
The point is strictly beyond the line of , so the turn is to the left, and differs from all vertices of , which are on the inner side of that line. Let be the vertex before , with the edge normal . Suppose is strictly beyond the line of too. The direction is in the normal cone of at , because maximizes over . So with , not both zero. Then , which contradicts that is a support point in the direction . So is on the inner side of the line of or on it, and the turn is to the left or straight. The same argument at shows that the turn is to the left or straight. All other turns are unchanged. So is convex.
Lemma 2 (the bracket). In each round, . When line L6 stops the loop, .
Proof. The origin is in the convex polygon , so its distance to is the smallest distance to the line of an edge, which is . Because , a disc about the origin that is inside is also inside , so . At the stop, the support point in the direction has , and by Lemma 1, .
Lemma 3 (the witness). At the stop, the returned points and are in and , and . If , then moving by along the returned normal makes and touch without overlap.
Proof. Each vertex of is stored as a triple with , and . The foot of the perpendicular from the origin to the line of is . It lies on the segment : otherwise the segment from the origin to it would leave through another edge, and that edge would have a smaller distance than . So , the clamp does nothing, and with and by convexity. With , Lemma 2 gives , and Lemma 1 gives the touching.
Theorem (termination on polygons). If and are polygons with and vertices and the support functions return vertices, EPA stops after at most rounds, for every .
Proof. Every support point of that the code can return is a difference of a vertex of and a vertex of , so there are at most of them. Each round that does not stop inserts a point that is not yet a vertex of (by the invariant), and no vertex is ever removed. So there are fewer than insertions, and the round after the last insertion stops.
Remarks. For curved shapes, such as discs, the set of support points is infinite, and the termination needs . This proof does not cover that case. The implementation bounds the number of rounds and raises an error. In floating point, the signs in the invariant can be wrong for nearly parallel edges, and then the polygon can lose its convexity. This is the reason for the tolerance in practice, not only for curved shapes.
Complexity
A round costs to find the closest edge and for a support query by a linear scan. After rounds, , so a call costs . With the edges in a priority queue by distance, as in the 3D form, the search for the closest edge costs . The proof bounds by for polygons, and for curved shapes depends on . In practice EPA starts from the GJK simplex, close to the answer, and is small. This is observed, not proved. The extra space is .
Properties
- Bracket. With exact arithmetic the result satisfies , and with on polytopes it is the exact depth.
- Support functions only. EPA works on any convex shape with a support function, as GJK does: polygons, discs, capsules and their Minkowski sums.
- A tolerance. For curved shapes must be positive. In floating point a positive also stops rounds that gain nothing because of rounding.
- Witness points. The result gives a contact normal and a point on each shape, which a simulator can use for a contact manifold.
Variants and improvements
- 3D. The polytope has triangle faces. An insertion removes all faces that the new point sees and connects the horizon edges to it. The start simplex must be a tetrahedron that contains the origin. If GJK stops with a smaller simplex, it must be blown up first, with extra support points.
- A priority queue of faces. Keep the faces in a heap by their distance, and skip the faces that were removed. This is the usual form in engines.
- Dual expansion. Kim, Lin and Manocha (2002) walk on the Gauss maps of two convex polytopes to estimate the depth incrementally from the previous time step.
- Separating axes. For boxes and other polytopes with few face normals, the separating axis theorem gives the depth as the smallest overlap over the candidate axes, with no iteration.
- Avoid the depth. Conservative advancement and other continuous collision detection methods stop the motion before the overlap, so only a distance is needed.
When to use it
Use EPA after GJK reports an overlap of two convex shapes and you need the penetration depth and normal, for example to push the bodies apart or to make a contact. It is the standard choice for general convex shapes in physics engines. For boxes, use the separating axis tests. For deep overlaps of nonconvex shapes, split them into convex pieces first, because the depth of a nonconvex pair is not the depth of its convex hulls.
Pitfalls
- Degenerate faces. In 3D, nearly flat or very thin faces give normals with a large error, and the polytope can lose its convexity. Check the orientation of each new face, and stop with the best face so far if a check fails.
- The origin on the boundary. When the shapes just touch, GJK can stop with the origin on an edge of the simplex or with a flat simplex. The depth is then 0, and the normal must come from the face, not from the origin.
- The tolerance. With on curved shapes the loop does not stop in exact arithmetic. In floating point it may stop only because the gain rounds to 0. Use a relative tolerance and a limit on the rounds.
- The sign of the normal. The normal points from to in this page. Mixing up and pushes the bodies into each other.
- Large depths. The penetration depth is not continuous in time: a small motion can flip the normal to another face. A simulator that uses it for deep contacts can push a body out of the wrong side.
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/expanding-polytope-algorithm/. The authors are listed in prov/PP6HVM.jsonl.
"""The expanding polytope algorithm (EPA) for two convex polygons in the plane.
Shapes are given only by support functions: support(d) returns a point of the shape that is
extreme in the direction d. A small 2D GJK (gjk_triangle) finds a triangle of support points of
the Minkowski difference A - B that contains the origin. EPA then grows a convex polygon inside
A - B: it takes the edge closest to the origin, asks for the support point of A - B along the
normal of that edge, and inserts it, until the support point is at most eps beyond the edge.
The result is the penetration depth d, the unit normal n from B to A (moving A by d n makes the
shapes touch), and a point on A and a point on B whose difference is the deepest point.
With exact arithmetic, the returned depth d satisfies d <= depth <= d + eps. Floats are used.
"""
from __future__ import annotations
import math
from typing import Callable
Vec = tuple[float, float]
Support = Callable[[Vec], Vec]
def _sub(p: Vec, q: Vec) -> Vec:
return (p[0] - q[0], p[1] - q[1])
def _dot(u: Vec, v: Vec) -> float:
return u[0] * v[0] + u[1] * v[1]
def _cross(u: Vec, v: Vec) -> float:
return u[0] * v[1] - u[1] * v[0]
def polygon_support(P: list[Vec]) -> Support:
"""The support function of the convex hull of the points P (a linear scan)."""
def s(d: Vec) -> Vec:
return max(P, key=lambda p: p[0] * d[0] + p[1] * d[1])
return s
def _diff_support(sa: Support, sb: Support, d: Vec) -> tuple[Vec, Vec, Vec]:
a = sa(d)
b = sb((-d[0], -d[1]))
return (a[0] - b[0], a[1] - b[1]), a, b
def gjk_triangle(sa: Support, sb: Support, max_iter: int = 100):
"""A counterclockwise triangle of (w, a, b) support triples of A - B that contains the origin.
Returns None if A and B are disjoint or only touch (the origin is on the boundary of A - B).
This is the boolean part of GJK in 2D.
"""
d = (1.0, 0.0)
simplex = [_diff_support(sa, sb, d)]
w = simplex[0][0]
if w == (0.0, 0.0):
return None # the origin is a support point, so it is on the boundary
d = (-w[0], -w[1])
for _ in range(max_iter):
t = _diff_support(sa, sb, d)
if _dot(t[0], d) < 0:
return None # the support point does not pass the origin: a separating direction
simplex.append(t)
a = t[0]
ao = (-a[0], -a[1])
if len(simplex) == 2:
b = simplex[0][0]
ab = _sub(b, a)
perp = (-ab[1], ab[0])
if _dot(perp, ao) < 0:
perp = (ab[1], -ab[0])
d = perp
continue
c, b = simplex[0][0], simplex[1][0]
ab, ac = _sub(b, a), _sub(c, a)
side = _cross(ab, ac)
if side == 0:
return None # a, b, c on one line through the origin: the shapes only touch
ab_out = (ab[1], -ab[0]) if side > 0 else (-ab[1], ab[0]) # normal of ab away from c
ac_out = (-ac[1], ac[0]) if side > 0 else (ac[1], -ac[0]) # normal of ac away from b
if _dot(ab_out, ao) > 0:
simplex = [simplex[1], simplex[2]]
d = ab_out
elif _dot(ac_out, ao) > 0:
simplex = [simplex[0], simplex[2]]
d = ac_out
else:
if side > 0: # a, b, c is counterclockwise, so c, b, a is clockwise
simplex = [simplex[2], simplex[1], simplex[0]]
return simplex
raise RuntimeError("GJK did not converge")
def epa(sa: Support, sb: Support, eps: float = 1e-10, max_iter: int = 200):
"""Penetration depth and normal of two overlapping convex shapes.
Returns (depth, normal, point_on_a, point_on_b, iterations), or None if the shapes are disjoint.
Shapes that only touch give None or a depth of 0.
"""
tri = gjk_triangle(sa, sb)
if tri is None:
return None
poly = list(tri) # @line L1
for it in range(1, max_iter + 1): # @line L2
best = None
for i in range(len(poly)): # @line L3
p, q = poly[i][0], poly[(i + 1) % len(poly)][0]
e = _sub(q, p)
length = math.hypot(e[0], e[1])
n = (e[1] / length, -e[0] / length) # outward for a counterclockwise polygon
dist = _dot(n, p)
if best is None or dist < best[0]: # @line L4
best = (dist, n, i)
dist, n, i = best
t = _diff_support(sa, sb, n) # @line L5
if _dot(n, t[0]) - dist <= eps: # @line L6
p, q = poly[i], poly[(i + 1) % len(poly)]
e = _sub(q[0], p[0])
lam = -_dot(p[0], e) / _dot(e, e) # the foot of the perpendicular from the origin
lam = min(1.0, max(0.0, lam))
pa = (p[1][0] + lam * (q[1][0] - p[1][0]), p[1][1] + lam * (q[1][1] - p[1][1]))
pb = (p[2][0] + lam * (q[2][0] - p[2][0]), p[2][1] + lam * (q[2][1] - p[2][1]))
return dist, (-n[0], -n[1]), pa, pb, it
poly.insert(i + 1, t) # @line L7
raise RuntimeError("EPA did not converge; eps is too small for the arithmetic")
test_expanding_polytope_algorithm.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/expanding-polytope-algorithm/. The authors are listed in prov/PP6HVM.jsonl.
import math
import random
from expanding_polytope_algorithm import epa, gjk_triangle, polygon_support
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.uniform(-r, r), cy + rng.uniform(-r, r)) for _ in range(rng.randint(3, 9))]
h = hull(pts)
if len(h) >= 3:
return h
def brute_depth(A, B):
"""The distance from the origin to the boundary of hull(A - B), or None if the origin is outside."""
H = hull([(a[0] - b[0], a[1] - b[1]) for a in A for b in B])
best = None
for i in range(len(H)):
p, q = H[i], H[(i + 1) % len(H)]
e = (q[0] - p[0], q[1] - p[1])
L = math.hypot(*e)
s = (e[1] * p[0] - e[0] * p[1]) / L # signed distance of the origin, outward positive
if s <= 0:
return None
best = s if best is None or s < best else best
return best
def inside(P, x, tol=1e-9):
return all(cross(P[i], P[(i + 1) % len(P)], x) >= -tol for i in range(len(P)))
def test_page_example():
A = [(0.0, 0.0), (4.0, 0.0), (4.0, 3.0), (0.0, 3.0)]
B = [(3.0, 1.0), (6.0, 2.0), (4.0, 4.0)]
sa, sb = polygon_support(A), polygon_support(B)
assert [t[0] for t in gjk_triangle(sa, sb)] == [(1.0, 2.0), (-6.0, 1.0), (1.0, -1.0)]
depth, n, pa, pb, it = epa(sa, sb)
assert (depth, n, pa, pb, it) == (1.0, (-1.0, 0.0), (4.0, 1.0), (3.0, 1.0), 2)
assert brute_depth(A, B) == 1.0
def test_gjk_triangle_contains_the_origin():
rng = random.Random(7)
found = 0
for _ in range(400):
A = random_polygon(rng, 0, 0, 4)
B = random_polygon(rng, rng.uniform(-6, 6), rng.uniform(-6, 6), 4)
tri = gjk_triangle(polygon_support(A), polygon_support(B))
assert (tri is not None) == (brute_depth(A, B) is not None)
if tri is not None:
found += 1
w = [t[0] for t in tri]
assert cross(w[0], w[1], w[2]) > 0
assert inside(w, (0.0, 0.0))
for wi, a, b in tri:
assert (a[0] - b[0], a[1] - b[1]) == wi
assert found >= 100
def test_random_pairs_against_the_hull_of_differences():
rng = random.Random(2001)
deep = 0
for _ in range(500):
A = random_polygon(rng, 0, 0, 5)
B = random_polygon(rng, rng.uniform(-7, 7), rng.uniform(-7, 7), 5)
ref = brute_depth(A, B)
res = epa(polygon_support(A), polygon_support(B), eps=1e-12)
assert (res is None) == (ref is None)
if res is None:
continue
deep += 1
depth, n, pa, pb, _ = res
assert abs(depth - ref) <= 1e-9 * (1 + ref)
assert abs(math.hypot(*n) - 1) < 1e-12
# moving A by depth * n makes the shapes touch: no difference point is beyond depth along -n
diffs = [(a[0] - b[0], a[1] - b[1]) for a in A for b in B]
reach = max(-n[0] * w[0] - n[1] * w[1] for w in diffs)
assert abs(reach - depth) <= 1e-9 * (1 + depth)
# the witness points lie on the shapes and differ by the deepest point
assert inside(A, pa) and inside(B, pb)
assert abs(pa[0] - pb[0] + depth * n[0]) < 1e-9 and abs(pa[1] - pb[1] + depth * n[1]) < 1e-9
assert deep >= 150
def test_disjoint_and_touching_shapes():
sq = [(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]
for dx, dy in ((3.0, 0.0), (-5.0, 1.0), (2.5, 2.5)):
other = [(x + dx, y + dy) for x, y in sq]
assert epa(polygon_support(sq), polygon_support(other)) is None
for dx, dy in ((2.0, 0.0), (2.0, 2.0), (0.0, -2.0), (-2.0, 1.0)):
# touching shapes: GJK may stop with the origin on the boundary, or EPA returns depth 0
other = [(x + dx, y + dy) for x, y in sq]
res = epa(polygon_support(sq), polygon_support(other))
assert res is None or res[0] == 0
inner = [(0.5, 0.5), (1.5, 0.5), (1.0, 1.5)]
depth, n, _, _, _ = epa(polygon_support(sq), polygon_support(inner))
assert abs(depth - 1.5) < 1e-12 # push the square down by 1.5 to clear the triangle
def disc(c, r):
def s(d):
L = math.hypot(*d)
return (c[0] + r * d[0] / L, c[1] + r * d[1] / L)
return s
def test_smooth_shapes_need_the_tolerance():
# two discs: the true depth is 2 + 1.5 - 1 = 2.5 along the x axis
counts = []
for eps in (1e-2, 1e-4, 1e-6, 1e-8):
depth, n, _, _, it = epa(disc((0.0, 0.0), 2.0), disc((1.0, 0.0), 1.5), eps=eps)
assert depth <= 2.5 + 1e-12 and 2.5 <= depth + eps + 1e-12
assert n[0] < 0 and abs(n[1]) <= 10 * math.sqrt(eps)
counts.append(it)
assert counts == sorted(counts) and counts[-1] > counts[0]
History
Cameron and Culley studied the penetration depth of convex polytopes in the 1980s, and Dobkin, Hershberger, Kirkpatrick and Suri (1993) analyzed its exact computation for convex polyhedra. Van den Bergen described EPA in 2001 as a way to get the depth from the last simplex of GJK with support functions only, and it is in his 2003 book. It became the usual companion of GJK in game and physics engines, which run GJK for the distance and EPA when the shapes overlap.
References
- Gino van den Bergen, Collision Detection in Interactive 3D Environments, Morgan Kaufmann, 2003, the material on penetration depth and the expanding polytope algorithm
- David Dobkin, John Hershberger, David Kirkpatrick and Subhash Suri, Computing the intersection-depth of polyhedra, Algorithmica 9(6), 1993, 518 to 533, the definition of the intersection depth as the shortest translation that separates two convex polyhedra
- Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann, 2005, Chapter 9, Convex-based Methods (GJK, support mappings and the Minkowski difference)
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 PP6HVM Edit this page History Report an error Markdown