Stephane-D / SGDK

SGDK - A free and open development kit for the Sega Mega Drive
https://www.patreon.com/SGDK
MIT License
1.75k stars 187 forks source link

JOY_setEventHandler docs should clarify interrupt callback ramifications #142

Closed pinobatch closed 5 years ago

pinobatch commented 5 years ago

The docs for JOY_setEventHandler() in inc/joy.h say "It update controllers state at each V Blank period and fire event if a state change is detected." It doesn't clarify that the call comes from within JOY_update() within _vint_callback. This matters for three reasons: stack use, vblank scheduling, and thread safety.

Stack use

An event handler called from the top level of a program can use practically all of the stack for automatic variables. By contrast, an event handler called from an interrupt handler that runs while a lot of stack is already allocated to functions on the call stack can use only the portion of the stack that said functions are not using.

Vblank scheduling

On a 60 Hz machine, the VDP is using most of memory bandwidth for 224 out of 262 scanlines, leaving 38 scanlines for transferring data to VRAM without bus contention and tearing. If controller reading runs during this time, it could take away VRAM DMA time. I guess this isn't too much of a problem for programs using the DMA queue because _vint_callback calls things in a sane order: XGM, then VRAM DMA queue, then user callback set in SYS_setVIntCallback, then input.

Thread safety

An event handler called from the top level of a program is not running at the same time as other game engine code (AI, physics, graphics, etc.) and can freely read and update game state variables without risking breaking atomicity by reading or writing game state behind the back of a function that does not expect it. By contrast, an event handler called from an interrupt handler can't do much more than queue up events to be handled later, and even the part of the program that reads the queue needs to take care to update in a way that causes the event handler never to see an inconsistent state. This is likely to happen during a "lag frame", a situation in which other game code takes more than 1/60 of a second on a 60 Hz machine or 1/50 of a second on a 50 Hz machine to execute.

Are examples of safe communication between the main program and the input event handler planned? Or a way to drive input by polling within the main thread as opposed to an interrupt?

Stephane-D commented 5 years ago

That is an issue well described !

As i told you in SGDK Discord channel, you have many ways to take care about thread safety. Still to reply your different points:

Hope that help you in understanding the SGDK workflow in general