Not long ago I complained on how painful it is to deal with state machines.
With video-games more than some other kind of software, there is a need to run concurrent threads. Multiple tasks that progressively do things over a larger amount of time.
Normally one programs thinking of one routine at the time. The flow of the code is meant to start in the routine and end with it.
I don’t have much time to make a decent example.. I’ll just say that generally one ends up with big switch statements;
Something like:
switch ( state )
{
case IDLE:
break;
case CREATE_CONNECTION:
// …
if ( done )
state = CONNECTING;
break;
case CONNECTING:
// …
if ( done )
state = TRANSMIT;
break;
case TRANSMIT:
// …
if ( done )
state = DISCONNECT;
break;
case DISCONNECT:
// ………
if ( done )
state = IDLE;
break;
}}
Which looks tidy in this example, until one gets into a practical application, with the state machine jumping from one state to another… it can get pretty messy !!!
So, how to simplify all this ? Given the limitation of the language (C/C++).
The solution is pretty simple.. and it comes from the plain old C hacking with the freedom that the language gives, and with the preprocessor. A very low tech solution, far from what one would think.. in this day of age with all those fancy C++ template code.
This hack has a name, it’s called coroutines. A proper explanation can be read at the link provided.
I’m pretty excited about this, but I haven’t had time to really test the usability on relatively complex cases yet.
Almost time to zzzzz !
Posted by Davide Pasca in Uncategorized
