HardwareRenderer.java revision 41ee465734d0006797a8fd36e88976c1e85d161c
1/* 2 * Copyright (C) 2010 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 17 18package android.view; 19 20import android.content.ComponentCallbacks2; 21import android.graphics.Paint; 22import android.graphics.Rect; 23import android.graphics.SurfaceTexture; 24import android.opengl.GLUtils; 25import android.opengl.ManagedEGLContext; 26import android.os.Handler; 27import android.os.Looper; 28import android.os.SystemClock; 29import android.os.SystemProperties; 30import android.util.Log; 31import com.google.android.gles_jni.EGLImpl; 32 33import javax.microedition.khronos.egl.EGL10; 34import javax.microedition.khronos.egl.EGL11; 35import javax.microedition.khronos.egl.EGLConfig; 36import javax.microedition.khronos.egl.EGLContext; 37import javax.microedition.khronos.egl.EGLDisplay; 38import javax.microedition.khronos.egl.EGLSurface; 39import javax.microedition.khronos.opengles.GL; 40 41import java.io.File; 42import java.io.PrintWriter; 43 44import static javax.microedition.khronos.egl.EGL10.*; 45 46/** 47 * Interface for rendering a ViewAncestor using hardware acceleration. 48 * 49 * @hide 50 */ 51public abstract class HardwareRenderer { 52 static final String LOG_TAG = "HardwareRenderer"; 53 54 /** 55 * Name of the file that holds the shaders cache. 56 */ 57 private static final String CACHE_PATH_SHADERS = "com.android.opengl.shaders_cache"; 58 59 /** 60 * Turn on to only refresh the parts of the screen that need updating. 61 * When turned on the property defined by {@link #RENDER_DIRTY_REGIONS_PROPERTY} 62 * must also have the value "true". 63 */ 64 public static final boolean RENDER_DIRTY_REGIONS = true; 65 66 /** 67 * System property used to enable or disable dirty regions invalidation. 68 * This property is only queried if {@link #RENDER_DIRTY_REGIONS} is true. 69 * The default value of this property is assumed to be true. 70 * 71 * Possible values: 72 * "true", to enable partial invalidates 73 * "false", to disable partial invalidates 74 */ 75 static final String RENDER_DIRTY_REGIONS_PROPERTY = "debug.hwui.render_dirty_regions"; 76 77 /** 78 * System property used to enable or disable vsync. 79 * The default value of this property is assumed to be false. 80 * 81 * Possible values: 82 * "true", to disable vsync 83 * "false", to enable vsync 84 */ 85 static final String DISABLE_VSYNC_PROPERTY = "debug.hwui.disable_vsync"; 86 87 /** 88 * System property used to enable or disable hardware rendering profiling. 89 * The default value of this property is assumed to be false. 90 * 91 * When profiling is enabled, the adb shell dumpsys gfxinfo command will 92 * output extra information about the time taken to execute by the last 93 * frames. 94 * 95 * Possible values: 96 * "true", to enable profiling 97 * "false", to disable profiling 98 * 99 * @hide 100 */ 101 public static final String PROFILE_PROPERTY = "debug.hwui.profile"; 102 103 /** 104 * System property used to specify the number of frames to be used 105 * when doing hardware rendering profiling. 106 * The default value of this property is #PROFILE_MAX_FRAMES. 107 * 108 * When profiling is enabled, the adb shell dumpsys gfxinfo command will 109 * output extra information about the time taken to execute by the last 110 * frames. 111 * 112 * Possible values: 113 * "60", to set the limit of frames to 60 114 */ 115 static final String PROFILE_MAXFRAMES_PROPERTY = "debug.hwui.profile.maxframes"; 116 117 /** 118 * System property used to debug EGL configuration choice. 119 * 120 * Possible values: 121 * "choice", print the chosen configuration only 122 * "all", print all possible configurations 123 */ 124 static final String PRINT_CONFIG_PROPERTY = "debug.hwui.print_config"; 125 126 /** 127 * Turn on to draw dirty regions every other frame. 128 * 129 * Possible values: 130 * "true", to enable dirty regions debugging 131 * "false", to disable dirty regions debugging 132 * 133 * @hide 134 */ 135 public static final String DEBUG_DIRTY_REGIONS_PROPERTY = "debug.hwui.show_dirty_regions"; 136 137 /** 138 * A process can set this flag to false to prevent the use of hardware 139 * rendering. 140 * 141 * @hide 142 */ 143 public static boolean sRendererDisabled = false; 144 145 /** 146 * Further hardware renderer disabling for the system process. 147 * 148 * @hide 149 */ 150 public static boolean sSystemRendererDisabled = false; 151 152 /** 153 * Number of frames to profile. 154 */ 155 private static final int PROFILE_MAX_FRAMES = 128; 156 157 /** 158 * Number of floats per profiled frame. 159 */ 160 private static final int PROFILE_FRAME_DATA_COUNT = 3; 161 162 private boolean mEnabled; 163 private boolean mRequested = true; 164 165 /** 166 * Invoke this method to disable hardware rendering in the current process. 167 * 168 * @hide 169 */ 170 public static void disable(boolean system) { 171 sRendererDisabled = true; 172 if (system) { 173 sSystemRendererDisabled = true; 174 } 175 } 176 177 /** 178 * Indicates whether hardware acceleration is available under any form for 179 * the view hierarchy. 180 * 181 * @return True if the view hierarchy can potentially be hardware accelerated, 182 * false otherwise 183 */ 184 public static boolean isAvailable() { 185 return GLES20Canvas.isAvailable(); 186 } 187 188 /** 189 * Destroys the hardware rendering context. 190 * 191 * @param full If true, destroys all associated resources. 192 */ 193 abstract void destroy(boolean full); 194 195 /** 196 * Initializes the hardware renderer for the specified surface. 197 * 198 * @param holder The holder for the surface to hardware accelerate. 199 * 200 * @return True if the initialization was successful, false otherwise. 201 */ 202 abstract boolean initialize(SurfaceHolder holder) throws Surface.OutOfResourcesException; 203 204 /** 205 * Updates the hardware renderer for the specified surface. 206 * 207 * @param holder The holder for the surface to hardware accelerate 208 */ 209 abstract void updateSurface(SurfaceHolder holder) throws Surface.OutOfResourcesException; 210 211 /** 212 * Destroys the layers used by the specified view hierarchy. 213 * 214 * @param view The root of the view hierarchy 215 */ 216 abstract void destroyLayers(View view); 217 218 /** 219 * Destroys all hardware rendering resources associated with the specified 220 * view hierarchy. 221 * 222 * @param view The root of the view hierarchy 223 */ 224 abstract void destroyHardwareResources(View view); 225 226 /** 227 * This method should be invoked whenever the current hardware renderer 228 * context should be reset. 229 * 230 * @param holder The holder for the surface to hardware accelerate 231 */ 232 abstract void invalidate(SurfaceHolder holder); 233 234 /** 235 * This method should be invoked to ensure the hardware renderer is in 236 * valid state (for instance, to ensure the correct EGL context is bound 237 * to the current thread.) 238 * 239 * @return true if the renderer is now valid, false otherwise 240 */ 241 abstract boolean validate(); 242 243 /** 244 * This method ensures the hardware renderer is in a valid state 245 * before executing the specified action. 246 * 247 * This method will attempt to set a valid state even if the window 248 * the renderer is attached to was destroyed. 249 * 250 * @return true if the action was run 251 */ 252 abstract boolean safelyRun(Runnable action); 253 254 /** 255 * Setup the hardware renderer for drawing. This is called whenever the 256 * size of the target surface changes or when the surface is first created. 257 * 258 * @param width Width of the drawing surface. 259 * @param height Height of the drawing surface. 260 */ 261 abstract void setup(int width, int height); 262 263 /** 264 * Gets the current width of the surface. This is the width that the surface 265 * was last set to in a call to {@link #setup(int, int)}. 266 * 267 * @return the current width of the surface 268 */ 269 abstract int getWidth(); 270 271 /** 272 * Gets the current height of the surface. This is the height that the surface 273 * was last set to in a call to {@link #setup(int, int)}. 274 * 275 * @return the current width of the surface 276 */ 277 abstract int getHeight(); 278 279 /** 280 * Gets the current canvas associated with this HardwareRenderer. 281 * 282 * @return the current HardwareCanvas 283 */ 284 abstract HardwareCanvas getCanvas(); 285 286 /** 287 * Outputs extra debugging information in the specified file descriptor. 288 * @param pw 289 */ 290 abstract void dumpGfxInfo(PrintWriter pw); 291 292 /** 293 * Outputs the total number of frames rendered (used for fps calculations) 294 * 295 * @return the number of frames rendered 296 */ 297 abstract long getFrameCount(); 298 299 /** 300 * Sets the directory to use as a persistent storage for hardware rendering 301 * resources. 302 * 303 * @param cacheDir A directory the current process can write to 304 */ 305 public static void setupDiskCache(File cacheDir) { 306 nSetupShadersDiskCache(new File(cacheDir, CACHE_PATH_SHADERS).getAbsolutePath()); 307 } 308 309 private static native void nSetupShadersDiskCache(String cacheFile); 310 311 /** 312 * Notifies EGL that the frame is about to be rendered. 313 * @param size 314 */ 315 private static void beginFrame(int[] size) { 316 nBeginFrame(size); 317 } 318 319 private static native void nBeginFrame(int[] size); 320 321 /** 322 * Preserves the back buffer of the current surface after a buffer swap. 323 * Calling this method sets the EGL_SWAP_BEHAVIOR attribute of the current 324 * surface to EGL_BUFFER_PRESERVED. Calling this method requires an EGL 325 * config that supports EGL_SWAP_BEHAVIOR_PRESERVED_BIT. 326 * 327 * @return True if the swap behavior was successfully changed, 328 * false otherwise. 329 */ 330 static boolean preserveBackBuffer() { 331 return nPreserveBackBuffer(); 332 } 333 334 private static native boolean nPreserveBackBuffer(); 335 336 /** 337 * Indicates whether the current surface preserves its back buffer 338 * after a buffer swap. 339 * 340 * @return True, if the surface's EGL_SWAP_BEHAVIOR is EGL_BUFFER_PRESERVED, 341 * false otherwise 342 */ 343 static boolean isBackBufferPreserved() { 344 return nIsBackBufferPreserved(); 345 } 346 347 private static native boolean nIsBackBufferPreserved(); 348 349 /** 350 * Disables v-sync. For performance testing only. 351 */ 352 static void disableVsync() { 353 nDisableVsync(); 354 } 355 356 private static native void nDisableVsync(); 357 358 /** 359 * Interface used to receive callbacks whenever a view is drawn by 360 * a hardware renderer instance. 361 */ 362 interface HardwareDrawCallbacks { 363 /** 364 * Invoked before a view is drawn by a hardware renderer. 365 * 366 * @param canvas The Canvas used to render the view. 367 */ 368 void onHardwarePreDraw(HardwareCanvas canvas); 369 370 /** 371 * Invoked after a view is drawn by a hardware renderer. 372 * 373 * @param canvas The Canvas used to render the view. 374 */ 375 void onHardwarePostDraw(HardwareCanvas canvas); 376 } 377 378 /** 379 * Draws the specified view. 380 * 381 * @param view The view to draw. 382 * @param attachInfo AttachInfo tied to the specified view. 383 * @param callbacks Callbacks invoked when drawing happens. 384 * @param dirty The dirty rectangle to update, can be null. 385 * 386 * @return true if the dirty rect was ignored, false otherwise 387 */ 388 abstract boolean draw(View view, View.AttachInfo attachInfo, HardwareDrawCallbacks callbacks, 389 Rect dirty); 390 391 /** 392 * Creates a new display list that can be used to record batches of 393 * drawing operations. 394 * 395 * @param name The name of the display list, used for debugging purpose. 396 * May be null 397 * 398 * @return A new display list. 399 */ 400 public abstract DisplayList createDisplayList(String name); 401 402 /** 403 * Creates a new hardware layer. A hardware layer built by calling this 404 * method will be treated as a texture layer, instead of as a render target. 405 * 406 * @param isOpaque Whether the layer should be opaque or not 407 * 408 * @return A hardware layer 409 */ 410 abstract HardwareLayer createHardwareLayer(boolean isOpaque); 411 412 /** 413 * Creates a new hardware layer. 414 * 415 * @param width The minimum width of the layer 416 * @param height The minimum height of the layer 417 * @param isOpaque Whether the layer should be opaque or not 418 * 419 * @return A hardware layer 420 */ 421 abstract HardwareLayer createHardwareLayer(int width, int height, boolean isOpaque); 422 423 /** 424 * Creates a new {@link SurfaceTexture} that can be used to render into the 425 * specified hardware layer. 426 * 427 * 428 * @param layer The layer to render into using a {@link android.graphics.SurfaceTexture} 429 * 430 * @return A {@link SurfaceTexture} 431 */ 432 abstract SurfaceTexture createSurfaceTexture(HardwareLayer layer); 433 434 /** 435 * Sets the {@link android.graphics.SurfaceTexture} that will be used to 436 * render into the specified hardware layer. 437 * 438 * @param layer The layer to render into using a {@link android.graphics.SurfaceTexture} 439 * @param surfaceTexture The {@link android.graphics.SurfaceTexture} to use for the layer 440 */ 441 abstract void setSurfaceTexture(HardwareLayer layer, SurfaceTexture surfaceTexture); 442 443 /** 444 * Detaches the specified functor from the current functor execution queue. 445 * 446 * @param functor The native functor to remove from the execution queue. 447 * 448 * @see HardwareCanvas#callDrawGLFunction(int) 449 * @see #attachFunctor(android.view.View.AttachInfo, int) 450 */ 451 abstract void detachFunctor(int functor); 452 453 /** 454 * Schedules the specified functor in the functors execution queue. 455 * 456 * @param attachInfo AttachInfo tied to this renderer. 457 * @param functor The native functor to insert in the execution queue. 458 * 459 * @see HardwareCanvas#callDrawGLFunction(int) 460 * @see #detachFunctor(int) 461 * 462 * @return true if the functor was attached successfully 463 */ 464 abstract boolean attachFunctor(View.AttachInfo attachInfo, int functor); 465 466 /** 467 * Initializes the hardware renderer for the specified surface and setup the 468 * renderer for drawing, if needed. This is invoked when the ViewAncestor has 469 * potentially lost the hardware renderer. The hardware renderer should be 470 * reinitialized and setup when the render {@link #isRequested()} and 471 * {@link #isEnabled()}. 472 * 473 * @param width The width of the drawing surface. 474 * @param height The height of the drawing surface. 475 * @param holder The target surface 476 */ 477 void initializeIfNeeded(int width, int height, SurfaceHolder holder) 478 throws Surface.OutOfResourcesException { 479 if (isRequested()) { 480 // We lost the gl context, so recreate it. 481 if (!isEnabled()) { 482 if (initialize(holder)) { 483 setup(width, height); 484 } 485 } 486 } 487 } 488 489 /** 490 * Creates a hardware renderer using OpenGL. 491 * 492 * @param glVersion The version of OpenGL to use (1 for OpenGL 1, 11 for OpenGL 1.1, etc.) 493 * @param translucent True if the surface is translucent, false otherwise 494 * 495 * @return A hardware renderer backed by OpenGL. 496 */ 497 static HardwareRenderer createGlRenderer(int glVersion, boolean translucent) { 498 switch (glVersion) { 499 case 2: 500 return Gl20Renderer.create(translucent); 501 } 502 throw new IllegalArgumentException("Unknown GL version: " + glVersion); 503 } 504 505 /** 506 * Invoke this method when the system is running out of memory. This 507 * method will attempt to recover as much memory as possible, based on 508 * the specified hint. 509 * 510 * @param level Hint about the amount of memory that should be trimmed, 511 * see {@link android.content.ComponentCallbacks} 512 */ 513 static void trimMemory(int level) { 514 startTrimMemory(level); 515 endTrimMemory(); 516 } 517 518 /** 519 * Starts the process of trimming memory. Usually this call will setup 520 * hardware rendering context and reclaim memory.Extra cleanup might 521 * be required by calling {@link #endTrimMemory()}. 522 * 523 * @param level Hint about the amount of memory that should be trimmed, 524 * see {@link android.content.ComponentCallbacks} 525 */ 526 static void startTrimMemory(int level) { 527 Gl20Renderer.startTrimMemory(level); 528 } 529 530 /** 531 * Finishes the process of trimming memory. This method will usually 532 * cleanup special resources used by the memory trimming process. 533 */ 534 static void endTrimMemory() { 535 Gl20Renderer.endTrimMemory(); 536 } 537 538 /** 539 * Indicates whether hardware acceleration is currently enabled. 540 * 541 * @return True if hardware acceleration is in use, false otherwise. 542 */ 543 boolean isEnabled() { 544 return mEnabled; 545 } 546 547 /** 548 * Indicates whether hardware acceleration is currently enabled. 549 * 550 * @param enabled True if the hardware renderer is in use, false otherwise. 551 */ 552 void setEnabled(boolean enabled) { 553 mEnabled = enabled; 554 } 555 556 /** 557 * Indicates whether hardware acceleration is currently request but not 558 * necessarily enabled yet. 559 * 560 * @return True if requested, false otherwise. 561 */ 562 boolean isRequested() { 563 return mRequested; 564 } 565 566 /** 567 * Indicates whether hardware acceleration is currently requested but not 568 * necessarily enabled yet. 569 * 570 * @return True to request hardware acceleration, false otherwise. 571 */ 572 void setRequested(boolean requested) { 573 mRequested = requested; 574 } 575 576 @SuppressWarnings({"deprecation"}) 577 static abstract class GlRenderer extends HardwareRenderer { 578 // These values are not exposed in our EGL APIs 579 static final int EGL_CONTEXT_CLIENT_VERSION = 0x3098; 580 static final int EGL_OPENGL_ES2_BIT = 4; 581 static final int EGL_SURFACE_TYPE = 0x3033; 582 static final int EGL_SWAP_BEHAVIOR_PRESERVED_BIT = 0x0400; 583 584 static final int SURFACE_STATE_ERROR = 0; 585 static final int SURFACE_STATE_SUCCESS = 1; 586 static final int SURFACE_STATE_UPDATED = 2; 587 588 static final int FUNCTOR_PROCESS_DELAY = 4; 589 590 static EGL10 sEgl; 591 static EGLDisplay sEglDisplay; 592 static EGLConfig sEglConfig; 593 static final Object[] sEglLock = new Object[0]; 594 int mWidth = -1, mHeight = -1; 595 596 static final ThreadLocal<ManagedEGLContext> sEglContextStorage 597 = new ThreadLocal<ManagedEGLContext>(); 598 599 EGLContext mEglContext; 600 Thread mEglThread; 601 602 EGLSurface mEglSurface; 603 604 GL mGl; 605 HardwareCanvas mCanvas; 606 607 long mFrameCount; 608 Paint mDebugPaint; 609 610 static boolean sDirtyRegions; 611 static final boolean sDirtyRegionsRequested; 612 static { 613 String dirtyProperty = SystemProperties.get(RENDER_DIRTY_REGIONS_PROPERTY, "true"); 614 //noinspection PointlessBooleanExpression,ConstantConditions 615 sDirtyRegions = RENDER_DIRTY_REGIONS && "true".equalsIgnoreCase(dirtyProperty); 616 sDirtyRegionsRequested = sDirtyRegions; 617 } 618 619 boolean mDirtyRegionsEnabled; 620 boolean mUpdateDirtyRegions; 621 622 final boolean mVsyncDisabled; 623 624 final boolean mProfileEnabled; 625 final float[] mProfileData; 626 int mProfileCurrentFrame = -PROFILE_FRAME_DATA_COUNT; 627 628 final boolean mDebugDirtyRegions; 629 630 final int mGlVersion; 631 final boolean mTranslucent; 632 633 private boolean mDestroyed; 634 635 private final Rect mRedrawClip = new Rect(); 636 637 private final int[] mSurfaceSize = new int[2]; 638 private final FunctorsRunnable mFunctorsRunnable = new FunctorsRunnable(); 639 640 GlRenderer(int glVersion, boolean translucent) { 641 mGlVersion = glVersion; 642 mTranslucent = translucent; 643 644 String property; 645 646 property = SystemProperties.get(DISABLE_VSYNC_PROPERTY, "false"); 647 mVsyncDisabled = "true".equalsIgnoreCase(property); 648 if (mVsyncDisabled) { 649 Log.d(LOG_TAG, "Disabling v-sync"); 650 } 651 652 property = SystemProperties.get(PROFILE_PROPERTY, "false"); 653 mProfileEnabled = "true".equalsIgnoreCase(property); 654 if (mProfileEnabled) { 655 Log.d(LOG_TAG, "Profiling hardware renderer"); 656 } 657 658 if (mProfileEnabled) { 659 property = SystemProperties.get(PROFILE_MAXFRAMES_PROPERTY, 660 Integer.toString(PROFILE_MAX_FRAMES)); 661 int maxProfileFrames = Integer.valueOf(property); 662 mProfileData = new float[maxProfileFrames * PROFILE_FRAME_DATA_COUNT]; 663 for (int i = 0; i < mProfileData.length; i += PROFILE_FRAME_DATA_COUNT) { 664 mProfileData[i] = mProfileData[i + 1] = mProfileData[i + 2] = -1; 665 } 666 } else { 667 mProfileData = null; 668 } 669 670 property = SystemProperties.get(DEBUG_DIRTY_REGIONS_PROPERTY, "false"); 671 mDebugDirtyRegions = "true".equalsIgnoreCase(property); 672 if (mDebugDirtyRegions) { 673 Log.d(LOG_TAG, "Debugging dirty regions"); 674 } 675 } 676 677 @Override 678 void dumpGfxInfo(PrintWriter pw) { 679 if (mProfileEnabled) { 680 pw.printf("\n\tDraw\tProcess\tExecute\n"); 681 for (int i = 0; i < mProfileData.length; i += PROFILE_FRAME_DATA_COUNT) { 682 if (mProfileData[i] < 0) { 683 break; 684 } 685 pw.printf("\t%3.2f\t%3.2f\t%3.2f\n", mProfileData[i], mProfileData[i + 1], 686 mProfileData[i + 2]); 687 mProfileData[i] = mProfileData[i + 1] = mProfileData[i + 2] = -1; 688 } 689 mProfileCurrentFrame = mProfileData.length; 690 } 691 } 692 693 @Override 694 long getFrameCount() { 695 return mFrameCount; 696 } 697 698 /** 699 * Indicates whether this renderer instance can track and update dirty regions. 700 */ 701 boolean hasDirtyRegions() { 702 return mDirtyRegionsEnabled; 703 } 704 705 /** 706 * Checks for OpenGL errors. If an error has occured, {@link #destroy(boolean)} 707 * is invoked and the requested flag is turned off. The error code is 708 * also logged as a warning. 709 */ 710 void checkEglErrors() { 711 if (isEnabled()) { 712 int error = sEgl.eglGetError(); 713 if (error != EGL_SUCCESS) { 714 // something bad has happened revert to 715 // normal rendering. 716 Log.w(LOG_TAG, "EGL error: " + GLUtils.getEGLErrorString(error)); 717 fallback(error != EGL11.EGL_CONTEXT_LOST); 718 } 719 } 720 } 721 722 private void fallback(boolean fallback) { 723 destroy(true); 724 if (fallback) { 725 // we'll try again if it was context lost 726 setRequested(false); 727 Log.w(LOG_TAG, "Mountain View, we've had a problem here. " 728 + "Switching back to software rendering."); 729 } 730 } 731 732 @Override 733 boolean initialize(SurfaceHolder holder) throws Surface.OutOfResourcesException { 734 if (isRequested() && !isEnabled()) { 735 initializeEgl(); 736 mGl = createEglSurface(holder); 737 mDestroyed = false; 738 739 if (mGl != null) { 740 int err = sEgl.eglGetError(); 741 if (err != EGL_SUCCESS) { 742 destroy(true); 743 setRequested(false); 744 } else { 745 if (mCanvas == null) { 746 mCanvas = createCanvas(); 747 } 748 if (mCanvas != null) { 749 setEnabled(true); 750 } else { 751 Log.w(LOG_TAG, "Hardware accelerated Canvas could not be created"); 752 } 753 } 754 755 return mCanvas != null; 756 } 757 } 758 return false; 759 } 760 761 @Override 762 void updateSurface(SurfaceHolder holder) throws Surface.OutOfResourcesException { 763 if (isRequested() && isEnabled()) { 764 createEglSurface(holder); 765 } 766 } 767 768 abstract HardwareCanvas createCanvas(); 769 770 abstract int[] getConfig(boolean dirtyRegions); 771 772 void initializeEgl() { 773 synchronized (sEglLock) { 774 if (sEgl == null && sEglConfig == null) { 775 sEgl = (EGL10) EGLContext.getEGL(); 776 777 // Get to the default display. 778 sEglDisplay = sEgl.eglGetDisplay(EGL_DEFAULT_DISPLAY); 779 780 if (sEglDisplay == EGL_NO_DISPLAY) { 781 throw new RuntimeException("eglGetDisplay failed " 782 + GLUtils.getEGLErrorString(sEgl.eglGetError())); 783 } 784 785 // We can now initialize EGL for that display 786 int[] version = new int[2]; 787 if (!sEgl.eglInitialize(sEglDisplay, version)) { 788 throw new RuntimeException("eglInitialize failed " + 789 GLUtils.getEGLErrorString(sEgl.eglGetError())); 790 } 791 792 sEglConfig = chooseEglConfig(); 793 if (sEglConfig == null) { 794 // We tried to use EGL_SWAP_BEHAVIOR_PRESERVED_BIT, try again without 795 if (sDirtyRegions) { 796 sDirtyRegions = false; 797 sEglConfig = chooseEglConfig(); 798 if (sEglConfig == null) { 799 throw new RuntimeException("eglConfig not initialized"); 800 } 801 } else { 802 throw new RuntimeException("eglConfig not initialized"); 803 } 804 } 805 } 806 } 807 808 ManagedEGLContext managedContext = sEglContextStorage.get(); 809 mEglContext = managedContext != null ? managedContext.getContext() : null; 810 mEglThread = Thread.currentThread(); 811 812 if (mEglContext == null) { 813 mEglContext = createContext(sEgl, sEglDisplay, sEglConfig); 814 sEglContextStorage.set(createManagedContext(mEglContext)); 815 } 816 } 817 818 abstract ManagedEGLContext createManagedContext(EGLContext eglContext); 819 820 private EGLConfig chooseEglConfig() { 821 EGLConfig[] configs = new EGLConfig[1]; 822 int[] configsCount = new int[1]; 823 int[] configSpec = getConfig(sDirtyRegions); 824 825 // Debug 826 final String debug = SystemProperties.get(PRINT_CONFIG_PROPERTY, ""); 827 if ("all".equalsIgnoreCase(debug)) { 828 sEgl.eglChooseConfig(sEglDisplay, configSpec, null, 0, configsCount); 829 830 EGLConfig[] debugConfigs = new EGLConfig[configsCount[0]]; 831 sEgl.eglChooseConfig(sEglDisplay, configSpec, debugConfigs, 832 configsCount[0], configsCount); 833 834 for (EGLConfig config : debugConfigs) { 835 printConfig(config); 836 } 837 } 838 839 if (!sEgl.eglChooseConfig(sEglDisplay, configSpec, configs, 1, configsCount)) { 840 throw new IllegalArgumentException("eglChooseConfig failed " + 841 GLUtils.getEGLErrorString(sEgl.eglGetError())); 842 } else if (configsCount[0] > 0) { 843 if ("choice".equalsIgnoreCase(debug)) { 844 printConfig(configs[0]); 845 } 846 return configs[0]; 847 } 848 849 return null; 850 } 851 852 private static void printConfig(EGLConfig config) { 853 int[] value = new int[1]; 854 855 Log.d(LOG_TAG, "EGL configuration " + config + ":"); 856 857 sEgl.eglGetConfigAttrib(sEglDisplay, config, EGL_RED_SIZE, value); 858 Log.d(LOG_TAG, " RED_SIZE = " + value[0]); 859 860 sEgl.eglGetConfigAttrib(sEglDisplay, config, EGL_GREEN_SIZE, value); 861 Log.d(LOG_TAG, " GREEN_SIZE = " + value[0]); 862 863 sEgl.eglGetConfigAttrib(sEglDisplay, config, EGL_BLUE_SIZE, value); 864 Log.d(LOG_TAG, " BLUE_SIZE = " + value[0]); 865 866 sEgl.eglGetConfigAttrib(sEglDisplay, config, EGL_ALPHA_SIZE, value); 867 Log.d(LOG_TAG, " ALPHA_SIZE = " + value[0]); 868 869 sEgl.eglGetConfigAttrib(sEglDisplay, config, EGL_DEPTH_SIZE, value); 870 Log.d(LOG_TAG, " DEPTH_SIZE = " + value[0]); 871 872 sEgl.eglGetConfigAttrib(sEglDisplay, config, EGL_STENCIL_SIZE, value); 873 Log.d(LOG_TAG, " STENCIL_SIZE = " + value[0]); 874 875 sEgl.eglGetConfigAttrib(sEglDisplay, config, EGL_SURFACE_TYPE, value); 876 Log.d(LOG_TAG, " SURFACE_TYPE = 0x" + Integer.toHexString(value[0])); 877 } 878 879 GL createEglSurface(SurfaceHolder holder) throws Surface.OutOfResourcesException { 880 // Check preconditions. 881 if (sEgl == null) { 882 throw new RuntimeException("egl not initialized"); 883 } 884 if (sEglDisplay == null) { 885 throw new RuntimeException("eglDisplay not initialized"); 886 } 887 if (sEglConfig == null) { 888 throw new RuntimeException("eglConfig not initialized"); 889 } 890 if (Thread.currentThread() != mEglThread) { 891 throw new IllegalStateException("HardwareRenderer cannot be used " 892 + "from multiple threads"); 893 } 894 895 // In case we need to destroy an existing surface 896 destroySurface(); 897 898 // Create an EGL surface we can render into. 899 if (!createSurface(holder)) { 900 return null; 901 } 902 903 /* 904 * Before we can issue GL commands, we need to make sure 905 * the context is current and bound to a surface. 906 */ 907 if (!sEgl.eglMakeCurrent(sEglDisplay, mEglSurface, mEglSurface, mEglContext)) { 908 throw new Surface.OutOfResourcesException("eglMakeCurrent failed " 909 + GLUtils.getEGLErrorString(sEgl.eglGetError())); 910 } 911 912 initCaches(); 913 914 enableDirtyRegions(); 915 916 return mEglContext.getGL(); 917 } 918 919 private void enableDirtyRegions() { 920 // If mDirtyRegions is set, this means we have an EGL configuration 921 // with EGL_SWAP_BEHAVIOR_PRESERVED_BIT set 922 if (sDirtyRegions) { 923 if (!(mDirtyRegionsEnabled = preserveBackBuffer())) { 924 Log.w(LOG_TAG, "Backbuffer cannot be preserved"); 925 } 926 } else if (sDirtyRegionsRequested) { 927 // If mDirtyRegions is not set, our EGL configuration does not 928 // have EGL_SWAP_BEHAVIOR_PRESERVED_BIT; however, the default 929 // swap behavior might be EGL_BUFFER_PRESERVED, which means we 930 // want to set mDirtyRegions. We try to do this only if dirty 931 // regions were initially requested as part of the device 932 // configuration (see RENDER_DIRTY_REGIONS) 933 mDirtyRegionsEnabled = isBackBufferPreserved(); 934 } 935 } 936 937 abstract void initCaches(); 938 939 EGLContext createContext(EGL10 egl, EGLDisplay eglDisplay, EGLConfig eglConfig) { 940 int[] attribs = { EGL_CONTEXT_CLIENT_VERSION, mGlVersion, EGL_NONE }; 941 942 return egl.eglCreateContext(eglDisplay, eglConfig, EGL_NO_CONTEXT, 943 mGlVersion != 0 ? attribs : null); 944 } 945 946 @Override 947 void destroy(boolean full) { 948 if (full && mCanvas != null) { 949 mCanvas = null; 950 } 951 952 if (!isEnabled() || mDestroyed) { 953 setEnabled(false); 954 return; 955 } 956 957 destroySurface(); 958 setEnabled(false); 959 960 mDestroyed = true; 961 mGl = null; 962 } 963 964 void destroySurface() { 965 if (mEglSurface != null && mEglSurface != EGL_NO_SURFACE) { 966 sEgl.eglMakeCurrent(sEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); 967 sEgl.eglDestroySurface(sEglDisplay, mEglSurface); 968 mEglSurface = null; 969 } 970 } 971 972 @Override 973 void invalidate(SurfaceHolder holder) { 974 // Cancels any existing buffer to ensure we'll get a buffer 975 // of the right size before we call eglSwapBuffers 976 sEgl.eglMakeCurrent(sEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); 977 978 if (mEglSurface != null && mEglSurface != EGL_NO_SURFACE) { 979 sEgl.eglDestroySurface(sEglDisplay, mEglSurface); 980 mEglSurface = null; 981 setEnabled(false); 982 } 983 984 if (holder.getSurface().isValid()) { 985 if (!createSurface(holder)) { 986 return; 987 } 988 989 mUpdateDirtyRegions = true; 990 991 if (mCanvas != null) { 992 setEnabled(true); 993 } 994 } 995 } 996 997 private boolean createSurface(SurfaceHolder holder) { 998 mEglSurface = sEgl.eglCreateWindowSurface(sEglDisplay, sEglConfig, holder, null); 999 1000 if (mEglSurface == null || mEglSurface == EGL_NO_SURFACE) { 1001 int error = sEgl.eglGetError(); 1002 if (error == EGL_BAD_NATIVE_WINDOW) { 1003 Log.e(LOG_TAG, "createWindowSurface returned EGL_BAD_NATIVE_WINDOW."); 1004 return false; 1005 } 1006 throw new RuntimeException("createWindowSurface failed " 1007 + GLUtils.getEGLErrorString(error)); 1008 } 1009 return true; 1010 } 1011 1012 @Override 1013 boolean validate() { 1014 return checkCurrent() != SURFACE_STATE_ERROR; 1015 } 1016 1017 @Override 1018 void setup(int width, int height) { 1019 if (validate()) { 1020 mCanvas.setViewport(width, height); 1021 mWidth = width; 1022 mHeight = height; 1023 } 1024 } 1025 1026 @Override 1027 int getWidth() { 1028 return mWidth; 1029 } 1030 1031 @Override 1032 int getHeight() { 1033 return mHeight; 1034 } 1035 1036 @Override 1037 HardwareCanvas getCanvas() { 1038 return mCanvas; 1039 } 1040 1041 boolean canDraw() { 1042 return mGl != null && mCanvas != null; 1043 } 1044 1045 void onPreDraw(Rect dirty) { 1046 1047 } 1048 1049 void onPostDraw() { 1050 } 1051 1052 class FunctorsRunnable implements Runnable { 1053 View.AttachInfo attachInfo; 1054 1055 @Override 1056 public void run() { 1057 final HardwareRenderer renderer = attachInfo.mHardwareRenderer; 1058 if (renderer == null || !renderer.isEnabled() || renderer != GlRenderer.this) { 1059 return; 1060 } 1061 1062 final int surfaceState = checkCurrent(); 1063 if (surfaceState != SURFACE_STATE_ERROR) { 1064 int status = mCanvas.invokeFunctors(mRedrawClip); 1065 handleFunctorStatus(attachInfo, status); 1066 } 1067 } 1068 } 1069 1070 @Override 1071 boolean draw(View view, View.AttachInfo attachInfo, HardwareDrawCallbacks callbacks, 1072 Rect dirty) { 1073 if (canDraw()) { 1074 if (!hasDirtyRegions()) { 1075 dirty = null; 1076 } 1077 attachInfo.mIgnoreDirtyState = true; 1078 attachInfo.mDrawingTime = SystemClock.uptimeMillis(); 1079 1080 view.mPrivateFlags |= View.DRAWN; 1081 1082 final int surfaceState = checkCurrent(); 1083 if (surfaceState != SURFACE_STATE_ERROR) { 1084 HardwareCanvas canvas = mCanvas; 1085 attachInfo.mHardwareCanvas = canvas; 1086 1087 // We had to change the current surface and/or context, redraw everything 1088 if (surfaceState == SURFACE_STATE_UPDATED) { 1089 dirty = null; 1090 beginFrame(null); 1091 } else { 1092 int[] size = mSurfaceSize; 1093 beginFrame(size); 1094 1095 if (size[1] != mHeight || size[0] != mWidth) { 1096 mWidth = size[0]; 1097 mHeight = size[1]; 1098 1099 canvas.setViewport(mWidth, mHeight); 1100 1101 dirty = null; 1102 } 1103 } 1104 1105 onPreDraw(dirty); 1106 1107 int saveCount = canvas.save(); 1108 callbacks.onHardwarePreDraw(canvas); 1109 1110 try { 1111 view.mRecreateDisplayList = 1112 (view.mPrivateFlags & View.INVALIDATED) == View.INVALIDATED; 1113 view.mPrivateFlags &= ~View.INVALIDATED; 1114 1115 long getDisplayListStartTime = 0; 1116 if (mProfileEnabled) { 1117 mProfileCurrentFrame += PROFILE_FRAME_DATA_COUNT; 1118 if (mProfileCurrentFrame >= mProfileData.length) { 1119 mProfileCurrentFrame = 0; 1120 } 1121 1122 getDisplayListStartTime = System.nanoTime(); 1123 } 1124 1125 DisplayList displayList = view.getDisplayList(); 1126 1127 if (mProfileEnabled) { 1128 long now = System.nanoTime(); 1129 float total = (now - getDisplayListStartTime) * 0.000001f; 1130 //noinspection PointlessArithmeticExpression 1131 mProfileData[mProfileCurrentFrame] = total; 1132 } 1133 1134 if (displayList != null) { 1135 long drawDisplayListStartTime = 0; 1136 if (mProfileEnabled) { 1137 drawDisplayListStartTime = System.nanoTime(); 1138 } 1139 1140 int status = canvas.drawDisplayList(displayList, mRedrawClip, 1141 DisplayList.FLAG_CLIP_CHILDREN); 1142 1143 if (mProfileEnabled) { 1144 long now = System.nanoTime(); 1145 float total = (now - drawDisplayListStartTime) * 0.000001f; 1146 mProfileData[mProfileCurrentFrame + 1] = total; 1147 } 1148 1149 handleFunctorStatus(attachInfo, status); 1150 } else { 1151 // Shouldn't reach here 1152 view.draw(canvas); 1153 } 1154 } finally { 1155 callbacks.onHardwarePostDraw(canvas); 1156 canvas.restoreToCount(saveCount); 1157 view.mRecreateDisplayList = false; 1158 1159 mFrameCount++; 1160 1161 if (mDebugDirtyRegions) { 1162 if (mDebugPaint == null) { 1163 mDebugPaint = new Paint(); 1164 mDebugPaint.setColor(0x7fff0000); 1165 } 1166 1167 if (dirty != null && (mFrameCount & 1) == 0) { 1168 canvas.drawRect(dirty, mDebugPaint); 1169 } 1170 } 1171 } 1172 1173 onPostDraw(); 1174 1175 attachInfo.mIgnoreDirtyState = false; 1176 1177 long eglSwapBuffersStartTime = 0; 1178 if (mProfileEnabled) { 1179 eglSwapBuffersStartTime = System.nanoTime(); 1180 } 1181 1182 sEgl.eglSwapBuffers(sEglDisplay, mEglSurface); 1183 1184 if (mProfileEnabled) { 1185 long now = System.nanoTime(); 1186 float total = (now - eglSwapBuffersStartTime) * 0.000001f; 1187 mProfileData[mProfileCurrentFrame + 2] = total; 1188 } 1189 1190 checkEglErrors(); 1191 1192 return dirty == null; 1193 } 1194 } 1195 1196 return false; 1197 } 1198 1199 private void handleFunctorStatus(View.AttachInfo attachInfo, int status) { 1200 // If the draw flag is set, functors will be invoked while executing 1201 // the tree of display lists 1202 if ((status & DisplayList.STATUS_DRAW) != 0) { 1203 if (mRedrawClip.isEmpty()) { 1204 attachInfo.mViewRootImpl.invalidate(); 1205 } else { 1206 attachInfo.mViewRootImpl.invalidateChildInParent(null, mRedrawClip); 1207 mRedrawClip.setEmpty(); 1208 } 1209 } 1210 1211 if ((status & DisplayList.STATUS_INVOKE) != 0) { 1212 scheduleFunctors(attachInfo); 1213 } 1214 } 1215 1216 private void scheduleFunctors(View.AttachInfo attachInfo) { 1217 mFunctorsRunnable.attachInfo = attachInfo; 1218 if (!attachInfo.mHandler.hasCallbacks(mFunctorsRunnable)) { 1219 // delay the functor callback by a few ms so it isn't polled constantly 1220 attachInfo.mHandler.postDelayed(mFunctorsRunnable, FUNCTOR_PROCESS_DELAY); 1221 } 1222 } 1223 1224 @Override 1225 void detachFunctor(int functor) { 1226 if (mCanvas != null) { 1227 mCanvas.detachFunctor(functor); 1228 } 1229 } 1230 1231 @Override 1232 boolean attachFunctor(View.AttachInfo attachInfo, int functor) { 1233 if (mCanvas != null) { 1234 mCanvas.attachFunctor(functor); 1235 scheduleFunctors(attachInfo); 1236 return true; 1237 } 1238 return false; 1239 } 1240 1241 /** 1242 * Ensures the current EGL context is the one we expect. 1243 * 1244 * @return {@link #SURFACE_STATE_ERROR} if the correct EGL context cannot be made current, 1245 * {@link #SURFACE_STATE_UPDATED} if the EGL context was changed or 1246 * {@link #SURFACE_STATE_SUCCESS} if the EGL context was the correct one 1247 */ 1248 int checkCurrent() { 1249 if (mEglThread != Thread.currentThread()) { 1250 throw new IllegalStateException("Hardware acceleration can only be used with a " + 1251 "single UI thread.\nOriginal thread: " + mEglThread + "\n" + 1252 "Current thread: " + Thread.currentThread()); 1253 } 1254 1255 if (!mEglContext.equals(sEgl.eglGetCurrentContext()) || 1256 !mEglSurface.equals(sEgl.eglGetCurrentSurface(EGL_DRAW))) { 1257 if (!sEgl.eglMakeCurrent(sEglDisplay, mEglSurface, mEglSurface, mEglContext)) { 1258 Log.e(LOG_TAG, "eglMakeCurrent failed " + 1259 GLUtils.getEGLErrorString(sEgl.eglGetError())); 1260 fallback(true); 1261 return SURFACE_STATE_ERROR; 1262 } else { 1263 if (mUpdateDirtyRegions) { 1264 enableDirtyRegions(); 1265 mUpdateDirtyRegions = false; 1266 } 1267 return SURFACE_STATE_UPDATED; 1268 } 1269 } 1270 return SURFACE_STATE_SUCCESS; 1271 } 1272 } 1273 1274 /** 1275 * Hardware renderer using OpenGL ES 2.0. 1276 */ 1277 static class Gl20Renderer extends GlRenderer { 1278 private GLES20Canvas mGlCanvas; 1279 1280 private static EGLSurface sPbuffer; 1281 private static final Object[] sPbufferLock = new Object[0]; 1282 1283 static class Gl20RendererEglContext extends ManagedEGLContext { 1284 final Handler mHandler = new Handler(); 1285 1286 public Gl20RendererEglContext(EGLContext context) { 1287 super(context); 1288 } 1289 1290 @Override 1291 public void onTerminate(final EGLContext eglContext) { 1292 // Make sure we do this on the correct thread. 1293 if (mHandler.getLooper() != Looper.myLooper()) { 1294 mHandler.post(new Runnable() { 1295 @Override 1296 public void run() { 1297 onTerminate(eglContext); 1298 } 1299 }); 1300 return; 1301 } 1302 1303 synchronized (sEglLock) { 1304 if (sEgl == null) return; 1305 1306 if (EGLImpl.getInitCount(sEglDisplay) == 1) { 1307 usePbufferSurface(eglContext); 1308 GLES20Canvas.terminateCaches(); 1309 1310 sEgl.eglDestroyContext(sEglDisplay, eglContext); 1311 sEglContextStorage.set(null); 1312 sEglContextStorage.remove(); 1313 1314 sEgl.eglDestroySurface(sEglDisplay, sPbuffer); 1315 sEgl.eglMakeCurrent(sEglDisplay, EGL_NO_SURFACE, 1316 EGL_NO_SURFACE, EGL_NO_CONTEXT); 1317 1318 sEgl.eglReleaseThread(); 1319 sEgl.eglTerminate(sEglDisplay); 1320 1321 sEgl = null; 1322 sEglDisplay = null; 1323 sEglConfig = null; 1324 sPbuffer = null; 1325 } 1326 } 1327 } 1328 } 1329 1330 Gl20Renderer(boolean translucent) { 1331 super(2, translucent); 1332 } 1333 1334 @Override 1335 HardwareCanvas createCanvas() { 1336 return mGlCanvas = new GLES20Canvas(mTranslucent); 1337 } 1338 1339 @Override 1340 ManagedEGLContext createManagedContext(EGLContext eglContext) { 1341 return new Gl20Renderer.Gl20RendererEglContext(mEglContext); 1342 } 1343 1344 @Override 1345 int[] getConfig(boolean dirtyRegions) { 1346 return new int[] { 1347 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, 1348 EGL_RED_SIZE, 8, 1349 EGL_GREEN_SIZE, 8, 1350 EGL_BLUE_SIZE, 8, 1351 EGL_ALPHA_SIZE, 8, 1352 EGL_DEPTH_SIZE, 0, 1353 EGL_STENCIL_SIZE, GLES20Canvas.getStencilSize(), 1354 EGL_SURFACE_TYPE, EGL_WINDOW_BIT | 1355 (dirtyRegions ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0), 1356 EGL_NONE 1357 }; 1358 } 1359 1360 @Override 1361 void initCaches() { 1362 GLES20Canvas.initCaches(); 1363 } 1364 1365 @Override 1366 boolean canDraw() { 1367 return super.canDraw() && mGlCanvas != null; 1368 } 1369 1370 @Override 1371 void onPreDraw(Rect dirty) { 1372 mGlCanvas.onPreDraw(dirty); 1373 } 1374 1375 @Override 1376 void onPostDraw() { 1377 mGlCanvas.onPostDraw(); 1378 } 1379 1380 @Override 1381 void destroy(boolean full) { 1382 try { 1383 super.destroy(full); 1384 } finally { 1385 if (full && mGlCanvas != null) { 1386 mGlCanvas = null; 1387 } 1388 } 1389 } 1390 1391 @Override 1392 void setup(int width, int height) { 1393 super.setup(width, height); 1394 if (mVsyncDisabled) { 1395 disableVsync(); 1396 } 1397 } 1398 1399 @Override 1400 public DisplayList createDisplayList(String name) { 1401 return new GLES20DisplayList(name); 1402 } 1403 1404 @Override 1405 HardwareLayer createHardwareLayer(boolean isOpaque) { 1406 return new GLES20TextureLayer(isOpaque); 1407 } 1408 1409 @Override 1410 HardwareLayer createHardwareLayer(int width, int height, boolean isOpaque) { 1411 return new GLES20RenderLayer(width, height, isOpaque); 1412 } 1413 1414 @Override 1415 SurfaceTexture createSurfaceTexture(HardwareLayer layer) { 1416 return ((GLES20TextureLayer) layer).getSurfaceTexture(); 1417 } 1418 1419 @Override 1420 void setSurfaceTexture(HardwareLayer layer, SurfaceTexture surfaceTexture) { 1421 ((GLES20TextureLayer) layer).setSurfaceTexture(surfaceTexture); 1422 } 1423 1424 @Override 1425 void destroyLayers(View view) { 1426 if (view != null && isEnabled() && checkCurrent() != SURFACE_STATE_ERROR) { 1427 destroyHardwareLayer(view); 1428 GLES20Canvas.flushCaches(GLES20Canvas.FLUSH_CACHES_LAYERS); 1429 } 1430 } 1431 1432 private static void destroyHardwareLayer(View view) { 1433 view.destroyLayer(true); 1434 1435 if (view instanceof ViewGroup) { 1436 ViewGroup group = (ViewGroup) view; 1437 1438 int count = group.getChildCount(); 1439 for (int i = 0; i < count; i++) { 1440 destroyHardwareLayer(group.getChildAt(i)); 1441 } 1442 } 1443 } 1444 1445 @Override 1446 boolean safelyRun(Runnable action) { 1447 boolean needsContext = true; 1448 if (isEnabled() && checkCurrent() != SURFACE_STATE_ERROR) needsContext = false; 1449 1450 if (needsContext) { 1451 Gl20RendererEglContext managedContext = 1452 (Gl20RendererEglContext) sEglContextStorage.get(); 1453 if (managedContext == null) return false; 1454 usePbufferSurface(managedContext.getContext()); 1455 } 1456 1457 try { 1458 action.run(); 1459 } finally { 1460 if (needsContext) { 1461 sEgl.eglMakeCurrent(sEglDisplay, EGL_NO_SURFACE, 1462 EGL_NO_SURFACE, EGL_NO_CONTEXT); 1463 } 1464 } 1465 1466 return true; 1467 } 1468 1469 @Override 1470 void destroyHardwareResources(final View view) { 1471 if (view != null) { 1472 safelyRun(new Runnable() { 1473 @Override 1474 public void run() { 1475 destroyResources(view); 1476 GLES20Canvas.flushCaches(GLES20Canvas.FLUSH_CACHES_LAYERS); 1477 } 1478 }); 1479 } 1480 } 1481 1482 private static void destroyResources(View view) { 1483 view.destroyHardwareResources(); 1484 1485 if (view instanceof ViewGroup) { 1486 ViewGroup group = (ViewGroup) view; 1487 1488 int count = group.getChildCount(); 1489 for (int i = 0; i < count; i++) { 1490 destroyResources(group.getChildAt(i)); 1491 } 1492 } 1493 } 1494 1495 static HardwareRenderer create(boolean translucent) { 1496 if (GLES20Canvas.isAvailable()) { 1497 return new Gl20Renderer(translucent); 1498 } 1499 return null; 1500 } 1501 1502 static void startTrimMemory(int level) { 1503 if (sEgl == null || sEglConfig == null) return; 1504 1505 Gl20RendererEglContext managedContext = 1506 (Gl20RendererEglContext) sEglContextStorage.get(); 1507 // We do not have OpenGL objects 1508 if (managedContext == null) { 1509 return; 1510 } else { 1511 usePbufferSurface(managedContext.getContext()); 1512 } 1513 1514 if (level >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE) { 1515 GLES20Canvas.flushCaches(GLES20Canvas.FLUSH_CACHES_FULL); 1516 } else if (level >= ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) { 1517 GLES20Canvas.flushCaches(GLES20Canvas.FLUSH_CACHES_MODERATE); 1518 } 1519 } 1520 1521 static void endTrimMemory() { 1522 if (sEgl != null && sEglDisplay != null) { 1523 sEgl.eglMakeCurrent(sEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); 1524 } 1525 } 1526 1527 private static void usePbufferSurface(EGLContext eglContext) { 1528 synchronized (sPbufferLock) { 1529 // Create a temporary 1x1 pbuffer so we have a context 1530 // to clear our OpenGL objects 1531 if (sPbuffer == null) { 1532 sPbuffer = sEgl.eglCreatePbufferSurface(sEglDisplay, sEglConfig, new int[] { 1533 EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE 1534 }); 1535 } 1536 } 1537 sEgl.eglMakeCurrent(sEglDisplay, sPbuffer, sPbuffer, eglContext); 1538 } 1539 } 1540} 1541