GLSurfaceView.java revision 451a224c46c297bd6b25e3570b45f5053b4788be
1dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project/*
2dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project * Copyright (C) 2008 The Android Open Source Project
3dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project *
4dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project * Licensed under the Apache License, Version 2.0 (the "License");
5dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project * you may not use this file except in compliance with the License.
6dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project * You may obtain a copy of the License at
7dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project *
8dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project *      http://www.apache.org/licenses/LICENSE-2.0
9dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project *
10dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project * Unless required by applicable law or agreed to in writing, software
11dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project * distributed under the License is distributed on an "AS IS" BASIS,
12dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project * See the License for the specific language governing permissions and
14dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project * limitations under the License.
15dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project */
16dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project
17dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Projectpackage android.opengl;
18dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project
19dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Projectimport java.io.Writer;
20dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Projectimport java.util.ArrayList;
21dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project
22dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Projectimport javax.microedition.khronos.egl.EGL10;
23dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Projectimport javax.microedition.khronos.egl.EGL11;
24dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Projectimport javax.microedition.khronos.egl.EGLConfig;
25dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Projectimport javax.microedition.khronos.egl.EGLContext;
26dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Projectimport javax.microedition.khronos.egl.EGLDisplay;
27dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Projectimport javax.microedition.khronos.egl.EGLSurface;
28dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Projectimport javax.microedition.khronos.opengles.GL;
29dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Projectimport javax.microedition.khronos.opengles.GL10;
30dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Project
31dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Projectimport android.content.Context;
32dd7bc3319deb2b77c5d07a51b7d6cd7e11b5beb0The Android Open Source Projectimport android.content.pm.ConfigurationInfo;
33import android.graphics.PixelFormat;
34import android.os.SystemProperties;
35import android.util.AttributeSet;
36import android.util.Log;
37import android.view.SurfaceHolder;
38import android.view.SurfaceView;
39
40/**
41 * An implementation of SurfaceView that uses the dedicated surface for
42 * displaying OpenGL rendering.
43 * <p>
44 * A GLSurfaceView provides the following features:
45 * <p>
46 * <ul>
47 * <li>Manages a surface, which is a special piece of memory that can be
48 * composited into the Android view system.
49 * <li>Manages an EGL display, which enables OpenGL to render into a surface.
50 * <li>Accepts a user-provided Renderer object that does the actual rendering.
51 * <li>Renders on a dedicated thread to decouple rendering performance from the
52 * UI thread.
53 * <li>Supports both on-demand and continuous rendering.
54 * <li>Optionally wraps, traces, and/or error-checks the renderer's OpenGL calls.
55 * </ul>
56 *
57 * <h3>Using GLSurfaceView</h3>
58 * <p>
59 * Typically you use GLSurfaceView by subclassing it and overriding one or more of the
60 * View system input event methods. If your application does not need to override event
61 * methods then GLSurfaceView can be used as-is. For the most part
62 * GLSurfaceView behavior is customized by calling "set" methods rather than by subclassing.
63 * For example, unlike a regular View, drawing is delegated to a separate Renderer object which
64 * is registered with the GLSurfaceView
65 * using the {@link #setRenderer(Renderer)} call.
66 * <p>
67 * <h3>Initializing GLSurfaceView</h3>
68 * All you have to do to initialize a GLSurfaceView is call {@link #setRenderer(Renderer)}.
69 * However, if desired, you can modify the default behavior of GLSurfaceView by calling one or
70 * more of these methods before calling setRenderer:
71 * <ul>
72 * <li>{@link #setDebugFlags(int)}
73 * <li>{@link #setEGLConfigChooser(boolean)}
74 * <li>{@link #setEGLConfigChooser(EGLConfigChooser)}
75 * <li>{@link #setEGLConfigChooser(int, int, int, int, int, int)}
76 * <li>{@link #setGLWrapper(GLWrapper)}
77 * </ul>
78 * <p>
79 * <h4>Specifying the android.view.Surface</h4>
80 * By default GLSurfaceView will create a PixelFormat.RGB_565 format surface. If a translucent
81 * surface is required, call getHolder().setFormat(PixelFormat.TRANSLUCENT).
82 * The exact format of a TRANSLUCENT surface is device dependent, but it will be
83 * a 32-bit-per-pixel surface with 8 bits per component.
84 * <p>
85 * <h4>Choosing an EGL Configuration</h4>
86 * A given Android device may support multiple EGLConfig rendering configurations.
87 * The available configurations may differ in how may channels of data are present, as
88 * well as how many bits are allocated to each channel. Therefore, the first thing
89 * GLSurfaceView has to do when starting to render is choose what EGLConfig to use.
90 * <p>
91 * By default GLSurfaceView chooses a EGLConfig that has an RGB_656 pixel format,
92 * with at least a 16-bit depth buffer and no stencil.
93 * <p>
94 * If you would prefer a different EGLConfig
95 * you can override the default behavior by calling one of the
96 * setEGLConfigChooser methods.
97 * <p>
98 * <h4>Debug Behavior</h4>
99 * You can optionally modify the behavior of GLSurfaceView by calling
100 * one or more of the debugging methods {@link #setDebugFlags(int)},
101 * and {@link #setGLWrapper}. These methods may be called before and/or after setRenderer, but
102 * typically they are called before setRenderer so that they take effect immediately.
103 * <p>
104 * <h4>Setting a Renderer</h4>
105 * Finally, you must call {@link #setRenderer} to register a {@link Renderer}.
106 * The renderer is
107 * responsible for doing the actual OpenGL rendering.
108 * <p>
109 * <h3>Rendering Mode</h3>
110 * Once the renderer is set, you can control whether the renderer draws
111 * continuously or on-demand by calling
112 * {@link #setRenderMode}. The default is continuous rendering.
113 * <p>
114 * <h3>Activity Life-cycle</h3>
115 * A GLSurfaceView must be notified when the activity is paused and resumed. GLSurfaceView clients
116 * are required to call {@link #onPause()} when the activity pauses and
117 * {@link #onResume()} when the activity resumes. These calls allow GLSurfaceView to
118 * pause and resume the rendering thread, and also allow GLSurfaceView to release and recreate
119 * the OpenGL display.
120 * <p>
121 * <h3>Handling events</h3>
122 * <p>
123 * To handle an event you will typically subclass GLSurfaceView and override the
124 * appropriate method, just as you would with any other View. However, when handling
125 * the event, you may need to communicate with the Renderer object
126 * that's running in the rendering thread. You can do this using any
127 * standard Java cross-thread communication mechanism. In addition,
128 * one relatively easy way to communicate with your renderer is
129 * to call
130 * {@link #queueEvent(Runnable)}. For example:
131 * <pre class="prettyprint">
132 * class MyGLSurfaceView extends GLSurfaceView {
133 *
134 *     private MyRenderer mMyRenderer;
135 *
136 *     public void start() {
137 *         mMyRenderer = ...;
138 *         setRenderer(mMyRenderer);
139 *     }
140 *
141 *     public boolean onKeyDown(int keyCode, KeyEvent event) {
142 *         if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
143 *             queueEvent(new Runnable() {
144 *                 // This method will be called on the rendering
145 *                 // thread:
146 *                 public void run() {
147 *                     mMyRenderer.handleDpadCenter();
148 *                 }});
149 *             return true;
150 *         }
151 *         return super.onKeyDown(keyCode, event);
152 *     }
153 * }
154 * </pre>
155 *
156 */
157public class GLSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
158    private final static boolean LOG_THREADS = false;
159    private final static boolean LOG_PAUSE_RESUME = true;
160    private final static boolean LOG_SURFACE = true;
161    private final static boolean LOG_RENDERER = true;
162    private final static boolean LOG_RENDERER_DRAW_FRAME = false;
163    private final static boolean LOG_EGL = true;
164    // Work-around for bug 2263168
165    private final static boolean DRAW_TWICE_AFTER_SIZE_CHANGED = true;
166    /**
167     * The renderer only renders
168     * when the surface is created, or when {@link #requestRender} is called.
169     *
170     * @see #getRenderMode()
171     * @see #setRenderMode(int)
172     * @see #requestRender()
173     */
174    public final static int RENDERMODE_WHEN_DIRTY = 0;
175    /**
176     * The renderer is called
177     * continuously to re-render the scene.
178     *
179     * @see #getRenderMode()
180     * @see #setRenderMode(int)
181     */
182    public final static int RENDERMODE_CONTINUOUSLY = 1;
183
184    /**
185     * Check glError() after every GL call and throw an exception if glError indicates
186     * that an error has occurred. This can be used to help track down which OpenGL ES call
187     * is causing an error.
188     *
189     * @see #getDebugFlags
190     * @see #setDebugFlags
191     */
192    public final static int DEBUG_CHECK_GL_ERROR = 1;
193
194    /**
195     * Log GL calls to the system log at "verbose" level with tag "GLSurfaceView".
196     *
197     * @see #getDebugFlags
198     * @see #setDebugFlags
199     */
200    public final static int DEBUG_LOG_GL_CALLS = 2;
201
202    /**
203     * Standard View constructor. In order to render something, you
204     * must call {@link #setRenderer} to register a renderer.
205     */
206    public GLSurfaceView(Context context) {
207        super(context);
208        init();
209    }
210
211    /**
212     * Standard View constructor. In order to render something, you
213     * must call {@link #setRenderer} to register a renderer.
214     */
215    public GLSurfaceView(Context context, AttributeSet attrs) {
216        super(context, attrs);
217        init();
218    }
219
220    private void init() {
221        // Install a SurfaceHolder.Callback so we get notified when the
222        // underlying surface is created and destroyed
223        SurfaceHolder holder = getHolder();
224        holder.addCallback(this);
225        holder.setFormat(PixelFormat.RGB_565);
226        // setType is not needed for SDK 2.0 or newer. Uncomment this
227        // statement if back-porting this code to older SDKs.
228        // holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
229    }
230
231    /**
232     * Set the glWrapper. If the glWrapper is not null, its
233     * {@link GLWrapper#wrap(GL)} method is called
234     * whenever a surface is created. A GLWrapper can be used to wrap
235     * the GL object that's passed to the renderer. Wrapping a GL
236     * object enables examining and modifying the behavior of the
237     * GL calls made by the renderer.
238     * <p>
239     * Wrapping is typically used for debugging purposes.
240     * <p>
241     * The default value is null.
242     * @param glWrapper the new GLWrapper
243     */
244    public void setGLWrapper(GLWrapper glWrapper) {
245        mGLWrapper = glWrapper;
246    }
247
248    /**
249     * Set the debug flags to a new value. The value is
250     * constructed by OR-together zero or more
251     * of the DEBUG_CHECK_* constants. The debug flags take effect
252     * whenever a surface is created. The default value is zero.
253     * @param debugFlags the new debug flags
254     * @see #DEBUG_CHECK_GL_ERROR
255     * @see #DEBUG_LOG_GL_CALLS
256     */
257    public void setDebugFlags(int debugFlags) {
258        mDebugFlags = debugFlags;
259    }
260
261    /**
262     * Get the current value of the debug flags.
263     * @return the current value of the debug flags.
264     */
265    public int getDebugFlags() {
266        return mDebugFlags;
267    }
268
269    /**
270     * Set the renderer associated with this view. Also starts the thread that
271     * will call the renderer, which in turn causes the rendering to start.
272     * <p>This method should be called once and only once in the life-cycle of
273     * a GLSurfaceView.
274     * <p>The following GLSurfaceView methods can only be called <em>before</em>
275     * setRenderer is called:
276     * <ul>
277     * <li>{@link #setEGLConfigChooser(boolean)}
278     * <li>{@link #setEGLConfigChooser(EGLConfigChooser)}
279     * <li>{@link #setEGLConfigChooser(int, int, int, int, int, int)}
280     * </ul>
281     * <p>
282     * The following GLSurfaceView methods can only be called <em>after</em>
283     * setRenderer is called:
284     * <ul>
285     * <li>{@link #getRenderMode()}
286     * <li>{@link #onPause()}
287     * <li>{@link #onResume()}
288     * <li>{@link #queueEvent(Runnable)}
289     * <li>{@link #requestRender()}
290     * <li>{@link #setRenderMode(int)}
291     * </ul>
292     *
293     * @param renderer the renderer to use to perform OpenGL drawing.
294     */
295    public void setRenderer(Renderer renderer) {
296        checkRenderThreadState();
297        if (mEGLConfigChooser == null) {
298            mEGLConfigChooser = new SimpleEGLConfigChooser(true);
299        }
300        if (mEGLContextFactory == null) {
301            mEGLContextFactory = new DefaultContextFactory();
302        }
303        if (mEGLWindowSurfaceFactory == null) {
304            mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory();
305        }
306        mGLThread = new GLThread(renderer);
307        mGLThread.start();
308    }
309
310    /**
311     * Install a custom EGLContextFactory.
312     * <p>If this method is
313     * called, it must be called before {@link #setRenderer(Renderer)}
314     * is called.
315     * <p>
316     * If this method is not called, then by default
317     * a context will be created with no shared context and
318     * with a null attribute list.
319     */
320    public void setEGLContextFactory(EGLContextFactory factory) {
321        checkRenderThreadState();
322        mEGLContextFactory = factory;
323    }
324
325    /**
326     * Install a custom EGLWindowSurfaceFactory.
327     * <p>If this method is
328     * called, it must be called before {@link #setRenderer(Renderer)}
329     * is called.
330     * <p>
331     * If this method is not called, then by default
332     * a window surface will be created with a null attribute list.
333     */
334    public void setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory factory) {
335        checkRenderThreadState();
336        mEGLWindowSurfaceFactory = factory;
337    }
338
339    /**
340     * Install a custom EGLConfigChooser.
341     * <p>If this method is
342     * called, it must be called before {@link #setRenderer(Renderer)}
343     * is called.
344     * <p>
345     * If no setEGLConfigChooser method is called, then by default the
346     * view will choose an EGLConfig that is compatible with the current
347     * android.view.Surface, with a depth buffer depth of
348     * at least 16 bits.
349     * @param configChooser
350     */
351    public void setEGLConfigChooser(EGLConfigChooser configChooser) {
352        checkRenderThreadState();
353        mEGLConfigChooser = configChooser;
354    }
355
356    /**
357     * Install a config chooser which will choose a config
358     * as close to 16-bit RGB as possible, with or without an optional depth
359     * buffer as close to 16-bits as possible.
360     * <p>If this method is
361     * called, it must be called before {@link #setRenderer(Renderer)}
362     * is called.
363     * <p>
364     * If no setEGLConfigChooser method is called, then by default the
365     * view will choose an RGB_565 surface with a depth buffer depth of
366     * at least 16 bits.
367     *
368     * @param needDepth
369     */
370    public void setEGLConfigChooser(boolean needDepth) {
371        setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth));
372    }
373
374    /**
375     * Install a config chooser which will choose a config
376     * with at least the specified depthSize and stencilSize,
377     * and exactly the specified redSize, greenSize, blueSize and alphaSize.
378     * <p>If this method is
379     * called, it must be called before {@link #setRenderer(Renderer)}
380     * is called.
381     * <p>
382     * If no setEGLConfigChooser method is called, then by default the
383     * view will choose an RGB_565 surface with a depth buffer depth of
384     * at least 16 bits.
385     *
386     */
387    public void setEGLConfigChooser(int redSize, int greenSize, int blueSize,
388            int alphaSize, int depthSize, int stencilSize) {
389        setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize,
390                blueSize, alphaSize, depthSize, stencilSize));
391    }
392
393    /**
394     * Inform the default EGLContextFactory and default EGLConfigChooser
395     * which EGLContext client version to pick.
396     * <p>Use this method to create an OpenGL ES 2.0-compatible context.
397     * Example:
398     * <pre class="prettyprint">
399     *     public MyView(Context context) {
400     *         super(context);
401     *         setEGLContextClientVersion(2); // Pick an OpenGL ES 2.0 context.
402     *         setRenderer(new MyRenderer());
403     *     }
404     * </pre>
405     * <p>Note: Activities which require OpenGL ES 2.0 should indicate this by
406     * setting @lt;uses-feature android:glEsVersion="0x00020000" /> in the activity's
407     * AndroidManifest.xml file.
408     * <p>If this method is called, it must be called before {@link #setRenderer(Renderer)}
409     * is called.
410     * <p>This method only affects the behavior of the default EGLContexFactory and the
411     * default EGLConfigChooser. If
412     * {@link #setEGLContextFactory(EGLContextFactory)} has been called, then the supplied
413     * EGLContextFactory is responsible for creating an OpenGL ES 2.0-compatible context.
414     * If
415     * {@link #setEGLConfigChooser(EGLConfigChooser)} has been called, then the supplied
416     * EGLConfigChooser is responsible for choosing an OpenGL ES 2.0-compatible config.
417     * @param version The EGLContext client version to choose. Use 2 for OpenGL ES 2.0
418     */
419    public void setEGLContextClientVersion(int version) {
420        checkRenderThreadState();
421        mEGLContextClientVersion = version;
422    }
423
424    /**
425     * Set the rendering mode. When renderMode is
426     * RENDERMODE_CONTINUOUSLY, the renderer is called
427     * repeatedly to re-render the scene. When renderMode
428     * is RENDERMODE_WHEN_DIRTY, the renderer only rendered when the surface
429     * is created, or when {@link #requestRender} is called. Defaults to RENDERMODE_CONTINUOUSLY.
430     * <p>
431     * Using RENDERMODE_WHEN_DIRTY can improve battery life and overall system performance
432     * by allowing the GPU and CPU to idle when the view does not need to be updated.
433     * <p>
434     * This method can only be called after {@link #setRenderer(Renderer)}
435     *
436     * @param renderMode one of the RENDERMODE_X constants
437     * @see #RENDERMODE_CONTINUOUSLY
438     * @see #RENDERMODE_WHEN_DIRTY
439     */
440    public void setRenderMode(int renderMode) {
441        mGLThread.setRenderMode(renderMode);
442    }
443
444    /**
445     * Get the current rendering mode. May be called
446     * from any thread. Must not be called before a renderer has been set.
447     * @return the current rendering mode.
448     * @see #RENDERMODE_CONTINUOUSLY
449     * @see #RENDERMODE_WHEN_DIRTY
450     */
451    public int getRenderMode() {
452        return mGLThread.getRenderMode();
453    }
454
455    /**
456     * Request that the renderer render a frame.
457     * This method is typically used when the render mode has been set to
458     * {@link #RENDERMODE_WHEN_DIRTY}, so that frames are only rendered on demand.
459     * May be called
460     * from any thread. Must not be called before a renderer has been set.
461     */
462    public void requestRender() {
463        mGLThread.requestRender();
464    }
465
466    /**
467     * This method is part of the SurfaceHolder.Callback interface, and is
468     * not normally called or subclassed by clients of GLSurfaceView.
469     */
470    public void surfaceCreated(SurfaceHolder holder) {
471        mGLThread.surfaceCreated();
472    }
473
474    /**
475     * This method is part of the SurfaceHolder.Callback interface, and is
476     * not normally called or subclassed by clients of GLSurfaceView.
477     */
478    public void surfaceDestroyed(SurfaceHolder holder) {
479        // Surface will be destroyed when we return
480        mGLThread.surfaceDestroyed();
481    }
482
483    /**
484     * This method is part of the SurfaceHolder.Callback interface, and is
485     * not normally called or subclassed by clients of GLSurfaceView.
486     */
487    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
488        mGLThread.onWindowResize(w, h);
489    }
490
491    /**
492     * Inform the view that the activity is paused. The owner of this view must
493     * call this method when the activity is paused. Calling this method will
494     * pause the rendering thread.
495     * Must not be called before a renderer has been set.
496     */
497    public void onPause() {
498        mGLThread.onPause();
499    }
500
501    /**
502     * Inform the view that the activity is resumed. The owner of this view must
503     * call this method when the activity is resumed. Calling this method will
504     * recreate the OpenGL display and resume the rendering
505     * thread.
506     * Must not be called before a renderer has been set.
507     */
508    public void onResume() {
509        mGLThread.onResume();
510    }
511
512    /**
513     * Queue a runnable to be run on the GL rendering thread. This can be used
514     * to communicate with the Renderer on the rendering thread.
515     * Must not be called before a renderer has been set.
516     * @param r the runnable to be run on the GL rendering thread.
517     */
518    public void queueEvent(Runnable r) {
519        mGLThread.queueEvent(r);
520    }
521
522    /**
523     * This method is used as part of the View class and is not normally
524     * called or subclassed by clients of GLSurfaceView.
525     * Must not be called before a renderer has been set.
526     */
527    @Override
528    protected void onDetachedFromWindow() {
529        super.onDetachedFromWindow();
530        mGLThread.requestExitAndWait();
531    }
532
533    // ----------------------------------------------------------------------
534
535    /**
536     * An interface used to wrap a GL interface.
537     * <p>Typically
538     * used for implementing debugging and tracing on top of the default
539     * GL interface. You would typically use this by creating your own class
540     * that implemented all the GL methods by delegating to another GL instance.
541     * Then you could add your own behavior before or after calling the
542     * delegate. All the GLWrapper would do was instantiate and return the
543     * wrapper GL instance:
544     * <pre class="prettyprint">
545     * class MyGLWrapper implements GLWrapper {
546     *     GL wrap(GL gl) {
547     *         return new MyGLImplementation(gl);
548     *     }
549     *     static class MyGLImplementation implements GL,GL10,GL11,... {
550     *         ...
551     *     }
552     * }
553     * </pre>
554     * @see #setGLWrapper(GLWrapper)
555     */
556    public interface GLWrapper {
557        /**
558         * Wraps a gl interface in another gl interface.
559         * @param gl a GL interface that is to be wrapped.
560         * @return either the input argument or another GL object that wraps the input argument.
561         */
562        GL wrap(GL gl);
563    }
564
565    /**
566     * A generic renderer interface.
567     * <p>
568     * The renderer is responsible for making OpenGL calls to render a frame.
569     * <p>
570     * GLSurfaceView clients typically create their own classes that implement
571     * this interface, and then call {@link GLSurfaceView#setRenderer} to
572     * register the renderer with the GLSurfaceView.
573     * <p>
574     * <h3>Threading</h3>
575     * The renderer will be called on a separate thread, so that rendering
576     * performance is decoupled from the UI thread. Clients typically need to
577     * communicate with the renderer from the UI thread, because that's where
578     * input events are received. Clients can communicate using any of the
579     * standard Java techniques for cross-thread communication, or they can
580     * use the {@link GLSurfaceView#queueEvent(Runnable)} convenience method.
581     * <p>
582     * <h3>EGL Context Lost</h3>
583     * There are situations where the EGL rendering context will be lost. This
584     * typically happens when device wakes up after going to sleep. When
585     * the EGL context is lost, all OpenGL resources (such as textures) that are
586     * associated with that context will be automatically deleted. In order to
587     * keep rendering correctly, a renderer must recreate any lost resources
588     * that it still needs. The {@link #onSurfaceCreated(GL10, EGLConfig)} method
589     * is a convenient place to do this.
590     *
591     *
592     * @see #setRenderer(Renderer)
593     */
594    public interface Renderer {
595        /**
596         * Called when the surface is created or recreated.
597         * <p>
598         * Called when the rendering thread
599         * starts and whenever the EGL context is lost. The EGL context will typically
600         * be lost when the Android device awakes after going to sleep.
601         * <p>
602         * Since this method is called at the beginning of rendering, as well as
603         * every time the EGL context is lost, this method is a convenient place to put
604         * code to create resources that need to be created when the rendering
605         * starts, and that need to be recreated when the EGL context is lost.
606         * Textures are an example of a resource that you might want to create
607         * here.
608         * <p>
609         * Note that when the EGL context is lost, all OpenGL resources associated
610         * with that context will be automatically deleted. You do not need to call
611         * the corresponding "glDelete" methods such as glDeleteTextures to
612         * manually delete these lost resources.
613         * <p>
614         * @param gl the GL interface. Use <code>instanceof</code> to
615         * test if the interface supports GL11 or higher interfaces.
616         * @param config the EGLConfig of the created surface. Can be used
617         * to create matching pbuffers.
618         */
619        void onSurfaceCreated(GL10 gl, EGLConfig config);
620
621        /**
622         * Called when the surface changed size.
623         * <p>
624         * Called after the surface is created and whenever
625         * the OpenGL ES surface size changes.
626         * <p>
627         * Typically you will set your viewport here. If your camera
628         * is fixed then you could also set your projection matrix here:
629         * <pre class="prettyprint">
630         * void onSurfaceChanged(GL10 gl, int width, int height) {
631         *     gl.glViewport(0, 0, width, height);
632         *     // for a fixed camera, set the projection too
633         *     float ratio = (float) width / height;
634         *     gl.glMatrixMode(GL10.GL_PROJECTION);
635         *     gl.glLoadIdentity();
636         *     gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
637         * }
638         * </pre>
639         * @param gl the GL interface. Use <code>instanceof</code> to
640         * test if the interface supports GL11 or higher interfaces.
641         * @param width
642         * @param height
643         */
644        void onSurfaceChanged(GL10 gl, int width, int height);
645
646        /**
647         * Called to draw the current frame.
648         * <p>
649         * This method is responsible for drawing the current frame.
650         * <p>
651         * The implementation of this method typically looks like this:
652         * <pre class="prettyprint">
653         * void onDrawFrame(GL10 gl) {
654         *     gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
655         *     //... other gl calls to render the scene ...
656         * }
657         * </pre>
658         * @param gl the GL interface. Use <code>instanceof</code> to
659         * test if the interface supports GL11 or higher interfaces.
660         */
661        void onDrawFrame(GL10 gl);
662    }
663
664    /**
665     * An interface for customizing the eglCreateContext and eglDestroyContext calls.
666     * <p>
667     * This interface must be implemented by clients wishing to call
668     * {@link GLSurfaceView#setEGLContextFactory(EGLContextFactory)}
669     */
670    public interface EGLContextFactory {
671        EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig);
672        void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context);
673    }
674
675    private class DefaultContextFactory implements EGLContextFactory {
676        private int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
677
678        public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig config) {
679            int[] attrib_list = {EGL_CONTEXT_CLIENT_VERSION, mEGLContextClientVersion,
680                    EGL10.EGL_NONE };
681
682            return egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT,
683                    mEGLContextClientVersion != 0 ? attrib_list : null);
684        }
685
686        public void destroyContext(EGL10 egl, EGLDisplay display,
687                EGLContext context) {
688            if (!egl.eglDestroyContext(display, context)) {
689                Log.e("DefaultContextFactory", "display:" + display + " context: " + context);
690                if (LOG_THREADS) {
691                    Log.i("DefaultContextFactory", "tid=" + Thread.currentThread().getId());
692                }
693                throw new RuntimeException("eglDestroyContext failed: "
694                        + EGLLogWrapper.getErrorString(egl.eglGetError()));
695            }
696        }
697    }
698
699    /**
700     * An interface for customizing the eglCreateWindowSurface and eglDestroySurface calls.
701     * <p>
702     * This interface must be implemented by clients wishing to call
703     * {@link GLSurfaceView#setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory)}
704     */
705    public interface EGLWindowSurfaceFactory {
706        EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, EGLConfig config,
707                Object nativeWindow);
708        void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface);
709    }
710
711    private static class DefaultWindowSurfaceFactory implements EGLWindowSurfaceFactory {
712
713        public EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display,
714                EGLConfig config, Object nativeWindow) {
715            return egl.eglCreateWindowSurface(display, config, nativeWindow, null);
716        }
717
718        public void destroySurface(EGL10 egl, EGLDisplay display,
719                EGLSurface surface) {
720            egl.eglDestroySurface(display, surface);
721        }
722    }
723
724    /**
725     * An interface for choosing an EGLConfig configuration from a list of
726     * potential configurations.
727     * <p>
728     * This interface must be implemented by clients wishing to call
729     * {@link GLSurfaceView#setEGLConfigChooser(EGLConfigChooser)}
730     */
731    public interface EGLConfigChooser {
732        /**
733         * Choose a configuration from the list. Implementors typically
734         * implement this method by calling
735         * {@link EGL10#eglChooseConfig} and iterating through the results. Please consult the
736         * EGL specification available from The Khronos Group to learn how to call eglChooseConfig.
737         * @param egl the EGL10 for the current display.
738         * @param display the current display.
739         * @return the chosen configuration.
740         */
741        EGLConfig chooseConfig(EGL10 egl, EGLDisplay display);
742    }
743
744    private abstract class BaseConfigChooser
745            implements EGLConfigChooser {
746        public BaseConfigChooser(int[] configSpec) {
747            mConfigSpec = filterConfigSpec(configSpec);
748        }
749
750        public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
751            int[] num_config = new int[1];
752            if (!egl.eglChooseConfig(display, mConfigSpec, null, 0,
753                    num_config)) {
754                throw new IllegalArgumentException("eglChooseConfig failed");
755            }
756
757            int numConfigs = num_config[0];
758
759            if (numConfigs <= 0) {
760                throw new IllegalArgumentException(
761                        "No configs match configSpec");
762            }
763
764            EGLConfig[] configs = new EGLConfig[numConfigs];
765            if (!egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs,
766                    num_config)) {
767                throw new IllegalArgumentException("eglChooseConfig#2 failed");
768            }
769            EGLConfig config = chooseConfig(egl, display, configs);
770            if (config == null) {
771                throw new IllegalArgumentException("No config chosen");
772            }
773            return config;
774        }
775
776        abstract EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
777                EGLConfig[] configs);
778
779        protected int[] mConfigSpec;
780
781        private int[] filterConfigSpec(int[] configSpec) {
782            if (mEGLContextClientVersion != 2) {
783                return configSpec;
784            }
785            /* We know none of the subclasses define EGL_RENDERABLE_TYPE.
786             * And we know the configSpec is well formed.
787             */
788            int len = configSpec.length;
789            int[] newConfigSpec = new int[len + 2];
790            System.arraycopy(configSpec, 0, newConfigSpec, 0, len-1);
791            newConfigSpec[len-1] = EGL10.EGL_RENDERABLE_TYPE;
792            newConfigSpec[len] = 4; /* EGL_OPENGL_ES2_BIT */
793            newConfigSpec[len+1] = EGL10.EGL_NONE;
794            return newConfigSpec;
795        }
796    }
797
798    /**
799     * Choose a configuration with exactly the specified r,g,b,a sizes,
800     * and at least the specified depth and stencil sizes.
801     */
802    private class ComponentSizeChooser extends BaseConfigChooser {
803        public ComponentSizeChooser(int redSize, int greenSize, int blueSize,
804                int alphaSize, int depthSize, int stencilSize) {
805            super(new int[] {
806                    EGL10.EGL_RED_SIZE, redSize,
807                    EGL10.EGL_GREEN_SIZE, greenSize,
808                    EGL10.EGL_BLUE_SIZE, blueSize,
809                    EGL10.EGL_ALPHA_SIZE, alphaSize,
810                    EGL10.EGL_DEPTH_SIZE, depthSize,
811                    EGL10.EGL_STENCIL_SIZE, stencilSize,
812                    EGL10.EGL_NONE});
813            mValue = new int[1];
814            mRedSize = redSize;
815            mGreenSize = greenSize;
816            mBlueSize = blueSize;
817            mAlphaSize = alphaSize;
818            mDepthSize = depthSize;
819            mStencilSize = stencilSize;
820       }
821
822        @Override
823        public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
824                EGLConfig[] configs) {
825            for (EGLConfig config : configs) {
826                int d = findConfigAttrib(egl, display, config,
827                        EGL10.EGL_DEPTH_SIZE, 0);
828                int s = findConfigAttrib(egl, display, config,
829                        EGL10.EGL_STENCIL_SIZE, 0);
830                if ((d >= mDepthSize) && (s >= mStencilSize)) {
831                    int r = findConfigAttrib(egl, display, config,
832                            EGL10.EGL_RED_SIZE, 0);
833                    int g = findConfigAttrib(egl, display, config,
834                             EGL10.EGL_GREEN_SIZE, 0);
835                    int b = findConfigAttrib(egl, display, config,
836                              EGL10.EGL_BLUE_SIZE, 0);
837                    int a = findConfigAttrib(egl, display, config,
838                            EGL10.EGL_ALPHA_SIZE, 0);
839                    if ((r == mRedSize) && (g == mGreenSize)
840                            && (b == mBlueSize) && (a == mAlphaSize)) {
841                        return config;
842                    }
843                }
844            }
845            return null;
846        }
847
848        private int findConfigAttrib(EGL10 egl, EGLDisplay display,
849                EGLConfig config, int attribute, int defaultValue) {
850
851            if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) {
852                return mValue[0];
853            }
854            return defaultValue;
855        }
856
857        private int[] mValue;
858        // Subclasses can adjust these values:
859        protected int mRedSize;
860        protected int mGreenSize;
861        protected int mBlueSize;
862        protected int mAlphaSize;
863        protected int mDepthSize;
864        protected int mStencilSize;
865        }
866
867    /**
868     * This class will choose a RGB_565 surface with
869     * or without a depth buffer.
870     *
871     */
872    private class SimpleEGLConfigChooser extends ComponentSizeChooser {
873        public SimpleEGLConfigChooser(boolean withDepthBuffer) {
874            super(5, 6, 5, 0, withDepthBuffer ? 16 : 0, 0);
875        }
876    }
877
878    /**
879     * An EGL helper class.
880     */
881
882    private class EglHelper {
883        public EglHelper() {
884
885        }
886
887        /**
888         * Initialize EGL for a given configuration spec.
889         * @param configSpec
890         */
891        public void start() {
892            if (LOG_EGL) {
893                Log.w("EglHelper", "start() tid=" + Thread.currentThread().getId());
894            }
895            /*
896             * Get an EGL instance
897             */
898            mEgl = (EGL10) EGLContext.getEGL();
899
900            /*
901             * Get to the default display.
902             */
903            mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
904
905            if (mEglDisplay == EGL10.EGL_NO_DISPLAY) {
906                throw new RuntimeException("eglGetDisplay failed");
907            }
908
909            /*
910             * We can now initialize EGL for that display
911             */
912            int[] version = new int[2];
913            if(!mEgl.eglInitialize(mEglDisplay, version)) {
914                throw new RuntimeException("eglInitialize failed");
915            }
916            mEglConfig = mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay);
917
918            /*
919            * Create an EGL context. We want to do this as rarely as we can, because an
920            * EGL context is a somewhat heavy object.
921            */
922            mEglContext = mEGLContextFactory.createContext(mEgl, mEglDisplay, mEglConfig);
923            if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) {
924                mEglContext = null;
925                throwEglException("createContext");
926            }
927            if (LOG_EGL) {
928                Log.w("EglHelper", "createContext " + mEglContext + " tid=" + Thread.currentThread().getId());
929            }
930
931            mEglSurface = null;
932        }
933
934        /*
935         * React to the creation of a new surface by creating and returning an
936         * OpenGL interface that renders to that surface.
937         */
938        public GL createSurface(SurfaceHolder holder) {
939            if (LOG_EGL) {
940                Log.w("EglHelper", "createSurface()  tid=" + Thread.currentThread().getId());
941            }
942            /*
943             * Check preconditions.
944             */
945            if (mEgl == null) {
946                throw new RuntimeException("egl not initialized");
947            }
948            if (mEglDisplay == null) {
949                throw new RuntimeException("eglDisplay not initialized");
950            }
951            if (mEglConfig == null) {
952                throw new RuntimeException("mEglConfig not initialized");
953            }
954            /*
955             *  The window size has changed, so we need to create a new
956             *  surface.
957             */
958            if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
959
960                /*
961                 * Unbind and destroy the old EGL surface, if
962                 * there is one.
963                 */
964                mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
965                        EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
966                mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface);
967            }
968
969            /*
970             * Create an EGL surface we can render into.
971             */
972            mEglSurface = mEGLWindowSurfaceFactory.createWindowSurface(mEgl,
973                    mEglDisplay, mEglConfig, holder);
974
975            if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) {
976                Log.w("EglHelper", "createWindowSurface failed. mEglDisplay: " + mEglDisplay +
977                        " mEglConfig: " + mEglConfig + " holder: " + holder);
978                throwEglException("createWindowSurface");
979            }
980
981            /*
982             * Before we can issue GL commands, we need to make sure
983             * the context is current and bound to a surface.
984             */
985            if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
986                throwEglException("eglMakeCurrent");
987            }
988
989            GL gl = mEglContext.getGL();
990            if (mGLWrapper != null) {
991                gl = mGLWrapper.wrap(gl);
992            }
993
994            if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS)) != 0) {
995                int configFlags = 0;
996                Writer log = null;
997                if ((mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) {
998                    configFlags |= GLDebugHelper.CONFIG_CHECK_GL_ERROR;
999                }
1000                if ((mDebugFlags & DEBUG_LOG_GL_CALLS) != 0) {
1001                    log = new LogWriter();
1002                }
1003                gl = GLDebugHelper.wrap(gl, configFlags, log);
1004            }
1005            return gl;
1006        }
1007
1008        /**
1009         * Display the current render surface.
1010         * @return false if the context has been lost.
1011         */
1012        public boolean swap() {
1013            if (! mEgl.eglSwapBuffers(mEglDisplay, mEglSurface)) {
1014
1015                /*
1016                 * Check for EGL_CONTEXT_LOST, which means the context
1017                 * and all associated data were lost (For instance because
1018                 * the device went to sleep). We need to sleep until we
1019                 * get a new surface.
1020                 */
1021                int error = mEgl.eglGetError();
1022                if (error == EGL11.EGL_CONTEXT_LOST) {
1023                    return false;
1024                } else {
1025                    throwEglException("eglSwapBuffers", error);
1026                }
1027            }
1028            return true;
1029        }
1030
1031        public void destroySurface() {
1032            if (LOG_EGL) {
1033                Log.w("EglHelper", "destroySurface()  tid=" + Thread.currentThread().getId());
1034            }
1035            if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
1036                mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
1037                        EGL10.EGL_NO_SURFACE,
1038                        EGL10.EGL_NO_CONTEXT);
1039                mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface);
1040                mEglSurface = null;
1041            }
1042        }
1043
1044        public void finish() {
1045            if (LOG_EGL) {
1046                Log.w("EglHelper", "finish() tid=" + Thread.currentThread().getId());
1047            }
1048            if (mEglContext != null) {
1049                mEGLContextFactory.destroyContext(mEgl, mEglDisplay, mEglContext);
1050                mEglContext = null;
1051            }
1052            if (mEglDisplay != null) {
1053                mEgl.eglTerminate(mEglDisplay);
1054                mEglDisplay = null;
1055            }
1056        }
1057
1058        private void throwEglException(String function) {
1059            throwEglException(function, mEgl.eglGetError());
1060        }
1061
1062        private void throwEglException(String function, int error) {
1063            String message = function + " failed: " + EGLLogWrapper.getErrorString(error);
1064            if (LOG_THREADS) {
1065                Log.e("EglHelper", "throwEglException tid=" + Thread.currentThread().getId() + " " + message);
1066            }
1067            throw new RuntimeException(message);
1068        }
1069
1070        EGL10 mEgl;
1071        EGLDisplay mEglDisplay;
1072        EGLSurface mEglSurface;
1073        EGLConfig mEglConfig;
1074        EGLContext mEglContext;
1075
1076    }
1077
1078    /**
1079     * A generic GL Thread. Takes care of initializing EGL and GL. Delegates
1080     * to a Renderer instance to do the actual drawing. Can be configured to
1081     * render continuously or on request.
1082     *
1083     * All potentially blocking synchronization is done through the
1084     * sGLThreadManager object. This avoids multiple-lock ordering issues.
1085     *
1086     */
1087    class GLThread extends Thread {
1088        GLThread(Renderer renderer) {
1089            super();
1090            mWidth = 0;
1091            mHeight = 0;
1092            mRequestRender = true;
1093            mRenderMode = RENDERMODE_CONTINUOUSLY;
1094            mRenderer = renderer;
1095        }
1096
1097
1098        @Override
1099        public void run() {
1100            setName("GLThread " + getId());
1101            if (LOG_THREADS) {
1102                Log.i("GLThread", "starting tid=" + getId());
1103            }
1104
1105            try {
1106                guardedRun();
1107            } catch (InterruptedException e) {
1108                // fall thru and exit normally
1109            } finally {
1110                sGLThreadManager.threadExiting(this);
1111            }
1112        }
1113
1114        /*
1115         * This private method should only be called inside a
1116         * synchronized(sGLThreadManager) block.
1117         */
1118        private void stopEglSurfaceLocked() {
1119            if (mHaveEglSurface) {
1120                mHaveEglSurface = false;
1121                mEglHelper.destroySurface();
1122            }
1123        }
1124
1125        /*
1126         * This private method should only be called inside a
1127         * synchronized(sGLThreadManager) block.
1128         */
1129        private void stopEglContextLocked() {
1130            if (mHaveEglContext) {
1131                mEglHelper.finish();
1132                mHaveEglContext = false;
1133                sGLThreadManager.releaseEglContextLocked(this);
1134            }
1135        }
1136        private void guardedRun() throws InterruptedException {
1137            mEglHelper = new EglHelper();
1138            mHaveEglContext = false;
1139            mHaveEglSurface = false;
1140            try {
1141                GL10 gl = null;
1142                boolean createEglContext = false;
1143                boolean createEglSurface = false;
1144                boolean lostEglContext = false;
1145                boolean sizeChanged = false;
1146                boolean wantRenderNotification = false;
1147                boolean doRenderNotification = false;
1148                int w = 0;
1149                int h = 0;
1150                Runnable event = null;
1151
1152                while (true) {
1153                    synchronized (sGLThreadManager) {
1154                        while (true) {
1155                            if (mShouldExit) {
1156                                return;
1157                            }
1158
1159                            if (! mEventQueue.isEmpty()) {
1160                                event = mEventQueue.remove(0);
1161                                break;
1162                            }
1163
1164                            // Update the pause state.
1165                            if (mPaused != mRequestPaused) {
1166                                mPaused = mRequestPaused;
1167                                sGLThreadManager.notifyAll();
1168                                if (LOG_PAUSE_RESUME) {
1169                                    Log.i("GLThread", "mPaused is now " + mPaused + " tid=" + getId());
1170                                }
1171                            }
1172
1173                            // Have we lost the EGL context?
1174                            if (lostEglContext) {
1175                                stopEglSurfaceLocked();
1176                                stopEglContextLocked();
1177                                lostEglContext = false;
1178                            }
1179
1180                            // Do we need to release the EGL surface?
1181                            if (mHaveEglSurface && mPaused) {
1182                                if (LOG_SURFACE) {
1183                                    Log.i("GLThread", "releasing EGL surface because paused tid=" + getId());
1184                                }
1185                                stopEglSurfaceLocked();
1186                                if (sGLThreadManager.shouldReleaseEGLContextWhenPausing()) {
1187                                    stopEglContextLocked();
1188                                    if (LOG_SURFACE) {
1189                                        Log.i("GLThread", "releasing EGL context because paused tid=" + getId());
1190                                    }
1191                                }
1192                                if (sGLThreadManager.shouldTerminateEGLWhenPausing()) {
1193                                    mEglHelper.finish();
1194                                    if (LOG_SURFACE) {
1195                                        Log.i("GLThread", "terminating EGL because paused tid=" + getId());
1196                                    }
1197                                }
1198                            }
1199
1200                            // Have we lost the surface view surface?
1201                            if ((! mHasSurface) && (! mWaitingForSurface)) {
1202                                if (LOG_SURFACE) {
1203                                    Log.i("GLThread", "noticed surfaceView surface lost tid=" + getId());
1204                                }
1205                                if (mHaveEglSurface) {
1206                                    stopEglSurfaceLocked();
1207                                }
1208                                mWaitingForSurface = true;
1209                                sGLThreadManager.notifyAll();
1210                            }
1211
1212                            // Have we acquired the surface view surface?
1213                            if (mHasSurface && mWaitingForSurface) {
1214                                if (LOG_SURFACE) {
1215                                    Log.i("GLThread", "noticed surfaceView surface acquired tid=" + getId());
1216                                }
1217                                mWaitingForSurface = false;
1218                                sGLThreadManager.notifyAll();
1219                            }
1220
1221                            if (doRenderNotification) {
1222                                wantRenderNotification = false;
1223                                doRenderNotification = false;
1224                                mRenderComplete = true;
1225                                sGLThreadManager.notifyAll();
1226                            }
1227
1228                            // Ready to draw?
1229                            if ((!mPaused) && mHasSurface
1230                                && (mWidth > 0) && (mHeight > 0)
1231                                && (mRequestRender || (mRenderMode == RENDERMODE_CONTINUOUSLY))) {
1232
1233                                // If we don't have an EGL context, try to acquire one.
1234                                if ((! mHaveEglContext) && sGLThreadManager.tryAcquireEglContextLocked(this)) {
1235                                    try {
1236                                        mEglHelper.start();
1237                                    } catch (RuntimeException t) {
1238                                        sGLThreadManager.releaseEglContextLocked(this);
1239                                        throw t;
1240                                    }
1241                                    mHaveEglContext = true;
1242                                    createEglContext = true;
1243
1244                                    sGLThreadManager.notifyAll();
1245                                }
1246
1247                                if (mHaveEglContext && !mHaveEglSurface) {
1248                                    mHaveEglSurface = true;
1249                                    createEglSurface = true;
1250                                    sizeChanged = true;
1251                                }
1252
1253                                if (mHaveEglSurface) {
1254                                    if (mSizeChanged) {
1255                                        sizeChanged = true;
1256                                        w = mWidth;
1257                                        h = mHeight;
1258                                        wantRenderNotification = true;
1259
1260                                        if (DRAW_TWICE_AFTER_SIZE_CHANGED) {
1261                                            // We keep mRequestRender true so that we draw twice after the size changes.
1262                                            // (Once because of mSizeChanged, the second time because of mRequestRender.)
1263                                            // This forces the updated graphics onto the screen.
1264                                        } else {
1265                                            mRequestRender = false;
1266                                        }
1267                                        mSizeChanged = false;
1268                                    } else {
1269                                        mRequestRender = false;
1270                                    }
1271                                    sGLThreadManager.notifyAll();
1272                                    break;
1273                                }
1274                            }
1275
1276                            // By design, this is the only place in a GLThread thread where we wait().
1277                            if (LOG_THREADS) {
1278                                Log.i("GLThread", "waiting tid=" + getId());
1279                            }
1280                            sGLThreadManager.wait();
1281                        }
1282                    } // end of synchronized(sGLThreadManager)
1283
1284                    if (event != null) {
1285                        event.run();
1286                        event = null;
1287                        continue;
1288                    }
1289
1290                    if (createEglSurface) {
1291                        if (LOG_SURFACE) {
1292                            Log.w("GLThread", "egl createSurface");
1293                        }
1294                        gl = (GL10) mEglHelper.createSurface(getHolder());
1295                        sGLThreadManager.checkGLDriver(gl);
1296                        createEglSurface = false;
1297                    }
1298
1299                    if (createEglContext) {
1300                        if (LOG_RENDERER) {
1301                            Log.w("GLThread", "onSurfaceCreated");
1302                        }
1303                        mRenderer.onSurfaceCreated(gl, mEglHelper.mEglConfig);
1304                        createEglContext = false;
1305                    }
1306
1307                    if (sizeChanged) {
1308                        if (LOG_RENDERER) {
1309                            Log.w("GLThread", "onSurfaceChanged(" + w + ", " + h + ")");
1310                        }
1311                        mRenderer.onSurfaceChanged(gl, w, h);
1312                        sizeChanged = false;
1313                    }
1314
1315                    if (LOG_RENDERER_DRAW_FRAME) {
1316                        Log.w("GLThread", "onDrawFrame");
1317                    }
1318                    mRenderer.onDrawFrame(gl);
1319                    if (!mEglHelper.swap()) {
1320                        if (LOG_SURFACE) {
1321                            Log.i("GLThread", "egl context lost tid=" + getId());
1322                        }
1323                        lostEglContext = true;
1324                    }
1325
1326                    if (wantRenderNotification) {
1327                        doRenderNotification = true;
1328                    }
1329                }
1330
1331            } finally {
1332                /*
1333                 * clean-up everything...
1334                 */
1335                synchronized (sGLThreadManager) {
1336                    stopEglSurfaceLocked();
1337                    stopEglContextLocked();
1338                }
1339            }
1340        }
1341
1342        public void setRenderMode(int renderMode) {
1343            if ( !((RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= RENDERMODE_CONTINUOUSLY)) ) {
1344                throw new IllegalArgumentException("renderMode");
1345            }
1346            synchronized(sGLThreadManager) {
1347                mRenderMode = renderMode;
1348                sGLThreadManager.notifyAll();
1349            }
1350        }
1351
1352        public int getRenderMode() {
1353            synchronized(sGLThreadManager) {
1354                return mRenderMode;
1355            }
1356        }
1357
1358        public void requestRender() {
1359            synchronized(sGLThreadManager) {
1360                mRequestRender = true;
1361                sGLThreadManager.notifyAll();
1362            }
1363        }
1364
1365        public void surfaceCreated() {
1366            synchronized(sGLThreadManager) {
1367                if (LOG_THREADS) {
1368                    Log.i("GLThread", "surfaceCreated tid=" + getId());
1369                }
1370                mHasSurface = true;
1371                sGLThreadManager.notifyAll();
1372                while((mWaitingForSurface) && (!mExited)) {
1373                    try {
1374                        sGLThreadManager.wait();
1375                    } catch (InterruptedException e) {
1376                        Thread.currentThread().interrupt();
1377                    }
1378                }
1379            }
1380        }
1381
1382        public void surfaceDestroyed() {
1383            synchronized(sGLThreadManager) {
1384                if (LOG_THREADS) {
1385                    Log.i("GLThread", "surfaceDestroyed tid=" + getId());
1386                }
1387                mHasSurface = false;
1388                sGLThreadManager.notifyAll();
1389                while((!mWaitingForSurface) && (!mExited)) {
1390                    try {
1391                        sGLThreadManager.wait();
1392                    } catch (InterruptedException e) {
1393                        Thread.currentThread().interrupt();
1394                    }
1395                }
1396            }
1397        }
1398
1399        public void onPause() {
1400            synchronized (sGLThreadManager) {
1401                if (LOG_PAUSE_RESUME) {
1402                    Log.i("GLThread", "onPause tid=" + getId());
1403                }
1404                mRequestPaused = true;
1405                sGLThreadManager.notifyAll();
1406                while ((! mExited) && (! mPaused)) {
1407                    if (LOG_PAUSE_RESUME) {
1408                        Log.i("Main thread", "onPause waiting for mPaused.");
1409                    }
1410                    try {
1411                        sGLThreadManager.wait();
1412                    } catch (InterruptedException ex) {
1413                        Thread.currentThread().interrupt();
1414                    }
1415                }
1416            }
1417        }
1418
1419        public void onResume() {
1420            synchronized (sGLThreadManager) {
1421                if (LOG_PAUSE_RESUME) {
1422                    Log.i("GLThread", "onResume tid=" + getId());
1423                }
1424                mRequestPaused = false;
1425                mRequestRender = true;
1426                mRenderComplete = false;
1427                sGLThreadManager.notifyAll();
1428                while ((! mExited) && mPaused && (!mRenderComplete)) {
1429                    if (LOG_PAUSE_RESUME) {
1430                        Log.i("Main thread", "onResume waiting for !mPaused.");
1431                    }
1432                    try {
1433                        sGLThreadManager.wait();
1434                    } catch (InterruptedException ex) {
1435                        Thread.currentThread().interrupt();
1436                    }
1437                }
1438            }
1439        }
1440
1441        public void onWindowResize(int w, int h) {
1442            synchronized (sGLThreadManager) {
1443                mWidth = w;
1444                mHeight = h;
1445                mSizeChanged = true;
1446                mRequestRender = true;
1447                mRenderComplete = false;
1448                sGLThreadManager.notifyAll();
1449
1450                // Wait for thread to react to resize and render a frame
1451                while (! mExited && !mPaused && !mRenderComplete ) {
1452                    if (LOG_SURFACE) {
1453                        Log.i("Main thread", "onWindowResize waiting for render complete.");
1454                    }
1455                    try {
1456                        sGLThreadManager.wait();
1457                    } catch (InterruptedException ex) {
1458                        Thread.currentThread().interrupt();
1459                    }
1460                }
1461            }
1462        }
1463
1464        public void requestExitAndWait() {
1465            // don't call this from GLThread thread or it is a guaranteed
1466            // deadlock!
1467            synchronized(sGLThreadManager) {
1468                mShouldExit = true;
1469                sGLThreadManager.notifyAll();
1470                while (! mExited) {
1471                    try {
1472                        sGLThreadManager.wait();
1473                    } catch (InterruptedException ex) {
1474                        Thread.currentThread().interrupt();
1475                    }
1476                }
1477            }
1478        }
1479
1480        /**
1481         * Queue an "event" to be run on the GL rendering thread.
1482         * @param r the runnable to be run on the GL rendering thread.
1483         */
1484        public void queueEvent(Runnable r) {
1485            if (r == null) {
1486                throw new IllegalArgumentException("r must not be null");
1487            }
1488            synchronized(sGLThreadManager) {
1489                mEventQueue.add(r);
1490                sGLThreadManager.notifyAll();
1491            }
1492        }
1493
1494        // Once the thread is started, all accesses to the following member
1495        // variables are protected by the sGLThreadManager monitor
1496        private boolean mShouldExit;
1497        private boolean mExited;
1498        private boolean mRequestPaused;
1499        private boolean mPaused;
1500        private boolean mHasSurface;
1501        private boolean mWaitingForSurface;
1502        private boolean mHaveEglContext;
1503        private boolean mHaveEglSurface;
1504        private int mWidth;
1505        private int mHeight;
1506        private int mRenderMode;
1507        private boolean mRequestRender;
1508        private boolean mRenderComplete;
1509        private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>();
1510
1511        // End of member variables protected by the sGLThreadManager monitor.
1512
1513        private Renderer mRenderer;
1514        private EglHelper mEglHelper;
1515    }
1516
1517    static class LogWriter extends Writer {
1518
1519        @Override public void close() {
1520            flushBuilder();
1521        }
1522
1523        @Override public void flush() {
1524            flushBuilder();
1525        }
1526
1527        @Override public void write(char[] buf, int offset, int count) {
1528            for(int i = 0; i < count; i++) {
1529                char c = buf[offset + i];
1530                if ( c == '\n') {
1531                    flushBuilder();
1532                }
1533                else {
1534                    mBuilder.append(c);
1535                }
1536            }
1537        }
1538
1539        private void flushBuilder() {
1540            if (mBuilder.length() > 0) {
1541                Log.v("GLSurfaceView", mBuilder.toString());
1542                mBuilder.delete(0, mBuilder.length());
1543            }
1544        }
1545
1546        private StringBuilder mBuilder = new StringBuilder();
1547    }
1548
1549
1550    private void checkRenderThreadState() {
1551        if (mGLThread != null) {
1552            throw new IllegalStateException(
1553                    "setRenderer has already been called for this instance.");
1554        }
1555    }
1556
1557    private static class GLThreadManager {
1558        private static String TAG = "GLThreadManager";
1559
1560        public synchronized void threadExiting(GLThread thread) {
1561            if (LOG_THREADS) {
1562                Log.i("GLThread", "exiting tid=" +  thread.getId());
1563            }
1564            thread.mExited = true;
1565            if (mEglOwner == thread) {
1566                mEglOwner = null;
1567            }
1568            notifyAll();
1569        }
1570
1571        /*
1572         * Tries once to acquire the right to use an EGL
1573         * context. Does not block. Requires that we are already
1574         * in the sGLThreadManager monitor when this is called.
1575         *
1576         * @return true if the right to use an EGL context was acquired.
1577         */
1578        public boolean tryAcquireEglContextLocked(GLThread thread) {
1579            if (mEglOwner == thread || mEglOwner == null) {
1580                mEglOwner = thread;
1581                notifyAll();
1582                return true;
1583            }
1584            checkGLESVersion();
1585            if (mMultipleGLESContextsAllowed) {
1586                return true;
1587            }
1588            return false;
1589        }
1590
1591        /*
1592         * Releases the EGL context. Requires that we are already in the
1593         * sGLThreadManager monitor when this is called.
1594         */
1595        public void releaseEglContextLocked(GLThread thread) {
1596            if (mEglOwner == thread) {
1597                mEglOwner = null;
1598            }
1599            notifyAll();
1600        }
1601
1602        public synchronized boolean shouldReleaseEGLContextWhenPausing() {
1603            // Release the EGL context when pausing even if
1604            // the hardware supports multiple EGL contexts.
1605            // Otherwise the device could run out of EGL contexts.
1606            return true;
1607        }
1608
1609        public synchronized boolean shouldTerminateEGLWhenPausing() {
1610            checkGLESVersion();
1611            return !mMultipleGLESContextsAllowed;
1612        }
1613
1614        public synchronized void checkGLDriver(GL10 gl) {
1615            if (! mGLESDriverCheckComplete) {
1616                checkGLESVersion();
1617                if (mGLESVersion < kGLES_20) {
1618                    String renderer = gl.glGetString(GL10.GL_RENDERER);
1619                    mMultipleGLESContextsAllowed =
1620                        ! renderer.startsWith(kMSM7K_RENDERER_PREFIX);
1621                    if (LOG_SURFACE) {
1622                        Log.w(TAG, "checkGLDriver renderer = \"" + renderer + "\" multipleContextsAllowed = "
1623                            + mMultipleGLESContextsAllowed);
1624                    }
1625                    notifyAll();
1626                }
1627                mGLESDriverCheckComplete = true;
1628            }
1629        }
1630
1631        private void checkGLESVersion() {
1632            if (! mGLESVersionCheckComplete) {
1633                mGLESVersion = SystemProperties.getInt(
1634                        "ro.opengles.version",
1635                        ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1636                if (mGLESVersion >= kGLES_20) {
1637                    mMultipleGLESContextsAllowed = true;
1638                }
1639                if (LOG_SURFACE) {
1640                    Log.w(TAG, "checkGLESVersion mGLESVersion =" +
1641                            " " + mGLESVersion + " mMultipleGLESContextsAllowed = " + mMultipleGLESContextsAllowed);
1642                }
1643                mGLESVersionCheckComplete = true;
1644            }
1645        }
1646
1647        private boolean mGLESVersionCheckComplete;
1648        private int mGLESVersion;
1649        private boolean mGLESDriverCheckComplete;
1650        private boolean mMultipleGLESContextsAllowed;
1651        private static final int kGLES_20 = 0x20000;
1652        private static final String kMSM7K_RENDERER_PREFIX =
1653            "Q3Dimension MSM7500 ";
1654        private GLThread mEglOwner;
1655    }
1656
1657    private static final GLThreadManager sGLThreadManager = new GLThreadManager();
1658    private boolean mSizeChanged = true;
1659
1660    private GLThread mGLThread;
1661    private EGLConfigChooser mEGLConfigChooser;
1662    private EGLContextFactory mEGLContextFactory;
1663    private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory;
1664    private GLWrapper mGLWrapper;
1665    private int mDebugFlags;
1666    private int mEGLContextClientVersion;
1667}
1668