GLSurfaceView.java revision 15e1c6dc7a778590068b1cad55beea2bc6159509
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;
21import java.util.concurrent.Semaphore;
22
23import javax.microedition.khronos.egl.EGL10;
24import javax.microedition.khronos.egl.EGL11;
25import javax.microedition.khronos.egl.EGLConfig;
26import javax.microedition.khronos.egl.EGLContext;
27import javax.microedition.khronos.egl.EGLDisplay;
28import javax.microedition.khronos.egl.EGLSurface;
29import javax.microedition.khronos.opengles.GL;
30import javax.microedition.khronos.opengles.GL10;
31
32import android.content.Context;
33import android.util.AttributeSet;
34import android.util.Log;
35import android.view.SurfaceHolder;
36import android.view.SurfaceView;
37
38/**
39 * An implementation of SurfaceView that uses the dedicated surface for
40 * displaying OpenGL rendering.
41 * <p>
42 * A GLSurfaceView provides the following features:
43 * <p>
44 * <ul>
45 * <li>Manages a surface, which is a special piece of memory that can be
46 * composited into the Android view system.
47 * <li>Manages an EGL display, which enables OpenGL to render into a surface.
48 * <li>Accepts a user-provided Renderer object that does the actual rendering.
49 * <li>Renders on a dedicated thread to decouple rendering performance from the
50 * UI thread.
51 * <li>Supports both on-demand and continuous rendering.
52 * <li>Optionally wraps, traces, and/or error-checks the renderer's OpenGL calls.
53 * </ul>
54 *
55 * <h3>Using GLSurfaceView</h3>
56 * <p>
57 * Typically you use GLSurfaceView by subclassing it and overriding one or more of the
58 * View system input event methods. If your application does not need to override event
59 * methods then GLSurfaceView can be used as-is. For the most part
60 * GLSurfaceView behavior is customized by calling "set" methods rather than by subclassing.
61 * For example, unlike a regular View, drawing is delegated to a separate Renderer object which
62 * is registered with the GLSurfaceView
63 * using the {@link #setRenderer(Renderer)} call.
64 * <p>
65 * <h3>Initializing GLSurfaceView</h3>
66 * All you have to do to initialize a GLSurfaceView is call {@link #setRenderer(Renderer)}.
67 * However, if desired, you can modify the default behavior of GLSurfaceView by calling one or
68 * more of these methods before calling setRenderer:
69 * <ul>
70 * <li>{@link #setDebugFlags(int)}
71 * <li>{@link #setEGLConfigChooser(boolean)}
72 * <li>{@link #setEGLConfigChooser(EGLConfigChooser)}
73 * <li>{@link #setEGLConfigChooser(int, int, int, int, int, int)}
74 * <li>{@link #setGLWrapper(GLWrapper)}
75 * </ul>
76 * <p>
77 * <h4>Choosing an EGL Configuration</h4>
78 * A given Android device may support multiple possible types of drawing surfaces.
79 * The available surfaces may differ in how may channels of data are present, as
80 * well as how many bits are allocated to each channel. Therefore, the first thing
81 * GLSurfaceView has to do when starting to render is choose what type of surface to use.
82 * <p>
83 * By default GLSurfaceView chooses an available surface that's closest to a 16-bit R5G6B5 surface
84 * with a 16-bit depth buffer and no stencil. If you would prefer a different surface (for example,
85 * if you do not need a depth buffer) you can override the default behavior by calling one of the
86 * setEGLConfigChooser methods.
87 * <p>
88 * <h4>Debug Behavior</h4>
89 * You can optionally modify the behavior of GLSurfaceView by calling
90 * one or more of the debugging methods {@link #setDebugFlags(int)},
91 * and {@link #setGLWrapper}. These methods may be called before and/or after setRenderer, but
92 * typically they are called before setRenderer so that they take effect immediately.
93 * <p>
94 * <h4>Setting a Renderer</h4>
95 * Finally, you must call {@link #setRenderer} to register a {@link Renderer}.
96 * The renderer is
97 * responsible for doing the actual OpenGL rendering.
98 * <p>
99 * <h3>Rendering Mode</h3>
100 * Once the renderer is set, you can control whether the renderer draws
101 * continuously or on-demand by calling
102 * {@link #setRenderMode}. The default is continuous rendering.
103 * <p>
104 * <h3>Activity Life-cycle</h3>
105 * A GLSurfaceView must be notified when the activity is paused and resumed. GLSurfaceView clients
106 * are required to call {@link #onPause()} when the activity pauses and
107 * {@link #onResume()} when the activity resumes. These calls allow GLSurfaceView to
108 * pause and resume the rendering thread, and also allow GLSurfaceView to release and recreate
109 * the OpenGL display.
110 * <p>
111 * <h3>Handling events</h3>
112 * <p>
113 * To handle an event you will typically subclass GLSurfaceView and override the
114 * appropriate method, just as you would with any other View. However, when handling
115 * the event, you may need to communicate with the Renderer object
116 * that's running in the rendering thread. You can do this using any
117 * standard Java cross-thread communication mechanism. In addition,
118 * one relatively easy way to communicate with your renderer is
119 * to call
120 * {@link #queueEvent(Runnable)}. For example:
121 * <pre class="prettyprint">
122 * class MyGLSurfaceView extends GLSurfaceView {
123 *
124 *     private MyRenderer mMyRenderer;
125 *
126 *     public void start() {
127 *         mMyRenderer = ...;
128 *         setRenderer(mMyRenderer);
129 *     }
130 *
131 *     public boolean onKeyDown(int keyCode, KeyEvent event) {
132 *         if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
133 *             queueEvent(new Runnable() {
134 *                 // This method will be called on the rendering
135 *                 // thread:
136 *                 public void run() {
137 *                     mMyRenderer.handleDpadCenter();
138 *                 }});
139 *             return true;
140 *         }
141 *         return super.onKeyDown(keyCode, event);
142 *     }
143 * }
144 * </pre>
145 *
146 */
147public class GLSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
148    /**
149     * The renderer only renders
150     * when the surface is created, or when {@link #requestRender} is called.
151     *
152     * @see #getRenderMode()
153     * @see #setRenderMode(int)
154     */
155    public final static int RENDERMODE_WHEN_DIRTY = 0;
156    /**
157     * The renderer is called
158     * continuously to re-render the scene.
159     *
160     * @see #getRenderMode()
161     * @see #setRenderMode(int)
162     * @see #requestRender()
163     */
164    public final static int RENDERMODE_CONTINUOUSLY = 1;
165
166    /**
167     * Check glError() after every GL call and throw an exception if glError indicates
168     * that an error has occurred. This can be used to help track down which OpenGL ES call
169     * is causing an error.
170     *
171     * @see #getDebugFlags
172     * @see #setDebugFlags
173     */
174    public final static int DEBUG_CHECK_GL_ERROR = 1;
175
176    /**
177     * Log GL calls to the system log at "verbose" level with tag "GLSurfaceView".
178     *
179     * @see #getDebugFlags
180     * @see #setDebugFlags
181     */
182    public final static int DEBUG_LOG_GL_CALLS = 2;
183
184    /**
185     * Standard View constructor. In order to render something, you
186     * must call {@link #setRenderer} to register a renderer.
187     */
188    public GLSurfaceView(Context context) {
189        super(context);
190        init();
191    }
192
193    /**
194     * Standard View constructor. In order to render something, you
195     * must call {@link #setRenderer} to register a renderer.
196     */
197    public GLSurfaceView(Context context, AttributeSet attrs) {
198        super(context, attrs);
199        init();
200    }
201
202    private void init() {
203        // Install a SurfaceHolder.Callback so we get notified when the
204        // underlying surface is created and destroyed
205        SurfaceHolder holder = getHolder();
206        holder.addCallback(this);
207    }
208
209    /**
210     * Set the glWrapper. If the glWrapper is not null, its
211     * {@link GLWrapper#wrap(GL)} method is called
212     * whenever a surface is created. A GLWrapper can be used to wrap
213     * the GL object that's passed to the renderer. Wrapping a GL
214     * object enables examining and modifying the behavior of the
215     * GL calls made by the renderer.
216     * <p>
217     * Wrapping is typically used for debugging purposes.
218     * <p>
219     * The default value is null.
220     * @param glWrapper the new GLWrapper
221     */
222    public void setGLWrapper(GLWrapper glWrapper) {
223        mGLWrapper = glWrapper;
224    }
225
226    /**
227     * Set the debug flags to a new value. The value is
228     * constructed by OR-together zero or more
229     * of the DEBUG_CHECK_* constants. The debug flags take effect
230     * whenever a surface is created. The default value is zero.
231     * @param debugFlags the new debug flags
232     * @see #DEBUG_CHECK_GL_ERROR
233     * @see #DEBUG_LOG_GL_CALLS
234     */
235    public void setDebugFlags(int debugFlags) {
236        mDebugFlags = debugFlags;
237    }
238
239    /**
240     * Get the current value of the debug flags.
241     * @return the current value of the debug flags.
242     */
243    public int getDebugFlags() {
244        return mDebugFlags;
245    }
246
247    /**
248     * Set the renderer associated with this view. Also starts the thread that
249     * will call the renderer, which in turn causes the rendering to start.
250     * <p>This method should be called once and only once in the life-cycle of
251     * a GLSurfaceView.
252     * <p>The following GLSurfaceView methods can only be called <em>before</em>
253     * setRenderer is called:
254     * <ul>
255     * <li>{@link #setEGLConfigChooser(boolean)}
256     * <li>{@link #setEGLConfigChooser(EGLConfigChooser)}
257     * <li>{@link #setEGLConfigChooser(int, int, int, int, int, int)}
258     * </ul>
259     * <p>
260     * The following GLSurfaceView methods can only be called <em>after</em>
261     * setRenderer is called:
262     * <ul>
263     * <li>{@link #getRenderMode()}
264     * <li>{@link #onPause()}
265     * <li>{@link #onResume()}
266     * <li>{@link #queueEvent(Runnable)}
267     * <li>{@link #requestRender()}
268     * <li>{@link #setRenderMode(int)}
269     * </ul>
270     *
271     * @param renderer the renderer to use to perform OpenGL drawing.
272     */
273    public void setRenderer(Renderer renderer) {
274        checkRenderThreadState();
275        if (mEGLConfigChooser == null) {
276            mEGLConfigChooser = new SimpleEGLConfigChooser(true);
277        }
278        if (mEGLContextFactory == null) {
279            mEGLContextFactory = new DefaultContextFactory();
280        }
281        if (mEGLWindowSurfaceFactory == null) {
282            mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory();
283        }
284        mGLThread = new GLThread(renderer);
285        mGLThread.start();
286    }
287
288    /**
289     * @hide
290     * Install a custom EGLContextFactory.
291     * <p>If this method is
292     * called, it must be called before {@link #setRenderer(Renderer)}
293     * is called.
294     * <p>
295     * If this method is not called, then by default
296     * a context will be created with no shared context and
297     * with a null attribute list.
298     */
299    public void setContextFactory(EGLContextFactory factory) {
300        checkRenderThreadState();
301        mEGLContextFactory = factory;
302    }
303
304    /**
305     * @hide
306     * Install a custom EGLWindowSurfaceFactory.
307     * <p>If this method is
308     * called, it must be called before {@link #setRenderer(Renderer)}
309     * is called.
310     * <p>
311     * If this method is not called, then by default
312     * a window surface will be created with a null attribute list.
313     */
314    public void setWindowSurfaceFactory(EGLWindowSurfaceFactory factory) {
315        checkRenderThreadState();
316        mEGLWindowSurfaceFactory = factory;
317    }
318
319    /**
320     * Install a custom EGLConfigChooser.
321     * <p>If this method is
322     * called, it must be called before {@link #setRenderer(Renderer)}
323     * is called.
324     * <p>
325     * If no setEGLConfigChooser method is called, then by default the
326     * view will choose a config as close to 16-bit RGB as possible, with
327     * a depth buffer as close to 16 bits as possible.
328     * @param configChooser
329     */
330    public void setEGLConfigChooser(EGLConfigChooser configChooser) {
331        checkRenderThreadState();
332        mEGLConfigChooser = configChooser;
333    }
334
335    /**
336     * Install a config chooser which will choose a config
337     * as close to 16-bit RGB as possible, with or without an optional depth
338     * buffer as close to 16-bits as possible.
339     * <p>If this method is
340     * called, it must be called before {@link #setRenderer(Renderer)}
341     * is called.
342     * <p>
343      * If no setEGLConfigChooser method is called, then by default the
344     * view will choose a config as close to 16-bit RGB as possible, with
345     * a depth buffer as close to 16 bits as possible.
346     *
347     * @param needDepth
348     */
349    public void setEGLConfigChooser(boolean needDepth) {
350        setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth));
351    }
352
353    /**
354     * Install a config chooser which will choose a config
355     * with at least the specified component sizes, and as close
356     * to the specified component sizes as possible.
357     * <p>If this method is
358     * called, it must be called before {@link #setRenderer(Renderer)}
359     * is called.
360     * <p>
361     * If no setEGLConfigChooser method is called, then by default the
362     * view will choose a config as close to 16-bit RGB as possible, with
363     * a depth buffer as close to 16 bits as possible.
364     *
365     */
366    public void setEGLConfigChooser(int redSize, int greenSize, int blueSize,
367            int alphaSize, int depthSize, int stencilSize) {
368        setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize,
369                blueSize, alphaSize, depthSize, stencilSize));
370    }
371    /**
372     * Set the rendering mode. When renderMode is
373     * RENDERMODE_CONTINUOUSLY, the renderer is called
374     * repeatedly to re-render the scene. When renderMode
375     * is RENDERMODE_WHEN_DIRTY, the renderer only rendered when the surface
376     * is created, or when {@link #requestRender} is called. Defaults to RENDERMODE_CONTINUOUSLY.
377     * <p>
378     * Using RENDERMODE_WHEN_DIRTY can improve battery life and overall system performance
379     * by allowing the GPU and CPU to idle when the view does not need to be updated.
380     * <p>
381     * This method can only be called after {@link #setRenderer(Renderer)}
382     *
383     * @param renderMode one of the RENDERMODE_X constants
384     * @see #RENDERMODE_CONTINUOUSLY
385     * @see #RENDERMODE_WHEN_DIRTY
386     */
387    public void setRenderMode(int renderMode) {
388        mGLThread.setRenderMode(renderMode);
389    }
390
391    /**
392     * Get the current rendering mode. May be called
393     * from any thread. Must not be called before a renderer has been set.
394     * @return the current rendering mode.
395     * @see #RENDERMODE_CONTINUOUSLY
396     * @see #RENDERMODE_WHEN_DIRTY
397     */
398    public int getRenderMode() {
399        return mGLThread.getRenderMode();
400    }
401
402    /**
403     * Request that the renderer render a frame.
404     * This method is typically used when the render mode has been set to
405     * {@link #RENDERMODE_WHEN_DIRTY}, so that frames are only rendered on demand.
406     * May be called
407     * from any thread. Must not be called before a renderer has been set.
408     */
409    public void requestRender() {
410        mGLThread.requestRender();
411    }
412
413    /**
414     * This method is part of the SurfaceHolder.Callback interface, and is
415     * not normally called or subclassed by clients of GLSurfaceView.
416     */
417    public void surfaceCreated(SurfaceHolder holder) {
418        mGLThread.surfaceCreated();
419    }
420
421    /**
422     * This method is part of the SurfaceHolder.Callback interface, and is
423     * not normally called or subclassed by clients of GLSurfaceView.
424     */
425    public void surfaceDestroyed(SurfaceHolder holder) {
426        // Surface will be destroyed when we return
427        mGLThread.surfaceDestroyed();
428    }
429
430    /**
431     * This method is part of the SurfaceHolder.Callback interface, and is
432     * not normally called or subclassed by clients of GLSurfaceView.
433     */
434    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
435        mGLThread.onWindowResize(w, h);
436    }
437
438    /**
439     * Inform the view that the activity is paused. The owner of this view must
440     * call this method when the activity is paused. Calling this method will
441     * pause the rendering thread.
442     * Must not be called before a renderer has been set.
443     */
444    public void onPause() {
445        mGLThread.onPause();
446    }
447
448    /**
449     * Inform the view that the activity is resumed. The owner of this view must
450     * call this method when the activity is resumed. Calling this method will
451     * recreate the OpenGL display and resume the rendering
452     * thread.
453     * Must not be called before a renderer has been set.
454     */
455    public void onResume() {
456        mGLThread.onResume();
457    }
458
459    /**
460     * Queue a runnable to be run on the GL rendering thread. This can be used
461     * to communicate with the Renderer on the rendering thread.
462     * Must not be called before a renderer has been set.
463     * @param r the runnable to be run on the GL rendering thread.
464     */
465    public void queueEvent(Runnable r) {
466        mGLThread.queueEvent(r);
467    }
468
469    /**
470     * This method is used as part of the View class and is not normally
471     * called or subclassed by clients of GLSurfaceView.
472     * Must not be called before a renderer has been set.
473     */
474    @Override
475    protected void onDetachedFromWindow() {
476        super.onDetachedFromWindow();
477        mGLThread.requestExitAndWait();
478    }
479
480    // ----------------------------------------------------------------------
481
482    /**
483     * An interface used to wrap a GL interface.
484     * <p>Typically
485     * used for implementing debugging and tracing on top of the default
486     * GL interface. You would typically use this by creating your own class
487     * that implemented all the GL methods by delegating to another GL instance.
488     * Then you could add your own behavior before or after calling the
489     * delegate. All the GLWrapper would do was instantiate and return the
490     * wrapper GL instance:
491     * <pre class="prettyprint">
492     * class MyGLWrapper implements GLWrapper {
493     *     GL wrap(GL gl) {
494     *         return new MyGLImplementation(gl);
495     *     }
496     *     static class MyGLImplementation implements GL,GL10,GL11,... {
497     *         ...
498     *     }
499     * }
500     * </pre>
501     * @see #setGLWrapper(GLWrapper)
502     */
503    public interface GLWrapper {
504        /**
505         * Wraps a gl interface in another gl interface.
506         * @param gl a GL interface that is to be wrapped.
507         * @return either the input argument or another GL object that wraps the input argument.
508         */
509        GL wrap(GL gl);
510    }
511
512    /**
513     * A generic renderer interface.
514     * <p>
515     * The renderer is responsible for making OpenGL calls to render a frame.
516     * <p>
517     * GLSurfaceView clients typically create their own classes that implement
518     * this interface, and then call {@link GLSurfaceView#setRenderer} to
519     * register the renderer with the GLSurfaceView.
520     * <p>
521     * <h3>Threading</h3>
522     * The renderer will be called on a separate thread, so that rendering
523     * performance is decoupled from the UI thread. Clients typically need to
524     * communicate with the renderer from the UI thread, because that's where
525     * input events are received. Clients can communicate using any of the
526     * standard Java techniques for cross-thread communication, or they can
527     * use the {@link GLSurfaceView#queueEvent(Runnable)} convenience method.
528     * <p>
529     * <h3>EGL Context Lost</h3>
530     * There are situations where the EGL rendering context will be lost. This
531     * typically happens when device wakes up after going to sleep. When
532     * the EGL context is lost, all OpenGL resources (such as textures) that are
533     * associated with that context will be automatically deleted. In order to
534     * keep rendering correctly, a renderer must recreate any lost resources
535     * that it still needs. The {@link #onSurfaceCreated(GL10, EGLConfig)} method
536     * is a convenient place to do this.
537     *
538     *
539     * @see #setRenderer(Renderer)
540     */
541    public interface Renderer {
542        /**
543         * Called when the surface is created or recreated.
544         * <p>
545         * Called when the rendering thread
546         * starts and whenever the EGL context is lost. The context will typically
547         * be lost when the Android device awakes after going to sleep.
548         * <p>
549         * Since this method is called at the beginning of rendering, as well as
550         * every time the EGL context is lost, this method is a convenient place to put
551         * code to create resources that need to be created when the rendering
552         * starts, and that need to be recreated when the EGL context is lost.
553         * Textures are an example of a resource that you might want to create
554         * here.
555         * <p>
556         * Note that when the EGL context is lost, all OpenGL resources associated
557         * with that context will be automatically deleted. You do not need to call
558         * the corresponding "glDelete" methods such as glDeleteTextures to
559         * manually delete these lost resources.
560         * <p>
561         * @param gl the GL interface. Use <code>instanceof</code> to
562         * test if the interface supports GL11 or higher interfaces.
563         * @param config the EGLConfig of the created surface. Can be used
564         * to create matching pbuffers.
565         */
566        void onSurfaceCreated(GL10 gl, EGLConfig config);
567
568        /**
569         * Called when the surface changed size.
570         * <p>
571         * Called after the surface is created and whenever
572         * the OpenGL ES surface size changes.
573         * <p>
574         * Typically you will set your viewport here. If your camera
575         * is fixed then you could also set your projection matrix here:
576         * <pre class="prettyprint">
577         * void onSurfaceChanged(GL10 gl, int width, int height) {
578         *     gl.glViewport(0, 0, width, height);
579         *     // for a fixed camera, set the projection too
580         *     float ratio = (float) width / height;
581         *     gl.glMatrixMode(GL10.GL_PROJECTION);
582         *     gl.glLoadIdentity();
583         *     gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
584         * }
585         * </pre>
586         * @param gl the GL interface. Use <code>instanceof</code> to
587         * test if the interface supports GL11 or higher interfaces.
588         * @param width
589         * @param height
590         */
591        void onSurfaceChanged(GL10 gl, int width, int height);
592
593        /**
594         * Called to draw the current frame.
595         * <p>
596         * This method is responsible for drawing the current frame.
597         * <p>
598         * The implementation of this method typically looks like this:
599         * <pre class="prettyprint">
600         * void onDrawFrame(GL10 gl) {
601         *     gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
602         *     //... other gl calls to render the scene ...
603         * }
604         * </pre>
605         * @param gl the GL interface. Use <code>instanceof</code> to
606         * test if the interface supports GL11 or higher interfaces.
607         */
608        void onDrawFrame(GL10 gl);
609    }
610
611    /**
612     * @hide
613     * An interface for customizing the eglCreateContext and eglDestroyContext calls.
614     * <p>
615     * This interface must be implemented by clients wishing to call
616     * {@link GLSurfaceView#setEGLContextFactory(EGLContextFactory)}
617     */
618    public interface EGLContextFactory {
619        EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig);
620        void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context);
621    }
622
623    private static class DefaultContextFactory implements EGLContextFactory {
624
625        public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig config) {
626            return egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT, null);
627        }
628
629        public void destroyContext(EGL10 egl, EGLDisplay display,
630                EGLContext context) {
631            egl.eglDestroyContext(display, context);
632        }
633    }
634
635    /**
636     * @hide
637     * An interface for customizing the eglCreateWindowSurface and eglDestroySurface calls.
638     * <p>
639     * This interface must be implemented by clients wishing to call
640     * {@link GLSurfaceView#setEGLContextCreator(EGLContextCreator)}
641     */
642    public interface EGLWindowSurfaceFactory {
643        EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, EGLConfig config,
644                Object nativeWindow);
645        void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface);
646    }
647
648    private static class DefaultWindowSurfaceFactory implements EGLWindowSurfaceFactory {
649
650        public EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display,
651                EGLConfig config, Object nativeWindow) {
652            return egl.eglCreateWindowSurface(display, config, nativeWindow, null);
653        }
654
655        public void destroySurface(EGL10 egl, EGLDisplay display,
656                EGLSurface surface) {
657            egl.eglDestroySurface(display, surface);
658        }
659    }
660
661    /**
662     * An interface for choosing an EGLConfig configuration from a list of
663     * potential configurations.
664     * <p>
665     * This interface must be implemented by clients wishing to call
666     * {@link GLSurfaceView#setEGLConfigChooser(EGLConfigChooser)}
667     */
668    public interface EGLConfigChooser {
669        /**
670         * Choose a configuration from the list. Implementors typically
671         * implement this method by calling
672         * {@link EGL10#eglChooseConfig} and iterating through the results. Please consult the
673         * EGL specification available from The Khronos Group to learn how to call eglChooseConfig.
674         * @param egl the EGL10 for the current display.
675         * @param display the current display.
676         * @return the chosen configuration.
677         */
678        EGLConfig chooseConfig(EGL10 egl, EGLDisplay display);
679    }
680
681    private static abstract class BaseConfigChooser
682            implements EGLConfigChooser {
683        public BaseConfigChooser(int[] configSpec) {
684            mConfigSpec = configSpec;
685        }
686        public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
687            int[] num_config = new int[1];
688            egl.eglChooseConfig(display, mConfigSpec, null, 0, num_config);
689
690            int numConfigs = num_config[0];
691
692            if (numConfigs <= 0) {
693                throw new IllegalArgumentException(
694                        "No configs match configSpec");
695            }
696
697            EGLConfig[] configs = new EGLConfig[numConfigs];
698            egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs,
699                    num_config);
700            EGLConfig config = chooseConfig(egl, display, configs);
701            if (config == null) {
702                throw new IllegalArgumentException("No config chosen");
703            }
704            return config;
705        }
706
707        abstract EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
708                EGLConfig[] configs);
709
710        protected int[] mConfigSpec;
711    }
712
713    private static class ComponentSizeChooser extends BaseConfigChooser {
714        public ComponentSizeChooser(int redSize, int greenSize, int blueSize,
715                int alphaSize, int depthSize, int stencilSize) {
716            super(new int[] {
717                    EGL10.EGL_RED_SIZE, redSize,
718                    EGL10.EGL_GREEN_SIZE, greenSize,
719                    EGL10.EGL_BLUE_SIZE, blueSize,
720                    EGL10.EGL_ALPHA_SIZE, alphaSize,
721                    EGL10.EGL_DEPTH_SIZE, depthSize,
722                    EGL10.EGL_STENCIL_SIZE, stencilSize,
723                    EGL10.EGL_NONE});
724            mValue = new int[1];
725            mRedSize = redSize;
726            mGreenSize = greenSize;
727            mBlueSize = blueSize;
728            mAlphaSize = alphaSize;
729            mDepthSize = depthSize;
730            mStencilSize = stencilSize;
731       }
732
733        @Override
734        public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
735                EGLConfig[] configs) {
736            EGLConfig closestConfig = null;
737            int closestDistance = 1000;
738            for(EGLConfig config : configs) {
739                int d = findConfigAttrib(egl, display, config,
740                        EGL10.EGL_DEPTH_SIZE, 0);
741                int s = findConfigAttrib(egl, display, config,
742                        EGL10.EGL_STENCIL_SIZE, 0);
743                if (d >= mDepthSize && s>= mStencilSize) {
744                    int r = findConfigAttrib(egl, display, config,
745                            EGL10.EGL_RED_SIZE, 0);
746                    int g = findConfigAttrib(egl, display, config,
747                             EGL10.EGL_GREEN_SIZE, 0);
748                    int b = findConfigAttrib(egl, display, config,
749                              EGL10.EGL_BLUE_SIZE, 0);
750                    int a = findConfigAttrib(egl, display, config,
751                            EGL10.EGL_ALPHA_SIZE, 0);
752                    int distance = Math.abs(r - mRedSize)
753                                + Math.abs(g - mGreenSize)
754                                + Math.abs(b - mBlueSize)
755                                + Math.abs(a - mAlphaSize);
756                    if (distance < closestDistance) {
757                        closestDistance = distance;
758                        closestConfig = config;
759                    }
760                }
761            }
762            return closestConfig;
763        }
764
765        private int findConfigAttrib(EGL10 egl, EGLDisplay display,
766                EGLConfig config, int attribute, int defaultValue) {
767
768            if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) {
769                return mValue[0];
770            }
771            return defaultValue;
772        }
773
774        private int[] mValue;
775        // Subclasses can adjust these values:
776        protected int mRedSize;
777        protected int mGreenSize;
778        protected int mBlueSize;
779        protected int mAlphaSize;
780        protected int mDepthSize;
781        protected int mStencilSize;
782        }
783
784    /**
785     * This class will choose a supported surface as close to
786     * RGB565 as possible, with or without a depth buffer.
787     *
788     */
789    private static class SimpleEGLConfigChooser extends ComponentSizeChooser {
790        public SimpleEGLConfigChooser(boolean withDepthBuffer) {
791            super(4, 4, 4, 0, withDepthBuffer ? 16 : 0, 0);
792            // Adjust target values. This way we'll accept a 4444 or
793            // 555 buffer if there's no 565 buffer available.
794            mRedSize = 5;
795            mGreenSize = 6;
796            mBlueSize = 5;
797        }
798    }
799
800    /**
801     * An EGL helper class.
802     */
803
804    private class EglHelper {
805        public EglHelper() {
806
807        }
808
809        /**
810         * Initialize EGL for a given configuration spec.
811         * @param configSpec
812         */
813        public void start(){
814            /*
815             * Get an EGL instance
816             */
817            mEgl = (EGL10) EGLContext.getEGL();
818
819            /*
820             * Get to the default display.
821             */
822            mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
823
824            /*
825             * We can now initialize EGL for that display
826             */
827            int[] version = new int[2];
828            mEgl.eglInitialize(mEglDisplay, version);
829            mEglConfig = mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay);
830
831            /*
832            * Create an OpenGL ES context. This must be done only once, an
833            * OpenGL context is a somewhat heavy object.
834            */
835            mEglContext = mEGLContextFactory.createContext(mEgl, mEglDisplay, mEglConfig);
836
837            mEglSurface = null;
838        }
839
840        /*
841         * React to the creation of a new surface by creating and returning an
842         * OpenGL interface that renders to that surface.
843         */
844        public GL createSurface(SurfaceHolder holder) {
845            /*
846             *  The window size has changed, so we need to create a new
847             *  surface.
848             */
849            if (mEglSurface != null) {
850
851                /*
852                 * Unbind and destroy the old EGL surface, if
853                 * there is one.
854                 */
855                mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
856                        EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
857                mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface);
858            }
859
860            /*
861             * Create an EGL surface we can render into.
862             */
863            mEglSurface = mEGLWindowSurfaceFactory.createWindowSurface(mEgl,
864                    mEglDisplay, mEglConfig, holder);
865
866            /*
867             * Before we can issue GL commands, we need to make sure
868             * the context is current and bound to a surface.
869             */
870            mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
871                    mEglContext);
872
873            GL gl = mEglContext.getGL();
874            if (mGLWrapper != null) {
875                gl = mGLWrapper.wrap(gl);
876            }
877
878            if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS))!= 0) {
879                int configFlags = 0;
880                Writer log = null;
881                if ((mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) {
882                    configFlags |= GLDebugHelper.CONFIG_CHECK_GL_ERROR;
883                }
884                if ((mDebugFlags & DEBUG_LOG_GL_CALLS) != 0) {
885                    log = new LogWriter();
886                }
887                gl = GLDebugHelper.wrap(gl, configFlags, log);
888            }
889            return gl;
890        }
891
892        /**
893         * Display the current render surface.
894         * @return false if the context has been lost.
895         */
896        public boolean swap() {
897            mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
898
899            /*
900             * Always check for EGL_CONTEXT_LOST, which means the context
901             * and all associated data were lost (For instance because
902             * the device went to sleep). We need to sleep until we
903             * get a new surface.
904             */
905            return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST;
906        }
907
908        public void destroySurface() {
909            if (mEglSurface != null) {
910                mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
911                        EGL10.EGL_NO_SURFACE,
912                        EGL10.EGL_NO_CONTEXT);
913                mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface);
914                mEglSurface = null;
915            }
916        }
917
918        public void finish() {
919            if (mEglContext != null) {
920                mEGLContextFactory.destroyContext(mEgl, mEglDisplay, mEglContext);
921                mEglContext = null;
922            }
923            if (mEglDisplay != null) {
924                mEgl.eglTerminate(mEglDisplay);
925                mEglDisplay = null;
926            }
927        }
928
929        EGL10 mEgl;
930        EGLDisplay mEglDisplay;
931        EGLSurface mEglSurface;
932        EGLConfig mEglConfig;
933        EGLContext mEglContext;
934    }
935
936    /**
937     * A generic GL Thread. Takes care of initializing EGL and GL. Delegates
938     * to a Renderer instance to do the actual drawing. Can be configured to
939     * render continuously or on request.
940     *
941     */
942    class GLThread extends Thread {
943        GLThread(Renderer renderer) {
944            super();
945            mDone = false;
946            mWidth = 0;
947            mHeight = 0;
948            mRequestRender = true;
949            mRenderMode = RENDERMODE_CONTINUOUSLY;
950            mRenderer = renderer;
951            setName("GLThread");
952        }
953
954        @Override
955        public void run() {
956            /*
957             * When the android framework launches a second instance of
958             * an activity, the new instance's onCreate() method may be
959             * called before the first instance returns from onDestroy().
960             *
961             * This semaphore ensures that only one instance at a time
962             * accesses EGL.
963             */
964            try {
965                try {
966                sEglSemaphore.acquire();
967                } catch (InterruptedException e) {
968                    return;
969                }
970                guardedRun();
971            } catch (InterruptedException e) {
972                // fall thru and exit normally
973            } finally {
974                sEglSemaphore.release();
975            }
976        }
977
978        private void guardedRun() throws InterruptedException {
979            mEglHelper = new EglHelper();
980            try {
981                mEglHelper.start();
982
983                GL10 gl = null;
984                boolean tellRendererSurfaceCreated = true;
985                boolean tellRendererSurfaceChanged = true;
986
987                /*
988                 * This is our main activity thread's loop, we go until
989                 * asked to quit.
990                 */
991                while (!mDone) {
992
993                    /*
994                     *  Update the asynchronous state (window size)
995                     */
996                    int w, h;
997                    boolean changed;
998                    boolean needStart = false;
999                    synchronized (this) {
1000                        Runnable r;
1001                        while ((r = getEvent()) != null) {
1002                            r.run();
1003                        }
1004                        if (mPaused) {
1005                            mEglHelper.destroySurface();
1006                            mEglHelper.finish();
1007                            needStart = true;
1008                        }
1009                        while (needToWait()) {
1010                            if (!mHasSurface) {
1011                                if (!mWaitingForSurface) {
1012                                    mEglHelper.destroySurface();
1013                                    mWaitingForSurface = true;
1014                                    notify();
1015                                }
1016                            }
1017                            wait();
1018                        }
1019                        if (mDone) {
1020                            break;
1021                        }
1022                        changed = mSizeChanged;
1023                        w = mWidth;
1024                        h = mHeight;
1025                        mSizeChanged = false;
1026                        mRequestRender = false;
1027                        if (mHasSurface && mWaitingForSurface) {
1028                            changed = true;
1029                            mWaitingForSurface = false;
1030                        }
1031                    }
1032                    if (needStart) {
1033                        mEglHelper.start();
1034                        tellRendererSurfaceCreated = true;
1035                        changed = true;
1036                    }
1037                    if (changed) {
1038                        gl = (GL10) mEglHelper.createSurface(getHolder());
1039                        tellRendererSurfaceChanged = true;
1040                    }
1041                    if (tellRendererSurfaceCreated) {
1042                        mRenderer.onSurfaceCreated(gl, mEglHelper.mEglConfig);
1043                        tellRendererSurfaceCreated = false;
1044                    }
1045                    if (tellRendererSurfaceChanged) {
1046                        mRenderer.onSurfaceChanged(gl, w, h);
1047                        tellRendererSurfaceChanged = false;
1048                    }
1049                    if ((w > 0) && (h > 0)) {
1050                        /* draw a frame here */
1051                        mRenderer.onDrawFrame(gl);
1052
1053                        /*
1054                         * Once we're done with GL, we need to call swapBuffers()
1055                         * to instruct the system to display the rendered frame
1056                         */
1057                        mEglHelper.swap();
1058                    }
1059                 }
1060            } finally {
1061                /*
1062                 * clean-up everything...
1063                 */
1064                mEglHelper.destroySurface();
1065                mEglHelper.finish();
1066            }
1067        }
1068
1069        private boolean needToWait() {
1070            if (mDone) {
1071                return false;
1072            }
1073
1074            if (mPaused || (! mHasSurface)) {
1075                return true;
1076            }
1077
1078            if ((mWidth > 0) && (mHeight > 0) && (mRequestRender || (mRenderMode == RENDERMODE_CONTINUOUSLY))) {
1079                return false;
1080            }
1081
1082            return true;
1083        }
1084
1085        public void setRenderMode(int renderMode) {
1086            if ( !((RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= RENDERMODE_CONTINUOUSLY)) ) {
1087                throw new IllegalArgumentException("renderMode");
1088            }
1089            synchronized(this) {
1090                mRenderMode = renderMode;
1091                if (renderMode == RENDERMODE_CONTINUOUSLY) {
1092                    notify();
1093                }
1094            }
1095        }
1096
1097        public int getRenderMode() {
1098            synchronized(this) {
1099                return mRenderMode;
1100            }
1101        }
1102
1103        public void requestRender() {
1104            synchronized(this) {
1105                mRequestRender = true;
1106                notify();
1107            }
1108        }
1109
1110        public void surfaceCreated() {
1111            synchronized(this) {
1112                mHasSurface = true;
1113                notify();
1114            }
1115        }
1116
1117        public void surfaceDestroyed() {
1118            synchronized(this) {
1119                mHasSurface = false;
1120                notify();
1121                while(!mWaitingForSurface && isAlive()) {
1122                    try {
1123                        wait();
1124                    } catch (InterruptedException e) {
1125                        Thread.currentThread().interrupt();
1126                    }
1127                }
1128            }
1129        }
1130
1131        public void onPause() {
1132            synchronized (this) {
1133                mPaused = true;
1134            }
1135        }
1136
1137        public void onResume() {
1138            synchronized (this) {
1139                mPaused = false;
1140                notify();
1141            }
1142        }
1143
1144        public void onWindowResize(int w, int h) {
1145            synchronized (this) {
1146                mWidth = w;
1147                mHeight = h;
1148                mSizeChanged = true;
1149                notify();
1150            }
1151        }
1152
1153        public void requestExitAndWait() {
1154            // don't call this from GLThread thread or it is a guaranteed
1155            // deadlock!
1156            synchronized(this) {
1157                mDone = true;
1158                notify();
1159            }
1160            try {
1161                join();
1162            } catch (InterruptedException ex) {
1163                Thread.currentThread().interrupt();
1164            }
1165        }
1166
1167        /**
1168         * Queue an "event" to be run on the GL rendering thread.
1169         * @param r the runnable to be run on the GL rendering thread.
1170         */
1171        public void queueEvent(Runnable r) {
1172            synchronized(this) {
1173                mEventQueue.add(r);
1174            }
1175        }
1176
1177        private Runnable getEvent() {
1178            synchronized(this) {
1179                if (mEventQueue.size() > 0) {
1180                    return mEventQueue.remove(0);
1181                }
1182
1183            }
1184            return null;
1185        }
1186
1187        private boolean mDone;
1188        private boolean mPaused;
1189        private boolean mHasSurface;
1190        private boolean mWaitingForSurface;
1191        private int mWidth;
1192        private int mHeight;
1193        private int mRenderMode;
1194        private boolean mRequestRender;
1195        private Renderer mRenderer;
1196        private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>();
1197        private EglHelper mEglHelper;
1198    }
1199
1200    static class LogWriter extends Writer {
1201
1202        @Override public void close() {
1203            flushBuilder();
1204        }
1205
1206        @Override public void flush() {
1207            flushBuilder();
1208        }
1209
1210        @Override public void write(char[] buf, int offset, int count) {
1211            for(int i = 0; i < count; i++) {
1212                char c = buf[offset + i];
1213                if ( c == '\n') {
1214                    flushBuilder();
1215                }
1216                else {
1217                    mBuilder.append(c);
1218                }
1219            }
1220        }
1221
1222        private void flushBuilder() {
1223            if (mBuilder.length() > 0) {
1224                Log.v("GLSurfaceView", mBuilder.toString());
1225                mBuilder.delete(0, mBuilder.length());
1226            }
1227        }
1228
1229        private StringBuilder mBuilder = new StringBuilder();
1230    }
1231
1232
1233    private void checkRenderThreadState() {
1234        if (mGLThread != null) {
1235            throw new IllegalStateException(
1236                    "setRenderer has already been called for this instance.");
1237        }
1238    }
1239
1240    private static final Semaphore sEglSemaphore = new Semaphore(1);
1241    private boolean mSizeChanged = true;
1242
1243    private GLThread mGLThread;
1244    private EGLConfigChooser mEGLConfigChooser;
1245    private EGLContextFactory mEGLContextFactory;
1246    private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory;
1247    private GLWrapper mGLWrapper;
1248    private int mDebugFlags;
1249}
1250