Algorithm Search⌘K

Algorithmadvanced

Conservative advancement

Also called conservative advancement CCD.

Advance time by the distance between two bodies divided by a bound on their approaching speed, repeating until they touch or the step ends.

Time
O(s D) callO(D) stepO(T L / e) steps_worst
Space
O(1) extra
Where
D = the cost of one distance query; L = a bound on the relative speed of all points; T = the length of the time interval; e = the distance tolerance; s = the number of steps
Properties
deterministicnot exactofflineiterative
Origin
Brian Mirtich, 1996

Conservative advancement is a method for continuous collision detection of two convex bodies that move during a time step. It computes the distance dd between the bodies at the current time, and a bound μ\mu on the speed at which any point of one body can approach the other. The bodies cannot touch before d/μd / \mu has passed, so the method moves the time forward by that amount and repeats. It stops when the distance is below a tolerance, which gives a time of impact from below, or when the time passes the end of the step. The method never steps past the first contact. It needs only a distance query, so it works for any convex shapes with a GJK or a closest-feature distance, and for any motion with a known speed bound.

In plain words

Two objects move during a short time. You want the first moment they touch.

Measure the gap between them now. You also know the fastest speed at which they can come together: the speed of the motion toward each other, plus the speed of the spin at the outer edge. In the time that it takes to close the gap at that top speed, they cannot touch. So you can jump that far ahead in time with no risk.

At the new time, measure the gap again and jump again. Each jump is safe. When the gap is tiny, report the time as the time of contact. If the time goes past the end of the step, they do not touch in this step.

The problem

The input is two convex polygons AA and BB with their vertices in local coordinates around their centers of rotation, a start pose, a constant velocity vv and a constant angular velocity ω\omega for each, an interval [0,T][0, T] and a tolerance tol>0\mathrm{tol} > 0. A local point pp of AA is at cA+vAt+R(θA+ωAt) pc_A + v_A t + R(\theta_A + \omega_A t)\, p at time tt. The output is a time tt with d(t)≤told(t) \le \mathrm{tol} that is not later than the first contact, or NO-CONTACT if the bodies do not touch in [0,T][0, T]. The 2D form on this page has the same structure as the 3D form, where ω\omega is a vector and the rotation part of the bound is ∣ω∣r|\omega| r in the same way.

The algorithm

  1. CONSERVATIVE-ADVANCEMENT(A, B, T, tol)
  2. 1t ← 0
  3. 2loop
  4. 3(d, pA, pB) ← DISTANCE(A(t), B(t))
  5. 4if d ≤ tol then return t
  6. 5n ← (pA - pB) / d
  7. 6μ ← -n · (vA - vB) + |ωA| rA + |ωB| rB
  8. 7if μ ≤ 0 then return NO-CONTACT
  9. 8t ← t + d / μ
  10. 9if t > T then return NO-CONTACT

Here rAr_A is the largest distance of a vertex of AA from its center of rotation. The first term of μ\mu is the speed of the translation along the closest direction nn, which is negative when the bodies move apart. The other terms bound the speed of any point that the rotation moves. The line through pBp_B with normal nn separates the bodies at time tt, and μ\mu bounds how fast the gap along nn can close, so the gap stays positive until t+d/μt + d/\mu. The implementation uses a brute force distance over all vertex-edge pairs. A real system uses GJK or a closest-feature walk, started from the result of the previous step.

Example

AA is the square with corners (±1,±1)(\pm 1, \pm 1), at rest. BB is the same square, with its center at (6,0)(6, 0), the velocity (−6,0)(-6, 0) and the angular velocity π\pi per unit of time. So rB=2r_B = \sqrt{2}, and the rotation adds π2≈4.443\pi \sqrt{2} \approx 4.443 to the bound. Take T=1T = 1 and tol=10−3\mathrm{tol} = 10^{-3}.

At t=0t = 0 the gap is d=4d = 4, between the right side of AA and the left side of BB, and n=(−1,0)n = (-1, 0). The bound is μ=6+4.443=10.443\mu = 6 + 4.443 = 10.443, so the first step is 4/10.443≈0.38304 / 10.443 \approx 0.3830. The direction nn stays (−1,0)(-1, 0) in all steps of this example, because the closest feature of AA stays its right side.

step t d d / μ
0 0 4 0.383036
1 0.383036 1.409299 0.134953
2 0.517989 0.837178 0.080167
3 0.598156 0.154728 0.014817
4 0.612973 0.036975 0.003541
5 0.616514 0.009246 0.000885
6 0.617399 0.002337 0.000224
7 0.617623 0.000592

At step 7 the gap is below the tolerance, and the method returns t≈0.617623t \approx 0.617623. Dense sampling and bisection give the first contact t∗≈0.617699t^* \approx 0.617699, when a corner of BB, turned by about 111111 degrees, hits the right side of AA. The answer is before t∗t^*, as it must be. Near the contact the gap shrinks by a factor of about 4 per step, because the true speed of the corner is about three quarters of the bound. With tol=10−2\mathrm{tol} = 10^{-2}, 10−410^{-4}, 10−610^{-6} and 10−810^{-8}, the method took 5, 9, 12 and 16 steps.

Correctness

The proof is in proofs/correctness.md. At time t0t_0 the line through the closest point of BB with normal nn separates the convex bodies with the gap d0d_0. A point of AA moves along nn by at least h n⋅vA−h ∣ωA∣ rAh\, n \cdot v_A - h\,|\omega_A|\, r_A in the time hh, because a rotation moves a point at the radius ∣p∣|p| by a chord, which is at most the arc ∣ω∣h∣p∣|\omega| h |p|. The same holds for BB. So every pair of points is at least d0−hμd_0 - h \mu apart, and the bodies cannot touch before h=d0/μh = d_0 / \mu. By induction, no time of the loop passes the first contact t∗t^*, and a NO-CONTACT answer is right. Each step that does not stop is longer than tol/L\mathrm{tol} / L, where LL bounds μ\mu, so the loop stops.

Proof: Conservative advancement never steps past the first contact, and stops when the gap is at most the tolerancefull

Let AA and BB be convex polygons that move over [0,T][0, T]. A point with local coordinates pp of body AA is at xp(t)=cA+vAt+R(θA+ωAt) px_p(t) = c_A + v_A t + R(\theta_A + \omega_A t)\, p, and the same holds for BB. Let rA=max⁡∣p∣r_A = \max |p| over the vertices of AA, which is also the maximum over all points of AA, and the same for rBr_B. Let d(t)d(t) be the distance between A(t)A(t) and B(t)B(t), and let t∗=min⁡{t∈[0,T]:d(t)=0}t^* = \min \{ t \in [0, T] : d(t) = 0 \} be the first contact, if there is one. Use exact arithmetic, and let tol>0\mathrm{tol} > 0.

Lemma 1 (the rotation part). For all t,st, s and pp, ∣R(θ+ωs) p−R(θ+ωt) p∣≤∣ω∣ ∣s−t∣ ∣p∣|R(\theta + \omega s)\,p - R(\theta + \omega t)\,p| \le |\omega|\,|s - t|\,|p|.

Proof. The two points are on the circle of radius ∣p∣|p|, at the angle ∣ω∣ ∣s−t∣|\omega|\,|s - t| apart. A chord is at most the arc, which is ∣ω∣ ∣s−t∣ ∣p∣|\omega|\,|s - t|\,|p|. □\square

Lemma 2 (the step is safe). Let t0∈[0,T]t_0 \in [0, T] with d0=d(t0)>0d_0 = d(t_0) > 0. Let pAp_A and pBp_B be a closest pair, n=(pA−pB)/d0n = (p_A - p_B) / d_0, and μ=−n⋅(vA−vB)+∣ωA∣ rA+∣ωB∣ rB\mu = -n \cdot (v_A - v_B) + |\omega_A|\, r_A + |\omega_B|\, r_B. Then for all t≥t0t \ge t_0,

d(t)≥d0−(t−t0) μ.d(t) \ge d_0 - (t - t_0)\,\mu.

Proof. Because A(t0)A(t_0) and B(t0)B(t_0) are convex and pA,pBp_A, p_B is a closest pair, the line through pBp_B with normal nn separates them: n⋅x≥n⋅pAn \cdot x \ge n \cdot p_A for x∈A(t0)x \in A(t_0) and n⋅y≤n⋅pBn \cdot y \le n \cdot p_B for y∈B(t0)y \in B(t_0). So n⋅(x−y)≥d0n \cdot (x - y) \ge d_0 for every pair. Now take a point pp of AA and a point qq of BB, and let h=t−t0≥0h = t - t_0 \ge 0. Then

xp(t)−xp(t0)=vAh+(R(θA+ωAt)−R(θA+ωAt0))p,x_p(t) - x_p(t_0) = v_A h + \big(R(\theta_A + \omega_A t) - R(\theta_A + \omega_A t_0)\big) p,

and by Lemma 1, n⋅(xp(t)−xp(t0))≥h n⋅vA−h ∣ωA∣ rAn \cdot (x_p(t) - x_p(t_0)) \ge h\, n \cdot v_A - h\, |\omega_A|\, r_A. In the same way, n⋅(yq(t)−yq(t0))≤h n⋅vB+h ∣ωB∣ rBn \cdot (y_q(t) - y_q(t_0)) \le h\, n \cdot v_B + h\, |\omega_B|\, r_B. Subtract:

n⋅(xp(t)−yq(t))≥d0+h n⋅(vA−vB)−h (∣ωA∣rA+∣ωB∣rB)=d0−hμ.n \cdot (x_p(t) - y_q(t)) \ge d_0 + h\, n \cdot (v_A - v_B) - h\,(|\omega_A| r_A + |\omega_B| r_B) = d_0 - h \mu.

For a unit vector nn, ∣x−y∣≥n⋅(x−y)|x - y| \ge n \cdot (x - y), so every pair of points is at least d0−hμd_0 - h\mu apart, and d(t)≥d0−hμd(t) \ge d_0 - h\mu. □\square

Theorem. Let t0=0<t1<t2<…t_0 = 0 < t_1 < t_2 < \dots be the times of the loop. If there is a first contact t∗t^*, then every tk≤t∗t_k \le t^*. If the loop returns a time tt, then d(t)≤told(t) \le \mathrm{tol} and t≤t∗t \le t^* when t∗t^* exists. If it returns NO-CONTACT, there is no contact in [0,T][0, T].

Proof. By induction, tk≤t∗t_k \le t^*, with t0=0t_0 = 0. A new time tk+1t_{k+1} is made only if d(tk)>tol>0d(t_k) > \mathrm{tol} > 0, so tk<t∗t_k < t^*. If μ≤0\mu \le 0, Lemma 2 gives d(t)≥d(tk)>0d(t) \ge d(t_k) > 0 for all t≥tkt \ge t_k, so there is no contact after tkt_k and none before it by the induction, and the answer NO-CONTACT of line L7 is right. If μ>0\mu > 0, Lemma 2 gives d(t)>0d(t) > 0 for t∈[tk,tk+d(tk)/μ)t \in [t_k, t_k + d(t_k)/\mu), so t∗≥tk+d(tk)/μ=tk+1t^* \ge t_k + d(t_k)/\mu = t_{k+1}. If tk+1>Tt_{k+1} > T, then t∗>Tt^* > T, and the answer NO-CONTACT of line L9 is right. A time returned by line L4 is some tkt_k with d(tk)≤told(t_k) \le \mathrm{tol}. □\square

Termination. Let L=∣vA−vB∣+∣ωA∣rA+∣ωB∣rBL = |v_A - v_B| + |\omega_A| r_A + |\omega_B| r_B. Each μ\mu is at most LL, so each step that does not stop is at least d(tk)/L>tol/Ld(t_k)/L > \mathrm{tol}/L. The times grow by more than tol/L\mathrm{tol}/L in each step and the loop stops when they pass TT, so there are at most ⌈TL/tol⌉+1\lceil T L / \mathrm{tol} \rceil + 1 steps. If L=0L = 0, the first μ\mu is 0 and the loop stops at once. ■\blacksquare

Remarks. The bound TL/tolT L / \mathrm{tol} grows without limit as the tolerance goes to 0, and the tests of this page show a grazing motion where the step count grows as the gap shrinks. For a head-on approach without rotation, μ\mu is exact and one step reaches the contact. For a contact at a positive angle the distance decreases at a rate bounded away from 0 near t∗t^*, and the gap then shrinks at least by a constant factor in each step, so the count grows like log⁡(1/tol)\log(1/\mathrm{tol}). This last claim needs a transversal contact and is not proved here. In floating point the computed distance and the bound have rounding errors, so a step can pass the contact by a few ulps. A small safety margin in the distance, for example using d−tol/2d - \mathrm{tol}/2 for the step, prevents this.

Complexity

Each step costs one distance query, O(D)O(D). With GJK on convex polytopes this is linear in the number of vertices, or close to O(1)O(1) with a closest-feature walk under coherent motion. The number of steps ss has no bound that is independent of the input. The proof gives s≤⌈TL/tol⌉+1s \le \lceil T L / \mathrm{tol} \rceil + 1. For a head-on approach without rotation, μ\mu is exact and one step reaches the contact. For a contact at a clear angle, the gap shrinks by a constant factor per step, as in the example, and ss grows like log⁡(1/tol)\log(1/\mathrm{tol}). This is observed, not proved. For a grazing motion, the gap stays small but positive and each step is short. In the tests of this page, a spinning square that passes another square with the smallest gap gg took 3, 9, 39 and 152 steps for g=1g = 1, 0.10.1, 0.010.01 and 0.0010.001. The extra space is O(1)O(1).

Properties

  • Conservative. In exact arithmetic the returned time is never after the first contact, and no contact is missed, also for fast rotation and thin objects. This is the property that discrete collision checks lack.
  • Any motion with a speed bound. The method needs a distance and a bound on the speed of the closest points. It does not need the motion to be linear: a screw motion or a spline motion works with a matching bound.
  • Approximate. It returns a time with a gap of at most tol\mathrm{tol}, not the exact time of contact.
  • Floating point. The distance and μ\mu have rounding errors. A step of (d−tol/2)/μ(d - \mathrm{tol}/2)/\mu keeps the result conservative when these errors are smaller than tol/2\mathrm{tol}/2.

Variants and improvements

  • Controlled advancement (C2A). Tang, Kim and Manocha (2009) apply the method to polygonal models with a bounding volume hierarchy, and control the size of the steps so that fewer of them are needed near the contact.
  • Nonconvex bodies. Run the method on the pairs of convex pieces or bounding volumes, and take the smallest time. A hierarchy lets the method skip pairs whose bound already shows no contact in the step.
  • Articulated bodies. For a chain of links, the speed bound of a link adds the bounds of its parents.
  • Exact tests for primitives. For triangle meshes with linear vertex motion, the elementary CCD tests solve a cubic for each vertex-face and edge-edge pair instead.

When to use it

Use conservative advancement to find the time of impact of two convex rigid bodies that rotate during a step, or of objects with a good distance query and a simple speed bound. It is the usual choice when the motion has a rotation, which makes the exact contact equations nonlinear. For meshes with linear vertex motion, as in cloth, use the elementary tests. Pair it with a broad phase such as sweep and prune over the swept bounding boxes, so that only near pairs reach the loop.

Pitfalls

  • A bound that is too small. If rr is measured from the center of mass but the body rotates about another point, or if ω\omega is the wrong norm, μ\mu is not a bound, and the method can step past the contact.
  • Tolerance zero. With tol=0\mathrm{tol} = 0, the loop approaches the contact in ever smaller steps and does not stop. Use a positive tolerance and a limit on the steps.
  • Grazing motion. A body that passes close to another with a spin makes many short steps. Limit the steps, and accept a conservative time if the limit is hit.
  • Penetration at the start. If d=0d = 0 at t=0t = 0, the method returns 0. Separate the bodies first, for example with the expanding polytope algorithm.
  • The sign of nn. The normal must point from BB to AA, so that the translation term is the approaching speed. With the wrong sign, the method steps too far when the bodies approach.

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.

conservative_advancement.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/conservative-advancement/. The authors are listed in prov/C2728X.jsonl.

"""Conservative advancement for two convex polygons with linear and angular velocity.

A body is a convex polygon with its vertices in local coordinates around its center of rotation,
a start position c0 and angle theta0, a constant velocity v and a constant angular velocity omega.
At time t its vertices are c0 + v t + R(theta0 + omega t) p.

conservative_advancement walks forward in time. At each time it computes the distance d and the
unit normal n from the closest point of B to the closest point of A. No point of the two bodies
can close the gap along n faster than mu = -n . (vA - vB) + |omegaA| rA + |omegaB| rB, where r is
the largest distance of a vertex from the center. So the bodies cannot touch before t + d / mu,
and the walk steps there. It stops when d <= tol (a time of impact, from below) or when the time
passes T or mu <= 0 (no contact in the interval). Floats are used, and tol must be positive.
"""

from __future__ import annotations

import math
from dataclasses import dataclass

Vec = tuple[float, float]


@dataclass(frozen=True)
class Body:
    local: list[Vec]  # counterclockwise convex polygon around the center of rotation
    c0: Vec
    theta0: float
    v: Vec
    omega: float

    def at(self, t: float) -> list[Vec]:
        th = self.theta0 + self.omega * t
        c, s = math.cos(th), math.sin(th)
        cx, cy = self.c0[0] + self.v[0] * t, self.c0[1] + self.v[1] * t
        return [(cx + c * x - s * y, cy + s * x + c * y) for x, y in self.local]

    def radius(self) -> float:
        return max(math.hypot(x, y) for x, y in self.local)


def _closest_on_segment(p: Vec, a: Vec, b: Vec) -> Vec:
    ex, ey = b[0] - a[0], b[1] - a[1]
    L = ex * ex + ey * ey
    lam = 0.0 if L == 0 else ((p[0] - a[0]) * ex + (p[1] - a[1]) * ey) / L
    lam = min(1.0, max(0.0, lam))
    return (a[0] + lam * ex, a[1] + lam * ey)


def _orient(a: Vec, b: Vec, c: Vec) -> float:
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])


def _inside(P: list[Vec], x: Vec) -> bool:
    return all(_orient(P[i], P[(i + 1) % len(P)], x) >= 0 for i in range(len(P)))


def _segments_cross(a: Vec, b: Vec, c: Vec, d: Vec) -> bool:
    # a proper crossing; touching cases give a distance of 0 below
    return _orient(a, b, c) * _orient(a, b, d) < 0 and _orient(c, d, a) * _orient(c, d, b) < 0


def polygon_distance(P: list[Vec], Q: list[Vec]) -> tuple[float, Vec, Vec]:
    """The distance of two convex polygons and a closest pair (pa on P, pb on Q); 0 if they meet."""
    for i in range(len(P)):
        for j in range(len(Q)):
            if _segments_cross(P[i], P[(i + 1) % len(P)], Q[j], Q[(j + 1) % len(Q)]):
                return 0.0, P[i], P[i]
    if _inside(Q, P[0]):
        return 0.0, P[0], P[0]
    if _inside(P, Q[0]):
        return 0.0, Q[0], Q[0]
    best = (math.inf, P[0], Q[0])
    for X, Y, flip in ((P, Q, False), (Q, P, True)):
        for x in X:
            for k in range(len(Y)):
                y = _closest_on_segment(x, Y[k], Y[(k + 1) % len(Y)])
                d = math.hypot(x[0] - y[0], x[1] - y[1])
                if d < best[0]:
                    best = (d, y, x) if flip else (d, x, y)
    return best


def conservative_advancement(A: Body, B: Body, T: float = 1.0, tol: float = 1e-6, max_iter: int = 100000):
    """The first time in [0, T] at which the distance is at most tol, or None, and the step count.

    The returned time is never later than the first time of contact.
    """
    rA, rB = A.radius(), B.radius()
    spin = abs(A.omega) * rA + abs(B.omega) * rB
    dv = (A.v[0] - B.v[0], A.v[1] - B.v[1])
    t = 0.0  # @line L1
    for steps in range(max_iter):  # @line L2
        d, pa, pb = polygon_distance(A.at(t), B.at(t))  # @line L3
        if d <= tol:  # @line L4
            return t, steps
        n = ((pa[0] - pb[0]) / d, (pa[1] - pb[1]) / d)  # @line L5
        mu = -(n[0] * dv[0] + n[1] * dv[1]) + spin  # @line L6
        if mu <= 0:  # @line L7
            return None, steps
        t += d / mu  # @line L8
        if t > T:  # @line L9
            return None, steps + 1
    raise RuntimeError("conservative advancement did not reach tol in max_iter steps")
test_conservative_advancement.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/conservative-advancement/. The authors are listed in prov/C2728X.jsonl.

import math
import random

from conservative_advancement import Body, conservative_advancement, polygon_distance

SQ = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]


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))
    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_body(rng, cx, cy):
    while True:
        h = hull([(rng.uniform(-1.5, 1.5), rng.uniform(-1.5, 1.5)) for _ in range(rng.randint(3, 7))])
        if len(h) >= 3 and abs(sum(cross((0, 0), h[i], h[(i + 1) % len(h)]) for i in range(len(h)))) > 0.5:
            break
    v = (rng.uniform(-8, 8), rng.uniform(-8, 8))
    return Body(h, (cx, cy), rng.uniform(0, 2 * math.pi), v, rng.uniform(-6, 6))


def dist(A, B, t):
    return polygon_distance(A.at(t), B.at(t))[0]


def first_contact(A, B, T=1.0, samples=400):
    """The first contact time by dense sampling and bisection, or None if no sample touches."""
    prev = 0.0
    if dist(A, B, 0.0) == 0:
        return 0.0
    for i in range(1, samples + 1):
        s = T * i / samples
        if dist(A, B, s) == 0:
            lo, hi = prev, s
            for _ in range(50):
                mid = (lo + hi) / 2
                if dist(A, B, mid) == 0:
                    hi = mid
                else:
                    lo = mid
            return hi
        prev = s
    return None


def test_polygon_distance():
    P = [(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]
    d, pa, pb = polygon_distance(P, [(5.0, 1.0), (7.0, 0.0), (7.0, 2.0)])
    assert (d, pa, pb) == (3.0, (2.0, 1.0), (5.0, 1.0))
    d, pa, pb = polygon_distance([(5.0, 1.0), (7.0, 0.0), (7.0, 2.0)], P)
    assert (d, pa, pb) == (3.0, (5.0, 1.0), (2.0, 1.0))
    assert polygon_distance(P, [(1.0, 1.0), (3.0, 1.0), (3.0, 3.0)])[0] == 0
    assert polygon_distance(P, [(0.5, 0.5), (1.5, 0.5), (1.0, 1.5)])[0] == 0
    assert polygon_distance(P, [(2.0, 2.0), (4.0, 2.0), (4.0, 4.0)])[0] == 0


def test_page_example():
    A = Body(SQ, (0.0, 0.0), 0.0, (0.0, 0.0), 0.0)
    B = Body(SQ, (6.0, 0.0), 0.0, (-6.0, 0.0), math.pi)
    t, steps = conservative_advancement(A, B, tol=1e-3)
    assert steps == 7 and abs(t - 0.6176228740) < 1e-9
    t_star = first_contact(A, B, samples=2000)
    assert abs(t_star - 0.61769886) < 1e-7
    assert t <= t_star and dist(A, B, t) <= 1e-3
    previous = -1.0
    for tol in (1e-2, 1e-4, 1e-6, 1e-8):
        t, _ = conservative_advancement(A, B, tol=tol)
        assert previous < t <= t_star
        previous = t


def test_random_motions_never_pass_the_first_contact():
    rng = random.Random(1996)
    hits = misses = 0
    for _ in range(120):
        A = random_body(rng, 0.0, 0.0)
        B = random_body(rng, rng.uniform(-9, 9), rng.uniform(-9, 9))
        s = rng.uniform(0.3, 1.5)  # aim B roughly at A, so that about half of the motions hit
        B = Body(B.local, B.c0, B.theta0, (-s * B.c0[0] + B.v[0] / 4, -s * B.c0[1] + B.v[1] / 4), B.omega)
        if dist(A, B, 0.0) == 0:
            continue
        t_star = first_contact(A, B)
        t, _ = conservative_advancement(A, B, tol=1e-7)
        if t_star is not None:
            hits += 1
            assert t is not None and t <= t_star
        if t is None:
            misses += 1
            assert t_star is None
        else:
            assert dist(A, B, t) <= 1e-7
    assert hits >= 20 and misses >= 20


def test_the_step_bound_is_a_true_bound():
    rng = random.Random(5)
    for _ in range(300):
        A = random_body(rng, 0.0, 0.0)
        B = random_body(rng, rng.uniform(-9, 9), rng.uniform(-9, 9))
        t0 = rng.uniform(0, 1)
        d0, pa, pb = polygon_distance(A.at(t0), B.at(t0))
        if d0 == 0:
            continue
        n = ((pa[0] - pb[0]) / d0, (pa[1] - pb[1]) / d0)
        dv = (A.v[0] - B.v[0], A.v[1] - B.v[1])
        mu = -(n[0] * dv[0] + n[1] * dv[1]) + abs(A.omega) * A.radius() + abs(B.omega) * B.radius()
        for _ in range(5):
            t1 = t0 + rng.uniform(0, 0.5)
            gap = min(n[0] * x[0] + n[1] * x[1] for x in A.at(t1)) - max(n[0] * y[0] + n[1] * y[1] for y in B.at(t1))
            assert gap >= d0 - (t1 - t0) * mu - 1e-9
            assert dist(A, B, t1) >= gap - 1e-9 or gap < 0


def test_simple_cases():
    A = Body(SQ, (0.0, 0.0), 0.0, (0.0, 0.0), 0.0)
    # moving apart without spin: the bound is negative at once
    assert conservative_advancement(A, Body(SQ, (4.0, 0.0), 0.0, (3.0, 0.0), 0.0)) == (None, 0)
    # head on without spin: the bound is exact, and one step reaches the contact
    t, steps = conservative_advancement(A, Body(SQ, (6.0, 0.0), 0.0, (-8.0, 0.0), 0.0))
    assert steps == 1 and abs(t - 0.5) < 1e-12
    # too slow to arrive before T
    assert conservative_advancement(A, Body(SQ, (6.0, 0.0), 0.0, (-2.0, 0.0), 0.0))[0] is None


def test_grazing_motion_needs_many_steps():
    A = Body(SQ, (0.0, 0.0), 0.0, (0.0, 0.0), 0.0)
    counts = []
    for g in (1.0, 0.1, 0.01, 0.001):
        B = Body(SQ, (-6.0, 1.0 + math.sqrt(2) + g), -math.pi / 4, (12.0, 0.0), math.pi)
        assert abs(dist(A, B, 0.5) - g) < 1e-9
        t, steps = conservative_advancement(A, B, tol=1e-6)
        assert t is None
        counts.append(steps)
    assert counts == [3, 9, 39, 152]

History

Mirtich used conservative advancement in his 1996 Berkeley thesis on impulse-based simulation of rigid bodies, where it finds the time of the next collision with distances from his closest-feature code. Later work extended the method to articulated models and to nonconvex meshes, and Tang, Kim and Manocha (2009) made the controlled form C2A for general polygonal models.

References

  1. Min Tang, Young J. Kim and Dinesh Manocha, C2A, controlled conservative advancement for continuous collision detection of polygonal models, Proceedings of the 2009 IEEE International Conference on Robotics and Automation, the description of conservative advancement for rigid motion, the bound on the motion of the closest points, and the controlled variant
  2. Brian Mirtich, V-Clip, fast and robust polyhedral collision detection, ACM Transactions on Graphics 17(3), 1998, 177 to 208, the closest features and distances that a time of impact loop of this kind uses
  3. Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann, 2005, Chapter 5, Basic Primitive Tests (the dynamic intersection tests of moving objects)

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.step
  • a full proof of time.steps_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