Asynchronous texture loading iPhone OpenGL ES 2 -
i'm creating , loading lot of textures (made of strings). keep animation running smoothly, offload work separate worker thread. seems work more or less way want, on older devices (iphone 3gs) notice long (1 sec) lag. occurs sometimes. i'm wondering if i'm doing correctly or if there conceptual issue. paste source code below.
i should mention not want use glkit textureloader because want offload texture generating work other thread, not loading part.
in case you're wondering need these textures for, have @ video: http://youtu.be/u03p4zhljvy?hd=1
nslock* _texturelock; nsmutabledictionary* _textureswithstring; nsmutablearray* _textureswithstringloading; // called when request new texture drawing routine. // if function returns 0, means texture not ready , 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; } // executed on separate worker thread. // lock makes sure there not hundreds of separate threads creating texture @ same time , therefore slowing down. // there must smarter way of doing that. please let me know if 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]; } // callback executed on main thread , marks adds texture texture cache. -(void)doneloadingtexturewithdictionary:(nsdictionary*)_dic{ [_textureswithstring setvalue:[_dic objectforkey:@"texture"] forkey:[_dic objectforkey:@"string"]]; [_textureswithstringloading removeobject:[_dic objectforkey:@"string"]]; }
the problem many threads started @ same time. using nsoperationqueue
rather nsthreads
. allows me set maxconcurrentoperationcount
, run 1 background thread texture loading.
Comments
Post a Comment