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