HTML and CSS Reference
In-Depth Information
Pool Structure
Listing 3-1 displays the pool recipe for the demo: an array of objects and an array that holds the free objects' indexes.
Listing 3-1. A Simple Object Pool
demo.ParticlePool = function(){
this.elements = []; // will be filled with particles
this.freeElements = new DoublyLinkedList();//hold free particles indices
// Fill the pool
this.grow();
};
As you can see, a linked list holds the free elements' indexes. Free-object pointers are kept in a dedicated data
structure so that the getFree method (see Listing 3-3) will yield a free particle quickly. I prefer using a custom
linked-list class to an array in order to avoid the memory churn that would be caused by using the Array.push() and
Array.pop() methods repeatedly (see Chapter 1): JavaScript is not the language you think it is. For more on linked
lists in JavaScript, visit www.nczonline.net/blog/2009/04/13/computer-science-in-javascript-linked-list .
Recyclable Objects
A recyclable object can look like the one that follows. The important thing to note is that an object can be either alive
or dead, so the game ignores the dead ones.
// Recyclable particle
demo.RecyclableParticle = function(poolindex) {
this._poolindex = poolindex; // used by the pool
this.allocated = false; // true means alive, false means dead
}
Right after creating the pool, you initialize it by filling it with objects (see Listing 3-2). The process of increasing
the number of allocated objects may also be used later in the life of the pool in the event that you run out of free
objects.
Listing 3-2. A Pool Containing Eight Recyclable Objects
demo.ParticlePool.prototype.grow = function( growth ){
growth = growth || demo.settings.rate * 130;
var oldsize = this.elements.length, // previous array size
newsize = oldsize + growth; // size after growth
 
Search WWH ::




Custom Search