GLSurfaceView.java revision a3a351e5d164d0c8b461ae7af86edc0227654a76
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.opengl;
18
19import java.io.Writer;
20import java.util.ArrayList;
21
22import javax.microedition.khronos.egl.EGL10;
23import javax.microedition.khronos.egl.EGL11;
24import javax.microedition.khronos.egl.EGLConfig;
25import javax.microedition.khronos.egl.EGLContext;
26import javax.microedition.khronos.egl.EGLDisplay;
27import javax.microedition.khronos.egl.EGLSurface;
28import javax.microedition.khronos.opengles.GL;
29import javax.microedition.khronos.opengles.GL10;
30
31import android.content.Context;
32import android.content.pm.ConfigurationInfo;
33import android.os.SystemProperties;
34import android.util.AttributeSet;
35import android.util.Log;
36import android.view.SurfaceHolder;
37import android.view.SurfaceView;
38
39/**
40 * An implementation of SurfaceView that uses the dedicated surface for
41 * displaying OpenGL rendering.
42 * <p>
43 * A GLSurfaceView provides the following features:
44 * <p>
45 * <ul>
46 * <li>Manages a surface, which is a special piece of memory that can be
47 * composited into the Android view system.
48 * <li>Manages an EGL display, which enables OpenGL to render into a surface.
49 * <li>Accepts a user-provided Renderer object that does the actual rendering.
50 * <li>Renders on a dedicated thread to decouple rendering performance from the
51 * UI thread.
52 * <li>Supports both on-demand and continuous rendering.
53 * <li>Optionally wraps, traces, and/or error-checks the renderer's OpenGL calls.
54 * </ul>
55 *
56 * <h3>Using GLSurfaceView</h3>
57 * <p>
58 * Typically you use GLSurfaceView by subclassing it and overriding one or more of the
59 * View system input event methods. If your application does not need to override event
60 * methods then GLSurfaceView can be used as-is. For the most part
61 * GLSurfaceView behavior is customized by calling "set" methods rather than by subclassing.
62 * For example, unlike a regular View, drawing is delegated to a separate Renderer object which
63 * is registered with the GLSurfaceView
64 * using the {@link #setRenderer(Renderer)} call.
65 * <p>
66 * <h3>Initializing GLSurfaceView</h3>
67 * All you have to do to initialize a GLSurfaceView is call {@link #setRenderer(Renderer)}.
68 * However, if desired, you can modify the default behavior of GLSurfaceView by calling one or
69 * more of these methods before calling setRenderer:
70 * <ul>
71 * <li>{@link #setDebugFlags(int)}
72 * <li>{@link #setEGLConfigChooser(boolean)}
73 * <li>{@link #setEGLConfigChooser(EGLConfigChooser)}
74 * <li>{@link #setEGLConfigChooser(int, int, int, int, int, int)}
75 * <li>{@link #setGLWrapper(GLWrapper)}
76 * </ul>
77 * <p>
78 * <h4>Choosing an EGL Configuration</h4>
79 * A given Android device may support multiple possible types of drawing surfaces.
80 * The available surfaces may differ in how may channels of data are present, as
81 * well as how many bits are allocated to each channel. Therefore, the first thing
82 * GLSurfaceView has to do when starting to render is choose what type of surface to use.
83 * <p>
84 * By default GLSurfaceView chooses an available surface that's closest to a 16-bit R5G6B5 surface
85 * with a 16-bit depth buffer and no stencil. If you would prefer a different surface (for example,
86 * if you do not need a depth buffer) you can override the default behavior by calling one of the
87 * setEGLConfigChooser methods.
88 * <p>
89 * <h4>Debug Behavior</h4>
90 * You can optionally modify the behavior of GLSurfaceView by calling
91 * one or more of the debugging methods {@link #setDebugFlags(int)},
92 * and {@link #setGLWrapper}. These methods may be called before and/or after setRenderer, but
93 * typically they are called before setRenderer so that they take effect immediately.
94 * <p>
95 * <h4>Setting a Renderer</h4>
96 * Finally, you must call {@link #setRenderer} to register a {@link Renderer}.
97 * The renderer is
98 * responsible for doing the actual OpenGL rendering.
99 * <p>
100 * <h3>Rendering Mode</h3>
101 * Once the renderer is set, you can control whether the renderer draws
102 * continuously or on-demand by calling
103 * {@link #setRenderMode}. The default is continuous rendering.
104 * <p>
105 * <h3>Activity Life-cycle</h3>
106 * A GLSurfaceView must be notified when the activity is paused and resumed. GLSurfaceView clients
107 * are required to call {@link #onPause()} when the activity pauses and
108 * {@link #onResume()} when the activity resumes. These calls allow GLSurfaceView to
109 * pause and resume the rendering thread, and also allow GLSurfaceView to release and recreate
110 * the OpenGL display.
111 * <p>
112 * <h3>Handling events</h3>
113 * <p>
114 * To handle an event you will typically subclass GLSurfaceView and override the
115 * appropriate method, just as you would with any other View. However, when handling
116 * the event, you may need to communicate with the Renderer object
117 * that's running in the rendering thread. You can do this using any
118 * standard Java cross-thread communication mechanism. In addition,
119 * one relatively easy way to communicate with your renderer is
120 * to call
121 * {@link #queueEvent(Runnable)}. For example:
122 * <pre class="prettyprint">
123 * class MyGLSurfaceView extends GLSurfaceView {
124 *
125 *     private MyRenderer mMyRenderer;
126 *
127 *     public void start() {
128 *         mMyRenderer = ...;
129 *         setRenderer(mMyRenderer);
130 *     }
131 *
132 *     public boolean onKeyDown(int keyCode, KeyEvent event) {
133 *         if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
134 *             queueEvent(new Runnable() {
135 *                 // This method will be called on the rendering
136 *                 // thread:
137 *                 public void run() {
138 *                     mMyRenderer.handleDpadCenter();
139 *                 }});
140 *             return true;
141 *         }
142 *         return super.onKeyDown(keyCode, event);
143 *     }
144 * }
145 * </pre>
146 *
147 */
148public class GLSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
149    private final static boolean LOG_THREADS = false;
150    /**
151     * The renderer only renders
152     * when the surface is created, or when {@link #requestRender} is called.
153     *
154     * @see #getRenderMode()
155     * @see #setRenderMode(int)
156     */
157    public final static int RENDERMODE_WHEN_DIRTY = 0;
158    /**
159     * The renderer is called
160     * continuously to re-render the scene.
161     *
162     * @see #getRenderMode()
163     * @see #setRenderMode(int)
164     * @see #requestRender()
165     */
166    public final static int RENDERMODE_CONTINUOUSLY = 1;
167
168    /**
169     * Check glError() after every GL call and throw an exception if glError indicates
170     * that an error has occurred. This can be used to help track down which OpenGL ES call
171     * is causing an error.
172     *
173     * @see #getDebugFlags
174     * @see #setDebugFlags
175     */
176    public final static int DEBUG_CHECK_GL_ERROR = 1;
177
178    /**
179     * Log GL calls to the system log at "verbose" level with tag "GLSurfaceView".
180     *
181     * @see #getDebugFlags
182     * @see #setDebugFlags
183     */
184    public final static int DEBUG_LOG_GL_CALLS = 2;
185
186    /**
187     * Standard View constructor. In order to render something, you
188     * must call {@link #setRenderer} to register a renderer.
189     */
190    public GLSurfaceView(Context context) {
191        super(context);
192        init();
193    }
194
195    /**
196     * Standard View constructor. In order to render something, you
197     * must call {@link #setRenderer} to register a renderer.
198     */
199    public GLSurfaceView(Context context, AttributeSet attrs) {
200        super(context, attrs);
201        init();
202    }
203
204    private void init() {
205        // Install a SurfaceHolder.Callback so we get notified when the
206        // underlying surface is created and destroyed
207        SurfaceHolder holder = getHolder();
208        holder.addCallback(this);
209    }
210
211    /**
212     * Set the glWrapper. If the glWrapper is not null, its
213     * {@link GLWrapper#wrap(GL)} method is called
214     * whenever a surface is created. A GLWrapper can be used to wrap
215     * the GL object that's passed to the renderer. Wrapping a GL
216     * object enables examining and modifying the behavior of the
217     * GL calls made by the renderer.
218     * <p>
219     * Wrapping is typically used for debugging purposes.
220     * <p>
221     * The default value is null.
222     * @param glWrapper the new GLWrapper
223     */
224    public void setGLWrapper(GLWrapper glWrapper) {
225        mGLWrapper = glWrapper;
226    }
227
228    /**
229     * Set the debug flags to a new value. The value is
230     * constructed by OR-together zero or more
231     * of the DEBUG_CHECK_* constants. The debug flags take effect
232     * whenever a surface is created. The default value is zero.
233     * @param debugFlags the new debug flags
234     * @see #DEBUG_CHECK_GL_ERROR
235     * @see #DEBUG_LOG_GL_CALLS
236     */
237    public void setDebugFlags(int debugFlags) {
238        mDebugFlags = debugFlags;
239    }
240
241    /**
242     * Get the current value of the debug flags.
243     * @return the current value of the debug flags.
244     */
245    public int getDebugFlags() {
246        return mDebugFlags;
247    }
248
249    /**
250     * Set the renderer associated with this view. Also starts the thread that
251     * will call the renderer, which in turn causes the rendering to start.
252     * <p>This method should be called once and only once in the life-cycle of
253     * a GLSurfaceView.
254     * <p>The following GLSurfaceView methods can only be called <em>before</em>
255     * setRenderer is called:
256     * <ul>
257     * <li>{@link #setEGLConfigChooser(boolean)}
258     * <li>{@link #setEGLConfigChooser(EGLConfigChooser)}
259     * <li>{@link #setEGLConfigChooser(int, int, int, int, int, int)}
260     * </ul>
261     * <p>
262     * The following GLSurfaceView methods can only be called <em>after</em>
263     * setRenderer is called:
264     * <ul>
265     * <li>{@link #getRenderMode()}
266     * <li>{@link #onPause()}
267     * <li>{@link #onResume()}
268     * <li>{@link #queueEvent(Runnable)}
269     * <li>{@link #requestRender()}
270     * <li>{@link #setRenderMode(int)}
271     * </ul>
272     *
273     * @param renderer the renderer to use to perform OpenGL drawing.
274     */
275    public void setRenderer(Renderer renderer) {
276        checkRenderThreadState();
277        if (mEGLConfigChooser == null) {
278            mEGLConfigChooser = new SimpleEGLConfigChooser(true);
279        }
280        if (mEGLContextFactory == null) {
281            mEGLContextFactory = new DefaultContextFactory();
282        }
283        if (mEGLWindowSurfaceFactory == null) {
284            mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory();
285        }
286        mGLThread = new GLThread(renderer);
287        mGLThread.start();
288    }
289
290    /**
291     * Install a custom EGLContextFactory.
292     * <p>If this method is
293     * called, it must be called before {@link #setRenderer(Renderer)}
294     * is called.
295     * <p>
296     * If this method is not called, then by default
297     * a context will be created with no shared context and
298     * with a null attribute list.
299     */
300    public void setEGLContextFactory(EGLContextFactory factory) {
301        checkRenderThreadState();
302        mEGLContextFactory = factory;
303    }
304
305    /**
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 setEGLWindowSurfaceFactory(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     * An interface for customizing the eglCreateContext and eglDestroyContext calls.
613     * <p>
614     * This interface must be implemented by clients wishing to call
615     * {@link GLSurfaceView#setEGLContextFactory(EGLContextFactory)}
616     */
617    public interface EGLContextFactory {
618        EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig);
619        void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context);
620    }
621
622    private static class DefaultContextFactory implements EGLContextFactory {
623
624        public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig config) {
625            return egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT, null);
626        }
627
628        public void destroyContext(EGL10 egl, EGLDisplay display,
629                EGLContext context) {
630            egl.eglDestroyContext(display, context);
631        }
632    }
633
634    /**
635     * An interface for customizing the eglCreateWindowSurface and eglDestroySurface calls.
636     * <p>
637     * This interface must be implemented by clients wishing to call
638     * {@link GLSurfaceView#setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory)}
639     */
640    public interface EGLWindowSurfaceFactory {
641        EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, EGLConfig config,
642                Object nativeWindow);
643        void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface);
644    }
645
646    private static class DefaultWindowSurfaceFactory implements EGLWindowSurfaceFactory {
647
648        public EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display,
649                EGLConfig config, Object nativeWindow) {
650            return egl.eglCreateWindowSurface(display, config, nativeWindow, null);
651        }
652
653        public void destroySurface(EGL10 egl, EGLDisplay display,
654                EGLSurface surface) {
655            egl.eglDestroySurface(display, surface);
656        }
657    }
658
659    /**
660     * An interface for choosing an EGLConfig configuration from a list of
661     * potential configurations.
662     * <p>
663     * This interface must be implemented by clients wishing to call
664     * {@link GLSurfaceView#setEGLConfigChooser(EGLConfigChooser)}
665     */
666    public interface EGLConfigChooser {
667        /**
668         * Choose a configuration from the list. Implementors typically
669         * implement this method by calling
670         * {@link EGL10#eglChooseConfig} and iterating through the results. Please consult the
671         * EGL specification available from The Khronos Group to learn how to call eglChooseConfig.
672         * @param egl the EGL10 for the current display.
673         * @param display the current display.
674         * @return the chosen configuration.
675         */
676        EGLConfig chooseConfig(EGL10 egl, EGLDisplay display);
677    }
678
679    private static abstract class BaseConfigChooser
680            implements EGLConfigChooser {
681        public BaseConfigChooser(int[] configSpec) {
682            mConfigSpec = configSpec;
683        }
684        public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
685            int[] num_config = new int[1];
686            if (!egl.eglChooseConfig(display, mConfigSpec, null, 0,
687                    num_config)) {
688                throw new IllegalArgumentException("eglChooseConfig failed");
689            }
690
691            int numConfigs = num_config[0];
692
693            if (numConfigs <= 0) {
694                throw new IllegalArgumentException(
695                        "No configs match configSpec");
696            }
697
698            EGLConfig[] configs = new EGLConfig[numConfigs];
699            if (!egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs,
700                    num_config)) {
701                throw new IllegalArgumentException("eglChooseConfig#2 failed");
702            }
703            EGLConfig config = chooseConfig(egl, display, configs);
704            if (config == null) {
705                throw new IllegalArgumentException("No config chosen");
706            }
707            return config;
708        }
709
710        abstract EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
711                EGLConfig[] configs);
712
713        protected int[] mConfigSpec;
714    }
715
716    private static class ComponentSizeChooser extends BaseConfigChooser {
717        public ComponentSizeChooser(int redSize, int greenSize, int blueSize,
718                int alphaSize, int depthSize, int stencilSize) {
719            super(new int[] {
720                    EGL10.EGL_RED_SIZE, redSize,
721                    EGL10.EGL_GREEN_SIZE, greenSize,
722                    EGL10.EGL_BLUE_SIZE, blueSize,
723                    EGL10.EGL_ALPHA_SIZE, alphaSize,
724                    EGL10.EGL_DEPTH_SIZE, depthSize,
725                    EGL10.EGL_STENCIL_SIZE, stencilSize,
726                    EGL10.EGL_NONE});
727            mValue = new int[1];
728            mRedSize = redSize;
729            mGreenSize = greenSize;
730            mBlueSize = blueSize;
731            mAlphaSize = alphaSize;
732            mDepthSize = depthSize;
733            mStencilSize = stencilSize;
734       }
735
736        @Override
737        public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
738                EGLConfig[] configs) {
739            EGLConfig closestConfig = null;
740            int closestDistance = 1000;
741            for(EGLConfig config : configs) {
742                int d = findConfigAttrib(egl, display, config,
743                        EGL10.EGL_DEPTH_SIZE, 0);
744                int s = findConfigAttrib(egl, display, config,
745                        EGL10.EGL_STENCIL_SIZE, 0);
746                if (d >= mDepthSize && s>= mStencilSize) {
747                    int r = findConfigAttrib(egl, display, config,
748                            EGL10.EGL_RED_SIZE, 0);
749                    int g = findConfigAttrib(egl, display, config,
750                             EGL10.EGL_GREEN_SIZE, 0);
751                    int b = findConfigAttrib(egl, display, config,
752                              EGL10.EGL_BLUE_SIZE, 0);
753                    int a = findConfigAttrib(egl, display, config,
754                            EGL10.EGL_ALPHA_SIZE, 0);
755                    int distance = Math.abs(r - mRedSize)
756                                + Math.abs(g - mGreenSize)
757                                + Math.abs(b - mBlueSize)
758                                + Math.abs(a - mAlphaSize);
759                    if (distance < closestDistance) {
760                        closestDistance = distance;
761                        closestConfig = config;
762                    }
763                }
764            }
765            return closestConfig;
766        }
767
768        private int findConfigAttrib(EGL10 egl, EGLDisplay display,
769                EGLConfig config, int attribute, int defaultValue) {
770
771            if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) {
772                return mValue[0];
773            }
774            return defaultValue;
775        }
776
777        private int[] mValue;
778        // Subclasses can adjust these values:
779        protected int mRedSize;
780        protected int mGreenSize;
781        protected int mBlueSize;
782        protected int mAlphaSize;
783        protected int mDepthSize;
784        protected int mStencilSize;
785        }
786
787    /**
788     * This class will choose a supported surface as close to
789     * RGB565 as possible, with or without a depth buffer.
790     *
791     */
792    private static class SimpleEGLConfigChooser extends ComponentSizeChooser {
793        public SimpleEGLConfigChooser(boolean withDepthBuffer) {
794            super(4, 4, 4, 0, withDepthBuffer ? 16 : 0, 0);
795            // Adjust target values. This way we'll accept a 4444 or
796            // 555 buffer if there's no 565 buffer available.
797            mRedSize = 5;
798            mGreenSize = 6;
799            mBlueSize = 5;
800        }
801    }
802
803    /**
804     * An EGL helper class.
805     */
806
807    private class EglHelper {
808        public EglHelper() {
809
810        }
811
812        /**
813         * Initialize EGL for a given configuration spec.
814         * @param configSpec
815         */
816        public void start(){
817            /*
818             * Get an EGL instance
819             */
820            mEgl = (EGL10) EGLContext.getEGL();
821
822            /*
823             * Get to the default display.
824             */
825            mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
826
827            if (mEglDisplay == EGL10.EGL_NO_DISPLAY) {
828                throw new RuntimeException("eglGetDisplay failed");
829            }
830
831            /*
832             * We can now initialize EGL for that display
833             */
834            int[] version = new int[2];
835            if(!mEgl.eglInitialize(mEglDisplay, version)) {
836                throw new RuntimeException("eglInitialize failed");
837            }
838            mEglConfig = mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay);
839
840            /*
841            * Create an OpenGL ES context. This must be done only once, an
842            * OpenGL context is a somewhat heavy object.
843            */
844            mEglContext = mEGLContextFactory.createContext(mEgl, mEglDisplay, mEglConfig);
845            if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) {
846                throw new RuntimeException("createContext failed");
847            }
848
849            mEglSurface = null;
850        }
851
852        /*
853         * React to the creation of a new surface by creating and returning an
854         * OpenGL interface that renders to that surface.
855         */
856        public GL createSurface(SurfaceHolder holder) {
857            /*
858             *  The window size has changed, so we need to create a new
859             *  surface.
860             */
861            if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
862
863                /*
864                 * Unbind and destroy the old EGL surface, if
865                 * there is one.
866                 */
867                mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
868                        EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
869                mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface);
870            }
871
872            /*
873             * Create an EGL surface we can render into.
874             */
875            mEglSurface = mEGLWindowSurfaceFactory.createWindowSurface(mEgl,
876                    mEglDisplay, mEglConfig, holder);
877
878            if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) {
879                throw new RuntimeException("createWindowSurface failed");
880            }
881
882            /*
883             * Before we can issue GL commands, we need to make sure
884             * the context is current and bound to a surface.
885             */
886            if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
887                throw new RuntimeException("eglMakeCurrent failed.");
888            }
889
890            GL gl = mEglContext.getGL();
891            if (mGLWrapper != null) {
892                gl = mGLWrapper.wrap(gl);
893            }
894
895            if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS))!= 0) {
896                int configFlags = 0;
897                Writer log = null;
898                if ((mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) {
899                    configFlags |= GLDebugHelper.CONFIG_CHECK_GL_ERROR;
900                }
901                if ((mDebugFlags & DEBUG_LOG_GL_CALLS) != 0) {
902                    log = new LogWriter();
903                }
904                gl = GLDebugHelper.wrap(gl, configFlags, log);
905            }
906            return gl;
907        }
908
909        /**
910         * Display the current render surface.
911         * @return false if the context has been lost.
912         */
913        public boolean swap() {
914            mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
915
916            /*
917             * Always check for EGL_CONTEXT_LOST, which means the context
918             * and all associated data were lost (For instance because
919             * the device went to sleep). We need to sleep until we
920             * get a new surface.
921             */
922            return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST;
923        }
924
925        public void destroySurface() {
926            if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
927                mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
928                        EGL10.EGL_NO_SURFACE,
929                        EGL10.EGL_NO_CONTEXT);
930                mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface);
931                mEglSurface = null;
932            }
933        }
934
935        public void finish() {
936            if (mEglContext != null) {
937                mEGLContextFactory.destroyContext(mEgl, mEglDisplay, mEglContext);
938                mEglContext = null;
939            }
940            if (mEglDisplay != null) {
941                mEgl.eglTerminate(mEglDisplay);
942                mEglDisplay = null;
943            }
944        }
945
946        EGL10 mEgl;
947        EGLDisplay mEglDisplay;
948        EGLSurface mEglSurface;
949        EGLConfig mEglConfig;
950        EGLContext mEglContext;
951    }
952
953    /**
954     * A generic GL Thread. Takes care of initializing EGL and GL. Delegates
955     * to a Renderer instance to do the actual drawing. Can be configured to
956     * render continuously or on request.
957     *
958     */
959    class GLThread extends Thread {
960        GLThread(Renderer renderer) {
961            super();
962            mDone = false;
963            mWidth = 0;
964            mHeight = 0;
965            mRequestRender = true;
966            mRenderMode = RENDERMODE_CONTINUOUSLY;
967            mRenderer = renderer;
968        }
969
970        @Override
971        public void run() {
972            setName("GLThread " + getId());
973            if (LOG_THREADS) {
974                Log.i("GLThread", "starting tid=" + getId());
975            }
976
977            /*
978             * When the android framework launches a second instance of
979             * an activity, the new instance's onCreate() method may be
980             * called before the first instance returns from onDestroy().
981             *
982             * This semaphore ensures that only one instance at a time
983             * accesses EGL.
984             */
985            try {
986                try {
987                    sGLThreadManager.start(this);
988                } catch (InterruptedException e) {
989                    return;
990                }
991                guardedRun();
992            } catch (InterruptedException e) {
993                // fall thru and exit normally
994            } finally {
995                try {
996                    sGLThreadManager.end(this);
997                } finally {
998                    synchronized(this) {
999                        if (LOG_THREADS) {
1000                            Log.i("GLThread", "exiting tid=" +  getId());
1001                        }
1002                        mDone = true;
1003                        notifyAll();
1004                    }
1005                }
1006            }
1007        }
1008
1009        private void guardedRun() throws InterruptedException {
1010            mEglHelper = new EglHelper();
1011            try {
1012                mEglHelper.start();
1013
1014                GL10 gl = null;
1015                boolean tellRendererSurfaceCreated = true;
1016                boolean tellRendererSurfaceChanged = true;
1017
1018                /*
1019                 * This is our main activity thread's loop, we go until
1020                 * asked to quit.
1021                 */
1022                while (!mDone) {
1023
1024                    /*
1025                     *  Update the asynchronous state (window size)
1026                     */
1027                    int w, h;
1028                    boolean changed;
1029                    boolean needStart = false;
1030                    synchronized (this) {
1031                        Runnable r;
1032                        while ((r = getEvent()) != null) {
1033                            r.run();
1034                        }
1035                        if (mPaused) {
1036                            mEglHelper.destroySurface();
1037                            mEglHelper.finish();
1038                            needStart = true;
1039                        }
1040                        while (needToWait()) {
1041                            if (LOG_THREADS) {
1042                                Log.i("GLThread", "needToWait tid=" + getId());
1043                            }
1044                            if (!mHasSurface) {
1045                                if (!mWaitingForSurface) {
1046                                    mEglHelper.destroySurface();
1047                                    mWaitingForSurface = true;
1048                                    notifyAll();
1049                                }
1050                            }
1051                            wait();
1052                        }
1053                        if (mDone) {
1054                            break;
1055                        }
1056                        changed = mSizeChanged;
1057                        w = mWidth;
1058                        h = mHeight;
1059                        mSizeChanged = false;
1060                        mRequestRender = false;
1061                        if (mHasSurface && mWaitingForSurface) {
1062                            changed = true;
1063                            mWaitingForSurface = false;
1064                            notifyAll();
1065                        }
1066                    }
1067                    if (needStart) {
1068                        mEglHelper.start();
1069                        tellRendererSurfaceCreated = true;
1070                        changed = true;
1071                    }
1072                    if (changed) {
1073                        gl = (GL10) mEglHelper.createSurface(getHolder());
1074                        sGLThreadManager.checkGLDriver(gl);
1075                        tellRendererSurfaceChanged = true;
1076                    }
1077                    if (tellRendererSurfaceCreated) {
1078                        mRenderer.onSurfaceCreated(gl, mEglHelper.mEglConfig);
1079                        tellRendererSurfaceCreated = false;
1080                    }
1081                    if (tellRendererSurfaceChanged) {
1082                        mRenderer.onSurfaceChanged(gl, w, h);
1083                        tellRendererSurfaceChanged = false;
1084                    }
1085                    if ((w > 0) && (h > 0)) {
1086                        /* draw a frame here */
1087                        mRenderer.onDrawFrame(gl);
1088
1089                        /*
1090                         * Once we're done with GL, we need to call swapBuffers()
1091                         * to instruct the system to display the rendered frame
1092                         */
1093                        mEglHelper.swap();
1094                    }
1095                 }
1096            } finally {
1097                /*
1098                 * clean-up everything...
1099                 */
1100                mEglHelper.destroySurface();
1101                mEglHelper.finish();
1102            }
1103        }
1104
1105        private boolean needToWait() {
1106            if (sGLThreadManager.shouldQuit(this)) {
1107                mDone = true;
1108                notifyAll();
1109            }
1110            if (mDone) {
1111                return false;
1112            }
1113
1114            if (mPaused || (! mHasSurface)) {
1115                return true;
1116            }
1117
1118            if ((mWidth > 0) && (mHeight > 0) && (mRequestRender || (mRenderMode == RENDERMODE_CONTINUOUSLY))) {
1119                return false;
1120            }
1121
1122            return true;
1123        }
1124
1125        public void setRenderMode(int renderMode) {
1126            if ( !((RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= RENDERMODE_CONTINUOUSLY)) ) {
1127                throw new IllegalArgumentException("renderMode");
1128            }
1129            synchronized(this) {
1130                mRenderMode = renderMode;
1131                if (renderMode == RENDERMODE_CONTINUOUSLY) {
1132                    notifyAll();
1133                }
1134            }
1135        }
1136
1137        public int getRenderMode() {
1138            synchronized(this) {
1139                return mRenderMode;
1140            }
1141        }
1142
1143        public void requestRender() {
1144            synchronized(this) {
1145                mRequestRender = true;
1146                notifyAll();
1147            }
1148        }
1149
1150        public void surfaceCreated() {
1151            synchronized(this) {
1152                if (LOG_THREADS) {
1153                    Log.i("GLThread", "surfaceCreated tid=" + getId());
1154                }
1155                mHasSurface = true;
1156                notifyAll();
1157            }
1158        }
1159
1160        public void surfaceDestroyed() {
1161            synchronized(this) {
1162                if (LOG_THREADS) {
1163                    Log.i("GLThread", "surfaceDestroyed tid=" + getId());
1164                }
1165                mHasSurface = false;
1166                notifyAll();
1167                while(!mWaitingForSurface && isAlive() && ! mDone) {
1168                    try {
1169                        wait();
1170                    } catch (InterruptedException e) {
1171                        Thread.currentThread().interrupt();
1172                    }
1173                }
1174            }
1175        }
1176
1177        public void onPause() {
1178            synchronized (this) {
1179                mPaused = true;
1180                notifyAll();
1181            }
1182        }
1183
1184        public void onResume() {
1185            synchronized (this) {
1186                mPaused = false;
1187                mRequestRender = true;
1188                notifyAll();
1189            }
1190        }
1191
1192        public void onWindowResize(int w, int h) {
1193            synchronized (this) {
1194                mWidth = w;
1195                mHeight = h;
1196                mSizeChanged = true;
1197                notifyAll();
1198            }
1199        }
1200
1201        public void requestExitAndWait() {
1202            // don't call this from GLThread thread or it is a guaranteed
1203            // deadlock!
1204            synchronized(this) {
1205                mDone = true;
1206                notifyAll();
1207            }
1208            try {
1209                join();
1210            } catch (InterruptedException ex) {
1211                Thread.currentThread().interrupt();
1212            }
1213        }
1214
1215        /**
1216         * Queue an "event" to be run on the GL rendering thread.
1217         * @param r the runnable to be run on the GL rendering thread.
1218         */
1219        public void queueEvent(Runnable r) {
1220            synchronized(this) {
1221                mEventQueue.add(r);
1222            }
1223        }
1224
1225        private Runnable getEvent() {
1226            synchronized(this) {
1227                if (mEventQueue.size() > 0) {
1228                    return mEventQueue.remove(0);
1229                }
1230
1231            }
1232            return null;
1233        }
1234
1235        private boolean mDone;
1236        private boolean mPaused;
1237        private boolean mHasSurface;
1238        private boolean mWaitingForSurface;
1239        private int mWidth;
1240        private int mHeight;
1241        private int mRenderMode;
1242        private boolean mRequestRender;
1243        private Renderer mRenderer;
1244        private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>();
1245        private EglHelper mEglHelper;
1246    }
1247
1248    static class LogWriter extends Writer {
1249
1250        @Override public void close() {
1251            flushBuilder();
1252        }
1253
1254        @Override public void flush() {
1255            flushBuilder();
1256        }
1257
1258        @Override public void write(char[] buf, int offset, int count) {
1259            for(int i = 0; i < count; i++) {
1260                char c = buf[offset + i];
1261                if ( c == '\n') {
1262                    flushBuilder();
1263                }
1264                else {
1265                    mBuilder.append(c);
1266                }
1267            }
1268        }
1269
1270        private void flushBuilder() {
1271            if (mBuilder.length() > 0) {
1272                Log.v("GLSurfaceView", mBuilder.toString());
1273                mBuilder.delete(0, mBuilder.length());
1274            }
1275        }
1276
1277        private StringBuilder mBuilder = new StringBuilder();
1278    }
1279
1280
1281    private void checkRenderThreadState() {
1282        if (mGLThread != null) {
1283            throw new IllegalStateException(
1284                    "setRenderer has already been called for this instance.");
1285        }
1286    }
1287
1288    private static class GLThreadManager {
1289        public void start(GLThread thread) throws InterruptedException {
1290           if (! mGLESVersionCheckComplete) {
1291                mGLESVersion = SystemProperties.getInt(
1292                        "ro.opengles.version",
1293                        ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1294                if (mGLESVersion >= kGLES_20) {
1295                    mMultipleGLESContextsAllowed = true;
1296                }
1297                mGLESVersionCheckComplete = true;
1298            }
1299
1300            GLThread oldThread = null;
1301            synchronized(this) {
1302                oldThread = mMostRecentGLThread;
1303                mMostRecentGLThread = thread;
1304            }
1305            if (oldThread != null && ! mMultipleGLESContextsAllowed) {
1306                synchronized(oldThread) {
1307                    oldThread.notifyAll();
1308                }
1309            }
1310
1311            synchronized(this) {
1312                while ((! mMultipleGLESContextsAllowed)
1313                        && mGLContextCount > 0) {
1314                    wait();
1315                }
1316
1317                mGLContextCount++;
1318            }
1319        }
1320
1321        public synchronized void end(GLThread thread) {
1322            mGLContextCount--;
1323            notifyAll();
1324            if (mMostRecentGLThread == thread) {
1325                mMostRecentGLThread = null;
1326            }
1327        }
1328
1329        public synchronized void checkGLDriver(GL10 gl) {
1330            if (! mGLESDriverCheckComplete) {
1331                if (mGLESVersion < kGLES_20) {
1332                    String renderer = gl.glGetString(GL10.GL_RENDERER);
1333                    mMultipleGLESContextsAllowed =
1334                        ! renderer.startsWith(kMSM7K_RENDERER_PREFIX);
1335                    notifyAll();
1336                }
1337                mGLESDriverCheckComplete = true;
1338            }
1339        }
1340
1341        public boolean shouldQuit(GLThread thread) {
1342            synchronized(this) {
1343                return thread != mMostRecentGLThread;
1344            }
1345        }
1346
1347        private boolean mGLESVersionCheckComplete;
1348        private int mGLESVersion;
1349        private GLThread mMostRecentGLThread;
1350        private boolean mGLESDriverCheckComplete;
1351        private boolean mMultipleGLESContextsAllowed;
1352        private int mGLContextCount;
1353        private static final int kGLES_20 = 0x20000;
1354        private static final String kMSM7K_RENDERER_PREFIX =
1355            "Q3Dimension MSM7500 ";
1356    };
1357
1358    private static final GLThreadManager sGLThreadManager = new GLThreadManager();
1359    private boolean mSizeChanged = true;
1360
1361    private GLThread mGLThread;
1362    private EGLConfigChooser mEGLConfigChooser;
1363    private EGLContextFactory mEGLContextFactory;
1364    private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory;
1365    private GLWrapper mGLWrapper;
1366    private int mDebugFlags;
1367}
1368