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