Wednesday, April 21, 2010

C#: Fibers

In the previous post, we looked briefly at the uses for fibers in relation to game code. Let's look at what this looks like in C# using yield, IEnumerable, and lambda expressions. We will need a CFiberManager class which handles updating and launching our fibers.

First we will examine the user code interface  we want to attain before we look at the whole implementation. We will make a sound player Play() function which only allows us to play a sound once every N frames.

// sound system example
public void Play(string name)
  if (registry.HasKey(name))

  SoundEffect sound = Content.Load(name);
  registry[name] = sound;

  int WaitFrames = 4;

  Fibers.Fork(() => {
            while (WaitFrames-- > 0)
                yield return WaitFrames;

Here we play a sound, and then add it to a registry which will prevent playing the same sound until 4 frames later. It would be good to also add some counts for tracking concurrent playing sounds, as well as minimum spacing to ensure the sound does not get spammed in certain gameplay situations, and to just sound 'right' with regards to spacing, even when lots of entities attempt to play a sound in a short time.

Here we can see the implementation of the Fiber manager:

Maybe one day we can see some nicer language support for fibers in C# without resorting to this IEnumerable trick!

No comments:

Post a Comment