Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-threaded OpenGL Programming in Cocos2D-iPhone

In an attempt to create a loading bar for an iPhone game I'm developing (using Cocos2D), I wanted to use a multithreaded approach.

One thread shows a loading screen and runs the main application event loop while a new thread silently loads all the Sprites in the background (through spriteWithFile) and then adds them to a layer.

I create the new thread using NSThread's detachNewThreadSelector method (which sends updates of the loading status to the main thread via performSelectorOnMainThread).

The problem I'm facing is that any OpenGL calls (such as those found within the spriteWithFile method) in the new thread die with a BUS ERROR or memory access error of some sort. I'm assuming this is because both threads are attempting to make OpenGL calls at the same time or the new thread is unaware of the OpenGL context.

What has to be done to allow multiple threads to make OpenGL calls on the iPhone using Cocos2D-iPhone.

like image 802
Asad R. Avatar asked Jul 15 '09 18:07

Asad R.


1 Answers

For the record, the new thread needs to execute the following two lines to be able to use the OpenGL API from a concurrent thread:

EAGLContext *k_context = [[[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1 sharegroup:[[[[Director sharedDirector] openGLView] context] sharegroup]] autorelease];
[EAGLContext setCurrentContext:k_context];

This is now made obsolete by the addImageAsync method provided by the TextureMgr class in Cocos2D 0.8.x onwards that does asynchronous texture loading for you.

like image 53
Asad R. Avatar answered Oct 24 '22 18:10

Asad R.