Showing posts with label Jakegr. Show all posts
Showing posts with label Jakegr. Show all posts

Sunday, January 20, 2013

Behavior Tree

I have been experimenting with behavior trees for a bit now, always finding I am over complicating things or that I did not prepare to solve all my needs with them, but the potential exists.

Right now I am working on a flash game along side an artist (I am so glad I don't have to draw) and I implemented an straight forward almost component like behavior system, such as "I give you the draw behavior, therefore you draw".

This was great to start, I didn't put too much thought into it and I ended creating some pretty cool behaviors, like interpolations (much like the tween class in Unity, but not as huge, of course), recycling routines, click events, functions proxy (Delegate like things, but in As3), collision responses, sequences, etc.

The problem was there was no stop at some behavior, once the entity got the behavior there was no way to stop the behavior from happening, since there was no real condition evaluation unless I went out of my way and filled the behavior with possibilities within its routine (which is dirty).

So I created 2 supporting templates that would work together to make my behaviors only fire when the conditions apply.

First, I created a "BaseCondition":


public class BaseCondition implements IBehavior
 {
  static var Head:BaseCondition;
  var Next:BaseCondition;
  var Self:BaseCondition;


The first part explains that this class is the type of IBeahvior (To comply with my Entity IBehavior collection, and to not disturb what was already in place and working properly).

The Head, Next and Self are the elements used to keep this class pooled, if you would like to know more about it please check my previous post here

The IBehavior interface contains 2 functions, Update():void and Recycle():void, pretty simple.

var Condition:ICondition;
  
  public var TrueConditions:Vector.<BaseCondition>
  public var FalseConditions:Vector.<BaseCondition>
  
  public var TrueActions:Vector.<IBehavior>
  public var FalseActions:Vector.<IBehavior>
  
  public function BaseCondition()
  {
   Self = this;
   TrueConditions = new Vector.<BaseCondition>();
   FalseConditions = new Vector.<BaseCondition>();
   TrueActions = new Vector.<IBehavior>();
   FalseActions = new Vector.<IBehavior>();
  }


Then we have a field for the condition, this condition is what makes the base condition unique, depending on this ICondition we will be able to tell what we are looking for, such as "Is this element inside the view frustum?".

Then we have 4 collections, one for the true branch (in case the condition is true, follow up with these conditions), another for the false conditions and 2 more of the true and false actions, meaning that depending on the residing condition in this base condition we will execute either the actions in the true collection or in the false collection, this proves to be very useful as you start evolving your behaviors.

Coming next we have the factory patterns I use, they are essentially the same with one another except for a small difference, this is done for convenience when creating behaviors (to avoid a mess of having to create things, link them and then reuse them).


public static function Create(Condition:ICondition):BaseCondition
  {
   var Vessel:BaseCondition;
   if (Head != null)
   {
    Vessel = Head;
    Head = Head.Next;
   }
   else
   {
    Vessel = new BaseCondition();
   }
   
   Vessel.Condition = Condition;
   
   return Vessel;
  }
  
  public static function CreateRoot(Owner:Entity, Condition:ICondition):BaseCondition
  {
   var Vessel:BaseCondition;
   if (Head != null)
   {
    Vessel = Head;
    Head = Head.Next;
   }
   else
   {
    Vessel = new BaseCondition();
   }
   
   Vessel.Condition = Condition;
   Owner.BehaviorList.push(Vessel);
   
   return Vessel;
  }
  
  public static function CreateTrueBranch(PreviousBranch:BaseCondition, Condition:ICondition)
  {
   var Vessel:BaseCondition;
   if (Head != null)
   {
    Vessel = Head;
    Head = Head.Next;
   }
   else
   {
    Vessel = new BaseCondition();
   }
   
   Vessel.Condition = Condition;
   PreviousBranch.TrueConditions.push(Vessel);
   
   return Vessel;
  }
  
  public static function CreateFalseBranch(PreviousBranch:BaseCondition, Condition:ICondition)
  {
   var Vessel:BaseCondition;
   if (Head != null)
   {
    Vessel = Head;
    Head = Head.Next;
   }
   else
   {
    Vessel = new BaseCondition();
   }
   
   Vessel.Condition = Condition;
   PreviousBranch.FalseConditions.push(Vessel);
   
   return Vessel;
  }


There's nothing really special to tell, if the factory pattern is not really clear to you please read my last post, there I explain my pool system and the factory pattern used in it.

public function Update():void
  {
   if (Condition.CheckCondition())
   {
    var count:int = TrueActions.length;
    for (var i:int = 0; i < count; i++)
    {
     TrueActions[i].Update();
    }
    
    count = TrueConditions.length;
    for (var i:int = 0; i < count; i++)
    {
     TrueConditions[i].Update();
    }
   }
   else
   {
    var count:int = FalseActions.length;
    for (var i:int = 0; i < count; i++)
    {
     FalseActions[i].Update();
    }
    
    count = FalseConditions.length;
    for (var i:int = 0; i < count; i++)
    {
     FalseConditions[i].Update();
    }
   }
  }

And here we have the heart of this behavior tree, where we check the condition and depending on the outcome we will either do the true reaction or false reaction, and follow the proper path in the behavior.
public function Recycle():void
  {
   Next = Head;
   Head = Self;
   
   var count:int = TrueActions.length;
   for (var i:int = 0; i < count; i++)
   {
    TrueActions[i].Recycle();
   }
   
   count = TrueConditions.length;
   for (var i:int = 0; i < count; i++)
   {
    TrueConditions[i].Recycle();
   }
   
   count = FalseActions.length;
   for (var i:int = 0; i < count; i++)
   {
    FalseActions[i].Recycle();
   }
   
   count = FalseConditions.length;
   for (var i:int = 0; i < count; i++)
   {
    FalseConditions[i].Recycle();
   }
   
   TrueActions.length = 0;
   FalseActions.length = 0;
   TrueConditions.length = 0;
   FalseConditions.length = 0;
  }
 
 }
Finally we have our recycle method, pretty essential to my system, we have to make sure to recycle absolutely every single behavior and condition, for reuse. And this concludes the BaseCondition, it is not complicated but we haven't really seen it in action, in order to make this work we require a "ICondition" as well as another "IBehavior" to append to one of the action branches, let's start with the condition:
public class Con_CollidedWith implements ICondition
 {
  static var Head:Con_CollidedWith;
  var Next:Con_CollidedWith;
  var Self:Con_CollidedWith;
  
  var Target:PhysicsComponent; //Contains all the physics info.

  
  public function Con_CollidedWith()
  {
   Self = this;
  }
  
  public static function Create(Target:PhysicsComponent):Con_CollidedWith
  {
   var Vessel:Con_CollidedWith;
   if(Head != null)
   {
    Vessel = Head;
    Head = Head.Next;
   }
   else
   {
    Vessel = new Con_CollidedWith();
   }
   
   Vessel.Target = Target;

   return Vessel;
  }

This is pretty much the same pattern I follow for almost everything that requires to be pooled, in there you can see an object of type of "PhysicsComponent", in there I store variables that represent the entity in the physical world, such as position, body type (Rectangle, poly, circle, etc), a collision list, etc.
  public function CheckCondition():Boolean
  {
   return Target.CollisionList.length > 0;
  }
  
  
  public function Recycle():void
  {
   Next = Head;
   Head = Self;
  }
  
 }
Finally we have the CheckCondition (which is part of the ICondition interface) where I test the condition at hand, in this case if we have something in our collision collection (meaning we have collided with something in the collision phase) it will return true, otherwise false. That concludes an example of a condition, you can create all sort of conditions, you can test if an enemy has certain amount of HP, or if a button has been clicked, etc. Now we move to the last piece of the puzzle, the Action, for this example I will use a function proxy action:
public class Act_ExecuteFunction implements IBehavior
 {
  static var Head:Act_ExecuteFunction;
  var Next:Act_ExecuteFunction;
  var Self:Act_ExecuteFunction;
  
  var Execute:Function;
  
  public function Act_ExecuteFunction()
  {
   Self = this;
  }
  
  public static function Create(Execute:Function):Act_ExecuteFunction
  {
   var Vessel:Act_ExecuteFunction;
   if(Head != null)
   {
    Vessel = Head;
    Head = Head.Next;
   }
   else
   {
    Vessel = new Act_ExecuteFunction();
   }
   
   Vessel.Execute = Execute;
   
   return Vessel;
  }
  
  public function Update():void
  {
   Execute.call();
  }
  
  
  public function Recycle():void
  {
   Execute = null;
   Next = Head;
   Head = Self;
  }
  
 }
As you can see in our Update function (this will only get called if the condition fell in the action branch where this action resided in) we call the function we appended to this action, much like a delegate. But we still don't know how to put all of this together, so allow me to make an example, in my current game there is "Honey" in the air and you require to collide with it in order to acquire it, here is how I make a honey:
public static function CreateHoneyItem(X:Number, Y:Number):void
  {
   var Honey:Entity = Entity.Create(World.InGameGroup);
   var Graphics:GraphicsComponent = GraphicsComponent.Create(Honey, AnimationLibrary.HONEY_GRAPHICS);
   var Physics:PhysicsComponent = PhysicsComponent.Create(Honey, X, Y, PhysicsComponent.ITEM);
   Physics.TurnIntoCircle(16);
   
   var Drawer:B_Draw = B_Draw.CreateOwnerless(1, Graphics, Physics); //gets recycled upon collision by the honey collision response
   
   var Condition_Collision:BaseCondition = BaseCondition.CreateRoot(Honey,Con_CollidedWith.Create(Physics));
   Condition_Collision.TrueActions.push(Act_ExecuteFunction.Create(HoneyCollisionResponse));

}

public static function HoneyCollisionResponse():void
{
    //Do your response here
}


So in order to make a honey I call the factory method for the honey, this will create a honey, and give it's behavior. The behavior says that it will Draw (B_Draw), Also says that if the honey collides with something then execute the function proxy (HoneyCollisionResponse).

There's more behind the scene, such as the collision system, the render system, etc, but it is not hard to get the idea on how the behavior tree works. Using this you can come up with all sort of complex behaviors, but the main issue with this is that they are inflexible upon creation, there won't be learning of AI, it will just run the routine over and over, but that doesn't have to be that way, there are methods to make this work the way you want to, implementing weight based decisions instead of just conditionals could be a way, there's a lot of things that can be implementing using this Behavior Tree pattern, but that would be another post for another time.

Wednesday, January 16, 2013

Final pool version

Since I went from C# to AS3 in order to complete web games I realized that the lack of generics in AS3 was going to be a huge problem for my pooling system, this forced me to think things once again and the result was something more elegant, secure and completely contained within the pooled class.

Making use of the factory design pattern once again I was able to create a pool system within the same class (which is now a template in my IDE), here is how it goes:

public class PooledItem
{
   private static var PoolHead:PooledItem;
   private var Next:PooledItem;
   private var Self:PooledItem;

   public function PooledItem()
   {
      Self = this;
   }

   public static function Create():PooledItem
   {
      var Vessel:PooledItem;
      if(PooledHead != null)
      {
         Vessel = PoolHead;
         PoolHead = PoolHead.Next;
      }
      else
      {
         Vessel = new PooledItem();
      }
      
      return Vessel;
   }
}


The PoolHead is private and static, making it unique locally and impossible to access from outside this class, then we have the Next and the Self which are unique to each instance of the PooledItem, and finally we have a factory pattern which creates a new instance of a PooledItem if the head is null, but if the head is not null it will return it and set the new head as the next element in the queue.

One thing to have in mind is that AS3 does not allow to have private constructors, thus making it possible to create an instance of the PooledItem without the factory method, if this happens and you don't properly get rid of it by calling its recycle method then you will have an extra element (outside the pool) doing nothing, but even if you create it without the "create" function you can still put it back in the pool by calling recycle, so no real harm done if handled properly, still if this was not AS3 I would make the constructor private.

Going to the recycle function now, the recycle function is where I do all my clean up code (if required depending on the elements of the class) as well as to put elements back into the pool:

public function Recycle():void
{
   //Do clean up code, maybe recycle other pooled items that were created within this
   //class or release references of an element to let GC deal with it, etc.

   Next = PoolHead; //we set the next element as the current head.
   PoolHead = Self; //and finally we set the this element as the new head.
}


And that's it, it is amazing how essential and memory friendly this can be, allocating memory and deallocating memory can be very tasking in the system, specially if you are planning on putting your games in mobile devices, have in mind also that the more memory you use the more battery it might consume, so in order to have some balance make sure to maintain your pools, this can be achieve by an internal reference counter and releasing some of them if the number gets to a certain point, however you want to handle that I will leave to you.


Friday, October 19, 2012

Intrusive linked node

Dealing with large number of objects can be tasking, specially in games, traditionally we have our objects living in some sort of collection, and then we traverse this collection to perform a task (like Update() or Draw()).

Collections work amazingly, traditionally I seen that the generic List is used the most, I use them often, but I stopped using them to managed my objects, simply because of how slow and tasking the "Remove()" function was, let me explain this:

when you have a collection of 10 elements in a List, and you decide to remove element 4, you would have to shift the following 6 elements down a slot to keep the list continuous, since the list is just a glorified "array", this can be very expensive, imagine if you were to remove element 1 in a list that contains 10,000 elements, not fun.

Linked list in the other hand do a much nicer job for removing elements, since they know what's next and what was previously, I would suggest to use linked list when you don't need to access an specific element in a collection, linked list do not work nicely when trying to "find" things inside them, because they are not indexed, you would have to check from start to end for an element using some comparison check on every single element, not fun.

Currently in my game, I use my own "collections" which are very specific, I have an "Actor Node" which takes care of the actors, like this:

public class ActorNode
    {
        public IActor Subject;
        public ActorNode SelfReference;
        public ActorNode NextActor;
        public ActorNode PreviousActor;

        public static ActorNode Head;

        public ActorNode(IActor subject)
        {
            SelfReference = this;
            Subject = subject;
        }

        public void Activate()
        {
            if (Head != null)
            {
                Head.PreviousActor = SelfReference;
                NextActor = Head;
            }
            Head = SelfReference;
        }

        public void Deactivate()
        {
            if (PreviousActor == null) //check for head
            {
                if (NextActor != null)
                {
                    Head = NextActor;
                    NextActor.PreviousActor = null;
                }
                else
                {
                    Head = null;
                }
            }
            else
            {
                if (NextActor != null) //check for tail
                {
                    NextActor.PreviousActor = PreviousActor;
                    PreviousActor.NextActor = NextActor;

                    NextActor = null;
                    PreviousActor = null;
                }
                else
                {
                    PreviousActor.NextActor = null;
                }
            }

            PreviousActor = null;
            NextActor = null;
        }
    }


This Node is a "component" of my actors, meaning that they live inside my actor class, using my factory design pattern (check last post for reference) I easily activate them, and using my Recycle method (also last post) I deactivate them before returning them to the pool, like this:

public class AnActor: PooleanNode<AnActor>, IActor, Irecycle
{
    LinkedPoolean<AnActor> Pool = new LinkedPoolean<AnActor>();
    
    ActorNode ActorLink;    

    public AnActor()
    {
        ActorLink = new ActorNode(this);
    }

    public static void Create()
    {   
        AnActor Vessel;
        Pool.Get(out Vessel);
        Vessel.ActorLink.Activate(); //Activates the node so it is in the collection
    }

    public void Recycle()
    {
        ActorLink.Deactivate(); //deactivates the node so it is taken out.
        Pool.ReturnPoolable(this);
    }
}


Now, let's assume that the "IActor" interface contains a method called "Update()", we can use this collection to update all the currently activated actors like this:

public static void UpdateAll() //function that updates all the actors
{
     ActorNode Current = ActorNode.Head; //gets the current head
     if(Current == null) //make sure there are elements in the collection
     {
         return; //if there's nothing, then get out.
     }
     IActor CurrentActor; //container for the current subject that needs to update

     do
     {
          CurrentActor = Current.Subject; //get the first subject
          
          CurrentActor.Update(); //Update it and then

          Current = Current.NextActor; //check for the next node

     } while (Current != null); //and if that node is not null, then repeat.
}

That function will make sure that all the activated nodes will update.

Thanks for reading.







My Factory Design Pattern

I will talk a bit about how I create my "Game objects".

The first thing you need to know is that I do not use the keyword "New" to instantiate a new object, this is because I need to have control over my game objects (coming from the pools), Let's create a quick example, I am going to assume that you know about my pool system, but if you don't please take a look at the previous post.

We will start with the body of the class.

public class Slime: PooleanNode<Slime> 
{
    static LinkedPoolean<Slime> Pool = new LinkedPoolean<Slime>();

    public Slime()
    {
    }
}

Here we have declared a "Slime class" that can be pooled with my pool class, as you can see the constructor is public so we can instantiate them with the activator class, also there's a static pool of slimes living inside this class, this will mean that in every single slime object you will have access to the same pool, this is important cause all the slimes need to come from the pool, now moving into the "creational" method.

public static Slime Create() //this function must live inside the slime class.
{
    Slime Vessel;
    Pool.Get(out Vessel); //if it doesn't live inside the class, the pool wouldn't be
    return Vessel;        //visible, you would have to make it public and access it
}                         //like "Slime.Pool", I don't recommend that. 

And done, we have create an static method that will take slimes out of the pool and return them, simple as that! now for some logic on why I do this, by making a new slime this way I make sure they come from the pool and that they are not generated outside of the pool, this is handy when we want to manage them and when we want to avoid tasking the garbage collector, since we are not allocating new memory.

Now let's expand on it, to make it useful, you can declare multiple creation methods to obtain different results, let's say that the Slime has some fields like position or maybe current hit points, etc, we can modify these elements like this:

public class Slime: PooleanNode<Slime> 
{
    static LinkedPoolean<Slime> Pool = new LinkedPoolean<Slime>();

    Vector2 Position;
    int HP;

    public Slime()
    {
        Position = Vector2.Zero;
        HP = 1;
    }

    public static Slime Create(Vector2 Position, int HP) 
    {
        Slime Vessel;
        Pool.Get(out Vessel); 
        Vessel.Position = Position;
        Vessel.HP = HP;
        return Vessel;       
    } 
}

By default the slime starts at position 0,0 and with 1 HP, but we can create any slime anywhere we want as well as giving it any amount of HP we want, we can create more methods to define things ever further.

Lastly I define a recycle method that I use when I need to get rid of the object and sent it back to the pool, like this:

public void Recycle()
{
    Pool.ReturnPoolable(this);
}

That makes sure that the object is sent back into the pool to be reused by the factory method, this is an overly simplified version of what I use in my current game, if you would like to check the game out, here:

Game

Thanks for reading!

Monday, October 15, 2012

Taking casting out of the picture

Once again! I have done another revision to the way I am doing pools, it is almost like an obsession, in any case, it has proven to be fantastic, onto the code:

public class LinkedPoolean<T> where T : PooleanNode<T>, new()
    {
        public T Head;

        public LinkedPoolean()
        {
            Head = Activator.CreateInstance<T>();
        }

        public void Get(out T Vessel)
        {
            if (Head != null)
            {
                Vessel = Head;
                Head = Head.Next;
            }
            else
            {
                Vessel = Activator.CreateInstance<T>();
            }
         
        }

        public void ReturnPoolable(T Return)
        {
            Return.Next = Head;
            Head = Return;
        }
    }

The Key change here is the way we access the "Activator", you see, there's a function to create an instance that takes a Generic parameter T, and there's another version of the function that takes an argument "Type" and returns an "Object", the object returned by the second function is sadly not the right type, so in order to use it I used to cast it, this would create a hit on the performance. The function that takes a parameter of type T returns an object of type T, making casting unnecessary.

This improvement was only possible though if the PooleanNode knew which "kind of poolean node" it was, new Poolean node class:

public class PooleanNode<T> where T: PooleanNode<T>
    {
        public T Next;
    }


This in turn makes the poolean node type safe, before hand it was potentially possible to subscribe a poolean node into a pool of another type, it was kind of weird at the beginning to see a class expecting itself to be the template, but it is kind of cool the way it works.

Thanks for reading~

Friday, September 21, 2012

The Pooling Redo

I can't believe that I first attempted to make a proper pool back in April, that's only 6 months ago! I learned so much and looking back I feel dumb, but that's the main purpose of this blog! I like to check out my learning curve.

Anyways, to the pools, not too long ago I read about intrusive lists and how they were awesome for managing your game objects, before that my take on recursions were weird as well, I abandon the method and just made a while loop scanning of the nodes to traverse the tree, so no more recursion because the Xbox hates you using memory!

My last revision on the pool was cool, managed and it served it's purpose pretty well, but then I read about recursive lists and I thought that I could use something like that in the pool, a linked list pretty much but instead of using the built in linked list I wanted to make the nodes of the pool the actual objects and not a sub object attached to a node.

public class LinkedPoolean<t> where T : PooleanNode, new()
    {
       Type TypeOfT;

        T Head;

        public LinkedPoolean()
        {
            TypeOfT = typeof(T);
            Head = (T)Activator.CreateInstance(TypeOfT);
        }

        public void Get(out T Vessel)
        {
            if (Head != null)
            {
                Vessel = Head;
                Head = (T)Head.Next;
            }
            else
            {
                Vessel = (T)Activator.CreateInstance(TypeOfT);
            }
        }

        public void ReturnPoolable(T Return)
        {
            Return.Next = Head;
            Head = Return;
        }
    }

The thing to note here is that it is so ridiculous simple in comparison to my first attempt, and I was thinking that the last attempt was short! now, in this case I made the "PooleanNode" a base class cause it bugs me to know that I would have to use a "Property" to fetch a single field (which is all that class has in it as for now), but if that doesn't bother you then you may as well make the class an interface.

Poolean class:

public class PooleanNode
    {
        public PooleanNode Next;
    }

Well more weird things will result out of this, I am going to be changing quite a bit of things in my engine, because this method it is not just about 10 times faster and more memory friendly but it is also a good design.

Saturday, August 18, 2012

Recursion

I have heard a lot about how recursion is bad, and why we should use collections instead and that collections are faster/safer, I believe it, but recursion has it's moments when it proves to be more useful than collections.

When you have that typical scenario of nodes, with one child and one parent (or many of both, etc) and then you call a function that calls the same function of either the parent of the child, that's a recursive function call, it will iterate all the elements that satisfy the criteria, such as "Draw all the children of this node", then we call draw on the parent, and the parent call draw on the children, etc.

What I think is bad about recursion is when the function being used recursively needs to pass arguments to be further tested down the line of nodes, or when the function itself returns a value to be processed by the parent, this is bad simply because we need to allocate memory for as long the functions we are using are alive (memory in the stack), for example if a parent node needs to count all it's children it could send an int by reference down the line and tell the children to add one or the children could return an int that's equal to the current number + 1, the stack wont release memory until the functions are finalized.

This could be avoid nevertheless, if you must have something to be analyzed down the line then you could make use of a "static" variable, that means you just need to set that variable once and all the nodes will know about it (a local static variable), that means you are not really allocating memory per call, just looking at memory already available to you.

I used recursion to add new elements to my drawing sorting, this proved to be quite fast and efficient, so instead of using a collection I used a node system that holds an "IDrawSorted" type of object and calls draw on it whenever the parent node needs to draw, code example:

public class SortingNode
    {
        public static SortingNode TopParent;
        static Poolean NodePool = new Poolean(1000, 100);
        public static SortingNode FindingAPlace;

        public SortingNode Child;
        public SortingNode Parent;
        public IDrawSorted Drawer;
        public int Z;

In the fields we have 2 static variables, one for the node that is being analyzed and another one for the current top parent, this node class is also pooled, take a look at my previous post to know about how the Poolean class works. After that you can see that the node can contain a child and a parent, as well as the information of the IDraw (The actual drawing object and it's Z position for Z sorting).

public static void Create(out SortingNode Vessel)
        {
            NodePool.Get(out Vessel);
        }

As a rule I never ever use "new" in my code design, simply because using new on objects can cause memory leaks, so all my objects are properly managed, using factory pattern methods to get "instantiated" since they really are not being created on the fly, they already live in a pool.

public void Add()
        {
            if (FindingAPlace.Z <= Z)
            {
                if (Child != null)
                {
                    Child.Add();
                }
                else
                {
                    Child = FindingAPlace;
                    FindingAPlace.Parent = this;
                }
            }
            else
            {
                if (Parent == null)
                {
                   //if a node has no parent, it is the head.
                    TopParent = FindingAPlace;
                    FindingAPlace.Child = this;
                    Parent = FindingAPlace;
                }
                else
                {
                    Parent.Child = FindingAPlace;
                    FindingAPlace.Child = this;
                    FindingAPlace.Parent = Parent;
                    Parent = FindingAPlace;
                }
            }
            FindingAPlace = null;
        }
So, this is a recursion function, as you can see it does not take any arguments and it returns nothing, so prior to call this function the information you want to analyze has to be pre loaded to the static variable inside the class, this is accomplished by accessing them by "SortingNode.FindingAPlace = YourDrawer;", this way we only set it once, and then send it to analyze. In this function we are looking if the current Z value we are passing through the static IDrawSorted is smaller or equal to the current's IDrawSorted living in the node, we will check if it has a child in the event that it is smaller or equal, so we further test down the line until we find a place were to place this new node, this is faster than a normal collection simply because I do not need to change or push down all the resting elements down the line by one because if we need to insert something in between the line we simply just change the references pointing to the parents and children to of the new node.
public void Draw()
        {
            if (Child != null)
            {
                Child.Draw();
            }
            Drawer.Draw();
        }
Recursively calling draw on every children, this is a secondary function.
public void StartDrawing()
        {
            if (Parent != null)
            {
                Parent.StartDrawing();
            }
            else
            {
                Draw();
            }
        }
this is the the entry point to the drawing class, I do it this way in case that the node that called "StartDrawing" might not be the current top node, therefore we need to find the top node to start calling draw.
public void Recycle()
        {
            if (Child != null)
            {
                Child.Parent = null;
                Child.Recycle();
            }
            Child = null;
            NodePool.ReturnPoolable(this);
        }

    }


Finally we have a recycle method to put the entire collection back into the pool when we don't need it anymore.




And that concludes my recursion method and how I use them to sort my drawing, this is working nicely in the Xbox. Currently I am working on an Xbox title because I am waiting for the new Windows phone 8 to come out as well as the new Visual Studio, once that's out I will be porting all my code to C++.