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