4/5/17

Basic

IMGD 4000

With material from: Introducon to Game Development, Second Edion, Steve Rabin (ed), Cengage Learning, 2009. (Chapter 4.3) and Arficial Intelligence for Games, Ian Millington, Morgan Kaufmann, 2006 (Chapter 3)

Introducon (1 of 2)

• What is game physics? – Compung moon of objects in virtual scene • Including player avatars, NPC’s, inanimate objects – Compung mechanical interacons of objects • Interacon usually involves contact (collision) – Simulaon must be real-me (versus high- precision simulaon for CAD/CAM, etc.) – Simulaon may be very realis, approximate, or intenonally distorted (for effect)

2

1 4/5/17

Introducon (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) – Maturaon of market

3

Physics Engines

• Similar buy vs. build analysis as game engines – Buy: • Complete soluon 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-specificaon opmizaons • Greater opportunity to innovate • Cost guaranteed to be expensive (unless features extremely minimal)

4

2 4/5/17

Physics Engines

• Open source – , , , JigLib, ODE, OPAL, OpenTissue, PAL, , Farseer, Physics2d, Glaze • Closed source (limited free distribuon) – , Simple Physics Engine, True Axis, PhysX • Commercial – , nV Physics, • Relaon to Game Engines – Nave, 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 effecvely, 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 – Kinemacs and dynamics – Projecle moon – Collision detecon and response

6

3 4/5/17

Outline

• Introducon (done) • Kinemacs (next) • The Firing Soluon • Collision Detecon • • PhysX

7

Kinemacs (1 of 3)

• Study of moon of objects without taking into account mass or force • Basic quanes: posion, me • ... and their derivaves: velocity, acceleraon • Basic equaons: Where: 1) d = vt t - (elapsed) me d - distance (change in posion) 2) v = u + at v - (final) velocity (change in distance per unit me) 3) d = ut + ½at2 a - acceleraon (change in velocity per unit me) 2 2 u - (inial) velocity 4) v = u + 2ad

Note, equaon #3 is the integral of equaon #2 with respect to me (see next slide). Equaon #4 can be useful. 8

4 4/5/17

Kinemacs (2 of 3)

Non-accelerated moon Accelerated moon

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

Kinemacs (3 of 3)

Predicon Example: If you throw a ball straight up into the air with an inial velocity of 10 m/ sec, how high will it go? v = 0 v2 = u2 + 2ad d a = -10 u = 10 m/sec (inial 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

• Mathemacally, consider all quanes involving posion to be vectors: d = vt v = u + at d = ut + at2/2 • Computaonally, using appropriate 3-element vector datatype

11

Dynamics

• Noce that preceding kinemac descripons say nothing about why an object accelerates (or why its acceleraon might change) • To get a full “modern” physical simulaon 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 connue to move in a straight line at a constant speed unless acted upon by a force. 2. The acceleraon of a body is proporonal to the resultant force acng on the body and is in the same direcon as the resultant force. 3. For every acon, there is an equal and opposite reacon.

13

Moon Without Newton’s Laws

• Pac-Man or early Mario style – Follow path with instantaneous changes in speed and direcon (velocity)

– Not physically possible • Note - fine for some casual games (especially with appropriate animaons)

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 maer), in kg a = acceleraon vector, in m/sec2

Player cares about state of world (posion of objects). Equaon is fundamental driver of all physics simulaons. • Force causes acceleraon (a = F/m) • Acceleraon causes change in velocity Kinemacs • Velocity causes change in posion equaons 15

How Are Forces Applied?

• May involve contact – Collision (rebound) – Fricon (rolling, sliding) • Without contact – Rockets/Muscles/Propellers – Gravity – Wind (if not modeling air parcles) – Magic • Dynamic (force) modeling also used for autonomous steering behaviors

16

8 4/5/17

Compung Kinemacs 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 simulaon with colliding forces and fricon (e.g., many interesng cases) … leading to “jerky” behavior 17

Frame Rate Independence

• Complex numerical simulaons used in physics engines are sensive to me steps (due to truncaon 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 • Soluon: Control physics simulaon interval independently of frame rate

18

9 4/5/17

Frame Rate Independence delta simulaon cks lag frame updates previous now

start = ... delta = 0.02 // physics simulaon 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 unl caught up t = t + delta simulate(t) lag = lag - delta previous = now // simulaon caught up to current me } 19

Outline

• Introducon (done) • Kinemacs (done) • The Firing Soluon (next) • Collision Detecon • Ragdoll Physics • PhysX

20

10 4/5/17

The Firing Soluon (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 projecle 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 situaons, magnitude of u fixed. We only need to know relave components (orientaon) à Challenge:

• Given a, d, solve for u 21

Remember Quadrac Equaons?

• Make nice curves – Like firing at target! • Soluons 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 quadrac but finding angle with y = gun, y = target • Angle changes speed in x-direcon, but also me spent in air • Aer hairy math [Millington 3.5.3], three relevant cases: – Target is out of range (no soluon) • Solve with quadrac formula – Target is at exact maximum range (single soluon) – Target is closer than maximum range (two possible soluons)

22

11 4/5/17

The Firing Soluon (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 shoong over wall, etc.

23

The Firing Soluon (3 of 3) function firingSolution (start, target, muzzle_v, gravity) {

// Calculate vector back from target to start delta = target - start

// Real-valued coefficents of quadrac equaon a = gravity * gravity b = -4 * (gravity * delta + muzzle_v * muzzle_v) c = 4 * delta * delta

// Check for no real soluons 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

• Introducon (done) • Kinemacs (done) • The Firing Soluon (done) • Collision Detecon (next) • Ragdoll Physics • PhysX

25

Collision Detecon

• 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 tesng • Detects whether collision has already occurred – Intersecon tesng • Predicts whether collision will occur in future

26

13 4/5/17

Basics – discussed and Overlap Tesng implemented in IMGD 3000!

• Most common technique used in games • Exhibits more error than intersecon tesng • Basic idea: – at every simulaon 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 reacon) – me that collision took place

27

Overlap Tesng: Finding Collision Time

• Calculated by doing “binary search” in me, moving object back and forth by 1/2 steps (bisecons) 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 pracce, five iteraons usually enough

28

14 4/5/17

Limitaons of Overlap Tesng

• Fails with objects that move too fast (no overlap during simulaon me slice) window

t-1 t0 t1 t2 bullet

• Soluon approach: – constrain game design so that fastest object moves smaller distance in one physics “ck” (delta) than thinnest object – may require reducing simulaon step size (adds computaon overhead)

29

Intersecon Tesng • Predict future collisions • Extrude geometry in direcon of movement – e.g., “swept” sphere turns into capsule shape

t0

t1

• Then, see if extruded shape overlaps objects • When collision found (predicted) – Move simulaon 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 Detecon

• Bounding Volumes – Oriented – Hierarchical • Paroning • 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 tesng is required – If overlap, more refined tesng required – Bounding volume alone may be good enough for some games

32

16 4/5/17

Complex Bounding Volumes

• Mulple volumes per object – e.g., separate volumes for head, torso and limbs of avatar object

• Hierarchical volumes – e.g., boxes inside of boxes

[Goschalk, Lin, Minocha, SIGGRAPH ’96]

33

Paroning for Collision Tesng • To address the n2 problem... • Paron space so only test objects in same cell

• In best case (uniform distribuon) 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 Tesng • Observaon: 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

• Introducon (done) • Kinemacs (done) • The Firing Soluon (done) • Collision Detecon (done) • Ragdoll Physics (next) • PhysX

36

18 4/5/17

What is Ragdoll Physics? • Procedural animaon oen used as replacement for tradional (stac) death animaon – Generated by code, not hand – Using physics constraints on body limbs & joints in real- me Sll from early animaon using ragdoll physics hps://en.wikipedia.org/wiki/Ragdoll_physics

hp://www.freeonlinegames.com/game/ragdoll-physics-2

Diablo 3 Ragdolls

“How to Smack a Demon” Erin Cao

(Game Developer’s Conference, San Francisco, California, USA, 2013)

Physics Programmer for Diablo 3 (Blizzard, 2012)

19 4/5/17

A ragdoll is a collecon 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 arst connects bones with Physics joints

Spherical Joint Weld Joint (for chandeliers) (locks two bodies, for advanced)

22 4/5/17

Paral ragdolls add flavor to living characters

Not just for death and destrucon

23 4/5/17

More Physics We Are Not Covering

• Collision response • Conservaon of momentum • Elasc collisions • Non-elasc collisions – coefficient of restuon • Rigid body simulaon (vs. point masses) • Joints as constraints to moon • So body simulaon

[see excellent book by Millington, “Game Physics Engine Development”, MK, 2007] 47

Outline

• Introducon (done) • Kinemacs (done) • The Firing Soluon (done) • Collision Detecon (done) • Ragdoll Physics (done) • PhysX (next)

48

24 4/5/17

PhysX Overview

• Developed by NVIDIA for C++ applicaons • Windows, Mac, , Playstaon, Xbox, Android, Apple iOS and Wii • Simulate – Fluids – So bodies (cloth, hair) – Rigid bodies (boxes, bones)

Why Does NVIDIA Make Physics Soware?

• NVIDIA is mainly known as a developer and manufacturer of graphics hardware (GPU’s)

• So taking advantage of GPU for hardware acceleraon of their physics engine – Algorithms can be tuned to their hardware – Giving a compeve 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 detecon – AABB and OBBT and (both axis-aligned and oriented bounding bounding box trees) – Constraints: hinges, springs, etc. – and lots of other hairy stuff, see hps://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 compung capabilies of new GF100 (Fermi) GPUs.

Raging Rapids Ride

Graphics ok, but with intensive and complex real-me fluid simulaon

27 4/5/17

Havok Cloth

PhysX competor bought by Microso

• Binary – Free! • Source code (e.g., to modify), costs How to Use PhsyX • General documentaon NVIDIA® PhysX® SDK Documentaon hp://docs.nvidia.com/gameworks/content/gameworkslibrary/physx/guide/Index.html • UE4 guide – PhysX, Integrang PhysX Code into Your Project (by Rama) hps://wiki.unrealengine.com/PhysX,_Integrang_PhysX_Code_into_Your_Project

28