Search code examples
androidopengl-esegl

EGL context management on Android


I'm developing a painting app using OpenGL and NDK (C++) and I have to write my own EGL context manager. It should manage EGLContext in a different way than the standard GLSurfaceView does, specifically, it should be able to switch between different EGLSurfaces, preserve EGLContext after onPause() and check if some EGL extensions are available before context creation. After reading official EGL documentation, GLSurfaceView's source code and documentation and other articles about EGL some things are still not clear to me.

Can EGLDisplay, initialized before onPause(), get invalidated / lost like EGLContext after onPause()?

EGL documentation states following:

Power management events can occur asynchronously while an application is running. When the system returns from the power management event the EGLContext will be invalidated ... Following a power management event, calls to eglSwapBuffers, eglCopyBuffers, or eglMakeCurrent will indicate failure by returning EGL_FALSE. The error EGL_CONTEXT_LOST will be returned if a power management event has occurred. On detection of this error, the application must destroy all contexts (by calling eglDestroyContext for each context). To continue rendering the application must recreate any contexts it requires, and subsequently restore any client API state and objects it wishes to use.

According to this only EGLContext must be recreated, but GLSurfaceView also reinitializes EGLDisplay. Why?

If EGLDisplay never gets invalidated, is it safe to initialize it only once and save in global variable? Do I need to call eglTerminate() to release such global display prior to process termination to prevent any leaks?


Solution

  • I can tell you I've written an EGLContextFactory as a singleton for GLSurfaceView in which I create a base context and then derive other contexts from it, in order to do multithreaded rendering and share textures. I only get the EGLDisplay once and reuse it throughout the application's lifecycle without problems.

    Moreover, if you look at EGLDisplay's mHandle, you might notice it's always the same (1).