Download presentation
Presentation is loading. Please wait.
2
Physics for Games Programmers: Collision Detection
Gino van den Bergen Playlogic
3
Three Phases Broad phase: Determine all pairs of objects that potentially collide. Mid phase: Determine potentially colliding primitives of a pair of objects. Narrow phase: Determine contact between two primitive shapes.
4
Overview Narrow phase: Mid phase: AABB tree Broad phase:
Discrete: GJK algorithm Continuous: GJK ray cast algorithm Mid phase: AABB tree Broad phase: Discrete: Sweep & Prune Continuous: Space-time Sweep & Prune
5
Discrete Collision Detection
Perform collision detection at sampled instances of time. Suffers from tunneling, i.e., collisions in-between sampled instances are not detected. Collisions are generally detected too late. Contact data is obtained for interpenetrating objects by computing the penetration depth.
6
Continuous Collision Detection
Perform collision detection in continuous space-time. Construct a plausible trajectory for each moving object. Detect collisions along these trajectories, using time as an added dimension. Obtain expected time of impact and contact data for colliding pairs.
7
Plausible Trajectory? Limited to trajectories with piecewise constant linear velocities. Angular velocities are ignored. Rotations are considered instantaneous.
8
Only Translations Solving continuous rotations is a lot more complex, so we’d rather dodge the issue. Tunneling may occur for rotating objects, but is less visible and often acceptable. Doing continuous translations only already fixes most of our problems and is doable in real time.
9
Narrow Phase: GJK Algorithm
An iterative method for computing the distance between convex objects. First publication in 1988 by Gilbert, Johnson, and Keerthi. Solves queries in configuration space. Uses an implicit object representation.
10
GJK Algorithm: Pros Extremely versatile:
Applicable to any combination of convex shape types. Computes distances, common points, and separating axes. Can be tailored for finding space-time collisions. Allows a smooth trade-off between accuracy and speed.
11
GJK Algorithm: Pros (cont'd)
Performs well: Exploits frame coherence. Competitive with dedicated solutions for polytopes (Lin-Canny, V-Clip, SWIFT) . Despite its conceptual complexity, implementing GJK is not too difficult. Small code size.
12
GJK Algorithm: Cons Difficult to grasp:
Concepts from linear algebra and convex analysis (determinants, Minkowski addition), take some time to get comfortable with. Maintaining a “geometric” mental image of the workings of the algorithm is challenging and not very helpful.
13
GJK Algorithm: Cons (cont'd)
Suffers from numerical issues: Termination is governed by predicates that rely on tolerances. Despite the use of tolerances, certain “hacks” are needed in order to guarantee termination in all cases. Using 32-bit floating-point numbers is doable but tricky.
14
Configuration Space (recap)
The configuration space obstacle of objects A and B is the set of all vectors from a point of B to a point of A.
15
Configuration Space (cont’d)
A and B intersect: A – B contains origin. Distance between A and B: length of shortest vector in A – B.
16
Translation Translation of A and/or B results in a translation of A – B.
17
Rotation Rotation of A and/or B changes the shape of A – B.
18
GJK Algorithm: Workings
Approximate the point of the CSO closest to the origin Generate a sequence of simplices inside the CSO, each simplex lying closer to the origin than its predecessor. A simplex is a point, a line segment, a triangle, or a tetrahedron.
19
GJK Algorithm: Workings (cont’d)
Simplex vertices are computed using support mappings. (Definition follows) Terminate as soon as the current simplex is close enough. In case of an intersection, the simplex contains the origin.
20
Any point on this face may be returned as support point
Support Mappings A support mapping sA of an object A maps vectors to points of A, such that Any point on this face may be returned as support point
21
Primitives
22
More Primitives
23
Affine Transformation
Shapes can be translated, rotated, and scaled. For T(x) = Bx + c, we have
24
Convex Hull Convex hulls of arbitrary convex shapes are readily available.
25
Minkowski Sum Shapes can be fattened by Minkowski addition.
26
Basic Steps (1/6) Suppose we have a simplex inside the CSO…
27
Basic Steps (2/6) …and the point v of the simplex closest to the origin.
28
Basic Steps (3/6) Compute support point w = sA-B(-v).
29
Basic Steps (4/6) Add support point w to the current simplex.
30
Basic Steps (5/6) Compute the closest point v’ of the new simplex.
31
Basic Steps (6/6) Discard all vertices that do not contribute to v’.
32
Termination (1/3) As upper bound for the squared distance we take the squared length of v. As lower bound we take v∙w, the signed distance of the supporting plane through w. Terminate a soon as where εrel is the tolerance for the relative error in the computed distance.
33
Termination (2/3) +
34
Termination (3/3) In case of a (near) contact, v will approximate zero, in which case previous termination condition is not likely to be met. As secondary termination condition we use where v is the current closest point, W is the set of vertices of the current simplex, and εtol is a tolerance based on the machine epsilon.
35
Separating Axes If only an intersection test is needed then let GJK terminate as soon as the lower bound v∙w becomes positive. For a positive lower bound v∙w, the vector v is a separating axis. The origin and the CSO lie on different sides of the supporting plane, and thus, the CSO cannot contain the origin.
36
Separating Axes (cont'd)
The supporting plane through w separates the origin from the CSO. +
37
Separating Axes and Coherence
Separating axes can be cached and reused as initial v in future tests on the same object pairs. When the degree of frame coherence is high, the cached v is likely to be a separating axis in the new frame as well. An incremental version of GJK takes roughly one iteration per frame for smoothly moving objects.
38
Computing Contact Data
For interpenetrating objects GJK returns a simplex W (usually a tetrahedron) that contains the origin. GJK also returns the barycentric coordinates of the origin with respect to W. These are the λi for which
39
Common Point Recall that simplex W is obtained from subtracting support points of A and B, thus These support points form simplices contained by the respective objects. By storing these support points we can compute a common point
40
Contact Normal For doing physics we also need a contact normal. If the objects are at close range but not intersecting then the vector v at termination can be used as a contact normal. However, keeping the objects from interpenetrating can be problematic.
41
Penetration Depth For interpenetrating objects we use the penetration depth vector as contact normal. The penetration depth is the shortest distance over which one of the two objects needs to be translated in order to stop the objects from interpenetrating.
42
Penetration Depth (cont'd)
The vector v is the penetration depth vector. +
43
Expanding Polytope Algorithm
Penetration depth cannot be computed using GJK. For this you need a separate algorithm called Expanding Polytope Algorithm. EPA relies also on support mappings and is applicable to the same family of convex shapes.
44
Shape Casting Find the earliest time two translated objects come in contact. Boils down to performing a ray cast in the objects’ configuration space. For objects A and B being translated over respectively vectors s and t, we perform a ray cast along the vector r = t – s onto A – B. The earliest time of contact is
45
Normals A normal at the hit point of the ray is normal to the contact plane.
46
Ray Clipping
47
Ray Clipping (cont'd) For , we know that
If v∙r > 0 then λ is a lower bound for the hit spot, and if also v·w > 0, the ray is clipped. If v·r < 0 then λ is an upper bound, and if also v·w > 0, then the ray misses. If v·r = 0 and v·w > 0, the ray misses as well.
48
GJK Ray Cast Do a standard GJK iteration, and use the support planes as clipping planes. Each time the ray is clipped, the origin is “shifted” to λr,… …and the current simplex is set to the last-found support point. The vector -v that corresponds to the latest clipping plane is the normal at the hit point.
49
The origin advances to the new lower bound.
GJK Ray Cast (cont'd) The origin advances to the new lower bound. The vector -v is the latest normal.
50
Termination The origin advances only if v·w > 0, which must happen within a finite number of iterations if the origin is not contained in the query object. Terminate as soon as the origin is close enough to the query object, or we have evidence that the ray misses. As termination condition in case of a hit we use
51
Accuracy vs. Performance
Accuracy can be traded for performance by tweaking the error tolerance εtol. A greater tolerance results in fewer iterations but less accurate hit points and normals.
52
Accuracy vs. Performance
εtol = 10-7, avg. time: GHz
53
Accuracy vs. Performance
εtol = 10-6, avg. time: GHz
54
Accuracy vs. Performance
εtol = 10-5, avg. time: GHz
55
Accuracy vs. Performance
εtol = 10-4, avg. time: GHz
56
Accuracy vs. Performance
εtol = 10-3, avg. time: GHz
57
Accuracy vs. Performance
εtol = 10-2, avg. time: GHz
58
Accuracy vs. Performance
εtol = 10-1, avg. time: GHz
59
Mid Phase: BV Trees Used for objects composed of lots of primitives, such as triangle meshes. Aim is to quickly reject groups of primitives based on geometric locality. ‘Capture’ locality by constructing a hierarchy of bounding volumes.
60
Bounding Volumes Should fit the model as tightly as possible.
Overlap tests between volumes should be cheap. Should use a small amount of memory. Cost of computing the best-fit bounding volume should be low.
61
Bounding Volumes Good bounding volume types are: Spheres
Axis-aligned bounding boxes (AABBs) Discrete-orientation polytopes (k-DOPs) Oriented bounding boxes (OBBs) Capsules (Sphere-swept line segments)
62
Bounding Volume Types Fit Test (ops) Memory (scalars) Best-fit Cost
Sphere poor 11 4 high AABB fair ≤ 6 6 low k-DOP good ≤ 2k 2k medium OBB excellent ≤ 200 15
63
Why AABBs? Offer a fair trade-off between storage space and fit.
Overlap tests are fast. Allow for fast construction and update of bounding volumes. Storage requirements can be further reduced through compression.
64
AABB Tree Construction
Compute the AABB of the set of primitives. Split the set using the plane that cuts the longest axis of the AABB in two equal halves. Primitives that straddle the plane are added to the dominant side. (AABBs of the two sets may overlap.) Repeat from step 1 for the split sets. Continue until all sets contain one primitive.
65
AABB Tree Construction
Demo
66
AABB Trees: Test One Object
Compute the object’s AABB in the AABB tree’s local coordinate system. Recursively visit all nodes whose AABBs overlap the object’s AABB. Test each visited leaf’s primitive against the object.
67
AABB Trees: Test Two Trees
Simultaneously descend in both trees. Requires an oriented-box test such as the SAT. Always unfold the largest of the current two AABBs. If both sub-trees are leaves, perform a primitive-primitive test.
68
Updating AABB Trees AABB trees can be updated rather than recomputed for deformable meshes. First recompute the AABBs of the leaves. Work your way back to the root: A parent’s box is the AABB of the children’s boxes.
69
Compressed AABB Trees [Gomez]
Each pair of child boxes has at least six sides in common with the parent box. The six new sides are represented relative to the parent’s sides using fixed-point deltas. (one byte per side) Use short-s as child references. (Max. 216 primitives in one AABB tree.)
70
Compressed AABB Trees (cont’d)
Add one byte for flags: Six bits, one for each side of the parent box, represent which of the two children borrows the corresponding side. Two bits, one for each child, represent whether the corresponding child is a leaf. This makes a total of 11 bytes per prim.
71
Broad Phase: Sweep & Prune
Find pairs of objects whose axis-aligned bounding boxes overlap. We need something better than the O(n2) test-all-pairs approach. Exploit temporal coherence: the configuration of objects does not change a lot per frame.
72
AABB Computation The projection of an object A onto an axis e is the interval: Compute an object’s AABB by projecting the object onto the world axes. The AABB of an oriented AABB Tree is the AABB of the root box.
73
Sweep and Prune (1/3) For each world axis, maintain a sorted list of interval endpoints. Maintain also the set of overlapping box pairs. When a box moves, locally re-sort the lists by comparing and (if necessary) swapping the box endpoints with adjacent endpoints.
74
Sweep and Prune (2/3) Re-order endpoints of moving objects. A B
75
Sweep and Prune (2/3) Re-order endpoints of moving objects. A B
76
Sweep and Prune (3/3) When swapping “][“ to “[]”, the intervals start to overlap. When swapping “[]“ to “][”, the intervals cease to overlap. If the intervals on the other axes overlap, then the box pair starts or ceases to overlap.
77
Implementation “]” is greater than “[“ at equal positions
Mangle the least-significant bit: 0 = “[”, 1 = “]”. Beware of float sign! For negative numbers: 1 = “[”, 0 = “]”. Better still: use fixed-point numbers for storing endpoint positions. Integer comparisons are generally faster than float comparisons.
78
Implementation (cont'd)
Endpoint lists are best implemented using arrays (std::vector): Local sorting on arrays is CPU-cache friendly. Each object maintains two indices per array. Interval overlap tests can be done using array indices rather than endpoint positions.
79
Adding Time: Encapsulation
Enlarge AABBs of moving objects, such that they encapsulate the swept AABBs. Creates false positives: Encapsulating AABBs overlap where in space-time, the actual AABBs do not.
80
Adding Time: Encapsulation (cont'd)
Encapsulation results in false positives. A B
81
Adding Time: Queued Swaps
Perform endpoint swaps in the proper order. Calculate swap times and prioritize swaps on earliest time. After each swap, re-evaluate swaps with new neighbors. Needs a priority queue that offers a decrease-key operation (as in Dijkstra’s algorithm or A*).
82
Adding Time: Queued Swaps (cont'd)
Swap endpoints in the proper order. A B
83
Adding Time: Queued Swaps (cont'd)
Swap endpoints in the proper order. A B
84
Adding Time: Queued Swaps (cont'd)
Swap endpoints in the proper order. A B
85
Performance Queue operations dominate processing.
Despite added bookkeeping for decrease-key, best results so far are obtained using binary heaps. (Cormen et al.). Binomial heaps turned out slower due to expensive delete-min operation. Still have to try Fibonacci heaps, relaxed heaps, skew heaps, pairing heaps, …
86
Motion Coherence Space-time Sweep and Prune is often faster than the original version when many objects are moving in the same direction. Among a group of objects all having the same velocity vector not a single endpoint swap needs to be done. Ideal for particle and fluid simulations.
87
Conclusion Exact continuous collision detection of objects under translation is doable in real time. Unfortunately, exact continuous collision response is impossible in real-time. Gino’s paradox (in the spirit of Zeno): “Continuous motion is an illusion since you cannot resolve an infinite number of collisions in a finite amount of time.”
88
References Thomas H. Cormen et al. Introduction to Algorithms, Second Edition. MIT Press, 2001. E. G. Gilbert, D. W. Johnson, and S. S. Keerthi. A fast procedure for computing the distance between complex objects in three-dimensional space. IEEE Journal of Robotics and Automation, 4(2): , 1988. M. Gomez. Compressed Axis-Aligned Bounding Box Trees. In Game Programming Gems 2, edited by M. De Loura, pp Charles River Media, 2001. Gino van den Bergen. Collision Detection in Interactive 3D Environments. Morgan Kaufmann Publishers, 2004.
89
Thank You! For papers and other information, check: www.dtecta.com
For information about Playlogic, please visit:
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.