You are on page 1of 4

ParticleSystems

Imsureyouloveplayingcomputergames,especiallythoseoneswhichinvolvelotsof
fighting,blood,blasts,rockets,etc.Yousureenjoy blastingarocketwhichleavesa
smokytrailbehinditandyoualsolovetowatchafireeffectshowingtheburningofthe
fuel.Whenthisrockethitsamonster,itspiecesflyawayrealisticallyasiftherocket
piecesareobeyingphysicslaws.
Indeed,theyareobeyingphysicslaws.Welcometotheworldofparticlesystems.Allthe
effectssuchasfire,water,smoke,blood,etc.areatabasiclevelparticlesystems.Now
whattheheckisaparticlesystem?Itcanbeacollectionofindividualparticlesofsmoke
(orforthatmatteranyothereffect)behavingaccordingtoasetofrules.Whenthe
(physics)rulesmixandmatchwiththeparticlespropertiessuchasvelocity,weight,
acceleration,etc.,itcreateswonders.Yougetatotallyrealisticeffectwithoutmuch
effort.Allyouhavetodoistodefinecharacteristicpropertiesfortheparticlesof the
desiredeffectandapplythebasicrudimentarylawssuchasgravity,momentumtransfer,
etc.toit.Yes,ofcourseyoucanaddmorelawssuchasviscousdrag,etc.toyourparticle
system.Morethelawsyouintegratebettertherealismis.
Youmaysay:WOW!Thatiswonderful.IwishIcouldgetmyhandsdirtyonanactual
particlesystem.Behold,yourwishisgranted.Weareactuallygoingtobuildourown
basicparticlesysteminC++.ItcanbeimplementedinanycompilerofC++supporting
graphics.But,herewearegoingtouseTurboC++3.1.But,notethatIhavealso
implementedthissystemusingAllegrolibrary.But,youarefreetouseanyother
graphicslibrarysuchasDirectX orOpenGL.
Firstly,notethedownloadlocationforthesourcecode.Itis
http://www.paraschopra.com/sourcecode/particle.zip
Duetospacerestrictions,wewilljustbediscussingcode snippetshereandnotthewhole
codeitself.Butwhateverwediscusswillbesufficientforyoutofollowthewholecode.
Firstletusdefinedatastructuresrequired.
enumParticleType{Create,Update}
structVector2d{
doublex
doubley
}
structParticle{
Vector2dPos//Positionoftheparticle
Vector2dVel //Velocityoftheparticle
intage //Currentageoftheparticle
intLifeSpan //Ageafterwhichtheparticledies
intcolor
intsize
}

Herewehaveastructuredefiningthepropertiesofaparticleviz.Position,velocity,age,
colorandsize.Aswearerunningourparticlesystemina2Dworld,wewilljustneed
twocoordinatesX&Y,whicharegivenbythestructure Vector2d.Notethatherethe
originistopleftcornerofthemonitorandXispositivetotheeast(or right)oforiginand
Yispositivetothesouth(ordownwards)oftheorigin.
TheCreateconstantdefineswhetheranexistingparticlehasdiedandshoulditbe
replacedbycreatinganewparticleelsewhere.
Nowwhataparticlesystemconsistsisahugelotcollectionofparticles.Eachindividual
particledefinedbystructureParticle.Sowhenthevariousforcesareappliedtothem,
theybehaveindifferentmanner.Thisbehaviorisdifferentbecausedifferentparticles
havedifferentpropertiessuchaslocationsorpositions,sowhenaforceactsonthem,the
sameforceproducesdifferentchanges.
Now,letustakealookattheInitializationfunction Init()oftheParticlesystemclass.
voidInit(longnum_part,longnum_forces,Vector2dForces[],ParticleTypepart_type,Vector2dvel,
Vector2dpos1,Vector2dpos2,intlifespan,intcolor,intsize){
Particles=newParticle[num_part]
ParticleNum=num_part
for(inti=0i<num_forcesi++){
TotForce.x+=Forces[i].x
TotForce.y+=Forces[i].y
}
Particle_Type=part_type
Vel=vel
Pos1=pos1
Pos2=pos2
LifeSpan=lifespan
Color=color
Size=size
randomize()
InitParticles()
}

Pos1andPos2(inthearguments)indicatethepositionofthetwooppositecornersofthe
rectanglebetweenwhichparticlesaregenerated.Thisrectanglebasicallyrestrictsthe
initialpositionofanewlygeneratedparticlewithinit.However,thepositionof
individualparticlesisrandomprovideditlieswithintherectangle.Thiscanbeseeninthe
functionInitParticles()whichinitializesalltheparticles.
Thearray Forcesindicatethevariousforcesactingonthesystem.Theseforcesare
universal,thatistheydonothavepositionvaluesbuthavemagnitudevaluesonly.They
actinthesamewayonalloftheparticles,irrespectiveoftheirrespectivepositions.These
forcesarethenaddedtogethertorepresentasingleforceTotForce.
Therealcoreofaparticlesystemisthemainloopofexecutionitiswheretheupdation
oftheparticlespropertiesoccurs.Itmeanstheparticlespropertiessuchaslocation,age,

velocity,etc.areupdatedaccordingtotheforcesandsomeothercriterialikeage,etc.Let
usanalyzeourownloopfunction run().
voidRun(){
while(!kbhit()){
delay(10)
cleardevice()
//delay(10)
for(inti=0i<ParticleNumi++){
if(Particles[i].age>=0){
setfillstyle(1,Particles[i].color)
setcolor(Particles[i].color)
//circle((int)Particles[i].Pos.x,(int)Particles[i].Pos.y,Particles[i].size)
fillellipse((int)Particles[i].Pos.x,(int)Particles[i].Pos.y,Particles[i].size,Particles[i].size)
Particles[i].Vel.x+=TotForce.x
Particles[i].Vel.y+=TotForce.y
Particles[i].Pos.x+=Particles[i].Vel.x
Particles[i].Pos.y+=Particles[i].Vel.y
Particles[i].age++
if(Particles[i].age>Particles[i].LifeSpan){
if(Particle_Type==Create){
InitParticle(i)
}else{
Particles[i].age=1
}}
}
}
}}

Thefunction kbhit()ensuresthattheparticlesystemisrununtilanyofthekeysis
pressed.Youmayobserveherethatthevalueof TotForceisaddedtothevalueofthe
velocity,henceincreasingitandthevalueoftheparticlesvelocityisaddedtoits
position.Thisincreasemayactuallybedecreaseifthevelocity orTotForceisnegative.
Foreachparticle,afterthepositionandvelocity areupdated,anellipse(orcircle)is
plottedonthescreenatthelocationspecifiedbyitspositionvariable.
Alsonotethattheparticlesageisincreasedby1eachtimeitisupdatedintheloopand
whenitsageincreasesitsmaximumageallowed,anewparticleisinitialized.Notethat
themaximumageisdifferentfordifferentparticlestoachievemorerealism.
WehaveusedthebaseclassParticleSystemtoderiveaclasscalledBouncy.Itjust
overridestherun()functionsoastointegrateavirtual wallsenclosingthescreenfrom
whichparticlesbounceand losesomeoftheirvelocity(10%inthiscase).Itis
implementedasfollows:
if(Particles[i].Pos.y>getmaxy()||Particles[i].Pos.y<0)Particles[i].Vel.y*=0.9
if(Particles[i].Pos.x>getmaxx()||Particles[i].Pos.x<0)Particles[i].Vel.x*=0.9

Youmaytryexperimentingwith othervaluesinsteadofjust0.9.Tryusing0.3 or
differentvaluesforxandy.Trustmethisthingisfun.

Nowforthelastpart,wecreateanactualparticlesystembycreatinganobjectforclass
Bouncy(or ParticleSystem)
voidmain(){
Bouncyn
//ParticleSystemn
intn_forces=1
Vector2df[1]
f[0].x=0.0
f[0].y=0.5
Vector2dvel,pos1,pos2
vel.x=5
vel.y=5
n.InitGraphics()
setbkcolor(BLACK)
pos1.x=getmaxx()/2
pos1.y=getmaxy()/2
pos2.x=getmaxx()/2
pos2.y=getmaxy()/2
n.Init(1000,n_forces,f,Create,vel,pos1,pos2,100,EGA_GREEN+EGA_RED,1)
n.Run()
getch()
}

Herewearecreatingaparticlesystemwith1000particlesoforangecolorandsize1.We
justhaveasingleverticalforceofvalue0.5.Thisistoemulateakindofgravity.We
initializethepositionsof all theparticlesatthecenterofthescreen.Wethushaveour
particlesystemreadytoroll.
Thatsit.Enjoytheshow.Youhaveallthefreedomtoplaywithyournewlycreatedcute
littleparticlesystem.YoumaytryaddinganXcomponentofvelocityalso,oryoumay
placetheinitial sourceofparticlesatthebottomofthescreenandthengivingthe
particlesnegativeYvelocity,thuscreatingafireeffect.
Youmayalsoaddsomemorefeaturesintotheexistingsystem byderivingclassesfrom
it.Youmayhavemultipleparticlesystemsoperatingsimultaneously orasystemwhich
reducesparticlessizeorcolorwithtime.Thediverseeffectsofferedbythissystemare
onlylimitedbyyourcreativity.Unleashitandruletheworld.
AttheendIwouldlikeyoutotinglewithyourgreymatterby tryingtosimulatevarious
effectssuchasviscousdrag,fire,smoke,ablastandflowofblood oranyothereffectyou
seeinaHollywoodflickorthelatestgames.
Weblocationofthistutorial:http://www.paraschopra.com/tutorials/particlesystems/
ParasChopra

You might also like