Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Sprite Kit render in the background, or on the main thread? How does it work?

The documentation shows a simplified runloop of Sprite Kit.

I am trying to understand how they implemented it. A SKView calls -update: on a SKScene. This then first evaluates actions, then simulates physics, and lets the subclass adjust the scene. After changes are made to the scene, SKView finally renders the node tree to the screen.

What I don't understand are the fine details. Does Sprite Kit decouple scene calculations from scene rendering by using different threads or GCD queues? Does it perform all the OpenGL rendering calls in the background, or is everything happening on the main thread? At which points is Sprite Kit switching back and forth between background and main thread, and how does it sync processing the scene with rendering the scene then? What happens when your scene updates take too long?

like image 748
openfrog Avatar asked Dec 01 '13 11:12

openfrog


1 Answers

The pie chart in the linked documentation shows the render loop for Sprite Kit. Each part of the loop is executed synchronously on the main thread. The OpenGL rendering is performed by the SKView at the end of the render loop.

Much like any render loop, if the update part takes too long, then the frame time interval is exceeded. This will result in the frame being rendered on the next vsync ie a reduction in frame rate.

The rendering itself is performed just as with GLKit: the render loop is synced to the display refresh rate using a CADisplayLink, with the frameInterval property controlling how many display refreshes there are per render loop. Once the model update is complete, the GL state is then sent to the GPU and [EAGLContext presentRenderbuffer:] is called to display the SKView renderbuffer. The loop is now complete, and won't start again until the display link fires, signalling that the previous frame was rendered and another one can be sent to the screen.

Whether or not the rendering occurs off the main thread is not documented and not possible to know, but it is only an implementation detail. If it did occur on a different thread, then the entire model tree would have to be duplicated in the render thread, or sufficient state so that one frame could be rendered, while the model is updated for the next frame. Most likely it is just synchronous on the main thread. Locking would be fairly pointless, if you are going to prevent the main thread from accessing state until you are done rendering, you might as well just do the rendering on the main thread.

like image 110
Tark Avatar answered Nov 02 '22 02:11

Tark