簡體   English   中英

異步紋理加載iPhone OpenGL ES 2

[英]Asynchronous texture loading iPhone OpenGL ES 2

我正在創建和加載大量紋理(由字符串組成)。 為了使動畫順利運行,我將工作卸載到單獨的工作線程。 它似乎或多或少地按照我想要的方式工作,但在舊設備(iPhone 3GS)上,我有時會注意到很長(1秒)的延遲。 它有時只會發生。 現在我想知道我是否正確地做了這個或者是否存在任何概念問題。 我粘貼下面的源代碼。

我還要提一下,我不想使用GLKit TextureLoader,因為我還想將紋理生成工作卸載到另一個線程,而不僅僅是加載部分。

如果你想知道我需要這些紋理,看看這個視頻:http: //youtu.be/U03p4ZhLjvY?hd = 1

NSLock*                     _textureLock;
NSMutableDictionary*        _texturesWithString;
NSMutableArray*             _texturesWithStringLoading;

// This is called when I request a new texture from the drawing routine. 
// If this function returns 0, it means the texture is not ready and Im not displaying it.

-(unsigned int)getTextureWithString:(NSString*)string {
    Texture2D* _texture = [_texturesWithString objectForKey:string];
    if (_texture==nil){
        if (![_texturesWithStringLoading containsObject:string]){
            [_texturesWithStringLoading addObject:string];
            NSDictionary* dic = [[NSDictionary alloc] initWithObjectsAndKeys:string,@"string", nil];
            NSThread* thread = [[NSThread alloc] initWithTarget:self selector:@selector(loadTextureWithDictionary:)object:dic];
            thread.threadPriority = 0.01;
            [thread start];
            [thread release];
        }
        return 0;
    }
    return _texture.name;
}

// This is executed on a separate worker thread.
// The lock makes sure that there are not hundreds of separate threads all creating a texture at the same time and therefore slowing everything down. 
// There must be a smarter way of doing that. Please let me know if you know how! ;-)
-(void)loadTextureWithOptions:(NSDictionary*)_dic{
    [_textureLock lock];
    EAGLContext* context = [[SharegroupManager defaultSharegroup] getNewContext];
    [EAGLContext setCurrentContext: context];

    NSString* string = [_dic objectForKey:@"string"];
    Texture2D* _texture = [[Texture2D alloc] initWithStringModified:string];

    if (_texture!=nil) {
        NSDictionary* _newdic = [[NSDictionary alloc] initWithObjectsAndKeys:_texture,@"texture",string,@"string", nil];
        [self performSelectorOnMainThread:@selector(doneLoadingTexture:) withObject:_newdic waitUntilDone:NO];
        [_newdic release];
        [_texture release];
    }
    [EAGLContext setCurrentContext: nil];
    [context release];
    [_textureLock unlock];
}

// This callback is executed on the main thread and marks adds the texture to the texture cache. 
-(void)doneLoadingTextureWithDictionary:(NSDictionary*)_dic{
    [_texturesWithString setValue:[_dic objectForKey:@"texture"] forKey:[_dic objectForKey:@"string"]];
    [_texturesWithStringLoading removeObject:[_dic objectForKey:@"string"]];
}

問題是同時啟動了太多線程。 現在我使用的是NSOperationQueue而不是NSThreads 這允許我設置maxConcurrentOperationCount並且只運行一個額外的后台線程來執行紋理加載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM