Posted December 15, 2023 by Klaim
#c++ #fsm #open-source #github #metaprogramming
This week I was supposed to setup a failure strategy and logging system but before that I wanted to quickly implement the most basic game states: having a title screen, going into the game, getting back to the title screen and having a settings screen openable from about everywhere. To achieve that I needed to use a finite state machine library and as mentionned last weeks and in livestreams while prototyping, I was not completely happy with the ones I have available for C++. So I decided to go with a custom one, to have the exact set of features I need.
It took most of the week’s spare time. I also had a ton of work with music and dayjob so as I’m writing this I’m completely exhausted, I’ll try to make it quick.
The FSM code is currently very runtime-efficient, because… well there is almost no runtime code, it’s all hardcore metaprogramming generic nunchucks. It have been a few years when I had an opportunity to get back to puerely generic programming for this kind of tools. It works, or at least my tests works. The thing allows to specify a table of transition statically, which also allows to easilly generate the state instances and will call their entrance and exit member functions if they exist, as expected. Providing an incorrect (as in “it makes no sense” or “there is duplicat transitions in there”) transition table will not compile, providing states that doesnt support how they are handled through the state machine usage either. You can, but are not forced, access the interface of every state without having any runtime cost (no inheritance or anything remotely close) and it basically takes no space other than a tuple of the different states. I’m quite happy with the result. As of now it is usable to continue with the game-specific code and can be used also in smaller contexts like in the behavior of some enties.
There is however some missing features, but they are not necessary to add immediately:
So this weekend I’ll setup quickly this time the 3 screens I want, driven by such state machine, and proceed with the other “seems simple enough but will take days” stuffs.
Hopefully I can focus on game-land code next week. At least that’s the plan.