4/11/2016

Introduction (1 of 2)

• What is ? – Computing motion of objects in virtual scene Basic Game Physics • Including player avatars, NPC’s, inanimate objects – Computing mechanical interactions of objects • Interaction usually involves contact (collision) IMGD 4000 – Simulation must be real-time (versus high- precision simulation for CAD/CAM, etc.) With material from: Introduction to Game – Simulation may be very realistic, approximate, or Development, Second Edition. Edited by Steve Rabin. Cengage Learning, 2009. (Chapter 4.3) intentionally distorted (for effect)

2

Introduction (2 of 2) Physics Engines

• And why is it important? • Similar buy vs. build analysis as game engines – Buy: – Can improve immersion • Complete solution from day one – Can support new gameplay elements • Proven, robust code base (hopefully) • Feature sets are pre-defined – Becoming increasingly prominent (expected) part of • Costs range from free to expensive high-end games – Build: • Choose exactly features you want – Like AI and graphics, facilitated by hardware • Opportunity for more game-specification optimizations developments (multi-core, GPU) • Greater opportunity to innovate • Cost guaranteed to be expensive (unless features extremely – Maturation of market minimal)

3 4

Physics Engines Basic Game Physics Concepts

• Open source • Why are we studying this? – , , , JigLib, ODE, OPAL, OpenTissue, – To use an engine effectively, you need to understand PAL, , Farseer, Physics2d, Glaze something about what it’s doing • Closed source (limited free distribution) – You may need to implement small features or – , Simple Physics Engine, True Axis, extensions yourself PhysX – Cf., owning a car without understanding anything • Commercial about how it works (possible, yes, but ideal?, no) – , nV Physics, • Examples • Relation to Game Engines – Native, e.g,. C4 – Kinematics and dynamics – Integrated, e.g., UE4 + PhysX – Projectile motion – Pluggable, e.g., C4 + PhysX, jME + ODE (via jME Physics) – Collision detection and response

6

1 4/11/2016

Outline Kinematics (1 of 3)

• Introduction (done) • Study of motion of objects without taking into account mass or force • Kinematics (next) • Basic quantities: position, time • Rigid Body Simulation • ... and their derivatives: velocity, acceleration • The Firing Solution • Basic equations: Where: • Collision Detection 1) d = vt t - (elapsed) time 2) v = u + at d - distance (change in position) • v - (final) velocity (change in distance per unit time) 3) d = ut + ½at2 a - acceleration (change in velocity per unit time) 2 2 u - (initial) velocity • PhysX 4) v = u + 2ad

Note, equation #3 is the integral of equation #2 with respect to time (see next slide). Equation #4 can be useful. 7 8

Kinematics (2 of 3) Kinematics (3 of 3)

Non-accelerated motion Accelerated motion Prediction Example: If you throw a ball straight up into the air with an initial velocity of 10 m/sec, how high will it go? v = 0 v2 = u2 + 2ad d a = -10 u = 10 m/sec (initial speed upward) a = -10 m/sec2 (approx gravity) v = 0 m/sec (at top of flight) 2 u = 10 d = ut d = ut + ½at 2 Example: Example: 0 = 10 + 2(-10)d 2 d = 5 meters u = 20 m/s, t = 300 s u=0 m/s, a=4m/s , t=3s (Note, answer independent of mass of ball!) d = 20 x 3000 = 6000 m d = 0x3 + 0.5x4x9 = 18m 10

Doing It In 3D Dynamics

• Mathematically, consider all quantities • Notice that preceding kinematic descriptions say involving position to be vectors: nothing about why an object accelerates (or why its acceleration might change) d = vt • To get a full “modern” physical simulation you v = u + at need to add two more basic concepts: 2 d = ut + at /2 – force • Computationally, using appropriate 3-element – mass vector datatype • Discovered by Sir Isaac Newton

• Around 1700 

11 12

2 4/11/2016

Newton’s Laws Motion Without Newton’s Laws

1. A body will remain at rest or continue to • Pac-Man or early Mario style move in a straight line at a constant speed – Follow path with instantaneous changes in speed and unless acted upon by a force. direction (velocity) 2. The acceleration of a body is proportional to the resultant force acting on the body and is

in the same direction as the resultant force. 3. For every action, there is an equal and – Not physically possible opposite reaction. • Note - fine for some casual games (especially with appropriate )

13 14

Newton’s Second Law How Are Forces Applied? F = ma • May involve contact At each moment in time: – Collision (rebound) F = force vector, in Newton’s – Friction (rolling, sliding) m = mass (intrinsic property of matter), in kg • Without contact a = acceleration vector, in m/sec2 – Rockets/Muscles/Propellers – Gravity Player cares about state of world (position of objects). Equation – Wind (if not modeling air particles) is fundamental driver of all physics simulations. – Magic • Force causes acceleration (a = F/m) • Dynamic (force) modeling also used for autonomous steering behaviors • Acceleration causes change in velocity

• Velocity causes change in position 15 16

Computing Kinematics in Real Time Outline

start = getTime() // start time p = 0 // initial position u = 10 // initial velocity • Introduction (done) a = -10 d • function update () { // in game loop a = -10 Kinematics (done) now = getTime() t = now – start • Rigid Body Simulation (next) simulate(t) } u, p • The Firing Solution

function simulate (t) { d = ut + at2/2 d = (u + (0.5 * a * t)) * t • Collision Detection move object to p + d // move to loc. computed since start } • Ragdoll Physics

Note! Number of calls and time values to simulate() depend on (changing) • PhysX game loop time (frame rate) Is this a problem? It can be! For rigid body simulation with colliding forces and friction (e.g., many interesting cases) … 17 18

3 4/11/2016

Rigid-Body Simulation Numerical Simulation of Newtonian • If no rotation, only gravity and occasional Equation of Motion (1 of 2) frictionless collision, basic Kinematic equations are fine • Suppose know position (p), – Closed form solution can be integrated velocity (v) and acceleration (e.g., d = ut + ½at2) (a) at time (ti) and frame time (∆t) • But in many games (and life!), interesting motion involves non-constant forces and collision impulse • Want position at next frame forces time (ti+1) – Don’t know exactly how forces vs. – Unfortunately, often no closed-form solutions are affecting (wind, friction, • What to do?  Numerical simulation gravity …) • Can compute:

Numerical Simulation techniques for incrementally solving equations of – pi+1 = si + vi * ∆t motion when forces applied to object are not constant, or when otherwise – vi+1 = vi + a * ∆t there is no closed-form solution What is this doing?  Instead of integrating a curve, sum over discrete time-slices 19

Numerical Simulation of Newtonian Equation of Motion (2 of 2) Explicit Euler Integration (1 of 2) • Family of numerical sim techniques called finite difference methods – Incremental “solution” to equations of motion • A “one-point” method since solve using – Most common for rigid-body dynamics simulation • Derived from Taylor series expansion of properties interested in properties at exactly one point in time, t, prior

(Taylor series are used to estimate unknown functions) to update time, t+Δt

S(t+Δt) = S(t) + Δt d/dt S(t) + (Δt)2/2! d2/dt S(t) + … – S(t+Δt) is only unknown value so can solve without solving system of simultaneous equations • In general, not know values of any higher order. Truncate, remove higher terms – Every term on right side is evaluated at t, right S(t+Δt) = S(t) + Δt d/dt S(t) + O(Δt)2 – Can do beyond, but always higher terms before new time t+Δt 2 – O(Δt) is called truncation error • Size is proportional to Δt (step size) • View: S(t+Δt) = S(t) + Δt d/dt S(t) • Can use to update properties (position) – Called “simple” or “explicit” Euler integration new state prior state state derivative

22

Explicit Euler Integration (2 of 2) Explicit Euler Integration Example (1 of 2)

• Write numerical integrator over arbitrary properties as change over Vinit = 30 m/s time Launch angle: 75.2 degrees (all motion in xz plane) • For single particle, S = (mV, p) and d/dt S = (F, V) Mass of projectile, m: 2.5 kg – Derivative of position (p) is velocity (V) • i.e., how position changes with respect to time – Derivative of momentum (mass m * V) is force (F) • i.e., how momentum changes with respect to time Position (m) Linear Momentum (kg-m/s) F o rc e (N ) Velocity (m/s) T im e p x p y p z mV x mV y mV z F x F y F z V x V y V z • Integrate state vector of length N 5 .0 0 1 0 .0 0 0 .0 0 2 .0 0 1 9 .2 0 0 .0 0 7 2 .5 0 0 .0 0 0 .0 0 -2 4 .5 3 7 .6 8 0 .0 0 2 9 .0 0 Vector ExplicitEuler(int N, Vector prior_S, Vector deriv_S, float delta_t) Vector new_S[N]; t p mV F=Weight = mg V for (i=0; i

• Note, for 3D, mV and p have 3 values each – S(t) = (m V ,p ,m V ,p , …, m V ,p ) 1 1 1 2 2 2 N N N S = dS/dt = – d/dt S(t) = (F1,V1,F2,V2, …,FN,VN)

23 24

4 4/11/2016

Pseudo Code for Numerical Integration (1 of 2) Explicit Euler Integration Example (2 of 2) Vector cur_S[2*N]; // S(t+Δt) Vector prior_S[2*N]; // S(t) Dt = .2 s Dt = .1 s Dt = .01 s Vector S_deriv[2*N]; // d/dt S at time t float mass[N]; // mass of particles 19 .2   0 .0  19 .2025  19 .2025  19 .2025  float t; // simulation time t           0 .0 0 .0 0 .0 0 .0 0 .0           void main() { d  72 .5    24 .53   67 .5951   72 .0476   72 .2549  float delta_t; // time step S (t  D t )  S (t )  D t S (t )     D t            dt 10 .0 7 .68 11 .5362 10 .7681 10 .0768           // Set current state to initial conditions  0 .0   0 .0   0 .0   0 .0   0 .0  for (i=0; i

25 26

Pseudo Code for Numerical Integration (2 of 2) Computing Position Over Time • Solution proceeds step-by-step, each time integrating from prior state // Update state of all particles based on physics

void doPhysicsSimulationStep(float delta_t) { Position (m) Linear Momentum (kg-m/s) Force (N) Velocity (m/s) copy cur_S to prior_S; Time p x p y p z mV x mV y mV z F x F y F z V x V y V z 5.00 10.00 0.00 2.00 19.20 0.00 72.50 0.00 0.00 -24.53 7.68 0.00 29.00 5.20 11.54 0.00 7.80 19.20 0.00 67.60 0.00 0.00 -24.53 7.68 0.00 27.04 // Calculate state derivative vector 5.40 13.07 0.00 13.21 19.20 0.00 62.69 0.00 0.00 -24.53 7.68 0.00 25.08 5.60 14.61 0.00 18.22 19.20 0.00 57.79 0.00 0.00 -24.53 7.68 0.00 23.11 for (i=0; i

4 0 .0 0 P o s it io n // Integrate equations of motion Target Position ExplicitEuler(2*N, cur_S, prior_S, S_deriv, delta_t); 3 0 .0 0 Closed-Form 2 0 .0 0 // By integrating, effectively moved simulation time forward by delta_t Explicit Euler t = t + delta_t; 1 0 .0 0

} Vertical Position (m ) 0 .0 0 p_init = <10,0,2> meters 0 .0 0 2 0 .0 0 4 0 .0 0 6 0 .0 0 p_target = <50,0,20> meters v_init = 30 meters per second Horizontal Position (m )

27

Truncation Error Truncation Error Example • Numerical simulation can be different from exact, closed-form solution – Difference primarily truncation error Euler • Error per step proportional to step • Truncation error can accumulate causing instability size squared – Ultimately produces floating point overflow • Global error (error at given time) proportional to step size – Unstable simulations behave unpredictably (not same each time) • (At lower limit, error goes to 0) • Sometimes, truncation error can become zero – In other words, produces exact, correct result – For example, when zero force is applied or frictionless and constant force • But, more often truncation error is non-zero. Control by: – Select different numerical integrator (Vertlet, Runge-Kutta or others). Typically, more state kept. Stable within bounds. Trade-off: truncation error and computation interval – Reduce time step, Dt (next slide) Guidelines? Step more often than frame rate (otherwise, no update!)

29  Dt under 30 ms (20 ms a good choice) 30

5 4/11/2016

Frame Rate Independence Frame Rate Independence delta simulation ticks lag • Complex numerical simulations used in physics frame updates engines are sensitive to time steps (due to previous now truncation error and other numerical effects) start = ... • But results need to be repeatable regardless of delta = 0.02 // physics simulation interval (sec) CPU/GPU performance lag = 0 // time since last simulated previous = 0 // time of previous call to update – for debugging function update() { // in game loop – for game play now = getTime() t = (previous - start) – lag // previous simulate() • So, if frame rate drops (game loop can’t keep up), lag = lag + (now - previous) // additional lag then physics will change while ( lag > delta ) // repeat until caught up t = t + delta • Solution: Control physics simulation interval simulate(t) // note: kinematics. If dynamic, use delta independently of frame rate lag = lag - delta previous = now // simulation caught up to current time } 31 32

Outline The Firing Solution (1 of 3) • How to hit target • Introduction (done) – Beam weapon or high-velocity bullet over short • Kinematics (done) ranges can be viewed as traveling in straight line – • Rigid Body Simulation (done) But projectile travels in parabolic arc • Grenade, spear, catapult, etc. • The Firing Solution (next) d = ut + at2/2

• Collision Detection a = [0, 0, -9.8] m/sec2 (but can use higher value, e.g., -18) • Ragdoll Physics d u = velocity vector • PhysX Most typical game situations, magnitude of u fixed. We only need to know relative components (orientation)  Challenge: • Given d, solve for u 33 34

Remember Quadratic Equations? The Firing Solution (2 of 3)

• Make nice curves – Like firing at target! long time trajectory • Solutions are where equals 0. E.g., when firing with gun on ground: – At gun muzzle – At target short time trajectory [Millington 3.5.3] • But unlike in algebra class, not just solving quadratic but finding angle u = (2Δ - at2) / (2 (muzzle_v) t) with y = gun, y = target d u = muzzle velocity vector • Angle changes speed in x-direction, where muzzle_v = max muzzle speed but also time spent in air Δ is difference vector from d to u • After hairy math [Millington 3.5.3], three relevant cases: • Usually choose short time trajectory a is gravity – Target is out of range (no solution) • Solve with quadratic formula – Gives target less time to escape – Target is at exact maximum range (single solution) – Unless shooting over wall, etc. – Target is closer than maximum range (two possible solutions) Project Firing

35 36

6 4/11/2016

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

// Calculate vector back from target to start delta = target - start • Introduction (done) // Real-valued coefficents of quadratic equation a = gravity * gravity b = -4 * (gravity * delta + muzzle_v * muzzle_v) • Kinematics (done) c = 4 * delta * delta

// Check for no real solutions • Rigid Body Simulation (done) if ( 4 * a * c > b * b ) return null

// Find short and long times to target • disc = sqrt (b * b - 4 * a *c) Note, a, b and c are scalars The Firing Solution (done) t1 = sqrt ( ( -b + disc ) / (2 * a )) so a normal square root. t2 = sqrt ( ( -b - disc ) / (2 * a )) • Collision Detection (next) // Pick shortest valid time to target (ttt) if ( t1 < 0 ) && ( t2 < 0) return null // No valid times if ( t1 < 0 ) ttt = t2 else • Ragdoll Physics 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 • PhysX // Return firing vector return ( 2 * delta - gravity * ttt * ttt ) / ( 2 * muzzle_v * ttt ) }

[Millington 3.5.3] 37 38

Basics – discussed and Collision Detection Overlap Testing implemented in IMGD 3000!

• Determining when objects collide is not as easy • Most common technique used in games as it seems • Exhibits more error than intersection testing – Geometry can be complex • Basic idea: – Objects can be moving quickly – at every simulation step, test every pair of objects to – There can be many objects see if overlap 2 • naive algorithms are O(n ) • Easy for simple volumes (e.g., spheres), harder • Two basic approaches: for polygonal models – Overlap testing • Results of test: • Detects whether collision has already occurred – collision normal vector (useful for reaction) – Intersection testing • Predicts whether collision will occur in future – time that collision took place

39 40

Overlap Testing: Finding Collision Time Limitations of Overlap Testing • Calculated by doing “binary search” in time, moving object • Fails with objects that move too fast (no overlap during back and forth by 1/2 steps (bisections) simulation time slice) A window t0 A A A A t0.25 A t 0.375 t t0.4375 0.40625 t-1 t0 t1 t2 t0.5 bullet

t1 • B B B B B B Solution approach: Initial Overlap Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 – constrain game design so that fastest object moves smaller distance in Test Forward 1/2 Backward 1/4 Forward 1/8 Forward 1/16 Backward 1/32 one physics “tick” (delta) than thinnest object • In practice, five iterations usually enough – may require reducing simulation step size (adds computation overhead)

41 42

7 4/11/2016

Intersection Testing Speeding Up Collision Detection • Predict future collisions • Extrude geometry in direction of movement – e.g., “swept” sphere turns into capsule shape • Bounding Volumes

– Oriented t0 – t Hierarchical 1 • Partitioning • Then, see if extruded shape overlaps objects • Plane Sweep • When collision found (predicted) – Move simulation to time of collision (have collision point) – Resolve collision – Works for bullet/window example (bullet becomes line segment)

43 44

Bounding Volumes Complex Bounding Volumes • Commonly used volumes

– sphere - distance between centers less than sum of radii • Multiple volumes per object – boxes – e.g., separate volumes for head, torso and limbs axis aligned (loose fit, easier math) of avatar object oriented (tighter fit, more expensive)

Axis-Aligned Bounding Box Oriented Bounding Box • Hierarchical volumes • If bounding volumes don’t overlap, then no – e.g., boxes inside of boxes more testing is required – If overlap, more refined testing required

– Bounding volume alone may be good enough [Gottschalk, Lin, Minocha, SIGGRAPH ’96] for some games 45 46

Partitioning for Collision Testing Plane Sweep for Collision Testing • Observation: many moveable objects stay in one place most of the • To address the n2 problem... time • Partition space so only test objects in same cell • 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 2 A0 • In best case (uniform distribution) reduces n to linear C1 R0 – Can happen for uniform size, density objects (e.g., cloth/fluids) C

• In worst case (all objects in same cell) no improvement C0

A0 A1 R0 B0 R1 C0 B1 C1 x 47 48

8 4/11/2016

Outline What is Ragdoll Physics? • Procedural often • Introduction (done) used as replacement for traditional (static) death • Kinematics (done) animation – Generated by code, not hand • Rigid Body Simulation (done) – Using physics constraints on body limbs & joints in real- • The Firing Solution (done) time • Collision Detection (done) Still from early animation using ragdoll physics • Ragdoll Physics (next) https://en.wikipedia.org/wiki/Ragdoll_physics • PhysX

49 http://www.freeonlinegames.com/game/ragdoll-physics-2

A ragdoll is a collection of collision Diablo 3 Ragdolls shapes connected to bones

“How to Smack a Demon” Erin Catto

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

Physics Programmer for Diablo 3 (Blizzard, 2012)

9 4/11/2016

Physics joints connect two bones We use the ragdoll bodies to adjust the pose

Cone Joint Revolute Joint (like shoulder) (like elbow)

Tech artist connects bones with Physics joints

Spherical Joint Weld Joint (for chandeliers) (locks two bodies, for advanced) model space keyed animation world space ragdoll

Update the actor bounding sphere Partial ragdolls add flavor to using the bone transforms living characters

actor transform

Not just for death and destruction

10 4/11/2016

More Physics We Are Not Covering

• Collision response • Conservation of momentum • Elastic collisions • Non-elastic collisions – coefficient of restitution • Rigid body simulation (vs. point masses) • Joints as constraints to motion • Soft body simulation

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

Outline PhysX Overview

• Introduction (done) • Developed by NVIDIA for C++ applications • Kinematics (done) • Windows, Mac, Linux, Playstation, Xbox, • Rigid Body Simulation (done) Android, Apple iOS and Wii • The Firing Solution (done) • Simulate • Collision Detection (done) – Fluids – Soft bodies (cloth, hair) • Ragdoll Physics (done) – Rigid bodies (boxes, bones) • PhysX (next)

63

Why Does NVIDIA Make Physics Software? Configure Video Card as Dedicated PhysX Processor • NVIDIA is mainly known as a developer and manufacturer of graphics hardware (GPU’s)

• So taking advantage of GPU for hardware acceleration of their physics engine – Algorithms can be tuned to their hardware Dedicated – Giving a competitive advantage over other GPU to PhyX manufacturers

65

11 4/11/2016

What Algorithms Does PhysX Use? Rocket Sled • 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 detection – AABB and OBBT and (both axis-aligned and oriented bounding bounding box trees) – Constraints: hinges, springs, etc. – and lots of other hairy stuff, see https://devtalk.nvidia.com/default/board/66/physx-and-physics-modeling/ CES 2010, Rocket Sled demonstrates both graphics and physics computing capabilities of new GF100 (Fermi) GPUs. 67

Raging Rapids Ride Havok Cloth

Graphics ok, but with intensive and complex real-time fluid simulation PhysX competitor bought by Microsoft

How to Use PhsyX • General documentation NVIDIA® PhysX® SDK Documentation http://docs.nvidia.com/gameworks/content/gameworkslibrary/physx/guide/Index.html • UE4 guide – PhysX, Integrating PhysX Code into Your Project (by Rama) https://wiki.unrealengine.com/PhysX,_Integrating_PhysX_Code_into_Your_Project

12