Presentation is loading. Please wait.

Presentation is loading. Please wait.

Development of a particle system

Similar presentations


Presentation on theme: "Development of a particle system"— Presentation transcript:

1 Development of a particle system
9.3. Particle Systems Development of a particle system

2 Question Clinic: FAQ In lecture exploration of answers to frequently asked student questions

3 Particle Systems Development of an XNA/Java deployable particle system

4 Particle Systems A particle system can be used to simulate phenomena such as fire, smoke, explosions, moving water (e.g. fountains, waterfalls), sparks, dust, snow, rain, bullet casings, etc. Particle systems can also be used to provide special effects for spells, etc. or provide a model of fur and grass. Particle effects are widely used within games.

5 Particle Systems A particle system is typically controlled by an emitter. The emitter acts as the source for generated particles. Particles may be emitted at a constant rate or in sudden bursts. Each update/draw can be defined in terms of a simulation stage and a rendering stage. Each generated particle can have a number of defined parameters, e.g. velocity, direction, lifetime, colour, etc. Typically each parameter value is randomly selected from within some defined range.

6 Particle Systems Simulation Stage
New particles are spawned if needed (alongside particle parameter selection/randomisation). Any particles that exceed their lifetime are removed from the simulation. All other particles properties are updated as needed (e.g. position, rotation, etc.) based on some simulation rules. The particles may also be tested for collision against other objects, with suitable interactions introduced Rendering stage Each particle is rendered (if in 3D typically using a textured billboard)

7 Particle Systems (example)
Based upon the XNA ParticleSample tutorial Particle Systems (example) Particle System Explosion Particle System Explosion Smoke Particle System Smoke Plume Particle System We will explore the XNA ParticleSample tutorial. Particle Aside: The tutorial uses a SpriteBatch to render the particles –a GPU point sprite based approach is explored in a later lecture.

8 Particle Systems (particles)
Each particle system comprises a number of particles. Each particle is defined with properties such as position, velocity, acceleration, rotation, lifetime, etc. When drawn each particle will display a common image that is layered on top of other particles (using either normal or additive blending). The particle properties are controlled to provide the desired effect.

9 Particle public class Particle public bool isActive {
public Vector2 position; public Vector2 velocity; public Vector2 acceleration; public float rotation; public float rotationSpeed; public float lifetime; public float timeSinceStart; public float scale; public bool isActive { get { return timeSinceStart < lifetime; } } public void Initialize( Vector2 position, Vector2 velocity, Vector2 acceleration, float lifetime, float scale, float rotationSpeed) { // Store passed values // Set time since start to zero // Randomly select rotation (0-2π radians) } public void Update(float dt) { velocity += acceleration * dt; position += velocity * dt; rotation += rotationSpeed * dt; timeSinceStart += dt; Determine if this particle is alive Definition position, velocity, rotation acceleration, and rotation speed Initialise the particle (e.g. upon particle reuse or ‘rebirth’) Define how long this particle will ‘live’ before it is removed/reborn And how long it has been alive Called each frame to update the particle’s position and rotation Define the scale of this particle (i.e. how close/far from the camera) Aside: Other properties can be stored within the particle.

10 Particle Systems (particle management)
The ParticleSystem class manages a collection of particle instances. As particles die and are reborn it is important the particle system caches and reuses particle (to reduce garbage collection churn). A particle system may have to manage particle load by controlling the number of active particles. Often the draw order for particles is important (i.e. particles drawn with normal alpha blending are drawn first before those using additive blending). Particle System Explosion Particle System Explosion Smoke Particle System Smoke Plume Particle System The presented approach uses a generic particle system that is extended/customised for each effect. Other approaches involve having a single manager manage and draw a number of different types of particle.

11 Particle System protected int minNumParticles;
Min-max number of particles that are added per effect call protected int minNumParticles; protected int maxNumParticles; protected float minInitialSpeed; protected float maxInitialSpeed; protected float minAcceleration; protected float maxAcceleration; protected float minRotationSpeed; protected float maxRotationSpeed; protected float minLifetime; protected float maxLifetime; protected float minScale; protected float maxScale; protected SpriteBlendMode spriteBlendMode; As a DrawableGameComponent, when added to a Game instance, XNA will automatically call the update and draw method public abstract class ParticleSystem : DrawableGameComponent { private Texture2D texture; private Vector2 origin; private const int howManyEffects; Particle[] particles; Queue<Particle> freeParticles; Range of initial speeds, accelerations and rotational speeds. Base texture used by particles in this system, alongside a defined origin for the texture Variable controlling the maximum number of effects of this type that can be ongoing Range of lifespans – also drives alpha value and scale Array of particles maintained by this system Range of scales – also effected by lifespan to avoid particle ‘popping’ on creation Queue from which new particles are born and to which dead particles are moved Blendmode to combined particle images

12 Particle System (construction)
protected ParticleSystem( Game game, int howManyEffects) : base(game) { this.howManyEffects = howManyEffects; } public override void Initialize() { InitialiseConstants(); particles = new Particle[ howManyEffects * maxNumParticles]; freeParticles = new Queue<Particle>( howManyEffects * maxNumParticles); for (int i = 0; i < particles.Length; i++) { particles[i] = new Particle(); freeParticles.Enqueue(particles[i]); This method will be overridden by extending classes to providing initial defining values protected abstract void InitializeConstants(); protected override void LoadContent() { // Load/obtain the texture // used by the particle system // Set the origin, i.e. centre, // of the texture } Initialise the constants associated with this particle system Create the particles and add them to the particles array and also to the free particle queue

13 Particle System (adding)
protected virtual void InitializeParticle( Particle particle, Vector2 where) { Vector2 direction = PickRandomDirection(); float velocity = Random.Next(min, max); float acceleration = Random.Next(min, max); float lifetime = Random.Next(min, max); float scale = Random.Next(min, max); float rotationSpeed = Random.Next(min, max); particle.Initialize( where, velocity * direction, acceleration * direction, lifetime, scale, rotationSpeed); } protected virtual Vector2 PickRandomDirection() { float angle = Random.Next(0, MathHelper.TwoPi); return new Vector2((float) Math.Cos(angle), (float)Math.Sin(angle)); Add the effect offered by this particle system at the specified location public void AddParticles( Vector2 where) { int numParticles = Random.Next( minNumParticles, maxNumParticles); for (int i = 0; i < numParticles && freeParticles.Count > 0; i++) Particle particle = freeParticles.Dequeue(); InitializeParticle(particle, where); } Randomise particle properties within defined ranges (can be overridden by extending classes) Min/max values as defined above, e.g. maxScale, minScale, etc. Remove particles from the free queue (where possible) and initialise them

14 Particle System public override void Draw(GameTime gameTime) {
game.SpriteBatch.Begin(spriteBlendMode); foreach (Particle p in particles) { if (!p.Active) continue; float normalizedLifetime = p.TimeSinceStart / p.Lifetime; float alpha = 4 * normalizedLifetime * (1 - normalizedLifetime); Color color = new Color(new Vector4(1, 1, 1, alpha)); float scale = p.Scale * (.75f + .25f * normalizedLifetime); game.SpriteBatch.Draw( texture, p.Position, null, color, p.Rotation, origin, scale, SpriteEffects.None, 0.0f); } game.SpriteBatch.End(); Particle System public override void Update( GameTime gameTime) { float dt = (float)gameTime. ElapsedGameTime.TotalSeconds; foreach (Particle p in particles) if (p.Active) { p.Update(dt); if (!p.Active) freeParticles.Enqueue(p); } Lifetime is normalised to be between 0 (born) and 1 (dead) and is used to calc alpha value (fade-in/out) and scale. Determine how long has passed Consider each particle. This will also consider non-active particles (a performance hit). Other (more complex) approaches can be used to minimise/avoid non-active consideration. Alpha = 0 at a lifetime of 0 and 1, and a maximum of 1 at a lifetime of 0.5 Update the particle and add to free particle queue if needed Particles slowly grow over their lifespan

15 Particle Systems (particle examples)
Three different particle systems are defined: SmokePlumeParticleSystem ExplosionParticleSystem ExplosionSmokeParticleSystem The explosion and explosion smoke particle systems are combined to produce a full explosion effect. Each particle system customises the values within the inherited ParticleSystem class to provide the desired effect. public class SmokePlumeParticleSystem : ParticleSystem { protected override void InitializeConstants() { textureFilename = "smoke"; minInitialSpeed = 20; maxInitialSpeed = 100; minAcceleration = 0; maxAcceleration = 0; spriteBlendMode = SpriteBlendMode.AlphaBlend; }

16 Game Class The Game class defines three instances of the particle system: ExplosionParticleSystem explosion; explosion = new ExplosionParticleSystem(this, 1); Components.Add(explosion); ExplosionSmokeParticleSystem smoke; ... SmokePlumeParticleSystem smokePlume; Repeat times are defined for each particle effect (one explosion every 2 seconds, one puff of smoke every seconds). const float TimeBetweenExplosions = 2.0f; float timeTillExplosion = 0.0f; const float TimeBetweenSmokePlumePuffs = .5f; float timeTillPuff = 0.0f; XNA Aside: As the ParticleSystem instances extend DrawableGame-Component once added to the game, XNA will automatically call their update and draw methods, i.e. the methods do not need to be explicitly called.

17 Game Class private void UpdateExplosions(float dt) { timeTillExplosion -= dt; if (timeTillExplosion < 0) Vector2 where = Vector2.Zero; where.X = RandomBetween(0, graphics.GraphicsDevice.Viewport.Width); where.Y = RandomBetween(0, graphics.GraphicsDevice.Viewport.Height); explosion.AddParticles(where); smoke.AddParticles(where); timeTillExplosion = TimeBetweenExplosions; } Determine if it’s time for another explosion effect Based on the currently active particle system, update the system to ensure that new effects are added as needed. Select a random spawn location protected override void Update( GameTime gameTime) { switch (currentState) { case State.Explosions: UpdateExplosions(dt); break; case State.SmokePlume: UpdateSmokePlume(dt); break; } Add the fire and smoke effects Reset the time Update the currently active particle system

18 To do: Summary Complete Question Clinic
Today we explored: Overview of particle effects Development of an introductory particle system To do: Complete Question Clinic Consider if material is of use within your game. Complete section in project document on alpha hand-in Submit alpha Hand-in if desired


Download ppt "Development of a particle system"

Similar presentations


Ads by Google