PHYSICS - pages.cpsc.ucalgary.ca

25
PHYSICS PHYSICS

Transcript of PHYSICS - pages.cpsc.ucalgary.ca

Page 1: PHYSICS - pages.cpsc.ucalgary.ca

PHYSICSPHYSICS

Page 2: PHYSICS - pages.cpsc.ucalgary.ca

OverviewOverview

• Collision detectionCollision detection– Model representationModel representation– Dynamic vs. staticDynamic vs. static– Discrete vs. continousDiscrete vs. continous– Efficiency issuesEfficiency issues

• Collision resolutionCollision resolution– EventsEvents– SolversSolvers

• DynamicsDynamics– Rigid bodiesRigid bodies– Impulse-based collision solversImpulse-based collision solvers

Page 3: PHYSICS - pages.cpsc.ucalgary.ca

Properties of a Good Physics EngineProperties of a Good Physics Engine

• FastFast– Naïve solutions eat up a lot of performanceNaïve solutions eat up a lot of performance– Designers will always push the limits of a physics engineDesigners will always push the limits of a physics engine

• RobustRobust– Stable and predictable under typical game frame-rates and object Stable and predictable under typical game frame-rates and object

interactionsinteractions• Doesn't “blow up” unexpectedlyDoesn't “blow up” unexpectedly

– ““Enough” accuracyEnough” accuracy• We are not landing a probe on MarsWe are not landing a probe on Mars

• TunableTunable– Intuitive controls to change behaviour of objectsIntuitive controls to change behaviour of objects

• No 15 parameter (all Greek letters) friction modelsNo 15 parameter (all Greek letters) friction models• ExtensibleExtensible

– One-size-fits all doesn'tOne-size-fits all doesn't

Page 4: PHYSICS - pages.cpsc.ucalgary.ca

Collision DetectionCollision Detection

• Find all relevant spatial interactions of objects in the worldFind all relevant spatial interactions of objects in the world• Input: Physics world descriptionInput: Physics world description

– Generally a simplified AI/rendering representationGenerally a simplified AI/rendering representation• Output: Object interactionsOutput: Object interactions

– Per-framePer-frame– Usually a list of Usually a list of collision pairscollision pairs– Information associated with interactions depends on how collisions Information associated with interactions depends on how collisions

are handled by the gameare handled by the game• Typical: colliding object ID's, points of contact, contact normals, Typical: colliding object ID's, points of contact, contact normals,

penetration depth penetration depth

Page 5: PHYSICS - pages.cpsc.ucalgary.ca

Model RepresentationModel Representation

• Arbitrary meshArbitrary mesh– NoNo

• Triangle meshTriangle mesh– Allows for collision detection against arbitrary shapeAllows for collision detection against arbitrary shape– Derived directly off rendering meshDerived directly off rendering mesh– Generally requires tuned hierarchical data structure to be efficientGenerally requires tuned hierarchical data structure to be efficient– Requires well-formed mesh (no cracks, T-junctions)Requires well-formed mesh (no cracks, T-junctions)– Collision response can be tricky Collision response can be tricky

• Convex hullConvex hull– Several can be combined to define an arbitrary shapeSeveral can be combined to define an arbitrary shape– Established, efficient collision detection algorithms (GJK)Established, efficient collision detection algorithms (GJK)– Artists aren't good at manually creating convex hullsArtists aren't good at manually creating convex hulls

• See See http://www.qhull.orghttp://www.qhull.org for an automated toolkit for an automated toolkit

Page 6: PHYSICS - pages.cpsc.ucalgary.ca

Model Representations Cont'dModel Representations Cont'd

• Simplified volumeSimplified volume– Sphere, ellipse box (OBB), capsule, cylinder, coneSphere, ellipse box (OBB), capsule, cylinder, cone– Straightforward, closed form, geometric collision detection formulasStraightforward, closed form, geometric collision detection formulas– Efficiently models certain types of curved surfacesEfficiently models certain types of curved surfaces– Requires artist to wrap meshesRequires artist to wrap meshes

• Or a somewhat tricky automated systemOr a somewhat tricky automated system• Height-fieldHeight-field

– Easy to createEasy to create– Very efficient collision detection, ray castingVery efficient collision detection, ray casting– Unsuitable for general purpose useUnsuitable for general purpose use

• Implicit surface (spline)Implicit surface (spline)– Generally requires partial, or full tesselation to perform collision Generally requires partial, or full tesselation to perform collision

detectiondetection

Page 7: PHYSICS - pages.cpsc.ucalgary.ca

DetectionDetection

• Collision detection is inherently Collision detection is inherently NN22

– For each object, test it for collision with every other objectFor each object, test it for collision with every other object– Gets very slow very quicklyGets very slow very quickly– Might be good enough for your games thoughMight be good enough for your games though

• Fortunately, very few objects actually are interacting each Fortunately, very few objects actually are interacting each frameframe– We hopeWe hope

• We know things about the world that can speed things upWe know things about the world that can speed things up

Page 8: PHYSICS - pages.cpsc.ucalgary.ca

Pair FilteringPair Filtering

• Some objects will never collide, so don't test them against Some objects will never collide, so don't test them against each othereach other– Objects that can't move (static world sections)Objects that can't move (static world sections)– Important enough that this is usually built into the low-level collision Important enough that this is usually built into the low-level collision

systemsystem• Use semantics of game world to avoid collision testsUse semantics of game world to avoid collision tests

– We represent this with bit masksWe represent this with bit masks

Page 9: PHYSICS - pages.cpsc.ucalgary.ca

Two Phase DetectionTwo Phase Detection

• Often, low-level collision detection is done in two stepsOften, low-level collision detection is done in two steps• Broad phaseBroad phase: rapidly find potential colliders, usually using : rapidly find potential colliders, usually using

approximate bounding volumesapproximate bounding volumes– Spheres, Axis Aligned Bounding Box (AABB)Spheres, Axis Aligned Bounding Box (AABB)– Sphere-sphere is much easier than mesh-mesh!Sphere-sphere is much easier than mesh-mesh!

• Narrow phaseNarrow phase: Brute-force compare potential colliders to : Brute-force compare potential colliders to find actual collisionsfind actual collisions

Page 10: PHYSICS - pages.cpsc.ucalgary.ca

Broad Phase StrategiesBroad Phase Strategies

• Spatial partitioningSpatial partitioning– Grid, octree, BSP treeGrid, octree, BSP tree

• ClusteringClustering– Volume trees, sweep-and-prune, spatial hashingVolume trees, sweep-and-prune, spatial hashing

• CoherenceCoherence– Collision cacheCollision cache– PredictionPrediction

Page 11: PHYSICS - pages.cpsc.ucalgary.ca

RaysRays

• Ray castingRay casting is a very frequently performed operation in a is a very frequently performed operation in a game.game.

• Collision detection systems have to consider rays in their Collision detection systems have to consider rays in their underlying designunderlying design– ““tacked-on” ray casting algorithms tend to be inefficient, and can tacked-on” ray casting algorithms tend to be inefficient, and can

overwhelm collision detection timesoverwhelm collision detection times• Rays are different from other collision primitivesRays are different from other collision primitives

– Rays can be very longRays can be very long– Often only concerned with the “first hit”Often only concerned with the “first hit”

• Some suggestions:Some suggestions:– Model rays as line segmentsModel rays as line segments– Keep rays as short as possibleKeep rays as short as possible– Bound short rays with AABBsBound short rays with AABBs– Favour data-structures that return collisions in “ray order”Favour data-structures that return collisions in “ray order”

Page 12: PHYSICS - pages.cpsc.ucalgary.ca

Discrete MethodsDiscrete Methods

• Collision detection is typically performed once per frameCollision detection is typically performed once per frame• Discrete approaches test instantaneous positions of objects, Discrete approaches test instantaneous positions of objects,

checking for overlapchecking for overlap– Majority of collision detection systems operate this wayMajority of collision detection systems operate this way– Algorithms well covered in literatureAlgorithms well covered in literature

• Have to deal with penetration issuesHave to deal with penetration issues– Carefully construct detection routines to give sensible results in Carefully construct detection routines to give sensible results in

moderate penetration casesmoderate penetration cases– Very deep penetration will be hard to deal with Very deep penetration will be hard to deal with

• Time-step has to be small enough to catch all collisionsTime-step has to be small enough to catch all collisions– Bullet through sheet of paper problemBullet through sheet of paper problem

Page 13: PHYSICS - pages.cpsc.ucalgary.ca

Continuous MethodsContinuous Methods

• Find the exact moment of contactFind the exact moment of contact• Doesn't suffer from pass-through problemsDoesn't suffer from pass-through problems• Easy with raysEasy with rays• Considerably more work for complex objects with multi-point Considerably more work for complex objects with multi-point

contactscontacts• Hard for non-linear motionHard for non-linear motion

– Ballistic trajectoryBallistic trajectory– Rigid body tumblingRigid body tumbling

• Usually approximated by assuming linear motion between Usually approximated by assuming linear motion between framesframes– Sweep-methods, interval arithmeticSweep-methods, interval arithmetic

• Higher per-frame cost than discreteHigher per-frame cost than discrete– But perhaps a larger time-step can be usedBut perhaps a larger time-step can be used

Page 14: PHYSICS - pages.cpsc.ucalgary.ca

ResolutionResolution

• What a game does with detected collisions is called What a game does with detected collisions is called resolution,resolution,or or solving solving

• Many possibilities -- some handled by the game logic, Many possibilities -- some handled by the game logic, others by the physics system itself:others by the physics system itself:– Ignore (objects pass through each other)Ignore (objects pass through each other)– Bounce (perhaps using dynamics engine)Bounce (perhaps using dynamics engine)– StickStick– Destroy one, or both objects (replace with special effect)Destroy one, or both objects (replace with special effect)– Send event (for sounds, damage application, AI triggers)Send event (for sounds, damage application, AI triggers)– Apply forceApply force– DeformDeform– Change state of one or more objectsChange state of one or more objects

• The resolution system must be flexibleThe resolution system must be flexible

Page 15: PHYSICS - pages.cpsc.ucalgary.ca

DynamicsDynamics

• A A dynamicsdynamics system is concerned with object positions and system is concerned with object positions and orientationsorientations– It can be thought of as physics-based animation systemIt can be thought of as physics-based animation system

• Lots of uses and approachesLots of uses and approaches• We'll briefly talk about We'll briefly talk about rigid bodiesrigid bodies• Won't talk about:Won't talk about:

– Articulated objects (constraints)Articulated objects (constraints)– Flexible objects (rope, hair, cloth, skin)Flexible objects (rope, hair, cloth, skin)– Fluids (smoke, water)Fluids (smoke, water)

Page 16: PHYSICS - pages.cpsc.ucalgary.ca

Rigid Body DynamicsRigid Body Dynamics

• Rigid bodyRigid body– Transform specifying position (centre of mass), and orientationTransform specifying position (centre of mass), and orientation– Linear and angular velocity vectorsLinear and angular velocity vectors– Mass, and mass matrix (inertia tensor)Mass, and mass matrix (inertia tensor)– Collision extentsCollision extents– Material properties (discussed later)Material properties (discussed later)

• Useful methods:Useful methods:– Get/Set velocity (linear, angular), positionGet/Set velocity (linear, angular), position– Get velocity of pointGet velocity of point– Apply force, torqueApply force, torque

• IntegratorIntegrator– Updates the linear and angular velocity, position and orientation of a Updates the linear and angular velocity, position and orientation of a

rigid bodyrigid body under the influence of gravity and other forces at each under the influence of gravity and other forces at each time steptime step

Page 17: PHYSICS - pages.cpsc.ucalgary.ca

Collision SolversCollision Solvers

• The dynamics system often is given the task of preventing The dynamics system often is given the task of preventing object interpenetration, and providing plausible collision object interpenetration, and providing plausible collision responseresponse

• Two major cases:Two major cases:– Collision (“bouncing”)Collision (“bouncing”)– Contact (resting, rolling, sliding, friction)Contact (resting, rolling, sliding, friction)

• Still an active area of researchStill an active area of research• We will describe a popular approach: We will describe a popular approach: impulse-based impulse-based

methodsmethods– Impulses can handle both collision and contactsImpulses can handle both collision and contacts

• A more accurate approach used e.g. in Havok and Radical A more accurate approach used e.g. in Havok and Radical engines is the LCP (engines is the LCP (Linear Complementarity ProblemLinear Complementarity Problem)) solver solver

Page 18: PHYSICS - pages.cpsc.ucalgary.ca

Impulse MethodsImpulse Methods

• Pioneered by Mirtich and Canny [1]Pioneered by Mirtich and Canny [1]• What is an impulse?What is an impulse?

– A force applied over a very small period of timeA force applied over a very small period of time– Impulses effect an instantaneous change in velocityImpulses effect an instantaneous change in velocity

• Collisions are processed pair-wiseCollisions are processed pair-wise• For each collision point between two objects, examine the For each collision point between two objects, examine the

relative velocities of the two pointsrelative velocities of the two points– If moving apart, do nothingIf moving apart, do nothing– Otherwise, compute and apply a pair of equal but opposite impulses Otherwise, compute and apply a pair of equal but opposite impulses

to the pair of rigid bodies at the collision pointsto the pair of rigid bodies at the collision points– Requires collision point, collision normals, velocities, body properties Requires collision point, collision normals, velocities, body properties

(inertia tensor, co-efficient of restitution, friction)(inertia tensor, co-efficient of restitution, friction)

[1] Brian Mirtich and John Canny, “Impulse-based simulation of rigid bodies,” in Proceedings of [1] Brian Mirtich and John Canny, “Impulse-based simulation of rigid bodies,” in Proceedings of Symposium on Interactive 3D Graphics, 1995.Symposium on Interactive 3D Graphics, 1995.

Page 19: PHYSICS - pages.cpsc.ucalgary.ca

Impulse CalculationImpulse Calculation

• Depends on the underlying collision and friction modelDepends on the underlying collision and friction model• Minimally, materials are defined byMinimally, materials are defined by

– Coefficient of restitution (bounciness)Coefficient of restitution (bounciness)– Coefficient of friction (Coefficient of friction (μ)μ)– Formulas or tables to define material interactionsFormulas or tables to define material interactions

• Mirtich gives formulas for computing an impulse assuming Mirtich gives formulas for computing an impulse assuming Newton's impact law and Coulomb frictionNewton's impact law and Coulomb friction

• Another approach is described by Chatterjee [2] which Another approach is described by Chatterjee [2] which separates restitution into linear and angular components separates restitution into linear and angular components

[2] [2] Anindya ChatterjeeAnindya Chatterjee, , Andy RuinaAndy Ruina, “, “A New Algebraic R igid Body Collision Law Based On A New Algebraic R igid Body Collision Law Based On Impulse S pace ConsiderationsImpulse S pace Considerations ” ” Journal of Applied Mechanics.Journal of Applied Mechanics.

Page 20: PHYSICS - pages.cpsc.ucalgary.ca

Multi-point CollisionMulti-point Collision

• For the best accuracy, impulses for all collisions should be For the best accuracy, impulses for all collisions should be computed, and applied simultaneouslycomputed, and applied simultaneously

• This is difficult (see LCP solvers [3]), and could be This is difficult (see LCP solvers [3]), and could be expensiveexpensive

• Instead, we can just apply the impulses sequentially, and Instead, we can just apply the impulses sequentially, and tolerate the inaccuracytolerate the inaccuracy

• For boxes, we can average collision points that lie on the For boxes, we can average collision points that lie on the same face, which improves results.same face, which improves results.

[3] Erin Catto, “[3] Erin Catto, “Iterative Dynamics with Temporal Coherence,Iterative Dynamics with Temporal Coherence,” Game Developer Conference, ” Game Developer Conference, 20052005..

Page 21: PHYSICS - pages.cpsc.ucalgary.ca

ConvergenceConvergence

• After all collisions have been processed, some points that After all collisions have been processed, some points that were moving apart may be adjusted by other impulseswere moving apart may be adjusted by other impulses

• Many iterations are needed to solve large stacksMany iterations are needed to solve large stacks

Page 22: PHYSICS - pages.cpsc.ucalgary.ca

Improving ConvergenceImproving Convergence

• Between two objects, solve deepest contact firstBetween two objects, solve deepest contact first• Generate a “contact graph”, and solve contacts bottom-up Generate a “contact graph”, and solve contacts bottom-up

with respect to gravitywith respect to gravity• Shock propagation [4]Shock propagation [4]

– Process a level of the contact graph, then freeze the objects for Process a level of the contact graph, then freeze the objects for subsequent processing (set mass to subsequent processing (set mass to ∞∞))

3

2

1 1

[4] Eran Guendelman, Robert Bridson, Ronald Fedkiw, “Nonconvex Rigid Bodies with Stacking,” [4] Eran Guendelman, Robert Bridson, Ronald Fedkiw, “Nonconvex Rigid Bodies with Stacking,” Stanford University.Stanford University.

Page 23: PHYSICS - pages.cpsc.ucalgary.ca

SleepingSleeping• Most physics systems employ a Most physics systems employ a rest detectionrest detection algorithm to algorithm to

put rigid bodies to sleep when they are in a stable put rigid bodies to sleep when they are in a stable configurationconfiguration– e.g. Resting on the grounde.g. Resting on the ground

• This serves primarily as an optimisation, but it also reduces This serves primarily as an optimisation, but it also reduces jitter at low time stepsjitter at low time steps

• The configuration of the rigid body is analysed each frame The configuration of the rigid body is analysed each frame to determine if it should be put to sleepto determine if it should be put to sleep– Velocity thresholdsVelocity thresholds– Contact analysisContact analysis

• External forces wake the body back upExternal forces wake the body back up– Gravity is excludedGravity is excluded

• There's a danger of objects floating if they go to sleep at the There's a danger of objects floating if they go to sleep at the wrong time wrong time

Page 24: PHYSICS - pages.cpsc.ucalgary.ca

SummarySummary

• Physics engines are complicated, and full of interesting Physics engines are complicated, and full of interesting design choicesdesign choices– Speed, accuracy tradeoffsSpeed, accuracy tradeoffs

• Active area of researchActive area of research– Impulse paper: 1995Impulse paper: 1995– Stacking paper: 2002Stacking paper: 2002– LCP paper: 2005LCP paper: 2005

• You may never have to implement one from scratch, but it is You may never have to implement one from scratch, but it is useful to have an idea of how they workuseful to have an idea of how they work

Page 25: PHYSICS - pages.cpsc.ucalgary.ca