Algorithm Search⌘K

Algorithmadvanced

Vertex-face and edge-edge continuous collision tests

Also called cubic CCD test.

Find when a moving vertex hits a moving triangle or two edges meet by solving the cubic coplanarity equation and checking the contact point.

Time
O(1) rootsO(k) test
Space
O(1) extra
Where
k = the number of bisection steps per root
Properties
deterministicnot exactofflineiterative
Origin
Xavier Provot, 1997

The elementary continuous collision tests find the first time in a time step at which a moving vertex hits a moving triangle, or two moving edges cross. Each of the four points moves on a straight line during the step. The four points are coplanar exactly when a triple product is zero, and with linear motion this triple product is a cubic polynomial in time. A contact can only happen at a root of the cubic. So the tests find the roots in [0,1][0, 1] in increasing order, and at each root they check if the vertex is really on the triangle, or if the edges really meet. They are the inner tests of continuous collision detection for triangle meshes and cloth, used by robust cloth collision, impact zones and the line search of incremental potential contact. In floating point they can miss contacts, and the choice of the tolerance is the hard part.

In plain words

A corner of one mesh and a flat piece of another mesh both move in straight lines during a short time. You want to know if the corner hits the flat piece, and when.

The corner can hit the piece only when it is on the same flat sheet as the piece. That moment is the answer to an equation in time with at most three answers. Find these answers in order. At each one, check if the corner is really inside the piece, and not on the sheet but outside it. The first answer that passes is the moment of the hit.

The test for two moving sides works the same way. The two sides can cross only when their four ends are on one flat sheet.

The problem

The input is four points with their positions xi0x_i^0 at t=0t = 0 and xi1x_i^1 at t=1t = 1, so that xi(t)=xi0+t (xi1−xi0)x_i(t) = x_i^0 + t\,(x_i^1 - x_i^0), and a distance tolerance δ≥0\delta \ge 0. For the vertex-face test the points are a vertex pp and the corners aa, bb, cc of a triangle. For the edge-edge test they are the ends of the edges abab and cdcd. The output is the first time t∈[0,1]t \in [0, 1] of a contact, or NO-CONTACT. A contact is a time at which pp is in the closed triangle, or at which the closed segments meet. The scenes on this page are 3D, because edge-edge contacts exist only in 3D.

The algorithm

  1. VERTEX-FACE-CCD(p, a, b, c, δ)
  2. 1f ← the coefficients of (p - a) · ((b - a) × (c - a)) as a cubic in t
  3. 2z ← the roots of f' in (0, 1), sorted
  4. 3for each piece [lo, hi] between 0, the values of z, and 1
  5. 4if f(lo) = 0 then add lo to R, else if f(lo) and f(hi) have opposite signs then add the root of the piece, by bisection, to R
  6. 5for each t in R, in increasing order
  7. 6if the distance of p(t) to the triangle a(t) b(t) c(t) is at most δ then
  8. 7return t
  9. 8return NO-CONTACT

The edge-edge test is the same with f(t)=(c−a)⋅((b−a)×(d−c))f(t) = (c - a) \cdot ((b - a) \times (d - c)) and the distance between the segments at line L6. A root at t=1t = 1 is added after the loop. The derivative f′f' is a quadratic, so line L2 needs one square root. On each piece ff is monotone, so a piece has at most one root, and bisection finds it. The bisection keeps the end of the bracket that is before the root, so the reported time is not later than the root. The distance at line L6 uses the closest point of a triangle by its Voronoi regions and the closest points of two segments, as in Ericson's book.

If all four coefficients are zero, the four points stay coplanar during the whole step. The cubic then gives no information, and the test must fall back to a 2D test in the common plane. The implementation raises an error in this case.

Example

The triangle has a=(0,0,0)a = (0, 0, 0) at rest, bb moves from (4,0,0)(4, 0, 0) to (5,2,3)(5, 2, 3), and cc moves from (0,4,0)(0, 4, 0) to (1,−2,0)(1, -2, 0). The vertex pp moves from (3,1,3)(3, 1, 3) to (1,0,0)(1, 0, 0). Line L1 gives

f(t)=48−144 t+117 t2−15 t3=−3 (5t−4)(t2−7t+4).f(t) = 48 - 144\,t + 117\,t^2 - 15\,t^3 = -3\,(5t - 4)(t^2 - 7t + 4).

The derivative f′(t)=−144+234 t−45 t2f'(t) = -144 + 234\,t - 45\,t^2 has one root in (0,1)(0, 1), at z1≈0.713204z_1 \approx 0.713204, with f(z1)≈−0.630f(z_1) \approx -0.630. So the pieces are [0,z1][0, z_1], where ff goes from 48 to −0.630-0.630, and [z1,1][z_1, 1], where it goes from −0.630-0.630 to 6. Each piece has one root: t1=(7−33)/2≈0.627719t_1 = (7 - \sqrt{33})/2 \approx 0.627719 and t2=4/5t_2 = 4/5. An exact Sturm count with fractions also gives two distinct roots in (0,1)(0, 1).

At t1t_1 the four points are coplanar, but p(t1)≈(1.7446,0.3723,1.1168)p(t_1) \approx (1.7446, 0.3723, 1.1168) has the barycentric weights (2,0.593,−1.593)(2, 0.593, -1.593) for (a,b,c)(a, b, c). The weight of cc is negative, so pp is outside the triangle, at the distance 0.400480.40048 from it, and line L6 rejects this root. At t2=4/5t_2 = 4/5, p=(1.4,0.2,0.6)p = (1.4, 0.2, 0.6), b=(4.8,1.6,2.4)b = (4.8, 1.6, 2.4) and c=(0.8,−0.8,0)c = (0.8, -0.8, 0). Then p=12a+14b+14cp = \frac{1}{2} a + \frac{1}{4} b + \frac{1}{4} c exactly, the vertex is inside the triangle, and the test returns t=0.8t = 0.8. A test that only looked at the sign of ff at the start and the end of the step would see f(0)=48f(0) = 48 and f(1)=6f(1) = 6, the same sign, and miss both roots.

Correctness

The proof is in proofs/correctness.md. At a contact the three vectors of the triple product are linearly dependent, so a contact time is a root of ff. The critical points split [0,1][0, 1] into pieces on which ff is monotone, so the loop finds every root in [0,1][0, 1], in increasing order, each to within 2−k2^{-k} before the root after kk bisection steps. The distance from the vertex to the triangle changes at most at the speed LL of the points, so if L 2−k≤δL\,2^{-k} \le \delta, the check passes at the reported value of the first contact. So in exact arithmetic the test returns a time that is not after the first contact, and at which the distance is at most δ\delta. In floating point the proof does not hold, and the pitfalls below are real.

Proof: The cubic CCD tests find every root in order and never return a time after the first contactfull

Each of the four points xi(t)=xi0+t (xi1−xi0)x_i(t) = x_i^0 + t\,(x_i^1 - x_i^0) moves on a line for t∈[0,1]t \in [0, 1], with the velocity wi=xi1−xi0w_i = x_i^1 - x_i^0. For the vertex-face test the points are p,a,b,cp, a, b, c, and a contact at time tt means that p(t)p(t) is in the closed triangle a(t)b(t)c(t)a(t) b(t) c(t). For the edge-edge test the points are a,b,c,da, b, c, d, and a contact means that the closed segments a(t)b(t)a(t) b(t) and c(t)d(t)c(t) d(t) meet. Let D(t)D(t) be the distance of the vertex to the triangle, or of the two segments, so a contact is D(t)=0D(t) = 0. Let t∗t^* be the first contact time in [0,1][0, 1], if there is one. We work in the real RAM, so the arithmetic, the square root of the critical points, and the bisection are exact. Let δ>0\delta > 0 be the distance tolerance and kk the number of bisection steps.

Lemma 1 (contact implies a root). Let f(t)=u(t)⋅(v(t)×w(t))f(t) = u(t) \cdot (v(t) \times w(t)) with u=p−au = p - a, v=b−av = b - a, w=c−aw = c - a for a vertex and a face, and u=c−au = c - a, v=b−av = b - a, w=d−cw = d - c for two edges. Then ff is a polynomial of degree at most 3, and f(t)=0f(t) = 0 at each contact time.

Proof. Each of uu, vv, ww is affine in tt, and the triple product is linear in each factor, so ff has degree at most 3. The triple product is the signed volume of the box spanned by uu, vv, ww, and it is 0 exactly when the three vectors are linearly dependent. At a vertex-face contact, p−ap - a is a combination of b−ab - a and c−ac - a. At an edge-edge contact there are s,r∈[0,1]s, r \in [0, 1] with a+s(b−a)=c+r(d−c)a + s(b - a) = c + r(d - c), so c−a=s(b−a)−r(d−c)c - a = s(b - a) - r(d - c). In both cases the vectors are dependent. □\square

Lemma 2 (all roots, in order). Suppose ff is not the zero polynomial. Let 0=z0<z1<⋯<zm=10 = z_0 < z_1 < \dots < z_m = 1 be 0, the roots of f′f' in (0,1)(0, 1), and 1, with m≤3m \le 3. Then each piece [zj,zj+1][z_j, z_{j+1}] has at most one root of ff, and it has one exactly when f(zj) f(zj+1)≤0f(z_j)\, f(z_{j+1}) \le 0. The loop of the code reports, for each root rr of ff in [0,1][0, 1] and in increasing order, a value r~\tilde r with r−2−k≤r~≤rr - 2^{-k} \le \tilde r \le r, and it reports nothing else.

Proof. f′f' has no root inside a piece, so it has one sign there, and ff is strictly monotone on the piece, or constant if f′≡0f' \equiv 0. A constant ff is not 0 here, so it has no root. A strictly monotone function has at most one root, and by the intermediate value theorem it has one exactly when the end values do not have the same strict sign. The code checks the pieces from left to right. If f(zj)=0f(z_j) = 0, it reports zjz_j. If the end values have strictly opposite signs, the bisection keeps a bracket [l,h][l, h] with f(l)f(l) of the sign of f(zj)f(z_j) and the root in (l,h](l, h], and halves it kk times, so it reports ll with r−2−k≤l≤rr - 2^{-k} \le l \le r, or the root itself if a midpoint hits it. If f(zj+1)=0f(z_{j+1}) = 0, the root is the left end of the next piece, or zm=1z_m = 1, which the last check reports. The duplicate removal drops a value that is not larger than the last one, which happens only for a root at a shared end zjz_j. So each root is reported once, in order. □\square

Lemma 3 (the distance is Lipschitz). ∣D(s)−D(t)∣≤L ∣s−t∣|D(s) - D(t)| \le L\,|s - t| with L=∣wp∣+max⁡(∣wa∣,∣wb∣,∣wc∣)L = |w_p| + \max(|w_a|, |w_b|, |w_c|) for a vertex and a face, and L=max⁡(∣wa∣,∣wb∣)+max⁡(∣wc∣,∣wd∣)L = \max(|w_a|, |w_b|) + \max(|w_c|, |w_d|) for two edges.

Proof. For a vertex and a face, D(t)=min⁡λ∣p(t)−∑iλixi(t)∣D(t) = \min_\lambda |p(t) - \sum_i \lambda_i x_i(t)| over the barycentric weights λ≥0\lambda \ge 0 with ∑iλi=1\sum_i \lambda_i = 1. For a fixed λ\lambda, the point ∑iλixi(t)\sum_i \lambda_i x_i(t) moves with the velocity ∑iλiwi\sum_i \lambda_i w_i, which has a length of at most max⁡i∣wi∣\max_i |w_i|. So each function in the minimum is LL-Lipschitz, and so is their minimum. The edge-edge case is the same with two weights. □\square

Theorem. Suppose ff is not the zero polynomial and L 2−k≤δL\,2^{-k} \le \delta. If the vertex and the face (or the two edges) touch in [0,1][0, 1], the test returns a time tt with t≤t∗t \le t^* and D(t)≤δD(t) \le \delta. If the test returns a time tt, then D(t)≤δD(t) \le \delta, and tt is within 2−k2^{-k} before a root of ff. If D(t)>δD(t) > \delta at every time within 2−k2^{-k} before each root of ff, the test returns no time. The test always terminates.

Proof. By Lemma 1, t∗t^* is a root of ff, and by Lemma 2 the loop meets a value r~\tilde r with t∗−2−k≤r~≤t∗t^* - 2^{-k} \le \tilde r \le t^*. By Lemma 3, D(r~)≤D(t∗)+L 2−k≤δD(\tilde r) \le D(t^*) + L\,2^{-k} \le \delta, so the check passes at r~\tilde r. The test returns the first value that passes, so it returns a time t≤r~≤t∗t \le \tilde r \le t^* with D(t)≤δD(t) \le \delta. The other two claims are the check itself and Lemma 2. The loop runs over at most three roots, and each bisection has kk steps, so the test terminates. ■\blacksquare

The exact count. For Fraction input, the coefficients of ff are exact, and so is the Sturm sequence p0=fp_0 = f, p1=f′p_1 = f', pi+1=−(pi−1 mod pi)p_{i+1} = -(p_{i-1} \bmod p_i). By Sturm's theorem, for l<hl < h that are not roots of ff, the number of sign changes of the sequence at ll minus that at hh is the number of distinct real roots of ff in (l,h)(l, h). The tests compare this exact count with the number of float roots that the loop finds.

Remarks. The theorem says nothing about floating point. There, the coefficients of ff, the critical points and the contact check have rounding errors. A root at which ff only touches 0 (a grazing contact) can become two close roots or none. A contact on an edge or at a vertex of a triangle can fail the check on both triangles that share it if δ=0\delta = 0. A positive δ\delta catches these cases, but it also reports near misses as contacts. Exact methods, such as that of Brochu, Edwards and Bridson (2012), evaluate the needed signs exactly and do not need the tolerance for correctness.

Complexity

A test costs O(1)O(1) arithmetic for the cubic and the critical points, at most three bisections of kk steps, and at most three distance checks, so O(k)O(k). The implementation uses k=80k = 80, and a bisection stops earlier when the bracket cannot be split in floating point. The extra space is O(1)O(1). For meshes the cost is in the number of pairs: a mesh pair has a vertex-face test for each vertex and triangle and an edge-edge test for each pair of edges, so a broad phase with swept boxes must prune the pairs first.

Properties

  • First contact. The tests return the earliest contact in the step, not just whether one happens, as a simulator needs for a time of impact.
  • No missed sign changes. Splitting at the critical points finds two roots that are close together, where ff has no sign change between the samples of a sampling method. In the tests of this page, a dense sampling with 600 steps missed one planted contact of 80, with two roots 0.00044 apart, and the critical point split found it.
  • Exact cubic with exact input. With Fraction input the coefficients and the signs of ff are exact. The code also gives an exact Sturm count of the roots, which the tests compare with the float roots on 400 random cubics.
  • Not exact in floating point. The roots, the critical points and the inside check have rounding errors. A tolerance δ>0\delta > 0 makes the test more conservative, at the cost of reporting near misses as contacts.

Variants and improvements

  • Exact tests. Brochu, Edwards and Bridson (2012) decide if a contact happens in the step with exact predicates, by the parity of the crossings of a ray with the space-time surface of the moving points. It never misses a contact, but it does not give the time directly.
  • Inclusion-based tests. Wang, Ferguson, Schneider, Jiang, Attene and Panozzo (2021) solve the contact equations in the parameters of the step and of the two primitives with interval arithmetic and subdivision, with a guaranteed conservative answer. Their benchmark shows false negatives in floating point cubic solvers.
  • A minimum separation. Cloth codes test for a time when the distance is at most a thickness η\eta, not 0, so that the contact is found before the meshes touch. With δ=η\delta = \eta this is the test of this page.
  • Rigid motion. With rotation the points do not move on lines, and the equation is not a cubic. Use conservative advancement, or approximate the motion by lines on sub-steps.

When to use it

Use these tests for deformable triangle meshes, such as cloth and soft bodies, where each vertex moves on a line during the step. They are the narrow phase under a broad phase of swept bounding boxes. Use an exact or inclusion-based variant when a missed contact is not acceptable, for example in the line search of incremental potential contact, where a missed contact lets the meshes pass through each other.

Pitfalls

  • A hit on a shared edge. In the tests of this page, a vertex goes down through the shared edge of two triangles at t=1/3t = 1/3, from (0.15,0.85,1)(0.15, 0.85, 1) to (0.15,0.85,−2)(0.15, 0.85, -2). With δ=0\delta = 0 both triangles miss the hit, because 0.15+0.850.15 + 0.85 is not exactly 1 after the rounding of the inputs, and the vertex passes through the mesh. With δ=10−12\delta = 10^{-12} both find it.
  • Grazing contacts. If the vertex only touches the plane, ff has a double root, and a rounding error can turn it into two close roots or none.
  • Coplanar motion. If the four points stay coplanar, ff is zero for all tt. Detect this case and use a 2D test.
  • Degenerate triangles and parallel edges. A barycentric inside test divides by the area of the triangle. A closest-point test, as in the code, handles thin triangles and parallel edges without a division by zero.
  • Scale. The coefficients of ff grow with the cube of the coordinates. Use a tolerance relative to the size of the scene and to the speeds, not a fixed number.

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.

elementary_ccd.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/elementary-ccd-tests/. The authors are listed in prov/RXJ8EY.jsonl.

"""Vertex-face and edge-edge continuous collision tests in 3D.

Each point moves on a line from its position at t = 0 to its position at t = 1. Four points are
coplanar at time t exactly when the triple product f(t) = u(t) . (v(t) x w(t)) is 0, where for a
vertex p and a triangle abc, u = p - a, v = b - a, w = c - a, and for edges ab and cd,
u = c - a, v = b - a, w = d - c. Each of u, v, w is linear in t, so f is a cubic.

The tests find the roots of f in [0, 1] in increasing order: the critical points of f (a quadratic)
split [0, 1] into pieces on which f is monotone, and bisection finds the root of each piece with a
sign change. At each root they check if the vertex is on the triangle, or if the edges meet, with
a distance tolerance delta. The first root that passes is the time of impact.

The cubic works on float or on Fraction input. sturm_count gives the exact number of distinct
roots in an open interval with Fraction arithmetic, which the tests use to check the float roots.

The module is not named after the slug, because a file name that ends in "tests" counts as a
test file.
"""

from __future__ import annotations

import math

Vec = tuple


def _sub(p, q):
    return (p[0] - q[0], p[1] - q[1], p[2] - q[2])


def _dot(u, v):
    return u[0] * v[0] + u[1] * v[1] + u[2] * v[2]


def _cross(u, v):
    return (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0])


def _lerp(p0, p1, t):
    return (p0[0] + t * (p1[0] - p0[0]), p0[1] + t * (p1[1] - p0[1]), p0[2] + t * (p1[2] - p0[2]))


def _pmul(a: list, b: list) -> list:
    out = [0] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            out[i + j] += x * y
    return out


def _padd(a: list, b: list) -> list:
    n = max(len(a), len(b))
    return [(a[i] if i < len(a) else 0) + (b[i] if i < len(b) else 0) for i in range(n)]


def _psub(a: list, b: list) -> list:
    return _padd(a, [-x for x in b])


def triple_product_cubic(u0, u1, v0, v1, w0, w1) -> list:
    """Coefficients [c0, c1, c2, c3] of f(t) = u(t) . (v(t) x w(t)) for linear u, v, w."""
    U = [[u0[i], u1[i] - u0[i]] for i in range(3)]
    V = [[v0[i], v1[i] - v0[i]] for i in range(3)]
    W = [[w0[i], w1[i] - w0[i]] for i in range(3)]
    f = [0]
    for i, j, k in ((0, 1, 2), (1, 2, 0), (2, 0, 1)):
        f = _padd(f, _pmul(U[i], _psub(_pmul(V[j], W[k]), _pmul(V[k], W[j]))))
    return (f + [0, 0, 0, 0])[:4]


def vertex_face_cubic(p0, p1, a0, a1, b0, b1, c0, c1) -> list:
    """The coplanarity cubic of a moving vertex p and a moving triangle abc."""
    return triple_product_cubic(_sub(p0, a0), _sub(p1, a1), _sub(b0, a0), _sub(b1, a1), _sub(c0, a0), _sub(c1, a1))


def edge_edge_cubic(a0, a1, b0, b1, c0, c1, d0, d1) -> list:
    """The coplanarity cubic of a moving edge ab and a moving edge cd."""
    return triple_product_cubic(_sub(c0, a0), _sub(c1, a1), _sub(b0, a0), _sub(b1, a1), _sub(d0, c0), _sub(d1, c1))


def poly_eval(c: list, t):
    r = 0
    for x in reversed(c):
        r = r * t + x
    return r


def _quadratic_roots(A: float, B: float, C: float) -> list[float]:
    if A == 0:
        return [] if B == 0 else [-C / B]
    disc = B * B - 4 * A * C
    if disc < 0:
        return []
    q = -(B + math.copysign(math.sqrt(disc), B)) / 2
    roots = [q / A]
    if q != 0:
        roots.append(C / q)
    return sorted(roots)


def cubic_roots_01(c: list, iters: int = 80) -> list[float]:
    """The roots of the cubic c in [0, 1], in increasing order, found in floating point.

    Raises ValueError if c is the zero polynomial (the four points stay coplanar).
    """
    c = [float(x) for x in c]
    if all(x == 0 for x in c):
        raise ValueError("the points are coplanar at all times")
    crit = [t for t in _quadratic_roots(3 * c[3], 2 * c[2], c[1]) if 0 < t < 1]  # @line L2
    pts = [0.0] + crit + [1.0]
    roots: list[float] = []
    for lo, hi in zip(pts, pts[1:]):  # @line L3
        flo, fhi = poly_eval(c, lo), poly_eval(c, hi)
        if flo == 0:
            roots.append(lo)
        elif fhi != 0 and (flo < 0) != (fhi < 0):  # @line L4
            for _ in range(iters):  # bisection on a monotone piece, keeping f(lo) of the sign of f(start)
                mid = (lo + hi) / 2
                if not lo < mid < hi:
                    break
                fm = poly_eval(c, mid)
                if fm == 0:
                    lo = mid
                    break
                if (fm < 0) == (flo < 0):
                    lo, flo = mid, fm
                else:
                    hi = mid
            roots.append(lo)  # the end of the bracket before the root, so the time is not late
    if poly_eval(c, 1.0) == 0:
        roots.append(1.0)
    out: list[float] = []
    for r in roots:
        if not out or r > out[-1]:
            out.append(r)
    return out


def closest_point_on_triangle(p, a, b, c):
    """The point of the triangle abc closest to p, by its Voronoi regions."""
    ab, ac, ap = _sub(b, a), _sub(c, a), _sub(p, a)
    d1, d2 = _dot(ab, ap), _dot(ac, ap)
    if d1 <= 0 and d2 <= 0:
        return a
    bp = _sub(p, b)
    d3, d4 = _dot(ab, bp), _dot(ac, bp)
    if d3 >= 0 and d4 <= d3:
        return b
    vc = d1 * d4 - d3 * d2
    if vc <= 0 and d1 >= 0 and d3 <= 0:
        return _lerp(a, b, d1 / (d1 - d3))
    cp = _sub(p, c)
    d5, d6 = _dot(ab, cp), _dot(ac, cp)
    if d6 >= 0 and d5 <= d6:
        return c
    vb = d5 * d2 - d1 * d6
    if vb <= 0 and d2 >= 0 and d6 <= 0:
        return _lerp(a, c, d2 / (d2 - d6))
    va = d3 * d6 - d5 * d4
    if va <= 0 and d4 - d3 >= 0 and d5 - d6 >= 0:
        return _lerp(b, c, (d4 - d3) / ((d4 - d3) + (d5 - d6)))
    s = va + vb + vc
    v, w = vb / s, vc / s
    return (a[0] + ab[0] * v + ac[0] * w, a[1] + ab[1] * v + ac[1] * w, a[2] + ab[2] * v + ac[2] * w)


def closest_points_segments(p1, q1, p2, q2):
    """Closest points of the segments p1q1 and p2q2."""
    d1, d2, r = _sub(q1, p1), _sub(q2, p2), _sub(p1, p2)
    a, e, f = _dot(d1, d1), _dot(d2, d2), _dot(d2, r)

    def clamp(x):
        return 0 if x < 0 else 1 if x > 1 else x

    if a == 0 and e == 0:
        s = t = 0
    elif a == 0:
        s, t = 0, clamp(f / e)
    else:
        cc = _dot(d1, r)
        if e == 0:
            s, t = clamp(-cc / a), 0
        else:
            b = _dot(d1, d2)
            denom = a * e - b * b
            s = clamp((b * f - cc * e) / denom) if denom != 0 else 0
            t = (b * s + f) / e
            if t < 0:
                s, t = clamp(-cc / a), 0
            elif t > 1:
                s, t = clamp((b - cc) / a), 1
    return _lerp(p1, q1, s), _lerp(p2, q2, t)


def _dist(p, q) -> float:
    return math.sqrt(float(_dot(_sub(p, q), _sub(p, q))))


def vertex_face_ccd(p0, p1, a0, a1, b0, b1, c0, c1, delta: float = 1e-9):
    """The first time in [0, 1] at which the moving vertex is on the moving triangle, or None."""
    c = vertex_face_cubic(p0, p1, a0, a1, b0, b1, c0, c1)  # @line L1
    for t in cubic_roots_01(c):  # @line L5
        p, a, b, cc = (_lerp(x0, x1, t) for x0, x1 in ((p0, p1), (a0, a1), (b0, b1), (c0, c1)))
        if _dist(p, closest_point_on_triangle(p, a, b, cc)) <= delta:  # @line L6
            return t  # @line L7
    return None  # @line L8


def edge_edge_ccd(a0, a1, b0, b1, c0, c1, d0, d1, delta: float = 1e-9):
    """The first time in [0, 1] at which the moving edges ab and cd meet, or None."""
    c = edge_edge_cubic(a0, a1, b0, b1, c0, c1, d0, d1)
    for t in cubic_roots_01(c):
        a, b, cc, d = (_lerp(x0, x1, t) for x0, x1 in ((a0, a1), (b0, b1), (c0, c1), (d0, d1)))
        x, y = closest_points_segments(a, b, cc, d)
        if _dist(x, y) <= delta:
            return t
    return None


def sturm_count(c: list, lo, hi) -> int:
    """The exact number of distinct real roots of the polynomial c in the open interval (lo, hi).

    Use Fraction coefficients and bounds, with lo and hi not roots. c must not be zero.
    """
    def trim(p):
        p = list(p)
        while p and p[-1] == 0:
            p.pop()
        return p

    def rem(a, b):
        a = list(a)
        while len(a) >= len(b):
            k = a[-1] / b[-1]
            shift = len(a) - len(b)
            for i in range(len(b)):
                a[shift + i] -= k * b[i]
            a.pop()
            a = trim(a)
            if not a:
                break
        return a

    p0 = trim(c)
    seq = [p0, trim([i * p0[i] for i in range(1, len(p0))])]
    while seq[-1]:
        r = rem(seq[-2], seq[-1])
        if not r:
            break
        seq.append([-x for x in r])

    def changes(x):
        signs = [s for s in (poly_eval(p, x) for p in seq if p) if s != 0]
        return sum(1 for u, v in zip(signs, signs[1:]) if (u < 0) != (v < 0))

    return changes(lo) - changes(hi)
elementary_ccd_tests.py 17 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/elementary-ccd-tests/. The authors are listed in prov/RXJ8EY.jsonl.

"""The module named after the slug. The code is in elementary_ccd.py, because a file name that ends in "tests" counts as a test file, and the checker reads no @line markers in a test file."""

from elementary_ccd import (  # noqa: F401
    closest_point_on_triangle,
    closest_points_segments,
    cubic_roots_01,
    edge_edge_ccd,
    edge_edge_cubic,
    poly_eval,
    sturm_count,
    triple_product_cubic,
    vertex_face_ccd,
    vertex_face_cubic,
)
test_elementary_ccd_tests.py 280 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/elementary-ccd-tests/. The authors are listed in prov/RXJ8EY.jsonl.

import math
import random
from fractions import Fraction

import pytest

from elementary_ccd import (
    closest_point_on_triangle,
    closest_points_segments,
    cubic_roots_01,
    edge_edge_ccd,
    edge_edge_cubic,
    poly_eval,
    sturm_count,
    vertex_face_ccd,
    vertex_face_cubic,
)


def sub(p, q):
    return tuple(x - y for x, y in zip(p, q))


def cross(u, v):
    return (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0])


def dot(u, v):
    return sum(x * y for x, y in zip(u, v))


def lerp(p0, p1, t):
    return tuple(x + t * (y - x) for x, y in zip(p0, p1))


def dist(p, q):
    return math.sqrt(dot(sub(p, q), sub(p, q)))


def rand_point(rng, lo=-3, hi=3, exact=False):
    if exact:
        return tuple(Fraction(rng.randint(8 * lo, 8 * hi), 8) for _ in range(3))
    return tuple(rng.uniform(lo, hi) for _ in range(3))


EXAMPLE = dict(
    p0=(3, 1, 3), p1=(1, 0, 0), a0=(0, 0, 0), a1=(0, 0, 0), b0=(4, 0, 0), b1=(5, 2, 3), c0=(0, 4, 0), c1=(1, -2, 0)
)


def example_args():
    e = EXAMPLE
    return e["p0"], e["p1"], e["a0"], e["a1"], e["b0"], e["b1"], e["c0"], e["c1"]


def test_page_example():
    c = vertex_face_cubic(*example_args())
    assert c == [48, -144, 117, -15]
    roots = cubic_roots_01(c)
    assert len(roots) == 2
    assert abs(roots[0] - (7 - math.sqrt(33)) / 2) < 1e-15 and abs(roots[1] - 0.8) < 1e-15
    assert sturm_count([Fraction(x) for x in c], Fraction(0), Fraction(1)) == 2
    # the first root is outside the triangle, the second one is the hit
    p0, p1, a0, a1, b0, b1, c0, c1 = example_args()
    t = roots[0]
    p, a, b, cc = lerp(p0, p1, t), lerp(a0, a1, t), lerp(b0, b1, t), lerp(c0, c1, t)
    assert abs(dist(p, closest_point_on_triangle(p, a, b, cc)) - 0.40047538) < 1e-8
    t = vertex_face_ccd(*example_args())
    assert 0.8 - 1e-15 <= t <= 0.8
    # the exact contact point at t = 4/5 has the barycentric coordinates (1/2, 1/4, 1/4)
    T = Fraction(4, 5)
    P = lerp(EXAMPLE["p0"], EXAMPLE["p1"], T)
    B, C = lerp(EXAMPLE["b0"], EXAMPLE["b1"], T), lerp(EXAMPLE["c0"], EXAMPLE["c1"], T)
    assert P == tuple(Fraction(1, 4) * x + Fraction(1, 4) * y for x, y in zip(B, C))


def test_cubic_equals_the_triple_product_exactly():
    rng = random.Random(11)
    for _ in range(100):
        pts = [rand_point(rng, exact=True) for _ in range(8)]
        cvf = vertex_face_cubic(*pts)
        cee = edge_edge_cubic(*pts)
        for _ in range(4):
            t = Fraction(rng.randint(0, 100), 100)
            x = [lerp(pts[2 * i], pts[2 * i + 1], t) for i in range(4)]
            p, a, b, c = x
            assert poly_eval(cvf, t) == dot(sub(p, a), cross(sub(b, a), sub(c, a)))
            a, b, c, d = x
            assert poly_eval(cee, t) == dot(sub(c, a), cross(sub(b, a), sub(d, c)))


def test_float_roots_against_an_exact_sturm_count():
    rng = random.Random(1997)
    total = 0
    for _ in range(400):
        pts = [rand_point(rng, exact=True) for _ in range(8)]
        c = (vertex_face_cubic if rng.random() < 0.5 else edge_edge_cubic)(*pts)
        if c[0] == 0 or sum(c) == 0 or all(x == 0 for x in c):
            continue
        roots = cubic_roots_01(c)
        n = sturm_count(c, Fraction(0), Fraction(1))
        assert len(roots) == n
        total += n
        for r in roots:  # the exact sign changes across each float root
            lo, hi = Fraction(max(0.0, r - 1e-9)), Fraction(min(1.0, r + 1e-9))
            assert poly_eval(c, lo) * poly_eval(c, hi) <= 0
    assert total >= 100


SAMPLES = 600


def reference_first_hit(f, contact, samples=SAMPLES):
    """Dense sampling of f for sign changes, bisection, and the contact check."""
    prev_t, prev_f = 0.0, f(0.0)
    if prev_f == 0 and contact(0.0):
        return 0.0
    for i in range(1, samples + 1):
        t = i / samples
        ft = f(t)
        if (ft < 0) != (prev_f < 0) or ft == 0:
            lo, hi, flo = prev_t, t, prev_f
            for _ in range(60):
                mid = (lo + hi) / 2
                fm = f(mid)
                if (fm < 0) == (flo < 0) and fm != 0:
                    lo, flo = mid, fm
                else:
                    hi = mid
            if contact(lo) or contact(hi):
                return lo
        prev_t, prev_f = t, ft
    return None


def vf_reference(pts, delta):
    p0, p1, a0, a1, b0, b1, c0, c1 = pts

    def at(t):
        return lerp(p0, p1, t), lerp(a0, a1, t), lerp(b0, b1, t), lerp(c0, c1, t)

    def f(t):
        p, a, b, c = at(t)
        return dot(sub(p, a), cross(sub(b, a), sub(c, a)))

    def contact(t):
        p, a, b, c = at(t)
        return dist(p, closest_point_on_triangle(p, a, b, c)) <= delta

    return reference_first_hit(f, contact)


def ee_reference(pts, delta):
    a0, a1, b0, b1, c0, c1, d0, d1 = pts

    def at(t):
        return lerp(a0, a1, t), lerp(b0, b1, t), lerp(c0, c1, t), lerp(d0, d1, t)

    def f(t):
        a, b, c, d = at(t)
        return dot(sub(c, a), cross(sub(b, a), sub(d, c)))

    def contact(t):
        a, b, c, d = at(t)
        x, y = closest_points_segments(a, b, c, d)
        return dist(x, y) <= delta

    return reference_first_hit(f, contact)


def planted(rng, kind):
    """A random linear motion with a contact at a known time t*."""
    t_star = rng.uniform(0.1, 0.9)
    vel = [rand_point(rng, -2, 2) for _ in range(4)]
    if kind == "vf":
        a, b, c = (rand_point(rng) for _ in range(3))
        w = [rng.uniform(0.05, 1) for _ in range(3)]
        s = sum(w)
        p = tuple((w[0] * x + w[1] * y + w[2] * z) / s for x, y, z in zip(a, b, c))
        at_star = [p, a, b, c]
    else:
        a, b, c = (rand_point(rng) for _ in range(3))
        u, v = rng.uniform(0.05, 0.95), rng.uniform(0.05, 0.95)
        x = lerp(a, b, u)  # the meeting point, on ab, and on cd at the parameter v
        d = tuple(c[i] + (x[i] - c[i]) / v for i in range(3))
        at_star = [a, b, c, d]
    pts = []
    for q, w in zip(at_star, vel):
        pts += [tuple(q[i] - t_star * w[i] for i in range(3)), tuple(q[i] + (1 - t_star) * w[i] for i in range(3))]
    return t_star, pts


@pytest.mark.parametrize("kind", ["vf", "ee"])
def test_planted_contacts(kind):
    rng = random.Random(7 if kind == "vf" else 8)
    test = vertex_face_ccd if kind == "vf" else edge_edge_ccd
    sampling_missed = 0
    for _ in range(80):
        t_star, pts = planted(rng, kind)
        t = test(*pts, delta=1e-7)
        assert t is not None and t <= t_star + 1e-12
        ref = (vf_reference if kind == "vf" else ee_reference)(pts, 1e-7)
        if ref is None:
            sampling_missed += 1
            assert close_pair_of_roots(kind, pts)
        else:
            assert abs(t - ref) < 1e-6
    assert sampling_missed <= 2


def close_pair_of_roots(kind, pts):
    """Two roots in one sample interval: f has no sign change there, so the sampling misses them."""
    roots = cubic_roots_01((vertex_face_cubic if kind == "vf" else edge_edge_cubic)(*pts))
    return any(r2 - r1 < 2 / SAMPLES for r1, r2 in zip(roots, roots[1:]))


@pytest.mark.parametrize("kind", ["vf", "ee"])
def test_random_motions_against_dense_sampling(kind):
    rng = random.Random(21 if kind == "vf" else 22)
    test = vertex_face_ccd if kind == "vf" else edge_edge_ccd
    hits = 0
    for _ in range(150):
        pts = [rand_point(rng) for _ in range(8)]
        t = test(*pts, delta=1e-7)
        ref = (vf_reference if kind == "vf" else ee_reference)(pts, 1e-7)
        if ref is not None:
            assert t is not None and abs(t - ref) < 1e-6
        elif t is not None:
            assert close_pair_of_roots(kind, pts)
        hits += t is not None
    assert hits >= 10


def test_closest_point_routines_against_sampling():
    rng = random.Random(3)
    for _ in range(80):
        a, b, c, p = (rand_point(rng) for _ in range(4))
        q = closest_point_on_triangle(p, a, b, c)
        best = min(
            dist(p, tuple(a[k] + i / 20 * (b[k] - a[k]) + j / 20 * (c[k] - a[k]) for k in range(3)))
            for i in range(21)
            for j in range(21 - i)
        )
        assert dist(p, q) <= best + 1e-12
        n = cross(sub(b, a), sub(c, a))  # q is in the plane of the triangle
        assert abs(dot(sub(q, a), n)) <= 1e-9 * (1 + dot(n, n))
        p1, q1, p2, q2 = (rand_point(rng) for _ in range(4))
        x, y = closest_points_segments(p1, q1, p2, q2)
        best = min(dist(lerp(p1, q1, i / 30), lerp(p2, q2, j / 30)) for i in range(31) for j in range(31))
        assert dist(x, y) <= best + 1e-12


def test_a_hit_on_a_shared_edge_needs_the_tolerance():
    # the vertex goes down through the shared edge bc of the triangles abc and cbd at t = 1/3
    a, b, c, d = (0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (1.0, 1.0, 0.0)
    p0, p1 = (0.15, 0.85, 1.0), (0.15, 0.85, -2.0)

    def run(q0, q1, delta):
        return [vertex_face_ccd(q0, q1, *[x for q in tri for x in (q, q)], delta=delta) for tri in ((a, b, c), (c, b, d))]

    assert all(t is not None and abs(t - 1 / 3) < 1e-15 for t in run(p0, p1, 1e-12))
    # with delta = 0, a hit inside a triangle is found, because the root gives z = 0 exactly here
    assert run((0.25, 0.25, 1.0), (0.25, 0.25, -2.0), 0.0)[0] is not None
    # but 0.15 + 0.85 is not 1 after rounding of the inputs, and both triangles miss the hit on bc
    assert run(p0, p1, 0.0) == [None, None]
    # with exact rational input and an exact root, the contact check is exact
    F = Fraction
    P0, P1 = (F(3, 10), F(7, 10), F(1)), (F(3, 10), F(7, 10), F(-2))
    T = F(1, 3)
    P = lerp(P0, P1, T)
    A, B, C = (F(0), F(0), F(0)), (F(1), F(0), F(0)), (F(0), F(1), F(0))
    assert closest_point_on_triangle(P, A, B, C) == P


def test_coplanar_motion_is_reported():
    with pytest.raises(ValueError):
        vertex_face_ccd((0.2, 0.2, 0.0), (0.5, 0.5, 0.0), (0, 0, 0), (0, 0, 0), (1, 0, 0), (1, 0, 0), (0, 1, 0), (0, 1, 0))

History

Provot (1997) used the vertex-face and edge-edge cubics with a check at each root for the collisions and self-collisions of cloth, and Bridson, Fedkiw and Anderson (2002) used them with a thickness tolerance in their robust treatment of cloth collisions. Later work showed that floating point cubic solvers miss contacts. Brochu, Edwards and Bridson (2012) gave an exact test, and Wang and others (2021) gave a large benchmark of hard queries and a conservative inclusion-based method.

References

  1. Xavier Provot, Collision and self-collision handling in cloth model dedicated to design garments, Computer Animation and Simulation 97 (Proceedings of the Eurographics Workshop), Springer, 1997, 177 to 189, the vertex-face and edge-edge tests with the cubic coplanarity equation and the check at each root
  2. Tyson Brochu, Essex Edwards and Robert Bridson, Efficient geometrically exact continuous collision detection, ACM Transactions on Graphics 31(4), 2012, article 96, the failure cases of floating point cubic solvers and the exact test by root parity
  3. Bolun Wang, Zachary Ferguson, Teseo Schneider, Xin Jiang, Marco Attene and Daniele Panozzo, A large-scale benchmark and an inclusion-based algorithm for continuous collision detection, ACM Transactions on Graphics 40(5), 2021, article 188, the benchmark of vertex-face and edge-edge queries, the false negatives of the methods it compares, and the conservative inclusion-based method

Where this leads

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.roots
  • a full proof of time.test
  • 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