rasmus haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/fulltext01.pdf ·...

53
Department of Science and Technology Institutionen för teknik och naturvetenskap Linköping University Linköpings universitet g n i p ö k r r o N 4 7 1 0 6 n e d e w S , g n i p ö k r r o N 4 7 1 0 6 - E S LiU-ITN-TEK-A--16/049--SE A collision framework for rigid and deformable body simulation Rasmus Haapaoja 2016-11-02

Upload: lycong

Post on 27-Aug-2018

228 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Department of Science and Technology Institutionen för teknik och naturvetenskap Linköping University Linköpings universitet

gnipökrroN 47 106 nedewS ,gnipökrroN 47 106-ES

LiU-ITN-TEK-A--16/049--SE

A collision framework for rigidand deformable body simulation

Rasmus Haapaoja

2016-11-02

Page 2: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

LiU-ITN-TEK-A--16/049--SE

A collision framework for rigidand deformable body simulation

Examensarbete utfört i Medieteknikvid Tekniska högskolan vid

Linköpings universitet

Rasmus Haapaoja

Handledare Andrew GardnerExaminator Jonas Unger

Norrköping 2016-11-02

Page 3: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Upphovsrätt

Detta dokument hålls tillgängligt på Internet – eller dess framtida ersättare –under en längre tid från publiceringsdatum under förutsättning att inga extra-ordinära omständigheter uppstår.

Tillgång till dokumentet innebär tillstånd för var och en att läsa, ladda ner,skriva ut enstaka kopior för enskilt bruk och att använda det oförändrat förickekommersiell forskning och för undervisning. Överföring av upphovsrättenvid en senare tidpunkt kan inte upphäva detta tillstånd. All annan användning avdokumentet kräver upphovsmannens medgivande. För att garantera äktheten,säkerheten och tillgängligheten finns det lösningar av teknisk och administrativart.

Upphovsmannens ideella rätt innefattar rätt att bli nämnd som upphovsman iden omfattning som god sed kräver vid användning av dokumentet på ovanbeskrivna sätt samt skydd mot att dokumentet ändras eller presenteras i sådanform eller i sådant sammanhang som är kränkande för upphovsmannens litteräraeller konstnärliga anseende eller egenart.

För ytterligare information om Linköping University Electronic Press seförlagets hemsida http://www.ep.liu.se/

Copyright

The publishers will keep this document online on the Internet - or its possiblereplacement - for a considerable time from the date of publication barringexceptional circumstances.

The online availability of the document implies a permanent permission foranyone to read, to download, to print out single copies for your own use and touse it unchanged for any non-commercial research and educational purpose.Subsequent transfers of copyright cannot revoke this permission. All other usesof the document are conditional on the consent of the copyright owner. Thepublisher has taken technical and administrative measures to assure authenticity,security and accessibility.

According to intellectual property law the author has the right to bementioned when his/her work is accessed as described above and to be protectedagainst infringement.

For additional information about the Linköping University Electronic Pressand its procedures for publication and for assurance of document integrity,please refer to its WWW home page: http://www.ep.liu.se/

© Rasmus Haapaoja

Page 4: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Abstract

This thesis describes methods for collision detection and collision response,implemented in a complete collision framework for both rigid and deformablebodies. The framework is intended to act as a base for new technologiesregarding muscle and facial simulation for feature film production, at thevisual effects studio MPC. Specifically, we implement sweep and prune asa first step in our collision detection for fast pruning of pairs, followed byoptimized spatial hashing to decrease the amount of triangle intersectiontests. Further, we use a constraint-based method for collision response basedon iterative constraint anticipation, which provides several advantages interms of accuracy compared to penalty- or impulse-based methods.

Page 5: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Acknowledgements

I would like express my gratitude and sincere thanks to my supervisor Sara C.Schvartzman, MPC, for her patience, guidance and discussions throughoutthe project. This work would not have been possible without her help. Anadditional thank you to Rob Pieke, MPC, who gave me the opportunity todo my thesis at MPC’s London studio, for which I am truly grateful. I wouldalso like to thank my examiner Jonas Unger and my supervisor AndrewGardner at Linkoping University for their guidance and support. Finally, agreat thank you to my family for both their mental and economical supportthroughout my stay in London.

Page 6: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Contents

1 Introduction 11.1 Purpose and Aim . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.3 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.4 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

1.4.1 Typographical conventions . . . . . . . . . . . . . . . . 3

2 Background 42.1 Dynamics and Numerical Integration . . . . . . . . . . . . . . 42.2 Collision detection . . . . . . . . . . . . . . . . . . . . . . . . 6

2.2.1 Bounding Volume Hierarchies . . . . . . . . . . . . . . 62.2.2 Distance Fields . . . . . . . . . . . . . . . . . . . . . . 7

2.3 Collision response . . . . . . . . . . . . . . . . . . . . . . . . . 82.3.1 Penalty-based collision response . . . . . . . . . . . . . 92.3.2 Impulse-based collision response . . . . . . . . . . . . . 10

3 Collision detection 123.1 Broad phase . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

3.1.1 Sweep and prune . . . . . . . . . . . . . . . . . . . . . 123.2 Narrow phase . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

3.2.1 Collision definition . . . . . . . . . . . . . . . . . . . . 153.2.2 Optimized spatial hashing . . . . . . . . . . . . . . . . 16

Update . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Query . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Parameters . . . . . . . . . . . . . . . . . . . . . . . . 18

3.2.3 Moller-Trumbore intersection test . . . . . . . . . . . . 193.2.4 Collision groups . . . . . . . . . . . . . . . . . . . . . . 23

4 Collision response 244.1 Constraint-based collision response . . . . . . . . . . . . . . . 24

4.1.1 Mixed linear complementary problem . . . . . . . . . . 254.1.2 Constraint anticipation . . . . . . . . . . . . . . . . . . 264.1.3 Matrix construction . . . . . . . . . . . . . . . . . . . . 274.1.4 Iterative constraint anticipation . . . . . . . . . . . . . 30

4.2 Projected Gauss-Seidel (PGS) . . . . . . . . . . . . . . . . . . 32

5 Implementation 345.1 Collision framework . . . . . . . . . . . . . . . . . . . . . . . . 345.2 Maya Plugin . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

Page 7: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Contents

6 Discussion 386.1 Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

6.1.1 Visual results . . . . . . . . . . . . . . . . . . . . . . . 386.1.2 Performance . . . . . . . . . . . . . . . . . . . . . . . . 40

6.2 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426.3 Future work . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

6.3.1 Alternative integration schemes . . . . . . . . . . . . . 426.3.2 Additional algorithms . . . . . . . . . . . . . . . . . . 436.3.3 Continuous collision detection . . . . . . . . . . . . . . 436.3.4 Friction . . . . . . . . . . . . . . . . . . . . . . . . . . 436.3.5 Additional constraints and simulated bodies . . . . . . 44

Page 8: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 1

Introduction

Most of the major visual effects studios have often been associated with ex-pertise in e.g. photo realistic digital characters, huge crowds or advanced vol-umetric effects like smoke and water. This classification has however startedto dissolve over the past few years, with studios catching up on their compe-tition within areas previously considered as slightly weaker, as the audiencenow a days often struggles to distinguish real footage from CG. The MovingPicture Company (MPC), often known for their realistic crowd simulations,has recently showed great improvement on digital actors and characters withthe creation of a young and completely digital Arnold Schwarzenegger in Ter-

minator: Genisys. Most recently, they blurred the line between reality andCG even more with the digital world and animals in The Jungle Book.

Despite these recent achievements, MPC is still looking to push their digitalactors to the next level with the Thalia project, where one group is currentlydoing research on simulation of muscles and facial animations. These simu-lations drives volumetric FEM meshes, whose dynamics are handled by theopen source FEM solver Vega FEM. However, Vega lacks collision handling,and MPC’s main collision solver Kali sometimes struggles with penetrationand stability issues when exposed to a higher number of concurrent colli-sions. Hence, this thesis propose a framework to accurately detect and solveboth internal collisions from the rigs themselves, as well as external collisionscaused by objects from the rest of the 3D scene.

1.1 Purpose and Aim

The purpose of this thesis project has been to implement an extendable colli-sion framework capable of handling both rigid and deformable contacts, witha robustness and accuracy that collision solvers currently in MPC’s pipelinestruggles to achieve. This, in order to allow for both internal and externalcollisions in the next generation of simulated muscle and face rigs currentlybeing developed at MPC. The aim has been to investigate promising collisiondetection and collision response models, and to implement a carefully chosenset of these, with accuracy and robustness as priority, into a framework with

1

Page 9: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 1. Introduction

the potential for further future extensions.

1.2 Outline

The thesis is organized as follows. Initially, chapter 2 summarizes the ba-sics regarding the dynamics and numerical integration along with promisingalgorithms for collision detection and standard methods for computation ofcollision response. Further, chapters 3 and 4 covers the methods and al-gorithms used for collision detection and collision response in this thesis.Focus then shifts, as chapter 5 presents the implementation of the selectedalgorithms in an extendable collision framework exposed to users as a Mayaplugin. Finally, chapter 6 summarizes the results, concludes the project anddiscusses possible future work.

1.3 Prerequisites

The reader is expected to have knowledge of linear algebra, programmingand computer graphics in general, at an undergraduate level, as well as fa-miliarity with basic concepts within collision detection, collision response andnumerical integration.

1.4 Glossary

1D One-dimensional2D Two-dimensional3D Three-dimensionalPGS Projected Gauss-SeidelLCP Linear Complementary ProblemMLCP Mixed Linear Complementary ProblemCA Constraint AnticipationICA Iterative Constraint AnticipationDoF Degree of FreedomODE Ordinary Differential EquationFEM Finite Element MethodAABB Axis Aligned Bounding BoxOBB Oriented Bounding Box

2

Page 10: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 1. Introduction

1.4.1 Typographical conventions

Code RandomClassName

Scalar x

Vector vMatrix MDerivative v

3

Page 11: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 2

Background

In this chapter we introduce the fundamental concepts of the dynamics for-mulations used for our simulations. We also cover the basic concepts, alongwith brief descriptions of some popular methods, for both collision detectionand collision response.

2.1 Dynamics and Numerical Integration

In general, Newton’s equations of motion is the foundation of all types ofphysics-based simulation. Newton’s second law states that the accelerationof a body, with constant mass, is proportional to the force that is beingapplied. Since simulations often includes multiple degrees of freedom (DoFs),the relation can be expressed in vector form:

f = Ma = Mv (2.1)

where f is the force vector, M is a constant mass matrix, a is a vectorcontaining the accelerations of all DoFs being simulated, and v contains thevelocities of the same DoFs.

Based on the formulations above, the corresponding positions for all DoFs ofthe simulation is comprised in a state vector q, allowing the dynamics to bediscretized with ODEs of the form:

Mv = fq = Gv

(2.2)

where G relates the velocity vector to the derivative of the state vector. Thematrix G is included in the relation between q and v since, for rigid bodies,the time derivative of the orientation matrix R is not the angular velocityω, but instead:

4

Page 12: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 2. Background

R = ω∗R where ω∗ =

0 −ωz ωy

ωz 0 −ωx

−ωy ωx 0

(2.3)

Since Eq. 2.2 is very general, it is applicable to several types of models, e.g.,rigid bodies, mass-spring systems, finite element methods (FEMs) etc. In thisthesis project, rigid body dynamics have been implemented from scratch,while the dynamics of deformable bodies are handled by the open sourcesolver Vega FEM developed by Schroeder et al. [7]. The solver handles, asthe name might hint, several types of FEMs, but also mass-spring systems,which allows for simulation of a wide variety of elastic materials.

Pairing Eq. 2.2 with a numerical integration scheme, positions (and orienta-tions for rigid bodies) and velocities can be computed at different instantsof time. Before choosing an appropriate integration scheme, the pros andcons of explicit vs. implicit schemes should first be considered. Since explicitschemes only uses the currently known state variables to compute the stateat the next time step, they are often easy to implement. However, an error isintroduced after each computation, which for stiff systems often cause severestability issues. The error can partially be reduced by decreasing the size ofthe time step, which obviously comes with the drawback of slowing down thesimulation. Hence, explicit integration schemes are better suited to simplesimulations and systems that does not depend on high accuracy. In order toobtain high accuracy as well as the ability to use large time steps, implicitintegration schemes can be used. While explicit methods uses the currentknown state in order to compute the new state one time step forward intime, implicit methods requires the new state in order to solve the system,hence the name implicit integration schemes. These are solved by either amatrix or iterative technique, in this thesis the matrix approach was used.Formulating the known state at the beginning of each time step as (q0,v0),the linear velocity update can be written as:

Av = b (2.4)

Which can be applied to each Newton iteration of implicit solvers as e.g.backward Euler or Newmark. In this thesis we use the backward Eulermethod coupled with the assumption of a constant mass matrix for eachtime step. The linear velocity update is then defined as:

5

Page 13: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 2. Background

A = M−∆t∂f

∂v−∆t2 G

∂f

∂q,

b = ∆t f(q0,v0) +(

M−∆t∂f

∂v

)

v0

(2.5)

where ∆t is the time step of the simulation.

2.2 Collision detection

The collision detection phase of the simulation loop is responsible for de-tecting whether bodies1 in the 3D scene are in contact or even penetratingeach other. Both of these cases are reported as collisions. The naive way ofdetecting these would be to compare all polygons in the scene against eachother to determine which bodies that collide. This approach will however bevery inefficient as the number of polygons grow, with a time complexity ofO(n2), where n is the number of polygons. In order to achieve better per-formance, the collision detection is often divided into two separate phases,known as the Broad Phase and the Narrow Phase. Both of which utilizevarious acceleration structures in order to prune as many triangle intersec-tion tests as possible, since these are computationally very heavy. The broadand narrow phases will be covered in-depth in Chapter 3, along with theacceleration structures implemented in this project. For completeness and toprovide a good base for the motivation of our algorithm of choice, two verypotent narrow phase collision detection algorithms will be presented brieflybellow.

2.2.1 Bounding Volume Hierarchies

Bounding volumes, Figure 2.1, are simple geometries used to encapsulate andapproximate a more advanced polygon model, that can be used with greatsuccess to accelerate the collision detection. The advanced model is encap-sulated in a tree-structure of these bounding volumes which provide betterapproximations as the structure is traversed deeper. Triangle tests are thenpruned efficiently, as the tree is traversed and collision tests between thebounding volumes are performed for as long as possible. The leaf nodesoften contain a single or a few triangles, which are then used to compute

13D meshes that are included in the simulation.

6

Page 14: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 2. Background

actual intersection points if the entire depth of the structure is traversed andbounding volumes are still intersecting. However, triangle intersections arenot forced, one might also compute an approximated intersection point byonly using the leaf bounding volume as the final level. Hence, the efficiencyand accuracy of the algorithm might depend heavily on the type bound-ing volume used. While Axis Aligned Bounding Boxes (AABBs) are veryefficient computation wise, they rarely provide a tight fit around the encap-sulated object, and hence struggles with accuracy if no further intersectiontests are performed after a leaf node have been reached. Oriented Bounding

Boxes (OBBs) on the other hand provide very good approximations of theenclosed body, while the intersection test between the bounding volumes isconsiderably more expensive. Another alternative is spheres, which allowfor fast computation of intersections since they can be expressed implicitlyby only a radius and position, while also approximating the body slightlybetter than an AABB. An illustration of the 3 mentioned bounding volumehierarchies is provided in Figure 2.1.

(a) (b) (c)

Figure 2.1: Simple 2D mesh enclosed in bounding volume hierarchies consisting of(a) AABBs, (b) OBBs and (c) implicit circles.

2.2.2 Distance Fields

With the introduction of libraries such as OpenVDB [20] and Field3D [23],that provides compact storage and fast manipulation of voxel-data, volumeshave been allowed to be exploited more efficiently within collision detection.The polygon surface is first represented implicitly by a function φ(x) thatmaps a scalar value to every point in space x. The surface can then be foundby selecting every point in space which corresponds to a specific iso-value

or level-set φ(x) = C. By setting C = 0, the inside/outside of the surface

7

Page 15: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 2. Background

can easily be classified by a negative/positive sign convention, and allowsthe scalar function φ(x) to describe the euclidean distance to the surfaceinterface. The distance field can now be used to determine if two surfacesintersects by simply evaluating their scalar functions in the voxels. If a voxelcontains two bodies with a negative distance to their respective surfaces, theyare intersecting and a collision is detected, as illustrated in Figure 2.2(b). Oneof the biggest advantages of the distance field approach is that collisions canbe detected with very high precision. However, even though the sparse datastructure provides sufficient improvements to both efficiency and memoryfootprint compared to dense representations, the memory usage is still oneof the major drawbacks with the method.

(a) (b)

Figure 2.2: 2D examples of implicit circle(s) discretized to uniform grid. (a)Implicit circle along with classification of its signed distance function φ(x, y). (b)Collision between implicit circles A and B where both φA(x, y) and φB(x, y) arenegative.

2.3 Collision response

In order to enhance the realism of the simulation, a collision response mustbe applied to the detected collisions. This step often involves both the avoid-ance of interpenetration as well as applying friction forces. However, in thisthesis we will only be taking the interpenetration part into consideration,while the friction will be left as future work. There are three main meth-ods for computation of collision response, each with their own strengths andweaknesses. Two of these will be covered briefly in this section. This in or-der to provide a good base and motivation for the constraint-based method

8

Page 16: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 2. Background

which was used in this project.

2.3.1 Penalty-based collision response

The penalty-based contact model, as first introduced by Moore and Wil-helms [19], utilizes the concept of spring-damper systems in order to coun-teract interpenetrations. Penalty forces are generated by zero rest-lengthdamped springs that are attached to each pair of collision points, as illus-trated in Figure 2.3.

Figure 2.3: Penetrations penalized by damped springs attached to collision points.

The total force vector f is then expressed as the sum of all external forcesfext and all the spring forces fspringi acting on a simulated body:

f = fext +∑

i

fspringi (2.6)

The spring force applied to a pair of collision points, pA and pB, is thencomputed as:

fspring = (−k d− b vr) · n (2.7)

where k is the stiffness of the spring, d is the penetration depth, b is thedamping constant, vr is the relative velocity between the collision pointsprojected on the normal, and n is the collision normal (assumed to be chosenas the normal at pB). The relative velocity is defined as:

vr = nT · (vA − vB) (2.8)

9

Page 17: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 2. Background

where vA and vB are the velocities of the contact points pA and pB respec-tively.

The penalty forces are easily applied to both rigid and deformable bodies.For rigid bodies, forces are usually applied to single points on both bodies.However, deformable bodies simulated by e.g. mass-spring systems or FEMs,requires forces to be applied to every node in contact, and then allowing theproduced internal forces to affect the rest of the structure in an appropriatemanner.

Even though the computations of the resulting forces are fairly simple, theyare associated with a few difficulties. First of all, the penetration depthand collision normal depends heavily on the geometry of the colliding bodiesand are far from trivial to compute. Furthermore, the coefficients of thedamped springs require precise tuning in order to produce a perfectly dampedbehaviour with no oscillations. Since these depend heavily on the scene setup,the penalty-based method is not suitable for a complete collision frameworkwhere situations with heavy stacking of both rigid and deformable bodies arecommon. Additionally, as mentioned in Sec. 2.1, explicit integration schemesmight struggle with instabilities for stiff differential equations. The penalty-based method is a perfect example of when this might become a problem sincethe attached springs in most cases are very stiff and hence might produce anoscillatory behaviour. However, this problem is often solved by using implicitintegration schemes instead, as was previously mentioned.

When high performance is prioritized, penalty forces is often the method ofchoice, since it presents linear time complexity as collisions are added.

2.3.2 Impulse-based collision response

Mirtich and Canny [17] introduced a collision response based on impulses,that separates colliding bodies by applying a large force over a short periodof time. Physically this is defined as the integral of force with respect totime:

j =

∫ tf

ti

f dt (2.9)

where j is the resulting impulse created by the force f over the time interval[ti, tf ]. Transferring this into an algebraic model, the impulse vector j isinstead computed as a scalar j along the collision normal n during one frame

10

Page 18: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 2. Background

of the simulation. Since this is only a brief overview of the method, thereader is referred to Baraff [6] for the full derivation of the impulse scalarj.

Solving a collision using impulses for a single contact between two bodiesis trivial. However, in a multibody framework consisting of both rigid anddeformable bodies, larger contact interfaces and/or simultaneous collisionsbetween several bodies are common. Solving for these multiple impulsesduring a single time step is done either sequentially or simultaneously.

The sequential approach is most straight forward, and treats multiple con-current contacts as a series of single contact points which are iterated andsolved until a collision free state is reached. Even though the method mightbe simple, there are a few major drawbacks associated with it. Since col-lisions are solved in a certain order, changing it might affect the outcomeof the simulation. Additionally, since collisions are solved one by one, thesequential solve might accidentally produce new collisions when velocitiesare updated for bodies from previous solves in the time step. One situa-tion where this problem is likely to occur is when bodies are heavily stackedagainst each other, and thus might create an infinite loop of collisions. Thereare however situations where this propagation of collisions is desired, as forexample Newton’s cradle.

The simultaneous method treat collisions in a slightly different manner. Bypredicting new velocities for the bodies in contact, impulses can then becomputed in order to satisfy these predictions and thus produce a globalcollision free state. Thus, the method does not suffer from the same problemsas the sequential solve, since collisions are instead solved at the same time.However, this doesn’t guarantee that the simultaneous approach is betterthan the sequential by any means. The simultaneous solve e.g. cannot handlepropagation of forces, as in the case of Newton’s cradle.

The sequential impulse-based method is the most popular one, and generallyworks good enough for most game applications, where both good performanceand realism is desired.

11

Page 19: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 3

Collision detection

This chapter will cover the collision detection methods implemented in thisthesis project in their entirety. Tweaks done to the algorithms as they wereoriginally proposed, based on discoveries during the implementation, will alsobe presented and motivated.

As stated previously in Sec. 2.2, a naive brute-force intersection test betweenevery possible triangle pair in a scene would produce a devastating quadratictime complexity. The first step towards a more efficient collision detection ishence to divide it into a Broad and Narrow phase, in order to prune as manytriangle intersection tests as possible.

3.1 Broad phase

The Broad phase of the collision detection is responsible for reporting po-tential collisions between pairs of bodies that are sufficiently close to eachother. This is usualy determined by either looking for overlapping boundingvolumes - as AABBs, OBBs or implicit spheres - or by partitioning spaceand assigning bodies to the intersected partitions. In this thesis we detectpossible collisions by using the bounding box approach.

3.1.1 Sweep and prune

The sweep and prune algorithm, initially presented by Baraff [3], utilizesbounding boxes, in this case AABBs, as approximations of the simulatedbodies in order to simply and efficiently determine probable collision pairs.If two bounding boxes are found to not overlap, no further investigationregarding the content of these boxes is required. Given a set of n AABBs,a naive pairwise comparison of all possible pairs would require O(n2) work,which obviously can be improved.

We start by breaking down the problem from 3D into three 1D problems.This allows us to instead describe an AABB as simply an interval [b, e] alongeach axis in 3D space. Now consider n such intervals and the ith interval

12

Page 20: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 3. Collision detection

being denoted as [bi, ei] ⊂ R1. We then want to find all pairs i and j with

overlapping intervals [bi, ei] and [bj, ej]. If two intervals i and j are reportedto overlap along all three coordinate-axis, the AABBs are intersecting andwe report the pair as a potential collision.

Initially, a list of all values bi and ei, sorted from lowest to highest is created.The sorted list is then swept, and a list of active intervals, initially empty,is maintained. We denote this as the active set S. When a value bi isencountered, all intervals currently in S is reported to be overlapping withinterval i, which is then also added to S. When a value ei is encountered,interval i is instead removed from the set S. Observing the time complexityof this process, the creation of the sorted list requires O(n log n), while thesweep through the list takes O(n) and finally the overlap output takes O(k),where k is the number of detected overlaps. This gives us a total timecomplexity of O(n log n+ k), which is an improvement to the naive pairwiseapproach.

There are however additional improvements that can be made by exploitingthe spatial coherence in the scene. Since bodies are likely to only moveslightly between two time steps, there is no need to create a new list ofendpoints bi and ei. Instead the order from the previous time step can beused as a warm-up, which will be ordered nearly correct if coherence is high.The sorting algorithm used to permute the nearly sorted list also have to bechosen carefully. At first glance it might feel convenient to use an algorithmthat is generally proven to be fast; as e.g merge sort or quick sort. Instead,insertion sort is used, as we can once again exploit the high coherence factorsince the list of intervals is nearly sorted at the beginning of the time step.Insertion sort works by moving entries towards the beginning of the listuntil a smaller value is encountered. When the last item in the list hasbeen processed, the list is sorted. A simple illustration of the insertion sortalgorithm is provided in Figure 3.1. A sort of this type takes O(n+ s) time,where s is the number of swaps performed during the sorting process.

Figure 3.1: Simple example where insertion sort is used to sort a nearly sorted list.

13

Page 21: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 3. Collision detection

Note that insertion sort is not recommended as a general sorting algorithmsince it may require O(n2) work. It is however very suitable for sorting nearlysorted lists, as in our highly coherent simulation world. For completeness,an example producing the worst possible scenario for our choice of algorithmwill also be covered. Consider a scene setup as in Figure 3.2(a) at time t,where 4 bodies are affected by gravity and nearly colliding with a static box.At the next time step t + ∆t, the bodies have collided with the box andare now moving upwards due to the applied collision response, accordingto Figure 3.2(b). In this scenario our assumption of high coherence failsconsiderably, since the order of the bodies along the y-axis are completelyinverted. Meaning that every single element in our list of endpoints has tobe swapped in order for our list to be sorted again. Luckily, a situation ofthis type is not very likely to appear, but should still be taken into accountwhen evaluating the full potential of the algorithm.

(a) (b)

Figure 3.2: Example of worst case scenario for the sweep and prune algorithm,with the ordering of endpoints along the y-axis being completely inverted betweenframes at time t (a) and t+∆t (b).

In summary, if a list of overlapping intervals at each time step is maintained,the list can be updated at each time step with a cost of O(n+s). Comparingthis to an optimal algorithm which would have a time complexity of O(n+k),we can observe that our approach is efficient when k − s is small. That iswhen the amount of swaps needed to sort the list of endpoints is close to thenumber of changes in overlap status. If we once again assume high coherence,the number of swaps s will be very close the number of overlap changes k.Hence the extra O(k − s) work will often be negligible. Thus, the coherenceview for the one-dimensional case of bounding-boxes yields a simple andefficient algorithm, approaching optimality as coherence increases.

14

Page 22: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 3. Collision detection

3.2 Narrow phase

When pairs of potentially colliding bodies have been detected in the broadphase, we proceed into the narrow phase where a more sophisticated andaccurate scheme is used in order to determine pairs of triangles that mightintersect. As mentioned in Sec. 2.2, bounding volume hierarchies and dis-tance fields are two popular approaches that has been used with success inother applications. However, since these also suffer from drawbacks whichmight end up crucial for our application, we instead use a grid based approachthat suits our needs slightly better. Note that the triangle intersection testis performed in a separate last step, but is, however, still classified as a partof the narrow phase.

3.2.1 Collision definition

Before we cover the collision detection algorithm used in the narrow phase,we should first define a collision. That is, the information required in orderto solve the detected collisions later on in the simulation step. In a colli-sion we gather information of a single contact between two bodies, A andB. Note that deformable bodies might produce a larger contact area withseveral points of contact. These will, however, still be initially defined asseparate collisions which will be collected into groups at a later stage. Wealso require information of which triangles TA and TB from both bodies thatare intersecting. These triangles will later be used to find the collision pointspA and pB which are used to define a penetration depth later on in thesimulation loop. Since discrete collision detection is used, we do require aspecial method, or hack, in order to find these collision points and to emulatethe result of continuous collision detection. The final component needed fora complete collision is the collision normal nc which is chosen as the facenormal of triangle TB. Thus, our collision structure looks as follows:

Listing 3.1: Collision structure.

struct Collision{Body ∗A , ∗B ;unsigned int T_A , T_B ;vec3 p_A , p_B ;vec3 normal ;

} ;

15

Page 23: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 3. Collision detection

3.2.2 Optimized spatial hashing

In the narrow phase we use optimized spatial hashing, which implicitly sub-divides R3 into small uniformly sized cells. In the original paper by Teschneret al. [22], they propose a two pass approach. In a first pass they classifyall vertices in the scene with respect to the small 3D cells, while they in asecond pass classify all tetrahedrons with respect to the same 3D cells. Ifa tetrahedron is mapped to the same cell/cells as one or more vertices, thistetrahedron and all vertices associated with the same cell has to be checkedfor intersection. This approach is however best suited for vertex-tetraherdacollisions. Since we use triangle meshes as our collision geometries, the al-gorithm has to be slightly modified to suit our needs. Worth mentioning isthat we performed tests with a similar approach to Teschner et al. [22] bymapping vertices in a first pass and then triangles instead of tetrahedrons ina second pass. However, this resulted in missed collisions and hence a lackof robustness and accuracy, both of which are two very important aspectsfor our application. The modified optimized spatial hashing algorithm usedin this thesis still utilize the two pass approach, also known as the updateand the query. In the update, all structures needed to perform the collisiondetection is updated, while the query perform the actual collision detectionusing the updated structures.

Update

In the first pass - the update - we start by computing the correspondingAABB for each triangle in the scene. The only information needed to rep-resent an AABB is two points in 3D space, one containing the maximumcoordinates pmax = (xmax, ymax, zmax) and one containing the minimum co-ordinates pmin = (xmin, ymin, zmin). The position of these endpoints are thendiscretized with respect to a user-defined cell size, i.e. the coordinates of agiven endpoint (x, y, z) are divided by the cell size l and rounded down tothe closest integer (i, j, k):

i =⌊x

l

, j =⌊y

l

, k =⌊z

l

, (3.1)

We then map all discretized coordinates (i, j, k), that are covered by theAABB, with a hash function to a 1D index h = hash(i, j, k) in a hash table.The required triangle and object information is then stored at this index h in

16

Page 24: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 3. Collision detection

the table. A simple 2D example of the update phase is provided in Figure 3.3,where a single triangle is mapped to the hash table.

Figure 3.3: 2D example where hash values are computed for all cells covered by theAABB of a triangle.

Query

In the second pass - the query - we loop over the hash table and look forentries with multiple triangles. If such an entry is found, we start by per-forming a simple overlap test of the AABBs of both triangles. This step isnot included in the original paper, however our tests showed that the AABBtest slightly increased performance since additional false triangle pairs waspruned. If the AABBs overlap, the triangle pair has to be further investi-gated. We then perform the actual intersection test which has been avoidedfor as long as possible, since it’s quite expensive to compute. The algorithmused to compute the collision points of both triangles is covered thoroughlyin Sec. 3.2.3.

Note that the hash table structure also allows us to easily detect self-collisionswithout any extraordinary extensions to the algorithm. The only conditionrequired is that adjacent triangles should not be tested. This is, however,easily determined by a comparison of the vertex indices used in both trianglesbefore any further evaluation is performed.

Another advantage that comes with the spatial hashing algorithm is that thequery phase can easily be multi-threaded. The cells of the hash table can sim-ply be distributed over all available cores, allowing each core to individually

17

Page 25: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 3. Collision detection

detect potential collisions using the method described above.

Parameters

The hash function, grid cell size and hash table size are parameters thathas to be carefully chosen in order to achieve optimal performance. In thework by Teschner et al. [22] they provide a nice motivation coupled withseveral performance tests in order to evaluate the importance of all threeparameters.

Since the first pass computes hash values for all discretized AABB end points,these need to be uniformly distributed in order for the algorithm to performas good as possible. Also, the hash function needs to handle triangles of thesame object that are close, as well as triangles of different objects that areseparated. Hence, the hash function used in this thesis, as well as in [22],takes a discretized position (i, j, k) and returns a hash value:

hash(i, j, k) = (x p1 xor y p2 xor z p3) mod n (3.2)

where the value n is the hash table size and p1, p2 and p3 are large primenumbers. We use the values 73856093, 19349663 and 83492791, for p1, p2and p3 respectively, as proposed by Teschner et al. [22].

The size of the hash table has a significant influence on the performanceof the overall algorithm. Larger hash tables reduces the risk of mappingdifferent primitives to the same hash index. Note however that very largetables might decrease performance slightly, since the memory managementthen becomes a problem instead. It has also been proved by Cormen etal. [10] that hash functions are more efficient when the size of the hash tablen is a prime number. Therefore, we use a hash table of the size 1.2 times thenumber of vertices in the scene, rounded to the next hundred subtracted byone. I.e. if a scene would contain 2000 vertices, the size of the table n wouldbe 2399. Which seems to be a good trade-of between memory consumptionand number of false positive hash table collisions.

The implementation of the hash table is an aspect that should also be takeninto account. A simple implementation would re-initialize the hash table ateach simulation step, which will be very inefficient for large tables. This canhowever be avoided by storing a time stamp in each table entry. Hence, ifthe first pass stores triangles in a cell with an outdated time stamp, the cellis cleared and the time stamp is updated before new triangles are inserted.

18

Page 26: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 3. Collision detection

If the time stamp is valid, new triangles are simply appended to the hashcell. When the hash table is traversed in the query phase, we only examinecells with a valid time stamp, while outdated cells are ignored.

The grid cell size l, used when discretizing AABB end points, heavily in-fluences the number of primitives that are mapped to the same hash index.Large cells generates a high amount of primitives per hash index, and henceslows the query phase down. However, if the cell size is significantly smallerthan a triangle, the triangle will cover more cells which might yield moreunnecessary intersection tests. Once again we refer to the performance testsdone by Teschner et al. [22], which shows that the grid cell size should bechosen as the average edge length of all vertices in the scene in order toachieve optimal performance. Their tests also shows that the cells size hasmore impact on the performance of the algorithm than the size of the hashtable or the hash function.

3.2.3 Moller-Trumbore intersection test

The intersection test determines if two triangles intersect or not. In orderto determine this, we use a slightly modified version of the algorithm pre-sented by Moller and Trumbore [18]. Note that their algorithm were initiallydeveloped for ray tracing, since it computes the intersection between a rayand a triangle. However, the theory can also be applied to our needs sincethe intersection between two triangles can be determined by performing 6edge vs. triangle tests. While a ray is defined as an infinite line with onlya starting point, an edge is also limited by an endpoint, which is the onlycondition that we need to add to the existing algorithm.

Lets first consider the case of a ray-triangle intersection. We first define aray r(t) with origin o and direction d as:

r(t) = o+ td (3.3)

A transformation is then constructed and applied to the origin of the ray,which yields a vector containing the distance t to the intersection as well asthe coordinates (u, v) of this intersection. This allows us to avoid the ray-plane intersection test which has been utilized in other algorithms, such asthe one by Badouel [2].

We express a point t(u, v) on a triangle using the barycentric coordinates uand v:

19

Page 27: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 3. Collision detection

t(u, v) = (1− u− v)v0 + uv1 + vv2 (3.4)

with the conditions u ≥ 0, v ≥ 0, u+ v ≤ 1, and where v0, v1 and v2 are thevertices of the triangle being tested. The intersection between the ray r(t)and the triangle t(u, v) is then computed by solving r(t) = t(u, v), which isequivalent to:

o+ td = (1− u− v)v0 + uv1 + vv2 (3.5)

Rearranging the terms and expressing in vector form yields:

[−d, v1 − v0, v2 − v0]

t

u

v

= o− v0 (3.6)

This allows us to compute the barycentric coordinates (u, v) and the distancet from the ray origin to the intersection point, by solving the linear systemin Eq. 3.6.

The formulation above can be geometrically thought of as translating thetriangle to the origin and then transforming it into a unit triangle in theyz-plane with the ray aligned with the x-axis. This is also illustrated inFigure 3.4, where M = [−d, v1−v0, v2−v0] is the matrix in Eq. 3.6.

(a) (b) (c)

Figure 3.4: (a) Ray and triangle, (b) Transform translating v0 to the origin appliedto both ray and triangle, (c) Triangle transformed to unit-triangle in uv-plane andray transformed to align with t-axis.

Denoting two of the triangle edges as e0 = v1 − v0 and e1 = v2 − v0, alongwith t = o−v0, the system in Eq. 3.6 can be solved using Cramer’s rule:

20

Page 28: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 3. Collision detection

t

u

v

=

1∣∣−d, e0, e1

∣∣

| t, e0, e1|| − d, t, e1|| − d, e0, t|

(3.7)

Utilizing that the determinant of three row vectors a, b and c can be com-puted as:

|a,b, c| = −(a× c) · b = −(c× b) · a (3.8)

we can then rewrite Eq. 3.7 as:

t

u

v

=

1

(d× e1) · e0

(t× e0) · e1(d× e1) · t(t× e0) · d

=1

p · e0

q · e1p · tq · d

(3.9)

where p = (d× e1) and q = t× e0. These factors can be precomputed once,and thus save computation time. The equation system in Eq. 3.9 can nowbe trivially solved for each of the parameters t, u and v. We must howeverconsider the order of which we solve for each of the parameters, in order toachieve optimal performance. In our implementation we start by solving forthe barycentric coordinates u and v, since there is no point in computingthe distance t to the possible intersection if the ray does not intersect thetriangle at all. Hence, computing the barycentric coordinates first allowsus to terminate the test early if the ray does not hit the triangle. Whencomputing the distance t to the intersection point, we must make sure thatit fulfills the condition 0 ≤ t ≤ |ei|, i.e. that the point is somewhere on theedge ei currently being tested for intersection.

We have now determined intersections between two triangles TA and TB

according to Figure 3.5(a) or Figure 3.5(b). Recalling the proposed collisionstructure in Sec. 3.2.1 we do, however, require one intersection point for eachtriangle. Hence, the information initially available from the intersection testis not sufficient enough.

In the case of continuous collision detection, the collision points computed bythe initial intersection test would be accurate. However, since we use discretecollision detection we have to track the collision points back in time, sinceit is highly unlikely that a collision occurs exactly at a discrete time step.Referring to Figure 3.5(c), we want to find the points pA and pB highlighted

21

Page 29: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 3. Collision detection

(a) (b) (c)

Figure 3.5: (a) and (b) shows the possible intersection cases, with collision pointsmarked as red, between two triangles TA and TB , (c) shows the approximatedcollision point (blue) obtained by tracking the vertex with deepest penetration(green) backwards using the negative velocity vector.

in green and blue, respectively. First the vertex with deepest penetrationis found by simply evaluating the dot product between the collision normaland the vectors from the initial intersection point to each vertex of triangleTA. The deepest penetrating vertex is then used as collision point pA. A rayis then fired from pA in the negative velocity direction of body A for a rigidbody, or the negative velocity of the corresponding node in the tetrahedralmesh for a deformable body. The intersection point between the ray andtriangle TB is then used as the collision point pB. We now have a good ap-proximation of where the collision first occurred and all information requiredfrom the collision detection has been gathered.

22

Page 30: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 3. Collision detection

3.2.4 Collision groups

The last step before a response to the detected collision can be computed isto divide the bodies that are in collision into separate collision groups. Thiswill allow the response to solve for smaller sub-systems instead of one largesystem, which will be described in detail in Sec. 4.1. The objective is to findchains of bodies that are currently in collision and then collect all collisionsthat consists of these chained bodies. Suppose we have 5 bodies in our scene,as in Figure 3.6, where bodies A, B and C as well as D and E are colliding.In this case 2 clear chains exists and thus 2 collision groups G1 = {A,B,C}and G2 = {D,E} are created.

Figure 3.6: 2D scene containing 5 bodies A, B, C, D and E, forming two separatecollision groups G1 = {A,B,C} and G2 = {D,E}.

In practice, this is done by first determining all bodies that are in contact withbody A, and adding them to a collision group. Further, we also investigatebodies in contact with the ones recently added, and repeat this pattern untilno new pair of bodies are found for the current group. We then move on, andapply the same iterative approach to any remaining bodies, until no furthercollision groups can be created.

23

Page 31: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 4

Collision response

Detected collisions in the simulation world are passed to the collision responsepart of the system, which strives to solve these in order to achieve a globalpenetration free state. The following chapter will thoroughly cover the con-cepts and mathematical theories of the constraint-based collision responsemethod used in this thesis.

4.1 Constraint-based collision response

Constraint-based methods are classified into two different categories: mini-mal coordinate methods, used by Armstrong and Green [1] as well as Feath-erstone [15], which tend to be recursive, and maximum coordinates methods,introduced by Baraff [4], which are based on complementary formulations.Furthermore, the complementary formulations generally comes in two fla-vors: acceleration-based formulations and velocity-based formulations. Oneof the major flaws of the acceleration-based formulations is that they cannothandle collisions, and thus has to stop at the point of collision and switch toa impulse-momentum law [13]. Additionally, the acceleration-based formula-tions are known to suffer from both indeterminacy as well as inconsistency.Hence, in this thesis we will make use of velocity-based formulations sincethese suffers from none of the drawbacks mentioned above.

A significant advantage of constraint-based methods compared to impulse-based methods is the ability to handle contact areas over time, where bodiesare stacked together or resting on each other. Compared to penalty-basedmethods, the constraint-based does not require any parameter tuning in orderto produce an accurate collision response, since the exact force needed toavoid penetration is computed in each time-step.

We start by formulating a scalar function g(pA,pB) for position-based non-penetration constraints as:

g(pA,pB) = nT (pA − pB) ≥ 0 (4.1)

24

Page 32: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 4. Collision response

where pA and pB are the collision points on bodies A and B, respectively, andn is the collision normal. These position-based constraints are then trans-formed into velocity-based constraints, as proposed by Otaduy et al. [21],which yields a set of algebraic inequalities g(p) ≥ 0 approximating the validconfiguration space. The velocity constraints are then formulated as:

Jv ≥ −1

∆tg0 (4.2)

where the Jacobian J = ∂g

∂p

∂p

∂vconsists of the time derivatives of the posi-

tion constraints in the simulation, formulated as in Eq. 4.1, v is the velocityvector, ∆t is the simulation time-step and g0 is the vector of position con-straints. The full derivation of the Jacobian J along with a few examples fordifferent scenarios are provided in Sec. 4.1.3.

4.1.1 Mixed linear complementary problem

Once the velocity-based constraints are defined, we model the collision re-sponse fc using the method of Lagrange multipliers as:

fc = JTλ (4.3)

where λ is the vector of Lagrange multipliers and J is once again the Jacobianmatrix of the constraints. Additionally, we utilize Signorini’s contact model,as in [12], which imposes the following conditions:

λ ≥ 0: enforces non-sticking constraints on the contact forces, meaningthey can push, but not pull.

0 ≤ λ ⊥ g(p) ≥ 0: states that contact points cannot push 0 ≤ λ and bedistant g(p) ≥ 0 at the same time.

In order for the constraints to affect the velocity computation, we add theconstraint forces in Eq. 4.3 to Eq. 2.4:

Av = JTλ+ b,

0 ≤ λ ⊥ Jv ≥ −1

∆tg0

(4.4)

25

Page 33: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 4. Collision response

The resulting system of equations is a mixed linear complementary problem,MLCP in short, called mixed since both linear equalities and inequalities arecombined.

4.1.2 Constraint anticipation

Constraint anticipation (CA), first proposed by Baraff [5], is used to convertthe MLCP in Eq. 4.4 into a regular linear complementary problem (LCP)by Schur-complement computation. Singling out v in the equality of Eq. 4.4and substituting in the inequality of Eq. 4.4, which gives us:

0 ≤ λ ⊥ Bλ ≥ c,

with B = JA−1JT the Schur-complement of A

and c = −1

∆tg0 − JA−1b

(4.5)

Baraff [5] named the method constraint anticipation since the computation ofA−1J is equivalent to solving for the independent collision response producedby a unit force applied to each constraint. We observe this more clearly byexpressing the final velocity vector v as:

v = v∗ +∆v (4.6)

where v∗ is the unconstrained velocity obtained by solving Eq. 2.4 and ∆vis the collision response velocity. This allows us to form an MLCP for thecollision response only:

A∆v = JTλ,

0 ≤ λ ⊥ J∆v ≥ −1

∆tg0 − Jv∗

(4.7)

Then the collision response ∆v is computed as:

∆v = A−1JTλ (4.8)

where A−1JT can also be expressed as A−1JT I. The multiplication by theidentity matrix I can be viewed as the successive multiplication of A−1JT

26

Page 34: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 4. Collision response

by each column of I, see [16]. Thus, the i :th column of I corresponds to aunitary force applied on the i :th collision point.

The LCP in Eq. 4.5 can be solved using any LCP solver, obtaining the vectorof Lagrange multipliers λ. In this thesis the Projected Gauss-Seidel (PGS)solver is used, which will be covered in more detail in Sec. 4.2.

The constraint anticipation method allows for real-time simulation of rigidbody contacts, since a rigid body only simulates 6 DoF (translation and rota-tion) for the entire body. Hence the entire system being simulated will consistof 6n DoF, where n is the number of bodies in the simulation. The mainbottleneck of the method is the computation of the inverse system matrixA−1, which for a system with few DoF are not too expensive. However, whendeformable bodies consisting of tetrahedral meshes are introduced into thesystem, the number of DoF grow rapidly. Since a tetrahedral mesh consists ofa set of nodes, often above the thousand mark, with 3 DoF each (translationonly), the number of simulated DoF of a deformable body greatly exceeds thenumber of DoF of a rigid body. Thus the system matrix A will grow rapidlywhen deformable bodies are introduced into the simulation, which will alsoslow down the computation of the inverse A−1 by a significant amount. Eventhough the constraint anticipation method succeeds in simulating deformablebodies, it is most suited for rigid body simulation when the number of DoFare kept within reasonable limits. Regarding the construction of the systemmatrix A, we refer to Sec. 4.1.3 bellow.

4.1.3 Matrix construction

Recall the concept of collision groups, as covered in Sec. 3.2.4, where chainsof bodies in contact are divided into separate groups. Utilizing this conceptwhen solving for the collision response yields significant speed-ups, since thesystem to be solved only need to consider the group of bodies that are cur-rently in contact with each other. In a situation like the one in Figure 4.1(a)we solve the collision response for the collision group G = {A,B,C}. Thus,the system matrix for G is constructed by gathering each individual systemmatrix from bodies A, B and C in the collision group, resulting in a singlelarge matrix according to Figure 4.1(b). Note the significant difference insize between the sub-matrix of the deformable bodies A and B compared tothe rigid body C. Also note the block-wise structure of the resulting sys-tem matrix, which is due to the fact that no external forces act between thebodies in G.

27

Page 35: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 4. Collision response

(a) (b)

Figure 4.1: (a) Collision group/sub-system containing 2 deformable bodies A andB and one rigid body C. mAC and mBC correspond to the number of contactsbetween bodies {A,C} and {B,C}, respectively. (b) System matrix for sub-systemin (a), constructed from system matrices of bodies A, B and C, with nA, nB andnC being the number of DoF for bodies A, B and C, respectively. Blue regionsrepresent non-zero elements while white regions correspond to zeros.

As mentioned previously, the Jacobian J consists of the time derivatives ofthe position constraints acting on the system, where each row is the derivativeof the corresponding constraint. Before deriving the velocity constraints, wefirst express the contact points pA and pB of two bodies A and B as:

pA = xA − rA, pB = xB − rB (4.9)

where xA and xB is the center of mass for bodies A and B, respectively, andrA and rB are the vectors form the center of mass to the contact point of therespective bodies. By utilizing the relation:

a · (b× c) = −b · (a× c) = b · (c× a) (4.10)

we compute the time derivative of the i :th position constraint gi(pA,pB),converting it into a velocity based constraint, as:

28

Page 36: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 4. Collision response

gi,rig(pA,pB) =d

dt

(n · (xA + rA − xB − rB)

)=

= n ·d

dt

((xA + rA − xB − rB)

)+

+ (xA + rA − xB − rB) ·d

dt(n) ≈

≈ n ·( d

dt(xA + rA − xB − rB)

)=

= n · (vA + ωA × rA − vB − ωB × rB) =

= n · vA + n · (ωA × rA)− n · vB − n · (ωB × rB) =

= vA · n+ ωA · (rA × n)− vB · n− ωB · (rB × n) =

=[nT (rA × n)T︸ ︷︷ ︸

JA,i

−nT − (rB × n)T︸ ︷︷ ︸

JB,i

]

vA

ωA

vB

ωB

(4.11)

where n is the collision normal chosen from body B, vA, ωA, vB and ωB

are the linear and angular velocities of bodies A and B respectively, and JA,i

and JB,i are the sub-Jacobians for the i :th constraint acting on bodies A andB. Note that this derivation is for rigid bodies with both linear and angularvelocities. For deformable bodies however, the computation is much simplersince the translation of each individual node controls the global rotation ofthe body. Hence, no explicit angular velocity or rotation is required, whichallows the corresponding constraint for a deformable body to be formulatedas only the collision normal n:

gi,def (pA,pB) =[nT

︸︷︷︸

JA,i

−nT

︸︷︷︸

JB,i

][vA

vB

]

(4.12)

For deformable bodies, the velocity constraint is applied to each node in thetetrahedral mesh that is connected to the collision point. Each affected nodeis also multiplied with its corresponding tetrahedral barycentric weight inorder for the magnitude of the collision response to be correctly distributed.Recalling the contact situation in Figure 4.1(a), the corresponding Jacobianis constructed according to Figure 4.2.

29

Page 37: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 4. Collision response

Figure 4.2: Structure of Jacobian constructed from the contact situation in Fig-ure 4.1(a), where blue regions are non-zero elements corresponding to the timederivative of the position constraints, and white areas are zeros. nA, nB and nC

are the number of DoF for bodies A, B and C respectively, while mAC and mBC

are the number of contacts for contact pairs {A,C} and {B,C}, respectively.

4.1.4 Iterative constraint anticipation

The constraint anticipation method covered above computes Lagrange multi-pliers λ and collision response ∆v in two separate steps. However, Otaduy etal. [21] presents an algorithm called iterative constraint anticipation (ICA),designed to suit deformable bodies, that solves for λ and ∆v in tandem in-stead. The algorithm exploits the base concepts of constraint anticipation,but instead of fully anticipating the effects of the constraints in a single com-putation as in Eq. 4.5, they are anticipated iteratively. That is, given thecollision response ∆v(i−1) from a certain iteration, the MLCP is transformedinto an LCP using constraint anticipation, followed by the computation ofLagrange multipliers λ(i) for a new iteration and then a refinement of thecollision response ∆v(i).

Assuming that the vector of Lagrange multipliers λ(i) are known at thecurrent iteration, we can solve for the collision response ∆v in A∆v = JTλ

through iterative relaxation. In this thesis we use block-Jacobi relaxation asproposed by Otaduy et al. [21]:

DA∆v(i) = (LA +UA)∆v(i− 1) + JTλ(i) (4.13)

where the system matrix A is decomposed into a block diagonal part DA, astrictly lower part LA and a strictly upper part UA, as A = DA−LA−UA.In our implementation A is decomposed into 3× 3 blocks. An illustration ofthe decomposition is provided in Figure 4.3 for further clarity.

30

Page 38: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 4. Collision response

Figure 4.3: Structure of the decomposition of system matrix A = DA − LA −UA

for the same collision group as in Figure 4.1(a). Blue regions are non-zero elementsand white regions corresponds to zeros.

The above formulation allows us to iteratively anticipate the effect of theconstraints. More specific, iterative constraint anticipation allows us to sub-stitute ∆v(i) in the MLCP in Eq. 4.7, thus obtaining an LCP which is usedto solve for λ(i):

0 ≤ λ(i) ⊥ Bλ(i) ≥ c(i),

with B = JDA−1JT ,

and c(i) = −1

∆tg0 − Jv∗ − JDA

−1(LA +UA)∆v(i− 1)

(4.14)

We can immediately notice two major advantages of ICA compared to thefull CA in Sec. 4.1.2. First of all, the matrix B of the LCP requires theinversion of the sparse block diagonal matrix DA, opposed to inverting theentire dense system matrixA as in CA. Resulting in a significant performanceboost since the non-zero 3×3 blocks ofDA are treated as sub-matrices, whichare individually inverted and then assembled into the complete inverseDA

−1.The second advantage is that B is very sparse, not dense as in CA, since off-diagonal terms are non-zero only if two constraints affect the same simulationnode [21]. Also note that B only needs to be computed once per simulationstep.

ICA consists of two nested problems; an outer problem, being the iterativerelaxation of ∆v, and an inner problem, being the sparse LCP for comput-ing λ. The inner problem (the LCP in Eq. 4.14) is solved using projectedGauss-Seidel relaxation [11]. Denoting the current iteration of the outer andinner problems as i and j, respectively, then the j:th iteration is formulatedas:

0 ≤ λ(i, j) ⊥ (DB − LB)λ(i, j) ≥ c(i) +UBλ(i, j − 1) (4.15)

31

Page 39: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 4. Collision response

where B is decomposed, similar to the system matrix A, as B = DB−LB−UB, where DB is diagonal, DL is strictly lower triangular and DU is strictlyupper triangular. Note that the diagonal of this decomposition consists of1× 1 blocks, apart from the 3× 3 structure of DA.

Once the inner problem has converged and the Lagrange multipliers λ arecomputed, the outer problem, that is the refinement of the collision response∆v, has to be resolved. As proposed by Otaduy et al. [21], we use oneiteration of block-Gauss-Seidel:

(DA − LA)∆v(i) = UA∆v(i− 1) + JTλ(i) (4.16)

Note that block-Gauss-Seidel is used for refining the collision response whileblock-Jacobi is used to iteratively anticipate the constraints as in Eq. 4.13.The result of this mismatch is that the Lagrange multipliers λ(i) at thei:th iteration does not guarantee that constraints are resolved for the refinedcollision response ∆v(i). However, constraints are resolved once the nestedrelaxation converges. As proposed in [21], the inner loop is terminated oncethe residual of the complementary conditions in the non-penetration LCP inEq. 4.14 change less than 5%. Similarly, the outer loop is terminated whenthe residual of the collision response A∆v(i) − JTλ(i) change less than 5%between two iterations.

4.2 Projected Gauss-Seidel (PGS)

The projected Gauss-Seidel solver used for solving LCPs in this project isbased on the iterative Gauss-Seidel method for solving systems of n linearequations with unknown x:

Ax = b (4.17)

The left-hand side matrix A is first decomposed into a lower triangular anda strictly upper triangular component A = L+U:

L =

a11 0 · · · 0a21 a2,2 · · · 0...

.... . .

...an1 an2 · · · ann

, U =

0 a12 · · · a1n0 0 · · · a2n...

.... . .

...0 0 · · · 0

(4.18)

32

Page 40: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 4. Collision response

which allows us to express the system of linear equations in Eq. 4.17 as:

Lx = b−Ux (4.19)

The method solves for x in the left hand side of the above expression by usingprevious values of x on the right hand side, which is analytically writtenas:

x(k+1) = L−1(b−Ux(k)) (4.20)

where the superscript k denotes the k:th iteration or approximation of x. Byexploiting the triangular form of L, the elements of x(k+1) is then computedsequentially using forward substitution:

x(k+1)i =

1

aii

(

bi −i−1∑

j=1

aijx(k+1)j

n∑

j=i+1

aijx(k)j

)

, i = 1, 2, ..., n (4.21)

After each iteration, newly computed values x(k+1)i that violates a defined

lower xmin or upper xmax limit are projected back onto the allowed inter-val:

x(k+1)i = max(min(x

(k+1)i , xmax), xmin) (4.22)

As mentioned previously, this iterative method for solving LCPs is termi-nated when the residual between two iterations are bellow some specifiedtolerance. The residual r is computed as the amount of which x(k) fails tosatisfy the original problem Ax = b:

r = ||b−Ax(k)|| (4.23)

33

Page 41: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 5

Implementation

Given the methods and theories from previous chapters, we will now covertheir actual implementation. The algorithms for collision detection and col-lision response covered in chapters 3 and 4, respectively, were implementedin an extendable collision framework exposed to users via the Maya C++API.

5.1 Collision framework

The collision framework named MpcVegaFramework is structured accordingto the Model-View-Controller (MVC) design pattern, which consists of 3major components:

• Model: Manages the data, logic and rules of the application or system.

• View: Any visual output of the information or data in the model.

• Controller: Accepts inputs which might change the model or the view.

Applying this to our application, the main collision framework componentacts as the model, as it holds all the information in the simulation world. Theviewer is represented by a separate class that renders information needed fordebugging, such as bounding boxes, collision points, normals etc., along withthe Maya viewport which renders the bodies in the simulated scene. Finally,the input from the Maya UI acts as the controller since it is allowed to changeand manipulate the bodies in the simulated scene as well as some parametersof the simulation.

34

Page 42: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 5. Implementation

Figure 5.1: Interaction between components of the MVC design pattern in ourimplementation.

Each simulated body is stored as an mvBody that derives into either mvRigidBodyor mvDeformableBody which handles rigid and deformable body dynamics,respectively. Additionally, the base class holds a mvCollisionGeometry inwhich the actual geometry, i.e. the surface mesh, is stored by the in-houseMPC-library Muggins. We provide our own solver for rigid body dynam-ics, while deformable body dynamics for volumetric tetrahedral meshes arehandled by the open source solver Vega FEM, which is integrated into themvDeformableBody class. Vega also allows us to extract the necessary infor-mation required for computing the collision response, as e.g. system matrixA, velocity vector v, tetrahedral barycentric weights etc. Apart from juststoring geometries, Muggins also provides a bridge between Maya and itsinternal format, allowing us to easily extract the geometry mesh for rigidbodies directly from the Maya scene. Deformable bodies however, requireslightly more work since Vega is involved. The required data is specified ina configuration file that is passed to the framework from the Maya scripteditor. The vital parts of the configuration file are the surface and the volu-metric tetrahedral mesh, along with material parameters such as the Youngmodulus and Poisson’s ratio. We read the surface mesh in standard fashionby extracting the required information from an .obj-file which is then passedto Muggins, while the volumetric file is read internally by Vega.

The heart of the simulation is the mvSolver, which, given a vector of bodies,performs the actual simulation loop. It also holds the two main componentsfor this thesis, being the mvCollisionDetector and the mvCollisionSolverwhich handles collision detection and collision response, respectively. ThemvCollisionDetector also stores one instance each of mvBroadPhaseCD andmvNarrowPhaseCD, which performs the broad and narrow phase collision de-tection. Both of these classes may further be derived with classes for different

35

Page 43: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 5. Implementation

collision detection algorithms. At this moment, however, we only providethe sweep and prune and optimized spatial hashing algorithms for collisiondetection as covered in Sec. 3.1.1 and 3.2.2, respectively. Note that addi-tional collision detection algorithms added to the framework must still followthe structure of which data is transferred between each component. ThemvBroadPhaseCD object is handed the vector of bodies that is being simu-lated and returns pairs of possible collisions between bodies. These pairsare then passed to the mvNarrowPhaseCD which computes actual collisionsas described in Sec. 3.2.1. Further, the mvCollisionSolver is responsi-ble for both solving and applying the collision response. This class mayalso be inherited from, making it possible to add alternative algorithms forsolving the collision response if desired. Currently we provide a base classmvConstraintAnticipation that derives into classes which implements boththe full constraint anticipation as well as the iterative constraint anticipationalgorithms. For clarity, an illustration of the class structure is provided inFigure 5.2. Additionally, we provide a utility class mvUtils where we gathere.g. the PGS LCP-solver, the reader for .obj-files etc.

(a) (b)

Figure 5.2: Class structure of (a) the collision detector and (b) the collisionsolver. Additional classes with implementations for collision detection or colli-sion response methods might be added by inheritance from mvNarrowPhaseCD ormvCollisionSolver, respectively.

36

Page 44: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 5. Implementation

5.2 Maya Plugin

As MPC uses Maya for rigging and animation of characters, the collisionframework is exposed to users as a Maya plugin. The framework node iscreated by a simple MEL-command, which then allows the bodies that is to besimulated to be added to the collision framework. Thus, getting a simulationrunning is very straight forward. Since discrete collision detection is used atthis time, it makes the simulation very sensitive to the size of the time stepwhich might need to be set differently depending on the setup. Hence, we givethe user the option to add a desired number of sub steps to the simulation.Additionally, control is given over the desired collision response method,being the full or iterative approaches of CA. We also provide the option ofusing self collisions or not, since self collisions for deformable bodies withdense meshes might slow down the simulation considerably. Since it mightalso be desired to fix some parts of a deformable body in certain situations,we provide the ability to add hard constraints by simply selecting a set ofvertices with the selection tool built into Maya. This allows the simulationto ignore the selected set of nodes, which also makes the computation timelower.

37

Page 45: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 6

Discussion

We described the full derivations and implementation behind an extendablecollision framework handling both rigid and deformable bodies, targeted to-wards muscle and facial simulations for the next generation of digital char-acters at MPC. Proven methods for both collision detection and collisionresponse were used, providing significant accuracy advantages compared toother methods currently implemented in MPC’s pipeline. Here we summarizeand discuss the results of the work.

6.1 Results

This section presents and discusses the results of the project with focus onthe positive aspects, in form of performance graphs and snapshots from Mayawith the framework in action.

6.1.1 Visual results

The framework produce an appealing visual appearance for collisions betweenall possible combinations of rigid and deformable bodies. In terms of accu-racy, interpenetration is avoided in the vast majority of the cases with onlyslight penetration appearing at high velocity collisions. Even then its hardto spot at first sight, and is only visible at extreme closeups if the simulationis examined step by step instead of in real-time playback. To exemplify, twosnapshots of contact areas produced by deformable bodies in contact, areprovided in Figure 6.1.

Comparing the accuracy to previous implementations that used the penaltybased method for computing the collision response, we can observe quitesignificant improvements. First of all, the penalty-based method producea movement of the deformable surface just before the actual collision oc-curs, since the method might otherwise struggle to solve the collision at allif spring coefficients are not optimized. This might be quite obvious to the

38

Page 46: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 6. Discussion

(a) (b)

Figure 6.1: Example simulation with a deformable dragon, 2 deformable spheresalong with a rigid floor and walls. (a) Contact area between floor and both spheres,and (b) between one sphere and dragon.

viewer in closeup shots, which is another reason why the penalty based ap-proach is better suited for game applications where closeups tend to not beas common. Additionally, contact areas were handled poorly by the previouspenalty-based implementation whereas the constraint-based method usingICA, implemented in our framework, produce a much more pleasing result,as can be seen in Figure 6.2.

(a) (b)

Figure 6.2: Scripted sphere colliding with the surface mesh of a deformable face,seen from the inside. Comparison between (a) the penalty based method fromprevious implementation and (b) the constraint based method using ICA from ourframework. Note that the penalty based method (a) allows deep interpenetrationwhile the constraint based (b) succeeds in producing an area of contact withoutpenetration.

39

Page 47: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 6. Discussion

Additionally, we ran test setups with varying values of Young’s modulus,which essentially controls the stiffness of the material for deformable bodies.This was performed since stiff materials tend to expose possible stabilityissues in the collision solver. However our tests showed no noticeable visualartifacts that would indicate any fatal stability issues.

Figure 6.3: Deformable dragons dropped on static rigid spheres with varyingYoung’s modulus: left 10k, center 100k and right 1M.

6.1.2 Performance

Regarding the performance of our framework, we first examine the narrowphase collision detection part of the simulation loop. The optimized spatialhashing algorithm was compared to the brute force approach for an increasingamount of collisions. According to Figure 6.4 the optimized spatial hashingscales in an almost linear fashion as more collisions are detected, while thebrute force approach computes all possible triangle intersections independentof how many collisions that are actually occurring. However, we should alsonote that an increasing number of collisions might not necessarily mean thatthe optimized spatial hashing performs slower. Instead we would like to pointout that the number of primitives in the scene might have a larger impacton the performance.

For the collision response, we have compared the performance between thefull and iterative approaches of CA. In Figure 6.5 we plot the timings forboth methods gathered form a sequence of the same scene as in Figure 6.1containing a deformable dragon and 2 deformable spheres. From the recordedtimings we see that the iterative approach basically halves the computationtime compared to the full CA. We do however believe that the iterative ap-proach could provide even greater performance gains in situations where the

40

Page 48: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 6. Discussion

Figure 6.4: Comparison of optimized spatial hashing (red) vs the brute force ap-proach (blue) for the narrow phase collision detection, performed on scene contain-ing 2560 triangles.

number of collisions reaches the thousand mark, since such indications areprovided in the work by Otaduy et al. [21]. The noticeable spike around 10collisions in the blue curve in Figure 6.5 is probably caused by a combina-tion of the inversion of A and that the PGS solver might have struggled toconverge when computing Lagrange multipliers λ.

Figure 6.5: Timings for collision response computations for the iterative (red) andfull (blue) CA methods. Results are gathered from the same scene setup as inFigure 6.1, during the first 200 frames of the simulation.

41

Page 49: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 6. Discussion

6.2 Conclusion

The goal of this thesis project was to provide a full software implementationof a collision framework with Vega at its core for deformable body simulation.A chosen set of algorithms were to be implemented with the ability for futureextension of additional methods for both collision detection and collisionresponse. The framework was also supposed to act as a base where developedtechnologies for simulation of the next generation of digital characters wereto be gathered.

The algorithms presented in chapters 3 and 4 were implemented in a frame-work carefully and thoroughly designed to support future extensions. Theframework is exposed to users as a Maya plugin which allows for simulationof static, dynamic and scripted rigid bodies as well as dynamic deformablebodies with fully working collision handling.

The focus of the thesis stayed on track during the entire project, as a veryclear time plan was set, outlaying how the work was to be proceeded fromstart to finish. The only deviation was the implementation of the iterativeCA, since everything additional to the sweep and prune, optimized spatialhashing and full CA algorithms was considered as a bonus. Thus, no majorproblems or setbacks were encountered during the project that affected thework in a negative way.

6.3 Future work

While the thesis fulfills the goals, it still reveals numerous possible improve-ments and extensions. A few of the most significant ones are presentedhere.

6.3.1 Alternative integration schemes

In the current implementation we only provide the semi-implicit backwardEuler integration scheme, which works well in practice. It would howeverbe nice to provide a larger set of numerical integration schemes such as e.g.the full implicit Euler and implicit Newmark, as it would be interesting tocompare their performance from both a stability and computational costpoint of view. An extended set of solvers would also add to the completeness

42

Page 50: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 6. Discussion

of the framework, allowing the user to choose the one most suited for thecurrent simulation.

6.3.2 Additional algorithms

In addition to the algorithms currently implemented for collision detectionand collision response it would add flexibility and completeness if more algo-rithms were available for the user. We believe that the approach of boundingvolume hierarchies, covered briefly in Sec. 2.2.1, is particularly interestingand could perform similar to optimized spatial hashing. The constraint-based method used for collision response was picked mainly for stability andaccuracy reasons. However, a good implementation of the penalty-basedmethod could still add some value to the framework if fast results are prior-itized over accuracy, e.g. when running tests for deciding on the scene setupor similar.

6.3.3 Continuous collision detection

At this point we use discrete collision detection and add a significant amountof sub steps to the simulation in order to guarantee stability at high velocityimpacts with stiff materials. This approach is however far from optimal, sincethe discrete collision detection also require us to approximate the actualcollision points, as covered in Sec. 3.2.3. This problem would be entirelyeliminated by continuous collision detection since collision points are insteadsampled at the exact time of impact, allowing us to decrease or even removethe sub steps form the simulation. Even though continuous collision detectionis considered much slower than the discrete approach, the removal of sub stepswould probably counteract the initial performance loss and thus make thefinal computational cost rather similar.

6.3.4 Friction

Due to time restrictions we did make an active choice of ignoring frictionfor this thesis. We do however believe that the addition of this vital com-ponent should be on top of the to-do list, since it is obviously very impor-tant for visual appearance of the simulation in case of sliding situations. Itwould also help bodies to reach a steady rest state in case of heavy stacking,

43

Page 51: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Chapter 6. Discussion

were infinite slow rotations are now occasionally apparent. The implemen-tation should however be straight forward since Otaduy et al. [21] alreadypresents the required mathematics in order to add friction to the iterativeCA method.

6.3.5 Additional constraints and simulated bodies

Since the base for constrained dynamics is already implemented, the frame-work could also be extended to include different type of constraints, as e.g.sliding constraints, in addition to the non-penetration counterpart that iscurrently implemented. This would be particularly useful for the muscle sys-tem currently being developed, where fat and skin layers are sliding on topof the muscles.

At the moment the framework supports rigid bodies and deformable bodiesconsisting of volumetric tetrahedral meshes. However, since Vega providessolvers for mass-spring systems, the addition of cloth simulation to the frame-work is a possible future extension. Furthermore, both full and iterative CAis based on a system formulation of the type Av = b, which along withan implicit integration scheme allows for addition of e.g. hair simulation aswell.

44

Page 52: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Bibliography

[1] William W Armstrong and Mark W Green. The dynamics of articulated rigidbodies for purposes of animation. The Visual Computer, 1(4):231–240, 1985.

[2] Didier Badouel. Graphics gems. chapter An Efficient Ray-polygon Intersec-tion, pages 390–393. Academic Press Professional, Inc., San Diego, CA, USA,1990.

[3] David Baraff. Dynamic Simulation of Non-Penetrating Rigid Bodies. PhDthesis, Cornell University, Ithaca, NY, USA, 3 1992.

[4] David Baraff. Fast contact force computation for nonpenetrating rigid bodies.In Proceedings of the 21st Annual Conference on Computer Graphics and

Interactive Techniques, SIGGRAPH ’94, pages 23–34, New York, NY, USA,1994. ACM.

[5] David Baraff. Linear-time dynamics using lagrange multipliers. In Proceedings

of the 23rd Annual Conference on Computer Graphics and Interactive Tech-

niques, SIGGRAPH ’96, pages 137–146, New York, NY, USA, 1996. ACM.

[6] David Baraff. An Introduction to Physically Based Modeling: Rigid BodySimulation II — Nonpenetration Constraints, 1997. SIGGRAPH course notes.

[7] Jernej Barbic, Fun Shing Sin, and Daniel Schroeder. Vega FEM Library,2012. http://www.jernejbarbic.com/vega.

[8] Daniel Chappuis. Constraints derivation for rigid body simulation in 3d, 112013.

[9] Michael Bradley Cline. Rigid body simulation with contact and constraints.Diploma thesis, The University of British Columbia, 07 2002.

[10] Thomas H. Cormen, Clifford Stein, Ronald L. Rivest, and Charles E. Leiser-son. Introduction to Algorithms. McGraw-Hill Higher Education, 2nd edition,2001.

[11] Pang Jong-Shi Stone Richard E. Cottle, Richard W. The Linear Complemen-

tarity Problem. Academic Press, San Diego, CA, USA, 1992.

[12] Christian Duriez, Frederic Dubois, Abderrahmane Kheddar, and Claude An-driot. Realistic haptic rendering of interacting deformable objects in virtualenvironments. IEEE Transactions on Visualization and Computer Graphics,12(1):36–47, January 2006.

[13] Kenny Erleben. Velocity-based shock propagation for multibody dynamicsanimation. ACM Trans. Graph., 26(2), June 2007.

45

Page 53: Rasmus Haapaoja - liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:1056414/FULLTEXT01.pdf · Rasmus Haapaoja Handledare Andrew Gardner Examinator Jonas Unger Norrköping 2016-11-02

Bibliography

[14] Kenny Erleben, Jon Sporring, Knud Henriksen, and Henrik Dohlmann.Physics-Based Animation. Charles River Media, Inc, 2005.

[15] Roy Featherstone. Robot Dynamics Algorithm. Kluwer Academic Publishers,Norwell, MA, USA, 1987.

[16] Eder Miguel. Methods for handling contact between rigid and deformableobjects. Diploma thesis, Universidad Rey Juan Carlos, 05 2010.

[17] Brian Mirtich and John Canny. Impulse-based simulation of rigid bodies.In Proceedings of the 1995 Symposium on Interactive 3D Graphics, I3D ’95,pages 181–ff., New York, NY, USA, 1995. ACM.

[18] Tomas Moller and Ben Trumbore. Fast, minimum storage ray-triangle inter-section. J. Graph. Tools, 2(1):21–28, October 1997.

[19] Matthew Moore and Jane Wilhelms. Collision detection and response forcomputer animation. In Proceedings of the 15th Annual Conference on Com-

puter Graphics and Interactive Techniques, SIGGRAPH ’88, pages 289–298,New York, NY, USA, 1988. ACM.

[20] Ken Museth. Vdb: High-resolution sparse volumes with dynamic topology.ACM Trans. Graph., 32(3):27:1–27:22, July 2013.

[21] Miguel A. Otaduy, Rasmus Tamstorf, Denis Steinemann, and Markus Gross.Implicit contact handling for deformable objects. In Computer Graphics Fo-

rum, volume 28(2), pages 559–568, 2009.

[22] Matthias Teschner, Bruno Heidelberger, Matthias Mueller, Danat Pomer-anets, and Markus Gross. Optimized spatial hashing for collision detection ofdeformable objects. In Proc. of Vision, Modeling and Visualization, 2003.

[23] Magnus Wrenninge. Production Volume Rendering: Design and Implementa-

tion. Taylor & Francis Inc, 2012.

46