Physics

Czech technical University in Prague
Faculty of Information Technology
Department of Software Engineering
© Adam Vesecký, MI-APH, 2019

Physics engine features

Physics engine

  • System that simulates physical phenomena
  • computes motion of objects in virtual scene
  • simulation must be real-time (accuracy is not that important)
  • you have to understand your game before you decide how to add a physical simulation to it
  • can improve immersion
  • can support new gameplay events
  • can broke the game story
  • takes significant computing resources
  • is based on heavy magic tricks that are difficult to comprehend

Physics engines

N-Collide

  • 2D and 3D collision detection library written in Rust

Box2D

  • open-source C++ 2D physics engine
  • supports CCD (continuous collision detection)

Bullet

  • open-source 3D physics engine
  • used in game and film industry
  • supports CCD

PhysX

  • it can run using Nvidia's GPU
  • PhysX destruction, PhysX Clothing, PhysX particles

p2.js

  • modular JavaScript engine, supports CCD

Havok

  • gold commercial standard

Physics engine steps

Physics vs animation

  • physics  animation!!
  • animations must at least partially bypass physics in order to run seamlessly
  • cut-scenes and state-transition animations are detached from physics

General purpose simulators

  • offer the dream of environment where everything is physically simulated
  • Pinball series (1980+), Incredible Machines (1993), Little Big Planet (2008), Angry Birds (2009)
  • for instance, in GTA V, the player can interact with less than 0.1% objects!

Physics engine features

  • collision detection (CCD or sub-stepping)
  • contact callbacks
  • joints
  • concave and convex hulls
  • compound bodies
  • sleeping objects
  • raycasting, shapecasting
  • deformable structures
  • destructible structures
  • trigger volumes
  • complex machines
  • drivable vehicles
  • rag doll characters
  • water surface, hair, cloth
  • particles

Example: Half-life 2

  • Havok Engine
  • destructible environment
  • simulating gravity, friction, mass, momentum, inertia,...
  • liquid physics with displacement, viscosity, adhesion

Example: Inside

  • published in 2016, proprietary physics and game engine
  • Huddle Potato
    • custom physics model developed by Thomas Krog
    • its core was simulated by 26-body-simulation procedures
    • it was driven by a network of impulses based on the direction of the player
    • often reconfiguration was needed in order to fit into tight spaces

Object types

Body

  • fundamental object in the physics scene

Rigid Body

  • idealized, infinitely hard, non-deformable solid object
  • physics-driven bodies - driven entirely by the simulation
  • game-driven bodies - moved in a non-physical way (animations)
  • fixed bodies - collision-only bodies

Soft Body

  • can be deformed

Shape

  • region of space described by a boundary, with a definite inside and outside (curved line, polygon, curved surface, polyhedron)

Fixture

  • used to describe size, shape and material properties

Object types

Constraint

  • connects bodies together in order to simulate interaction (ropes, wheels, vehicles, chains)

Sensor/Phantom

  • entity that provides a feedback when certain objects overlap
  • participates on collision detection but doesn't affect the scene

Rag doll

  • displays human-like figures with a realistic motion

Destructible object

  • breakable object, can be implemented by using rigid body dynamics, dividing the model into a number of breakable pieces

Constraints

  • Revolute - a hinge or pin, where the bodies rotate
    • wheels, chains, rotating doors, catapults, levers
  • Distance - a point on each body will be kept at a fixed distance apart
  • Rope - restricts the maximum distance between two points
  • Prismatic - body's motion is restricted to a single degree of freedom
    • elevators, sliding doors, pistons
  • Weld - holds the bodies at the same orientation
  • Cone-Twist - adds a cone and twist axis limits (6 degrees of freedom)
  • Gear - controls two other joints so that the movement of one affects the other
  • Motor - joint with torque or angular impulses

Constraints

rope

revolute

prismatic

cone-twist

Constraints

Collision detection

Collision Detection

common issues of simple platformers

Steps

  • positions for the next frame are determined
  • a spatial data structure finds collision candidates
  • collision candidates are filtered out into a set of real collision pairs
  • collisions are resolved by the collision resolver (by applying impulses or penalty forces)
  • constraints are satisfied by the constraint resolver

Collidable entities

  • we need to provide a collision representation for each object
  • simple shapes are preferred (a car might be modelled as a rectangle)
  • more-complex shapes should be used only when the simple ones provide inadequate information to achieve the desired behavior
  • if collidable entities don't overlap, no more testing is required
  • if they do overlap, more refined testing is required

Example: Unity interaction matrix

Static ColliderRigidbody ColliderKinematic Rigidbody ColliderStatic Trigger ColliderRigidbody Trigger ColliderKinematic Rigidbody Trigger Collider
Static Collidercollisiontriggertrigger
Rigidbody Collidercollisioncollisioncollisiontriggertriggertrigger
Kinematic Rigidbody Collidercollisiontriggertriggertrigger
Static Trigger Collidertriggertriggertriggertrigger
Rigidbody Trigger Collidertriggertriggertriggertriggertriggertrigger
Kinematic Rigidbody Trigger Collidertriggertriggertriggertriggertriggertrigger

Primitives

Sphere

  • center point and radius (4 numbers)

Capsule

  • 2D: rectangle and two circles
  • 3D: cylinder and two hemispherical end-caps
  • representation: two points and radius

AABB

  • axis-aligned bounding box
  • rectangular volume (cuboid) whose faces are parallel to the axes of the coordinate system
  • very efficient test for penetration
  • AABB must be recalculated whenever the object rotates

Primitives

OBB

  • oriented bounding box
  • defined by a position, half-extents and orientation
  • commonly used

k-DOP

  • discrete oriented polytope
  • more-general case of AABB and OBB
  • approximates the shape of an object

Convex volume

  • more general shape
  • must be convex
  • expensive for intersection test

Primitives

Poly Soup

  • used to model complex static geometry (terrain)
  • very expensive kind of collision test

Compound shapes

  • more-efficient alternative to a poly-soup
  • the system first tests bounding volumes of compound shapes

Convex hull

  • smallest convex volume containing the object

Complex shape/volume

  • not necessarily convex
  • simplified mesh/sprite
  • needs preprocessing (BSP)

Comparison

Example: Box2D

Looking for collision candidates

Naive solution

  • each pair
  •  -> 10 objects result in 100 checks, 100 in 10 000 etc.

Quad-tree

  • efficiency usually , since the index takes about   comparisons to traverse
  • good for point-like small objects
  • worst-case:

Sweep and Prune

  • sorts the starts (lower bound) and ends (upper bound) of bounding volumes of each solid along a number of axes

BSP

  • binary space partitioning, good for complex static geometries (facilities, buildings)

Grid, Oct-tree, R-Tree, R+tree, R*-tree, X-tree, M-tree,...

Resolving collision candidates

Sphere-sphere

  •  where  is a central point

Sphere-ray

  • we just test the distance between a single sphere center and a ray

AABB-AABB

  • test the borders

AABB-Ray

  • intervals  and  mustn't overlap

Resolving collision candidates

Capsules

  • capsule-capsule - calculate the distance between two line segments
  • capsule-ray - find the distance between a ray and a line segment

OBB-OBB

  • axis-separating theorem by Gottschalk

Triangles

  • triangle-triangle - compute the plane equation and test each point if it lies on the same side
  • triangle-ray - Möller's affine combination

SAT

SAT (separating axis theorem)

  • based on collection of intersection tests
  • if an axis can be found along which the projection of two convex shapes do not overlap, then the two shapes do not intersect
  • for 2D: AABB 2 axes, OBB 4 axes
  • for 3D: AABB 3 axes, OBB 15 axes

Other methods

  • GJK, Line Sweep, Sphere test,...

Example: SAT

  • AABB in 2D: only 2 axes to check

Tunneling problem

Stepped world

  • time steps vary based on occurring situation
  • collision time is calculated by doing binary search in time, moving object back and forth by 1/2 steps (5 iterations is usually enough)

Continuous Collision Detection (CCD)

  • uses Swept Shapes
  • a new shape is formed by the motion of the original one
  • rotating shapes may result in shapes that aren't convex

Collision queries

Queries:
  • Find the first target the bullet hits
  • Can a camera move without interpenetrating the wall?
  • Find all objects within a given radius

Ray casting

  • any game is going to need a good raycaster
  • the cast line segment is tested against the collidable objects in the collision world; if it intersects any of them, the contact point is returned
  • weapon systems, player mechanics, AI systems, vehicle systems, line-of-sight
  • used in 80's and 90's also for pseudo-3D rendering, nowadays it's being replaced by raytracing

Shape casting

  • how far a shape would be able to travel along a directed line segment before it hits something
  • sphere casts - e.g. to determine whether the camera is in a collision
  • capsule casts - e.g. character movement on uneven terrain

Collision response

How to respond to a collision?

Explosion

  • adding energy to a system of rigid bodies

Fracturing

  • breaking objects apart

Restitution

  • amount of bounce an object has when it hits something

Impulsive response

  • when two bodies collide, the bodies compress slightly and then rebound, changing their velocities, losing energy

Friction

  • force that arises between two bodies that are in continuous contact, resisting their movement relative to one another
  • removes energy from a system of rigid bodies
  • static, dynamic, rolling

Collision resolver

Collision resolving

  • LCP - Linear Complementarity Problem
  • very complex numeric algorithms
  • resolvers: PGS, Dantzig solver, Lemke method, Jacobi method

Coming to rest

  • all objects lose energy, leading to eventual rest
  • not simple (floating-point error, inaccuracies, numerical instability)
    • sleep criteria
      • momentum or energy are below a threshold
    • simulation islands
      • grouping objects that either are interacting or have a potential to interact

Sleeping objects

Fracturing

  • breaking an object into smaller fragments
  • in many cases destruction is not dynamic (can be made using animations)
  • techniques: manual fracturing, boolean operations, Voronoi Shattering

Particle systems

Particle systems

  • a collection of point masses that obeys certain physical laws
  • can model complex fuzzy shapes and dynamics
  • heavily used Flyweight pattern (array of positions, velocities, group lists)
  • particles are not only moving points! Even a tree may become a particle!

Applications

  • fluids
  • visual effects
  • flocks
  • rendered trails (plants)
  • soft bodies (flag, cloth)

Basic model

  1. generate new particles
  2. assign individual attributes
  3. extinguish dead particles
  4. move and transform particles according to their dynamic attributes
  5. render meshes

Attributes

  • position
  • velocity
  • orientation
  • acceleration
  • mass
  • size
  • color
  • lifetime
  • material
  • temperature

Particle systems in games

Example: Fairlight

  • a demoscene group that pushed the idea about particle systems to absolute hardware limits

Agenda Circling Forth (2010)

Instant God (2016)

Liquidfun

  • 2D rigid body and fluid simulation library, Box2D extension
  • Android, iOS, Windows, OS X
  • phase 1: collision detection
    • find pairs of particles closer than the particle diameter
  • phase 2: apply pressure
    • sum up the weight of contacts for each particle
    • calculate the pressure and apply repulsive forces
  • phase 3: apply other forces
    • viscous force, spring force, elastic force,...
  • phase 4: update positions
  • phase 5: handle interaction with Box2D

Example: Noita

  • WIP game that uses a falling sand-style simulation
  • each pixel is considered a particle having their own attributes
  • flood-algorithm for ignition effects
  • each screen is divided into 64x64 chunks processed in 4 stages from the bottom up

Lecture 7 Review

  • Physics engine steps: apply forces, update positions, detect and resolve collisions and constraints
  • Object types: Body, Rigid Body, Soft Body, Shape, Fixture, Constraint, Sensor, Rag doll, Destructible object
  • Constraints: revolute, distance, rope, prismatic, weld, cone-twist, gear, motor
  • Primitives: sphere, capsule, AABB, OBB, k-DOP, Convex volume, Poly Soup, Compound shapes, Convex hull, Complex volume
  • SAT (separating axis theorem
    • if an axis can be found along which the projection of two convex shapes do not overlap, then the two shapes do not intersect
  • Tunneling problem - handled by stepped world or CCD
  • Collision queries: ray casting, shape casting
  • Particle systems - a collection of point masses that obeys certain physical laws

Goodbye quote

Didn’t we have some fun though?Portal