Search code examples
iosnsoperationnsoperationqueueglteximage2d

OpenGL on iOS. Can glTexImage2D be called on a separate thread?


On iOS I have always assume that it is not possible to do OpenGL texture creation - glTexImage2D - on a separate thread via an NSOperation subclass. Can someone please confirm/deny.

Since texture creation potentially hang the GUI - bad! - has anyone come up with a workaround that they are happy with?

Thanks,
Doug


Solution

  • Yes, take a look at CCTextureCache.m in cocos2d for iPhone.

    cocos2d-iphone / cocos2d / CCTextureCache.m

    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
    
    // textures will be created on the main OpenGL context
    // it seems that in SDK 2.2.x there can't be 2 threads creating textures at the same time
    // the lock is used for this purpose: issue #472
    [contextLock_ lock];
    if( auxGLcontext == nil ) {
        auxGLcontext = [[EAGLContext alloc]
                               initWithAPI:kEAGLRenderingAPIOpenGLES1
                               sharegroup:[[[[CCDirector sharedDirector] openGLView] context] sharegroup]];
    
        if( ! auxGLcontext )
            CCLOG(@"cocos2d: TextureCache: Could not create EAGL context");
    }
    
    if( [EAGLContext setCurrentContext:auxGLcontext] ) {
    
        // load / create the texture
        CCTexture2D *tex = [self addImage:async.data];
    
        /* This method calls glTexImage2D. */
    
    
        // The callback will be executed on the main thread
        [async.target performSelectorOnMainThread:async.selector withObject:tex waitUntilDone:NO];        
    
        [EAGLContext setCurrentContext:nil];
    } else {
        CCLOG(@"cocos2d: TetureCache: EAGLContext error");
    }
    [contextLock_ unlock];
    
    [autoreleasepool release];