Search code examples
iosmultithreadingopengl-escocos2d-iphonerender-to-texture

CCSprite.draw doesn't work on CCRenderTexture in thread (iOS cocos2d 2.0 rc2)


I'm trying to draw onto a CCRenderTexture in a thread. I've got:

EAGLSharegroup *sharegroup = [[[[CCDirector sharedDirector] openGLView] context] sharegroup];
EAGLContext *k_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2 sharegroup:sharegroup];
[EAGLContext setCurrentContext:k_context];

at the beginning of the thread. Everything worked besides CCSprite.draw . I've tested the render texture with:

[rt beginWithClear:1 g:1 b:1 a:1];
[sprite visit];
[rt end];

Calling [CCSprite visit] will not draw the sprite. glGetError returns 0 in all steps.

To further investigate this problem, I put everything in the UI thread, and removed the context calls, I'll see the sprite correctly drawn with the same code. I've also verified that the sprite is correct by adding this sprite to the scene.

And even if I don't use threads, putting the above "context setting calls" will make CCSprite.draw stop working, but only when drawing to a CCRenderTexture. If it's drawing on the screen, it works fine.

Any ideas how to solve this problem? Thanks in advance!


Solution

  • You can only draw on the same thread on which the cocos2d OpenGL view (CCGLView) is created, that's normally the main thread. That's also why the dispatch to the main queue fixes the issue but it also prevents parallel execution of the code in question, since it now is run on the main thread.

    If you want to speed things up by using multiple threads consider parallelizing other algorithms of your app, for example game logic like pathfinding, AI or other critical code paths.