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