Tasks, schedules and priorities

Here we are with another rather technical update! Last time I was posting some information about how I want to get more diversity into the game graphics by switching parts of the character set on the fly while the player moves through the world. That actually raised an interesting new problem: how to handle tasks with different priorities!

Up to now there were only two possible priorities: tasks that need to be done during the currently displayed frame (like color RAM scrolling or inserting new characters at the border of the screen) and tasks that only need to be finished eventually during the next frames (like scrolling the currently invisible double buffer or checking for trigger areas for events). The character set swapping adds another priority: in theory it can take quite long and there is no need to have it finished in the next 2-3 frames, it is ok even if it takes e.g. 10 frames or so. Instead of patching this into the existing engine I decided to do it right from the start and be prepared for any upcoming additional tasks.  Which means: implement a task scheduler!

clocks-1098080_640

What does a task scheduler do? It makes sure, that most of the processor time is spent on the tasks with the highest priority. I simplified the concept a bit, so that higher priority tasks are always finished before lower priority tasks are continued. The implementation is actually simple, although there is some mean stack fiddling involved and it needed a bit of head scratching until I got it right. The interface of the scheduler module has only two routines: task_add, which adds a new task with a given priority and might switch to it immediately (if it is the highest priority), and task_done, which is called by a task when it is done and selects the next highest priority task to be executed.  All that is needed is to modify the stack such, that the RTI instruction at the end of the interrupt routine jumps to the right task. Apologies for the clumsy block diagram trying to depict this with an example. Did I mention that I am not a graphician?

In any case: implementation is done and unit tests are passing (yay!), so I am looking forward to put this new module into good use!