Top Banner

of 81

IntroductionToSoftBodyPhysics-Skeel

Apr 03, 2018

Download

Documents

bobbob24
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    1/81

    Introduction toSoft Body Physics

    SkeelKeng-SiangLee

    [email protected]

    http://cg.skeelogy.com

    mailto:[email protected]://cg.skeelogy.com/http://cg.skeelogy.com/http://cg.skeelogy.com/mailto:[email protected]
  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    2/81

    i

    Contents

    Introduction........................................................................................................................................

    1

    BaseCodes.......................................................................................................................................... 4

    Chapter1 SpringSimulation.............................................................................................................. 7

    1.1PhysicsSimulationAlgorithm............................................................................................................ 8

    1.2SimulationObjectClasses................................................................................................................. 9

    1.2.1SimObjectAbstractClass............................................................................................................ 9

    1.2.2SimModel

    ..................................................................................................................................

    12

    1.3ForceGeneratorClasses.................................................................................................................. 13

    1.3.1ForceGeneratorInterface......................................................................................................... 13

    1.3.2Gravity...................................................................................................................................... 14

    1.3.3Medium.................................................................................................................................... 15

    1.3.4Spring........................................................................................................................................ 17

    1.4IntegratorClasses............................................................................................................................ 21

    1.4.1IntegratorAbstractClass.......................................................................................................... 21

    1.4.2ForwardEulerIntegrator.......................................................................................................... 23

    1.5SimulationClass............................................................................................................................... 24

    1.6UsingTheNewClassesToCreateASpringSimulation................................................................... 28

    Chapter

    2

    Cloth

    Simulation

    .............................................................................................................

    34

    2.1Constraints...................................................................................................................................... 35

    2.1.1ConstraintInterface.................................................................................................................. 36

    2.1.2LengthConstraint..................................................................................................................... 37

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    3/81

    ii

    2.1.3PointConstraint........................................................................................................................ 39

    2.1.4ProcessingTheConstraintsInTheSimulationClass................................................................ 40

    2.2Verlet(NoVelocity)Integrator........................................................................................................ 42

    2.3SimulationVertex............................................................................................................................ 44

    2.4SoftBodyandClothSimulationClasses.......................................................................................... 45

    2.5UsingTheNewClassesToCreateAClothSimulation.................................................................... 53

    Chapter3 GoalSoftBodies:SlinkySimulation................................................................................. 59

    3.1GoalSoftBodySimulationClass...................................................................................................... 60

    3.2CreatingAGoalSoftBody............................................................................................................... 63

    Chapter4FakingRigidBodies:ChainSimulation............................................................................ 70

    4.1ChainSimulationClass.................................................................................................................... 70

    4.2CreatingAChainSimulation............................................................................................................ 73

    Conclusion........................................................................................................................................ 77

    References........................................................................................................................................ 78

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    4/81

    Introduction

    Inrecentyears,therehasbeenahighproliferationintheusageofphysicssimulationsingames.This

    might

    be

    due

    to

    the

    increasing

    need

    for

    realistic

    movements

    of

    the

    objects

    to

    match

    their

    realistic

    renderings.Someofthesephysicssimulationsincluderigidbodysimulationswheretheobjectsmove

    androtatebutdonotchangetheirshapes,andragdollphysicswherethemotionofacharactercanbe

    simulatedunderforceperturbations. Therehashowevernotbeenalotofsoftbodyphysicsingames

    yet, thus itmight beworthwhile to start diving into this type of simulation so that you can start

    implementingsomesoftbodiesforyourgame.

    Asoftbody isbasicallyanobjectwhichchanges itsoverallshapeduetoexternal forcesactingon it.

    Someexamplesthatwecommonlyseeincludecloth,balloonsandjelly.Aclothdrapesdownwardsdue

    togravitationalforcesandfluttersduetowindforces.Similarly,aballoonenlargeswhentheinternal

    pressureforces

    increase,

    and

    produces

    indentations

    when

    achild

    exerts

    forces

    on

    it

    by

    squeezing.

    Thesekindofnaturalbehaviorsareinterestingtoobserve,especiallyinagameenvironmentwherethe

    entertainmentvalueisofhighimportance.

    This tutorial has been written to help you get a quick understanding of some basic theories and

    implementationsbehindsimulatingsoftbodies inrealtime. It ismeantforbeginnersaswewillstart

    fromtheverybasics. Inanefforttoshowtheusefulnessofsoftbodyphysics,someoftheexamples

    giveninthistutorialalsoillustratehowitcanbeusedasaquicksubstitutionforcaseswhereusingrigid

    bodysimulationwillprovetobemuchmoreexpensive.

    Thereare

    four

    major

    chapters

    in

    this

    tutorial

    and

    we

    will

    be

    creating

    adifferent

    soft

    body

    simulation

    foreachofthem.Thistutorialprogressivelybuildsanobjectorientedsoftbodyphysicssystem,thus

    wewillbeheavilyreusingandinheritingfromthecodeswritteninearlierchapters.Itassumesthatyou

    haveabasicunderstandingofobjectorientedprogramming.

    This tutorialprimarily targetsusersofMicrosoftXNA3.0but the ideasandalgorithmscaneasilybe

    implementedusingotherlanguagesandAPIsonceyouunderstandthem.

    Bytheendofthiswholetutorial,youwillbeabletocreatethesesimulations:

    1

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    5/81

    Video1:Aninteractiveclothsimulation[Clickonimageabovetowatchthevideo]

    Video2:

    An

    interactive

    slinky

    simulation

    (created

    using

    a

    goal

    based

    soft

    body)

    [Clickonimageabovetowatchthevideo]

    2

    http://www.youtube.com/watch?v=_yR_Tiqze2Ehttp://www.youtube.com/watch?v=JncQOCg9FS0
  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    6/81

    Video3:Aninteractivechainsimulation(createdusingspringsandlengthconstraints)[Clickonimageabovetowatchthevideo]

    3

    http://www.youtube.com/watch?v=XNyO0XXhh_o
  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    7/81

    BaseCodes

    Ihave includedsomebasicgamecomponentsandclasses intheprojectfilesofeachchaptersothat

    certainbasictaskscanbeperformedeasily.Someofthethingsthatthesegamecomponentscando

    include:

    i) LoadinganddrawingamodelfromfilebycallingLoadModel ( t heFi l eName) ii) TransformingofamodelinthescenebysettingtheTr ansl at e,RotateandScal epropertiesiii) CreatingofacamerabycreatingaCamer aComponent andaddingittogame. Component siv) Detecting if a key is held down, just pressed or just released by calling the methods

    I sKeyHel dDown( ) ,I sKeyJ ust Down() ,I sKeyJ ust Up( ) respectively

    v) Creatinga3DlinebyjustcreatingaLi ne3DComponent ,addingittogame. Component s andthensettingtheSt art Pos i t i on,EndPosi t i onandCol or properties

    These base codes basically encapsulates some of the basic operations in XNA. They aremeant to

    improvetheclarityofthesoftbodysimulation implementations,whichwillotherwisebeaffectedby

    unnecessarycodesthatarethereto loadmodels,drawprimitives,detect ifakey isjustpressedetc.

    TheseclassesareprettymuchthebasicsofXNA,soifyouknowyourXNAwellenough,itshouldnotbe

    toohardtounderstandwhatiswrittenintherewithoutmeexplainingthem.

    Touse thebasecodes,youjustneed tocreateanew instanceofeachof thecomponentsandadd

    themtothet hi s. Componentslistinyourgame.ThishasbeendoneforyouinGame1.csineachofthe

    chapterfiles.

    ( Game1. cs, addi t i on of codes i n bol d)

    usi ng Mi cr osof t . Xna. Framework;usi ng Mi cr osof t . Xna. Framework. Gr aphi cs;usi ng Mi cr osof t . Xna. Framework. I nput ;usi ng Skeel Sof t BodyPhysi csTut ori al . Mai n;

    namespace Skeel Sof t BodyPhysi csTut or i al{

    publ i c c l ass Game1 : Mi cr osof t . Xna. Framework. Game{

    Gr aphi csDevi ceManager gr aphi cs;Spr i t eBat ch spr i t eBat ch;

    4

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    8/81

    / / component member sCamer aComponent camer aComponent ;I nputComponent i nput Component ;Model Component model Component ;Li ne3DComponent l i ne3DComponent ;

    publ i c Game1( ){gr aphi cs = new Gr aphi csDevi ceManager ( t hi s) ;Cont ent . Root Di r ect or y = "Cont ent " ;

    / / i nst ant i ate t he component s and add t hemt o t hi s. Component sVect or3 cameraPosi t i on = new Vect or3( 0, 10, 10) ;Vect or3 t ar get Posi t i on = Vect or3. Zer o;Vect or3 upVect or = Vect or3. Uni t Y;st r i ng backgr oundI mage = "" ;camer aComponent = new Camer aComponent ( t hi s, camer aPosi t i on,

    t arget Posi t i on, upVect or, backgr oundI mage) ;t hi s. Component s. Add(camer aComponent ) ;

    bool showMouse = f al se;i nput Component = new I nputComponent ( t hi s, showMouse) ;t hi s. Components. Add( i nputComponent ) ;

    model Component = new Model Component ( t hi s) ;t hi s. Components. Add( model Component) ;

    l i ne3DComponent = new Li ne3DComponent ( t hi s) ;t hi s. Components. Add( l i ne3DComponent ) ;

    }

    pr ot ect ed over r i de voi d I ni t i al i ze( ){

    base. I ni t i al i ze( ) ;}

    pr ot ect ed over r i de voi d LoadCont ent ( ){

    spr i t eBat ch = new Spr i t eBat ch( Gr aphi csDevi ce) ;}

    pr ot ect ed over r i de voi d Unl oadCont ent ( ){

    }

    pr ot ect ed over r i de voi d Updat e( GameTi me gameTi me){

    base. Updat e( gameTi me) ;}

    pr ot ect ed over r i de voi d Dr aw( GameTi me gameTi me){

    Gr aphi csDevi ce. Cl ear ( Col or. Cor nf l ower Bl ue) ;base. Dr aw( gameTi me) ;

    5

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    9/81

    }}

    }

    Therestofthecodesabovearejustthestandardtemplatecodesthatareprovidedwhenyoucreatea

    newprojectinXNAGameStudio,withthecommentsremoved.

    6

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    10/81

    Chapter1 - SpringSimulation

    GetthesourcefilesforthestartofthischapterfromtheSkeelSoftBodyPhysicsTutorialChapter1BEGINfolder

    Wewill

    start

    off

    the

    tutorial

    by

    implementing

    asimple

    spring

    simulation

    where

    two

    objects

    are

    attachedviaaspring.By learninghowtocreateaspringsimulation,youwillgainenoughknowledge

    onhow toperformsoftbodysimulations ingames.Thissimplesimulationwillthusprepareyou for

    morecomplicatedsoftbodysimulationsinlaterchapters.

    Bytheendofthischapter,youshouldhaveasimplespringsimulationlikethis:

    Video4: Asimplespringsimulationbetweentwoobjects[Clickonimageabovetowatchthevideo]

    Itdoesnotlookparticularlyimpressivebecauseitisjustabasictestofhowtocreateaspringandrun

    the simulation. However, do not get too worried about it as we will create much betterlooking

    simulationsin

    later

    chapters.

    7

    http://www.youtube.com/watch?v=GBvH4nvYBg8
  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    11/81

    1.1PhysicsSimulationAlgorithmToimplementanyphysicssimulationingames,weneedtodothesesteps(inorder):

    i)Sum

    up

    all

    forces

    acting

    on

    a

    body/vertex

    to

    get

    the

    resultant

    force

    ii) Findaccelerationbydividingtheresultantforcebytheobjectmass:a=f/m(NewtonsSecondLawforaconstantmass)

    iii) Performnumericalintegrationontheaccelerationtogetvelocity/positioniv) Updatethebody/vertexwiththenewvelocity/position,andrepeatfrom(i)

    Ateach time step,wegetanewposition for the simulatedobject,basedonall the forces thatare

    actingon it.Asweupdate theobjectwith thisnewposition,wewillobserve itsmotionunder the

    simulation.

    Wewillcovermorealgorithmsandformulasaswemovealongwiththeimplementation,particularly

    onhowthedifferenttypesofforcesarecalculatedandhowtoperformthenumericalintegration.

    Inorder to implement thissimulationsystem, thereare fourmaingroupsofclasses thatwewillbe

    creating:

    Simulationobjects:Thesepackanobject(canbeamodel,vertex,triangleetc)togetherwithitssimulation

    attributes

    such

    as

    position,

    velocity

    and

    mass

    into

    one.

    Forcegenerators:Theserepresentthingsthatcangenerateforces,suchasaspringorgravity. Integrators: These perform numerical integration using the acceleration to find the new

    position/velocity,andupdatesthecorrespondingattributesinthegivensimulationobject.

    Simulations:Thesearethemainclassesthatwillmanagethewholesimulationalgorithm.Thetasksthattheywilldoincludeinitializingallthevariables,connectingthespringsandupdating

    thesimulations.

    8

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    12/81

    1.2SimulationObjectClassesRecallthatweneedtokeeptrackofthepositionandpossiblythevelocityof theobjectundergoing

    simulation. It will be convenient if we pack the simulated object together with these simulation

    attributes.Thus,

    let

    us

    first

    start

    with

    the

    simulation

    object

    classes.

    1.2.1SimObjectAbstractClass

    WefirstcreateanabstractclasscalledSi mObj ect .Thiswillcontainnecessarymembersandfunctions

    thatwillbeinheritedbyothersimulationobjectclasses.

    UsingtheSolutionExplorer,addanewfoldercalledSimObjects intheexistingSoftBodyfolder.Then

    createanewclassfileandnameitSimObject.cs.

    ( Si mObj ect . cs)

    usi ng Mi cr osof t . Xna. Framework;usi ng Skeel Sof t BodyPhysi csTut ori al . Mai n;

    namespace Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mObj ect s{

    publ i c enum Si mObj ect Type { PASSI VE, ACTI VE }

    publ i c abst r act c l ass Si mObj ect

    { pr i vat e f l oat mass;pr i vat e Si mObj ect Type si mObj ect Type;pr ot ect ed Vect or3 cur r Posi t i on;pr ot ect ed Vect or3 pr evPosi t i on;pr ot ect ed Vect or3 cur r Vel oci t y;

    publ i c f l oat Mass{

    get { return mass ; }set { mass = val ue; }

    }

    publ i c Si mObj ect Type Si mObj ect Type{

    get { return si mObj ectType; }set { si mObj ect Type = val ue; }

    }

    9

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    13/81

    publ i c Vect or3 Cur r Posi t i on{

    get { return cur r Posi t i on; }set { cur r Posi t i on = val ue; }

    }

    publ i c f l oat Cur r Posi t i onX

    { get { return cur r Posi t i on. X; }set { cur r Posi t i on. X = val ue; }

    }

    publ i c f l oat Cur r Posi t i onY{

    get { return curr Pos i t i on. Y; }set { cur r Posi t i on. Y = val ue; }

    }

    publ i c f l oat Cur r Posi t i onZ{

    get { return cur r Posi t i on. Z; }

    set { cur r Posi t i on. Z = val ue; }}

    publ i c Vect or3 Pr evPosi t i on{

    get { return pr evPosi t i on; }set { pr evPosi t i on = val ue; }

    }

    publ i c Vect or3 Cur r Vel oci t y{

    get { return cur r Vel oci t y; }set { cur r Vel oci t y = val ue; }

    }

    / / - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    publ i c Si mObj ect ( f l oat mass, Si mObj ect Type si mObj ect Type){

    t hi s. mass = mass;t hi s. curr Pos i t i on = Vect or3. Zer o;t hi s. pr evPosi t i on = cur r Posi t i on;t hi s. cur r Vel oci t y = Vect or3. Zer o;t hi s. si mObj ect Type = si mObj ect Type;

    }}

    }

    ASi mObj ect hasamassandisofaSi mObj ect Typewhichiseitheractiveorpassive. Activesimulation

    objectshavetheirpositionsandvelocitiesdeterminedbythe forces inthesystem,whilethepassive

    onesdonot. Passive simulationobjects are still consideredpartof the simulation since they allow

    10

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    14/81

    activeobjectstointeractwiththem.Settinganobjecttobepassiveisusefulincaseswhereweneedto

    allowtheusertocontrolitsposition,possiblyusingthemouseorkeyboard.

    In the constructor above, we also initialize the curr Pos i t i on, pr evPosi t i on and cur r Vel oci t y

    variablestothezerovector.

    Recallthat

    we

    have

    to

    sum

    up

    the

    forces

    acting

    on

    this

    simulation

    object.

    It

    will

    be

    convenient

    for

    the

    object itselftostoretheresultantforcesothattheobjectcanbepassedaroundtodifferentclasses

    and the resultant force is still being tracked and stored. Thus we will create a r esul t ant For ce

    variableasaclassmemberintheSi mObj ect .

    ( cl ass member i n Si mObj ect . cs)

    pr ot ect ed Vect or3 r esul t ant For ce;

    publ i c Vect or3 Resul t ant For ce{

    get { return r esul t ant For ce; }set { r esul t ant For ce = val ue; }

    }

    Wewillalsocreateamethodtoresettheresultantforce.Thiswilltypicallybecalledeitherattheend

    oratthebeginningofeachtimestep.

    ( cl ass met hod i n Si mObj ect . cs)

    publ i c voi d ResetFor ces( ){

    t hi s. r esul t ant For ce = Vect or3. Zer o;}

    Finally,anyclassthatinheritstheSi mObj ect classshouldhaveitsownUpdat emethod,sowedefine

    anabstractmethodcalledUpdat etomakeitcompulsoryforderivedclassestoimplementit.

    ( cl ass abst r act met hod i n Si mObj ect . cs)

    publ i c abst r act voi d Updat e( GameTi me gameTi me) ;

    11

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    15/81

    1.2.2SimModel

    Based on the Si mObj ect abstract class,we shall implement our first simulation object class called

    Si mModel .Itismeanttowrapsimulationattributestoamodelthatwewillloadfromfileandupdate

    thepositionofthisloadedmodelateverytimestep.IntheSimObjectsfolder,createanewclassfile

    namedSimModel.cs.

    ( Si mModel . cs)

    usi ng Mi cr osof t . Xna. Framework;usi ng Skeel Sof t BodyPhysi csTut ori al . Mai n;

    namespace Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mObj ect s{

    publ i c seal ed cl ass Si mModel : Si mObj ect{

    pr i vat e GameModel model ;

    publ i c GameModel Model{

    get { return model ; }set { model = val ue; }

    }

    / / - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    publ i c Si mModel ( GameModel model , f l oat mass, Si mObj ect Type si mObj ect Type): base( mass, si mObj ect Type)

    {t hi s. model = model ;

    t hi s. cur r Posi t i on = model . Transl at e;t hi s. pr evPosi t i on = cur r Posi t i on;}

    }}

    Basicallywe pass in a GameModel (oneof the classesprovided in thebase codes), its mass and its

    Si mObj ect TypewhenwecreateaSi mModel instance.Thecur r Posi t i onandpr evPosi t i onvariables

    areupdatedtothecurrentpositionoftheGameModel .

    Sincethe

    Updat emethod

    is

    defined

    as

    abstract

    in

    the

    base

    class,

    we

    will

    have

    to

    implement

    it

    using

    an

    override method. All we have to do for this method is to update the position of the GameModel

    according to the cur r Posi t i on, which will be recalculated at every time step. This basically

    synchronizesthepositionoftheGameModel withthestoredposition.

    12

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    16/81

    ( cl ass method i n Si mModel . cs)

    publ i c over r i de voi d Updat e( GameTi me gameTi me){

    t hi s. model . Transl at e = t hi s. cur rPos i t i on;}

    Thatisallwehavetodoforthisclass,sincetheothernecessaryimplementationsareallinheritedfrom

    thebaseclass.

    1.3ForceGeneratorClassesNow thatwehave the simulationobjectscreated,we can start to implement the forcegenerators.

    Recallfrom

    the

    simulation

    algorithm

    in

    Section

    1.1

    that

    we

    need

    to

    sum

    up

    the

    forces

    that

    are

    acting

    onabodyateverytimestep.Theseforceswillcomefromtheforcegeneratorclassesthatwewillbe

    implementingnow.

    1.3.1ForceGeneratorInterface

    WeshallstartoffbycreatingaForceGenerat or interfaceandmakeitcompulsoryforderivedclasses

    toimplementamethodAppl yFor ce.

    Createanew

    folder

    called

    ForceGenerators

    in

    the

    SoftBody

    folder,

    and

    create

    anew

    class

    file

    named

    ForceGenerator.csinthenewfolder.

    ( For ceGenerat or. cs)

    usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mObj ect s;

    namespace Skeel Sof t BodyPhysi csTut ori al . Sof t Body. For ceGener at or s{

    publ i c i nt erf ace ForceGenerat or{

    voi d Appl yFor ce(Si mObj ect si mObj ect ) ;}

    }

    13

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    17/81

    WhatweareexpectingthederivedclassestodowhenimplementingtheAppl yFor cemethodistouse

    thepropertiesoftheSi mObj ect (suchasmass,position,velocityetc)tocalculateanappropriateforce

    andaddthattoitsResul t ant For ceproperty.

    1.3.2Gravity

    Letusproceedon tocreateour firstandsimplest forcegenerator:gravity. Toget thegravitational

    forceactingonanobject,weneedtwopiecesof information,namelythemassofthebodyandthe

    gravitationalaccelerationthatitisexperiencing.Thegravitationalforcecanthensimplybefoundas

    gravitationalforce=mass*gravitationalacceleration [1]

    Now,addanewclassfilenamedGravity.csintheForceGeneratorsfolderandcreateaGr avi t yclass

    whichinheritsfromtheForceGenerat or interface:

    ( Gr avi t y. cs)

    usi ng Mi cr osof t . Xna. Framework;usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mObj ect s;

    namespace Skeel Sof t BodyPhysi csTut ori al . Sof t Body. For ceGener at or s

    {publ i c seal ed cl ass Gr avi t y : ForceGenerat or{

    pr i vat e Vect or3 accel er at i on;

    publ i c Vect or3 Accel er at i on{

    get { return accel er at i on; }set { accel er at i on = val ue; }

    }

    publ i c f l oat Accel er at i onX{

    get { return accel er at i on. X; }set { accel er at i on. X = val ue; }

    }

    publ i c f l oat Accel er at i onY{

    get { return accel er at i on. Y; }set { accel er at i on. Y = val ue; }

    }

    14

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    18/81

    publ i c f l oat Accel er at i onZ{

    get { return accel er at i on. Z; }set { accel er at i on. Z = val ue; }

    }

    / / - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    publ i c Gr avi t y( ): t hi s( new Vect or3( 0, - 9. 81f , 0) ) { }

    publ i c Gr avi t y( Vect or3 accel er at i on): base( )

    {t hi s. accel er at i on = accel er at i on;

    }}

    }

    The first constructor takes in no acceleration but creates an acceleration of 9.81 downwards by

    default.ThisisthegravitationalaccelerationthatweexperienceonEarth.

    Wenowhave to implement the Appl yFor cemethod.Asdescribed inEqn.1,weneed to find the

    product of the object mass and gravitational acceleration, and add that to its Resul t ant For ce

    property.

    ( cl ass met hod i n Gr avi t y. cs)

    publ i c voi d Appl yFor ce(Si mObj ect si mObj ect ){

    si mObj ect . Resul t ant For ce += si mObj ect . Mass * accel erat i on;}

    1.3.3Medium

    Next,weimplementaforcegeneratorcalledMedi umwhichrepresentsthemediumthatthesimulation

    objectisin.Theviscosityofthemediumthatthebodyisinwilldeterminehowmuchdragforceitwill

    experience.Anobjectmovinginhoney,forinstance,willexperiencemoredragforcesthananobjectin

    air.To

    simplify

    the

    implementation,

    we

    shall

    only

    represent

    the

    viscosity

    by

    adrag

    coefficient

    that

    can

    bearbitrarilyadjustedbytheusertogetthedesireddrageffect.

    AddaMedium.csfileintheForceGeneratorsfolder.

    15

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    19/81

    ( Medi um. cs)

    usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mObj ect s;

    namespace Skeel Sof t BodyPhysi csTut ori al . Sof t Body. For ceGener at or s{

    publ i c seal ed cl ass Medi um : ForceGenerat or

    { pr i vat e f l oat dr agCoef f i ci ent ;

    publ i c f l oat Dr agCoef f i ci ent{

    get { return dr agCoef f i ci ent ; }set { dr agCoef f i ci ent = val ue; }

    }

    / / - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    publ i c Medi um( f l oat dr agCoef f i ci ent ): base( )

    {

    t hi s. dr agCoef f i ci ent = dr agCoef f i ci ent ;}

    }}

    Asusual,wehavetoimplementtheAppl yFor cemethod.Thedragforceisusuallyproportionaltothe

    currentvelocityofthebody.Thefaster it ismoving,themoredragforce itexperiences.Thus,allwe

    havetodoismultiplyourdragcoefficientwiththecurrentvelocityofthesimulationobject:

    dragforce= dragcoefficient*objectvelocity [2]

    Sincethisisanopposingforcethatslowsdownthemotionoftheobject,wehavetonegatetheresult.

    Theimplementationforthisisasfollows:

    ( cl ass met hod i n Medi um. cs)

    publ i c voi d Appl yFor ce(Si mObj ect si mObj ect ){

    si mObj ect . Resul t ant For ce += - dr agCoef f i ci ent * si mObj ect . Cur r Vel oci t y;}

    16

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    20/81

    1.3.4Spring

    Wenowimplementthelastforcegenerator,whichisaspring.Aspringhastheseattributes:

    Stiffness:Thisdetermines thespringinessof the spring.Thehigher the stiffnessvalue, themoreforcethatwillbegeneratedwhenthespringiscompressedorstretched.Thiscausesthe

    springto

    return

    to

    its

    original

    shape

    faster,

    thus

    creating

    astiffer

    behavior.

    This

    is

    also

    known

    as

    thespringconstant.

    Damping:Thisdetermines theamountof internaldrag force that the springwillexperience.Thedampingforceisparalleltothedirectionofthespring.

    Restlength:Thisisthelengththatthespringwilltrytomaintainwhenundergoingcompressionorstretching.

    Intermsofimplementation,aspringalsoneedstostorethetwoobjectsarethatattachedtoitsothat

    its

    current

    length

    can

    be

    calculated

    at

    any

    time

    step.

    Figure1:Springforcesactingonthetwoendsofthespringwhenundergoingcompression

    ReferringtoFig.1,thespringforceexperiencedbyobjectAiscalculatedas:

    springforceonA= stiffness*(currentlengthrestlength)*unitvectorBA [3]

    17

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    21/81

    Aspringhasitsowndampingforce,inadditiontothedampingforcecausedbythemediumthatitisin.

    Thedifferencebetweenthesetwotypesofdampingforcesisthatthespringdampingforceonlyacts

    on the spring itselfwhile themediumdamping forcedamps themotionofall theobjects in it.The

    springdampingforceisproportionaltotherelativevelocitiesofthetwoobjectsandisusuallywritten

    as:

    springdampingonA= damping*((velocityofAvelocityofB).unitvectorBA)*unitvectorBA [4]

    Note that this damping force should be in the direction from B to A. However, the difference in

    velocitiesisavectoranditmaynotbeinthatdesireddirection.Thus,wehavetoprojectthevelocity

    differencevectortothedirectionvectorfromBtoA.Thisprojectionisdonebytakingthedotproduct

    ofthevelocitydifferencevectorwiththeunitvectorfromBtoA(whichwillgivethemagnitude),and

    thenmultiplyingthatwiththeunitvectorfromBtoA(whichwillthengivethevectorthatweneed).

    Thereisanegationinthetermbecausethisisanopposingforce.

    NewtonsThirdLawofMotionstatesthat forevery forcegenerated,there isanequalandopposite

    force.Thus,thespringforceexperiencedbyobjectBisjustthesameforceasexperiencedbyobjectA,

    butintheoppositedirection.Thisappliestothespringdampingforceaswell.

    Nowthatwehaveenoughknowledgeaboutthespringforces, letusstartto implementtheSpr i ng

    class.CreateanewclassfilecalledSpring.csfileintheForceGeneratorsfolder.

    ( Spr i ng. cs)

    usi ng Mi cr osof t . Xna. Framework;usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mObj ect s;

    namespace Skeel Sof t BodyPhysi csTut ori al . Sof t Body. For ceGener at or s{

    publ i c seal ed cl ass Spr i ng : ForceGenerat or{

    pr i vat e f l oat s t i f f ness;pr i vat e f l oat dampi ng;

    pr i vat e f l oat r estLengt h;pr i vat e Si mObj ect si mObj ect A;pr i vat e Si mObj ect si mObj ect B;

    publ i c f l oat St i f f ness{

    get { return st i f f ness; }set { st i f f ness = val ue; }

    }

    18

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    22/81

    publ i c f l oat Dampi ng{

    get { return dampi ng; }set { dampi ng = val ue; }

    }

    publ i c Si mObj ect Si mObj ect A{get { return si mObj ectA; }set { si mObj ect A = val ue; }

    }

    publ i c Si mObj ect Si mObj ect B{

    get { return si mObj ectB; }set { si mObj ect B = val ue; }

    }

    / / - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    publ i c Spr i ng( f l oat s t i f f ness, f l oat dampi ng, Si mObj ect si mObj ect A,Si mObj ect si mObj ect B)

    : t hi s( st i f f ness, dampi ng, si mObj ect A, si mObj ect B,( si mObj ect A. Cur r Posi t i on - si mObj ect B. Cur r Posi t i on) . Lengt h( ) ) { }

    publ i c Spr i ng( f l oat s t i f f ness, f l oat dampi ng, Si mObj ect si mObj ect A,Si mObj ect si mObj ect B, f l oat r est Lengt h)

    : base( ){

    t hi s. s t i f f ness = st i f f ness;t hi s. dampi ng = dampi ng;t hi s. si mObj ect A = si mObj ect A;t hi s. si mObj ect B = si mObj ect B;

    t hi s. r est Lengt h = r est Lengt h;}}

    }

    TheSpr i ngclassbasicallytakesinthenecessaryattributesofaspringandstoresthem.Italsotakesin

    thetwoSi mObj ect sthatareattachedtoeachendofthespring. Ifnorest length issupplied tothe

    constructor,thenitisjusttakenasthestartingdistancebetweenthetwoSi mObj ect sgiven.

    Next,weimplementtheAppl yFor cemethod:

    19

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    23/81

    ( cl ass met hod i n Spr i ng. cs)

    pr i vat e Vect or3 di r ecti on;pr i vat e f l oat cur r Lengt h;pr i vat e Vect or3 f or ce;publ i c voi d Appl yFor ce(Si mObj ect si mObj ect ){

    / / get t he di r ecti on vectordi r ect i on = si mObj ect A. Cur r Posi t i on - si mObj ect B. Cur r Posi t i on;

    / / check f or zer o vect ori f ( di r ect i on != Vect or3. Zer o){

    / / get l engt hcur r Lengt h = di r ect i on. Lengt h( ) ;

    / / nor mal i zedi r ecti on. Nor mal i ze( ) ;

    / / add spr i ng f or cef or ce = - st i f f ness * ( ( cur r Lengt h - r est Lengt h) * di r ecti on) ;

    / / add spri ng dampi ng f orcef or ce += - dampi ng * Vect or3. Dot( si mObj ect A. Cur r Vel oci t y -

    si mObj ectB. Cur r Vel oci t y, di r ecti on) * di r ecti on;

    / / appl y t he equal and opposi t e f or ces t o the obj ect ssi mObj ectA. Resul t ant Force += f orce;si mObj ectB. Resul t ant Force += - f orce;

    }}

    Implementing theAppl yFor cemethod isabitmore involved.We firstget thedirectionvector that

    pointsfromobjectBtoA,thenwefinditslengthandnormalizeit.Rememberthatwehavetocheck

    whetheravectoristhezerovectorbeforewenormalizeitorelsewewillhaveadivisionbyzero.With

    theseinformation,wecancalculatethespringforceandspringdampingforcesaccordingtoEqn.3and

    Eqn.4respectively.Finally,weaddtheseforcestoobjectAandaddtheequalbutoppositeforceto

    objectB.

    NoticethatwearenotusingtheSi mObj ect thathasbeenpassed inasaparameter,sincewehave

    alreadystoredboththenecessarySi mObj ect sintheclassitself.Thisisabitofaquirkinesscausedby

    implementingthemethodspecifiedintheinterfaceclass.However,itdoesnotcausemuchharmand

    wecan

    just

    pass

    in

    nul lwhen

    we

    are

    calling

    this

    method

    for

    a

    Spr i nginstance.

    20

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    24/81

    1.4IntegratorClassesRecallthatoncewehavetheaccelerationoftheobject,weneedtoperformintegrationwithrespect

    totimetoobtainthevelocityandpositionoftheobject.Inarealtimeenvironment,wearenotableto

    performintegration

    in

    an

    analytical

    manner,

    meaning

    that

    you

    cannot

    just

    integrate

    an

    equation

    like

    what you did in your basic calculus classes (e.g. add one to the exponent and divide thewhole

    equationby it).Whatwehavetorelyonnow isanumericalmethodcallednumerical integration.

    Suchanumericalsolutionallowsustosampleatdiscretepointsintheintegraltogetanapproximate

    solution.Inourcase,wesampletheintegralateachtimestep(forsinglestepintegrators).Numerical

    integratorsallowustousesomeequationsinvolvingacceleration,velocityandpositiontoapproximate

    thenewpositionofanobject.

    One major concept that is associated with numerical integrators is that there is always an error

    associatedwith thenumerical integrator thatweuse. This is roughly indicatedby theorderof the

    integrator.Thehigher theorder, the lesserror there is.However,higherorder integrationmethods

    usuallymeansmorecalculationsandthusslowerinexecution.

    There is a variety of integrators available for us to choose from, ranging from a Forward Euler

    integrationmethodwhich is the fastestbutnotvery stable (firstorder), tosomething likeaRunge

    KuttaFourthOrderwhichisverystablebutveryexpensiveincalculationsaswell.Forgames,thereisa

    popularmiddlegroundtechniquecalledVerletintegrationwhichisfastandstable(secondorder).For

    thistutorial,weshallstartoffwithaForwardEulerintegratorsinceitisthesimplesttounderstandand

    implement,andthenmoveontoaVerletintegratorinlaterchapters.

    Theseintegratorsrequiredifferentattributesoftheobject.Somerequireyoutostorethecurrentand

    previousposition,whilesomerequireyoutostorethecurrentpositionandcurrentvelocity.Whatever

    thecaseis,thenewpositionforthenexttimestepisalwaysgenerated,andthatwillbeusedtoupdate

    theCur r Posi t i onpropertyoftheSi mObj ect .

    Now thatwe have a brief overview of numerical integrators,we can start creating the Integrator

    classes. These classes basically take in the acceleration of a Si mObj ect and performs numerical

    integrationtofindthenewpositionandpossiblyvelocity.

    1.4.1IntegratorAbstractClass

    Asusual,wewillfirstcreateanabstractclassforotherintegratorclassestoderivefrom. First,createa

    newfoldercalledIntegratorsundertheSoftBodyfolder,andcreateanewclassfilenamedIntegator.cs

    init.

    21

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    25/81

    ( I nt egrator. cs)

    usi ng Mi cr osof t . Xna. Framework;usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mObj ect s;

    namespace Skeel Sof t BodyPhysi csTut or i al . Sof t Body. I nt egr at or s{

    publ i c abst r act c l ass I nt egr at or{pr i vat e Game game;

    / / use a f i xed t i me st ep t o get pr edi ct abl e si m pr ot ect ed f l oat f i xedTi meSt ep;

    publ i c f l oat Fi xedTi meSt ep{

    get { return f i xedTi meSt ep; }set { f i xedTi meSt ep = val ue; }

    }

    / / - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    publ i c I nt egr at or ( Game game){

    t hi s. game = game;

    / / set t he f i xed t i me st ep t o target el apsed t i me ( def aul t at 1/ 60)f i xedTi meSt ep = ( f l oat ) game. Tar getEl apsedTi me. Tot al Seconds;

    }}

    }

    The

    I nt egr at orabstract

    class

    defines

    aclass

    variable

    called

    f i xedTi meSt epwhich

    stores

    afixed

    time

    stepvalueforthesimulation. Simulationbehaviorchangesasthetimestepchanges,meaningthata

    spring, for instance, with the same stiffness and damping constants will behave differently when

    undergoing a simulation at 30 frames per second and at 60 frames per second. In order to get

    consistent and predictable simulations, it is better to keep it at a constant value. There are other

    solutionsforthis,suchasadaptivetimestepmethods,butwewillkeeptothissimplesolutioninour

    tutorial.Forthe f i xedTi meSt epvariable,wewillbeusingthevaluefromgame. Target El apsedTi me

    whichspecifiesthedesiredtimestepforthegame.Thedefaultvalueforthisis1/60seconds.

    DerivedclasseswillneedtoimplementtheirownI nt egr at emethod,soitisdefinedasabstractinthe

    class.

    ( cl ass abst r act met hod i n I nt egr at or . cs)

    publ i c abst r act voi d I nt egr at e( Vect or3 accel er at i on, Si mObj ect si mObj ect ) ;

    22

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    26/81

    1.4.2ForwardEulerIntegrator

    Wecannowstarttodiscussaboutourfirstnumericalintegrator,calledtheForwardEulerintegrator.

    Thisisoneofthemostbasicintegratorthatcanbeimplemented.

    Tofindthevalueofanattributeyinthenexttimestep,theForwardEulerintegratorbasicallyfindsthe

    productof

    the

    time

    step

    tand

    the

    derivative

    of

    y,

    and

    adds

    the

    result

    to

    yat

    the

    current

    time

    step:

    y(t+ t)=y(t)+ y(t)t [5]

    Relatingthattooursimulation,wehave:

    v(t+ t)=v(t)+a(t) t [6]

    Thismeansthatthevelocityatthenexttimestepisequalstothevelocityatthecurrenttimeaddedto

    theproductofthetimestepandaccelerationatthecurrenttime.

    Asimilarequationexistsforthepositionoftheobject:

    x(t+ t)=x(t)+v(t) t [7]

    Now,createanewfilecalledForwardEulerIntegrator.cs.

    ( For war dEul er I nt egr at or . cs)

    usi ng Mi cr osof t . Xna. Framework;usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mObj ect s;

    namespace Skeel Sof t BodyPhysi csTut or i al . Sof t Body. I nt egr at or s{

    publ i c seal ed cl ass For war dEul er I nt egr ator : I nt egr at or{

    publ i c For war dEul er I nt egr ator ( Game game): base( game) { }

    }}

    23

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    27/81

    ThisclassbasicallyinheritsfromtheI nt egr at or abstractclass.

    We then createanoverridemethodnamed I nt egr at e, anduseEqn.6andEqn.7 given above to

    obtain thenew velocityandposition respectively.Thesenewattributes areupdated into the given

    Si mObj ect .

    ( cl ass met hod i n For war dEul er I nt egr at or . cs)

    publ i c over r i de voi d I nt egr at e( Vect or3 accel er at i on, Si mObj ect si mObj ect ){

    / / cal cul at e new posi t i on usi ng t he vel oci t y at cur r ent t i mesi mObj ect . Cur r Posi t i on += si mObj ect . Cur r Vel oci t y * f i xedTi meSt ep;

    / / cal cul at e new vel oci t y usi ng t he accel er at i on at cur r ent t i mesi mObj ect . Cur r Vel oci t y += accel erat i on * f i xedTi meSt ep;

    }

    1.5SimulationClassWenowhaveallthenecessaryclassesthatweneedtoimplementthesimulationalgorithmdiscussed

    inSection1.1.Weshallpackthesimulationalgorithm intoaSi mul at i onclassso that it iseasierto

    createotherkindsofsimulationsinlaterchapters.

    Createanew

    folder

    called

    Simulations

    in

    the

    SoftBody

    folder,

    and

    then

    add

    anew

    class

    file

    named

    Simulation.cs.

    ( Si mul at i on. cs)

    usi ng System. Col l ect i ons. Gener i c;usi ng Mi cr osof t . Xna. Framework;usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. For ceGener at or s;usi ng Skeel Sof t BodyPhysi csTut or i al . Sof t Body. I nt egr at or s;usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mObj ect s;

    namespace Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mul at i ons{

    publ i c c l ass Si mul at i on{

    pr ot ect ed Game game;pr ot ect ed Li st si mObj ect s = new Li st ( ) ;pr otect ed Li st gl obal For ceGenerators = new

    Li st ( ) ;

    24

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    28/81

    pr ot ect ed Li st spr i ngs = new Li st ( ) ;pr ot ect ed I nt egr at or i nt egr at or ;

    publ i c Li s t Si mObj ect s{

    get { return si mObj ect s; }set { si mObj ect s = val ue; }

    }

    publ i c I nt egr at or I nt egr at or{

    get { return i nt egr at or ; }set { i nt egr at or = val ue; }

    }

    / / - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    publ i c Si mul at i on( Game game){

    t hi s. game = game;

    / / creat e a def aul t i nt egr at ort hi s. i nt egrator = new For war dEul er I nt egr at or ( game) ;

    }}

    }

    FromthealgorithmstatedinSection1.1,weknowthatwehavetoiteratethroughlistsofsimulation

    objects,forcesandalsouseanintegrator.ThustheSi mul at i onclasskeepstrackof:

    A listofSi mObj ect s:Thesearetheobjectsthatareinthesimulationsystem.Theactiveoneshave

    their

    motion

    determined

    by

    the

    simulation

    system,

    while

    the

    passive

    ones

    do

    not.

    AlistofForceGenerators:Thesearetheglobalforcegenerators,suchasGr avi t yandMedi um.TheywillbeappliedtoallSi mObj ect sinthesystem.

    A listofSpr i ngs:TheseareconsideredlocalforcegeneratorsthatwillapplyforceswhichactonlyontheattachedSi mObj ect s.

    An integrator: This is used to integrate the acceleration of the Si mObj ect s to obtainpositions/velocitiesforthenexttimestep.

    WeshallalsocreatesomemethodstoaddtheSpr i ngs,ForceGenerat or sandSi mObj ect s intothe

    simulationsystem:

    25

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    29/81

    ( cl ass met hods i n Si mul at i on. cs)

    publ i c voi d AddSpr i ng( f l oat s t i f f ness, f l oat dampi ng, Si mObj ect si mObj A,Si mObj ect si mObj B)

    {Spr i ng spr i ng = new Spr i ng( st i f f ness, dampi ng, si mObj A, si mObj B) ;spr i ngs. Add( spr i ng) ;

    }

    publ i c voi d AddSi mObj ect ( Si mObj ect si mObj ect ){

    si mObj ect s. Add( si mObj ect ) ;}

    publ i c voi d AddGl obal ForceGenerat or ( ForceGenerat or f orceGener ator){

    gl obal For ceGener ators . Add( f orceGener ator) ;}

    Nowwe

    create

    an

    Updat emethod

    that

    implements

    the

    physics

    simulation

    algorithm

    in

    astep

    by

    step

    fashion.

    ( cl ass met hod i n Si mul at i on. cs)

    publ i c vi r t ual voi d Updat e( GameTi me gameTi me){

    }

    First,we

    sum

    up

    all

    the

    forces.

    This

    is

    done

    by

    iterating

    through

    each

    Spr i ngto

    sum

    up

    the

    local

    spring

    forces,andthenapplyingtheglobalforcestoeachSi mObj ect .

    26

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    30/81

    ( i nsi de Updat e( ) i n Si mul at i on. cs)

    / / sum al l l ocal f orcesf or each ( Spr i ng spr i ng i n spr i ngs){

    spr i ng. Appl yForce(nul l ) ; / / no need t o speci f y any si mObj}

    / / sum al l gl obal f or ces acti ng on t he obj ectsf or each ( Si mObj ect si mObj ect i n si mObj ect s){

    i f ( si mObj ect . Si mObj ect Type == Si mObj ect Type. ACTI VE){

    f or each ( ForceGenerat or f orceGenerat or i n gl obal For ceGener ators){

    f orceGener ator. Appl yForce( si mObj ect ) ;}

    }}

    Next,wefindtheaccelerationbydividingtheresultantforcebythemassoftheobject.Wethenask

    theassignedintegratortointegratetheacceleration.

    ( out si de Updat e( ) i n Si mul at i on. cs)

    Vect or3 accel er at i on;

    ( i nsi de Updat e( ) i n Si mul at i on. cs)

    f or each ( Si mObj ect si mObj ect i n si mObj ect s){

    i f ( si mObj ect . Si mObj ect Type == Si mObj ect Type. ACTI VE){

    / / f i nd accel erat i onaccel er at i on = si mObj ect . Resul t ant For ce / si mObj ect . Mass;

    / / i ntegratei nt egr at or . I nt egr at e( accel er at i on, si mObj ect) ;

    }}

    Nowwe

    update

    the

    object

    by

    asking

    the

    Si mObj ect

    to

    update

    itself.

    27

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    31/81

    ( i nsi de Updat e( ) i n Si mul at i on. cs)

    / / updat e obj ectf or each ( Si mObj ect si mObj ect i n si mObj ect s){

    si mObj ect . Updat e( gameTi me) ;}

    RecallthattheSi mModel classimplementedUpdat ebyassigningthepositionoftheGameModel tothe

    Cur r Posi t i onproperty.Thisessentiallyupdatesthepositionofthemodelthatweseeonthescreen

    accordingtothenewlycalculatedCur r Posi t i on.

    Finally,weresettheforcesactingontheSi mObj ect ssothattherearenoforcesintheaccumulative

    Resul t ant For cepropertyatthestartofthenexttimestep.

    ( i nsi de Updat e( ) i n Si mul at i on. cs)

    / / r eset f or ces on s i m obj ectsf or each ( Si mObj ect si mObj ect i n si mObj ect s){

    i f ( si mObj ect . Si mObj ect Type == Si mObj ect Type. ACTI VE){

    si mObj ect . Reset For ces( ) ;}

    }

    1.6UsingTheNewClassesToCreateASpringSimulationNowletuscreatethesimulationinthemaingameclassbyusingalltheclassesthatwehavecreated.If

    you take a look at the Game1.cs provided in the project files, it is pretty much the same as the

    templateversionprovidedautomaticallybyXNAGameStudiowhenyoucreateanewXNAproject.The

    only difference is that all the unnecessary comments have been removed, and that the necessary

    componentshavebeenaddedin(refertothechapteronBaseCodesformoredetails).

    We

    shall

    first

    create

    a

    blank

    method

    for

    initializing

    the

    scene:

    28

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    32/81

    ( cl ass members i n Game1. cs, addi t i on of code i n bol d)

    pr ot ect ed over r i de voi d I ni t i al i ze( ){

    I ni t Spr i ngScene( ) ;base. I ni t i al i ze( ) ;

    }

    pr i vat e voi d I ni t Spr i ngScene( ){

    }

    Next,wewillinitializethesimulationinthenewlycreatedmethod.Wefirstloadinacubeandasphere.

    Theywill serveasmarkers to indicatebothendsof thesprings.Thesemodelsare loadedusing the

    Model Component fromourbasecodes.

    ( at t he t op of Game1. cs)

    usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mObj ect s;

    ( out si de I ni t Spr i ngScene( ) i n Game1. cs)

    Si mModel st at i onaryCubeSi mObj , movi ngSpher eSi mObj ;

    ( i nsi de I ni t Spr i ngScene( ) i n Game1. cs)

    / / l oad i n a cube and a sphere

    GameModel st at i onar yCube = model Component . LoadGameModel ( @"cube" ) ;st at i onaryCube. Transl ateY = 5;GameModel movi ngSphere = model Component . LoadGameModel ( @"sphere") ;

    Wethencreateaspringsimulation:

    ( at t he t op of Game1. cs)

    usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mul at i ons;

    ( out si de I ni t Spr i ngScene( ) i n Game1. cs)

    Si mul at i on spr i ngSi m;

    ( i nsi de I ni t Spr i ngScene( ) i n Game1. cs)

    / / creat e a spr i ng s i mspr i ngSi m = new Si mul at i on( t hi s) ;

    29

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    33/81

    Next,wepackthecubeandsphereintoSi mObj ect sandaddthemintothespringsimulation.Thecube

    will be controlled by us, so it will be marked as passive. The sphere on the other hand is to be

    controlledbythesimulation,soithastobemarkedasactive.Themassofthesphereissetto1.0after

    sometrialanderror,whilethemassofthecubeissettosomearbitruaryvalue(1000.0inthiscase)but

    thevaluedoesnotmattersinceitisnotusedinthecalculations.

    ( i nsi de I ni t Spr i ngScene( ) i n Game1. cs)

    / / cr eat e si m obj ect s f r om t he l oaded model sf l oat spher eMass = 1. 0f ;movi ngSphereSi mObj = new Si mModel ( movi ngSpher e, spher eMass,

    Si mObj ect Type. ACTI VE) ;spr i ngSi m. AddSi mObj ect ( movi ngSpher eSi mObj ) ;st at i onaryCubeSi mObj = new Si mModel ( st at i onar yCube, 1000. 0f ,

    Si mObj ect Type. PASSI VE) ;spr i ngSi m. AddSi mObj ect ( st at i onaryCubeSi mObj ) ;

    WethencreateaspringbetweenthetwoSi mObj ect screated:

    ( i nsi de I ni t Spr i ngScene( ) i n Game1. cs)

    / / att ach a spr i ng bet ween t he si m obj ect sf l oat st i f f ness = 8. 0f ;f l oat dampi ng = 0. 1f ;spr i ngSi m. AddSpr i ng( st i f f ness, dampi ng, st at i onaryCubeSi mObj ,

    movi ngSpher eSi mObj ) ;

    Next,weaddglobalforcestothesimulationsystem.Wewillbeusingthegravitationalaccelerationof

    Earth(9.81downwards)forthegravity.Forthedragcoefficientvalue,avalueof0.5wasdeemedtobe

    appropriateaftersometrialanderror.

    ( at t he t op of Game1. cs)

    usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. For ceGener at or s;

    ( i nsi de I ni t Spr i ngScene( ) i n Game1. cs)

    / / add i n a gl obal f or ce gener at or : gr avi t yGr avi t y gr avi t y = new Gr avi t y( new Vect or3(0, - 9. 81f , 0) ) ;spri ngSi m. AddGl obal For ceGener ator( gr avi t y) ;

    30

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    34/81

    / / add i n a gl obal f or ce gener at or : ai rf l oat dr agCoef f i ci ent = 0. 5f ;Medi um ai r = new Medi um( dr agCoef f i ci ent ) ;spr i ngSi m. AddGl obal For ceGener at or( ai r ) ;

    Nowwe

    create

    an

    I nt egr at orand

    assign

    it

    to

    the

    simulation.

    ( at t he t op of Game1. cs)

    usi ng Skeel Sof t BodyPhysi csTut or i al . Sof t Body. I nt egr at or s;

    ( i nsi de I ni t Spr i ngScene( ) i n Game1. cs)

    / / creat e an i nt egr at or and assi gn i t t o t he si m For war dEul er I nt egr at or i nt egr at or = new For war dEul er I nt egr ator ( t hi s) ;

    spr i ngSi m. I nt egr at or = i nt egr at or ;

    Inordertovisualizethespring,weshallalsodrawalinefromthecubetothespherethatrepresents

    thespring.AlinehasalreadybeencreatedwhenweincludeLi ne3DComponent intogame. Component s,

    soallwehavetodonowistosetthepositionsofthetwoends,andalsothecoloroftheline.

    ( i nsi de I ni t Spr i ngScene( ) i n Game1. cs)

    / / i ni t t he l i ne f r om cube t o spher e that r epr esent s t he spr i ngl i ne3DComponent . St art Posi t i on = st at i onaryCube. Transl ate;l i ne3DComponent . EndPosi t i on = movi ngSpher e. Transl at e;l i ne3DComponent . Col or = Col or. Whi t e;

    Now,weneedtoupdatethesimulationandthelineintheUpdat emethod.Allwehavetodoistoask

    thesimulationtoupdateitself,andthenmovethetwoendsofthelinetothenewpositionscalculated

    forthesphereandcubesimulationobjects.

    31

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    35/81

    ( i nsi de Updat e( ) i n Game1. cs, addi t i on of code i n bol d)

    pr ot ect ed over r i de voi d Updat e( GameTi me gameTi me){

    / / updat e t he si mspr i ngSi m. Updat e( gameTi me) ;

    / / updat e l i nel i ne3DComponent . St ar t Posi t i on = st at i onar yCubeSi mObj . Cur r Posi t i on;l i ne3DComponent . EndPosi t i on = movi ngSpher eSi mObj . Curr Posi t i on;

    base. Updat e( gameTi me) ;}

    Ifyoucompileandexecutetheprogramnow,youshouldhaveastationarycubeandamovingsphere

    thatisattachedviaaspring,whichmeansthatthesimulationthatwehavecodedworks!

    Letusnowdothelastbitsofcodingtoallowtheusertocontrolthestationarycube.

    ( cl ass met hods i n Game1. cs, addi t i on of code i n bol d)

    pr ot ect ed over r i de voi d Updat e( GameTi me gameTi me){

    / / pol l f or i nputHandl eI nput ( gameTi me) ;

    / / updat e t he si mspr i ngSi m. Updat e( gameTi me) ;

    / / updat e l i nel i ne3DComponent . St art Posi t i on = st at i onaryCubeSi mObj . Cur r Posi t i on;l i ne3DComponent . EndPosi t i on = movi ngSpher eSi mObj . Curr Posi t i on;

    base. Updat e( gameTi me) ;}

    pri vat e voi d Handl eI nput ( GameTi me gameTi me){

    i f ( i nput Component . I sKeyHel dDown(Keys. Ri ght ) ){

    st at i onaryCubeSi mObj . Cur r Posi t i onX += 0. 1f ;}

    i f ( i nput Component . I sKeyHel dDown(Keys. Le f t ) ){st at i onar yCubeSi mObj . Cur r Posi t i onX - = 0. 1f ;

    }i f ( i nput Component . I sKeyHel dDown(Keys. Up) ){

    st at i onar yCubeSi mObj . Cur r Posi t i onY += 0. 1f ;}

    32

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    36/81

    i f ( i nputComponent . I sKeyHel dDown(Keys. Down) ){

    st at i onar yCubeSi mObj . Cur r Posi t i onY - = 0. 1f ;}

    }

    Youshouldnowhaveaspringsimulationthatcanbecontrolledusingthekeyboard,just likeVideo4

    thatyousawinthebeginningofthischapter.

    Inthischapter,wehavelookedathowaphysicssimulationshouldbedoneingames.Wethencreated

    fourmaingroupsofclassesthathelpuscreatethesesimulationsinanobjectorientedmanner.Finally,

    wemadeuseofalltheseclassestocreateasimplespringsimulation.

    Thischapterisquitelongbecauseitcoversalotofbasicsforsoftbodysimulations.Westillhavethree

    morechapterstogobutdonotworry,mostoftheworkhasalreadybeendoneinthischapter.Inthe

    nextchapter,

    we

    shall

    start

    to

    implement

    acloth

    simulation,

    and

    it

    will

    rely

    largely

    on

    the

    codes

    that

    wehavecreatedsofar.

    GetthesourcefilesfortheendofthischapterfromtheSkeelSoftBodyPhysicsTutorialChapter1ENDfolder

    33

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    37/81

    Chapter2 - ClothSimulation

    GetthesourcefilesforthestartofthischapterfromtheSkeelSoftBodyPhysicsTutorialChapter2BEGINfolder

    Inthischapter,wewillbecreatingasimpleclothsimulation.Aclothisoneofthebasicsoftbodiesthat

    issimple

    to

    create

    and

    yet

    produces

    pleasant

    results.

    Softbodies,ingeneral,ismostlyabouthowyouconnectthespringsbetweenvertices.Eachvertexof

    themodel isabletomove independentlyfromothers,allowingthemodeltodeformandchange its

    overallshape.Whetherthemodeldeformslikeasoftbodythatyouexpectverymuchdependsonhow

    youconnect thespringsand theattributesof thesprings.Now thatweknowhow tocreatesprings

    from thepreviouschapter,wewill learnhow toconnect the springs for theplanegeometry in this

    chaptersothataclothsimulationcanbecreated.

    Bytheendofthischapter,youshouldbeabletocreateacloththatlookslikethis:

    Video5:Aclothsimulationcreatedusingsimplespringsandconstraints[Clickonimageabovetowatchthevideo]

    34

    http://www.youtube.com/watch?v=JncQOCg9FS0
  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    38/81

    2.1ConstraintsBeforewegetintocreatingtheclothitself,letusfirsttakealookatconstraintsandwhyweneedthem.

    Constraints

    are

    basically

    conditions

    that

    the

    simulation

    system

    must

    try

    to

    satisfy.

    Some

    examples

    of

    constraintsare lengthconstraintswhere twoobjects try tomaintain theirdistanceapart,andpoint

    constraintswhereanobjecttriestosticktoacertainpointinspace.

    Inordertounderstandwhylengthconstraintsforclothareso important, Ihavecreatedaversionof

    the cloth thatdoes not use them.Notice how thewhole cloth looks too elastic due to the highly

    springybehavior,especiallyatthepinnedcorners.Itisalsoquiteunstableattimes.

    Video6:Aclothsimulationwithoutlengthconstraints.Theclothtendstobetooelasticandquiteunstableattimes.

    [Clickonimageabovetowatchthevideo]

    Whatwe

    really

    want

    for

    acloth

    simulation

    is

    to

    have

    length

    constraints

    between

    the

    vertices

    on

    top

    of

    thesprings.Thiswillhelpmaintainthedistancesbetweentheverticesandgiveamuchmorerealistic

    behavior for thecloth simulation.Wewillalsowant tohavepointconstraintsat thecornersof the

    clothsothatthecornerscanbepinnedinspacefortheusertocontrol.

    35

    http://www.youtube.com/watch?v=nCrA6eUrXSc
  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    39/81

    Thewaywe solve theconstraintswillbeby relaxation,averypracticalmethod thatworkswell for

    games.Wewilliteratennumberoftimesandateachiteration,wetrytogeteachconstrainttosatisfy

    thegoal.Forexample, forapointconstraint,wecouldperhapsdoa10iteration loopandatevery

    iteration,wemovetheobjecttowardsthegoalpositionasspecifiedbythepointconstraint.

    Why

    then

    do

    we

    want

    to

    iterate

    n

    times

    and

    get

    the

    constraint

    to

    move

    towards

    the

    goal

    repeatedly?

    Thereason isthattheremightbemanydifferentconstraintstobesatisfiedandbysatisfyingoneof

    them, the other constraints might be violated. Imagine a simulation with two connected length

    constraints.Duringeachiteration,thefirstconstraintmovestowardsthegoallengthbutbydoingso,

    thegoallengthofthesecondconstraintmighthavebeenincreased.Thesecondconstraintthenmoves

    towardsitsgoallengthandinturnmighthavecausedthegoallengthofthefirstconstrainttoincrease.

    Thisseemsliketheyarecounteringtheeffectofeachother,butattheendofeachiteration,bothof

    themwouldhavemovedtowardstheirgoallengthstosomeextent(convergenceisguaranteedunder

    therightconditions).Thisisthereasonwhywehavetoiteratethroughnnumberoftimessothatwe

    are slowly relaxing the fight between the constraints and theywill slowly converge to their goal

    lengthsrespectively.

    Thenumberofiterationstoperformdependsonhowmuchprocessingpoweryouhaveforyourgame.

    Thehigherthe iterations,thebettertheconstraintswillbesatisfied,butthemoreexpensive it isto

    calculate.Amoderatenumberofabout10to20oftenworkswelltogivesatisfactoryresult,sothereis

    usually no need to increase this number to high values like 100. In fact, in some cases,just one

    iterationmightbeenough.Itissuggestedthatyoureducethisnumbertoasuitablevaluewhichgives

    visuallyacceptableresults.

    2.1.1ConstraintInterface

    CreateafoldercalledConstraintsintheSoftBodyfolder,andaddanewclassfilenamedConstraint.cs.

    The Const r ai nt classwillbasicallybean interface thatmakes it compulsory forderived classes to

    implementamethodcalledSat i sf yConst r ai nt .

    ( Const r ai nt . cs)

    namespace Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Const r ai nt s{

    publ i c i nt erf ace Const r ai nt{

    voi d Sat i sf yConstr ai nt ( ) ;}

    }

    36

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    40/81

    2.1.2LengthConstraint

    Asmentionedearlier, lengthconstraintsarebasicallyconstraints that tries tomaintain thedistance

    betweentwoobjects.

    IntheConstraintsfolder,addanewclassfilenamedLengthConstraint.cs.ALengt hConst r ai nt class

    basicallytakes

    in

    two

    Si mObj ect sand

    the

    expected

    distance

    between

    them.

    ( Lengt hConst r ai nt . cs)

    usi ng Mi cr osof t . Xna. Framework;usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mObj ect s;

    namespace Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Const r ai nt s{

    publ i c seal ed cl ass LengthConst r ai nt : Const r ai nt{

    pr i vat e f l oat l engt h;pr i vat e Si mObj ect si mObj 1;pr i vat e Si mObj ect si mObj 2;

    publ i c f l oat Length{

    get { return l engt h; }set { l engt h = val ue; }

    }

    / / - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    publ i c Lengt hConst r ai nt ( f l oat l engt h, Si mObj ect si mObj 1, Si mObj ect si mObj 2){

    t hi s. l engt h = l engt h;t hi s. si mObj 1 = si mObj 1;t hi s. si mObj 2 = si mObj 2;

    }}

    }

    Next, we have to implement the Sat i sf yConst r ai nt method. Recall that we have to satisfy the

    constraint at each iteration. For a length constraint, this canbedonebymovingboth ends of the

    constraintbyhalfthedifferenceofthecurrentlengthandthegoallength,asshowninFig.2.

    37

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    41/81

    Figure2:Twoendsofalengthconstraintmovingtowardsthegoallengthinasingleiteration

    The implementationofthat isgivenbelow.Basicallywecalculate thedirectionandcurrentdistance

    between the twoSi mObj ect s.Thenwenormalize thedirectionvector,andmovebothSi mObj ect s

    halfthedifferencedistanceintheconvergingdirection.

    ( cl ass met hod i n Lengt hConst r ai nt . cs)

    Vect or3 di r ecti on;f l oat cur r ent Lengt h;Vect or3 moveVect or ;publ i c voi d Sat i sf yConst r ai nt ( ){

    / / cal cul at e di rect i ondi r ect i on = si mObj 2. Cur r Posi t i on - si mObj 1. Cur r Posi t i on;

    / / cal cul at e cur r ent l engt hcur r ent Lengt h = di r ect i on. Lengt h( ) ;

    / / check f or zer o vect ori f ( di r ect i on != Vect or3. Zer o){

    / / nor mal i ze di r ect i on vect ordi r ecti on. Nor mal i ze( ) ;

    / / move t o goal posi t i onsmoveVect or = 0. 5f * ( cur r ent Lengt h - l engt h) * di r ect i on;si mObj 1. Curr Posi t i on += moveVect or ;si mObj 2. Curr Posi t i on += - moveVect or ;

    }}

    38

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    42/81

    2.1.3PointConstraint

    Anotheruseful typeofconstraint isapointconstraint.Apointconstraint tries topinanobject toa

    certainpointinspace.Thisisusefulforconstrainingthetoptwocornersofourclothlateron.Byusing

    point constraints,we are also able to control the twopinned cornersby changing their respective

    constraintposition.

    IntheConstraintsfolder,createanewclassfileandcallitPointConstraint.cs.

    ( Poi nt Const r ai nt . cs)

    usi ng Mi cr osof t . Xna. Framework;usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mObj ect s;

    namespace Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Const r ai nt s{

    publ i c seal ed cl ass Poi nt Const r ai nt : Const r ai nt{

    pr i vat e Vect or3 poi nt ;pr i vat e Si mObj ect si mObj ect ;

    publ i c Vect or3 Poi nt{

    get { return poi nt ; }set { poi nt = val ue; }

    }

    publ i c f l oat Poi nt X{

    get { return poi nt . X; }

    set { poi nt . X = val ue; }}

    publ i c f l oat Poi nt Y{

    get { return poi nt . Y; }set { poi nt . Y = val ue; }

    }

    publ i c f l oat Poi nt Z{

    get { return poi nt . Z; }set { poi nt . Z = val ue; }

    }

    publ i c Si mObj ect Si mModel{

    get { return si mObj ect ; }set { si mObj ect = val ue; }

    }

    / / - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    39

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    43/81

    publ i c Poi nt Const r ai nt ( Vect or3 poi nt , Si mObj ect si mObj ect ){

    t hi s. poi nt = poi nt ;t hi s. si mObj ect = si mObj ect ;

    }}

    }

    NowwehavetoimplementtheSat i sf yConst r ai nt method.Tosatisfyapointconstraint,allwehave

    todoismovetheobjecttothegoalposition.

    ( cl ass met hod i n Poi nt Const r ai nt . cs)

    publ i c voi d Sat i sf yConst r ai nt ( ){

    / / move t o goal posi t i onsi mObj ect . Cur r Posi t i on = poi nt ;}

    2.1.4ProcessingTheConstraintsInTheSimulationClass

    NowthatwehaveboththeLengt hConst r ai nt andPoi nt Const r ai nt classescreated,weneedtolet

    theSi mul at i onclassprocessthem.

    First,weaddinsomevariablesinSimulation.cstokeeptrackoftheConst r ai nt s.Thisconsistsofalist

    of Const r ai nt sanda constr ai nt I t er at i ons variable thatdetermineshowmany times to iterate

    throughthe

    Const r ai nt s

    per

    time

    step.

    ( at t he t op of Si mul at i on. cs)

    usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Const r ai nt s;

    ( cl ass member s i n Si mul at i on. cs)

    pr ot ect ed Li st const r ai nt s = new Li s t( ) ;pr otect ed i nt constr ai nt I t er at i ons;

    publ i c Li s t Const r ai nt s{

    get { return constr ai nt s; }set { const r ai nt s = val ue; }

    }

    40

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    44/81

    publ i c i nt Const r ai nt I t er at i ons{

    get { return constr ai nt I t er at i ons; }set { const r ai nt I t er at i ons = val ue; }

    }

    Thenwe

    have

    to

    iterate

    through

    the

    constraints

    to

    relax

    them,

    as

    described

    in

    the

    beginning

    of

    Section

    2.1.Thisrelaxationiterationhastobedoneaftertheintegratorhassolvedforthenewobjectpositions,

    butbeforeupdatingtheobjects.

    ( cl ass met hod i n Si mul at i on. cs, addi t i on of code i n bol d)

    publ i c vi r t ual voi d Updat e( GameTi me gameTi me){

    / / sum al l l ocal f orcesf oreach ( Spr i ng spr i ng i n spr i ngs)

    {spr i ng. Appl yFor ce( nul l ) ; / / no need t o speci f y any si mObj

    }

    / / sum al l gl obal f or ces acti ng on t he obj ectsf oreach ( Si mObj ect si mObj ect i n si mObj ect s){

    i f ( si mObj ect . Si mObj ect Type == Si mObj ect Type. ACTI VE){

    f or each ( ForceGenerat or f orceGenerat or i n gl obal For ceGener ators){

    f orceGener ator. Appl yForce( si mObj ect ) ;}

    }}

    f oreach ( Si mObj ect si mObj ect i n si mObj ect s){

    i f ( si mObj ect . Si mObj ect Type == Si mObj ect Type. ACTI VE){

    / / f i nd accel erat i onaccel er at i on = si mObj ect . Resul t ant For ce / si mObj ect . Mass;

    / / i ntegratei nt egr at or . I nt egr at e( accel er at i on, si mObj ect) ;

    }}

    / / sat i s fy constr ai nt sf or ( i nt i = 0; i < const r ai nt I t er at i ons; i ++){

    f oreach ( Const r ai nt const r ai nt i n const r ai nt s){

    constr ai nt . Sat i sf yConstr ai nt ( ) ;}

    }

    41

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    45/81

    / / updat e obj ectf or each ( Si mObj ect si mObj ect i n si mObj ect s){

    si mObj ect . Updat e( gameTi me) ;}

    / / r eset f or ces on s i m obj ectsf oreach ( Si mObj ect si mObj ect i n si mObj ect s){

    i f ( si mObj ect . Si mObj ect Type == Si mObj ect Type. ACTI VE){

    si mObj ect . Reset For ces( ) ;}

    }}

    2.2Verlet(NoVelocity)IntegratorItistimetointroduceanotherintegratorcalledtheVerletintegrator.Itisknowntobefastandstable

    (secondorder,ascomparedtofirstorderforForwardEuler),andthushasbeenapopularchoicefor

    games.There are severalvariantsofVerlet integrators available, suchasVelocityVerlet and also a

    multistepmethodcalledLeapFrogVerlet.However,theVerletintegratorthatweareinterestedinisa

    versionthattotallyomitstheobjectsvelocityinitscalculations.

    Intheprevioussection,wehavecoveredhowtosolveconstraintsbyrelaxation.Ifyouhaverealized,in

    ordertosatisfytheconstraints,wesimplymovedtheobjectstowardstheirgoalpositionswithoutany

    consideration for theirvelocities!This iswheretheVerlet integratorcomes in.Byexplicitlyomitting

    the velocities in the calculations,we canperform the simple shiftingofpositionsduring relaxation

    withoutworryingaboutthevelocities,andwewillstillbeabletosolveforthenewpositionsateach

    timestep.

    TheequationfortheVerletintegrationisasfollows:

    x(t+ t)=2x(t)+x(t t)+a(t)(t)2

    [8]

    Itbasicallyusesthepositioninthecurrentandprevioustimestepstodeterminethepositionforthe

    nexttimestep.

    42

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    46/81

    TheaboveVerletintegrationequationcanbemodifiedtosimulatedragforcesinthemedium,whered

    isadragcoefficientbetween0and1inclusive.

    x(t+ t)=(2d)x(t)+(1d)x(t t)+a(t)(t)2

    [9]

    ByusingEqn.9,wecan leaveouttheMedi umforcegenerator inoursimulation lateron,sincethed

    variableintheequationaboveisagoodsubstituteforthat.Wewillbeusingthismodifiedequationin

    oursimulationfromnowon.

    Letusnow start implementing thisVerlet integrator. Inorder todifferentiate thisVerlet integrator

    from theothervariants,we shallname thisclass Ver l et NoVel oci t yI nt egr at or . In the Integrators

    folder,createanewclassfilenamedVerletNoVelocityIntegrator.cs.

    ( Ver l et NoVel oci t yI nt egr at or . cs)

    usi ng Syst em;usi ng Mi cr osof t . Xna. Framework;usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mObj ect s;

    namespace Skeel Sof t BodyPhysi csTut or i al . Sof t Body. I nt egr at or s{

    publ i c seal ed cl ass Ver l et NoVel oci t yI nt egr at or : I nt egr at or{

    pr i vat e f l oat drag;

    publ i c f l oat Dr ag{

    get { return dr ag; }set{

    i f ( val ue < 0 | | val ue > 1){

    throw new Ar gument Except i on( "Ai r r esi st ance must be between 0and 1" ) ;

    }drag = val ue;

    }

    }

    publ i c Ver l et NoVel oci t yI nt egr at or ( Game game) : t hi s( game, 0. 005f ) { }

    publ i c Ver l et NoVel oci t yI nt egr at or ( Game game, f l oat drag): base( game)

    {t hi s. drag = drag;

    }

    43

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    47/81

    }}

    Thisclassbasicallytakesinadragvalueintheconstructor.Itwillbesetto0.005bydefaultifnovalue

    is

    provided.

    WenowneedtoimplementthecompulsoryI nt egr at emethod,usingEqn.9.

    ( cl ass met hod i n Ver l et NoVel oci t yI nt egr at or . cs)

    Vect or3 newPosi t i on;publ i c over r i de voi d I nt egr at e( Vect or3 accel er at i on, Si mObj ect si mObj ect ){

    newPosi t i on = ( 2 - dr ag) * si mObj ect . Cur r Posi t i on- ( 1 - dr ag) * si mObj ect . Pr evPosi t i on

    + accel er at i on * f i xedTi meSt ep * f i xedTi meSt ep;

    si mObj ect . Pr evPosi t i on = si mObj ect . Cur r Posi t i on;si mObj ect . Cur r Posi t i on = newPosi t i on;

    }

    2.3SimulationVertexRecallthatinthepreviouschapter,wepackedamodelintoasimulationobjectcalledSi mModel sothat

    thesimulation

    attributes

    such

    as

    position,

    velocity

    and

    mass

    are

    included.

    For

    acloth,

    we

    are

    interested inmoving itsvertices,meaningthatthesimulationobjectsareactuallytheverticesofthe

    clothitself!Wewillthusneedtoimplementanewsimulationclassforthevertices.

    IntheSimObjectsfolder,createanewclassfilenamedSimVertex.cs.

    ( Si mVert ex. cs)

    usi ng Mi cr osof t . Xna. Framework;usi ng Skeel Sof t BodyPhysi csTut or i al . Pr i mi t i ves;

    namespace Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mObj ect s{

    publ i c seal ed cl ass Si mVer t ex : Si mObj ect{

    pr i vat e i nt ver t exI d;pr i vat eText uredPri mi t i ve pr i mi t i ve;

    44

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    48/81

    publ i c i nt Ver t exI d{

    get { return ver t exI d; }set { ver t exI d = val ue; }

    }

    / / - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    publ i c Si mVer t ex( f l oat mass, Si mObj ect Type si mObj ect Type, i nt ver t exI d,Text uredPr i mi t i ve pr i mi t i ve)

    : base( mass, si mObj ect Type){

    t hi s. ver t exI d = ver t exI d;t hi s. pr i mi t i ve = pr i mi t i ve;t hi s. cur r Posi t i on = pr i mi t i ve. Get Ver t exPosi t i on( ver t exI d) ;t hi s. pr evPosi t i on = cur r Posi t i on;

    }}

    }

    TheSi mVert exclasstakesinthemassofthevertex,theSi mObj ect Type(activeorpassive),thevertex

    idandtheprimitive.Allthese informationwillallowustoretrieveandsetthevertexpositionswhen

    weneedto.TheothernecessaryinformationwillcomefromthebaseclassSi mObj ect .

    Wewillhave to implement the Updat emethodaswell.Allwehave todo is tojust set the vertex

    positiontothenewlycalculatedposition.

    ( cl ass method i n Si mVert ex. cs)

    publ i c over r i de voi d Updat e( GameTi me gameTi me){

    pr i mi t i ve. Set Ver t exPosi t i on( t hi s. ver t exI d, t hi s. curr Pos i t i on) ;}

    2.4SoftBodyandClothSimulationClassesWewillnowproceedonbycreatingclassesthatrepresentasoftbodyandacloth.Aclothisessentially

    a

    soft

    body,

    so

    the

    Cl ot hSi mclass

    that

    we

    will

    be

    creating

    will

    inherit

    from

    the

    Sof t BodySi mclass.

    Let

    us firststartoffbycreatingtheSof t BodySi mclass. IntheSimulations folder,createanewclass file

    namedSoftBodySim.cs.

    45

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    49/81

    ( Sof t BodySi m. cs)

    usi ng Mi cr osof t . Xna. Framework;usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mObj ect s;

    namespace Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mul at i ons{

    publ i c c l ass Sof t BodySi m : Si mul at i on{pr ot ect ed Si mVer t ex[ ] si mVer t i ces;

    publ i c Si mVer t ex[ ] Si mVer t i ces{

    get { return si mVer t i ces; }set { si mVer t i ces = val ue; }

    }

    / / - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    publ i c Sof t BodySi m( Game game): base( game) { }

    }}

    TheSof t BodySi mclassbasicallyinheritsfromtheSi mul at i onclass,andstoresalistofSi mVer t ex.

    Next,forourCl ot hSi mclass,createanewclassfilenamedClothSim.csintheSimulationsfolder.

    ( Cl ot hSi m. cs)

    usi ng Mi cr osof t . Xna. Framework;usi ng Mi cr osof t . Xna. Framework. Gr aphi cs;usi ng Skeel Sof t BodyPhysi csTut or i al . Pr i mi t i ves;usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Const r ai nt s;usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mObj ect s;

    namespace Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mul at i ons{

    publ i c seal ed cl ass Cl ot hSi m : Sof t BodySi m{

    pr i vat eText uredPl ane cl ot hPl ane;

    publ i c Cl ot hSi m( Game game, Text uredPl ane cl ot hPl ane, f l oat cl ot hMass,f l oat str uct St i f f ness, f l oat st r uct Dampi ng,f l oat shear St i f f ness, f l oat shearDampi ng,f l oat bendSt i f f ness, f l oat bendDampi ng)

    : base( game){

    t hi s. cl othPl ane = cl ot hPl ane;

    46

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    50/81

    / / creat e s i m dat aCr eat eSi mVer t i ces( cl ot hPl ane, cl ot hMass);

    / / connect spr i ngs and add const r ai nt sConnect Spr i ngs( st r uct St i f f ness, st r uct Dampi ng,

    shear St i f f ness, shearDampi ng,bendSt i f f ness, bendDampi ng) ;

    }}}

    TheCl ot hSi mclasstakesinaText uredPl aneastheclothgeometry,aswellastheattributesforthe

    differenttypesofspringsneededto linkuptheclothvertices. Italsocreatesthesimulationvertices,

    connects thespringsandadds lengthconstraintsbetween thevertices.The twomethodcalls inthe

    constructorhavenotbeenimplementedyet,andwillbediscussednow.

    TheimplementationforCr eat eSi mVert i cesisasfollows:

    ( cl ass met hod i n Cl othSi m. cs)

    pr i vat e voi d Cr eat eSi mVer t i ces(Text uredPl ane cl ot hPl ane, f l oat cl othMass){

    i nt numVert i ces = cl ot hPl ane. NumVert i ces;f l oat vert exMass = cl ot hMass / numVer t i ces;si mVer t i ces = new Si mVer t ex[ numVer t i ces] ;f or ( i nt i = 0; i < numVert i ces; i ++){

    si mVer t i ces[i ] = new Si mVer t ex( ver t exMass, Si mObj ect Type. ACTI VE, i ,cl ot hPl ane) ;

    t hi s. AddSi mObj ect ( si mVer t i ces[ i ] ) ;}

    }

    ItbasicallycreatesaSi mVer t exforeachvertexoftheplane,andsetsittoactivesothattheywillbe

    processedbythesimulation.

    BeforewediscussabouttheConnect Spr i ngsmethod,weneedtotalkabouthowthespringsshould

    beconnectedfortheclothgeometry.Thereareessentiallythreekindsofspringsthatareneededfora

    goodcloth

    simulation:

    1. Structuralsprings(Fig.3):Theseareplacedalongeachquadedge.Theyarethebasicspringswhichmaintaintheinterdistancebetweentheverticesinthehorizontalandverticaldirections.

    47

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    51/81

    Figure3:Structuralspringsonaplane

    2. Shearsprings(Fig.4):Theseareplacedalongthediagonalsofeachquad.Theyhelptomaintainthe square shape of each quadon the geometry, preventing them from collapsing into flat

    diamondshapes.

    Figure4:Shearspringsonaplane

    3. Bend springs (Fig. 5 and 6): These are placed horizontally and vertically as well, just likestructuralsprings.However,theyareplacedbetweenverticesthataretwoverticesapart.They

    helptocontrolhowmuchtheclothcanbend.Ahighstiffnessvalueforthesespringswillcreate

    astifferlook(e.g.leather)whilealowstiffnessvaluewillcreateasofterbehavior(e.g.silk).

    48

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    52/81

    Figure5:Horizontalbendspringsonaplane

    Figure6:Verticalbendspringsonaplane

    Thesevideosillustratehowtheclothwillbehavewithoutsomeofthesesprings:

    49

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    53/81

    Video7:Clothsimulationwithonlystructuralsprings(noshearandbendsprings).Theclothisunabletomaintainagoodshapewhendrapingdownwards.

    [Clickonimageabovetowatchthevideo]

    Video8:Clothsimulationwithstructuralandshearsprings(nobendsprings).Theclothholdsitsshapebetterbutisunabletobendrealisticallyandpenetratesitselfeasily.

    [Clickonimageabovetowatchthevideo]

    50

    http://www.youtube.com/watch?v=RMqgajfZSvYhttp://www.youtube.com/watch?v=L4oFuXovsrM
  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    54/81

    Youcanprobablygetawaywithnotusingthebendsprings incertaincases,suchasapieceofcloth

    that isflutteringwiththewind,as longas it isvisuallyplausible.Thiscanactuallyhelptosavesome

    springandconstraintcalculations.Wewill,however,beusingthebendspringsinoursimulation.

    With this new knowledge of how to connect the springs, we can start to implement the

    Connect Spr i ngs

    method:

    ( cl ass met hod i n Cl othSi m. cs)

    pr i vat e voi d Connect Spr i ngs( f l oat str uctSt i f f ness, f l oat st r uct Dampi ng,f l oat shear St i f f ness, f l oat shearDampi ng,f l oat bendSt i f f ness, f l oat bendDampi ng)

    {f or ( i nt x = 0; x < cl ot hPl ane. Lengt hSegment s; x++){

    f or ( i nt y = 0; y

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    55/81

    t hi s. AddSpr i ng( shearSt i f f ness, shearDampi ng,si mVer t i ces[ ver t exAI d] , si mVer t i ces[ ver t exBI d] ) ;

    f l oat l engt h = ( cl othPl ane. Get Ver t exPosi t i on( ver t exAI d) -cl ot hPl ane. Get Ver t exPosi t i on( ver t exBI d) ) . Lengt h( ) ;

    t hi s. Const r ai nt s. Add( new Lengt hConst r ai nt ( l engt h,si mVer t i ces[ ver t exAI d] , si mVer t i ces[ ver t exBI d] ) ) ;

    / / shear spr i ng: di agonal ( \ )ver t exAI d = x + y * ( cl ot hPl ane. LengthSegment s + 1) ;ver t exBI d = ( x + 1) + ( y + 1) * ( cl ot hPl ane. LengthSegment s + 1) ;t hi s. AddSpr i ng( shearSt i f f ness, shearDampi ng,

    si mVer t i ces[ ver t exAI d] , si mVer t i ces[ ver t exBI d] ) ;l engt h = ( cl ot hPl ane. Get Ver t exPosi t i on( ver t exAI d) -

    cl ot hPl ane. Get Ver t exPosi t i on( ver t exBI d) ) . Lengt h( ) ;t hi s. Const r ai nt s. Add( new Lengt hConst r ai nt ( l engt h,

    si mVer t i ces[ ver t exAI d] , si mVer t i ces[ ver t exBI d] ) ) ;}

    }

    f or ( i nt x = 0; x < cl ot hPl ane. Lengt hSegment s - 1; x++){

    f or ( i nt y = 0; y

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    56/81

    That isquitea lotofcode,butmostof the codesareactually repetitive.The structural springsare

    createdfirst,followedbytheshearspringsandthenthebendsprings.Lengthconstraintsarecreated

    inthesameloops.

    Nowthatwehavethespringsconnected,weneedtoupdatetheclothgeometryintheUpdat emethod:

    ( cl ass met hod i n Cl othSi m. cs)

    publ i c over r i de voi d Updat e( GameTi me gameTi me){

    / / cal l base. Updat e( ) t o updat e the ver t ex posi t i onsbase. Updat e( gameTi me) ;

    / / r ecal cul at e the ver t ex nor mal scl othPl ane. Recal cul at eNor mal s( ) ;

    / / commi t t he ver t ex posi t i on and normal changes

    cl ot hPl ane. Commi t Changes( ) ;}

    Wefirstcallthebaseclasstoupdateitselffirst,whichwillcalculateallthenewpositionsofthevertices

    and set the clothvertices to thosenewpositions.Since theverticesmove independently fromone

    another,theirrelativepositionschangeovertimeandtheirnormalswillchangeaswell.Thus,weneed

    to recalculate the normals so that the rendering is faithful to the geometry changes. Note that

    Recal cul at eNormal s has already been implemented in the base class. Finally, we need to call

    Commi t Changeson

    the

    plane

    geometry

    which

    will

    update

    all

    the

    vertex

    position

    changes

    in

    the

    video

    RAM.

    2.5UsingTheNewClassesToCreateAClothSimulationWearenowreadytocreatetheclothinourmainprogramfileGame1.cs.

    First,weinitializethescene.

    53

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    57/81

    ( cl ass met hod i n Game1. cs, addi t i onal codes i n bol d)

    pr ot ect ed over r i de voi d I ni t i al i ze( ){

    I ni t Cl ot hScene( ) ;base. I ni t i al i ze( ) ;

    }

    pri vat e voi d I ni t Cl ot hScene( ){

    }

    Wedefinetheclothattributesandcreateaplaneastheclothgeometry.

    ( at t he t op of Game1. cs)

    usi ng Skeel Sof t BodyPhysi csTut or i al . Pr i mi t i ves;

    ( out si de I ni t Cl ot hScene( ) i n Game1. cs)

    Text uredPl ane cl ot hPl ane;

    ( i nsi de I ni t Cl othScene( ) i n Game1. cs)

    / / c l ot h at t r i but esi nt l ength = 10;i nt wi dt h = 5;i nt l engthSegment s = 20;

    i nt wi dt hSegment s = 15;

    / / l oad i n a pl anecl ot hPl ane = newText uredPl ane( t hi s, l engt h, wi dt h, l engt hSegment s,

    wi dt hSegments, @"checker board") ;cl ot hPl ane. I ni t i al i ze( ) ;

    IntheSolutionExplorer,noticethatthereisafoldercalledPrimitivesthatcontainsclassesthatyoucan

    usetocreatetexturedplanesandcylinders.Iwillnotbeexplainingthecodes intheseclassesbutdo

    notethatwiththeseclasses,youwillbeabletocreateprimitivesandalsoget/setthevertexattributes

    suchas

    the

    position

    and

    normal.

    If

    you

    are

    going

    to

    use

    your

    own

    primitive

    classes

    or

    load

    your

    own

    modelsfromfiles,youwillalsoneedtohavemethodstoget/setthevertexattributes.

    We thendefine themassof thecloth,attributesof thedifferent springs for thecloth,andcreatea

    Cl ot hSi minstance:

    54

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    58/81

    ( at t he t op of Game1. cs)

    usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Si mul at i ons;

    ( out si de I ni t Cl ot hScene( ) i n Game1. cs)

    Cl ot hSi m cl othSi m;

    ( i nsi de I ni t Cl ot hScene( ) i n Game1. cs)

    / / creat e a cl ot h s i m f l oat cl othMass = 2. 0f ;

    f l oat st r uctSti f f ness = 2. 0f ;f l oat st r uctDampi ng = 0. 02f ;f l oat shear St i f f ness = 2. 0f ;f l oat shear Dampi ng = 0. 02f ;f l oat bendSt i f f ness = 2. 0f ;f l oat bendDampi ng = 0. 02f ;cl ot hSi m = new Cl ot hSi m( t hi s, cl ot hPl ane, cl ot hMass, st r uctSti f f ness,

    st r uct Dampi ng, shear St i f f ness, shearDampi ng,bendSt i f f ness, bendDampi ng) ;

    cl ot hSi m. Const r ai nt I t er at i ons = 10;

    Next,wecreate theglobal forcegenerators.Forourcloth simulation, thiswillonlybegravity.Note

    thatwewillnotbecreatingaMedi umforcegeneratorsincethedrag forceswillbesimulated in the

    Verletintegrator.

    ( at t he t op of Game1. cs)

    usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. For ceGener at or s;

    ( i nsi de I ni t Cl othScene( ) i n Game1. cs)

    / / add i n a gl obal f or ceGener at or s: gr avi t yGr avi t y gr avi t y = new Gr avi t y( new Vect or3(0, - 9. 81f , 0) ) ;cl ot hSi m. AddGl obal For ceGener at or( gr avi t y) ;

    Wewillconstrainthetopleftandtoprightcornersoftheplaneinordertocontrolthemlateron.This

    isdonebyusingPoi nt Const r ai nt s.

    ( at t he t op of Game1. cs)

    usi ng Skeel Sof t BodyPhysi csTut ori al . Sof t Body. Const r ai nt s;

    55

  • 7/28/2019 IntroductionToSoftBodyPhysics-Skeel

    59/81

    ( out si de I ni t Cl ot hScene( ) i n Game1. cs)

    Poi nt Const r ai nt t opLef t Cor ner , t opRi ght Cor ner ;

    ( i nsi de I ni t Cl othScene( ) i n Game1. cs)

    / / const r ai n t he t wo t op cor ner s of t he cl ot h so t hat we can cont r ol i t

    t opLef t Cor ner = newPoi nt Const r ai nt ( cl ot hSi m. Si mVer t i ces[ 0] . Cur r Posi t i on, cl ot hSi m. Si mVer t i ces[ 0] ) ;cl ot hSi m. Const r ai nt s. Add( t opLef t Cor ner ) ;t opRi ght Corner = new

    Poi nt Const r ai nt ( cl othSi m. Si mVer t i ces[ l engt hSegment s] . Cur r Posi t i on,cl othSi m. Si mVer t i ces[ l engt hSegment s] ) ;

    cl othSi m. Const r ai nt s. Add( t opRi ght Cor ner ) ;

    WethencreateaVerletintegrator,withanassociateddragvalue.

    ( at t he t op of Game1. cs)

    usi ng Skeel Sof t BodyPhysi csTut or i al . Sof t Body. I nt egr at or s;

    ( i nsi de I ni t Cl othScene( ) i n Game1. cs)

    / / creat e an i nt egr at or and assi gn i t t o t he si m f l oat drag = 0. 01f ;

    I nt egr at or i nt egr at or = new Ver l et NoVel oci t yI nt egr at or ( t hi s, dr ag) ;cl ot hSi m. I nt egr at or = i nt egr at or ;

    Thereareafewmorestepsregardingourclothplanebeforewecanexecutetheprogram.Weneedto

    callitsLoadCont ent methodsothatitcanloadthenecessarycontents.

    ( cl ass met hod, addi t i onal code i n bol d)

    pr ot ect ed over r i de voi d LoadCont en