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