Algorithm Search⌘K

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.

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
Properties
deterministicnot exactofflineiterative
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 A−BA - B, which contains the origin when the shapes overlap. The depth is the distance from the origin to the boundary of A−BA - B. EPA starts from the simplex in which the GJK algorithm found the origin, and it grows this polytope inside A−BA - B 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 AA and BB, given by support functions sA(u)s_A(u) and sB(u)s_B(u) that return a point of the shape that is extreme in the direction uu, and a tolerance ε≥0\varepsilon \ge 0. The support function of M=A−BM = A - B is sM(u)=sA(u)−sB(−u)s_M(u) = s_A(u) - s_B(-u). If AA and BB overlap, the output is a depth dd and a unit normal, such that moving AA by about dd along the normal makes the shapes touch, and two witness points on AA and BB. 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

  1. EPA(sA, sB, ε)
  2. 1P ← the GJK triangle of support points of A - B that contains the origin, counterclockwise
  3. 2loop
  4. 3for each edge of P, compute its outward unit normal n and its distance r = n · p from the origin
  5. 4let [p, q] be the edge with the smallest r, with the normal n
  6. 5t ← sA(n) - sB(-n)
  7. 6if n · t - r ≤ ε then return the depth r, the normal -n and the witness points on [p, q]
  8. 7insert t between p and q in P

Each vertex of PP keeps the two points aa and bb that gave it, with w=a−bw = a - b. At the end, the foot of the perpendicular from the origin to the edge [p,q][p, q] is λ\lambda of the way from wpw_p to wqw_q, and the same λ\lambda between apa_p and aqa_q, and between bpb_p and bqb_q, gives the witness points. The GJK stage is the boolean form of GJK in 2D: it returns no triangle if the origin is outside MM or on its boundary, and then the shapes are disjoint or only touch.

Example

Let AA be the rectangle with corners (0,0)(0, 0), (4,0)(4, 0), (4,3)(4, 3), (0,3)(0, 3), and BB the triangle (3,1)(3, 1), (6,2)(6, 2), (4,4)(4, 4). The corner (3,1)(3, 1) of BB is inside AA.

The GJK stage returns the counterclockwise triangle w0=(1,2)w_0 = (1, 2), w1=(−6,1)w_1 = (-6, 1), w2=(1,−1)w_2 = (1, -1). For example, w2=(4,0)−(3,1)w_2 = (4, 0) - (3, 1) is the support point in the direction (1,0)(1, 0).

Round 1. The edges have the distances 13/50≈1.83813/\sqrt{50} \approx 1.838 for [w0,w1][w_0, w_1], 5/53≈0.6875/\sqrt{53} \approx 0.687 for [w1,w2][w_1, w_2] with the normal (−2,−7)/53(-2, -7)/\sqrt{53}, and 11 for [w2,w0][w_2, w_0] with the normal (1,0)(1, 0). The closest edge is [w1,w2][w_1, w_2]. The support point in its normal direction is t=(0,0)−(4,4)=(−4,−4)t = (0, 0) - (4, 4) = (-4, -4), at the distance 36/53≈4.94536/\sqrt{53} \approx 4.945. That is far past the edge, so line L7 inserts it, and PP is (1,2)(1, 2), (−6,1)(-6, 1), (−4,−4)(-4, -4), (1,−1)(1, -1).

Round 2. The new edges have the distances 28/29≈5.2028/\sqrt{29} \approx 5.20 and 8/34≈1.378/\sqrt{34} \approx 1.37. Now the closest edge is [w2,w0][w_2, w_0], the line x=1x = 1, at the distance 1. The support point in the direction (1,0)(1, 0) is (1,−1)(1, -1) again, so the gain is 0, and line L6 stops. The depth is 1 with the normal (−1,0)(-1, 0): move AA one unit to the left, and its right side touches the corner (3,1)(3, 1) of BB. The foot of the perpendicular is (1,0)(1, 0), at λ=1/3\lambda = 1/3 from w2w_2 to w0w_0, which gives the witness points (4,1)(4, 1) on AA and (3,1)(3, 1) on BB.

The tests of this page compare the result with the hull of all nmnm 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 ε=10−2\varepsilon = 10^{-2}, 10−410^{-4}, 10−610^{-6}, 10−810^{-8} and 10−1010^{-10}.

Correctness

The proof is in proofs/correctness.md. The invariant is that PP is a convex polygon that contains the origin, and that its vertices are support points of MM, so P⊆MP \subseteq M. An inserted point tt 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 P⊆MP \subseteq M, the smallest edge distance rr is at most the depth. At the stop, the support value in the direction nn is at most r+εr + \varepsilon, and the depth is the smallest support value over all directions, so r≤d≤r+εr \le d \le r + \varepsilon. For polygons, each round adds a new difference of two vertices, so EPA stops after at most nmnm rounds, also with ε=0\varepsilon = 0.

Proof: The 2D expanding polytope algorithm brackets the penetration depth and terminates on polygonsfull

Let AA and BB be convex polygons and M=A−B={a−b:a∈A,b∈B}M = A - B = \{a - b : a \in A, b \in B\}, a convex polygon. The support function of MM is hM(u)=max⁡x∈Mu⋅x=hA(u)+hB(−u)h_M(u) = \max_{x \in M} u \cdot x = h_A(u) + h_B(-u), and a support point of MM in the direction uu is sA(u)−sB(−u)s_A(u) - s_B(-u). Use exact arithmetic. The penetration depth is δ=min⁡{∣t∣:(A+t)∩B has no interior point}\delta = \min \{ |t| : (A + t) \cap B \text{ has no interior point} \}. Since (A+t)∩B≠∅(A + t) \cap B \neq \emptyset exactly when −t∈M-t \in M, δ\delta is the distance from the origin to the boundary of MM when the origin is in MM.

Lemma 1 (the depth is the smallest support value). If 0∈M0 \in M, then δ=min⁡∣u∣=1hM(u)\delta = \min_{|u| = 1} h_M(u), and AA moved by −hM(u) u-h_M(u)\,u touches BB without overlap.

Proof. Let zz be a point of ∂M\partial M closest to the origin, so ∣z∣=δ|z| = \delta. There is a supporting line of MM at zz with a unit normal uu, so hM(u)=u⋅z≤∣z∣=δh_M(u) = u \cdot z \le |z| = \delta. Conversely, the open disc of radius δ\delta about the origin is inside MM, so for each unit uu the point δu\delta u is in the closure of MM and hM(u)≥δh_M(u) \ge \delta. For the second claim, (A−su)−B=M−su(A - s u) - B = M - s u, and with s=hM(u)s = h_M(u) every point xx of it has u⋅x≤0u \cdot x \le 0, with equality on a face. So the origin is on the boundary of M−suM - s u. □\square

The start. The GJK stage returns a triangle T0T_0 with three properties. Its vertices are support points of MM 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 PP be the polygon of EPA at the start of a round. Then:

  1. PP is a convex polygon in counterclockwise order, possibly with collinear vertices, and no two of its vertices are equal;
  2. each vertex vv of PP is a support point of MM for a nonzero direction dvd_v;
  3. 0∈P⊆M0 \in P \subseteq M.

Proof. The start triangle has the three properties. Suppose PP has them, line L4 picks the edge pqpq with the outward unit normal nn and the distance r=n⋅pr = n \cdot p, and line L5 gets the support point tt with n⋅t>r+ε≥rn \cdot t > r + \varepsilon \ge r. Line L7 puts tt between pp and qq. Property 2 holds for tt with dt=nd_t = n, and t∈Mt \in M, so P′⊆MP' \subseteq M by the convexity of MM, and 0∈P⊆P′0 \in P \subseteq P'. It remains to show that P′P' is convex.

The point tt is strictly beyond the line of pqpq, so the turn p→t→qp \to t \to q is to the left, and tt differs from all vertices of PP, which are on the inner side of that line. Let oo be the vertex before pp, with the edge normal n′n'. Suppose tt is strictly beyond the line of opop too. The direction dpd_p is in the normal cone of PP at pp, because pp maximizes dp⋅xd_p \cdot x over M⊇PM \supseteq P. So dp=αn′+βnd_p = \alpha n' + \beta n with α,β≥0\alpha, \beta \ge 0, not both zero. Then dp⋅(t−p)=α n′⋅(t−p)+β n⋅(t−p)>0d_p \cdot (t - p) = \alpha\, n' \cdot (t - p) + \beta\, n \cdot (t - p) > 0, which contradicts that pp is a support point in the direction dpd_p. So tt is on the inner side of the line of opop or on it, and the turn o→p→to \to p \to t is to the left or straight. The same argument at qq shows that the turn t→q→rt \to q \to r is to the left or straight. All other turns are unchanged. So P′P' is convex. □\square

Lemma 2 (the bracket). In each round, r≤δr \le \delta. When line L6 stops the loop, r≤δ≤r+εr \le \delta \le r + \varepsilon.

Proof. The origin is in the convex polygon PP, so its distance to ∂P\partial P is the smallest distance to the line of an edge, which is rr. Because P⊆MP \subseteq M, a disc about the origin that is inside PP is also inside MM, so r≤δr \le \delta. At the stop, the support point tt in the direction nn has hM(n)=n⋅t≤r+εh_M(n) = n \cdot t \le r + \varepsilon, and by Lemma 1, δ≤hM(n)≤r+ε\delta \le h_M(n) \le r + \varepsilon. □\square

Lemma 3 (the witness). At the stop, the returned points pAp_A and pBp_B are in AA and BB, and pA−pB=r np_A - p_B = r\,n. If ε=0\varepsilon = 0, then moving AA by rr along the returned normal −n-n makes AA and BB touch without overlap.

Proof. Each vertex of PP is stored as a triple (w,a,b)(w, a, b) with w=a−bw = a - b, a∈Aa \in A and b∈Bb \in B. The foot of the perpendicular from the origin to the line of pqpq is r nr\,n. It lies on the segment pqpq: otherwise the segment from the origin to it would leave PP through another edge, and that edge would have a smaller distance than rr. So λ∈[0,1]\lambda \in [0, 1], the clamp does nothing, and r n=(1−λ)wp+λwq=pA−pBr\,n = (1 - \lambda) w_p + \lambda w_q = p_A - p_B with pA=(1−λ)ap+λaq∈Ap_A = (1 - \lambda) a_p + \lambda a_q \in A and pB=(1−λ)bp+λbq∈Bp_B = (1 - \lambda) b_p + \lambda b_q \in B by convexity. With ε=0\varepsilon = 0, Lemma 2 gives hM(n)=r=δh_M(n) = r = \delta, and Lemma 1 gives the touching. □\square

Theorem (termination on polygons). If AA and BB are polygons with nn and mm vertices and the support functions return vertices, EPA stops after at most nmnm rounds, for every ε≥0\varepsilon \ge 0.

Proof. Every support point of MM that the code can return is a difference a−ba - b of a vertex of AA and a vertex of BB, so there are at most nmnm of them. Each round that does not stop inserts a point that is not yet a vertex of PP (by the invariant), and no vertex is ever removed. So there are fewer than nmnm insertions, and the round after the last insertion stops. ■\blacksquare

Remarks. For curved shapes, such as discs, the set of support points is infinite, and the termination needs ε>0\varepsilon > 0. 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 O(∣P∣)O(|P|) to find the closest edge and O(n+m)O(n + m) for a support query by a linear scan. After kk rounds, ∣P∣=k+2|P| = k + 2, so a call costs O(k(k+n+m))O(k(k + n + m)). With the edges in a priority queue by distance, as in the 3D form, the search for the closest edge costs O(log⁡k)O(\log k). The proof bounds kk by nmnm for polygons, and for curved shapes kk depends on ε\varepsilon. In practice EPA starts from the GJK simplex, close to the answer, and kk is small. This is observed, not proved. The extra space is O(k)O(k).

Properties

  • Bracket. With exact arithmetic the result satisfies r≤d≤r+εr \le d \le r + \varepsilon, and with ε=0\varepsilon = 0 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 ε\varepsilon must be positive. In floating point a positive ε\varepsilon 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 ε=0\varepsilon = 0 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 BB to AA in this page. Mixing up A−BA - B and B−AB - A 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.

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

  1. Gino van den Bergen, Collision Detection in Interactive 3D Environments, Morgan Kaufmann, 2003, the material on penetration depth and the expanding polytope algorithm
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.call
  • a full proof of time.heap_call
  • a full proof of time.rounds_worst
  • 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