Currently, when opengl es context lost after back from background, cocos2d-x will try to reload all resources as possible. In order to achieve it, we do some complex work in engine:
- reload all programs
- re-create all textures
- re-set all gl state
Then you can see similar codes spread all over the engine:
#if CC_ENABLE_CACHE_TEXTURE_DATA // Listen this event to save render texture before come to background. // Then it can be restored after coming to foreground on Android. auto toBackgroundListener = EventListenerCustom::create(EVENT_COME_TO_BACKGROUND, CC_CALLBACK_1(RenderTexture::listenToBackground, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(toBackgroundListener, this); auto toForegroundListener = EventListenerCustom::create(EVENT_COME_TO_FOREGROUND, CC_CALLBACK_1(RenderTexture::listenToForeground, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(toForegroundListener, this); #endif
And if program or texture is created from raw data, then we should record all the raw data in engine. It will add the memory usage too.
Another solution is to re-start application if the opengl es context lost. This method will simplify the codes, we can remove all codes to recover the states. And may be we can use native activity to prevent missing opengl es context, i am not sure if it works.
pros and cons
Pros and cons of recovering opengl es context:
- application can continue from the point before lost opengl es context
- should add complex logic to recover opengl es context
- increase memory usage
- may not recover all the things
- take a long time to return to foreground if opengl es context lost in background
Pros and cons of re-start application:
- simplify the codes
- reduce memory usage
- will restart application if gl context lost
when opengl es context lost
I don’t find a documentation to mention it. I think it may happen when system resource is limited. And we find it will not happen frequently as we add this line in engine:
I think we can restart application if opengl es context lost, it will simplify and unify the codes. cocos creator use this method now, and not one complain it.
And we will continue to research how to prevent missing opengl es context, native active may be the solution.