OpenGLRenderer.cpp revision 8df5ffa9ae0667d9e0241adf4675753156fcef84
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#include "OpenGLRenderer.h" 18 19#include "DeferredDisplayList.h" 20#include "GammaFontRenderer.h" 21#include "Glop.h" 22#include "GlopBuilder.h" 23#include "Patch.h" 24#include "PathTessellator.h" 25#include "Properties.h" 26#include "RenderNode.h" 27#include "renderstate/MeshState.h" 28#include "renderstate/RenderState.h" 29#include "ShadowTessellator.h" 30#include "SkiaShader.h" 31#include "Vector.h" 32#include "VertexBuffer.h" 33#include "utils/GLUtils.h" 34#include "utils/PaintUtils.h" 35#include "utils/TraceUtils.h" 36 37#include <stdlib.h> 38#include <stdint.h> 39#include <sys/types.h> 40 41#include <SkCanvas.h> 42#include <SkColor.h> 43#include <SkShader.h> 44#include <SkTypeface.h> 45 46#include <utils/Log.h> 47#include <utils/StopWatch.h> 48 49#include <private/hwui/DrawGlInfo.h> 50 51#include <ui/Rect.h> 52 53#if DEBUG_DETAILED_EVENTS 54 #define EVENT_LOGD(...) eventMarkDEBUG(__VA_ARGS__) 55#else 56 #define EVENT_LOGD(...) 57#endif 58 59namespace android { 60namespace uirenderer { 61 62/////////////////////////////////////////////////////////////////////////////// 63// Constructors/destructor 64/////////////////////////////////////////////////////////////////////////////// 65 66OpenGLRenderer::OpenGLRenderer(RenderState& renderState) 67 : mState(*this) 68 , mCaches(Caches::getInstance()) 69 , mRenderState(renderState) 70 , mFrameStarted(false) 71 , mScissorOptimizationDisabled(false) 72 , mSuppressTiling(false) 73 , mFirstFrameAfterResize(true) 74 , mDirty(false) 75 , mLightCenter((Vector3){FLT_MIN, FLT_MIN, FLT_MIN}) 76 , mLightRadius(FLT_MIN) 77 , mAmbientShadowAlpha(0) 78 , mSpotShadowAlpha(0) { 79} 80 81OpenGLRenderer::~OpenGLRenderer() { 82 // The context has already been destroyed at this point, do not call 83 // GL APIs. All GL state should be kept in Caches.h 84} 85 86void OpenGLRenderer::initProperties() { 87 char property[PROPERTY_VALUE_MAX]; 88 if (property_get(PROPERTY_DISABLE_SCISSOR_OPTIMIZATION, property, "false")) { 89 mScissorOptimizationDisabled = !strcasecmp(property, "true"); 90 INIT_LOGD(" Scissor optimization %s", 91 mScissorOptimizationDisabled ? "disabled" : "enabled"); 92 } else { 93 INIT_LOGD(" Scissor optimization enabled"); 94 } 95} 96 97void OpenGLRenderer::initLight(const Vector3& lightCenter, float lightRadius, 98 uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) { 99 mLightCenter = lightCenter; 100 mLightRadius = lightRadius; 101 mAmbientShadowAlpha = ambientShadowAlpha; 102 mSpotShadowAlpha = spotShadowAlpha; 103} 104 105/////////////////////////////////////////////////////////////////////////////// 106// Setup 107/////////////////////////////////////////////////////////////////////////////// 108 109void OpenGLRenderer::onViewportInitialized() { 110 glDisable(GL_DITHER); 111 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 112 mFirstFrameAfterResize = true; 113} 114 115void OpenGLRenderer::setupFrameState(float left, float top, 116 float right, float bottom, bool opaque) { 117 mCaches.clearGarbage(); 118 mState.initializeSaveStack(left, top, right, bottom, mLightCenter); 119 mOpaque = opaque; 120 mTilingClip.set(left, top, right, bottom); 121} 122 123void OpenGLRenderer::startFrame() { 124 if (mFrameStarted) return; 125 mFrameStarted = true; 126 127 mState.setDirtyClip(true); 128 129 discardFramebuffer(mTilingClip.left, mTilingClip.top, mTilingClip.right, mTilingClip.bottom); 130 131 mRenderState.setViewport(mState.getWidth(), mState.getHeight()); 132 133 // Functors break the tiling extension in pretty spectacular ways 134 // This ensures we don't use tiling when a functor is going to be 135 // invoked during the frame 136 mSuppressTiling = mCaches.hasRegisteredFunctors() 137 || mFirstFrameAfterResize; 138 mFirstFrameAfterResize = false; 139 140 startTilingCurrentClip(true); 141 142 debugOverdraw(true, true); 143 144 clear(mTilingClip.left, mTilingClip.top, 145 mTilingClip.right, mTilingClip.bottom, mOpaque); 146} 147 148void OpenGLRenderer::prepareDirty(float left, float top, 149 float right, float bottom, bool opaque) { 150 151 setupFrameState(left, top, right, bottom, opaque); 152 153 // Layer renderers will start the frame immediately 154 // The framebuffer renderer will first defer the display list 155 // for each layer and wait until the first drawing command 156 // to start the frame 157 if (currentSnapshot()->fbo == 0) { 158 mRenderState.blend().syncEnabled(); 159 updateLayers(); 160 } else { 161 startFrame(); 162 } 163} 164 165void OpenGLRenderer::discardFramebuffer(float left, float top, float right, float bottom) { 166 // If we know that we are going to redraw the entire framebuffer, 167 // perform a discard to let the driver know we don't need to preserve 168 // the back buffer for this frame. 169 if (mCaches.extensions().hasDiscardFramebuffer() && 170 left <= 0.0f && top <= 0.0f && right >= mState.getWidth() && bottom >= mState.getHeight()) { 171 const bool isFbo = getTargetFbo() == 0; 172 const GLenum attachments[] = { 173 isFbo ? (const GLenum) GL_COLOR_EXT : (const GLenum) GL_COLOR_ATTACHMENT0, 174 isFbo ? (const GLenum) GL_STENCIL_EXT : (const GLenum) GL_STENCIL_ATTACHMENT }; 175 glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments); 176 } 177} 178 179void OpenGLRenderer::clear(float left, float top, float right, float bottom, bool opaque) { 180 if (!opaque) { 181 mRenderState.scissor().setEnabled(true); 182 mRenderState.scissor().set(left, getViewportHeight() - bottom, right - left, bottom - top); 183 glClear(GL_COLOR_BUFFER_BIT); 184 mDirty = true; 185 return; 186 } 187 188 mRenderState.scissor().reset(); 189} 190 191void OpenGLRenderer::startTilingCurrentClip(bool opaque, bool expand) { 192 if (!mSuppressTiling) { 193 const Snapshot* snapshot = currentSnapshot(); 194 195 const Rect* clip = &mTilingClip; 196 if (snapshot->flags & Snapshot::kFlagFboTarget) { 197 clip = &(snapshot->layer->clipRect); 198 } 199 200 startTiling(*clip, getViewportHeight(), opaque, expand); 201 } 202} 203 204void OpenGLRenderer::startTiling(const Rect& clip, int windowHeight, bool opaque, bool expand) { 205 if (!mSuppressTiling) { 206 if(expand) { 207 // Expand the startTiling region by 1 208 int leftNotZero = (clip.left > 0) ? 1 : 0; 209 int topNotZero = (windowHeight - clip.bottom > 0) ? 1 : 0; 210 211 mCaches.startTiling( 212 clip.left - leftNotZero, 213 windowHeight - clip.bottom - topNotZero, 214 clip.right - clip.left + leftNotZero + 1, 215 clip.bottom - clip.top + topNotZero + 1, 216 opaque); 217 } else { 218 mCaches.startTiling(clip.left, windowHeight - clip.bottom, 219 clip.right - clip.left, clip.bottom - clip.top, opaque); 220 } 221 } 222} 223 224void OpenGLRenderer::endTiling() { 225 if (!mSuppressTiling) mCaches.endTiling(); 226} 227 228bool OpenGLRenderer::finish() { 229 renderOverdraw(); 230 endTiling(); 231 mTempPaths.clear(); 232 233 // When finish() is invoked on FBO 0 we've reached the end 234 // of the current frame 235 if (getTargetFbo() == 0) { 236 mCaches.pathCache.trim(); 237 mCaches.tessellationCache.trim(); 238 } 239 240 if (!suppressErrorChecks()) { 241#if DEBUG_OPENGL 242 GLUtils::dumpGLErrors(); 243#endif 244 245#if DEBUG_MEMORY_USAGE 246 mCaches.dumpMemoryUsage(); 247#else 248 if (mCaches.getDebugLevel() & kDebugMemory) { 249 mCaches.dumpMemoryUsage(); 250 } 251#endif 252 } 253 254 mFrameStarted = false; 255 256 return reportAndClearDirty(); 257} 258 259void OpenGLRenderer::resumeAfterLayer() { 260 mRenderState.setViewport(getViewportWidth(), getViewportHeight()); 261 mRenderState.bindFramebuffer(currentSnapshot()->fbo); 262 debugOverdraw(true, false); 263 264 mRenderState.scissor().reset(); 265 dirtyClip(); 266} 267 268void OpenGLRenderer::callDrawGLFunction(Functor* functor, Rect& dirty) { 269 if (mState.currentlyIgnored()) return; 270 271 Rect clip(mState.currentClipRect()); 272 clip.snapToPixelBoundaries(); 273 274 // Since we don't know what the functor will draw, let's dirty 275 // the entire clip region 276 if (hasLayer()) { 277 dirtyLayerUnchecked(clip, getRegion()); 278 } 279 280 DrawGlInfo info; 281 info.clipLeft = clip.left; 282 info.clipTop = clip.top; 283 info.clipRight = clip.right; 284 info.clipBottom = clip.bottom; 285 info.isLayer = hasLayer(); 286 info.width = getViewportWidth(); 287 info.height = getViewportHeight(); 288 currentTransform()->copyTo(&info.transform[0]); 289 290 bool prevDirtyClip = mState.getDirtyClip(); 291 // setup GL state for functor 292 if (mState.getDirtyClip()) { 293 setStencilFromClip(); // can issue draws, so must precede enableScissor()/interrupt() 294 } 295 if (mRenderState.scissor().setEnabled(true) || prevDirtyClip) { 296 setScissorFromClip(); 297 } 298 299 mRenderState.invokeFunctor(functor, DrawGlInfo::kModeDraw, &info); 300 // Scissor may have been modified, reset dirty clip 301 dirtyClip(); 302 303 mDirty = true; 304} 305 306/////////////////////////////////////////////////////////////////////////////// 307// Debug 308/////////////////////////////////////////////////////////////////////////////// 309 310void OpenGLRenderer::eventMarkDEBUG(const char* fmt, ...) const { 311#if DEBUG_DETAILED_EVENTS 312 const int BUFFER_SIZE = 256; 313 va_list ap; 314 char buf[BUFFER_SIZE]; 315 316 va_start(ap, fmt); 317 vsnprintf(buf, BUFFER_SIZE, fmt, ap); 318 va_end(ap); 319 320 eventMark(buf); 321#endif 322} 323 324 325void OpenGLRenderer::eventMark(const char* name) const { 326 mCaches.eventMark(0, name); 327} 328 329void OpenGLRenderer::startMark(const char* name) const { 330 mCaches.startMark(0, name); 331} 332 333void OpenGLRenderer::endMark() const { 334 mCaches.endMark(); 335} 336 337void OpenGLRenderer::debugOverdraw(bool enable, bool clear) { 338 mRenderState.debugOverdraw(enable, clear); 339} 340 341void OpenGLRenderer::renderOverdraw() { 342 if (mCaches.debugOverdraw && getTargetFbo() == 0) { 343 const Rect* clip = &mTilingClip; 344 345 mRenderState.scissor().setEnabled(true); 346 mRenderState.scissor().set(clip->left, 347 mState.firstSnapshot()->getViewportHeight() - clip->bottom, 348 clip->right - clip->left, 349 clip->bottom - clip->top); 350 351 // 1x overdraw 352 mRenderState.stencil().enableDebugTest(2); 353 drawColor(mCaches.getOverdrawColor(1), SkXfermode::kSrcOver_Mode); 354 355 // 2x overdraw 356 mRenderState.stencil().enableDebugTest(3); 357 drawColor(mCaches.getOverdrawColor(2), SkXfermode::kSrcOver_Mode); 358 359 // 3x overdraw 360 mRenderState.stencil().enableDebugTest(4); 361 drawColor(mCaches.getOverdrawColor(3), SkXfermode::kSrcOver_Mode); 362 363 // 4x overdraw and higher 364 mRenderState.stencil().enableDebugTest(4, true); 365 drawColor(mCaches.getOverdrawColor(4), SkXfermode::kSrcOver_Mode); 366 367 mRenderState.stencil().disable(); 368 } 369} 370 371/////////////////////////////////////////////////////////////////////////////// 372// Layers 373/////////////////////////////////////////////////////////////////////////////// 374 375bool OpenGLRenderer::updateLayer(Layer* layer, bool inFrame) { 376 if (layer->deferredUpdateScheduled && layer->renderer 377 && layer->renderNode.get() && layer->renderNode->isRenderable()) { 378 379 if (inFrame) { 380 endTiling(); 381 debugOverdraw(false, false); 382 } 383 384 if (CC_UNLIKELY(inFrame || mCaches.drawDeferDisabled)) { 385 layer->render(*this); 386 } else { 387 layer->defer(*this); 388 } 389 390 if (inFrame) { 391 resumeAfterLayer(); 392 startTilingCurrentClip(); 393 } 394 395 layer->debugDrawUpdate = mCaches.debugLayersUpdates; 396 layer->hasDrawnSinceUpdate = false; 397 398 return true; 399 } 400 401 return false; 402} 403 404void OpenGLRenderer::updateLayers() { 405 // If draw deferring is enabled this method will simply defer 406 // the display list of each individual layer. The layers remain 407 // in the layer updates list which will be cleared by flushLayers(). 408 int count = mLayerUpdates.size(); 409 if (count > 0) { 410 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) { 411 startMark("Layer Updates"); 412 } else { 413 startMark("Defer Layer Updates"); 414 } 415 416 // Note: it is very important to update the layers in order 417 for (int i = 0; i < count; i++) { 418 Layer* layer = mLayerUpdates.itemAt(i).get(); 419 updateLayer(layer, false); 420 } 421 422 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) { 423 mLayerUpdates.clear(); 424 mRenderState.bindFramebuffer(getTargetFbo()); 425 } 426 endMark(); 427 } 428} 429 430void OpenGLRenderer::flushLayers() { 431 int count = mLayerUpdates.size(); 432 if (count > 0) { 433 startMark("Apply Layer Updates"); 434 435 // Note: it is very important to update the layers in order 436 for (int i = 0; i < count; i++) { 437 mLayerUpdates.itemAt(i)->flush(); 438 } 439 440 mLayerUpdates.clear(); 441 mRenderState.bindFramebuffer(getTargetFbo()); 442 443 endMark(); 444 } 445} 446 447void OpenGLRenderer::pushLayerUpdate(Layer* layer) { 448 if (layer) { 449 // Make sure we don't introduce duplicates. 450 // SortedVector would do this automatically but we need to respect 451 // the insertion order. The linear search is not an issue since 452 // this list is usually very short (typically one item, at most a few) 453 for (int i = mLayerUpdates.size() - 1; i >= 0; i--) { 454 if (mLayerUpdates.itemAt(i) == layer) { 455 return; 456 } 457 } 458 mLayerUpdates.push_back(layer); 459 } 460} 461 462void OpenGLRenderer::cancelLayerUpdate(Layer* layer) { 463 if (layer) { 464 for (int i = mLayerUpdates.size() - 1; i >= 0; i--) { 465 if (mLayerUpdates.itemAt(i) == layer) { 466 mLayerUpdates.removeAt(i); 467 break; 468 } 469 } 470 } 471} 472 473void OpenGLRenderer::flushLayerUpdates() { 474 ATRACE_NAME("Update HW Layers"); 475 mRenderState.blend().syncEnabled(); 476 updateLayers(); 477 flushLayers(); 478 // Wait for all the layer updates to be executed 479 glFinish(); 480} 481 482void OpenGLRenderer::markLayersAsBuildLayers() { 483 for (size_t i = 0; i < mLayerUpdates.size(); i++) { 484 mLayerUpdates[i]->wasBuildLayered = true; 485 } 486} 487 488/////////////////////////////////////////////////////////////////////////////// 489// State management 490/////////////////////////////////////////////////////////////////////////////// 491 492void OpenGLRenderer::onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) { 493 bool restoreViewport = removed.flags & Snapshot::kFlagIsFboLayer; 494 bool restoreClip = removed.flags & Snapshot::kFlagClipSet; 495 bool restoreLayer = removed.flags & Snapshot::kFlagIsLayer; 496 497 if (restoreViewport) { 498 mRenderState.setViewport(getViewportWidth(), getViewportHeight()); 499 } 500 501 if (restoreClip) { 502 dirtyClip(); 503 } 504 505 if (restoreLayer) { 506 endMark(); // Savelayer 507 ATRACE_END(); // SaveLayer 508 startMark("ComposeLayer"); 509 composeLayer(removed, restored); 510 endMark(); 511 } 512} 513 514/////////////////////////////////////////////////////////////////////////////// 515// Layers 516/////////////////////////////////////////////////////////////////////////////// 517 518int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom, 519 const SkPaint* paint, int flags, const SkPath* convexMask) { 520 // force matrix/clip isolation for layer 521 flags |= SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag; 522 523 const int count = mState.saveSnapshot(flags); 524 525 if (!mState.currentlyIgnored()) { 526 createLayer(left, top, right, bottom, paint, flags, convexMask); 527 } 528 529 return count; 530} 531 532void OpenGLRenderer::calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer) { 533 const Rect untransformedBounds(bounds); 534 535 currentTransform()->mapRect(bounds); 536 537 // Layers only make sense if they are in the framebuffer's bounds 538 if (bounds.intersect(mState.currentClipRect())) { 539 // We cannot work with sub-pixels in this case 540 bounds.snapToPixelBoundaries(); 541 542 // When the layer is not an FBO, we may use glCopyTexImage so we 543 // need to make sure the layer does not extend outside the bounds 544 // of the framebuffer 545 const Snapshot& previous = *(currentSnapshot()->previous); 546 Rect previousViewport(0, 0, previous.getViewportWidth(), previous.getViewportHeight()); 547 if (!bounds.intersect(previousViewport)) { 548 bounds.setEmpty(); 549 } else if (fboLayer) { 550 clip.set(bounds); 551 mat4 inverse; 552 inverse.loadInverse(*currentTransform()); 553 inverse.mapRect(clip); 554 clip.snapToPixelBoundaries(); 555 if (clip.intersect(untransformedBounds)) { 556 clip.translate(-untransformedBounds.left, -untransformedBounds.top); 557 bounds.set(untransformedBounds); 558 } else { 559 clip.setEmpty(); 560 } 561 } 562 } else { 563 bounds.setEmpty(); 564 } 565} 566 567void OpenGLRenderer::updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip, 568 bool fboLayer, int alpha) { 569 if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize || 570 bounds.getHeight() > mCaches.maxTextureSize || 571 (fboLayer && clip.isEmpty())) { 572 writableSnapshot()->empty = fboLayer; 573 } else { 574 writableSnapshot()->invisible = writableSnapshot()->invisible || (alpha <= 0 && fboLayer); 575 } 576} 577 578int OpenGLRenderer::saveLayerDeferred(float left, float top, float right, float bottom, 579 const SkPaint* paint, int flags) { 580 const int count = mState.saveSnapshot(flags); 581 582 if (!mState.currentlyIgnored() && (flags & SkCanvas::kClipToLayer_SaveFlag)) { 583 // initialize the snapshot as though it almost represents an FBO layer so deferred draw 584 // operations will be able to store and restore the current clip and transform info, and 585 // quick rejection will be correct (for display lists) 586 587 Rect bounds(left, top, right, bottom); 588 Rect clip; 589 calculateLayerBoundsAndClip(bounds, clip, true); 590 updateSnapshotIgnoreForLayer(bounds, clip, true, getAlphaDirect(paint)); 591 592 if (!mState.currentlyIgnored()) { 593 writableSnapshot()->resetTransform(-bounds.left, -bounds.top, 0.0f); 594 writableSnapshot()->resetClip(clip.left, clip.top, clip.right, clip.bottom); 595 writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight()); 596 writableSnapshot()->roundRectClipState = nullptr; 597 } 598 } 599 600 return count; 601} 602 603/** 604 * Layers are viewed by Skia are slightly different than layers in image editing 605 * programs (for instance.) When a layer is created, previously created layers 606 * and the frame buffer still receive every drawing command. For instance, if a 607 * layer is created and a shape intersecting the bounds of the layers and the 608 * framebuffer is draw, the shape will be drawn on both (unless the layer was 609 * created with the SkCanvas::kClipToLayer_SaveFlag flag.) 610 * 611 * A way to implement layers is to create an FBO for each layer, backed by an RGBA 612 * texture. Unfortunately, this is inefficient as it requires every primitive to 613 * be drawn n + 1 times, where n is the number of active layers. In practice this 614 * means, for every primitive: 615 * - Switch active frame buffer 616 * - Change viewport, clip and projection matrix 617 * - Issue the drawing 618 * 619 * Switching rendering target n + 1 times per drawn primitive is extremely costly. 620 * To avoid this, layers are implemented in a different way here, at least in the 621 * general case. FBOs are used, as an optimization, when the "clip to layer" flag 622 * is set. When this flag is set we can redirect all drawing operations into a 623 * single FBO. 624 * 625 * This implementation relies on the frame buffer being at least RGBA 8888. When 626 * a layer is created, only a texture is created, not an FBO. The content of the 627 * frame buffer contained within the layer's bounds is copied into this texture 628 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame 629 * buffer and drawing continues as normal. This technique therefore treats the 630 * frame buffer as a scratch buffer for the layers. 631 * 632 * To compose the layers back onto the frame buffer, each layer texture 633 * (containing the original frame buffer data) is drawn as a simple quad over 634 * the frame buffer. The trick is that the quad is set as the composition 635 * destination in the blending equation, and the frame buffer becomes the source 636 * of the composition. 637 * 638 * Drawing layers with an alpha value requires an extra step before composition. 639 * An empty quad is drawn over the layer's region in the frame buffer. This quad 640 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the 641 * quad is used to multiply the colors in the frame buffer. This is achieved by 642 * changing the GL blend functions for the GL_FUNC_ADD blend equation to 643 * GL_ZERO, GL_SRC_ALPHA. 644 * 645 * Because glCopyTexImage2D() can be slow, an alternative implementation might 646 * be use to draw a single clipped layer. The implementation described above 647 * is correct in every case. 648 * 649 * (1) The frame buffer is actually not cleared right away. To allow the GPU 650 * to potentially optimize series of calls to glCopyTexImage2D, the frame 651 * buffer is left untouched until the first drawing operation. Only when 652 * something actually gets drawn are the layers regions cleared. 653 */ 654bool OpenGLRenderer::createLayer(float left, float top, float right, float bottom, 655 const SkPaint* paint, int flags, const SkPath* convexMask) { 656 LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top); 657 LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize()); 658 659 const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag; 660 661 // Window coordinates of the layer 662 Rect clip; 663 Rect bounds(left, top, right, bottom); 664 calculateLayerBoundsAndClip(bounds, clip, fboLayer); 665 updateSnapshotIgnoreForLayer(bounds, clip, fboLayer, getAlphaDirect(paint)); 666 667 // Bail out if we won't draw in this snapshot 668 if (mState.currentlyIgnored()) { 669 return false; 670 } 671 672 mCaches.textureState().activateTexture(0); 673 Layer* layer = mCaches.layerCache.get(mRenderState, bounds.getWidth(), bounds.getHeight()); 674 if (!layer) { 675 return false; 676 } 677 678 layer->setPaint(paint); 679 layer->layer.set(bounds); 680 layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->getHeight()), 681 bounds.getWidth() / float(layer->getWidth()), 0.0f); 682 683 layer->setBlend(true); 684 layer->setDirty(false); 685 layer->setConvexMask(convexMask); // note: the mask must be cleared before returning to the cache 686 687 // Save the layer in the snapshot 688 writableSnapshot()->flags |= Snapshot::kFlagIsLayer; 689 writableSnapshot()->layer = layer; 690 691 ATRACE_FORMAT_BEGIN("%ssaveLayer %ux%u", 692 fboLayer ? "" : "unclipped ", 693 layer->getWidth(), layer->getHeight()); 694 startMark("SaveLayer"); 695 if (fboLayer) { 696 return createFboLayer(layer, bounds, clip); 697 } else { 698 // Copy the framebuffer into the layer 699 layer->bindTexture(); 700 if (!bounds.isEmpty()) { 701 if (layer->isEmpty()) { 702 // Workaround for some GL drivers. When reading pixels lying outside 703 // of the window we should get undefined values for those pixels. 704 // Unfortunately some drivers will turn the entire target texture black 705 // when reading outside of the window. 706 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->getWidth(), layer->getHeight(), 707 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); 708 layer->setEmpty(false); 709 } 710 711 glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 712 bounds.left, getViewportHeight() - bounds.bottom, 713 bounds.getWidth(), bounds.getHeight()); 714 715 // Enqueue the buffer coordinates to clear the corresponding region later 716 mLayers.push_back(Rect(bounds)); 717 } 718 } 719 720 return true; 721} 722 723bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, Rect& clip) { 724 layer->clipRect.set(clip); 725 layer->setFbo(mCaches.fboCache.get()); 726 727 writableSnapshot()->region = &writableSnapshot()->layer->region; 728 writableSnapshot()->flags |= Snapshot::kFlagFboTarget | Snapshot::kFlagIsFboLayer; 729 writableSnapshot()->fbo = layer->getFbo(); 730 writableSnapshot()->resetTransform(-bounds.left, -bounds.top, 0.0f); 731 writableSnapshot()->resetClip(clip.left, clip.top, clip.right, clip.bottom); 732 writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight()); 733 writableSnapshot()->roundRectClipState = nullptr; 734 735 endTiling(); 736 debugOverdraw(false, false); 737 // Bind texture to FBO 738 mRenderState.bindFramebuffer(layer->getFbo()); 739 layer->bindTexture(); 740 741 // Initialize the texture if needed 742 if (layer->isEmpty()) { 743 layer->allocateTexture(); 744 layer->setEmpty(false); 745 } 746 747 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 748 layer->getTextureId(), 0); 749 750 // Expand the startTiling region by 1 751 startTilingCurrentClip(true, true); 752 753 // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering 754 mRenderState.scissor().setEnabled(true); 755 mRenderState.scissor().set(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f, 756 clip.getWidth() + 2.0f, clip.getHeight() + 2.0f); 757 glClear(GL_COLOR_BUFFER_BIT); 758 759 dirtyClip(); 760 761 // Change the ortho projection 762 mRenderState.setViewport(bounds.getWidth(), bounds.getHeight()); 763 return true; 764} 765 766/** 767 * Read the documentation of createLayer() before doing anything in this method. 768 */ 769void OpenGLRenderer::composeLayer(const Snapshot& removed, const Snapshot& restored) { 770 if (!removed.layer) { 771 ALOGE("Attempting to compose a layer that does not exist"); 772 return; 773 } 774 775 Layer* layer = removed.layer; 776 const Rect& rect = layer->layer; 777 const bool fboLayer = removed.flags & Snapshot::kFlagIsFboLayer; 778 779 bool clipRequired = false; 780 mState.calculateQuickRejectForScissor(rect.left, rect.top, rect.right, rect.bottom, 781 &clipRequired, nullptr, false); // safely ignore return, should never be rejected 782 mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired); 783 784 if (fboLayer) { 785 endTiling(); 786 787 // Detach the texture from the FBO 788 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); 789 790 layer->removeFbo(false); 791 792 // Unbind current FBO and restore previous one 793 mRenderState.bindFramebuffer(restored.fbo); 794 debugOverdraw(true, false); 795 796 startTilingCurrentClip(); 797 } 798 799 if (!fboLayer && layer->getAlpha() < 255) { 800 SkPaint layerPaint; 801 layerPaint.setAlpha(layer->getAlpha()); 802 layerPaint.setXfermodeMode(SkXfermode::kDstIn_Mode); 803 layerPaint.setColorFilter(layer->getColorFilter()); 804 805 drawColorRect(rect.left, rect.top, rect.right, rect.bottom, &layerPaint, true); 806 // Required below, composeLayerRect() will divide by 255 807 layer->setAlpha(255); 808 } 809 810 mRenderState.meshState().unbindMeshBuffer(); 811 812 mCaches.textureState().activateTexture(0); 813 814 // When the layer is stored in an FBO, we can save a bit of fillrate by 815 // drawing only the dirty region 816 if (fboLayer) { 817 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *restored.transform); 818 composeLayerRegion(layer, rect); 819 } else if (!rect.isEmpty()) { 820 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom); 821 822 save(0); 823 // the layer contains screen buffer content that shouldn't be alpha modulated 824 // (and any necessary alpha modulation was handled drawing into the layer) 825 writableSnapshot()->alpha = 1.0f; 826 composeLayerRect(layer, rect, true); 827 restore(); 828 } 829 830 dirtyClip(); 831 832 // Failing to add the layer to the cache should happen only if the layer is too large 833 layer->setConvexMask(nullptr); 834 if (!mCaches.layerCache.put(layer)) { 835 LAYER_LOGD("Deleting layer"); 836 layer->decStrong(nullptr); 837 } 838} 839 840void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) { 841 bool snap = !layer->getForceFilter() 842 && layer->getWidth() == (uint32_t) rect.getWidth() 843 && layer->getHeight() == (uint32_t) rect.getHeight(); 844 Glop glop; 845 GlopBuilder(mRenderState, mCaches, &glop) 846 .setMeshTexturedUvQuad(nullptr, Rect(0, 1, 1, 0)) // TODO: simplify with VBO 847 .setFillTextureLayer(*layer, getLayerAlpha(layer)) 848 .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false) 849 .setModelViewMapUnitToRectOptionalSnap(snap, rect) 850 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 851 .build(); 852 renderGlop(glop); 853} 854 855void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) { 856 if (layer->isTextureLayer()) { 857 EVENT_LOGD("composeTextureLayerRect"); 858 drawTextureLayer(layer, rect); 859 } else { 860 EVENT_LOGD("composeHardwareLayerRect"); 861 862 Blend::ModeOrderSwap modeUsage = swap ? 863 Blend::ModeOrderSwap::Swap : Blend::ModeOrderSwap::NoSwap; 864 const Matrix4& transform = swap ? Matrix4::identity() : *currentTransform(); 865 bool snap = !swap 866 && layer->getWidth() == static_cast<uint32_t>(rect.getWidth()) 867 && layer->getHeight() == static_cast<uint32_t>(rect.getHeight()); 868 Glop glop; 869 GlopBuilder(mRenderState, mCaches, &glop) 870 .setMeshTexturedUvQuad(nullptr, layer->texCoords) 871 .setFillLayer(layer->getTexture(), layer->getColorFilter(), getLayerAlpha(layer), layer->getMode(), modeUsage) 872 .setTransform(currentSnapshot()->getOrthoMatrix(), transform, false) 873 .setModelViewMapUnitToRectOptionalSnap(snap, rect) 874 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 875 .build(); 876 renderGlop(glop); 877 } 878} 879 880/** 881 * Issues the command X, and if we're composing a save layer to the fbo or drawing a newly updated 882 * hardware layer with overdraw debug on, draws again to the stencil only, so that these draw 883 * operations are correctly counted twice for overdraw. NOTE: assumes composeLayerRegion only used 884 * by saveLayer's restore 885 */ 886#define DRAW_DOUBLE_STENCIL_IF(COND, DRAW_COMMAND) { \ 887 DRAW_COMMAND; \ 888 if (CC_UNLIKELY(mCaches.debugOverdraw && getTargetFbo() == 0 && COND)) { \ 889 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); \ 890 DRAW_COMMAND; \ 891 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); \ 892 } \ 893 } 894 895#define DRAW_DOUBLE_STENCIL(DRAW_COMMAND) DRAW_DOUBLE_STENCIL_IF(true, DRAW_COMMAND) 896 897// This class is purely for inspection. It inherits from SkShader, but Skia does not know how to 898// use it. The OpenGLRenderer will look at it to find its Layer and whether it is opaque. 899class LayerShader : public SkShader { 900public: 901 LayerShader(Layer* layer, const SkMatrix* localMatrix) 902 : INHERITED(localMatrix) 903 , mLayer(layer) { 904 } 905 906 virtual bool asACustomShader(void** data) const override { 907 if (data) { 908 *data = static_cast<void*>(mLayer); 909 } 910 return true; 911 } 912 913 virtual bool isOpaque() const override { 914 return !mLayer->isBlend(); 915 } 916 917protected: 918 virtual void shadeSpan(int x, int y, SkPMColor[], int count) { 919 LOG_ALWAYS_FATAL("LayerShader should never be drawn with raster backend."); 920 } 921 922 virtual void flatten(SkWriteBuffer&) const override { 923 LOG_ALWAYS_FATAL("LayerShader should never be flattened."); 924 } 925 926 virtual Factory getFactory() const override { 927 LOG_ALWAYS_FATAL("LayerShader should never be created from a stream."); 928 return nullptr; 929 } 930private: 931 // Unowned. 932 Layer* mLayer; 933 typedef SkShader INHERITED; 934}; 935 936void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) { 937 if (CC_UNLIKELY(layer->region.isEmpty())) return; // nothing to draw 938 939 if (layer->getConvexMask()) { 940 save(SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag); 941 942 // clip to the area of the layer the mask can be larger 943 clipRect(rect.left, rect.top, rect.right, rect.bottom, SkRegion::kIntersect_Op); 944 945 SkPaint paint; 946 paint.setAntiAlias(true); 947 paint.setColor(SkColorSetARGB(int(getLayerAlpha(layer) * 255), 0, 0, 0)); 948 949 // create LayerShader to map SaveLayer content into subsequent draw 950 SkMatrix shaderMatrix; 951 shaderMatrix.setTranslate(rect.left, rect.bottom); 952 shaderMatrix.preScale(1, -1); 953 LayerShader layerShader(layer, &shaderMatrix); 954 paint.setShader(&layerShader); 955 956 // Since the drawing primitive is defined in local drawing space, 957 // we don't need to modify the draw matrix 958 const SkPath* maskPath = layer->getConvexMask(); 959 DRAW_DOUBLE_STENCIL(drawConvexPath(*maskPath, &paint)); 960 961 paint.setShader(nullptr); 962 restore(); 963 964 return; 965 } 966 967 if (layer->region.isRect()) { 968 layer->setRegionAsRect(); 969 970 DRAW_DOUBLE_STENCIL(composeLayerRect(layer, layer->regionRect)); 971 972 layer->region.clear(); 973 return; 974 } 975 976 EVENT_LOGD("composeLayerRegion"); 977 // standard Region based draw 978 size_t count; 979 const android::Rect* rects; 980 Region safeRegion; 981 if (CC_LIKELY(hasRectToRectTransform())) { 982 rects = layer->region.getArray(&count); 983 } else { 984 safeRegion = Region::createTJunctionFreeRegion(layer->region); 985 rects = safeRegion.getArray(&count); 986 } 987 988 const float texX = 1.0f / float(layer->getWidth()); 989 const float texY = 1.0f / float(layer->getHeight()); 990 const float height = rect.getHeight(); 991 992 TextureVertex quadVertices[count * 4]; 993 TextureVertex* mesh = &quadVertices[0]; 994 for (size_t i = 0; i < count; i++) { 995 const android::Rect* r = &rects[i]; 996 997 const float u1 = r->left * texX; 998 const float v1 = (height - r->top) * texY; 999 const float u2 = r->right * texX; 1000 const float v2 = (height - r->bottom) * texY; 1001 1002 // TODO: Reject quads outside of the clip 1003 TextureVertex::set(mesh++, r->left, r->top, u1, v1); 1004 TextureVertex::set(mesh++, r->right, r->top, u2, v1); 1005 TextureVertex::set(mesh++, r->left, r->bottom, u1, v2); 1006 TextureVertex::set(mesh++, r->right, r->bottom, u2, v2); 1007 } 1008 Rect modelRect = Rect(rect.getWidth(), rect.getHeight()); 1009 Glop glop; 1010 GlopBuilder(mRenderState, mCaches, &glop) 1011 .setMeshTexturedIndexedQuads(&quadVertices[0], count * 6) 1012 .setFillLayer(layer->getTexture(), layer->getColorFilter(), getLayerAlpha(layer), layer->getMode(), Blend::ModeOrderSwap::NoSwap) 1013 .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false) 1014 .setModelViewOffsetRectSnap(rect.left, rect.top, modelRect) 1015 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1016 .build(); 1017 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, renderGlop(glop)); 1018 1019#if DEBUG_LAYERS_AS_REGIONS 1020 drawRegionRectsDebug(layer->region); 1021#endif 1022 1023 layer->region.clear(); 1024} 1025 1026#if DEBUG_LAYERS_AS_REGIONS 1027void OpenGLRenderer::drawRegionRectsDebug(const Region& region) { 1028 size_t count; 1029 const android::Rect* rects = region.getArray(&count); 1030 1031 uint32_t colors[] = { 1032 0x7fff0000, 0x7f00ff00, 1033 0x7f0000ff, 0x7fff00ff, 1034 }; 1035 1036 int offset = 0; 1037 int32_t top = rects[0].top; 1038 1039 for (size_t i = 0; i < count; i++) { 1040 if (top != rects[i].top) { 1041 offset ^= 0x2; 1042 top = rects[i].top; 1043 } 1044 1045 SkPaint paint; 1046 paint.setColor(colors[offset + (i & 0x1)]); 1047 Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom); 1048 drawColorRect(r.left, r.top, r.right, r.bottom, paint); 1049 } 1050} 1051#endif 1052 1053void OpenGLRenderer::drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty) { 1054 Vector<float> rects; 1055 1056 SkRegion::Iterator it(region); 1057 while (!it.done()) { 1058 const SkIRect& r = it.rect(); 1059 rects.push(r.fLeft); 1060 rects.push(r.fTop); 1061 rects.push(r.fRight); 1062 rects.push(r.fBottom); 1063 it.next(); 1064 } 1065 1066 drawColorRects(rects.array(), rects.size(), &paint, true, dirty, false); 1067} 1068 1069void OpenGLRenderer::dirtyLayer(const float left, const float top, 1070 const float right, const float bottom, const Matrix4& transform) { 1071 if (hasLayer()) { 1072 Rect bounds(left, top, right, bottom); 1073 transform.mapRect(bounds); 1074 dirtyLayerUnchecked(bounds, getRegion()); 1075 } 1076} 1077 1078void OpenGLRenderer::dirtyLayer(const float left, const float top, 1079 const float right, const float bottom) { 1080 if (hasLayer()) { 1081 Rect bounds(left, top, right, bottom); 1082 dirtyLayerUnchecked(bounds, getRegion()); 1083 } 1084} 1085 1086void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) { 1087 if (bounds.intersect(mState.currentClipRect())) { 1088 bounds.snapToPixelBoundaries(); 1089 android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom); 1090 if (!dirty.isEmpty()) { 1091 region->orSelf(dirty); 1092 } 1093 } 1094} 1095 1096void OpenGLRenderer::clearLayerRegions() { 1097 const size_t quadCount = mLayers.size(); 1098 if (quadCount == 0) return; 1099 1100 if (!mState.currentlyIgnored()) { 1101 EVENT_LOGD("clearLayerRegions"); 1102 // Doing several glScissor/glClear here can negatively impact 1103 // GPUs with a tiler architecture, instead we draw quads with 1104 // the Clear blending mode 1105 1106 // The list contains bounds that have already been clipped 1107 // against their initial clip rect, and the current clip 1108 // is likely different so we need to disable clipping here 1109 bool scissorChanged = mRenderState.scissor().setEnabled(false); 1110 1111 Vertex mesh[quadCount * 4]; 1112 Vertex* vertex = mesh; 1113 1114 for (uint32_t i = 0; i < quadCount; i++) { 1115 const Rect& bounds = mLayers[i]; 1116 1117 Vertex::set(vertex++, bounds.left, bounds.top); 1118 Vertex::set(vertex++, bounds.right, bounds.top); 1119 Vertex::set(vertex++, bounds.left, bounds.bottom); 1120 Vertex::set(vertex++, bounds.right, bounds.bottom); 1121 } 1122 // We must clear the list of dirty rects before we 1123 // call clearLayerRegions() in renderGlop to prevent 1124 // stencil setup from doing the same thing again 1125 mLayers.clear(); 1126 1127 Glop glop; 1128 GlopBuilder(mRenderState, mCaches, &glop) 1129 .setMeshIndexedQuads(&mesh[0], quadCount) 1130 .setFillClear() 1131 .setTransform(currentSnapshot()->getOrthoMatrix(), Matrix4::identity(), false) 1132 .setModelViewOffsetRect(0, 0, Rect(currentSnapshot()->getClipRect())) 1133 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1134 .build(); 1135 renderGlop(glop, false); 1136 1137 if (scissorChanged) mRenderState.scissor().setEnabled(true); 1138 } else { 1139 mLayers.clear(); 1140 } 1141} 1142 1143/////////////////////////////////////////////////////////////////////////////// 1144// State Deferral 1145/////////////////////////////////////////////////////////////////////////////// 1146 1147bool OpenGLRenderer::storeDisplayState(DeferredDisplayState& state, int stateDeferFlags) { 1148 const Rect& currentClip = mState.currentClipRect(); 1149 const mat4* currentMatrix = currentTransform(); 1150 1151 if (stateDeferFlags & kStateDeferFlag_Draw) { 1152 // state has bounds initialized in local coordinates 1153 if (!state.mBounds.isEmpty()) { 1154 currentMatrix->mapRect(state.mBounds); 1155 Rect clippedBounds(state.mBounds); 1156 // NOTE: if we ever want to use this clipping info to drive whether the scissor 1157 // is used, it should more closely duplicate the quickReject logic (in how it uses 1158 // snapToPixelBoundaries) 1159 1160 if (!clippedBounds.intersect(currentClip)) { 1161 // quick rejected 1162 return true; 1163 } 1164 1165 state.mClipSideFlags = kClipSide_None; 1166 if (!currentClip.contains(state.mBounds)) { 1167 int& flags = state.mClipSideFlags; 1168 // op partially clipped, so record which sides are clipped for clip-aware merging 1169 if (currentClip.left > state.mBounds.left) flags |= kClipSide_Left; 1170 if (currentClip.top > state.mBounds.top) flags |= kClipSide_Top; 1171 if (currentClip.right < state.mBounds.right) flags |= kClipSide_Right; 1172 if (currentClip.bottom < state.mBounds.bottom) flags |= kClipSide_Bottom; 1173 } 1174 state.mBounds.set(clippedBounds); 1175 } else { 1176 // Empty bounds implies size unknown. Label op as conservatively clipped to disable 1177 // overdraw avoidance (since we don't know what it overlaps) 1178 state.mClipSideFlags = kClipSide_ConservativeFull; 1179 state.mBounds.set(currentClip); 1180 } 1181 } 1182 1183 state.mClipValid = (stateDeferFlags & kStateDeferFlag_Clip); 1184 if (state.mClipValid) { 1185 state.mClip.set(currentClip); 1186 } 1187 1188 // Transform and alpha always deferred, since they are used by state operations 1189 // (Note: saveLayer/restore use colorFilter and alpha, so we just save restore everything) 1190 state.mMatrix.load(*currentMatrix); 1191 state.mAlpha = currentSnapshot()->alpha; 1192 1193 // always store/restore, since it's just a pointer 1194 state.mRoundRectClipState = currentSnapshot()->roundRectClipState; 1195 return false; 1196} 1197 1198void OpenGLRenderer::restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore) { 1199 setMatrix(state.mMatrix); 1200 writableSnapshot()->alpha = state.mAlpha; 1201 writableSnapshot()->roundRectClipState = state.mRoundRectClipState; 1202 1203 if (state.mClipValid && !skipClipRestore) { 1204 writableSnapshot()->setClip(state.mClip.left, state.mClip.top, 1205 state.mClip.right, state.mClip.bottom); 1206 dirtyClip(); 1207 } 1208} 1209 1210/** 1211 * Merged multidraw (such as in drawText and drawBitmaps rely on the fact that no clipping is done 1212 * in the draw path. Instead, clipping is done ahead of time - either as a single clip rect (when at 1213 * least one op is clipped), or disabled entirely (because no merged op is clipped) 1214 * 1215 * This method should be called when restoreDisplayState() won't be restoring the clip 1216 */ 1217void OpenGLRenderer::setupMergedMultiDraw(const Rect* clipRect) { 1218 if (clipRect != nullptr) { 1219 writableSnapshot()->setClip(clipRect->left, clipRect->top, clipRect->right, clipRect->bottom); 1220 } else { 1221 writableSnapshot()->setClip(0, 0, mState.getWidth(), mState.getHeight()); 1222 } 1223 dirtyClip(); 1224 bool enableScissor = (clipRect != nullptr) || mScissorOptimizationDisabled; 1225 mRenderState.scissor().setEnabled(enableScissor); 1226} 1227 1228/////////////////////////////////////////////////////////////////////////////// 1229// Clipping 1230/////////////////////////////////////////////////////////////////////////////// 1231 1232void OpenGLRenderer::setScissorFromClip() { 1233 Rect clip(mState.currentClipRect()); 1234 clip.snapToPixelBoundaries(); 1235 1236 if (mRenderState.scissor().set(clip.left, getViewportHeight() - clip.bottom, 1237 clip.getWidth(), clip.getHeight())) { 1238 mState.setDirtyClip(false); 1239 } 1240} 1241 1242void OpenGLRenderer::ensureStencilBuffer() { 1243 // Thanks to the mismatch between EGL and OpenGL ES FBO we 1244 // cannot attach a stencil buffer to fbo0 dynamically. Let's 1245 // just hope we have one when hasLayer() returns false. 1246 if (hasLayer()) { 1247 attachStencilBufferToLayer(currentSnapshot()->layer); 1248 } 1249} 1250 1251void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) { 1252 // The layer's FBO is already bound when we reach this stage 1253 if (!layer->getStencilRenderBuffer()) { 1254 // GL_QCOM_tiled_rendering doesn't like it if a renderbuffer 1255 // is attached after we initiated tiling. We must turn it off, 1256 // attach the new render buffer then turn tiling back on 1257 endTiling(); 1258 1259 RenderBuffer* buffer = mCaches.renderBufferCache.get( 1260 Stencil::getSmallestStencilFormat(), 1261 layer->getWidth(), layer->getHeight()); 1262 layer->setStencilRenderBuffer(buffer); 1263 1264 startTiling(layer->clipRect, layer->layer.getHeight()); 1265 } 1266} 1267 1268static void handlePoint(std::vector<Vertex>& rectangleVertices, const Matrix4& transform, 1269 float x, float y) { 1270 Vertex v; 1271 v.x = x; 1272 v.y = y; 1273 transform.mapPoint(v.x, v.y); 1274 rectangleVertices.push_back(v); 1275} 1276 1277static void handlePointNoTransform(std::vector<Vertex>& rectangleVertices, float x, float y) { 1278 Vertex v; 1279 v.x = x; 1280 v.y = y; 1281 rectangleVertices.push_back(v); 1282} 1283 1284void OpenGLRenderer::drawRectangleList(const RectangleList& rectangleList) { 1285 int quadCount = rectangleList.getTransformedRectanglesCount(); 1286 std::vector<Vertex> rectangleVertices(quadCount * 4); 1287 Rect scissorBox = rectangleList.calculateBounds(); 1288 scissorBox.snapToPixelBoundaries(); 1289 for (int i = 0; i < quadCount; ++i) { 1290 const TransformedRectangle& tr(rectangleList.getTransformedRectangle(i)); 1291 const Matrix4& transform = tr.getTransform(); 1292 Rect bounds = tr.getBounds(); 1293 if (transform.rectToRect()) { 1294 transform.mapRect(bounds); 1295 if (!bounds.intersect(scissorBox)) { 1296 bounds.setEmpty(); 1297 } else { 1298 handlePointNoTransform(rectangleVertices, bounds.left, bounds.top); 1299 handlePointNoTransform(rectangleVertices, bounds.right, bounds.top); 1300 handlePointNoTransform(rectangleVertices, bounds.left, bounds.bottom); 1301 handlePointNoTransform(rectangleVertices, bounds.right, bounds.bottom); 1302 } 1303 } else { 1304 handlePoint(rectangleVertices, transform, bounds.left, bounds.top); 1305 handlePoint(rectangleVertices, transform, bounds.right, bounds.top); 1306 handlePoint(rectangleVertices, transform, bounds.left, bounds.bottom); 1307 handlePoint(rectangleVertices, transform, bounds.right, bounds.bottom); 1308 } 1309 } 1310 1311 mRenderState.scissor().set(scissorBox.left, getViewportHeight() - scissorBox.bottom, 1312 scissorBox.getWidth(), scissorBox.getHeight()); 1313 1314 Glop glop; 1315 Vertex* vertices = &rectangleVertices[0]; 1316 GlopBuilder(mRenderState, mCaches, &glop) 1317 .setMeshIndexedQuads(vertices, rectangleVertices.size() / 4) 1318 .setFillBlack() 1319 .setTransform(currentSnapshot()->getOrthoMatrix(), Matrix4::identity(), false) 1320 .setModelViewOffsetRect(0, 0, scissorBox) 1321 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1322 .build(); 1323 renderGlop(glop); 1324} 1325 1326void OpenGLRenderer::setStencilFromClip() { 1327 if (!mCaches.debugOverdraw) { 1328 if (!currentSnapshot()->clipIsSimple()) { 1329 int incrementThreshold; 1330 EVENT_LOGD("setStencilFromClip - enabling"); 1331 1332 // NOTE: The order here is important, we must set dirtyClip to false 1333 // before any draw call to avoid calling back into this method 1334 mState.setDirtyClip(false); 1335 1336 ensureStencilBuffer(); 1337 1338 const ClipArea& clipArea = currentSnapshot()->getClipArea(); 1339 1340 bool isRectangleList = clipArea.isRectangleList(); 1341 if (isRectangleList) { 1342 incrementThreshold = clipArea.getRectangleList().getTransformedRectanglesCount(); 1343 } else { 1344 incrementThreshold = 0; 1345 } 1346 1347 mRenderState.stencil().enableWrite(incrementThreshold); 1348 1349 // Clean and update the stencil, but first make sure we restrict drawing 1350 // to the region's bounds 1351 bool resetScissor = mRenderState.scissor().setEnabled(true); 1352 if (resetScissor) { 1353 // The scissor was not set so we now need to update it 1354 setScissorFromClip(); 1355 } 1356 1357 mRenderState.stencil().clear(); 1358 1359 // stash and disable the outline clip state, since stencil doesn't account for outline 1360 bool storedSkipOutlineClip = mSkipOutlineClip; 1361 mSkipOutlineClip = true; 1362 1363 SkPaint paint; 1364 paint.setColor(SK_ColorBLACK); 1365 paint.setXfermodeMode(SkXfermode::kSrc_Mode); 1366 1367 if (isRectangleList) { 1368 drawRectangleList(clipArea.getRectangleList()); 1369 } else { 1370 // NOTE: We could use the region contour path to generate a smaller mesh 1371 // Since we are using the stencil we could use the red book path 1372 // drawing technique. It might increase bandwidth usage though. 1373 1374 // The last parameter is important: we are not drawing in the color buffer 1375 // so we don't want to dirty the current layer, if any 1376 drawRegionRects(clipArea.getClipRegion(), paint, false); 1377 } 1378 if (resetScissor) mRenderState.scissor().setEnabled(false); 1379 mSkipOutlineClip = storedSkipOutlineClip; 1380 1381 mRenderState.stencil().enableTest(incrementThreshold); 1382 1383 // Draw the region used to generate the stencil if the appropriate debug 1384 // mode is enabled 1385 // TODO: Implement for rectangle list clip areas 1386 if (mCaches.debugStencilClip == Caches::kStencilShowRegion && 1387 !clipArea.isRectangleList()) { 1388 paint.setColor(0x7f0000ff); 1389 paint.setXfermodeMode(SkXfermode::kSrcOver_Mode); 1390 drawRegionRects(currentSnapshot()->getClipRegion(), paint); 1391 } 1392 } else { 1393 EVENT_LOGD("setStencilFromClip - disabling"); 1394 mRenderState.stencil().disable(); 1395 } 1396 } 1397} 1398 1399/** 1400 * Returns false and sets scissor enable based upon bounds if drawing won't be clipped out. 1401 * 1402 * @param paint if not null, the bounds will be expanded to account for stroke depending on paint 1403 * style, and tessellated AA ramp 1404 */ 1405bool OpenGLRenderer::quickRejectSetupScissor(float left, float top, float right, float bottom, 1406 const SkPaint* paint) { 1407 bool snapOut = paint && paint->isAntiAlias(); 1408 1409 if (paint && paint->getStyle() != SkPaint::kFill_Style) { 1410 float outset = paint->getStrokeWidth() * 0.5f; 1411 left -= outset; 1412 top -= outset; 1413 right += outset; 1414 bottom += outset; 1415 } 1416 1417 bool clipRequired = false; 1418 bool roundRectClipRequired = false; 1419 if (mState.calculateQuickRejectForScissor(left, top, right, bottom, 1420 &clipRequired, &roundRectClipRequired, snapOut)) { 1421 return true; 1422 } 1423 1424 // not quick rejected, so enable the scissor if clipRequired 1425 mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired); 1426 mSkipOutlineClip = !roundRectClipRequired; 1427 return false; 1428} 1429 1430void OpenGLRenderer::debugClip() { 1431#if DEBUG_CLIP_REGIONS 1432 if (!currentSnapshot()->clipRegion->isEmpty()) { 1433 SkPaint paint; 1434 paint.setColor(0x7f00ff00); 1435 drawRegionRects(*(currentSnapshot()->clipRegion, paint); 1436 1437 } 1438#endif 1439} 1440 1441void OpenGLRenderer::renderGlop(const Glop& glop, bool clearLayer) { 1442 // TODO: It would be best if we could do this before quickRejectSetupScissor() 1443 // changes the scissor test state 1444 if (clearLayer) clearLayerRegions(); 1445 1446 if (mState.getDirtyClip()) { 1447 if (mRenderState.scissor().isEnabled()) { 1448 setScissorFromClip(); 1449 } 1450 1451 setStencilFromClip(); 1452 } 1453 mRenderState.render(glop); 1454 if (!mRenderState.stencil().isWriteEnabled()) { 1455 // TODO: specify more clearly when a draw should dirty the layer. 1456 // is writing to the stencil the only time we should ignore this? 1457 dirtyLayer(glop.bounds.left, glop.bounds.top, glop.bounds.right, glop.bounds.bottom); 1458 mDirty = true; 1459 } 1460} 1461 1462/////////////////////////////////////////////////////////////////////////////// 1463// Drawing 1464/////////////////////////////////////////////////////////////////////////////// 1465 1466void OpenGLRenderer::drawRenderNode(RenderNode* renderNode, Rect& dirty, int32_t replayFlags) { 1467 // All the usual checks and setup operations (quickReject, setupDraw, etc.) 1468 // will be performed by the display list itself 1469 if (renderNode && renderNode->isRenderable()) { 1470 // compute 3d ordering 1471 renderNode->computeOrdering(); 1472 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) { 1473 startFrame(); 1474 ReplayStateStruct replayStruct(*this, dirty, replayFlags); 1475 renderNode->replay(replayStruct, 0); 1476 return; 1477 } 1478 1479 // Don't avoid overdraw when visualizing, since that makes it harder to 1480 // debug where it's coming from, and when the problem occurs. 1481 bool avoidOverdraw = !mCaches.debugOverdraw; 1482 DeferredDisplayList deferredList(mState.currentClipRect(), avoidOverdraw); 1483 DeferStateStruct deferStruct(deferredList, *this, replayFlags); 1484 renderNode->defer(deferStruct, 0); 1485 1486 flushLayers(); 1487 startFrame(); 1488 1489 deferredList.flush(*this, dirty); 1490 } else { 1491 // Even if there is no drawing command(Ex: invisible), 1492 // it still needs startFrame to clear buffer and start tiling. 1493 startFrame(); 1494 } 1495} 1496 1497/** 1498 * Important note: this method is intended to draw batches of bitmaps and 1499 * will not set the scissor enable or dirty the current layer, if any. 1500 * The caller is responsible for properly dirtying the current layer. 1501 */ 1502void OpenGLRenderer::drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry, 1503 int bitmapCount, TextureVertex* vertices, bool pureTranslate, 1504 const Rect& bounds, const SkPaint* paint) { 1505 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 1506 if (!texture) return; 1507 1508 const AutoTexture autoCleanup(texture); 1509 1510 // TODO: remove layer dirty in multi-draw callers 1511 // TODO: snap doesn't need to touch transform, only texture filter. 1512 bool snap = pureTranslate; 1513 const float x = floorf(bounds.left + 0.5f); 1514 const float y = floorf(bounds.top + 0.5f); 1515 int textureFillFlags = static_cast<int>((bitmap->colorType() == kAlpha_8_SkColorType) 1516 ? TextureFillFlags::kIsAlphaMaskTexture : TextureFillFlags::kNone); 1517 Glop glop; 1518 GlopBuilder(mRenderState, mCaches, &glop) 1519 .setMeshTexturedMesh(vertices, bitmapCount * 6) 1520 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha) 1521 .setTransform(currentSnapshot()->getOrthoMatrix(), Matrix4::identity(), false) 1522 .setModelViewOffsetRectOptionalSnap(snap, x, y, Rect(0, 0, bounds.getWidth(), bounds.getHeight())) 1523 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1524 .build(); 1525 renderGlop(glop); 1526} 1527 1528void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, const SkPaint* paint) { 1529 if (quickRejectSetupScissor(0, 0, bitmap->width(), bitmap->height())) { 1530 return; 1531 } 1532 1533 mCaches.textureState().activateTexture(0); 1534 Texture* texture = getTexture(bitmap); 1535 if (!texture) return; 1536 const AutoTexture autoCleanup(texture); 1537 1538 int textureFillFlags = static_cast<int>((bitmap->colorType() == kAlpha_8_SkColorType) 1539 ? TextureFillFlags::kIsAlphaMaskTexture : TextureFillFlags::kNone); 1540 Glop glop; 1541 GlopBuilder(mRenderState, mCaches, &glop) 1542 .setMeshTexturedUnitQuad(texture->uvMapper) 1543 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha) 1544 .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false) 1545 .setModelViewMapUnitToRectSnap(Rect(0, 0, texture->width, texture->height)) 1546 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1547 .build(); 1548 renderGlop(glop); 1549} 1550 1551void OpenGLRenderer::drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight, 1552 const float* vertices, const int* colors, const SkPaint* paint) { 1553 if (!vertices || mState.currentlyIgnored()) { 1554 return; 1555 } 1556 1557 float left = FLT_MAX; 1558 float top = FLT_MAX; 1559 float right = FLT_MIN; 1560 float bottom = FLT_MIN; 1561 1562 const uint32_t elementCount = meshWidth * meshHeight * 6; 1563 1564 std::unique_ptr<ColorTextureVertex[]> mesh(new ColorTextureVertex[elementCount]); 1565 ColorTextureVertex* vertex = &mesh[0]; 1566 1567 std::unique_ptr<int[]> tempColors; 1568 if (!colors) { 1569 uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1); 1570 tempColors.reset(new int[colorsCount]); 1571 memset(tempColors.get(), 0xff, colorsCount * sizeof(int)); 1572 colors = tempColors.get(); 1573 } 1574 1575 Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap); 1576 const UvMapper& mapper(getMapper(texture)); 1577 1578 for (int32_t y = 0; y < meshHeight; y++) { 1579 for (int32_t x = 0; x < meshWidth; x++) { 1580 uint32_t i = (y * (meshWidth + 1) + x) * 2; 1581 1582 float u1 = float(x) / meshWidth; 1583 float u2 = float(x + 1) / meshWidth; 1584 float v1 = float(y) / meshHeight; 1585 float v2 = float(y + 1) / meshHeight; 1586 1587 mapper.map(u1, v1, u2, v2); 1588 1589 int ax = i + (meshWidth + 1) * 2; 1590 int ay = ax + 1; 1591 int bx = i; 1592 int by = bx + 1; 1593 int cx = i + 2; 1594 int cy = cx + 1; 1595 int dx = i + (meshWidth + 1) * 2 + 2; 1596 int dy = dx + 1; 1597 1598 ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]); 1599 ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]); 1600 ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]); 1601 1602 ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]); 1603 ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]); 1604 ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]); 1605 1606 left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx]))); 1607 top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy]))); 1608 right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx]))); 1609 bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy]))); 1610 } 1611 } 1612 1613 if (quickRejectSetupScissor(left, top, right, bottom)) { 1614 return; 1615 } 1616 1617 if (!texture) { 1618 texture = mCaches.textureCache.get(bitmap); 1619 if (!texture) { 1620 return; 1621 } 1622 } 1623 const AutoTexture autoCleanup(texture); 1624 1625 /* 1626 * TODO: handle alpha_8 textures correctly by applying paint color, but *not* 1627 * shader in that case to mimic the behavior in SkiaCanvas::drawBitmapMesh. 1628 */ 1629 Glop glop; 1630 GlopBuilder(mRenderState, mCaches, &glop) 1631 .setMeshColoredTexturedMesh(mesh.get(), elementCount) 1632 .setFillTexturePaint(*texture, static_cast<int>(TextureFillFlags::kNone), paint, currentSnapshot()->alpha) 1633 .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false) 1634 .setModelViewOffsetRect(0, 0, Rect(left, top, right, bottom)) 1635 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1636 .build(); 1637 renderGlop(glop); 1638} 1639 1640void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, Rect src, Rect dst, const SkPaint* paint) { 1641 if (quickRejectSetupScissor(dst)) { 1642 return; 1643 } 1644 1645 Texture* texture = getTexture(bitmap); 1646 if (!texture) return; 1647 const AutoTexture autoCleanup(texture); 1648 1649 Rect uv(fmax(0.0f, src.left / texture->width), 1650 fmax(0.0f, src.top / texture->height), 1651 fmin(1.0f, src.right / texture->width), 1652 fmin(1.0f, src.bottom / texture->height)); 1653 1654 int textureFillFlags = static_cast<int>((bitmap->colorType() == kAlpha_8_SkColorType) 1655 ? TextureFillFlags::kIsAlphaMaskTexture : TextureFillFlags::kNone); 1656 Glop glop; 1657 GlopBuilder(mRenderState, mCaches, &glop) 1658 .setMeshTexturedUvQuad(texture->uvMapper, uv) 1659 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha) 1660 .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false) 1661 .setModelViewMapUnitToRectSnap(dst) 1662 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1663 .build(); 1664 renderGlop(glop); 1665} 1666 1667void OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Patch* mesh, 1668 AssetAtlas::Entry* entry, float left, float top, float right, float bottom, 1669 const SkPaint* paint) { 1670 if (!mesh || !mesh->verticesCount || quickRejectSetupScissor(left, top, right, bottom)) { 1671 return; 1672 } 1673 1674 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 1675 if (!texture) return; 1676 1677 // 9 patches are built for stretching - always filter 1678 int textureFillFlags = static_cast<int>(TextureFillFlags::kForceFilter); 1679 if (bitmap->colorType() == kAlpha_8_SkColorType) { 1680 textureFillFlags |= TextureFillFlags::kIsAlphaMaskTexture; 1681 } 1682 Glop glop; 1683 GlopBuilder(mRenderState, mCaches, &glop) 1684 .setMeshPatchQuads(*mesh) 1685 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha) 1686 .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false) 1687 .setModelViewOffsetRectSnap(left, top, Rect(0, 0, right - left, bottom - top)) // TODO: get minimal bounds from patch 1688 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1689 .build(); 1690 renderGlop(glop); 1691} 1692 1693/** 1694 * Important note: this method is intended to draw batches of 9-patch objects and 1695 * will not set the scissor enable or dirty the current layer, if any. 1696 * The caller is responsible for properly dirtying the current layer. 1697 */ 1698void OpenGLRenderer::drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry, 1699 TextureVertex* vertices, uint32_t elementCount, const SkPaint* paint) { 1700 mCaches.textureState().activateTexture(0); 1701 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 1702 if (!texture) return; 1703 const AutoTexture autoCleanup(texture); 1704 1705 // TODO: get correct bounds from caller 1706 // 9 patches are built for stretching - always filter 1707 int textureFillFlags = static_cast<int>(TextureFillFlags::kForceFilter); 1708 if (bitmap->colorType() == kAlpha_8_SkColorType) { 1709 textureFillFlags |= TextureFillFlags::kIsAlphaMaskTexture; 1710 } 1711 Glop glop; 1712 GlopBuilder(mRenderState, mCaches, &glop) 1713 .setMeshTexturedIndexedQuads(vertices, elementCount) 1714 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha) 1715 .setTransform(currentSnapshot()->getOrthoMatrix(), Matrix4::identity(), false) 1716 .setModelViewOffsetRect(0, 0, Rect(0, 0, 0, 0)) 1717 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1718 .build(); 1719 renderGlop(glop); 1720} 1721 1722void OpenGLRenderer::drawVertexBuffer(float translateX, float translateY, 1723 const VertexBuffer& vertexBuffer, const SkPaint* paint, int displayFlags) { 1724 // not missing call to quickReject/dirtyLayer, always done at a higher level 1725 if (!vertexBuffer.getVertexCount()) { 1726 // no vertices to draw 1727 return; 1728 } 1729 1730 bool fudgeOffset = displayFlags & kVertexBuffer_Offset; 1731 bool shadowInterp = displayFlags & kVertexBuffer_ShadowInterp; 1732 Glop glop; 1733 GlopBuilder(mRenderState, mCaches, &glop) 1734 .setMeshVertexBuffer(vertexBuffer, shadowInterp) 1735 .setFillPaint(*paint, currentSnapshot()->alpha) 1736 .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), fudgeOffset) 1737 .setModelViewOffsetRect(translateX, translateY, vertexBuffer.getBounds()) 1738 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1739 .build(); 1740 renderGlop(glop); 1741} 1742 1743/** 1744 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to 1745 * that of AA lines in the drawLines() function. We expand the convex path by a half pixel in 1746 * screen space in all directions. However, instead of using a fragment shader to compute the 1747 * translucency of the color from its position, we simply use a varying parameter to define how far 1748 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used. 1749 * 1750 * Doesn't yet support joins, caps, or path effects. 1751 */ 1752void OpenGLRenderer::drawConvexPath(const SkPath& path, const SkPaint* paint) { 1753 VertexBuffer vertexBuffer; 1754 // TODO: try clipping large paths to viewport 1755 PathTessellator::tessellatePath(path, paint, *currentTransform(), vertexBuffer); 1756 drawVertexBuffer(vertexBuffer, paint); 1757} 1758 1759/** 1760 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha 1761 * and additional geometry for defining an alpha slope perimeter. 1762 * 1763 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some 1764 * unexpected results, and may vary between hardware devices. Previously we used a varying-base 1765 * in-shader alpha region, but found it to be taxing on some GPUs. 1766 * 1767 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce 1768 * memory transfer by removing need for degenerate vertices. 1769 */ 1770void OpenGLRenderer::drawLines(const float* points, int count, const SkPaint* paint) { 1771 if (mState.currentlyIgnored() || count < 4) return; 1772 1773 count &= ~0x3; // round down to nearest four 1774 1775 VertexBuffer buffer; 1776 PathTessellator::tessellateLines(points, count, paint, *currentTransform(), buffer); 1777 const Rect& bounds = buffer.getBounds(); 1778 1779 if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) { 1780 return; 1781 } 1782 1783 int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset; 1784 drawVertexBuffer(buffer, paint, displayFlags); 1785} 1786 1787void OpenGLRenderer::drawPoints(const float* points, int count, const SkPaint* paint) { 1788 if (mState.currentlyIgnored() || count < 2) return; 1789 1790 count &= ~0x1; // round down to nearest two 1791 1792 VertexBuffer buffer; 1793 PathTessellator::tessellatePoints(points, count, paint, *currentTransform(), buffer); 1794 1795 const Rect& bounds = buffer.getBounds(); 1796 if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) { 1797 return; 1798 } 1799 1800 int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset; 1801 drawVertexBuffer(buffer, paint, displayFlags); 1802 1803 mDirty = true; 1804} 1805 1806void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) { 1807 // No need to check against the clip, we fill the clip region 1808 if (mState.currentlyIgnored()) return; 1809 1810 Rect clip(mState.currentClipRect()); 1811 clip.snapToPixelBoundaries(); 1812 1813 SkPaint paint; 1814 paint.setColor(color); 1815 paint.setXfermodeMode(mode); 1816 1817 drawColorRect(clip.left, clip.top, clip.right, clip.bottom, &paint, true); 1818 1819 mDirty = true; 1820} 1821 1822void OpenGLRenderer::drawShape(float left, float top, PathTexture* texture, 1823 const SkPaint* paint) { 1824 if (!texture) return; 1825 const AutoTexture autoCleanup(texture); 1826 1827 const float x = left + texture->left - texture->offset; 1828 const float y = top + texture->top - texture->offset; 1829 1830 drawPathTexture(texture, x, y, paint); 1831 1832 mDirty = true; 1833} 1834 1835void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom, 1836 float rx, float ry, const SkPaint* p) { 1837 if (mState.currentlyIgnored() 1838 || quickRejectSetupScissor(left, top, right, bottom, p) 1839 || PaintUtils::paintWillNotDraw(*p)) { 1840 return; 1841 } 1842 1843 if (p->getPathEffect() != nullptr) { 1844 mCaches.textureState().activateTexture(0); 1845 PathTexture* texture = mCaches.pathCache.getRoundRect( 1846 right - left, bottom - top, rx, ry, p); 1847 drawShape(left, top, texture, p); 1848 } else { 1849 const VertexBuffer* vertexBuffer = mCaches.tessellationCache.getRoundRect( 1850 *currentTransform(), *p, right - left, bottom - top, rx, ry); 1851 drawVertexBuffer(left, top, *vertexBuffer, p); 1852 } 1853} 1854 1855void OpenGLRenderer::drawCircle(float x, float y, float radius, const SkPaint* p) { 1856 if (mState.currentlyIgnored() 1857 || quickRejectSetupScissor(x - radius, y - radius, x + radius, y + radius, p) 1858 || PaintUtils::paintWillNotDraw(*p)) { 1859 return; 1860 } 1861 if (p->getPathEffect() != nullptr) { 1862 mCaches.textureState().activateTexture(0); 1863 PathTexture* texture = mCaches.pathCache.getCircle(radius, p); 1864 drawShape(x - radius, y - radius, texture, p); 1865 } else { 1866 SkPath path; 1867 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 1868 path.addCircle(x, y, radius + p->getStrokeWidth() / 2); 1869 } else { 1870 path.addCircle(x, y, radius); 1871 } 1872 drawConvexPath(path, p); 1873 } 1874} 1875 1876void OpenGLRenderer::drawOval(float left, float top, float right, float bottom, 1877 const SkPaint* p) { 1878 if (mState.currentlyIgnored() 1879 || quickRejectSetupScissor(left, top, right, bottom, p) 1880 || PaintUtils::paintWillNotDraw(*p)) { 1881 return; 1882 } 1883 1884 if (p->getPathEffect() != nullptr) { 1885 mCaches.textureState().activateTexture(0); 1886 PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p); 1887 drawShape(left, top, texture, p); 1888 } else { 1889 SkPath path; 1890 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 1891 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 1892 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 1893 } 1894 path.addOval(rect); 1895 drawConvexPath(path, p); 1896 } 1897} 1898 1899void OpenGLRenderer::drawArc(float left, float top, float right, float bottom, 1900 float startAngle, float sweepAngle, bool useCenter, const SkPaint* p) { 1901 if (mState.currentlyIgnored() 1902 || quickRejectSetupScissor(left, top, right, bottom, p) 1903 || PaintUtils::paintWillNotDraw(*p)) { 1904 return; 1905 } 1906 1907 // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180) 1908 if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != nullptr || useCenter) { 1909 mCaches.textureState().activateTexture(0); 1910 PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top, 1911 startAngle, sweepAngle, useCenter, p); 1912 drawShape(left, top, texture, p); 1913 return; 1914 } 1915 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 1916 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 1917 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 1918 } 1919 1920 SkPath path; 1921 if (useCenter) { 1922 path.moveTo(rect.centerX(), rect.centerY()); 1923 } 1924 path.arcTo(rect, startAngle, sweepAngle, !useCenter); 1925 if (useCenter) { 1926 path.close(); 1927 } 1928 drawConvexPath(path, p); 1929} 1930 1931// See SkPaintDefaults.h 1932#define SkPaintDefaults_MiterLimit SkIntToScalar(4) 1933 1934void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, 1935 const SkPaint* p) { 1936 if (mState.currentlyIgnored() 1937 || quickRejectSetupScissor(left, top, right, bottom, p) 1938 || PaintUtils::paintWillNotDraw(*p)) { 1939 return; 1940 } 1941 1942 if (p->getStyle() != SkPaint::kFill_Style) { 1943 // only fill style is supported by drawConvexPath, since others have to handle joins 1944 if (p->getPathEffect() != nullptr || p->getStrokeJoin() != SkPaint::kMiter_Join || 1945 p->getStrokeMiter() != SkPaintDefaults_MiterLimit) { 1946 mCaches.textureState().activateTexture(0); 1947 PathTexture* texture = 1948 mCaches.pathCache.getRect(right - left, bottom - top, p); 1949 drawShape(left, top, texture, p); 1950 } else { 1951 SkPath path; 1952 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 1953 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 1954 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 1955 } 1956 path.addRect(rect); 1957 drawConvexPath(path, p); 1958 } 1959 } else { 1960 if (p->isAntiAlias() && !currentTransform()->isSimple()) { 1961 SkPath path; 1962 path.addRect(left, top, right, bottom); 1963 drawConvexPath(path, p); 1964 } else { 1965 drawColorRect(left, top, right, bottom, p); 1966 1967 mDirty = true; 1968 } 1969 } 1970} 1971 1972void OpenGLRenderer::drawTextShadow(const SkPaint* paint, const char* text, 1973 int bytesCount, int count, const float* positions, 1974 FontRenderer& fontRenderer, int alpha, float x, float y) { 1975 mCaches.textureState().activateTexture(0); 1976 1977 TextShadow textShadow; 1978 if (!getTextShadow(paint, &textShadow)) { 1979 LOG_ALWAYS_FATAL("failed to query shadow attributes"); 1980 } 1981 1982 // NOTE: The drop shadow will not perform gamma correction 1983 // if shader-based correction is enabled 1984 mCaches.dropShadowCache.setFontRenderer(fontRenderer); 1985 ShadowTexture* texture = mCaches.dropShadowCache.get( 1986 paint, text, bytesCount, count, textShadow.radius, positions); 1987 // If the drop shadow exceeds the max texture size or couldn't be 1988 // allocated, skip drawing 1989 if (!texture) return; 1990 const AutoTexture autoCleanup(texture); 1991 1992 const float sx = x - texture->left + textShadow.dx; 1993 const float sy = y - texture->top + textShadow.dy; 1994 1995 Glop glop; 1996 GlopBuilder(mRenderState, mCaches, &glop) 1997 .setMeshTexturedUnitQuad(nullptr) 1998 .setFillShadowTexturePaint(*texture, textShadow.color, *paint, currentSnapshot()->alpha) 1999 .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false) 2000 .setModelViewMapUnitToRect(Rect(sx, sy, sx + texture->width, sy + texture->height)) 2001 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 2002 .build(); 2003 renderGlop(glop); 2004} 2005 2006bool OpenGLRenderer::canSkipText(const SkPaint* paint) const { 2007 float alpha = (hasTextShadow(paint) ? 1.0f : paint->getAlpha()) * currentSnapshot()->alpha; 2008 return MathUtils::isZero(alpha) 2009 && PaintUtils::getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode; 2010} 2011 2012void OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count, 2013 const float* positions, const SkPaint* paint) { 2014 if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) { 2015 return; 2016 } 2017 2018 // NOTE: Skia does not support perspective transform on drawPosText yet 2019 if (!currentTransform()->isSimple()) { 2020 return; 2021 } 2022 2023 mRenderState.scissor().setEnabled(true); 2024 2025 float x = 0.0f; 2026 float y = 0.0f; 2027 const bool pureTranslate = currentTransform()->isPureTranslate(); 2028 if (pureTranslate) { 2029 x = floorf(x + currentTransform()->getTranslateX() + 0.5f); 2030 y = floorf(y + currentTransform()->getTranslateY() + 0.5f); 2031 } 2032 2033 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2034 fontRenderer.setFont(paint, SkMatrix::I()); 2035 2036 int alpha; 2037 SkXfermode::Mode mode; 2038 getAlphaAndMode(paint, &alpha, &mode); 2039 2040 if (CC_UNLIKELY(hasTextShadow(paint))) { 2041 drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, 2042 alpha, 0.0f, 0.0f); 2043 } 2044 2045 // Pick the appropriate texture filtering 2046 bool linearFilter = currentTransform()->changesBounds(); 2047 if (pureTranslate && !linearFilter) { 2048 linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f; 2049 } 2050 fontRenderer.setTextureFiltering(linearFilter); 2051 2052 const Rect& clip(pureTranslate ? writableSnapshot()->getClipRect() : writableSnapshot()->getLocalClip()); 2053 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2054 2055 TextDrawFunctor functor(this, x, y, pureTranslate, alpha, mode, paint); 2056 if (fontRenderer.renderPosText(paint, &clip, text, 0, bytesCount, count, x, y, 2057 positions, hasLayer() ? &bounds : nullptr, &functor)) { 2058 dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, *currentTransform()); 2059 mDirty = true; 2060 } 2061 2062} 2063 2064bool OpenGLRenderer::findBestFontTransform(const mat4& transform, SkMatrix* outMatrix) const { 2065 if (CC_LIKELY(transform.isPureTranslate())) { 2066 outMatrix->setIdentity(); 2067 return false; 2068 } else if (CC_UNLIKELY(transform.isPerspective())) { 2069 outMatrix->setIdentity(); 2070 return true; 2071 } 2072 2073 /** 2074 * Input is a non-perspective, scaling transform. Generate a scale-only transform, 2075 * with values rounded to the nearest int. 2076 */ 2077 float sx, sy; 2078 transform.decomposeScale(sx, sy); 2079 outMatrix->setScale( 2080 roundf(fmaxf(1.0f, sx)), 2081 roundf(fmaxf(1.0f, sy))); 2082 return true; 2083} 2084 2085int OpenGLRenderer::getSaveCount() const { 2086 return mState.getSaveCount(); 2087} 2088 2089int OpenGLRenderer::save(int flags) { 2090 return mState.save(flags); 2091} 2092 2093void OpenGLRenderer::restore() { 2094 mState.restore(); 2095} 2096 2097void OpenGLRenderer::restoreToCount(int saveCount) { 2098 mState.restoreToCount(saveCount); 2099} 2100 2101void OpenGLRenderer::translate(float dx, float dy, float dz) { 2102 mState.translate(dx, dy, dz); 2103} 2104 2105void OpenGLRenderer::rotate(float degrees) { 2106 mState.rotate(degrees); 2107} 2108 2109void OpenGLRenderer::scale(float sx, float sy) { 2110 mState.scale(sx, sy); 2111} 2112 2113void OpenGLRenderer::skew(float sx, float sy) { 2114 mState.skew(sx, sy); 2115} 2116 2117void OpenGLRenderer::setMatrix(const Matrix4& matrix) { 2118 mState.setMatrix(matrix); 2119} 2120 2121void OpenGLRenderer::concatMatrix(const Matrix4& matrix) { 2122 mState.concatMatrix(matrix); 2123} 2124 2125bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) { 2126 return mState.clipRect(left, top, right, bottom, op); 2127} 2128 2129bool OpenGLRenderer::clipPath(const SkPath* path, SkRegion::Op op) { 2130 return mState.clipPath(path, op); 2131} 2132 2133bool OpenGLRenderer::clipRegion(const SkRegion* region, SkRegion::Op op) { 2134 return mState.clipRegion(region, op); 2135} 2136 2137void OpenGLRenderer::setClippingOutline(LinearAllocator& allocator, const Outline* outline) { 2138 mState.setClippingOutline(allocator, outline); 2139} 2140 2141void OpenGLRenderer::setClippingRoundRect(LinearAllocator& allocator, 2142 const Rect& rect, float radius, bool highPriority) { 2143 mState.setClippingRoundRect(allocator, rect, radius, highPriority); 2144} 2145 2146void OpenGLRenderer::drawText(const char* text, int bytesCount, int count, float x, float y, 2147 const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds, 2148 DrawOpMode drawOpMode) { 2149 2150 if (drawOpMode == DrawOpMode::kImmediate) { 2151 // The checks for corner-case ignorable text and quick rejection is only done for immediate 2152 // drawing as ops from DeferredDisplayList are already filtered for these 2153 if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint) || 2154 quickRejectSetupScissor(bounds)) { 2155 return; 2156 } 2157 } 2158 2159 const float oldX = x; 2160 const float oldY = y; 2161 2162 const mat4& transform = *currentTransform(); 2163 const bool pureTranslate = transform.isPureTranslate(); 2164 2165 if (CC_LIKELY(pureTranslate)) { 2166 x = floorf(x + transform.getTranslateX() + 0.5f); 2167 y = floorf(y + transform.getTranslateY() + 0.5f); 2168 } 2169 2170 int alpha; 2171 SkXfermode::Mode mode; 2172 getAlphaAndMode(paint, &alpha, &mode); 2173 2174 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2175 2176 if (CC_UNLIKELY(hasTextShadow(paint))) { 2177 fontRenderer.setFont(paint, SkMatrix::I()); 2178 drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, 2179 alpha, oldX, oldY); 2180 } 2181 2182 const bool hasActiveLayer = hasLayer(); 2183 2184 // We only pass a partial transform to the font renderer. That partial 2185 // matrix defines how glyphs are rasterized. Typically we want glyphs 2186 // to be rasterized at their final size on screen, which means the partial 2187 // matrix needs to take the scale factor into account. 2188 // When a partial matrix is used to transform glyphs during rasterization, 2189 // the mesh is generated with the inverse transform (in the case of scale, 2190 // the mesh is generated at 1.0 / scale for instance.) This allows us to 2191 // apply the full transform matrix at draw time in the vertex shader. 2192 // Applying the full matrix in the shader is the easiest way to handle 2193 // rotation and perspective and allows us to always generated quads in the 2194 // font renderer which greatly simplifies the code, clipping in particular. 2195 SkMatrix fontTransform; 2196 bool linearFilter = findBestFontTransform(transform, &fontTransform) 2197 || fabs(y - (int) y) > 0.0f 2198 || fabs(x - (int) x) > 0.0f; 2199 fontRenderer.setFont(paint, fontTransform); 2200 fontRenderer.setTextureFiltering(linearFilter); 2201 2202 // TODO: Implement better clipping for scaled/rotated text 2203 const Rect* clip = !pureTranslate ? nullptr : &mState.currentClipRect(); 2204 Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2205 2206 bool status; 2207 TextDrawFunctor functor(this, x, y, pureTranslate, alpha, mode, paint); 2208 2209 // don't call issuedrawcommand, do it at end of batch 2210 bool forceFinish = (drawOpMode != DrawOpMode::kDefer); 2211 if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) { 2212 SkPaint paintCopy(*paint); 2213 paintCopy.setTextAlign(SkPaint::kLeft_Align); 2214 status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y, 2215 positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish); 2216 } else { 2217 status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y, 2218 positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish); 2219 } 2220 2221 if ((status || drawOpMode != DrawOpMode::kImmediate) && hasActiveLayer) { 2222 if (!pureTranslate) { 2223 transform.mapRect(layerBounds); 2224 } 2225 dirtyLayerUnchecked(layerBounds, getRegion()); 2226 } 2227 2228 drawTextDecorations(totalAdvance, oldX, oldY, paint); 2229 2230 mDirty = true; 2231} 2232 2233void OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count, 2234 const SkPath* path, float hOffset, float vOffset, const SkPaint* paint) { 2235 if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) { 2236 return; 2237 } 2238 2239 // TODO: avoid scissor by calculating maximum bounds using path bounds + font metrics 2240 mRenderState.scissor().setEnabled(true); 2241 2242 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2243 fontRenderer.setFont(paint, SkMatrix::I()); 2244 fontRenderer.setTextureFiltering(true); 2245 2246 int alpha; 2247 SkXfermode::Mode mode; 2248 getAlphaAndMode(paint, &alpha, &mode); 2249 TextDrawFunctor functor(this, 0.0f, 0.0f, false, alpha, mode, paint); 2250 2251 const Rect* clip = &writableSnapshot()->getLocalClip(); 2252 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2253 2254 if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path, 2255 hOffset, vOffset, hasLayer() ? &bounds : nullptr, &functor)) { 2256 dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, *currentTransform()); 2257 mDirty = true; 2258 } 2259} 2260 2261void OpenGLRenderer::drawPath(const SkPath* path, const SkPaint* paint) { 2262 if (mState.currentlyIgnored()) return; 2263 2264 mCaches.textureState().activateTexture(0); 2265 2266 PathTexture* texture = mCaches.pathCache.get(path, paint); 2267 if (!texture) return; 2268 const AutoTexture autoCleanup(texture); 2269 2270 const float x = texture->left - texture->offset; 2271 const float y = texture->top - texture->offset; 2272 2273 drawPathTexture(texture, x, y, paint); 2274 mDirty = true; 2275} 2276 2277void OpenGLRenderer::drawLayer(Layer* layer, float x, float y) { 2278 if (!layer) { 2279 return; 2280 } 2281 2282 mat4* transform = nullptr; 2283 if (layer->isTextureLayer()) { 2284 transform = &layer->getTransform(); 2285 if (!transform->isIdentity()) { 2286 save(SkCanvas::kMatrix_SaveFlag); 2287 concatMatrix(*transform); 2288 } 2289 } 2290 2291 bool clipRequired = false; 2292 const bool rejected = mState.calculateQuickRejectForScissor( 2293 x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(), 2294 &clipRequired, nullptr, false); 2295 2296 if (rejected) { 2297 if (transform && !transform->isIdentity()) { 2298 restore(); 2299 } 2300 return; 2301 } 2302 2303 EVENT_LOGD("drawLayer," RECT_STRING ", clipRequired %d", x, y, 2304 x + layer->layer.getWidth(), y + layer->layer.getHeight(), clipRequired); 2305 2306 updateLayer(layer, true); 2307 2308 mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired); 2309 mCaches.textureState().activateTexture(0); 2310 2311 if (CC_LIKELY(!layer->region.isEmpty())) { 2312 if (layer->region.isRect()) { 2313 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, 2314 composeLayerRect(layer, layer->regionRect)); 2315 } else if (layer->mesh) { 2316 Glop glop; 2317 GlopBuilder(mRenderState, mCaches, &glop) 2318 .setMeshTexturedIndexedQuads(layer->mesh, layer->meshElementCount) 2319 .setFillLayer(layer->getTexture(), layer->getColorFilter(), getLayerAlpha(layer), layer->getMode(), Blend::ModeOrderSwap::NoSwap) 2320 .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false) 2321 .setModelViewOffsetRectSnap(x, y, Rect(0, 0, layer->layer.getWidth(), layer->layer.getHeight())) 2322 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 2323 .build(); 2324 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, renderGlop(glop)); 2325#if DEBUG_LAYERS_AS_REGIONS 2326 drawRegionRectsDebug(layer->region); 2327#endif 2328 } 2329 2330 if (layer->debugDrawUpdate) { 2331 layer->debugDrawUpdate = false; 2332 2333 SkPaint paint; 2334 paint.setColor(0x7f00ff00); 2335 drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(), &paint); 2336 } 2337 } 2338 layer->hasDrawnSinceUpdate = true; 2339 2340 if (transform && !transform->isIdentity()) { 2341 restore(); 2342 } 2343 2344 mDirty = true; 2345} 2346 2347/////////////////////////////////////////////////////////////////////////////// 2348// Draw filters 2349/////////////////////////////////////////////////////////////////////////////// 2350void OpenGLRenderer::setDrawFilter(SkDrawFilter* filter) { 2351 // We should never get here since we apply the draw filter when stashing 2352 // the paints in the DisplayList. 2353 LOG_ALWAYS_FATAL("OpenGLRenderer does not directly support DrawFilters"); 2354} 2355 2356/////////////////////////////////////////////////////////////////////////////// 2357// Drawing implementation 2358/////////////////////////////////////////////////////////////////////////////// 2359 2360Texture* OpenGLRenderer::getTexture(const SkBitmap* bitmap) { 2361 Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap); 2362 if (!texture) { 2363 return mCaches.textureCache.get(bitmap); 2364 } 2365 return texture; 2366} 2367 2368void OpenGLRenderer::drawPathTexture(PathTexture* texture, float x, float y, 2369 const SkPaint* paint) { 2370 if (quickRejectSetupScissor(x, y, x + texture->width, y + texture->height)) { 2371 return; 2372 } 2373 2374 Glop glop; 2375 GlopBuilder(mRenderState, mCaches, &glop) 2376 .setMeshTexturedUnitQuad(nullptr) 2377 .setFillPathTexturePaint(*texture, *paint, currentSnapshot()->alpha) 2378 .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false) 2379 .setModelViewMapUnitToRect(Rect(x, y, x + texture->width, y + texture->height)) 2380 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 2381 .build(); 2382 renderGlop(glop); 2383} 2384 2385// Same values used by Skia 2386#define kStdStrikeThru_Offset (-6.0f / 21.0f) 2387#define kStdUnderline_Offset (1.0f / 9.0f) 2388#define kStdUnderline_Thickness (1.0f / 18.0f) 2389 2390void OpenGLRenderer::drawTextDecorations(float underlineWidth, float x, float y, 2391 const SkPaint* paint) { 2392 // Handle underline and strike-through 2393 uint32_t flags = paint->getFlags(); 2394 if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) { 2395 SkPaint paintCopy(*paint); 2396 2397 if (CC_LIKELY(underlineWidth > 0.0f)) { 2398 const float textSize = paintCopy.getTextSize(); 2399 const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f); 2400 2401 const float left = x; 2402 float top = 0.0f; 2403 2404 int linesCount = 0; 2405 if (flags & SkPaint::kUnderlineText_Flag) linesCount++; 2406 if (flags & SkPaint::kStrikeThruText_Flag) linesCount++; 2407 2408 const int pointsCount = 4 * linesCount; 2409 float points[pointsCount]; 2410 int currentPoint = 0; 2411 2412 if (flags & SkPaint::kUnderlineText_Flag) { 2413 top = y + textSize * kStdUnderline_Offset; 2414 points[currentPoint++] = left; 2415 points[currentPoint++] = top; 2416 points[currentPoint++] = left + underlineWidth; 2417 points[currentPoint++] = top; 2418 } 2419 2420 if (flags & SkPaint::kStrikeThruText_Flag) { 2421 top = y + textSize * kStdStrikeThru_Offset; 2422 points[currentPoint++] = left; 2423 points[currentPoint++] = top; 2424 points[currentPoint++] = left + underlineWidth; 2425 points[currentPoint++] = top; 2426 } 2427 2428 paintCopy.setStrokeWidth(strokeWidth); 2429 2430 drawLines(&points[0], pointsCount, &paintCopy); 2431 } 2432 } 2433} 2434 2435void OpenGLRenderer::drawRects(const float* rects, int count, const SkPaint* paint) { 2436 if (mState.currentlyIgnored()) { 2437 return; 2438 } 2439 2440 drawColorRects(rects, count, paint, false, true, true); 2441} 2442 2443void OpenGLRenderer::drawShadow(float casterAlpha, 2444 const VertexBuffer* ambientShadowVertexBuffer, const VertexBuffer* spotShadowVertexBuffer) { 2445 if (mState.currentlyIgnored()) return; 2446 2447 // TODO: use quickRejectWithScissor. For now, always force enable scissor. 2448 mRenderState.scissor().setEnabled(true); 2449 2450 SkPaint paint; 2451 paint.setAntiAlias(true); // want to use AlphaVertex 2452 2453 // The caller has made sure casterAlpha > 0. 2454 float ambientShadowAlpha = mAmbientShadowAlpha; 2455 if (CC_UNLIKELY(mCaches.propertyAmbientShadowStrength >= 0)) { 2456 ambientShadowAlpha = mCaches.propertyAmbientShadowStrength; 2457 } 2458 if (ambientShadowVertexBuffer && ambientShadowAlpha > 0) { 2459 paint.setARGB(casterAlpha * ambientShadowAlpha, 0, 0, 0); 2460 drawVertexBuffer(*ambientShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp); 2461 } 2462 2463 float spotShadowAlpha = mSpotShadowAlpha; 2464 if (CC_UNLIKELY(mCaches.propertySpotShadowStrength >= 0)) { 2465 spotShadowAlpha = mCaches.propertySpotShadowStrength; 2466 } 2467 if (spotShadowVertexBuffer && spotShadowAlpha > 0) { 2468 paint.setARGB(casterAlpha * spotShadowAlpha, 0, 0, 0); 2469 drawVertexBuffer(*spotShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp); 2470 } 2471 2472 mDirty=true; 2473} 2474 2475void OpenGLRenderer::drawColorRects(const float* rects, int count, const SkPaint* paint, 2476 bool ignoreTransform, bool dirty, bool clip) { 2477 if (count == 0) { 2478 return; 2479 } 2480 2481 float left = FLT_MAX; 2482 float top = FLT_MAX; 2483 float right = FLT_MIN; 2484 float bottom = FLT_MIN; 2485 2486 Vertex mesh[count]; 2487 Vertex* vertex = mesh; 2488 2489 for (int index = 0; index < count; index += 4) { 2490 float l = rects[index + 0]; 2491 float t = rects[index + 1]; 2492 float r = rects[index + 2]; 2493 float b = rects[index + 3]; 2494 2495 Vertex::set(vertex++, l, t); 2496 Vertex::set(vertex++, r, t); 2497 Vertex::set(vertex++, l, b); 2498 Vertex::set(vertex++, r, b); 2499 2500 left = fminf(left, l); 2501 top = fminf(top, t); 2502 right = fmaxf(right, r); 2503 bottom = fmaxf(bottom, b); 2504 } 2505 2506 if (clip && quickRejectSetupScissor(left, top, right, bottom)) { 2507 return; 2508 } 2509 2510 const Matrix4& transform = ignoreTransform ? Matrix4::identity() : *currentTransform(); 2511 Glop glop; 2512 GlopBuilder(mRenderState, mCaches, &glop) 2513 .setMeshIndexedQuads(&mesh[0], count / 4) 2514 .setFillPaint(*paint, currentSnapshot()->alpha) 2515 .setTransform(currentSnapshot()->getOrthoMatrix(), transform, false) 2516 .setModelViewOffsetRect(0, 0, Rect(left, top, right, bottom)) 2517 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 2518 .build(); 2519 renderGlop(glop); 2520} 2521 2522void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom, 2523 const SkPaint* paint, bool ignoreTransform) { 2524 const Matrix4& transform = ignoreTransform ? Matrix4::identity() : *currentTransform(); 2525 Glop glop; 2526 GlopBuilder(mRenderState, mCaches, &glop) 2527 .setMeshUnitQuad() 2528 .setFillPaint(*paint, currentSnapshot()->alpha) 2529 .setTransform(currentSnapshot()->getOrthoMatrix(), transform, false) 2530 .setModelViewMapUnitToRect(Rect(left, top, right, bottom)) 2531 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 2532 .build(); 2533 renderGlop(glop); 2534} 2535 2536void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, 2537 SkXfermode::Mode* mode) const { 2538 getAlphaAndModeDirect(paint, alpha, mode); 2539 *alpha *= currentSnapshot()->alpha; 2540} 2541 2542float OpenGLRenderer::getLayerAlpha(const Layer* layer) const { 2543 return (layer->getAlpha() / 255.0f) * currentSnapshot()->alpha; 2544} 2545 2546}; // namespace uirenderer 2547}; // namespace android 2548