extrawurst's blog

#dlang Fibers and a lightweight eventloop

• dlang, gamedev, events, and fibers

###D and Fibers

Fibers are D’s concept for resumable functions and the barebone behind the popular event driven framework vibe.d. In the unecht project I recently added a generic system to use resumable functions much like Unity3D supports it using their coroutine system. In Unity3D a simple usage example is this:

IEnumerator DeferedPrint() {
    Debug.Log("hello");
    yield return new WaitForSeconds(1f);
    Debug.Log("... 1s later");
}
// start the coroutine:
StartCoroutine(DeferedPrint);

The same behaviour in D and unecht looks like this:

void DeferedPrint() {
    writefln("hello");
    UEFibers.yield(waitFiber!"1.seconds");
    writefln("... 1s later");
}
// start the fiber:
UEFibers.startFiber(DeferedPrint);

###Lightweight Eventloop

The eventloop necessary to allow this is simply resuming all active fibers each frame. The main addition to the Fibers in the standard library is that each Fiber can have a child Fiber that has to finish before the parent Fiber can resume. Following code shows a practical example:

@MenuItem("test/deleteAll")
static void removeOnePerX()
{
    UEFibers.startFiber({
            while(ballRoot.sceneNode.children.length > 0)
            {
                UEFibers.yield(waitFiber!"200.msecs");
                removeBall();
            }
        });
}

This way the execution of a single function can be defered over a specific time span. The result of that example is demonstrated here: fibers demo

The whole code of this is available on github here

comments powered by Disqus