How to set OpenGL version in either EGL or GLSurfaceView?

Matt J. picture Matt J. · Nov 11, 2011 · Viewed 10.3k times · Source

For the OpenGL Android project I am working on, I need ES 2.0, but I need the control of rendering buffers/surfaces I am accustomed to achieving by using EGL. For I cannot figure out any way to render to an offscreen buffer using GLSurfaceView, and then never displaying the buffer. Even if I use GLSurfaceView.EGLContextFactory, I cannot think of any way to accomplish this without EGL 1.2 functions/constants not included in Android's EGL package (e.g. EGL_CONTEXT_CLIENT_VERSION).

So the first obvious question is: is there a way to either 1) use EGL with ES 2.0 despite the omission of EGL_CONTEXT_CLIENT_VERSION and of eglBindAPI()? 2) is there some new API for setting the rendering context used before GLSurfaceView's callback surfaceCreated(EGLConfig) is called?

Answer

svdree picture svdree · Nov 11, 2011

If you can live with the default EGLContextFactory and EGLConfigChooser, you can use the setEGLContextClientVersion() method of the GLSurfaceView.

Otherwise, if you're writing your own EGLContextFactory and EGLConfigChooser, just define the constants yourself. In the config chooser, define

private static final int EGL_OPENGL_ES2_BIT = 4;

then pass this as the value for EGL_RENDERABLE_TYPE to eglChooseConfig, together with other attributes you desire:

int attribs[] = {
    EGL10.EGL_RED_SIZE,   mRedSize,
    EGL10.EGL_GREEN_SIZE, mGreenSize,
    EGL10.EGL_BLUE_SIZE,  mBlueSize,
    EGL10.EGL_ALPHA_SIZE, mAlphaSize,
    EGL10.EGL_DEPTH_SIZE, mDepthSize,
    EGL10.EGL_SAMPLE_BUFFERS, mSampleBuffers,
    EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
    EGL10.EGL_NONE
};

For the context factory, define

private static final int EGL_CONTEXT_CLIENT_VERSION = 0x3098;

and use this when creating a context:

public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig) 
{
  int[] attrib_list = {
    EGL_CONTEXT_CLIENT_VERSION, 2,
    EGL10.EGL_NONE 
  };

  EGLContext context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list);

  return context;
}

When you've written those, pass them to setEGLContextFactory and setEGLConfigChooser, respectively.