4/5/17
Basic Game Physics
IMGD 4000
With material from: Introduc on to Game Development, Second Edi on, Steve Rabin (ed), Cengage Learning, 2009. (Chapter 4.3) and Ar ficial Intelligence for Games, Ian Millington, Morgan Kaufmann, 2006 (Chapter 3)
Introduc on (1 of 2)
• What is game physics? – Compu ng mo on of objects in virtual scene • Including player avatars, NPC’s, inanimate objects – Compu ng mechanical interac ons of objects • Interac on usually involves contact (collision) – Simula on must be real- me (versus high- precision simula on for CAD/CAM, etc.) – Simula on may be very realis c, approximate, or inten onally distorted (for effect)
2
1 4/5/17
Introduc on (2 of 2)
• And why is it important? – Can improve immersion – Can support new gameplay elements – Becoming increasingly prominent (expected) part of high-end games – Like AI and graphics, facilitated by hardware developments (mul -core, GPU) – Matura on of physics engine market
3
Physics Engines
• Similar buy vs. build analysis as game engines – Buy: • Complete solu on from day one • Proven, robust code base (hopefully) • Feature sets are pre-defined • Costs range from free to expensive – Build: • Choose exactly features you want • Opportunity for more game-specifica on op miza ons • Greater opportunity to innovate • Cost guaranteed to be expensive (unless features extremely minimal)
4
2 4/5/17
Physics Engines
• Open source – Box2D, Bullet, Chipmunk, JigLib, ODE, OPAL, OpenTissue, PAL, Tokamak, Farseer, Physics2d, Glaze • Closed source (limited free distribu on) – Newton Game Dynamics, Simple Physics Engine, True Axis, PhysX • Commercial – Havok, nV Physics, Vortex • Rela on to Game Engines – Na ve, e.g,. C4 – Integrated, e.g., UE4 + PhysX – Pluggable, e.g., C4 + PhysX, jME + ODE (via jME Physics)
Basic Game Physics Concepts
• Why are we studying this? – To use an engine effec vely, you need to understand something about what it’s doing – You may need to implement small features or extensions yourself – Cf., owning a car without understanding anything about how it works • Examples – Kinema cs and dynamics – Projec le mo on – Collision detec on and response
6
3 4/5/17
Outline
• Introduc on (done) • Kinema cs (next) • The Firing Solu on • Collision Detec on • Ragdoll Physics • PhysX
7
Kinema cs (1 of 3)
• Study of mo on of objects without taking into account mass or force • Basic quan es: posi on, me • ... and their deriva ves: velocity, accelera on • Basic equa ons: Where: 1) d = vt t - (elapsed) me d - distance (change in posi on) 2) v = u + at v - (final) velocity (change in distance per unit me) 3) d = ut + ½at2 a - accelera on (change in velocity per unit me) 2 2 u - (ini al) velocity 4) v = u + 2ad
Note, equa on #3 is the integral of equa on #2 with respect to me (see next slide). Equa on #4 can be useful. 8
4 4/5/17
Kinema cs (2 of 3)
Non-accelerated mo on Accelerated mo on
d = ut d = ut + ½at2 Example: Example: u = 20 m/s, t = 300 s u=0 m/s, a=4m/s2, t=3s d = 20 x 3000 = 6000 m d = 0x3 + 0.5x4x9 = 18m
Kinema cs (3 of 3)
Predic on Example: If you throw a ball straight up into the air with an ini al velocity of 10 m/ sec, how high will it go? v = 0 v2 = u2 + 2ad d a = -10 u = 10 m/sec (ini al speed upward) a = -10 m/sec2 (approx gravity) v = 0 m/sec (at top of flight) u = 10 0 = 102 + 2(-10)d d = 5 meters (Note, answer independent of mass of ball!)
10
5 4/5/17
Doing It In 3D
• Mathema cally, consider all quan es involving posi on to be vectors: d = vt v = u + at d = ut + at2/2 • Computa onally, using appropriate 3-element vector datatype
11
Dynamics
• No ce that preceding kinema c descrip ons say nothing about why an object accelerates (or why its accelera on might change) • To get a full “modern” physical simula on you need to add two more basic concepts: – force – mass • Discovered by Sir Isaac Newton • Around 1700 J
12
6 4/5/17
Newton’s Laws 1. A body will remain at rest or con nue to move in a straight line at a constant speed unless acted upon by a force. 2. The accelera on of a body is propor onal to the resultant force ac ng on the body and is in the same direc on as the resultant force. 3. For every ac on, there is an equal and opposite reac on.
13
Mo on Without Newton’s Laws
• Pac-Man or early Mario style – Follow path with instantaneous changes in speed and direc on (velocity)
– Not physically possible • Note - fine for some casual games (especially with appropriate anima ons)
14
7 4/5/17
Newton’s Second Law F = ma
At each moment in me: F = force vector, in Newton’s m = mass (intrinsic scalar property of ma er), in kg a = accelera on vector, in m/sec2
Player cares about state of world (posi on of objects). Equa on is fundamental driver of all physics simula ons. • Force causes accelera on (a = F/m) • Accelera on causes change in velocity Kinema cs • Velocity causes change in posi on equa ons 15
How Are Forces Applied?
• May involve contact – Collision (rebound) – Fric on (rolling, sliding) • Without contact – Rockets/Muscles/Propellers – Gravity – Wind (if not modeling air par cles) – Magic • Dynamic (force) modeling also used for autonomous steering behaviors
16
8 4/5/17
Compu ng Kinema cs in Real Time start = getTime() // start time p = 0 // initial position u = 10 // initial velocity a = -10 d
function update () { // in game loop a = -10 now = getTime() t = now – start simulate(t) } u, p
function simulate (t) { 2 d = (u + (0.5 * a * t)) * t d = ut + at /2 move object to p + d // move to loc. computed since start }
Note! Number of calls and me values to simulate() depend on (changing) game loop me (frame rate) Is this a problem? It can be! For rigid body simula on with colliding forces and fric on (e.g., many interes ng cases) … leading to “jerky” behavior 17
Frame Rate Independence
• Complex numerical simula ons used in physics engines are sensi ve to me steps (due to trunca on error and other numerical effects) • But results need to be repeatable regardless of CPU/GPU performance – for debugging – for game play • So, if frame rate drops (game loop can’t keep up), then physics will change • Solu on: Control physics simula on interval independently of frame rate
18
9 4/5/17
Frame Rate Independence delta simula on cks lag frame updates previous now
start = ... delta = 0.02 // physics simula on interval (sec) lag = 0 // me since last simulated previous = 0 // me of previous call to update
function update() { // in game loop now = getTime() t = (previous - start) – lag // previous simulate() lag = lag + (now - previous) // current lag while ( lag > delta ) // repeat un l caught up t = t + delta simulate(t) lag = lag - delta previous = now // simula on caught up to current me } 19
Outline
• Introduc on (done) • Kinema cs (done) • The Firing Solu on (next) • Collision Detec on • Ragdoll Physics • PhysX
20
10 4/5/17
The Firing Solu on (1 of 3) • How to hit target – Beam weapon or high-velocity bullet over short ranges can be viewed as traveling in straight line – But projec le travels in parabolic arc • Grenade, spear, catapult, etc. d = ut + at2/2
a = [0, 0, -9.8] m/sec2 (but can use higher value, e.g., -18) d u = velocity vector
Most typical game situa ons, magnitude of u fixed. We only need to know rela ve components (orienta on) à Challenge:
• Given a, d, solve for u 21
Remember Quadra c Equa ons?
• Make nice curves – Like firing at target! • Solu ons are where equals 0. E.g., when firing with gun on ground: – At gun muzzle – At target • But unlike in algebra class, not just solving quadra c but finding angle with y = gun, y = target • Angle changes speed in x-direc on, but also me spent in air • A er hairy math [Millington 3.5.3], three relevant cases: – Target is out of range (no solu on) • Solve with quadra c formula – Target is at exact maximum range (single solu on) – Target is closer than maximum range (two possible solu ons)
22
11 4/5/17
The Firing Solu on (2 of 3)
long me trajectory
short me trajectory [Millington 3.5.3]
u = (2Δ - at2) / (2 (muzzle_v) t) d u = muzzle velocity vector where muzzle_v = max muzzle speed Δ is difference vector from d to u • Usually choose short me trajectory a is gravity – Gives target less me to escape – Unless shoo ng over wall, etc.
23
The Firing Solu on (3 of 3) function firingSolution (start, target, muzzle_v, gravity) {
// Calculate vector back from target to start delta = target - start
// Real-valued coefficents of quadra c equa on a = gravity * gravity b = -4 * (gravity * delta + muzzle_v * muzzle_v) c = 4 * delta * delta
// Check for no real solu ons if ( 4 * a * c > b * b ) return null
// Find short and long mes to target disc = sqrt (b * b - 4 * a *c) Note, a, b and c are scalars t1 = sqrt ( ( -b + disc ) / (2 * a )) so a normal square root. t2 = sqrt ( ( -b - disc ) / (2 * a ))
// Pick shortest valid me to target ( t) if ( t1 < 0 ) && ( t2 < 0) return null // No valid mes if ( t1 < 0 ) ttt = t2 else if ( t2 < 0 ) ttt = t1 else Note scalar product of two vectors using *: ttt = min ( t1, t2 ) [a,b,c] * [d,e,f] = a*d + b*e + c*f // Return firing vector return ( 2 * delta - gravity * ttt * ttt ) / ( 2 * muzzle_v * ttt ) }
[Millington 3.5.3] 24
12 4/5/17
Outline
• Introduc on (done) • Kinema cs (done) • The Firing Solu on (done) • Collision Detec on (next) • Ragdoll Physics • PhysX
25
Collision Detec on
• Determining when objects collide is not as easy as it seems – Geometry can be complex – Objects can be moving quickly – There can be many objects • naive algorithms are O(n2) • Two basic approaches: – Overlap tes ng • Detects whether collision has already occurred – Intersec on tes ng • Predicts whether collision will occur in future
26
13 4/5/17
Basics – discussed and Overlap Tes ng implemented in IMGD 3000!
• Most common technique used in games • Exhibits more error than intersec on tes ng • Basic idea: – at every simula on step, test every pair of objects to see if overlap • Easy for simple volumes (e.g., spheres), harder for polygonal models • Results of test: – collision normal vector (useful for reac on) – me that collision took place
27
Overlap Tes ng: Finding Collision Time
• Calculated by doing “binary search” in me, moving object back and forth by 1/2 steps (bisec ons) A
t0 A A A A t0.25 A t0.375 t0.4375 t0.40625 t0.5
t1
B B B B B B Initial Overlap Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 Test Forward 1/2 Backward 1/4 Forward 1/8 Forward 1/16 Backward 1/32 • In prac ce, five itera ons usually enough
28
14 4/5/17
Limita ons of Overlap Tes ng
• Fails with objects that move too fast (no overlap during simula on me slice) window
t-1 t0 t1 t2 bullet
• Solu on approach: – constrain game design so that fastest object moves smaller distance in one physics “ ck” (delta) than thinnest object – may require reducing simula on step size (adds computa on overhead)
29
Intersec on Tes ng • Predict future collisions • Extrude geometry in direc on of movement – e.g., “swept” sphere turns into capsule shape
t0
t1
• Then, see if extruded shape overlaps objects • When collision found (predicted) – Move simula on to me of collision (have collision point) – Resolve collision – Works for bullet/window example (bullet becomes line segment)
30
15 4/5/17
Speeding Up Collision Detec on
• Bounding Volumes – Oriented – Hierarchical • Par oning • Plane Sweep
31
Bounding Volumes • Commonly used volumes – sphere - distance between centers less than sum of radii – boxes axis aligned (loose fit, easier math) oriented ( ghter fit, more expensive)
Axis-Aligned Bounding Box Oriented Bounding Box • If bounding volumes don’t overlap, then no more tes ng is required – If overlap, more refined tes ng required – Bounding volume alone may be good enough for some games
32
16 4/5/17
Complex Bounding Volumes
• Mul ple volumes per object – e.g., separate volumes for head, torso and limbs of avatar object
• Hierarchical volumes – e.g., boxes inside of boxes
[Go schalk, Lin, Minocha, SIGGRAPH ’96]
33
Par oning for Collision Tes ng • To address the n2 problem... • Par on space so only test objects in same cell
• In best case (uniform distribu on) reduces n2 to linear – Can happen for uniform size, density objects (e.g., cloth/fluids) • In worst case (all objects in same cell) no improvement
34
17 4/5/17
Plane Sweep for Collision Tes ng • Observa on: many moveable objects stay in one place most of the me • Sort bounds along axes (expensive to do, so do just once!) • Only adjacent sorted objects which overlap on all axes need to be checked further • Since many objects don’t move, can keep sort up to date very cheaply with bubblesort (nearly linear) y
B1 A1 R1 B A B0 R A0 C1 R0 C
C0
A0 A1 R0 B0 R1 C0 B1 C1 x
35
Outline
• Introduc on (done) • Kinema cs (done) • The Firing Solu on (done) • Collision Detec on (done) • Ragdoll Physics (next) • PhysX
36
18 4/5/17
What is Ragdoll Physics? • Procedural anima on o en used as replacement for tradi onal (sta c) death anima on – Generated by code, not hand – Using physics constraints on body limbs & joints in real- me S ll from early anima on using ragdoll physics h ps://en.wikipedia.org/wiki/Ragdoll_physics
h p://www.freeonlinegames.com/game/ragdoll-physics-2
Diablo 3 Ragdolls
“How to Smack a Demon” Erin Ca o
(Game Developer’s Conference, San Francisco, California, USA, 2013)
Physics Programmer for Diablo 3 (Blizzard, 2012)
19 4/5/17
A ragdoll is a collec on of collision shapes connected to bones
20 4/5/17
21 4/5/17
Physics joints connect two bones
Cone Joint Revolute Joint (like shoulder) (like elbow)
Tech ar st connects bones with Physics joints
Spherical Joint Weld Joint (for chandeliers) (locks two bodies, for advanced)
22 4/5/17
Par al ragdolls add flavor to living characters
Not just for death and destruc on
23 4/5/17
More Physics We Are Not Covering
• Collision response • Conserva on of momentum • Elas c collisions • Non-elas c collisions – coefficient of res tu on • Rigid body simula on (vs. point masses) • Joints as constraints to mo on • So body simula on
[see excellent book by Millington, “Game Physics Engine Development”, MK, 2007] 47
Outline
• Introduc on (done) • Kinema cs (done) • The Firing Solu on (done) • Collision Detec on (done) • Ragdoll Physics (done) • PhysX (next)
48
24 4/5/17
PhysX Overview
• Developed by NVIDIA for C++ applica ons • Windows, Mac, Linux, Playsta on, Xbox, Android, Apple iOS and Wii • Simulate – Fluids – So bodies (cloth, hair) – Rigid bodies (boxes, bones)
Why Does NVIDIA Make Physics So ware?
• NVIDIA is mainly known as a developer and manufacturer of graphics hardware (GPU’s)
• So taking advantage of GPU for hardware accelera on of their physics engine – Algorithms can be tuned to their hardware – Giving a compe ve advantage over other GPU manufacturers
50
25 4/5/17
Configure Video Card as Dedicated PhysX Processor
Dedicated to PhysX
What Algorithms Does PhysX Use? • Hard to know exactly, because algorithm details are NVIDIA’s intellectual property (IP)
• However from various forums and clues, it is clear PhysX uses: – Both sweep and overlap collision detec on – AABB and OBBT and (both axis-aligned and oriented bounding bounding box trees) – Constraints: hinges, springs, etc. – and lots of other hairy stuff, see h ps://devtalk.nvidia.com/default/board/66/physx-and-physics-modeling/
52
26 4/5/17
Rocket Sled
CES 2010, Rocket Sled demonstrates both graphics and physics compu ng capabili es of new GF100 (Fermi) GPUs.
Raging Rapids Ride
Graphics ok, but with intensive and complex real- me fluid simula on
27 4/5/17
Havok Cloth
PhysX compe tor bought by Microso
• Binary – Free! • Source code (e.g., to modify), costs How to Use PhsyX • General documenta on NVIDIA® PhysX® SDK Documenta on h p://docs.nvidia.com/gameworks/content/gameworkslibrary/physx/guide/Index.html • UE4 guide – PhysX, Integra ng PhysX Code into Your Project (by Rama) h ps://wiki.unrealengine.com/PhysX,_Integra ng_PhysX_Code_into_Your_Project
28