Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright (C) 2008 The Android Open Source Project
    *
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    *
    *      http://www.apache.org/licenses/LICENSE-2.0
    *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  package android.opengl;
  
  import java.io.Writer;
  
  
  import android.util.Log;
An implementation of SurfaceView that uses the dedicated surface for displaying OpenGL rendering.

A GLSurfaceView provides the following features:

  • Manages a surface, which is a special piece of memory that can be composited into the Android view system.
  • Manages an EGL display, which enables OpenGL to render into a surface.
  • Accepts a user-provided Renderer object that does the actual rendering.
  • Renders on a dedicated thread to decouple rendering performance from the UI thread.
  • Supports both on-demand and continuous rendering.
  • Optionally wraps, traces, and/or error-checks the renderer's OpenGL calls.

Using GLSurfaceView

Typically you use GLSurfaceView by subclassing it and overriding one or more of the View system input event methods. If your application does not need to override event methods then GLSurfaceView can be used as-is. For the most part GLSurfaceView behavior is customized by calling "set" methods rather than by subclassing. For example, unlike a regular View, drawing is delegated to a separate Renderer object which is registered with the GLSurfaceView using the setRenderer(android.opengl.GLSurfaceView.Renderer) call.

Initializing GLSurfaceView

All you have to do to initialize a GLSurfaceView is call setRenderer(android.opengl.GLSurfaceView.Renderer). However, if desired, you can modify the default behavior of GLSurfaceView by calling one or more of these methods before calling setRenderer:

Specifying the android.view.Surface

By default GLSurfaceView will create a PixelFormat.RGB_565 format surface. If a translucent surface is required, call getHolder().setFormat(PixelFormat.TRANSLUCENT). The exact format of a TRANSLUCENT surface is device dependent, but it will be a 32-bit-per-pixel surface with 8 bits per component.

Choosing an EGL Configuration

A given Android device may support multiple EGLConfig rendering configurations. The available configurations may differ in how may channels of data are present, as well as how many bits are allocated to each channel. Therefore, the first thing GLSurfaceView has to do when starting to render is choose what EGLConfig to use.

By default GLSurfaceView chooses a EGLConfig that has an RGB_656 pixel format, with at least a 16-bit depth buffer and no stencil.

If you would prefer a different EGLConfig you can override the default behavior by calling one of the setEGLConfigChooser methods.

Debug Behavior

You can optionally modify the behavior of GLSurfaceView by calling one or more of the debugging methods setDebugFlags(int), and setGLWrapper(android.opengl.GLSurfaceView.GLWrapper). These methods may be called before and/or after setRenderer, but typically they are called before setRenderer so that they take effect immediately.

Setting a Renderer

Finally, you must call setRenderer(android.opengl.GLSurfaceView.Renderer) to register a GLSurfaceView.Renderer. The renderer is responsible for doing the actual OpenGL rendering.

Rendering Mode

Once the renderer is set, you can control whether the renderer draws continuously or on-demand by calling setRenderMode(int). The default is continuous rendering.

Activity Life-cycle

A GLSurfaceView must be notified when the activity is paused and resumed. GLSurfaceView clients are required to call onPause() when the activity pauses and onResume() when the activity resumes. These calls allow GLSurfaceView to pause and resume the rendering thread, and also allow GLSurfaceView to release and recreate the OpenGL display.

Handling events

To handle an event you will typically subclass GLSurfaceView and override the appropriate method, just as you would with any other View. However, when handling the event, you may need to communicate with the Renderer object that's running in the rendering thread. You can do this using any standard Java cross-thread communication mechanism. In addition, one relatively easy way to communicate with your renderer is to call queueEvent(java.lang.Runnable). For example:

 class MyGLSurfaceView extends GLSurfaceView {

     private MyRenderer mMyRenderer;

     public void start() {
         mMyRenderer = ...;
         setRenderer(mMyRenderer);
     }

     public boolean onKeyDown(int keyCode, KeyEvent event) {
         if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
             queueEvent(new Runnable() {
                 // This method will be called on the rendering
                 // thread:
                 public void run() {
                     mMyRenderer.handleDpadCenter();
                 }});
             return true;
         }
         return super.onKeyDown(keyCode, event);
     }
 }
 
 
 public class GLSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
     private final static boolean LOG_THREADS = false;
     private final static boolean LOG_PAUSE_RESUME = false;
     private final static boolean LOG_SURFACE = false;
     private final static boolean LOG_RENDERER = false;
     private final static boolean LOG_RENDERER_DRAW_FRAME = false;
     private final static boolean LOG_EGL = false;
     // Work-around for bug 2263168
     private final static boolean DRAW_TWICE_AFTER_SIZE_CHANGED = true;
    
The renderer only renders when the surface is created, or when requestRender() is called.

 
     public final static int RENDERMODE_WHEN_DIRTY = 0;
    
The renderer is called continuously to re-render the scene.

 
     public final static int RENDERMODE_CONTINUOUSLY = 1;

    
Check glError() after every GL call and throw an exception if glError indicates that an error has occurred. This can be used to help track down which OpenGL ES call is causing an error.

 
     public final static int DEBUG_CHECK_GL_ERROR = 1;

    
Log GL calls to the system log at "verbose" level with tag "GLSurfaceView".

 
     public final static int DEBUG_LOG_GL_CALLS = 2;

    
Standard View constructor. In order to render something, you must call setRenderer(android.opengl.GLSurfaceView.Renderer) to register a renderer.
 
     public GLSurfaceView(Context context) {
         super(context);
         init();
     }

    
Standard View constructor. In order to render something, you must call setRenderer(android.opengl.GLSurfaceView.Renderer) to register a renderer.
 
     public GLSurfaceView(Context contextAttributeSet attrs) {
         super(contextattrs);
         init();
     }
 
     private void init() {
         // Install a SurfaceHolder.Callback so we get notified when the
         // underlying surface is created and destroyed
         SurfaceHolder holder = getHolder();
         holder.addCallback(this);
         // setFormat is done by SurfaceView in SDK 2.3 and newer. Uncomment
         // this statement if back-porting to 2.2 or older:
         // holder.setFormat(PixelFormat.RGB_565);
         //
         // setType is not needed for SDK 2.0 or newer. Uncomment this
         // statement if back-porting this code to older SDKs.
         // holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
     }

    
Set the glWrapper. If the glWrapper is not null, its GLSurfaceView.GLWrapper.wrap(javax.microedition.khronos.opengles.GL) method is called whenever a surface is created. A GLWrapper can be used to wrap the GL object that's passed to the renderer. Wrapping a GL object enables examining and modifying the behavior of the GL calls made by the renderer.

Wrapping is typically used for debugging purposes.

The default value is null.

Parameters:
glWrapper the new GLWrapper
 
     public void setGLWrapper(GLWrapper glWrapper) {
          = glWrapper;
     }

    
Set the debug flags to a new value. The value is constructed by OR-together zero or more of the DEBUG_CHECK_* constants. The debug flags take effect whenever a surface is created. The default value is zero.

Parameters:
debugFlags the new debug flags
See also:
DEBUG_CHECK_GL_ERROR
DEBUG_LOG_GL_CALLS
 
     public void setDebugFlags(int debugFlags) {
          = debugFlags;
     }

    
Get the current value of the debug flags.

Returns:
the current value of the debug flags.
 
     public int getDebugFlags() {
         return ;
     }

    
Set the renderer associated with this view. Also starts the thread that will call the renderer, which in turn causes the rendering to start.

This method should be called once and only once in the life-cycle of a GLSurfaceView.

The following GLSurfaceView methods can only be called before setRenderer is called:

The following GLSurfaceView methods can only be called after setRenderer is called:

Parameters:
renderer the renderer to use to perform OpenGL drawing.
 
     public void setRenderer(Renderer renderer) {
         checkRenderThreadState();
         if ( == null) {
              = new SimpleEGLConfigChooser(true);
         }
         if ( == null) {
              = new DefaultContextFactory();
         }
         if ( == null) {
              = new DefaultWindowSurfaceFactory();
         }
          = new GLThread(renderer);
         .start();
     }

    
Install a custom EGLContextFactory.

If this method is called, it must be called before setRenderer(android.opengl.GLSurfaceView.Renderer) is called.

If this method is not called, then by default a context will be created with no shared context and with a null attribute list.

 
     public void setEGLContextFactory(EGLContextFactory factory) {
         checkRenderThreadState();
          = factory;
     }

    
Install a custom EGLWindowSurfaceFactory.

If this method is called, it must be called before setRenderer(android.opengl.GLSurfaceView.Renderer) is called.

If this method is not called, then by default a window surface will be created with a null attribute list.

 
     public void setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory factory) {
         checkRenderThreadState();
          = factory;
     }

    
Install a custom EGLConfigChooser.

If this method is called, it must be called before setRenderer(android.opengl.GLSurfaceView.Renderer) is called.

If no setEGLConfigChooser method is called, then by default the view will choose an EGLConfig that is compatible with the current android.view.Surface, with a depth buffer depth of at least 16 bits.

Parameters:
configChooser
 
     public void setEGLConfigChooser(EGLConfigChooser configChooser) {
         checkRenderThreadState();
          = configChooser;
     }

    
Install a config chooser which will choose a config as close to 16-bit RGB as possible, with or without an optional depth buffer as close to 16-bits as possible.

If this method is called, it must be called before setRenderer(android.opengl.GLSurfaceView.Renderer) is called.

If no setEGLConfigChooser method is called, then by default the view will choose an RGB_565 surface with a depth buffer depth of at least 16 bits.

Parameters:
needDepth
 
     public void setEGLConfigChooser(boolean needDepth) {
         setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth));
     }

    
Install a config chooser which will choose a config with at least the specified depthSize and stencilSize, and exactly the specified redSize, greenSize, blueSize and alphaSize.

If this method is called, it must be called before setRenderer(android.opengl.GLSurfaceView.Renderer) is called.

If no setEGLConfigChooser method is called, then by default the view will choose an RGB_565 surface with a depth buffer depth of at least 16 bits.

 
     public void setEGLConfigChooser(int redSizeint greenSizeint blueSize,
             int alphaSizeint depthSizeint stencilSize) {
         setEGLConfigChooser(new ComponentSizeChooser(redSizegreenSize,
                 blueSizealphaSizedepthSizestencilSize));
     }

    
Inform the default EGLContextFactory and default EGLConfigChooser which EGLContext client version to pick.

Use this method to create an OpenGL ES 2.0-compatible context. Example:

     public MyView(Context context) {
         super(context);
         setEGLContextClientVersion(2); // Pick an OpenGL ES 2.0 context.
         setRenderer(new MyRenderer());
     }
 

Note: Activities which require OpenGL ES 2.0 should indicate this by setting

Parameters:
version The EGLContext client version to choose. Use 2 for OpenGL ES 2.0
Lt:
uses-feature android:glEsVersion="0x00020000" /> in the activity's AndroidManifest.xml file.

If this method is called, it must be called before setRenderer(android.opengl.GLSurfaceView.Renderer) is called.

This method only affects the behavior of the default EGLContexFactory and the default EGLConfigChooser. If setEGLContextFactory(android.opengl.GLSurfaceView.EGLContextFactory) has been called, then the supplied EGLContextFactory is responsible for creating an OpenGL ES 2.0-compatible context. If setEGLConfigChooser(android.opengl.GLSurfaceView.EGLConfigChooser) has been called, then the supplied EGLConfigChooser is responsible for choosing an OpenGL ES 2.0-compatible config.

 
     public void setEGLContextClientVersion(int version) {
         checkRenderThreadState();
          = version;
     }

    
Set the rendering mode. When renderMode is RENDERMODE_CONTINUOUSLY, the renderer is called repeatedly to re-render the scene. When renderMode is RENDERMODE_WHEN_DIRTY, the renderer only rendered when the surface is created, or when requestRender() is called. Defaults to RENDERMODE_CONTINUOUSLY.

Using RENDERMODE_WHEN_DIRTY can improve battery life and overall system performance by allowing the GPU and CPU to idle when the view does not need to be updated.

This method can only be called after setRenderer(android.opengl.GLSurfaceView.Renderer)

Parameters:
renderMode one of the RENDERMODE_X constants
See also:
RENDERMODE_CONTINUOUSLY
RENDERMODE_WHEN_DIRTY
 
     public void setRenderMode(int renderMode) {
         .setRenderMode(renderMode);
     }

    
Get the current rendering mode. May be called from any thread. Must not be called before a renderer has been set.

Returns:
the current rendering mode.
See also:
RENDERMODE_CONTINUOUSLY
RENDERMODE_WHEN_DIRTY
 
     public int getRenderMode() {
         return .getRenderMode();
     }

    
Request that the renderer render a frame. This method is typically used when the render mode has been set to RENDERMODE_WHEN_DIRTY, so that frames are only rendered on demand. May be called from any thread. Must not be called before a renderer has been set.
 
     public void requestRender() {
         .requestRender();
     }

    
This method is part of the SurfaceHolder.Callback interface, and is not normally called or subclassed by clients of GLSurfaceView.
 
     public void surfaceCreated(SurfaceHolder holder) {
         .surfaceCreated();
     }

    
This method is part of the SurfaceHolder.Callback interface, and is not normally called or subclassed by clients of GLSurfaceView.
 
     public void surfaceDestroyed(SurfaceHolder holder) {
         // Surface will be destroyed when we return
         .surfaceDestroyed();
     }

    
This method is part of the SurfaceHolder.Callback interface, and is not normally called or subclassed by clients of GLSurfaceView.
 
     public void surfaceChanged(SurfaceHolder holderint formatint wint h) {
         .onWindowResize(wh);
     }

    
Inform the view that the activity is paused. The owner of this view must call this method when the activity is paused. Calling this method will pause the rendering thread. Must not be called before a renderer has been set.
 
     public void onPause() {
         .onPause();
     }

    
Inform the view that the activity is resumed. The owner of this view must call this method when the activity is resumed. Calling this method will recreate the OpenGL display and resume the rendering thread. Must not be called before a renderer has been set.
 
     public void onResume() {
         .onResume();
     }

    
Queue a runnable to be run on the GL rendering thread. This can be used to communicate with the Renderer on the rendering thread. Must not be called before a renderer has been set.

Parameters:
r the runnable to be run on the GL rendering thread.
 
     public void queueEvent(Runnable r) {
         .queueEvent(r);
     }

    
This method is used as part of the View class and is not normally called or subclassed by clients of GLSurfaceView. Must not be called before a renderer has been set.
 
     @Override
     protected void onDetachedFromWindow() {
         super.onDetachedFromWindow();
         .requestExitAndWait();
     }
 
     // ----------------------------------------------------------------------
 
    
An interface used to wrap a GL interface.

Typically used for implementing debugging and tracing on top of the default GL interface. You would typically use this by creating your own class that implemented all the GL methods by delegating to another GL instance. Then you could add your own behavior before or after calling the delegate. All the GLWrapper would do was instantiate and return the wrapper GL instance:

 class MyGLWrapper implements GLWrapper {
     GL wrap(GL gl) {
         return new MyGLImplementation(gl);
     }
     static class MyGLImplementation implements GL,GL10,GL11,... {
         ...
     }
 }
 

 
     public interface GLWrapper {
        
Wraps a gl interface in another gl interface.

Parameters:
gl a GL interface that is to be wrapped.
Returns:
either the input argument or another GL object that wraps the input argument.
 
         GL wrap(GL gl);
     }

    
A generic renderer interface.

The renderer is responsible for making OpenGL calls to render a frame.

GLSurfaceView clients typically create their own classes that implement this interface, and then call GLSurfaceView.setRenderer(android.opengl.GLSurfaceView.Renderer) to register the renderer with the GLSurfaceView.

Threading

The renderer will be called on a separate thread, so that rendering performance is decoupled from the UI thread. Clients typically need to communicate with the renderer from the UI thread, because that's where input events are received. Clients can communicate using any of the standard Java techniques for cross-thread communication, or they can use the GLSurfaceView.queueEvent(java.lang.Runnable) convenience method.

EGL Context Lost

There are situations where the EGL rendering context will be lost. This typically happens when device wakes up after going to sleep. When the EGL context is lost, all OpenGL resources (such as textures) that are associated with that context will be automatically deleted. In order to keep rendering correctly, a renderer must recreate any lost resources that it still needs. The onSurfaceCreated(javax.microedition.khronos.opengles.GL10,javax.microedition.khronos.egl.EGLConfig) method is a convenient place to do this.

 
     public interface Renderer {
        
Called when the surface is created or recreated.

Called when the rendering thread starts and whenever the EGL context is lost. The EGL context will typically be lost when the Android device awakes after going to sleep.

Since this method is called at the beginning of rendering, as well as every time the EGL context is lost, this method is a convenient place to put code to create resources that need to be created when the rendering starts, and that need to be recreated when the EGL context is lost. Textures are an example of a resource that you might want to create here.

Note that when the EGL context is lost, all OpenGL resources associated with that context will be automatically deleted. You do not need to call the corresponding "glDelete" methods such as glDeleteTextures to manually delete these lost resources.

Parameters:
gl the GL interface. Use instanceof to test if the interface supports GL11 or higher interfaces.
config the EGLConfig of the created surface. Can be used to create matching pbuffers.
 
         void onSurfaceCreated(GL10 glEGLConfig config);

        
Called when the surface changed size.

Called after the surface is created and whenever the OpenGL ES surface size changes.

Typically you will set your viewport here. If your camera is fixed then you could also set your projection matrix here:

 void onSurfaceChanged(GL10 gl, int width, int height) {
     gl.glViewport(0, 0, width, height);
     // for a fixed camera, set the projection too
     float ratio = (float) width / height;
     gl.glMatrixMode(GL10.GL_PROJECTION);
     gl.glLoadIdentity();
     gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
 }
 

Parameters:
gl the GL interface. Use instanceof to test if the interface supports GL11 or higher interfaces.
width
height
 
         void onSurfaceChanged(GL10 glint widthint height);

        
Called to draw the current frame.

This method is responsible for drawing the current frame.

The implementation of this method typically looks like this:

 void onDrawFrame(GL10 gl) {
     gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
     //... other gl calls to render the scene ...
 }
 

Parameters:
gl the GL interface. Use instanceof to test if the interface supports GL11 or higher interfaces.
 
         void onDrawFrame(GL10 gl);
     }

    
An interface for customizing the eglCreateContext and eglDestroyContext calls.

This interface must be implemented by clients wishing to call GLSurfaceView.setEGLContextFactory(android.opengl.GLSurfaceView.EGLContextFactory)

 
     public interface EGLContextFactory {
         EGLContext createContext(EGL10 eglEGLDisplay displayEGLConfig eglConfig);
         void destroyContext(EGL10 eglEGLDisplay displayEGLContext context);
     }
 
     private class DefaultContextFactory implements EGLContextFactory {
         private int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
 
         public EGLContext createContext(EGL10 eglEGLDisplay displayEGLConfig config) {
             int[] attrib_list = {,
                     . };
 
             return egl.eglCreateContext(displayconfig.,
                      != 0 ? attrib_list : null);
         }
 
         public void destroyContext(EGL10 eglEGLDisplay display,
                 EGLContext context) {
             if (!egl.eglDestroyContext(displaycontext)) {
                 Log.e("DefaultContextFactory""display:" + display + " context: " + context);
                 if () {
                     Log.i("DefaultContextFactory""tid=" + Thread.currentThread().getId());
                 }
                 throw new RuntimeException("eglDestroyContext failed: "
                         + EGLLogWrapper.getErrorString(egl.eglGetError()));
             }
         }
     }

    
An interface for customizing the eglCreateWindowSurface and eglDestroySurface calls.

This interface must be implemented by clients wishing to call GLSurfaceView.setEGLWindowSurfaceFactory(android.opengl.GLSurfaceView.EGLWindowSurfaceFactory)

 
     public interface EGLWindowSurfaceFactory {
         EGLSurface createWindowSurface(EGL10 eglEGLDisplay displayEGLConfig config,
                 Object nativeWindow);
         void destroySurface(EGL10 eglEGLDisplay displayEGLSurface surface);
     }
 
     private static class DefaultWindowSurfaceFactory implements EGLWindowSurfaceFactory {
 
         public EGLSurface createWindowSurface(EGL10 eglEGLDisplay display,
                 EGLConfig configObject nativeWindow) {
             return egl.eglCreateWindowSurface(displayconfignativeWindownull);
         }
 
         public void destroySurface(EGL10 eglEGLDisplay display,
                 EGLSurface surface) {
             egl.eglDestroySurface(displaysurface);
         }
     }

    
An interface for choosing an EGLConfig configuration from a list of potential configurations.

This interface must be implemented by clients wishing to call GLSurfaceView.setEGLConfigChooser(android.opengl.GLSurfaceView.EGLConfigChooser)

 
     public interface EGLConfigChooser {
        
Choose a configuration from the list. Implementors typically implement this method by calling javax.microedition.khronos.egl.EGL10.eglChooseConfig(javax.microedition.khronos.egl.EGLDisplay,int[],javax.microedition.khronos.egl.EGLConfig[],int,int[]) and iterating through the results. Please consult the EGL specification available from The Khronos Group to learn how to call eglChooseConfig.

Parameters:
egl the EGL10 for the current display.
display the current display.
Returns:
the chosen configuration.
 
         EGLConfig chooseConfig(EGL10 eglEGLDisplay display);
     }
 
     private abstract class BaseConfigChooser
             implements EGLConfigChooser {
         public BaseConfigChooser(int[] configSpec) {
              = filterConfigSpec(configSpec);
         }
 
         public EGLConfig chooseConfig(EGL10 eglEGLDisplay display) {
             int[] num_config = new int[1];
             if (!egl.eglChooseConfig(displaynull, 0,
                     num_config)) {
                 throw new IllegalArgumentException("eglChooseConfig failed");
             }
 
             int numConfigs = num_config[0];
 
             if (numConfigs <= 0) {
                 throw new IllegalArgumentException(
                         "No configs match configSpec");
             }
 
             EGLConfig[] configs = new EGLConfig[numConfigs];
             if (!egl.eglChooseConfig(displayconfigsnumConfigs,
                     num_config)) {
                 throw new IllegalArgumentException("eglChooseConfig#2 failed");
             }
             EGLConfig config = chooseConfig(egldisplayconfigs);
             if (config == null) {
                 throw new IllegalArgumentException("No config chosen");
             }
             return config;
         }
 
         abstract EGLConfig chooseConfig(EGL10 eglEGLDisplay display,
                 EGLConfig[] configs);
 
         protected int[] mConfigSpec;
 
         private int[] filterConfigSpec(int[] configSpec) {
             if ( != 2) {
                 return configSpec;
             }
             /* We know none of the subclasses define EGL_RENDERABLE_TYPE.
              * And we know the configSpec is well formed.
              */
             int len = configSpec.length;
             int[] newConfigSpec = new int[len + 2];
             System.arraycopy(configSpec, 0, newConfigSpec, 0, len-1);
             newConfigSpec[len-1] = .;
             newConfigSpec[len] = 4; /* EGL_OPENGL_ES2_BIT */
             newConfigSpec[len+1] = .;
             return newConfigSpec;
         }
     }

    
Choose a configuration with exactly the specified r,g,b,a sizes, and at least the specified depth and stencil sizes.
 
     private class ComponentSizeChooser extends BaseConfigChooser {
         public ComponentSizeChooser(int redSizeint greenSizeint blueSize,
                 int alphaSizeint depthSizeint stencilSize) {
             super(new int[] {
                     .redSize,
                     .greenSize,
                     .blueSize,
                     .alphaSize,
                     .depthSize,
                     .stencilSize,
                     .});
              = new int[1];
              = redSize;
              = greenSize;
              = blueSize;
              = alphaSize;
              = depthSize;
              = stencilSize;
        }
 
         @Override
         public EGLConfig chooseConfig(EGL10 eglEGLDisplay display,
                 EGLConfig[] configs) {
             for (EGLConfig config : configs) {
                 int d = findConfigAttrib(egldisplayconfig,
                         ., 0);
                 int s = findConfigAttrib(egldisplayconfig,
                         ., 0);
                 if ((d >= ) && (s >= )) {
                     int r = findConfigAttrib(egldisplayconfig,
                             ., 0);
                     int g = findConfigAttrib(egldisplayconfig,
                              ., 0);
                     int b = findConfigAttrib(egldisplayconfig,
                               ., 0);
                     int a = findConfigAttrib(egldisplayconfig,
                             ., 0);
                     if ((r == ) && (g == )
                             && (b == ) && (a == )) {
                         return config;
                     }
                 }
             }
             return null;
         }
 
         private int findConfigAttrib(EGL10 eglEGLDisplay display,
                 EGLConfig configint attributeint defaultValue) {
 
             if (egl.eglGetConfigAttrib(displayconfigattribute)) {
                 return [0];
             }
             return defaultValue;
         }
 
         private int[] mValue;
         // Subclasses can adjust these values:
         protected int mRedSize;
         protected int mGreenSize;
         protected int mBlueSize;
         protected int mAlphaSize;
         protected int mDepthSize;
         protected int mStencilSize;
         }

    
This class will choose a RGB_565 surface with or without a depth buffer.
 
     private class SimpleEGLConfigChooser extends ComponentSizeChooser {
         public SimpleEGLConfigChooser(boolean withDepthBuffer) {
             super(5, 6, 5, 0, withDepthBuffer ? 16 : 0, 0);
         }
     }

    
An EGL helper class.
 
 
     private class EglHelper {
         public EglHelper() {
 
         }

        
Initialize EGL for a given configuration spec.

Parameters:
configSpec
 
         public void start() {
             if () {
                 Log.w("EglHelper""start() tid=" + Thread.currentThread().getId());
             }
             /*
              * Get an EGL instance
              */
              = (EGL10) EGLContext.getEGL();
 
             /*
              * Get to the default display.
              */
 
             if ( == .) {
                 throw new RuntimeException("eglGetDisplay failed");
             }
 
             /*
              * We can now initialize EGL for that display
              */
             int[] version = new int[2];
             if(!.eglInitialize(version)) {
                 throw new RuntimeException("eglInitialize failed");
             }
              = .chooseConfig();
 
             /*
             * Create an EGL context. We want to do this as rarely as we can, because an
             * EGL context is a somewhat heavy object.
             */
             if ( == null ||  == .) {
                  = null;
                 throwEglException("createContext");
             }
             if () {
                 Log.w("EglHelper""createContext " +  + " tid=" + Thread.currentThread().getId());
             }
 
              = null;
         }
 
         /*
          * React to the creation of a new surface by creating and returning an
          * OpenGL interface that renders to that surface.
          */
         public GL createSurface(SurfaceHolder holder) {
             if () {
                 Log.w("EglHelper""createSurface()  tid=" + Thread.currentThread().getId());
             }
             /*
              * Check preconditions.
              */
             if ( == null) {
                 throw new RuntimeException("egl not initialized");
             }
             if ( == null) {
                 throw new RuntimeException("eglDisplay not initialized");
             }
             if ( == null) {
                 throw new RuntimeException("mEglConfig not initialized");
             }
             /*
              *  The window size has changed, so we need to create a new
              *  surface.
              */
             if ( != null &&  != .) {
 
                 /*
                  * Unbind and destroy the old EGL surface, if
                  * there is one.
                  */
                 .eglMakeCurrent(.,
                         ..);
             }
 
             /*
              * Create an EGL surface we can render into.
              */
                     holder);
 
             if ( == null ||  == .) {
                 int error = .eglGetError();
                 if (error == .) {
                     Log.e("EglHelper""createWindowSurface returned EGL_BAD_NATIVE_WINDOW.");
                     return null;
                 }
                 throwEglException("createWindowSurface"error);
             }
 
             /*
              * Before we can issue GL commands, we need to make sure
              * the context is current and bound to a surface.
              */
             if (!.eglMakeCurrent()) {
                 throwEglException("eglMakeCurrent");
             }
 
             GL gl = .getGL();
             if ( != null) {
                 gl = .wrap(gl);
             }
 
            if (( & ( | )) != 0) {
                int configFlags = 0;
                Writer log = null;
                if (( & ) != 0) {
                    configFlags |= .;
                }
                if (( & ) != 0) {
                    log = new LogWriter();
                }
                gl = GLDebugHelper.wrap(glconfigFlagslog);
            }
            return gl;
        }

        
Display the current render surface.

Returns:
false if the context has been lost.
        public boolean swap() {
            if (! .eglSwapBuffers()) {
                /*
                 * Check for EGL_CONTEXT_LOST, which means the context
                 * and all associated data were lost (For instance because
                 * the device went to sleep). We need to sleep until we
                 * get a new surface.
                 */
                int error = .eglGetError();
                switch(error) {
                case .:
                    return false;
                case .:
                    // The native window is bad, probably because the
                    // window manager has closed it. Ignore this error,
                    // on the expectation that the application will be closed soon.
                    Log.e("EglHelper""eglSwapBuffers returned EGL_BAD_NATIVE_WINDOW. tid=" + Thread.currentThread().getId());
                    break;
                default:
                    throwEglException("eglSwapBuffers"error);
                }
            }
            return true;
        }
        public void destroySurface() {
            if () {
                Log.w("EglHelper""destroySurface()  tid=" + Thread.currentThread().getId());
            }
            if ( != null &&  != .) {
                .eglMakeCurrent(.,
                        .,
                        .);
                 = null;
            }
        }
        public void finish() {
            if () {
                Log.w("EglHelper""finish() tid=" + Thread.currentThread().getId());
            }
            if ( != null) {
                .destroyContext();
                 = null;
            }
            if ( != null) {
                .eglTerminate();
                 = null;
            }
        }
        private void throwEglException(String function) {
            throwEglException(function.eglGetError());
        }
        private void throwEglException(String functionint error) {
            String message = function + " failed: " + EGLLogWrapper.getErrorString(error);
            if () {
                Log.e("EglHelper""throwEglException tid=" + Thread.currentThread().getId() + " " + message);
            }
            throw new RuntimeException(message);
        }
        EGL10 mEgl;
        EGLDisplay mEglDisplay;
        EGLSurface mEglSurface;
        EGLConfig mEglConfig;
        EGLContext mEglContext;
    }

    
A generic GL Thread. Takes care of initializing EGL and GL. Delegates to a Renderer instance to do the actual drawing. Can be configured to render continuously or on request. All potentially blocking synchronization is done through the sGLThreadManager object. This avoids multiple-lock ordering issues.
    class GLThread extends Thread {
        GLThread(Renderer renderer) {
            super();
             = 0;
             = 0;
             = true;
             = ;
             = renderer;
        }
        @Override
        public void run() {
            setName("GLThread " + getId());
            if () {
                Log.i("GLThread""starting tid=" + getId());
            }
            try {
                guardedRun();
            } catch (InterruptedException e) {
                // fall thru and exit normally
            } finally {
                .threadExiting(this);
            }
        }
        /*
         * This private method should only be called inside a
         * synchronized(sGLThreadManager) block.
         */
        private void stopEglSurfaceLocked() {
            if () {
                 = false;
                .destroySurface();
            }
        }
        /*
         * This private method should only be called inside a
         * synchronized(sGLThreadManager) block.
         */
        private void stopEglContextLocked() {
            if () {
                .finish();
                 = false;
                .releaseEglContextLocked(this);
            }
        }
        private void guardedRun() throws InterruptedException {
             = new EglHelper();
             = false;
             = false;
            try {
                GL10 gl = null;
                boolean createEglContext = false;
                boolean createEglSurface = false;
                boolean lostEglContext = false;
                boolean sizeChanged = false;
                boolean wantRenderNotification = false;
                boolean doRenderNotification = false;
                boolean askedToReleaseEglContext = false;
                int w = 0;
                int h = 0;
                Runnable event = null;
                while (true) {
                    synchronized () {
                        while (true) {
                            if () {
                                return;
                            }
                            if (! .isEmpty()) {
                                event = .remove(0);
                                break;
                            }
                            // Update the pause state.
                            if ( != ) {
                                 = ;
                                .notifyAll();
                                if () {
                                    Log.i("GLThread""mPaused is now " +  + " tid=" + getId());
                                }
                            }
                            // Do we need to give up the EGL context?
                            if () {
                                if () {
                                    Log.i("GLThread""releasing EGL context because asked to tid=" + getId());
                                }
                                stopEglSurfaceLocked();
                                stopEglContextLocked();
                                 = false;
                                askedToReleaseEglContext = true;
                            }
                            // Have we lost the EGL context?
                            if (lostEglContext) {
                                stopEglSurfaceLocked();
                                stopEglContextLocked();
                                lostEglContext = false;
                            }
                            // Do we need to release the EGL surface?
                            if ( && ) {
                                if () {
                                    Log.i("GLThread""releasing EGL surface because paused tid=" + getId());
                                }
                                stopEglSurfaceLocked();
                                if (.shouldReleaseEGLContextWhenPausing()) {
                                    stopEglContextLocked();
                                    if () {
                                        Log.i("GLThread""releasing EGL context because paused tid=" + getId());
                                    }
                                }
                                if (.shouldTerminateEGLWhenPausing()) {
                                    .finish();
                                    if () {
                                        Log.i("GLThread""terminating EGL because paused tid=" + getId());
                                    }
                                }
                            }
                            // Have we lost the surface view surface?
                            if ((! ) && (! )) {
                                if () {
                                    Log.i("GLThread""noticed surfaceView surface lost tid=" + getId());
                                }
                                if () {
                                    stopEglSurfaceLocked();
                                }
                                 = true;
                                .notifyAll();
                            }
                            // Have we acquired the surface view surface?
                            if ( && ) {
                                if () {
                                    Log.i("GLThread""noticed surfaceView surface acquired tid=" + getId());
                                }
                                 = false;
                                .notifyAll();
                            }
                            if (doRenderNotification) {
                                if () {
                                    Log.i("GLThread""sending render notification tid=" + getId());
                                }
                                wantRenderNotification = false;
                                doRenderNotification = false;
                                 = true;
                                .notifyAll();
                            }
                            // Ready to draw?
                            if (readyToDraw()) {
                                // If we don't have an EGL context, try to acquire one.
                                if (! ) {
                                    if (askedToReleaseEglContext) {
                                        askedToReleaseEglContext = false;
                                    } else if (.tryAcquireEglContextLocked(this)) {
                                        try {
                                            .start();
                                        } catch (RuntimeException t) {
                                            .releaseEglContextLocked(this);
                                            throw t;
                                        }
                                         = true;
                                        createEglContext = true;
                                        .notifyAll();
                                    }
                                }
                                if ( && !) {
                                     = true;
                                    createEglSurface = true;
                                    sizeChanged = true;
                                }
                                if () {
                                    if () {
                                        sizeChanged = true;
                                        w = ;
                                        h = ;
                                        wantRenderNotification = true;
                                        if () {
                                            Log.i("GLThread""noticing that we want render notification tid=" + getId());
                                        }
                                        if () {
                                            // We keep mRequestRender true so that we draw twice after the size changes.
                                            // (Once because of mSizeChanged, the second time because of mRequestRender.)
                                            // This forces the updated graphics onto the screen.
                                        } else {
                                             = false;
                                        }
                                         = false;
                                    } else {
                                         = false;
                                    }
                                    .notifyAll();
                                    break;
                                }
                            }
                            // By design, this is the only place in a GLThread thread where we wait().
                            if () {
                                Log.i("GLThread""waiting tid=" + getId()
                                    + " mHaveEglContext: " + 
                                    + " mHaveEglSurface: " + 
                                    + " mPaused: " + 
                                    + " mHasSurface: " + 
                                    + " mWaitingForSurface: " + 
                                    + " mWidth: " + 
                                    + " mHeight: " + 
                                    + " mRequestRender: " + 
                                    + " mRenderMode: " + );
                            }
                            .wait();
                        }
                    } // end of synchronized(sGLThreadManager)
                    if (event != null) {
                        event.run();
                        event = null;
                        continue;
                    }
                    if (createEglSurface) {
                        if () {
                            Log.w("GLThread""egl createSurface");
                        }
                        gl = (GL10.createSurface(getHolder());
                        if (gl == null) {
                            // Couldn't create a surface. Quit quietly.
                            break;
                        }
                        .checkGLDriver(gl);
                        createEglSurface = false;
                    }
                    if (createEglContext) {
                        if () {
                            Log.w("GLThread""onSurfaceCreated");
                        }
                        .onSurfaceCreated(gl.);
                        createEglContext = false;
                    }
                    if (sizeChanged) {
                        if () {
                            Log.w("GLThread""onSurfaceChanged(" + w + ", " + h + ")");
                        }
                        .onSurfaceChanged(glwh);
                        sizeChanged = false;
                    }
                    if () {
                        Log.w("GLThread""onDrawFrame tid=" + getId());
                    }
                    .onDrawFrame(gl);
                    if (!.swap()) {
                        if () {
                            Log.i("GLThread""egl context lost tid=" + getId());
                        }
                        lostEglContext = true;
                    }
                    if (wantRenderNotification) {
                        doRenderNotification = true;
                    }
                }
            } finally {
                /*
                 * clean-up everything...
                 */
                synchronized () {
                    stopEglSurfaceLocked();
                    stopEglContextLocked();
                }
            }
        }
        public boolean ableToDraw() {
            return  &&  && readyToDraw();
        }
        private boolean readyToDraw() {
            return (!) && 
                && ( > 0) && ( > 0)
                && ( || ( == ));
        }
        public void setRenderMode(int renderMode) {
            if ( !(( <= renderMode) && (renderMode <= )) ) {
                throw new IllegalArgumentException("renderMode");
            }
            synchronized() {
                 = renderMode;
                .notifyAll();
            }
        }
        public int getRenderMode() {
            synchronized() {
                return ;
            }
        }
        public void requestRender() {
            synchronized() {
                 = true;
                .notifyAll();
            }
        }
        public void surfaceCreated() {
            synchronized() {
                if () {
                    Log.i("GLThread""surfaceCreated tid=" + getId());
                }
                 = true;
                .notifyAll();
                while(() && (!)) {
                    try {
                        .wait();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }
        public void surfaceDestroyed() {
            synchronized() {
                if () {
                    Log.i("GLThread""surfaceDestroyed tid=" + getId());
                }
                 = false;
                .notifyAll();
                while((!) && (!)) {
                    try {
                        .wait();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }
        public void onPause() {
            synchronized () {
                if () {
                    Log.i("GLThread""onPause tid=" + getId());
                }
                 = true;
                .notifyAll();
                while ((! ) && (! )) {
                    if () {
                        Log.i("Main thread""onPause waiting for mPaused.");
                    }
                    try {
                        .wait();
                    } catch (InterruptedException ex) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }
        public void onResume() {
            synchronized () {
                if () {
                    Log.i("GLThread""onResume tid=" + getId());
                }
                 = false;