Intermission #7 – Resource pools and Particles

I was going to do this as two separate articles, but after a refresh trawl at what is already our there and available I’ve decided to put them together.  We don’t need anything overly complex at this stage of the game, although I will point out some of the areas where you could go further (and point you in the right direction).

I’ve always been an advocate for “not re-inventing the wheel” and in these days of XNA development, you don’t need to.  There are many resources and code stores to find implementations of what you need and you can either learn the lesson of someone else’s approach or just copy it for your own use (make sure the original author gets a mention if you do.

Source updated for Final combined update project for GS 4.0 project here on Codeplex (Windows and WP7)


 

Trawling through the net

In looking around at what other particle and resource pool are around, I found very different levels of content available, some were old but good (that just need tweaking to get back up to date), some were new but were either too basic or didn’t offer enough flexibility.  Some I really liked, here’s a list of what is good that I’ve found so far:

    Resource Pools by the SwampThing – best description of what is required  for a full resource pool, implements this in the CC sample below (still in GS 2)
    An XNA resource pool on CodeCube – Quick and dirty yet ultimately flexible pool system
    An Honourable mention to my colleague NemoKrads particle tutorial series – Good graphics oriented particle tutorial (both 3D and 2D with shading)
    Creators club 2D particle sample – Good resource but still in Game Studio 2 framework, needs a little love to get it going
    Riemers 2D game series particles section – Riemers has always been one of my favourites, the site hasn’t been updated in a while and the tuts are in GS 3, but the forums are still alive and happening (I don’t believe I actually wrote that then).


Resource Pools

Resource pools are an attempt to make large lists of items as memory efficient as possible, the problem with using lists or fixed arrays are countless for areas where you need a large amount of objects that need to be created and destroyed on a regular basis.  Lists incur garbage collection issues (which on the XBOX is really bad) and arrays are of fixed size so unless you know exactly how many you are going to need and how often you need to clear it our or loop through it, it becomes problematic.

Resources pools try to get through this by using several methods, they use the fixed limit of an array and combine it with a stack of some description (usually a Queue, which is a dynamic list of values which takes items from the top and adds them back to the bottom when done, like the queue in the bank, once you leave the front of the queue you have to go to the back if you want in again 🙂 ).  Some just use a queue but this can be problematic.

The idea is simple enough, have a group of people standing around waiting to do work  (no pun intended in the current state of the economy) and have a manager sitting on the side calling names.  When a workers name is called they are set off and when they are done they go to the back of the queue.

 

Now the XNA sample just uses a Queue with no management, which is too light. The CodeCube class is nice and neat and extends this basic format efficiently, but doesn’t have enough umph to it (IMHO, but I may still use it for my own projects at some point where it’s useful).

So we are left with the SwampThing Resource pool, overall it provides a good framework for a memory efficient resource pool and there is good documentation for how to consume it.  So add the Pool.CS class to the engine of our project as is for now.  Look in SwampThings post above for some of the background detail.


Particles

Particle systems can be some of the most complex systems of many a game, where the desire for effect is key.  It doesn’t have to be though, it just depends on your implementation and how far you want to go with it.

Particle systems are comprised of several Key components:

    Particles – A single sprite texture or point sprite, the smallest component of particle effects.  Like a single spark in a firework.
    Particle Managers – Managers control how long an individual particle lives for, destroying it when it’s dead and updating the one’s still alive.
    Particle Emitters – Emitters are a point of flow, like a hosepipe flooding out water, how you squeeze the pipe effects the kind of flow or spray emitted.
    Particle Behaviours – Control what a particle does once it has been emitted, swirls, dives or splits in two.  Many possibilities.
    Particle Animation – A scripted animation of several effects or particles.  Bit like a firework show.

We’ll only cover the first two or three here and maybe add more later, animations with particles in particular can be quite a bit of a challenge to get right.

An individual particle, as described above, is like a spark in a firework, however that spark can either be very small like a coloured pixel on a screen (sometimes referred to as a point sprite) or it can be quite large, which is usually referred to as a billboard sprite.  Of course it can also be in-between, point is that the actual texture used for the particle can be anything you want.

If you look around there are several good test apps or samples of firework displays which are all driven by particle effects.

image image image

Explosion effect (with Smoke)

Smoke Plume effect

Explosion Particle

1. Particle class

Now in keeping with reuse, the MS particle class example is as good an effort as any, so we’ll reuse that, grab it from here off the codeplex site and add it to the engine folder (it has been updated slightly to fit in the project properly, just so you are aware, should you use the one direct from the CC particle sample).  To keep things simple though we will update the namespace of the class to the same as our project this time.  So update the namespace to:

The class itself is easy to under stand and well commented, in short we have a set of attributes about the particle:

    Position – location on the screen of the particle
    Velocity – it’s velocity
    Acceleration – Its acceleration state so the particle increases or decreases each update
    Lifetime – how long the particle should live
    Scale – so we can expand or reduce the particle size
    Rotation Speed – how fast the particle rotates
    Rotation – the particles current rotation, initialised to a random angle
    Time Since Start – how long the particle has been alive for

We do need to add a few bits to the StarTrooperGame.cs class to support the MS version, nothing major, just adding the “RandomBetween” function and changing the state of the m_Random attribute/.  First change the m_Random attribute at the start of the StarTlrooperGame class to be static, like so:

Then add the following function towards the end of the class after the LoadResources function:

Finally add the following property for the Random attribute, this helps us later when we need random values for particles or emitters:

2. Particle Manager

Now this class we’ll create from scratch as the sample that is available is a bit hard to read and Swampthings version although complete doe beat around the bush a bit.  Since we also want to have more control over how the particles flow we need to remove some of the randomness (adding a but of particle behaviour)

So right click on the Engine folder in the solution explorer and select new item, ensure you have “XNA Game Studio 3.1” highlighted in the tree on the left hand side and select the “Game Component” option and enter a name of “ParticleManager”.

What you will see now is the standard framework for an XNA game component, however we need a drawable game component as we want it to draw to the screen, pretty obvious really (It’s still a mystery why Drawable game component is not an option on the new item screen).  So to change this into a drawable game component, we need to update the following:

    Change the inherited type from Game Component to Drawable Game component
    Add the Load and Unload Resource overloads
    Add the overloaded Draw function

This is what it should look like after it’s updated:

 

 

With the base component in place, it’s best to add the component to the game, mainly so you don’t forget to later and wonder why it’s not working Winking smile

So in the StarTrooperGame class add the following after the gamer service component:

 

There, now with the manager in place we can start defining how it should work. 

3. Particle Emitter

The particle emitter is the work horse of any particle engine and like Sprites we have a large template from which to create a multitude of different effects based upon a set of customisable attributes.

So the template Particle Emitter takes care of individual particle management and generation plus some default behaviour, the individual particle effects define how each effect works and can supplement the defaults or completely replace them as necessary.

As this section is quite long, we will go through it section by section.  First off create a new class in the engine folder called “ParticleEmitter.cs” (don’t forget to update the namespace and remove the .Engine part)

First the class and constructor:

The code is fairly well commented, the main thing to notice here (that’s different from most the samples) is that the Emitter can move, so we have some attributes (like the Particles) to control movement.  We could just leave the Emitter static so it is just the point at which particles are launched from and have them move themselves, but this limits us for certain effects which might revolve around the emitter or where outside forces can effect particle generation.  We also couldn’t effectively do collision detection against individual particles (more on that later in the series), although it has been done by others with more advanced particle engines.
We also have an extra attribute to control how often particles are sent out from the emitter but more on that later.

Next is the initialise function, which sets an emitter up and creates the pool for the particles:

So we load the texture for the emitter (which is actually stored in the particle manager to reduce duplicate textures being loaded, but more on that later) and set the origin point for the emitter, which is impotent if the emitter needs to rotate.

We then call the Initialise Constants function which is the internal initialisation function for the different effects.  In this Emitter template the initialisation constants function is an abstract function (meaning it has no code as it is provided by classes that inherit this template class)

Lastly we set up the pool for the particles and set the emitter as active.

Next up are the Add Particles function which control the flow of particles from the emitter, which can either produce a random number of particles depending on the constants or a fixed number.

This results in a set of active particles in the particle pool

As you can see above, adding particles causes them to be initialised, by default we produce a completely random effect, this can be overridden or supplemented by the actual effects as the class is defined as virtual:

This returns initialised particles ready for action.

Then we have the Update and supporting function which pretty much speak for themselves (note we don’t draw particles from the emitter as this is handled by the Particle Manager):

The update loop simply updates all the particles for the emitter, the PickRandomDirection does exactly what it says on the tin and produces a random angle, used to give a random direction for a particle.

Lastly we have the properties and constants for the Emitter Class