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