SHARE
TWEET

Android GlSurfaceView with setPreserveEGLContextOnPause

arberg Jun 23rd, 2012 2,647 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. // Based on Android-15 Source Code Version (from Android-SDK release) of GLSurfaceView med små lokale ændringer
  17.  
  18. package example.opengl;
  19.  
  20. import android.content.Context;
  21. import android.content.pm.ConfigurationInfo;
  22. import android.graphics.PixelFormat;
  23. import android.opengl.GLDebugHelper;
  24. import android.os.Build;
  25. import android.util.AttributeSet;
  26. import android.util.Log;
  27. import android.view.SurfaceHolder;
  28. import android.view.SurfaceView;
  29.  
  30. import dk.logisoft.opengl.android10.EGLLogWrapper;
  31. import dk.logisoft.trace.CustomExceptionHandler;
  32. import dk.logisoft.util.LogTimer;
  33. import dk.logisoft.util.LogUtil;
  34. import dk.logisoft.util.Logs;
  35.  
  36. import java.io.Writer;
  37. import java.util.ArrayList;
  38.  
  39. import javax.microedition.khronos.egl.EGL10;
  40. import javax.microedition.khronos.egl.EGL11;
  41. import javax.microedition.khronos.egl.EGLConfig;
  42. import javax.microedition.khronos.egl.EGLContext;
  43. import javax.microedition.khronos.egl.EGLDisplay;
  44. import javax.microedition.khronos.egl.EGLSurface;
  45. import javax.microedition.khronos.opengles.GL;
  46. import javax.microedition.khronos.opengles.GL10;
  47.  
  48. /**
  49.  * An implementation of SurfaceView that uses the dedicated surface for
  50.  * displaying OpenGL rendering.
  51.  * <p>
  52.  * A GLSurfaceView provides the following features:
  53.  * <p>
  54.  * <ul>
  55.  * <li>Manages a surface, which is a special piece of memory that can be
  56.  * composited into the Android view system.
  57.  * <li>Manages an EGL display, which enables OpenGL to render into a surface.
  58.  * <li>Accepts a user-provided Renderer object that does the actual rendering.
  59.  * <li>Renders on a dedicated thread to decouple rendering performance from the
  60.  * UI thread.
  61.  * <li>Supports both on-demand and continuous rendering.
  62.  * <li>Optionally wraps, traces, and/or error-checks the renderer's OpenGL
  63.  * calls.
  64.  * </ul>
  65.  * <div class="special reference">
  66.  * <h3>Developer Guides</h3>
  67.  * <p>
  68.  * For more information about how to use OpenGL, read the <a href="{@docRoot}
  69.  * guide/topics/graphics/opengl.html">OpenGL</a> developer guide.
  70.  * </p>
  71.  * </div> <h3>Using GLSurfaceView</h3>
  72.  * <p>
  73.  * Typically you use GLSurfaceView by subclassing it and overriding one or more
  74.  * of the View system input event methods. If your application does not need to
  75.  * override event methods then GLSurfaceView can be used as-is. For the most
  76.  * part GLSurfaceView behavior is customized by calling "set" methods rather
  77.  * than by subclassing. For example, unlike a regular View, drawing is delegated
  78.  * to a separate Renderer object which is registered with the GLSurfaceView
  79.  * using the {@link #setRenderer(Renderer)} call.
  80.  * <p>
  81.  * <h3>Initializing GLSurfaceView</h3> All you have to do to initialize a
  82.  * GLSurfaceView is call {@link #setRenderer(Renderer)}. However, if desired,
  83.  * you can modify the default behavior of GLSurfaceView by calling one or more
  84.  * of these methods before calling setRenderer:
  85.  * <ul>
  86.  * <li>{@link #setDebugFlags(int)}
  87.  * <li>{@link #setEGLConfigChooser(boolean)}
  88.  * <li>{@link #setEGLConfigChooser(EGLConfigChooser)}
  89.  * <li>{@link #setEGLConfigChooserStrict(int, int, int, int, int, int)}
  90.  * <li>{@link #setGLWrapper(GLWrapper)}
  91.  * </ul>
  92.  * <p>
  93.  * <h4>Specifying the android.view.Surface</h4> By default GLSurfaceView will
  94.  * create a PixelFormat.RGB_565 format surface. If a translucent surface is
  95.  * required, call getHolder().setFormat(PixelFormat.TRANSLUCENT). The exact
  96.  * format of a TRANSLUCENT surface is device dependent, but it will be a
  97.  * 32-bit-per-pixel surface with 8 bits per component.
  98.  * <p>
  99.  * <h4>Choosing an EGL Configuration</h4> A given Android device may support
  100.  * multiple EGLConfig rendering configurations. The available configurations may
  101.  * differ in how may channels of data are present, as well as how many bits are
  102.  * allocated to each channel. Therefore, the first thing GLSurfaceView has to do
  103.  * when starting to render is choose what EGLConfig to use.
  104.  * <p>
  105.  * By default GLSurfaceView chooses a EGLConfig that has an RGB_565 pixel
  106.  * format, with at least a 16-bit depth buffer and no stencil.
  107.  * <p>
  108.  * If you would prefer a different EGLConfig you can override the default
  109.  * behavior by calling one of the setEGLConfigChooser methods.
  110.  * <p>
  111.  * It is best to use either 16bit or 32bit (not 24bits) because those two should
  112.  * be supported by all android devices - According to Romain Guy@Google (see
  113.  * google-groups '24 bit color'). Even if device supports 8880, it may run with
  114.  * pixelflinger (Sony xPeria Play) or run slower due to conversions in the
  115.  * hardware (untested hypothesis).
  116.  * <p>
  117.  * <h4>Debug Behavior</h4> You can optionally modify the behavior of
  118.  * GLSurfaceView by calling one or more of the debugging methods
  119.  * {@link #setDebugFlags(int)}, and {@link #setGLWrapper}. These methods may be
  120.  * called before and/or after setRenderer, but typically they are called before
  121.  * setRenderer so that they take effect immediately.
  122.  * <p>
  123.  * <h4>Setting a Renderer</h4> Finally, you must call {@link #setRenderer} to
  124.  * register a {@link Renderer}. The renderer is responsible for doing the actual
  125.  * OpenGL rendering.
  126.  * <p>
  127.  * <h3>Rendering Mode</h3> Once the renderer is set, you can control whether the
  128.  * renderer draws continuously or on-demand by calling {@link #setRenderMode}.
  129.  * The default is continuous rendering.
  130.  * <p>
  131.  * <h3>Activity Life-cycle</h3> A GLSurfaceView must be notified when the
  132.  * activity is paused and resumed. GLSurfaceView clients are required to call
  133.  * {@link #onPause()} when the activity pauses and {@link #onResume()} when the
  134.  * activity resumes. These calls allow GLSurfaceView to pause and resume the
  135.  * rendering thread, and also allow GLSurfaceView to release and recreate the
  136.  * OpenGL display.
  137.  * <p>
  138.  * <h3>Handling events</h3>
  139.  * <p>
  140.  * To handle an event you will typically subclass GLSurfaceView and override the
  141.  * appropriate method, just as you would with any other View. However, when
  142.  * handling the event, you may need to communicate with the Renderer object
  143.  * that's running in the rendering thread. You can do this using any standard
  144.  * Java cross-thread communication mechanism. In addition, one relatively easy
  145.  * way to communicate with your renderer is to call
  146.  * {@link #queueEvent(Runnable)}. For example:
  147.  *
  148.  * <pre class="prettyprint">
  149.  * class MyGLSurfaceView extends GLSurfaceView {
  150.  *
  151.  *     private MyRenderer mMyRenderer;
  152.  *
  153.  *     public void start() {
  154.  *         mMyRenderer = ...;
  155.  *         setRenderer(mMyRenderer);
  156.  *     }
  157.  *
  158.  *     public boolean onKeyDown(int keyCode, KeyEvent event) {
  159.  *         if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
  160.  *             queueEvent(new Runnable() {
  161.  *                 // This method will be called on the rendering
  162.  *                 // thread:
  163.  *                 public void run() {
  164.  *                     mMyRenderer.handleDpadCenter();
  165.  *                 }
  166.  *             });
  167.  *             return true;
  168.  *         }
  169.  *         return super.onKeyDown(keyCode, event);
  170.  *     }
  171.  * }
  172.  *
  173.  *
  174.  *
  175.  * </pre>
  176.  */
  177. public class GLSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
  178.     private final static String TAG = "GlSurfaceView";
  179.     private static final int ANDROID_SDK_VERSION = Integer.parseInt(Build.VERSION.SDK);
  180.     private final static boolean LOG_PAUSE_RESUME = false;
  181.     private final static boolean LOG_SWAP_TIME = false;
  182.     private final static boolean LOG_ATTACH_DETACH = false;
  183.     private final static boolean LOG_THREADS = false;
  184.     private final static boolean LOG_SURFACE = false;
  185.     private final static boolean LOG_RENDERER = false;
  186.     private final static boolean LOG_RENDERER_DRAW_FRAME = false;
  187.     private final static boolean LOG_EGL = false;
  188.     // Work-around for bug 2263168
  189.     private final static boolean DRAW_TWICE_AFTER_SIZE_CHANGED = true;
  190.     /**
  191.      * The renderer only renders when the surface is created, or when
  192.      * {@link #requestRender} is called.
  193.      *
  194.      * @see #getRenderMode()
  195.      * @see #setRenderMode(int)
  196.      * @see #requestRender()
  197.      */
  198.     public final static int RENDERMODE_WHEN_DIRTY = 0;
  199.     /**
  200.      * The renderer is called continuously to re-render the scene.
  201.      *
  202.      * @see #getRenderMode()
  203.      * @see #setRenderMode(int)
  204.      */
  205.     public final static int RENDERMODE_CONTINUOUSLY = 1;
  206.  
  207.     /**
  208.      * Check glError() after every GL call and throw an exception if glError
  209.      * indicates that an error has occurred. This can be used to help track down
  210.      * which OpenGL ES call is causing an error.
  211.      *
  212.      * @see #getDebugFlags
  213.      * @see #setDebugFlags
  214.      */
  215.     public final static int DEBUG_CHECK_GL_ERROR = 1;
  216.  
  217.     /**
  218.      * Log GL calls to the system log at "verbose" level with tag
  219.      * "GLSurfaceView".
  220.      *
  221.      * @see #getDebugFlags
  222.      * @see #setDebugFlags
  223.      */
  224.     public final static int DEBUG_LOG_GL_CALLS = 2;
  225.  
  226.     private final Context context;
  227.  
  228.     /**
  229.      * Standard View constructor. In order to render something, you must call
  230.      * {@link #setRenderer} to register a renderer.
  231.      */
  232.     public GLSurfaceView(final Context context) {
  233.         super(context);
  234.         this.context = context;
  235.         init();
  236.     }
  237.  
  238.     /**
  239.      * Standard View constructor. In order to render something, you must call
  240.      * {@link #setRenderer} to register a renderer.
  241.      */
  242.     public GLSurfaceView(final Context context, final AttributeSet attrs) {
  243.         super(context, attrs);
  244.         this.context = context;
  245.         init();
  246.     }
  247.  
  248.     private void init() {
  249.         // Install a SurfaceHolder.Callback so we get notified when the
  250.         // underlying surface is created and destroyed
  251.         final SurfaceHolder holder = getHolder();
  252.         holder.addCallback(this);
  253.         if (ANDROID_SDK_VERSION <= 4) {
  254.             // setType is not needed for SDK 2.0 or newer.
  255.             holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
  256.         } else if (ANDROID_SDK_VERSION <= 8) {
  257.             // setFormat is done by SurfaceView in SDK 2.3 and newer.
  258.             holder.setFormat(PixelFormat.RGB_565);
  259.         }
  260.     }
  261.  
  262.     /**
  263.      * Set the glWrapper. If the glWrapper is not null, its
  264.      * {@link GLWrapper#wrap(GL)} method is called whenever a surface is
  265.      * created. A GLWrapper can be used to wrap the GL object that's passed to
  266.      * the renderer. Wrapping a GL object enables examining and modifying the
  267.      * behavior of the GL calls made by the renderer.
  268.      * <p>
  269.      * Wrapping is typically used for debugging purposes.
  270.      * <p>
  271.      * The default value is null.
  272.      *
  273.      * @param glWrapper the new GLWrapper
  274.      */
  275.     public void setGLWrapper(final GLWrapper glWrapper) {
  276.         mGLWrapper = glWrapper;
  277.     }
  278.  
  279.     /**
  280.      * Set the debug flags to a new value. The value is constructed by
  281.      * OR-together zero or more of the DEBUG_CHECK_* constants. The debug flags
  282.      * take effect whenever a surface is created. The default value is zero.
  283.      *
  284.      * @param debugFlags the new debug flags
  285.      * @see #DEBUG_CHECK_GL_ERROR
  286.      * @see #DEBUG_LOG_GL_CALLS
  287.      */
  288.     public void setDebugFlags(final int debugFlags) {
  289.         mDebugFlags = debugFlags;
  290.     }
  291.  
  292.     /**
  293.      * Get the current value of the debug flags.
  294.      *
  295.      * @return the current value of the debug flags.
  296.      */
  297.     public int getDebugFlags() {
  298.         return mDebugFlags;
  299.     }
  300.  
  301.     /**
  302.      * Control whether the EGL context is preserved when the GLSurfaceView is
  303.      * paused and resumed.
  304.      * <p>
  305.      * If set to true, then the EGL context may be preserved when the
  306.      * GLSurfaceView is paused. Whether the EGL context is actually preserved or
  307.      * not depends upon whether the Android device that the program is running
  308.      * on can support an arbitrary number of EGL contexts or not. Devices that
  309.      * can only support a limited number of EGL contexts must release the EGL
  310.      * context in order to allow multiple applications to share the GPU.
  311.      * <p>
  312.      * If set to false, the EGL context will be released when the GLSurfaceView
  313.      * is paused, and recreated when the GLSurfaceView is resumed.
  314.      * <p>
  315.      * The default is false.
  316.      *
  317.      * @param preserveOnPause preserve the EGL context when paused
  318.      */
  319.     public void setPreserveEGLContextOnPause(final boolean preserveOnPause) {
  320.         mPreserveEGLContextOnPause = preserveOnPause;
  321.     }
  322.  
  323.     /**
  324.      * @return true if the EGL context will be preserved when paused
  325.      */
  326.     public boolean getPreserveEGLContextOnPause() {
  327.         return mPreserveEGLContextOnPause;
  328.     }
  329.  
  330.     /**
  331.      * Set the renderer associated with this view. Also starts the thread that
  332.      * will call the renderer, which in turn causes the rendering to start.
  333.      * <p>
  334.      * This method should be called once and only once in the life-cycle of a
  335.      * GLSurfaceView.
  336.      * <p>
  337.      * The following GLSurfaceView methods can only be called <em>before</em>
  338.      * setRenderer is called:
  339.      * <ul>
  340.      * <li>{@link #setEGLConfigChooser(boolean)}
  341.      * <li>{@link #setEGLConfigChooser(EGLConfigChooser)}
  342.      * <li>{@link #setEGLConfigChooserStrict(int, int, int, int, int, int)}
  343.      * </ul>
  344.      * <p>
  345.      * The following GLSurfaceView methods can only be called <em>after</em>
  346.      * setRenderer is called:
  347.      * <ul>
  348.      * <li>{@link #getRenderMode()}
  349.      * <li>{@link #onPause()}
  350.      * <li>{@link #onResume()}
  351.      * <li>{@link #queueEvent(Runnable)}
  352.      * <li>{@link #requestRender()}
  353.      * <li>{@link #setRenderMode(int)}
  354.      * </ul>
  355.      *
  356.      * @param renderer the renderer to use to perform OpenGL drawing.
  357.      */
  358.     public void setRenderer(final Renderer renderer) {
  359.         checkRenderThreadState();
  360.         if (mEGLConfigChooser == null) {
  361.             mEGLConfigChooser = new SimpleComponentEGLConfigChooser(5, 6, 5, 0, true);
  362.         }
  363.         if (mEGLContextFactory == null) {
  364.             mEGLContextFactory = new DefaultContextFactory();
  365.         }
  366.         if (mEGLWindowSurfaceFactory == null) {
  367.             mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory();
  368.         }
  369.         mRenderer = renderer;
  370.         mGLThread = new GLThread(renderer);
  371.         mGLThread.start();
  372.     }
  373.  
  374.     /**
  375.      * Install a custom EGLContextFactory.
  376.      * <p>
  377.      * If this method is called, it must be called before
  378.      * {@link #setRenderer(Renderer)} is called.
  379.      * <p>
  380.      * If this method is not called, then by default a context will be created
  381.      * with no shared context and with a null attribute list.
  382.      */
  383.     public void setEGLContextFactory(final EGLContextFactory factory) {
  384.         checkRenderThreadState();
  385.         mEGLContextFactory = factory;
  386.     }
  387.  
  388.     /**
  389.      * Install a custom EGLWindowSurfaceFactory.
  390.      * <p>
  391.      * If this method is called, it must be called before
  392.      * {@link #setRenderer(Renderer)} is called.
  393.      * <p>
  394.      * If this method is not called, then by default a window surface will be
  395.      * created with a null attribute list.
  396.      */
  397.     public void setEGLWindowSurfaceFactory(final EGLWindowSurfaceFactory factory) {
  398.         checkRenderThreadState();
  399.         mEGLWindowSurfaceFactory = factory;
  400.     }
  401.  
  402.     /**
  403.      * Install a custom EGLConfigChooser.
  404.      * <p>
  405.      * If this method is called, it must be called before
  406.      * {@link #setRenderer(Renderer)} is called.
  407.      * <p>
  408.      * If no setEGLConfigChooser method is called, then by default the view will
  409.      * choose an EGLConfig that is compatible with the current
  410.      * android.view.Surface, with a depth buffer depth of at least 16 bits.
  411.      *
  412.      * @param configChooser
  413.      */
  414.     public void setEGLConfigChooser(final EGLConfigChooser configChooser) {
  415.         checkRenderThreadState();
  416.         mEGLConfigChooser = configChooser;
  417.     }
  418.  
  419.     /**
  420.      * Install a config chooser which will choose a config as close to 16-bit
  421.      * rgb as possible, with or without an optional depth buffer as close to
  422.      * 16-bits as possible.
  423.      * <p>
  424.      * The matching alpha value is preferred over matching RGB.
  425.      * <p>
  426.      * If this method is called, it must be called before
  427.      * {@link #setrenderer(renderer)} is called.
  428.      * <p>
  429.      * If no seteglconfigchooser method is called, then by default the view will
  430.      * choose an rgb_565 surface with a depth buffer depth of at least 16 bits.
  431.      *
  432.      * @param needdepth
  433.      */
  434.     public void setEGLConfigChooser(final boolean needDepth) {
  435.         setEGLConfigChooser(new SimpleComponentEGLConfigChooser(5, 6, 5, 0, needDepth));
  436.     }
  437.  
  438.     /**
  439.      * Install a config chooser which will choose a config as close to the
  440.      * requested rgb bit-detph as possible, but at least rgba=4440, with or
  441.      * without an optional depth buffer as close to 16-bits as possible.
  442.      * <p>
  443.      * The matching alpha value is preferred over matching RGB.
  444.      * <p>
  445.      * If this method is called, it must be called before
  446.      * {@link #setrenderer(renderer)} is called.
  447.      * <p>
  448.      * If no seteglconfigchooser method is called, then by default the view will
  449.      * choose an rgb_565 surface with a depth buffer depth of at least 16 bits.
  450.      *
  451.      * @param needdepth
  452.      */
  453.     public void setEGLConfigChooser(final int redSize, final int greenSize, final int blueSize,
  454.             final int alphaSize, final boolean needDepth) {
  455.         setEGLConfigChooser(new SimpleComponentEGLConfigChooser(redSize, greenSize, blueSize,
  456.                 alphaSize, needDepth));
  457.     }
  458.  
  459.     /**
  460.      * Install a config chooser which will choose a config with at least the
  461.      * specified depthSize and stencilSize, and exactly the specified redSize,
  462.      * greenSize, blueSize and alphaSize. If no such config exists, creation of
  463.      * the GL surface will fail with exception.
  464.      * <p>
  465.      * If this method is called, it must be called before
  466.      * {@link #setRenderer(Renderer)} is called.
  467.      * <p>
  468.      * If no setEGLConfigChooser method is called, then by default the view will
  469.      * choose an RGB_565 surface with a depth buffer depth of at least 16 bits.
  470.      */
  471.     public void setEGLConfigChooserStrict(final int redSize, final int greenSize,
  472.             final int blueSize, final int alphaSize, final int depthSize,
  473.             final int stencilSize) {
  474.         setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize, blueSize, alphaSize,
  475.                 depthSize, stencilSize));
  476.     }
  477.  
  478.     /**
  479.      * Inform the default EGLContextFactory and default EGLConfigChooser which
  480.      * EGLContext client version to pick.
  481.      * <p>
  482.      * Use this method to create an OpenGL ES 2.0-compatible context. Example:
  483.      *
  484.      * <pre class="prettyprint">
  485.      * public MyView(Context context) {
  486.      *     super(context);
  487.      *     setEGLContextClientVersion(2); // Pick an OpenGL ES 2.0 context.
  488.      *     setRenderer(new MyRenderer());
  489.      * }
  490.      * </pre>
  491.      * <p>
  492.      * Note: Activities which require OpenGL ES 2.0 should indicate this by
  493.      * setting @lt;uses-feature android:glEsVersion="0x00020000" /> in the
  494.      * activity's AndroidManifest.xml file.
  495.      * <p>
  496.      * If this method is called, it must be called before
  497.      * {@link #setRenderer(Renderer)} is called.
  498.      * <p>
  499.      * This method only affects the behavior of the default EGLContexFactory and
  500.      * the default EGLConfigChooser. If
  501.      * {@link #setEGLContextFactory(EGLContextFactory)} has been called, then
  502.      * the supplied EGLContextFactory is responsible for creating an OpenGL ES
  503.      * 2.0-compatible context. If {@link #setEGLConfigChooser(EGLConfigChooser)}
  504.      * has been called, then the supplied EGLConfigChooser is responsible for
  505.      * choosing an OpenGL ES 2.0-compatible config.
  506.      *
  507.      * @param version The EGLContext client version to choose. Use 2 for OpenGL
  508.      *            ES 2.0
  509.      */
  510.     public void setEGLContextClientVersion(final int version) {
  511.         checkRenderThreadState();
  512.         mEGLContextClientVersion = version;
  513.     }
  514.  
  515.     /**
  516.      * Set the rendering mode. When renderMode is RENDERMODE_CONTINUOUSLY, the
  517.      * renderer is called repeatedly to re-render the scene. When renderMode is
  518.      * RENDERMODE_WHEN_DIRTY, the renderer only rendered when the surface is
  519.      * created, or when {@link #requestRender} is called. Defaults to
  520.      * RENDERMODE_CONTINUOUSLY.
  521.      * <p>
  522.      * Using RENDERMODE_WHEN_DIRTY can improve battery life and overall system
  523.      * performance by allowing the GPU and CPU to idle when the view does not
  524.      * need to be updated.
  525.      * <p>
  526.      * This method can only be called after {@link #setRenderer(Renderer)}
  527.      *
  528.      * @param renderMode one of the RENDERMODE_X constants
  529.      * @see #RENDERMODE_CONTINUOUSLY
  530.      * @see #RENDERMODE_WHEN_DIRTY
  531.      */
  532.     public void setRenderMode(final int renderMode) {
  533.         mGLThread.setRenderMode(renderMode);
  534.     }
  535.  
  536.     /**
  537.      * Get the current rendering mode. May be called from any thread. Must not
  538.      * be called before a renderer has been set.
  539.      *
  540.      * @return the current rendering mode.
  541.      * @see #RENDERMODE_CONTINUOUSLY
  542.      * @see #RENDERMODE_WHEN_DIRTY
  543.      */
  544.     public int getRenderMode() {
  545.         return mGLThread.getRenderMode();
  546.     }
  547.  
  548.     /**
  549.      * Request that the renderer render a frame. This method is typically used
  550.      * when the render mode has been set to {@link #RENDERMODE_WHEN_DIRTY}, so
  551.      * that frames are only rendered on demand. May be called from any thread.
  552.      * Must not be called before a renderer has been set.
  553.      */
  554.     public void requestRender() {
  555.         mGLThread.requestRender();
  556.     }
  557.  
  558.     /**
  559.      * This method is part of the SurfaceHolder.Callback interface, and is not
  560.      * normally called or subclassed by clients of GLSurfaceView.
  561.      */
  562.     @Override
  563.     public void surfaceCreated(final SurfaceHolder holder) {
  564.         mGLThread.surfaceCreated();
  565.     }
  566.  
  567.     /**
  568.      * This method is part of the SurfaceHolder.Callback interface, and is not
  569.      * normally called or subclassed by clients of GLSurfaceView.
  570.      */
  571.     @Override
  572.     public void surfaceDestroyed(final SurfaceHolder holder) {
  573.         // Surface will be destroyed when we return
  574.         mGLThread.surfaceDestroyed();
  575.     }
  576.  
  577.     /**
  578.      * This method is part of the SurfaceHolder.Callback interface, and is not
  579.      * normally called or subclassed by clients of GLSurfaceView.
  580.      */
  581.     @Override
  582.     public void surfaceChanged(final SurfaceHolder holder, final int format, final int w,
  583.             final int h) {
  584.         mGLThread.onWindowResize(w, h);
  585.     }
  586.  
  587.     /**
  588.      * Inform the view that the activity is paused. The owner of this view must
  589.      * call this method when the activity is paused. Calling this method will
  590.      * pause the rendering thread. Must not be called before a renderer has been
  591.      * set.
  592.      */
  593.     public void onPause() {
  594.         mGLThread.onPause();
  595.     }
  596.  
  597.     /**
  598.      * Inform the view that the activity is resumed. The owner of this view must
  599.      * call this method when the activity is resumed. Calling this method will
  600.      * recreate the OpenGL display and resume the rendering thread. Must not be
  601.      * called before a renderer has been set.
  602.      */
  603.     public void onResume() {
  604.         mGLThread.onResume();
  605.     }
  606.  
  607.     /**
  608.      * Queue a runnable to be run on the GL rendering thread. This can be used
  609.      * to communicate with the Renderer on the rendering thread. Must not be
  610.      * called before a renderer has been set.
  611.      *
  612.      * @param r the runnable to be run on the GL rendering thread.
  613.      */
  614.     public void queueEvent(final Runnable r) {
  615.         mGLThread.queueEvent(r);
  616.     }
  617.  
  618.     /**
  619.      * Inform the view that the window focus has changed. Added to fix Android <
  620.      * 5 G1 Clipping problem, see comments around if-block at line 1575.
  621.      */
  622.     @Override
  623.     public void onWindowFocusChanged(final boolean hasFocus) {
  624.         super.onWindowFocusChanged(hasFocus);
  625.         mGLThread.onWindowFocusChanged(hasFocus);
  626.     }
  627.  
  628.     /**
  629.      * This method is used as part of the View class and is not normally called
  630.      * or subclassed by clients of GLSurfaceView.
  631.      */
  632.     @Override
  633.     protected void onAttachedToWindow() {
  634.         super.onAttachedToWindow();
  635.         if (LOG_ATTACH_DETACH) {
  636.             Log.d(TAG, "onAttachedToWindow reattach =" + mDetached);
  637.         }
  638.         if (mDetached && mRenderer != null) {
  639.             int renderMode = RENDERMODE_CONTINUOUSLY;
  640.             if (mGLThread != null) {
  641.                 renderMode = mGLThread.getRenderMode();
  642.             }
  643.             mGLThread = new GLThread(mRenderer);
  644.             if (renderMode != RENDERMODE_CONTINUOUSLY) {
  645.                 mGLThread.setRenderMode(renderMode);
  646.             }
  647.             mGLThread.start();
  648.         }
  649.         mDetached = false;
  650.     }
  651.  
  652.     /**
  653.      * This method is used as part of the View class and is not normally called
  654.      * or subclassed by clients of GLSurfaceView. Must not be called before a
  655.      * renderer has been set.
  656.      */
  657.     @Override
  658.     protected void onDetachedFromWindow() {
  659.         if (LOG_ATTACH_DETACH) {
  660.             Log.d(TAG, "onDetachedFromWindow");
  661.         }
  662.         if (mGLThread != null) {
  663.             mGLThread.requestExitAndWait();
  664.         }
  665.         mDetached = true;
  666.         super.onDetachedFromWindow();
  667.     }
  668.  
  669.     /**
  670.      * Waits for the GLThread to exit if the thread has been created.
  671.      */
  672.     public void waitForGlThreadExit() {
  673.         if (mGLThread != null)
  674.             mGLThread.waitForExit();
  675.     }
  676.  
  677.     /**
  678.      * Returns true if the GLThread has been started and is still running.
  679.      *
  680.      * @return true if the GLThread has been started and is still running.
  681.      */
  682.     public boolean isAlive() {
  683.         return mGLThread != null && mGLThread.isAlive();
  684.     }
  685.  
  686.     // ----------------------------------------------------------------------
  687.  
  688.     /**
  689.      * An interface used to wrap a GL interface.
  690.      * <p>
  691.      * Typically used for implementing debugging and tracing on top of the
  692.      * default GL interface. You would typically use this by creating your own
  693.      * class that implemented all the GL methods by delegating to another GL
  694.      * instance. Then you could add your own behavior before or after calling
  695.      * the delegate. All the GLWrapper would do was instantiate and return the
  696.      * wrapper GL instance:
  697.      *
  698.      * <pre class="prettyprint">
  699.      * class MyGLWrapper implements GLWrapper {
  700.      *     GL wrap(GL gl) {
  701.      *         return new MyGLImplementation(gl);
  702.      *     }
  703.      *     static class MyGLImplementation implements GL,GL10,GL11,... {
  704.      *         ...
  705.      *     }
  706.      * }
  707.      * </pre>
  708.      *
  709.      * @see #setGLWrapper(GLWrapper)
  710.      */
  711.     public interface GLWrapper {
  712.         /**
  713.          * Wraps a gl interface in another gl interface.
  714.          *
  715.          * @param gl a GL interface that is to be wrapped.
  716.          * @return either the input argument or another GL object that wraps the
  717.          *         input argument.
  718.          */
  719.         GL wrap(GL gl);
  720.     }
  721.  
  722.     /**
  723.      * A generic renderer interface.
  724.      * <p>
  725.      * The renderer is responsible for making OpenGL calls to render a frame.
  726.      * <p>
  727.      * GLSurfaceView clients typically create their own classes that implement
  728.      * this interface, and then call {@link GLSurfaceView#setRenderer} to
  729.      * register the renderer with the GLSurfaceView.
  730.      * <p>
  731.      * <div class="special reference">
  732.      * <h3>Developer Guides</h3>
  733.      * <p>
  734.      * For more information about how to use OpenGL, read the <a
  735.      * href="{@docRoot}guide/topics/graphics/opengl.html">OpenGL</a> developer
  736.      * guide.
  737.      * </p>
  738.      * </div> <h3>Threading</h3> The renderer will be called on a separate
  739.      * thread, so that rendering performance is decoupled from the UI thread.
  740.      * Clients typically need to communicate with the renderer from the UI
  741.      * thread, because that's where input events are received. Clients can
  742.      * communicate using any of the standard Java techniques for cross-thread
  743.      * communication, or they can use the
  744.      * {@link GLSurfaceView#queueEvent(Runnable)} convenience method.
  745.      * <p>
  746.      * <h3>EGL Context Lost</h3> There are situations where the EGL rendering
  747.      * context will be lost. This typically happens when device wakes up after
  748.      * going to sleep. When the EGL context is lost, all OpenGL resources (such
  749.      * as textures) that are associated with that context will be automatically
  750.      * deleted. In order to keep rendering correctly, a renderer must recreate
  751.      * any lost resources that it still needs. The
  752.      * {@link #onSurfaceCreated(GL10, EGLConfig)} method is a convenient place
  753.      * to do this.
  754.      *
  755.      * @see #setRenderer(Renderer)
  756.      */
  757.     public interface Renderer {
  758.         /**
  759.          * Called when the surface is created or recreated.
  760.          * <p>
  761.          * Called when the rendering thread starts and whenever the EGL context
  762.          * is lost. The EGL context will typically be lost when the Android
  763.          * device awakes after going to sleep.
  764.          * <p>
  765.          * Since this method is called at the beginning of rendering, as well as
  766.          * every time the EGL context is lost, this method is a convenient place
  767.          * to put code to create resources that need to be created when the
  768.          * rendering starts, and that need to be recreated when the EGL context
  769.          * is lost. Textures are an example of a resource that you might want to
  770.          * create here.
  771.          * <p>
  772.          * Note that when the EGL context is lost, all OpenGL resources
  773.          * associated with that context will be automatically deleted. You do
  774.          * not need to call the corresponding "glDelete" methods such as
  775.          * glDeleteTextures to manually delete these lost resources.
  776.          * <p>
  777.          *
  778.          * @param gl the GL interface. Use <code>instanceof</code> to test if
  779.          *            the interface supports GL11 or higher interfaces.
  780.          * @param config the EGLConfig of the created surface. Can be used to
  781.          *            create matching pbuffers.
  782.          */
  783.         void onSurfaceCreated(GL10 gl, EglConfigInfo config);
  784.  
  785.         /**
  786.          * Called when the surface changed size.
  787.          * <p>
  788.          * Called after the surface is created and whenever the OpenGL ES
  789.          * surface size changes.
  790.          * <p>
  791.          * Typically you will set your viewport here. If your camera is fixed
  792.          * then you could also set your projection matrix here:
  793.          *
  794.          * <pre class="prettyprint">
  795.          * void onSurfaceChanged(GL10 gl, int width, int height) {
  796.          *     gl.glViewport(0, 0, width, height);
  797.          *     // for a fixed camera, set the projection too
  798.          *     float ratio = (float) width / height;
  799.          *     gl.glMatrixMode(GL10.GL_PROJECTION);
  800.          *     gl.glLoadIdentity();
  801.          *     gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
  802.          * }
  803.          * </pre>
  804.          *
  805.          * @param gl the GL interface. Use <code>instanceof</code> to test if
  806.          *            the interface supports GL11 or higher interfaces.
  807.          * @param width
  808.          * @param height
  809.          */
  810.         void onSurfaceChanged(GL10 gl, int width, int height);
  811.  
  812.         /**
  813.          * Called to draw the current frame.
  814.          * <p>
  815.          * This method is responsible for drawing the current frame.
  816.          * <p>
  817.          * The implementation of this method typically looks like this:
  818.          *
  819.          * <pre class="prettyprint">
  820.          * void onDrawFrame(GL10 gl) {
  821.          *     gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
  822.          *     // ... other gl calls to render the scene ...
  823.          * }
  824.          * </pre>
  825.          *
  826.          * @param gl the GL interface. Use <code>instanceof</code> to test if
  827.          *            the interface supports GL11 or higher interfaces.
  828.          */
  829.         void onDrawFrame(GL10 gl) throws InterruptedException;
  830.  
  831.         void logLastSwapDuration(long nanoTimeBeforeEglSwap, long nanoTimeAfterEglSwap);
  832.  
  833.         void onExit();
  834.     }
  835.  
  836.     /**
  837.      * An interface for customizing the eglCreateContext and eglDestroyContext
  838.      * calls.
  839.      * <p>
  840.      * This interface must be implemented by clients wishing to call
  841.      * {@link GLSurfaceView#setEGLContextFactory(EGLContextFactory)}
  842.      */
  843.     public interface EGLContextFactory {
  844.         EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig);
  845.  
  846.         void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context);
  847.     }
  848.  
  849.     private class DefaultContextFactory implements EGLContextFactory {
  850.         private final int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
  851.  
  852.         @Override
  853.         public EGLContext createContext(final EGL10 egl, final EGLDisplay display,
  854.                 final EGLConfig config) {
  855.             final int[] attrib_list = {
  856.                     EGL_CONTEXT_CLIENT_VERSION, mEGLContextClientVersion, EGL10.EGL_NONE
  857.             };
  858.  
  859.             return egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT,
  860.                     mEGLContextClientVersion != 0 ? attrib_list : null);
  861.         }
  862.  
  863.         @Override
  864.         public void destroyContext(final EGL10 egl, final EGLDisplay display,
  865.                 final EGLContext context) {
  866.             if (!egl.eglDestroyContext(display, context)) {
  867.                 Log.e("DefaultContextFactory", "display:" + display + " context: " + context);
  868.                 if (LOG_THREADS) {
  869.                     Log.i("DefaultContextFactory", "tid=" + Thread.currentThread().getId());
  870.                 }
  871.                 throw new RuntimeException("eglDestroyContext failed: "
  872.                         + EGLLogWrapper.getErrorString(egl.eglGetError()));
  873.             }
  874.         }
  875.     }
  876.  
  877.     /**
  878.      * An interface for customizing the eglCreateWindowSurface and
  879.      * eglDestroySurface calls.
  880.      * <p>
  881.      * This interface must be implemented by clients wishing to call
  882.      * {@link GLSurfaceView#setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory)}
  883.      */
  884.     public interface EGLWindowSurfaceFactory {
  885.         /**
  886.          * @return null if the surface cannot be constructed.
  887.          */
  888.         EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, EGLConfig config,
  889.                 Object nativeWindow);
  890.  
  891.         void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface);
  892.     }
  893.  
  894.     private static class DefaultWindowSurfaceFactory implements EGLWindowSurfaceFactory {
  895.  
  896.         @Override
  897.         public EGLSurface createWindowSurface(final EGL10 egl, final EGLDisplay display,
  898.                 final EGLConfig config, final Object nativeWindow) {
  899.             EGLSurface result = null;
  900.             try {
  901.                 result = egl.eglCreateWindowSurface(display, config, nativeWindow, null);
  902.             } catch (final IllegalArgumentException e) {
  903.                 // This exception indicates that the surface flinger surface
  904.                 // is not valid. This can happen if the surface flinger surface
  905.                 // has
  906.                 // been torn down, but the application has not yet been
  907.                 // notified via SurfaceHolder.Callback.surfaceDestroyed.
  908.                 // In theory the application should be notified first,
  909.                 // but in practice sometimes it is not. See b/4588890
  910.                 Log.e(TAG, "eglCreateWindowSurface", e);
  911.             }
  912.             return result;
  913.         }
  914.  
  915.         @Override
  916.         public void destroySurface(final EGL10 egl, final EGLDisplay display,
  917.                 final EGLSurface surface) {
  918.             egl.eglDestroySurface(display, surface);
  919.         }
  920.     }
  921.  
  922.     /**
  923.      * An interface for choosing an EGLConfig configuration from a list of
  924.      * potential configurations.
  925.      * <p>
  926.      * This interface must be implemented by clients wishing to call
  927.      * {@link GLSurfaceView#setEGLConfigChooser(EGLConfigChooser)}
  928.      */
  929.     public interface EGLConfigChooser {
  930.         /**
  931.          * Choose a configuration from the list. Implementors typically
  932.          * implement this method by calling {@link EGL10#eglChooseConfig} and
  933.          * iterating through the results. Please consult the EGL specification
  934.          * available from The Khronos Group to learn how to call
  935.          * eglChooseConfig.
  936.          *
  937.          * @param egl the EGL10 for the current display.
  938.          * @param display the current display.
  939.          * @return the chosen configuration.
  940.          */
  941.         EGLConfig chooseConfig(EGL10 egl, EGLDisplay display);
  942.     }
  943.  
  944.     private abstract class BaseConfigChooser implements EGLConfigChooser {
  945.         public BaseConfigChooser(final int[] configSpec) {
  946.             mConfigSpec = filterConfigSpec(configSpec);
  947.         }
  948.  
  949.         @Override
  950.         public EGLConfig chooseConfig(final EGL10 egl, final EGLDisplay display) {
  951.             final int[] num_config = new int[1];
  952.             if (!egl.eglChooseConfig(display, mConfigSpec, null, 0, num_config)) {
  953.                 throw new IllegalArgumentException("eglChooseConfig failed");
  954.             }
  955.  
  956.             final int numConfigs = num_config[0];
  957.  
  958.             if (numConfigs <= 0) {
  959.                 throw new IllegalArgumentException("No configs match configSpec");
  960.             }
  961.  
  962.             final EGLConfig[] configs = new EGLConfig[numConfigs];
  963.             if (!egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs, num_config)) {
  964.                 throw new IllegalArgumentException("eglChooseConfig#2 failed");
  965.             }
  966.             final EGLConfig config = chooseConfig(egl, display, configs);
  967.             if (config == null) {
  968.                 throw new IllegalArgumentException("No config chosen");
  969.             }
  970.             return config;
  971.         }
  972.  
  973.         abstract EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs);
  974.  
  975.         protected int[] mConfigSpec;
  976.  
  977.         private int[] filterConfigSpec(final int[] configSpec) {
  978.             if (mEGLContextClientVersion != 2) {
  979.                 return configSpec;
  980.             }
  981.             /*
  982.              * We know none of the subclasses define EGL_RENDERABLE_TYPE. And we
  983.              * know the configSpec is well formed.
  984.              */
  985.             final int len = configSpec.length;
  986.             final int[] newConfigSpec = new int[len + 2];
  987.             System.arraycopy(configSpec, 0, newConfigSpec, 0, len - 1);
  988.             newConfigSpec[len - 1] = EGL10.EGL_RENDERABLE_TYPE;
  989.             newConfigSpec[len] = 4; /* EGL_OPENGL_ES2_BIT */
  990.             newConfigSpec[len + 1] = EGL10.EGL_NONE;
  991.             return newConfigSpec;
  992.         }
  993.     }
  994.  
  995.     /**
  996.      * Choose a configuration with exactly the specified r,g,b,a sizes, and at
  997.      * least the specified depth and stencil sizes.
  998.      */
  999.     private class ComponentSizeChooser extends BaseConfigChooser {
  1000.         public ComponentSizeChooser(final int redSize, final int greenSize, final int blueSize,
  1001.                 final int alphaSize, final int depthSize,
  1002.                 final int stencilSize) {
  1003.             super(new int[] {
  1004.                     EGL10.EGL_RED_SIZE, redSize, EGL10.EGL_GREEN_SIZE, greenSize,
  1005.                     EGL10.EGL_BLUE_SIZE, blueSize, EGL10.EGL_ALPHA_SIZE,
  1006.                     alphaSize, EGL10.EGL_DEPTH_SIZE, depthSize, EGL10.EGL_STENCIL_SIZE,
  1007.                     stencilSize, EGL10.EGL_NONE
  1008.             });
  1009.             mValue = new int[1];
  1010.             mRedSize = redSize;
  1011.             mGreenSize = greenSize;
  1012.             mBlueSize = blueSize;
  1013.             mAlphaSize = alphaSize;
  1014.             mDepthSize = depthSize;
  1015.             mStencilSize = stencilSize;
  1016.         }
  1017.  
  1018.         @Override
  1019.         public EGLConfig chooseConfig(final EGL10 egl, final EGLDisplay display,
  1020.                 final EGLConfig[] configs) {
  1021.             EGLConfig closestConfig = null;
  1022.             int closestDistance = Integer.MAX_VALUE;
  1023.             if (LOG_EGL)
  1024.                 Log.d(TAG, "Searching for Config with rgba=" + mRedSize + "," + mGreenSize + ","
  1025.                         + mBlueSize + "," + mAlphaSize + ", depth="
  1026.                         + mDepthSize + ",stencil=" + mStencilSize
  1027.                         + " (alpha distance weighted 100 as much as rgb distance)");
  1028.             for (final EGLConfig config : configs) {
  1029.                 // Depth refers to Depth Buffer Size (z-buffer).
  1030.                 final int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0);
  1031.                 final int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0);
  1032.                 if (d >= mDepthSize && s >= mStencilSize) {
  1033.                     final int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0);
  1034.                     final int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0);
  1035.                     final int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0);
  1036.                     final int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0);
  1037.                     final int distance = Math.abs(r - mRedSize) + Math.abs(g - mGreenSize)
  1038.                             + Math.abs(b - mBlueSize) + Math.abs(a - mAlphaSize);
  1039.                     if (LOG_EGL)
  1040.                         Log.d(TAG, "Config with distance " + distance + ", rgba=" + r + "," + g
  1041.                                 + "," + b + "," + a + ", depth=" + d + ", stencil="
  1042.                                 + s);
  1043.                     if (distance < closestDistance) {
  1044.                         if (LOG_EGL)
  1045.                             Log.d(TAG, "Best Config so far: (distance " + distance + "), rgba=" + r
  1046.                                     + "," + g + "," + b + "," + a + ", depth=" + d
  1047.                                     + ", stencil=" + s);
  1048.                         closestDistance = distance;
  1049.                         closestConfig = config;
  1050.                     }
  1051.                 }
  1052.             }
  1053.             if (ANDROID_SDK_VERSION <= 8 && closestConfig != null) {
  1054.                 // setFormat is done by SurfaceView in SDK 2.3 and newer.
  1055.                 final int format;
  1056.                 final int r = findConfigAttrib(egl, display, closestConfig, EGL10.EGL_RED_SIZE, 0);
  1057.                 final int g = findConfigAttrib(egl, display, closestConfig, EGL10.EGL_GREEN_SIZE, 0);
  1058.                 final int b = findConfigAttrib(egl, display, closestConfig, EGL10.EGL_BLUE_SIZE, 0);
  1059.                 final int a = findConfigAttrib(egl, display, closestConfig, EGL10.EGL_ALPHA_SIZE, 0);
  1060.                 if (a == 0) {
  1061.                     if (r == 8 && g == 8 && b == 8) {
  1062.                         format = PixelFormat.RGB_888;
  1063.                     } else {
  1064.                         format = PixelFormat.RGB_565;
  1065.                     }
  1066.                 } else {
  1067.                     if (r == 8 && g == 8 && b == 8) {
  1068.                         format = PixelFormat.RGBA_8888;
  1069.                     } else if (r == 5 && g == 5 && b == 5) {
  1070.                         format = PixelFormat.RGBA_5551;
  1071.                     } else {
  1072.                         format = a > 1 ? PixelFormat.TRANSLUCENT : PixelFormat.TRANSPARENT;
  1073.                     }
  1074.                 }
  1075.                 getHolder().setFormat(format);
  1076.             }
  1077.             return closestConfig;
  1078.         }
  1079.  
  1080.         private int findConfigAttrib(final EGL10 egl, final EGLDisplay display,
  1081.                 final EGLConfig config, final int attribute, final int defaultValue) {
  1082.  
  1083.             if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) {
  1084.                 return mValue[0];
  1085.             }
  1086.             return defaultValue;
  1087.         }
  1088.  
  1089.         private final int[] mValue;
  1090.         // Subclasses can adjust these values:
  1091.         protected int mRedSize;
  1092.         protected int mGreenSize;
  1093.         protected int mBlueSize;
  1094.         protected int mAlphaSize;
  1095.         protected int mDepthSize;
  1096.         protected int mStencilSize;
  1097.         protected EglConfigInfo mChosenEglConfigInfo;
  1098.     }
  1099.  
  1100.     /**
  1101.      * This class will choose a surface as close to RGB_565 as possible with or
  1102.      * without a depth buffer. If no RGB_565 surface is available it will fall
  1103.      * back on lower resolution surfaces like 555 or 4444.
  1104.      */
  1105.     public class SimpleComponentEGLConfigChooser extends ComponentSizeChooser {
  1106.         public SimpleComponentEGLConfigChooser(final int r, final int g, final int b, final int a,
  1107.                 final boolean withDepthBuffer) {
  1108.             super(4, 4, 4, a, withDepthBuffer ? 16 : 0, 0);
  1109.             /*
  1110.              * The ComponentSizeChooser.chooseConfig() will choose the config
  1111.              * closest to the values of mRedSize, mGreenSize, mBlueSize,
  1112.              * mALphaSizeAdjust on the time of creation of the surface (which is
  1113.              * later than this config instance is created). The component
  1114.              * chooser chooses amongst the set of available configs on the
  1115.              * device for which bitsizes are equal or larger than those
  1116.              * specified in the super-call. This way we'll accept a 4444 or 555
  1117.              * buffer if there's no 565 buffer available.
  1118.              */
  1119.             mRedSize = r;
  1120.             mGreenSize = g;
  1121.             mBlueSize = b;
  1122.         }
  1123.     }
  1124.  
  1125.     /**
  1126.      * An EGL helper class.
  1127.      */
  1128.  
  1129.     private class EglHelper {
  1130.         public EglHelper() {
  1131.  
  1132.         }
  1133.  
  1134.         /**
  1135.          * Initialize EGL for a given configuration spec.
  1136.          *
  1137.          * @param configSpec
  1138.          * @throws StopGlThreadException
  1139.          */
  1140.         public void start() throws StopGlThreadException {
  1141.             if (LOG_EGL) {
  1142.                 Log.w("EglHelper", "start() tid=" + Thread.currentThread().getId());
  1143.             }
  1144.             /* Get an EGL instance */
  1145.             mEgl = (EGL10) EGLContext.getEGL();
  1146.             if (mEgl == null) {
  1147.                 throwEglException("egl was null");
  1148.             }
  1149.             /* Get to the default display. */
  1150.             mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
  1151.             if (mEglDisplay == null) {
  1152.                 throwEglException("eglDisplay was null");
  1153.             }
  1154.  
  1155.             if (mEglDisplay == EGL10.EGL_NO_DISPLAY) {
  1156.                 throwEglException("eglGetDisplay failed");
  1157.             }
  1158.  
  1159.             /* We can now initialize EGL for that display */
  1160.             final int[] version = new int[2];
  1161.             if (!mEgl.eglInitialize(mEglDisplay, version)) {
  1162.                 throwEglException("eglInitialize failed");
  1163.             }
  1164.             mEglConfig = mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay);
  1165.             if (mEglConfig == null) {
  1166.                 throwEglException("eglConfig was null");
  1167.             }
  1168.  
  1169.             /*
  1170.              * Create an EGL context. We want to do this as rarely as we can,
  1171.              * because an EGL context is a somewhat heavy object.
  1172.              */
  1173.             mEglContext = mEGLContextFactory.createContext(mEgl, mEglDisplay, mEglConfig);
  1174.             if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) {
  1175.                 mEglContext = null;
  1176.                 throwEglException("createContext");
  1177.             }
  1178.             if (LOG_EGL) {
  1179.                 Log.w("EglHelper", "createContext " + mEglContext + " tid="
  1180.                         + Thread.currentThread().getId());
  1181.             }
  1182.  
  1183.             mEglSurface = null;
  1184.         }
  1185.  
  1186.         /*
  1187.          * React to the creation of a new surface by creating and returning an
  1188.          * OpenGL interface that renders to that surface.
  1189.          */
  1190.         public GL createSurface(final SurfaceHolder holder) throws StopGlThreadException {
  1191.             if (LOG_EGL) {
  1192.                 Log.w("EglHelper", "createSurface()  tid=" + Thread.currentThread().getId());
  1193.             }
  1194.             /* Check preconditions. */
  1195.             if (mEgl == null) {
  1196.                 throw new RuntimeException("egl not initialized");
  1197.             }
  1198.             if (mEglDisplay == null) {
  1199.                 throw new RuntimeException("eglDisplay not initialized");
  1200.             }
  1201.             if (mEglConfig == null) {
  1202.                 throw new RuntimeException("mEglConfig not initialized");
  1203.             }
  1204.             /* The window size has changed, so we need to create a new surface. */
  1205.             if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
  1206.  
  1207.                 /* Unbind and destroy the old EGL surface, if there is one. */
  1208.                 mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE,
  1209.                         EGL10.EGL_NO_CONTEXT);
  1210.                 mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface);
  1211.             }
  1212.  
  1213.             /* Create an EGL surface we can render into. */
  1214.             mEglSurface = mEGLWindowSurfaceFactory.createWindowSurface(mEgl, mEglDisplay,
  1215.                     mEglConfig, holder);
  1216.  
  1217.             if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) {
  1218.                 final int error = mEgl.eglGetError();
  1219.                 if (error == EGL10.EGL_BAD_NATIVE_WINDOW) {
  1220.                     reportEglException("createWindowSurface returned EGL_BAD_NATIVE_WINDOW.");
  1221.                 }
  1222.                 return null;
  1223.             }
  1224.  
  1225.             /*
  1226.              * Before we can issue GL commands, we need to make sure the context
  1227.              * is current and bound to a surface.
  1228.              */
  1229.             if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
  1230.                 throwEglException("eglMakeCurrent");
  1231.             }
  1232.  
  1233.             GL gl = mEglContext.getGL();
  1234.             if (mGLWrapper != null) {
  1235.                 gl = mGLWrapper.wrap(gl);
  1236.             }
  1237.  
  1238.             if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS)) != 0) {
  1239.                 int configFlags = 0;
  1240.                 Writer log = null;
  1241.                 if ((mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) {
  1242.                     configFlags |= GLDebugHelper.CONFIG_CHECK_GL_ERROR;
  1243.                 }
  1244.                 if ((mDebugFlags & DEBUG_LOG_GL_CALLS) != 0) {
  1245.                     log = new LogWriter();
  1246.                 }
  1247.                 gl = GLDebugHelper.wrap(gl, configFlags, log);
  1248.             }
  1249.             return gl;
  1250.         }
  1251.  
  1252.         public void purgeBuffers() {
  1253.             mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE,
  1254.                     EGL10.EGL_NO_CONTEXT);
  1255.             mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext);
  1256.         }
  1257.  
  1258.         /**
  1259.          * Display the current render surface.
  1260.          *
  1261.          * @return false if the context has been lost.
  1262.          * @throws StopGlThreadException
  1263.          */
  1264.         public boolean swap() throws StopGlThreadException {
  1265.             if (!mEgl.eglSwapBuffers(mEglDisplay, mEglSurface)) {
  1266.  
  1267.                 /*
  1268.                  * Check for EGL_CONTEXT_LOST, which means the context and all
  1269.                  * associated data were lost (For instance because the device
  1270.                  * went to sleep). We need to sleep until we get a new surface.
  1271.                  */
  1272.                 final int error = mEgl.eglGetError();
  1273.                 switch (error) {
  1274.                     case EGL11.EGL_CONTEXT_LOST:
  1275.                         return false;
  1276.                     case EGL10.EGL_BAD_NATIVE_WINDOW:
  1277.                         // The native window is bad, probably because the
  1278.                         // window manager has closed it. Ignore this error,
  1279.                         // on the expectation that the application will be
  1280.                         // closed soon.
  1281.                         Log.e("EglHelper", "eglSwapBuffers returned EGL_BAD_NATIVE_WINDOW. tid="
  1282.                                 + Thread.currentThread().getId());
  1283.                         break;
  1284.                     default:
  1285.                         throwEglException("eglSwapBuffers", error);
  1286.                 }
  1287.             }
  1288.             return true;
  1289.         }
  1290.  
  1291.         public void destroySurface() {
  1292.             if (LOG_EGL) {
  1293.                 Log.w("EglHelper", "destroySurface()  tid=" + Thread.currentThread().getId());
  1294.             }
  1295.             if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
  1296.                 mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE,
  1297.                         EGL10.EGL_NO_CONTEXT);
  1298.                 mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface);
  1299.                 mEglSurface = null;
  1300.             }
  1301.         }
  1302.  
  1303.         public void finish() {
  1304.             if (LOG_EGL) {
  1305.                 Log.w("EglHelper", "finish() tid=" + Thread.currentThread().getId());
  1306.             }
  1307.             if (mEglContext != null) {
  1308.                 mEGLContextFactory.destroyContext(mEgl, mEglDisplay, mEglContext);
  1309.                 mEglContext = null;
  1310.             }
  1311.             if (mEglDisplay != null) {
  1312.                 // Disabled hack - so we always do terminate the display, just
  1313.                 // as in original version
  1314.  
  1315.                 // Removed the teminate display call due to bugreports on
  1316.                 // cupcake and donut
  1317.                 // with exception: eglMakeCurrent failed: 12294
  1318.                 // http://forum.xda-developers.com/archive/index.php/t-644710.html
  1319.                 // That was related to Windows mobile gl crashing, so it may
  1320.                 // have nothing
  1321.                 // to do with our problem, but it solved their no 12294 bug.
  1322.                 // if (ANDROID_SDK_VERSION >= 5) {
  1323.                 // On Tattoo we must terminate the display or the app sometimes
  1324.                 // hang it appears
  1325.                 mEgl.eglTerminate(mEglDisplay);
  1326.                 // }
  1327.                 mEglDisplay = null;
  1328.             }
  1329.         }
  1330.  
  1331.         private void throwEglException(final String function) throws StopGlThreadException {
  1332.             final String errorCode = mEgl != null ? "" + mEgl.eglGetError() : "(mEgl was null)";
  1333.             final boolean handled = handleSurfaceException(context, function, errorCode);
  1334.             if (handled) {
  1335.                 throw new StopGlThreadException(function + " failed: " + errorCode);
  1336.             } else {
  1337.                 throw new RuntimeException(function + " failed: " + errorCode);
  1338.             }
  1339.         }
  1340.  
  1341.         private void reportEglException(final String errorMsg) {
  1342.             CustomExceptionHandler.reportCaughtException(new IllegalStateException(errorMsg));
  1343.             Log.e(TAG, errorMsg);
  1344.         }
  1345.  
  1346.         private void throwEglException(final String function, final int error)
  1347.                 throws StopGlThreadException {
  1348.             final String errorCode = "" + error;
  1349.             final boolean handled = handleSurfaceException(context, function, errorCode);
  1350.             if (handled) {
  1351.                 throw new StopGlThreadException(function + " failed: " + errorCode);
  1352.             } else {
  1353.                 throw new RuntimeException(function + " failed: " + errorCode);
  1354.             }
  1355.         }
  1356.  
  1357.         EGL10 mEgl;
  1358.         EGLDisplay mEglDisplay;
  1359.         EGLSurface mEglSurface;
  1360.         EGLConfig mEglConfig;
  1361.         EGLContext mEglContext;
  1362.  
  1363.     }
  1364.  
  1365.     /**
  1366.      * A generic GL Thread. Takes care of initializing EGL and GL. Delegates to
  1367.      * a Renderer instance to do the actual drawing. Can be configured to render
  1368.      * continuously or on request. All potentially blocking synchronization is
  1369.      * done through the sGLThreadManager object. This avoids multiple-lock
  1370.      * ordering issues.
  1371.      */
  1372.     private class GLThread extends Thread {
  1373.         public GLThread(final Renderer renderer) {
  1374.             super();
  1375.             mWidth = 0;
  1376.             mHeight = 0;
  1377.             mRequestRender = true;
  1378.             mRenderMode = RENDERMODE_CONTINUOUSLY;
  1379.             mRenderer = renderer;
  1380.         }
  1381.  
  1382.         @Override
  1383.         public void run() {
  1384.             setName("GLThread " + getId());
  1385.             if (LOG_THREADS)
  1386.                 Log.i(TAG, "GLThread.run(): starting tid=" + getId());
  1387.  
  1388.             try {
  1389.                 guardedRun();
  1390.             } catch (final InterruptedException e) {
  1391.                 // fall thru and exit normally
  1392.             } catch (final StopGlThreadException e) {
  1393.                 // fall thru and exit normally
  1394.             } finally {
  1395.                 sGLThreadManager.threadExiting(this);
  1396.             }
  1397.             if (LOG_THREADS)
  1398.                 Log.i(TAG, "GLThread.run(): GlThread stopped running");
  1399.         }
  1400.  
  1401.         /*
  1402.          * This private method should only be called inside a
  1403.          * synchronized(sGLThreadManager) block.
  1404.          */
  1405.         private void stopEglSurfaceLocked() {
  1406.             if (mHaveEglSurface) {
  1407.                 mHaveEglSurface = false;
  1408.                 mEglHelper.destroySurface();
  1409.             }
  1410.         }
  1411.  
  1412.         /*
  1413.          * This private method should only be called inside a
  1414.          * synchronized(sGLThreadManager) block.
  1415.          */
  1416.         private void stopEglContextLocked() {
  1417.             if (mHaveEglContext) {
  1418.                 mEglHelper.finish();
  1419.                 mHaveEglContext = false;
  1420.                 sGLThreadManager.releaseEglContextLocked(this);
  1421.             }
  1422.         }
  1423.  
  1424.         private void guardedRun() throws InterruptedException, StopGlThreadException {
  1425.             mEglHelper = new EglHelper();
  1426.             mHaveEglContext = false;
  1427.             mHaveEglSurface = false;
  1428.             try {
  1429.                 GL10 gl = null;
  1430.                 boolean createEglContext = false;
  1431.                 boolean createEglSurface = false;
  1432.                 boolean lostEglContext = false;
  1433.                 boolean sizeChanged = false;
  1434.                 boolean wantRenderNotification = false;
  1435.                 boolean doRenderNotification = false;
  1436.                 boolean askedToReleaseEglContext = false;
  1437.                 int w = 0;
  1438.                 int h = 0;
  1439.                 Runnable event = null;
  1440.  
  1441.                 while (true) {
  1442.                     LogTimer.incrementFrameCounter();
  1443.                     LogTimer.rootCheckPoint();
  1444.                     LogTimer.startTimer(Logs.glsurfaceviewOneRunLoop);
  1445.                     synchronized (sGLThreadManager) {
  1446.                         LogTimer.startTimer(Logs.glsurfaceviewsynchronized);
  1447.                         while (true) {
  1448.                             if (mShouldExit) {
  1449.                                 return;
  1450.                             }
  1451.  
  1452.                             if (!mEventQueue.isEmpty()) {
  1453.                                 event = mEventQueue.remove(0);
  1454.                                 break;
  1455.                             }
  1456.  
  1457.                             // Update the pause state.
  1458.                             if (mPaused != mRequestPaused) {
  1459.                                 mPaused = mRequestPaused;
  1460.                                 sGLThreadManager.notifyAll();
  1461.                                 if (LOG_PAUSE_RESUME) {
  1462.                                     Log.i("GLThread", "mPaused is now " + mPaused + " tid="
  1463.                                             + getId());
  1464.                                 }
  1465.                             }
  1466.  
  1467.                             // Do we need to give up the EGL context?
  1468.                             if (mShouldReleaseEglContext) {
  1469.                                 if (LOG_SURFACE) {
  1470.                                     Log.i("GLThread", "releasing EGL context because asked to tid="
  1471.                                             + getId());
  1472.                                 }
  1473.                                 stopEglSurfaceLocked();
  1474.                                 stopEglContextLocked();
  1475.                                 mShouldReleaseEglContext = false;
  1476.                                 askedToReleaseEglContext = true;
  1477.                             }
  1478.  
  1479.                             // Have we lost the EGL context?
  1480.                             if (lostEglContext) {
  1481.                                 stopEglSurfaceLocked();
  1482.                                 stopEglContextLocked();
  1483.                                 lostEglContext = false;
  1484.                             }
  1485.  
  1486.                             // Do we need to release the EGL surface?
  1487.                             if (mHaveEglSurface && mPaused) {
  1488.                                 if (LOG_SURFACE)
  1489.                                     Log.i(TAG, "releasing EGL surface because paused tid="
  1490.                                             + getId());
  1491.                                 if (LOG_SURFACE) {
  1492.                                     Log.i("GLThread", "releasing EGL surface because paused tid="
  1493.                                             + getId());
  1494.                                 }
  1495.                                 stopEglSurfaceLocked();
  1496.                                 if (!mPreserveEGLContextOnPause
  1497.                                         || sGLThreadManager.shouldReleaseEGLContextWhenPausing()) {
  1498.                                     stopEglContextLocked();
  1499.                                     if (LOG_SURFACE) {
  1500.                                         Log.i("GLThread",
  1501.                                                 "releasing EGL context because paused tid="
  1502.                                                         + getId()
  1503.                                                         + ", device supports preserve: "
  1504.                                                         + !sGLThreadManager
  1505.                                                                 .shouldReleaseEGLContextWhenPausing());
  1506.                                     }
  1507.                                 }
  1508.                                 if (sGLThreadManager.shouldTerminateEGLWhenPausing()) {
  1509.                                     mEglHelper.finish();
  1510.                                     if (LOG_SURFACE) {
  1511.                                         Log.i("GLThread", "terminating EGL because paused tid="
  1512.                                                 + getId());
  1513.                                     }
  1514.                                 }
  1515.                             }
  1516.  
  1517.                             // Have we lost the surface view surface?
  1518.                             if (!mHasSurface && !mWaitingForSurface) {
  1519.                                 if (LOG_SURFACE)
  1520.                                     Log.i(TAG,
  1521.                                             "GLThread.guardedRun(): noticed surfaceView surface lost tid="
  1522.                                                     + getId());
  1523.                                 if (mHaveEglSurface) {
  1524.                                     stopEglSurfaceLocked();
  1525.                                 }
  1526.                                 mWaitingForSurface = true;
  1527.                                 sGLThreadManager.notifyAll();
  1528.                             }
  1529.  
  1530.                             // Have we acquired the surface view surface?
  1531.                             if (mHasSurface && mWaitingForSurface) {
  1532.                                 if (LOG_SURFACE)
  1533.                                     Log.i(TAG,
  1534.                                             "GLThread.guardedRun(): noticed surfaceView surface acquired tid="
  1535.                                                     + getId());
  1536.                                 mWaitingForSurface = false;
  1537.                                 sGLThreadManager.notifyAll();
  1538.                             }
  1539.  
  1540.                             if (doRenderNotification) {
  1541.                                 if (LOG_SURFACE) {
  1542.                                     Log.i("GLThread", "sending render notification tid=" + getId());
  1543.                                 }
  1544.                                 wantRenderNotification = false;
  1545.                                 doRenderNotification = false;
  1546.                                 mRenderComplete = true;
  1547.                                 sGLThreadManager.notifyAll();
  1548.                             }
  1549.  
  1550.                             // Ready to draw?
  1551.                             if (readyToDraw()) {
  1552.  
  1553.                                 // If we don't have an EGL context, try to
  1554.                                 // acquire one.
  1555.                                 if (!mHaveEglContext) {
  1556.                                     if (askedToReleaseEglContext) {
  1557.                                         askedToReleaseEglContext = false;
  1558.                                     } else if (sGLThreadManager.tryAcquireEglContextLocked(this)) {
  1559.                                         try {
  1560.                                             mEglHelper.start();
  1561.                                         } catch (final RuntimeException t) {
  1562.                                             sGLThreadManager.releaseEglContextLocked(this);
  1563.                                             throw t;
  1564.                                         }
  1565.                                         mHaveEglContext = true;
  1566.                                         createEglContext = true;
  1567.  
  1568.                                         sGLThreadManager.notifyAll();
  1569.                                         if (LOG_SURFACE) {
  1570.                                             Log.w("GLThread", "egl create context");
  1571.                                         }
  1572.                                     }
  1573.                                 }
  1574.  
  1575.                                 if (mHaveEglContext && !mHaveEglSurface) {
  1576.                                     mHaveEglSurface = true;
  1577.                                     createEglSurface = true;
  1578.                                     sizeChanged = true;
  1579.                                 }
  1580.  
  1581.                                 if (mHaveEglSurface) {
  1582.                                     if (mSizeChanged) {
  1583.                                         sizeChanged = true;
  1584.                                         w = mWidth;
  1585.                                         h = mHeight;
  1586.                                         wantRenderNotification = true;
  1587.                                         if (LOG_SURFACE) {
  1588.                                             Log.i("GLThread",
  1589.                                                     "noticing that we want render notification tid="
  1590.                                                             + getId());
  1591.                                         }
  1592.  
  1593.                                         if (DRAW_TWICE_AFTER_SIZE_CHANGED) {
  1594.                                             // We keep mRequestRender true so
  1595.                                             // that we draw twice after the size
  1596.                                             // changes.
  1597.                                             // (Once because of mSizeChanged,
  1598.                                             // the second time because of
  1599.                                             // mRequestRender.)
  1600.                                             // This forces the updated graphics
  1601.                                             // onto the screen.
  1602.                                         } else {
  1603.                                             mRequestRender = false;
  1604.                                         }
  1605.                                         mSizeChanged = false;
  1606.                                     } else {
  1607.                                         mRequestRender = false;
  1608.                                     }
  1609.                                     sGLThreadManager.notifyAll();
  1610.                                     break;
  1611.                                 }
  1612.                             }
  1613.  
  1614.                             // By design, this is the only place in a GLThread
  1615.                             // thread where we wait().
  1616.                             if (LOG_THREADS)
  1617.                                 Log.i(TAG, "GLThread.guardedRun(): waiting tid=" + getId()
  1618.                                         + ", rendermode continuous="
  1619.                                         + (mRenderMode == RENDERMODE_CONTINUOUSLY));
  1620.                             LogTimer.startTimer(Logs.glsurfaceviewsynchronizedWait);
  1621.                             sGLThreadManager.wait();
  1622.                             LogTimer.stopTimer(Logs.glsurfaceviewsynchronizedWait);
  1623.                         }
  1624.                         LogTimer.stopTimer(Logs.glsurfaceviewsynchronized);
  1625.                     } // end of synchronized(sGLThreadManager)
  1626.  
  1627.                     if (event != null) {
  1628.                         event.run();
  1629.                         event = null;
  1630.                         continue;
  1631.                     }
  1632.  
  1633.                     /*
  1634.                      * The mHasFocus is applied on two levels. It is used it
  1635.                      * readyToDraw to avoid continuous draws if mHasFocus=false,
  1636.                      * but to allow one draw even without focus (to get stuff
  1637.                      * drawn behind dialogs for instance, and perhaps also on
  1638.                      * resume). The mHasFocus is also applied here for small SDK
  1639.                      * versions to avoid or reduce incorrect portrait mode
  1640.                      * clipping. On G1 clipping will become wrong after screen
  1641.                      * has been off if we ommit this mHasFocus check, and on G1
  1642.                      * the problem will remain until user has gone to home
  1643.                      * screen and back (thus destroying and recreating the
  1644.                      * context and surface)
  1645.                      */
  1646.                     if (mHasFocus || ANDROID_SDK_VERSION >= 5) {
  1647.                         if (createEglSurface) {
  1648.                             if (LOG_SURFACE) {
  1649.                                 Log.w("GLThread", "GLThread.guardedRun(): egl createSurface");
  1650.                             }
  1651.                             gl = (GL10) mEglHelper.createSurface(getHolder());
  1652.                             if (gl == null) {
  1653.                                 // Couldn't create a surface. Quit quietly.
  1654.                                 break;
  1655.                             }
  1656.                             sGLThreadManager.checkGLDriver(gl);
  1657.                             createEglSurface = false;
  1658.                             // Here the previous GLSurfaceView always called
  1659.                             // mRenderer.onSurfaceCreated
  1660.                         }
  1661.  
  1662.                         if (createEglContext) {
  1663.                             if (LOG_RENDERER) {
  1664.                                 Log.w("GLThread", "GLThread.guardedRun(): onSurfaceCreated");
  1665.                             }
  1666.                             mRenderer.onSurfaceCreated(gl, new EglConfigInfo(mEglHelper));
  1667.                             createEglContext = false;
  1668.                         }
  1669.                         if (sizeChanged) {
  1670.                             if (LOG_RENDERER) {
  1671.                                 Log.w("GLThread", "GLThread.guardedRun(): onSurfaceChanged(" + w
  1672.                                         + ", " + h + ")");
  1673.                             }
  1674.                             mEglHelper.purgeBuffers();
  1675.                             mRenderer.onSurfaceChanged(gl, w, h);
  1676.                             sizeChanged = false;
  1677.                         }
  1678.                         if (LOG_RENDERER_DRAW_FRAME) {
  1679.                             Log.w(TAG, "GLThread.guardedRun(): onDrawFrame tid=" + getId());
  1680.                         }
  1681.                         mRenderer.onDrawFrame(gl);
  1682.                         long time;
  1683.                         if (LOG_SWAP_TIME)
  1684.                             time = System.nanoTime();
  1685.                         if (!mEglHelper.swap()) {
  1686.                             if (LOG_SURFACE)
  1687.                                 Log.i(TAG, "egl surface lost tid=" + getId());
  1688.                             lostEglContext = true;
  1689.                         }
  1690.                         if (LOG_SWAP_TIME)
  1691.                             mRenderer.logLastSwapDuration(time, System.nanoTime());
  1692.                     }
  1693.                     if (wantRenderNotification) {
  1694.                         doRenderNotification = true;
  1695.                     }
  1696.                     LogTimer.stopTimer(Logs.glsurfaceviewOneRunLoop);
  1697.                 }
  1698.             } finally {
  1699.                 mRenderer.onExit();
  1700.                 /* clean-up everything... */
  1701.                 synchronized (sGLThreadManager) {
  1702.                     stopEglSurfaceLocked();
  1703.                     stopEglContextLocked();
  1704.                 }
  1705.             }
  1706.         }
  1707.  
  1708.         public boolean ableToDraw() {
  1709.             return mHaveEglContext && mHaveEglSurface && readyToDraw();
  1710.         }
  1711.  
  1712.         private boolean readyToDraw() {
  1713.             // Added mHasFocus to fix Android < 5 G1 Clipping problem, see
  1714.             // comments around if-block at line 1575.
  1715.             return !mPaused
  1716.                     && mHasSurface
  1717.                     && mWidth > 0
  1718.                     && mHeight > 0
  1719.                     && (mRequestRender || mRenderMode == RENDERMODE_CONTINUOUSLY
  1720.                             && (mHasFocus || ANDROID_SDK_VERSION >= 5));
  1721.         }
  1722.  
  1723.         public void setRenderMode(final int renderMode) {
  1724.             if (!(RENDERMODE_WHEN_DIRTY <= renderMode && renderMode <= RENDERMODE_CONTINUOUSLY)) {
  1725.                 throw new IllegalArgumentException("renderMode");
  1726.             }
  1727.             synchronized (sGLThreadManager) {
  1728.                 mRenderMode = renderMode;
  1729.                 sGLThreadManager.notifyAll();
  1730.             }
  1731.         }
  1732.  
  1733.         public int getRenderMode() {
  1734.             synchronized (sGLThreadManager) {
  1735.                 return mRenderMode;
  1736.             }
  1737.         }
  1738.  
  1739.         public void requestRender() {
  1740.             synchronized (sGLThreadManager) {
  1741.                 mRequestRender = true;
  1742.                 sGLThreadManager.notifyAll();
  1743.             }
  1744.         }
  1745.  
  1746.         public void surfaceCreated() {
  1747.             synchronized (sGLThreadManager) {
  1748.                 if (LOG_THREADS) {
  1749.                     Log.i(TAG, "GLThread.surfaceCreated() tid=" + getId());
  1750.                 }
  1751.                 mHasSurface = true;
  1752.                 sGLThreadManager.notifyAll();
  1753.                 while (mWaitingForSurface && !mExited) {
  1754.                     try {
  1755.                         sGLThreadManager.wait();
  1756.                     } catch (final InterruptedException e) {
  1757.                         Thread.currentThread().interrupt();
  1758.                     }
  1759.                 }
  1760.             }
  1761.         }
  1762.  
  1763.         public void surfaceDestroyed() {
  1764.             synchronized (sGLThreadManager) {
  1765.                 if (LOG_THREADS) {
  1766.                     Log.i(TAG, "GLThread.surfaceDestroyed() tid=" + getId());
  1767.                 }
  1768.                 mHasSurface = false;
  1769.                 sGLThreadManager.notifyAll();
  1770.                 while (!mWaitingForSurface && !mExited) {
  1771.                     try {
  1772.                         sGLThreadManager.wait();
  1773.                     } catch (final InterruptedException e) {
  1774.                         Thread.currentThread().interrupt();
  1775.                     }
  1776.                 }
  1777.             }
  1778.         }
  1779.  
  1780.         public void onPause() {
  1781.             synchronized (sGLThreadManager) {
  1782.                 if (LOG_PAUSE_RESUME) {
  1783.                     Log.i("GLThread", "onPause tid=" + getId());
  1784.                 }
  1785.                 mRequestPaused = true;
  1786.                 sGLThreadManager.notifyAll();
  1787.                 while (!mExited && !mPaused) {
  1788.                     if (LOG_PAUSE_RESUME) {
  1789.                         Log.i("Main thread", "onPause waiting for mPaused.");
  1790.                     }
  1791.                     try {
  1792.                         sGLThreadManager.wait();
  1793.                     } catch (final InterruptedException ex) {
  1794.                         Thread.currentThread().interrupt();
  1795.                     }
  1796.                 }
  1797.             }
  1798.         }
  1799.  
  1800.         public void onResume() {
  1801.             synchronized (sGLThreadManager) {
  1802.                 if (LOG_PAUSE_RESUME) {
  1803.                     Log.i("GLThread", "onResume tid=" + getId());
  1804.                 }
  1805.                 mRequestPaused = false;
  1806.                 mRequestRender = true;
  1807.                 mRenderComplete = false;
  1808.                 sGLThreadManager.notifyAll();
  1809.                 while (!mExited && mPaused && !mRenderComplete) {
  1810.                     if (LOG_PAUSE_RESUME) {
  1811.                         Log.i("Main thread", "onResume waiting for !mPaused.");
  1812.                     }
  1813.                     try {
  1814.                         sGLThreadManager.wait();
  1815.                     } catch (final InterruptedException ex) {
  1816.                         Thread.currentThread().interrupt();
  1817.                     }
  1818.                 }
  1819.             }
  1820.         }
  1821.  
  1822.         public void onWindowResize(final int w, final int h) {
  1823.             synchronized (sGLThreadManager) {
  1824.                 mWidth = w;
  1825.                 mHeight = h;
  1826.                 mSizeChanged = true;
  1827.                 mRequestRender = true;
  1828.                 mRenderComplete = false;
  1829.                 sGLThreadManager.notifyAll();
  1830.  
  1831.                 // Wait for thread to react to resize and render a frame
  1832.                 while (!mExited && !mPaused && !mRenderComplete && mGLThread != null
  1833.                         && mGLThread.ableToDraw()) {
  1834.                     if (LOG_SURFACE) {
  1835.                         Log.i("GlSurface Main thread", "GLThread.onWindowResize(" + w + "," + h
  1836.                                 + ") waiting for render complete.");
  1837.                     }
  1838.                     try {
  1839.                         sGLThreadManager.wait();
  1840.                     } catch (final InterruptedException ex) {
  1841.                         Thread.currentThread().interrupt();
  1842.                     }
  1843.                 }
  1844.             }
  1845.         }
  1846.  
  1847.         // On some Qualcomm devices (such as the HTC Magic running Android 1.6),
  1848.         // there's a bug in the graphics driver that will cause glViewport() to
  1849.         // do the wrong thing in a very specific situation. When the screen is
  1850.         // rotated, if a surface is created in one layout (say, portrait view)
  1851.         // and then rotated to another, subsequent calls to glViewport are
  1852.         // clipped.
  1853.         // So, if the window is, say, 320x480 when the surface is created, and
  1854.         // then the rotation occurs and glViewport() is called with the new
  1855.         // size of 480x320, devices with the buggy driver will clip the viewport
  1856.         // to the old width (which means 320x320...ugh!). This is fixed in
  1857.         // Android 2.1 Qualcomm devices (like Nexus One) and doesn't affect
  1858.         // non-Qualcomm devices (like the Motorola DROID).
  1859.         //
  1860.         // Unfortunately, under Android 1.6 this exact case occurs when the
  1861.         // screen is put to sleep and then wakes up again. The lock screen
  1862.         // comes up in portrait mode, but at the same time the window surface
  1863.         // is also created in the backgrounded game. When the lock screen is
  1864.         // closed
  1865.         // and the game comes forward, the window is fixed to the correct size
  1866.         // which causes the bug to occur.
  1867.  
  1868.         // The solution used here is to simply never render when the window
  1869.         // surface
  1870.         // does not have the focus. When the lock screen (or menu) is up,
  1871.         // rendering
  1872.         // will stop. This resolves the driver bug (as the egl surface won't be
  1873.         // created
  1874.         // until after the screen size has been fixed), and is generally good
  1875.         // practice
  1876.         // since you don't want to be doing a lot of CPU intensive work when the
  1877.         // lock
  1878.         // screen is up (to preserve battery life).
  1879.  
  1880.         // Added to fix Android < 5 G1 Clipping problem, see comments around
  1881.         // if-block at line 1575.
  1882.         public void onWindowFocusChanged(final boolean hasFocus) {
  1883.             synchronized (sGLThreadManager) {
  1884.                 mHasFocus = hasFocus;
  1885.                 // Request a render here, because mHasFocus=false now overrides
  1886.                 // continous mode drawing
  1887.                 mRequestRender = true;
  1888.                 sGLThreadManager.notifyAll();
  1889.             }
  1890.             if (LOG_SURFACE) {
  1891.                 Log.i(TAG, "GLThread.onWindowFocusChanged(): Focus "
  1892.                         + (mHasFocus ? "gained" : "lost"));
  1893.             }
  1894.  
  1895.         }
  1896.  
  1897.         public void requestExitAndWait() {
  1898.             // don't call this from GLThread thread or it is a guaranteed
  1899.             // deadlock!
  1900.             synchronized (sGLThreadManager) {
  1901.                 mShouldExit = true;
  1902.                 sGLThreadManager.notifyAll();
  1903.                 while (!mExited) {
  1904.                     try {
  1905.                         sGLThreadManager.wait();
  1906.                     } catch (final InterruptedException ex) {
  1907.                         Thread.currentThread().interrupt();
  1908.                     }
  1909.                 }
  1910.             }
  1911.         }
  1912.  
  1913.         public void waitForExit() {
  1914.             // don't call this from GLThread thread or it is a guaranteed
  1915.             // deadlock!
  1916.             synchronized (sGLThreadManager) {
  1917.                 while (!mExited) {
  1918.                     try {
  1919.                         sGLThreadManager.wait();
  1920.                     } catch (final InterruptedException ex) {
  1921.                         Thread.currentThread().interrupt();
  1922.                     }
  1923.                 }
  1924.             }
  1925.         }
  1926.  
  1927.         public void requestReleaseEglContextLocked() {
  1928.             mShouldReleaseEglContext = true;
  1929.             sGLThreadManager.notifyAll();
  1930.         }
  1931.  
  1932.         /**
  1933.          * Queue an "event" to be run on the GL rendering thread.
  1934.          *
  1935.          * @param r the runnable to be run on the GL rendering thread.
  1936.          */
  1937.         public void queueEvent(final Runnable r) {
  1938.             if (r == null) {
  1939.                 throw new IllegalArgumentException("r must not be null");
  1940.             }
  1941.             synchronized (sGLThreadManager) {
  1942.                 mEventQueue.add(r);
  1943.                 sGLThreadManager.notifyAll();
  1944.             }
  1945.         }
  1946.  
  1947.         // Once the thread is started, all accesses to the following member
  1948.         // variables are protected by the sGLThreadManager monitor
  1949.         private boolean mShouldExit;
  1950.         private boolean mExited;
  1951.         private boolean mRequestPaused;
  1952.         private boolean mPaused;
  1953.         private boolean mHasSurface;
  1954.         private boolean mWaitingForSurface;
  1955.         private boolean mHaveEglContext;
  1956.         private boolean mHaveEglSurface;
  1957.         private boolean mShouldReleaseEglContext;
  1958.         private int mWidth;
  1959.         private int mHeight;
  1960.         private int mRenderMode;
  1961.         private boolean mRequestRender;
  1962.         private boolean mRenderComplete;
  1963.         private final ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>();
  1964.         private boolean mHasFocus;
  1965.  
  1966.         // End of member variables protected by the sGLThreadManager monitor.
  1967.  
  1968.         private final Renderer mRenderer;
  1969.         private EglHelper mEglHelper;
  1970.     }
  1971.  
  1972.     static class LogWriter extends Writer {
  1973.  
  1974.         @Override
  1975.         public void close() {
  1976.             flushBuilder();
  1977.         }
  1978.  
  1979.         @Override
  1980.         public void flush() {
  1981.             flushBuilder();
  1982.         }
  1983.  
  1984.         @Override
  1985.         public void write(final char[] buf, final int offset, final int count) {
  1986.             for (int i = 0; i < count; i++) {
  1987.                 final char c = buf[offset + i];
  1988.                 if (c == '\n') {
  1989.                     flushBuilder();
  1990.                 } else {
  1991.                     mBuilder.append(c);
  1992.                 }
  1993.             }
  1994.         }
  1995.  
  1996.         private void flushBuilder() {
  1997.             if (mBuilder.length() > 0) {
  1998.                 Log.v(TAG, mBuilder.toString());
  1999.                 mBuilder.delete(0, mBuilder.length());
  2000.             }
  2001.         }
  2002.  
  2003.         private final StringBuilder mBuilder = new StringBuilder();
  2004.     }
  2005.  
  2006.     private void checkRenderThreadState() {
  2007.         if (mGLThread != null) {
  2008.             throw new IllegalStateException(
  2009.                     "setRenderer has already been called for this instance.");
  2010.         }
  2011.     }
  2012.  
  2013.     private static class GLThreadManager {
  2014.  
  2015.         public synchronized void threadExiting(final GLThread thread) {
  2016.             if (LOG_THREADS) {
  2017.                 Log.i(TAG, "GLThreadManager: exiting tid=" + thread.getId());
  2018.             }
  2019.             thread.mExited = true;
  2020.             if (mEglOwner == thread) {
  2021.                 mEglOwner = null;
  2022.             }
  2023.             notifyAll();
  2024.         }
  2025.  
  2026.         /*
  2027.          * Tries once to acquire the right to use an EGL context. Does not
  2028.          * block. Requires that we are already in the sGLThreadManager monitor
  2029.          * when this is called.
  2030.          * @return true if the right to use an EGL context was acquired.
  2031.          */
  2032.         public boolean tryAcquireEglContextLocked(final GLThread thread) {
  2033.             if (mEglOwner == thread || mEglOwner == null) {
  2034.                 mEglOwner = thread;
  2035.                 notifyAll();
  2036.                 return true;
  2037.             }
  2038.             checkGLESVersion();
  2039.             if (mMultipleGLESContextsAllowed) {
  2040.                 return true;
  2041.             }
  2042.             // Notify the owning thread that it should release the context.
  2043.             // TODO: implement a fairness policy. Currently
  2044.             // if the owning thread is drawing continuously it will just
  2045.             // reacquire the EGL context.
  2046.             if (mEglOwner != null) {
  2047.                 mEglOwner.requestReleaseEglContextLocked();
  2048.             }
  2049.             return false;
  2050.         }
  2051.  
  2052.         /*
  2053.          * Releases the EGL context. Requires that we are already in the
  2054.          * sGLThreadManager monitor when this is called.
  2055.          */
  2056.         public void releaseEglContextLocked(final GLThread thread) {
  2057.             if (mEglOwner == thread) {
  2058.                 mEglOwner = null;
  2059.             }
  2060.             notifyAll();
  2061.         }
  2062.  
  2063.         public synchronized boolean shouldReleaseEGLContextWhenPausing() {
  2064.             // Release the EGL context when pausing even if
  2065.             // the hardware supports multiple EGL contexts.
  2066.             // Otherwise the device could run out of EGL contexts.
  2067.             return mLimitedGLESContexts;
  2068.         }
  2069.  
  2070.         public synchronized boolean shouldTerminateEGLWhenPausing() {
  2071.             checkGLESVersion();
  2072.             return !mMultipleGLESContextsAllowed;
  2073.         }
  2074.  
  2075.         public synchronized void checkGLDriver(final GL10 gl) {
  2076.             if (!mGLESDriverCheckComplete) {
  2077.                 checkGLESVersion();
  2078.                 final String renderer = gl.glGetString(GL10.GL_RENDERER);
  2079.                 if (mGLESVersion < kGLES_20) {
  2080.                     mMultipleGLESContextsAllowed = !renderer.startsWith(kMSM7K_RENDERER_PREFIX);
  2081.                     notifyAll();
  2082.                 }
  2083.                 // Regarding adreno limited contexts:
  2084.                 // https://developer.qualcomm.com/forum/qdevnet-forums/mobile-gaming-graphics-optimization-adreno/12173
  2085.                 mLimitedGLESContexts = !mMultipleGLESContextsAllowed
  2086.                         || renderer.startsWith(kADRENO);
  2087.                 if (LOG_SURFACE) {
  2088.                     Log.w(TAG, "checkGLDriver renderer = \"" + renderer
  2089.                             + "\" multipleContextsAllowed = " + mMultipleGLESContextsAllowed
  2090.                             + " mLimitedGLESContexts = " + mLimitedGLESContexts);
  2091.                 }
  2092.                 mGLESDriverCheckComplete = true;
  2093.             }
  2094.         }
  2095.  
  2096.         private void checkGLESVersion() {
  2097.             if (!mGLESVersionCheckComplete) {
  2098.                 if (ANDROID_SDK_VERSION >= 4) {
  2099.                     try {
  2100.                         mGLESVersion = ConfigurationInfo.class.getField("GL_ES_VERSION_UNDEFINED")
  2101.                                 .getInt(null);
  2102.                     } catch (final Exception e) {
  2103.                         if (LogUtil.DO_ERROR_LOGGING)
  2104.                             Log.e(TAG, "extracting GL_ES_VERSION_UNDEFINED failed", e);
  2105.                         mGLESVersion = 0; // The constant is zero
  2106.                     }
  2107.                     if (mGLESVersion >= kGLES_20) {
  2108.                         mMultipleGLESContextsAllowed = true;
  2109.                     }
  2110.                 } else {
  2111.                     mGLESVersion = 0;
  2112.                 }
  2113.                 if (LOG_SURFACE) {
  2114.                     Log.w(TAG, "checkGLESVersion mGLESVersion =" + " " + mGLESVersion
  2115.                             + " mMultipleGLESContextsAllowed = "
  2116.                             + mMultipleGLESContextsAllowed);
  2117.                 }
  2118.                 mGLESVersionCheckComplete = true;
  2119.             }
  2120.         }
  2121.  
  2122.         private boolean mGLESVersionCheckComplete;
  2123.         private int mGLESVersion;
  2124.         private boolean mGLESDriverCheckComplete;
  2125.         private boolean mMultipleGLESContextsAllowed;
  2126.         private boolean mLimitedGLESContexts;
  2127.         private static final int kGLES_20 = 0x20000;
  2128.         private static final String kMSM7K_RENDERER_PREFIX = "Q3Dimension MSM7500 ";
  2129.         private static final String kADRENO = "Adreno";
  2130.         private GLThread mEglOwner;
  2131.     }
  2132.  
  2133.     public boolean handleSurfaceException(final Context context, final String function,
  2134.             final String errorCode) {
  2135.         return false;
  2136.     }
  2137.  
  2138.     public static class StopGlThreadException extends Exception {
  2139.         private static final long serialVersionUID = 1L;
  2140.  
  2141.         public StopGlThreadException(final String detailMessage) {
  2142.             super(detailMessage);
  2143.         }
  2144.     }
  2145.  
  2146.     public class EglConfigInfo {
  2147.         public final int mRedSize;
  2148.         public final int mGreenSize;
  2149.         public final int mBlueSize;
  2150.         public final int mAlphaSize;
  2151.         public final int mDepthSize;
  2152.         public final int mStencilSize;
  2153.  
  2154.         private int findConfigAttrib(final EGL10 egl, final EGLDisplay display,
  2155.                 final EGLConfig config, final int attribute, final int defaultValue) {
  2156.             final int[] value = new int[1];
  2157.             if (egl.eglGetConfigAttrib(display, config, attribute, value)) {
  2158.                 return value[0];
  2159.             }
  2160.             return defaultValue;
  2161.         }
  2162.  
  2163.         private EglConfigInfo(final EglHelper eglHelper) {
  2164.             this(eglHelper.mEgl, eglHelper.mEglDisplay, eglHelper.mEglConfig);
  2165.         }
  2166.  
  2167.         private EglConfigInfo(final EGL10 egl, final EGLDisplay display, final EGLConfig config) {
  2168.             final int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0);
  2169.             final int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0);
  2170.             final int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0);
  2171.             final int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0);
  2172.             final int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0);
  2173.             final int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0);
  2174.  
  2175.             this.mRedSize = r;
  2176.             this.mGreenSize = g;
  2177.             this.mBlueSize = b;
  2178.             this.mAlphaSize = a;
  2179.             this.mDepthSize = d;
  2180.             this.mStencilSize = s;
  2181.         }
  2182.  
  2183.         public boolean isRgb888() {
  2184.             return mRedSize == 8 && mGreenSize == 8 && mBlueSize == 8;
  2185.         }
  2186.  
  2187.         public boolean isRgb565() {
  2188.             return mRedSize == 5 && mGreenSize == 6 && mBlueSize == 5;
  2189.         }
  2190.  
  2191.         public boolean isAlpha8() {
  2192.             return mAlphaSize == 8;
  2193.         }
  2194.  
  2195.         public boolean isAlpha0() {
  2196.             return mAlphaSize == 0;
  2197.         }
  2198.  
  2199.         @Override
  2200.         public String toString() {
  2201.             return "RGBADS=" + mRedSize + mGreenSize + mBlueSize + mAlphaSize + mDepthSize
  2202.                     + mStencilSize;
  2203.         }
  2204.     }
  2205.  
  2206.     private static final GLThreadManager sGLThreadManager = new GLThreadManager();
  2207.     private boolean mSizeChanged = true;
  2208.  
  2209.     private GLThread mGLThread;
  2210.     private Renderer mRenderer;
  2211.     private boolean mDetached;
  2212.     private EGLConfigChooser mEGLConfigChooser;
  2213.     private EGLContextFactory mEGLContextFactory;
  2214.     private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory;
  2215.     private GLWrapper mGLWrapper;
  2216.     private int mDebugFlags;
  2217.     private int mEGLContextClientVersion;
  2218.     private boolean mPreserveEGLContextOnPause;
  2219. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top