RenderNode.cpp revision b5a5435a77bae40b55053ccde93b1ed45d0e8329
1/* 2 * Copyright (C) 2014 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#define ATRACE_TAG ATRACE_TAG_VIEW 18#define LOG_TAG "OpenGLRenderer" 19 20#include "RenderNode.h" 21 22#include <algorithm> 23#include <string> 24 25#include <SkCanvas.h> 26#include <algorithm> 27 28#include <utils/Trace.h> 29 30#include "DamageAccumulator.h" 31#include "Debug.h" 32#include "DisplayListOp.h" 33#include "DisplayListLogBuffer.h" 34#include "LayerRenderer.h" 35#include "OpenGLRenderer.h" 36#include "utils/MathUtils.h" 37#include "renderthread/CanvasContext.h" 38 39namespace android { 40namespace uirenderer { 41 42void RenderNode::outputLogBuffer(int fd) { 43 DisplayListLogBuffer& logBuffer = DisplayListLogBuffer::getInstance(); 44 if (logBuffer.isEmpty()) { 45 return; 46 } 47 48 FILE *file = fdopen(fd, "a"); 49 50 fprintf(file, "\nRecent DisplayList operations\n"); 51 logBuffer.outputCommands(file); 52 53 if (Caches::hasInstance()) { 54 String8 cachesLog; 55 Caches::getInstance().dumpMemoryUsage(cachesLog); 56 fprintf(file, "\nCaches:\n%s\n", cachesLog.string()); 57 } else { 58 fprintf(file, "\nNo caches instance.\n"); 59 } 60 61 fflush(file); 62} 63 64void RenderNode::debugDumpLayers(const char* prefix) { 65 if (mLayer) { 66 ALOGD("%sNode %p (%s) has layer %p (fbo = %u, wasBuildLayered = %s)", 67 prefix, this, getName(), mLayer, mLayer->getFbo(), 68 mLayer->wasBuildLayered ? "true" : "false"); 69 } 70 if (mDisplayListData) { 71 for (size_t i = 0; i < mDisplayListData->children().size(); i++) { 72 mDisplayListData->children()[i]->mRenderNode->debugDumpLayers(prefix); 73 } 74 } 75} 76 77RenderNode::RenderNode() 78 : mDirtyPropertyFields(0) 79 , mNeedsDisplayListDataSync(false) 80 , mDisplayListData(0) 81 , mStagingDisplayListData(0) 82 , mAnimatorManager(*this) 83 , mLayer(0) 84 , mParentCount(0) { 85} 86 87RenderNode::~RenderNode() { 88 deleteDisplayListData(); 89 delete mStagingDisplayListData; 90 if (mLayer) { 91 ALOGW("Memory Warning: Layer %p missed its detachment, held on to for far too long!", mLayer); 92 mLayer->postDecStrong(); 93 mLayer = 0; 94 } 95} 96 97void RenderNode::setStagingDisplayList(DisplayListData* data) { 98 mNeedsDisplayListDataSync = true; 99 delete mStagingDisplayListData; 100 mStagingDisplayListData = data; 101} 102 103/** 104 * This function is a simplified version of replay(), where we simply retrieve and log the 105 * display list. This function should remain in sync with the replay() function. 106 */ 107void RenderNode::output(uint32_t level) { 108 ALOGD("%*sStart display list (%p, %s%s%s%s)", (level - 1) * 2, "", this, 109 getName(), 110 (properties().hasShadow() ? ", casting shadow" : ""), 111 (isRenderable() ? "" : ", empty"), 112 (mLayer != NULL ? ", on HW Layer" : "")); 113 ALOGD("%*s%s %d", level * 2, "", "Save", 114 SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag); 115 116 properties().debugOutputProperties(level); 117 int flags = DisplayListOp::kOpLogFlag_Recurse; 118 if (mDisplayListData) { 119 // TODO: consider printing the chunk boundaries here 120 for (unsigned int i = 0; i < mDisplayListData->displayListOps.size(); i++) { 121 mDisplayListData->displayListOps[i]->output(level, flags); 122 } 123 } 124 125 ALOGD("%*sDone (%p, %s)", (level - 1) * 2, "", this, getName()); 126} 127 128int RenderNode::getDebugSize() { 129 int size = sizeof(RenderNode); 130 if (mStagingDisplayListData) { 131 size += mStagingDisplayListData->getUsedSize(); 132 } 133 if (mDisplayListData && mDisplayListData != mStagingDisplayListData) { 134 size += mDisplayListData->getUsedSize(); 135 } 136 return size; 137} 138 139void RenderNode::prepareTree(TreeInfo& info) { 140 ATRACE_CALL(); 141 LOG_ALWAYS_FATAL_IF(!info.damageAccumulator, "DamageAccumulator missing"); 142 143 prepareTreeImpl(info); 144} 145 146void RenderNode::addAnimator(const sp<BaseRenderNodeAnimator>& animator) { 147 mAnimatorManager.addAnimator(animator); 148} 149 150void RenderNode::damageSelf(TreeInfo& info) { 151 if (isRenderable()) { 152 if (properties().getClipDamageToBounds()) { 153 info.damageAccumulator->dirty(0, 0, properties().getWidth(), properties().getHeight()); 154 } else { 155 // Hope this is big enough? 156 // TODO: Get this from the display list ops or something 157 info.damageAccumulator->dirty(INT_MIN, INT_MIN, INT_MAX, INT_MAX); 158 } 159 } 160} 161 162void RenderNode::prepareLayer(TreeInfo& info, uint32_t dirtyMask) { 163 LayerType layerType = properties().layerProperties().type(); 164 if (CC_UNLIKELY(layerType == kLayerTypeRenderLayer)) { 165 // Damage applied so far needs to affect our parent, but does not require 166 // the layer to be updated. So we pop/push here to clear out the current 167 // damage and get a clean state for display list or children updates to 168 // affect, which will require the layer to be updated 169 info.damageAccumulator->popTransform(); 170 info.damageAccumulator->pushTransform(this); 171 if (dirtyMask & DISPLAY_LIST) { 172 damageSelf(info); 173 } 174 } 175} 176 177void RenderNode::pushLayerUpdate(TreeInfo& info) { 178 LayerType layerType = properties().layerProperties().type(); 179 // If we are not a layer OR we cannot be rendered (eg, view was detached) 180 // we need to destroy any Layers we may have had previously 181 if (CC_LIKELY(layerType != kLayerTypeRenderLayer) || CC_UNLIKELY(!isRenderable())) { 182 if (CC_UNLIKELY(mLayer)) { 183 LayerRenderer::destroyLayer(mLayer); 184 mLayer = NULL; 185 } 186 return; 187 } 188 189 bool transformUpdateNeeded = false; 190 if (!mLayer) { 191 mLayer = LayerRenderer::createRenderLayer(info.renderState, getWidth(), getHeight()); 192 applyLayerPropertiesToLayer(info); 193 damageSelf(info); 194 transformUpdateNeeded = true; 195 } else if (mLayer->layer.getWidth() != getWidth() || mLayer->layer.getHeight() != getHeight()) { 196 if (!LayerRenderer::resizeLayer(mLayer, getWidth(), getHeight())) { 197 LayerRenderer::destroyLayer(mLayer); 198 mLayer = 0; 199 } 200 damageSelf(info); 201 transformUpdateNeeded = true; 202 } 203 204 SkRect dirty; 205 info.damageAccumulator->peekAtDirty(&dirty); 206 207 if (!mLayer) { 208 Caches::getInstance().dumpMemoryUsage(); 209 if (info.errorHandler) { 210 std::string msg = "Unable to create layer for "; 211 msg += getName(); 212 info.errorHandler->onError(msg); 213 } 214 return; 215 } 216 217 if (transformUpdateNeeded) { 218 // update the transform in window of the layer to reset its origin wrt light source position 219 Matrix4 windowTransform; 220 info.damageAccumulator->computeCurrentTransform(&windowTransform); 221 mLayer->setWindowTransform(windowTransform); 222 } 223 224 if (dirty.intersect(0, 0, getWidth(), getHeight())) { 225 dirty.roundOut(); 226 mLayer->updateDeferred(this, dirty.fLeft, dirty.fTop, dirty.fRight, dirty.fBottom); 227 } 228 // This is not inside the above if because we may have called 229 // updateDeferred on a previous prepare pass that didn't have a renderer 230 if (info.renderer && mLayer->deferredUpdateScheduled) { 231 info.renderer->pushLayerUpdate(mLayer); 232 } 233 234 if (CC_UNLIKELY(info.canvasContext)) { 235 // If canvasContext is not null that means there are prefetched layers 236 // that need to be accounted for. That might be us, so tell CanvasContext 237 // that this layer is in the tree and should not be destroyed. 238 info.canvasContext->markLayerInUse(this); 239 } 240} 241 242void RenderNode::prepareTreeImpl(TreeInfo& info) { 243 info.damageAccumulator->pushTransform(this); 244 245 if (info.mode == TreeInfo::MODE_FULL) { 246 pushStagingPropertiesChanges(info); 247 } 248 uint32_t animatorDirtyMask = 0; 249 if (CC_LIKELY(info.runAnimations)) { 250 animatorDirtyMask = mAnimatorManager.animate(info); 251 } 252 prepareLayer(info, animatorDirtyMask); 253 if (info.mode == TreeInfo::MODE_FULL) { 254 pushStagingDisplayListChanges(info); 255 } 256 prepareSubTree(info, mDisplayListData); 257 pushLayerUpdate(info); 258 259 info.damageAccumulator->popTransform(); 260} 261 262void RenderNode::pushStagingPropertiesChanges(TreeInfo& info) { 263 // Push the animators first so that setupStartValueIfNecessary() is called 264 // before properties() is trampled by stagingProperties(), as they are 265 // required by some animators. 266 if (CC_LIKELY(info.runAnimations)) { 267 mAnimatorManager.pushStaging(); 268 } 269 if (mDirtyPropertyFields) { 270 mDirtyPropertyFields = 0; 271 damageSelf(info); 272 info.damageAccumulator->popTransform(); 273 mProperties = mStagingProperties; 274 applyLayerPropertiesToLayer(info); 275 // We could try to be clever and only re-damage if the matrix changed. 276 // However, we don't need to worry about that. The cost of over-damaging 277 // here is only going to be a single additional map rect of this node 278 // plus a rect join(). The parent's transform (and up) will only be 279 // performed once. 280 info.damageAccumulator->pushTransform(this); 281 damageSelf(info); 282 } 283} 284 285void RenderNode::applyLayerPropertiesToLayer(TreeInfo& info) { 286 if (CC_LIKELY(!mLayer)) return; 287 288 const LayerProperties& props = properties().layerProperties(); 289 mLayer->setAlpha(props.alpha(), props.xferMode()); 290 mLayer->setColorFilter(props.colorFilter()); 291 mLayer->setBlend(props.needsBlending()); 292} 293 294void RenderNode::pushStagingDisplayListChanges(TreeInfo& info) { 295 if (mNeedsDisplayListDataSync) { 296 mNeedsDisplayListDataSync = false; 297 // Make sure we inc first so that we don't fluctuate between 0 and 1, 298 // which would thrash the layer cache 299 if (mStagingDisplayListData) { 300 for (size_t i = 0; i < mStagingDisplayListData->children().size(); i++) { 301 mStagingDisplayListData->children()[i]->mRenderNode->incParentRefCount(); 302 } 303 } 304 // Damage with the old display list first then the new one to catch any 305 // changes in isRenderable or, in the future, bounds 306 damageSelf(info); 307 deleteDisplayListData(); 308 // TODO: Remove this caches stuff 309 if (mStagingDisplayListData && mStagingDisplayListData->functors.size()) { 310 Caches::getInstance().registerFunctors(mStagingDisplayListData->functors.size()); 311 } 312 mDisplayListData = mStagingDisplayListData; 313 mStagingDisplayListData = NULL; 314 if (mDisplayListData) { 315 for (size_t i = 0; i < mDisplayListData->functors.size(); i++) { 316 (*mDisplayListData->functors[i])(DrawGlInfo::kModeSync, NULL); 317 } 318 } 319 damageSelf(info); 320 } 321} 322 323void RenderNode::deleteDisplayListData() { 324 if (mDisplayListData) { 325 for (size_t i = 0; i < mDisplayListData->children().size(); i++) { 326 mDisplayListData->children()[i]->mRenderNode->decParentRefCount(); 327 } 328 if (mDisplayListData->functors.size()) { 329 Caches::getInstance().unregisterFunctors(mDisplayListData->functors.size()); 330 } 331 } 332 delete mDisplayListData; 333 mDisplayListData = NULL; 334} 335 336void RenderNode::prepareSubTree(TreeInfo& info, DisplayListData* subtree) { 337 if (subtree) { 338 TextureCache& cache = Caches::getInstance().textureCache; 339 info.out.hasFunctors |= subtree->functors.size(); 340 // TODO: Fix ownedBitmapResources to not require disabling prepareTextures 341 // and thus falling out of async drawing path. 342 if (subtree->ownedBitmapResources.size()) { 343 info.prepareTextures = false; 344 } 345 for (size_t i = 0; info.prepareTextures && i < subtree->bitmapResources.size(); i++) { 346 info.prepareTextures = cache.prefetchAndMarkInUse(subtree->bitmapResources[i]); 347 } 348 for (size_t i = 0; i < subtree->children().size(); i++) { 349 DrawRenderNodeOp* op = subtree->children()[i]; 350 RenderNode* childNode = op->mRenderNode; 351 info.damageAccumulator->pushTransform(&op->mTransformFromParent); 352 childNode->prepareTreeImpl(info); 353 info.damageAccumulator->popTransform(); 354 } 355 } 356} 357 358void RenderNode::destroyHardwareResources() { 359 if (mLayer) { 360 LayerRenderer::destroyLayer(mLayer); 361 mLayer = NULL; 362 } 363 if (mDisplayListData) { 364 for (size_t i = 0; i < mDisplayListData->children().size(); i++) { 365 mDisplayListData->children()[i]->mRenderNode->destroyHardwareResources(); 366 } 367 if (mNeedsDisplayListDataSync) { 368 // Next prepare tree we are going to push a new display list, so we can 369 // drop our current one now 370 deleteDisplayListData(); 371 } 372 } 373} 374 375void RenderNode::decParentRefCount() { 376 LOG_ALWAYS_FATAL_IF(!mParentCount, "already 0!"); 377 mParentCount--; 378 if (!mParentCount) { 379 // If a child of ours is being attached to our parent then this will incorrectly 380 // destroy its hardware resources. However, this situation is highly unlikely 381 // and the failure is "just" that the layer is re-created, so this should 382 // be safe enough 383 destroyHardwareResources(); 384 } 385} 386 387/* 388 * For property operations, we pass a savecount of 0, since the operations aren't part of the 389 * displaylist, and thus don't have to compensate for the record-time/playback-time discrepancy in 390 * base saveCount (i.e., how RestoreToCount uses saveCount + properties().getCount()) 391 */ 392#define PROPERTY_SAVECOUNT 0 393 394template <class T> 395void RenderNode::setViewProperties(OpenGLRenderer& renderer, T& handler) { 396#if DEBUG_DISPLAY_LIST 397 properties().debugOutputProperties(handler.level() + 1); 398#endif 399 if (properties().getLeft() != 0 || properties().getTop() != 0) { 400 renderer.translate(properties().getLeft(), properties().getTop()); 401 } 402 if (properties().getStaticMatrix()) { 403 renderer.concatMatrix(*properties().getStaticMatrix()); 404 } else if (properties().getAnimationMatrix()) { 405 renderer.concatMatrix(*properties().getAnimationMatrix()); 406 } 407 if (properties().hasTransformMatrix()) { 408 if (properties().isTransformTranslateOnly()) { 409 renderer.translate(properties().getTranslationX(), properties().getTranslationY()); 410 } else { 411 renderer.concatMatrix(*properties().getTransformMatrix()); 412 } 413 } 414 const bool isLayer = properties().layerProperties().type() != kLayerTypeNone; 415 int clipFlags = properties().getClippingFlags(); 416 if (properties().getAlpha() < 1) { 417 if (isLayer) { 418 clipFlags &= ~CLIP_TO_BOUNDS; // bounds clipping done by layer 419 420 renderer.setOverrideLayerAlpha(properties().getAlpha()); 421 } else if (!properties().getHasOverlappingRendering()) { 422 renderer.scaleAlpha(properties().getAlpha()); 423 } else { 424 Rect layerBounds(0, 0, getWidth(), getHeight()); 425 int saveFlags = SkCanvas::kHasAlphaLayer_SaveFlag; 426 if (clipFlags) { 427 saveFlags |= SkCanvas::kClipToLayer_SaveFlag; 428 properties().getClippingRectForFlags(clipFlags, &layerBounds); 429 clipFlags = 0; // all clipping done by saveLayer 430 } 431 432 SaveLayerOp* op = new (handler.allocator()) SaveLayerOp( 433 layerBounds.left, layerBounds.top, layerBounds.right, layerBounds.bottom, 434 properties().getAlpha() * 255, saveFlags); 435 handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds()); 436 } 437 } 438 if (clipFlags) { 439 Rect clipRect; 440 properties().getClippingRectForFlags(clipFlags, &clipRect); 441 ClipRectOp* op = new (handler.allocator()) ClipRectOp( 442 clipRect.left, clipRect.top, clipRect.right, clipRect.bottom, 443 SkRegion::kIntersect_Op); 444 handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds()); 445 } 446 447 // TODO: support nesting round rect clips 448 if (mProperties.getRevealClip().willClip()) { 449 Rect bounds; 450 mProperties.getRevealClip().getBounds(&bounds); 451 renderer.setClippingRoundRect(handler.allocator(), bounds, mProperties.getRevealClip().getRadius()); 452 } else if (mProperties.getOutline().willClip()) { 453 renderer.setClippingOutline(handler.allocator(), &(mProperties.getOutline())); 454 } 455} 456 457/** 458 * Apply property-based transformations to input matrix 459 * 460 * If true3dTransform is set to true, the transform applied to the input matrix will use true 4x4 461 * matrix computation instead of the Skia 3x3 matrix + camera hackery. 462 */ 463void RenderNode::applyViewPropertyTransforms(mat4& matrix, bool true3dTransform) const { 464 if (properties().getLeft() != 0 || properties().getTop() != 0) { 465 matrix.translate(properties().getLeft(), properties().getTop()); 466 } 467 if (properties().getStaticMatrix()) { 468 mat4 stat(*properties().getStaticMatrix()); 469 matrix.multiply(stat); 470 } else if (properties().getAnimationMatrix()) { 471 mat4 anim(*properties().getAnimationMatrix()); 472 matrix.multiply(anim); 473 } 474 475 bool applyTranslationZ = true3dTransform && !MathUtils::isZero(properties().getZ()); 476 if (properties().hasTransformMatrix() || applyTranslationZ) { 477 if (properties().isTransformTranslateOnly()) { 478 matrix.translate(properties().getTranslationX(), properties().getTranslationY(), 479 true3dTransform ? properties().getZ() : 0.0f); 480 } else { 481 if (!true3dTransform) { 482 matrix.multiply(*properties().getTransformMatrix()); 483 } else { 484 mat4 true3dMat; 485 true3dMat.loadTranslate( 486 properties().getPivotX() + properties().getTranslationX(), 487 properties().getPivotY() + properties().getTranslationY(), 488 properties().getZ()); 489 true3dMat.rotate(properties().getRotationX(), 1, 0, 0); 490 true3dMat.rotate(properties().getRotationY(), 0, 1, 0); 491 true3dMat.rotate(properties().getRotation(), 0, 0, 1); 492 true3dMat.scale(properties().getScaleX(), properties().getScaleY(), 1); 493 true3dMat.translate(-properties().getPivotX(), -properties().getPivotY()); 494 495 matrix.multiply(true3dMat); 496 } 497 } 498 } 499} 500 501/** 502 * Organizes the DisplayList hierarchy to prepare for background projection reordering. 503 * 504 * This should be called before a call to defer() or drawDisplayList() 505 * 506 * Each DisplayList that serves as a 3d root builds its list of composited children, 507 * which are flagged to not draw in the standard draw loop. 508 */ 509void RenderNode::computeOrdering() { 510 ATRACE_CALL(); 511 mProjectedNodes.clear(); 512 513 // TODO: create temporary DDLOp and call computeOrderingImpl on top DisplayList so that 514 // transform properties are applied correctly to top level children 515 if (mDisplayListData == NULL) return; 516 for (unsigned int i = 0; i < mDisplayListData->children().size(); i++) { 517 DrawRenderNodeOp* childOp = mDisplayListData->children()[i]; 518 childOp->mRenderNode->computeOrderingImpl(childOp, 519 properties().getOutline().getPath(), &mProjectedNodes, &mat4::identity()); 520 } 521} 522 523void RenderNode::computeOrderingImpl( 524 DrawRenderNodeOp* opState, 525 const SkPath* outlineOfProjectionSurface, 526 Vector<DrawRenderNodeOp*>* compositedChildrenOfProjectionSurface, 527 const mat4* transformFromProjectionSurface) { 528 mProjectedNodes.clear(); 529 if (mDisplayListData == NULL || mDisplayListData->isEmpty()) return; 530 531 // TODO: should avoid this calculation in most cases 532 // TODO: just calculate single matrix, down to all leaf composited elements 533 Matrix4 localTransformFromProjectionSurface(*transformFromProjectionSurface); 534 localTransformFromProjectionSurface.multiply(opState->mTransformFromParent); 535 536 if (properties().getProjectBackwards()) { 537 // composited projectee, flag for out of order draw, save matrix, and store in proj surface 538 opState->mSkipInOrderDraw = true; 539 opState->mTransformFromCompositingAncestor.load(localTransformFromProjectionSurface); 540 compositedChildrenOfProjectionSurface->add(opState); 541 } else { 542 // standard in order draw 543 opState->mSkipInOrderDraw = false; 544 } 545 546 if (mDisplayListData->children().size() > 0) { 547 const bool isProjectionReceiver = mDisplayListData->projectionReceiveIndex >= 0; 548 bool haveAppliedPropertiesToProjection = false; 549 for (unsigned int i = 0; i < mDisplayListData->children().size(); i++) { 550 DrawRenderNodeOp* childOp = mDisplayListData->children()[i]; 551 RenderNode* child = childOp->mRenderNode; 552 553 const SkPath* projectionOutline = NULL; 554 Vector<DrawRenderNodeOp*>* projectionChildren = NULL; 555 const mat4* projectionTransform = NULL; 556 if (isProjectionReceiver && !child->properties().getProjectBackwards()) { 557 // if receiving projections, collect projecting descendent 558 559 // Note that if a direct descendent is projecting backwards, we pass it's 560 // grandparent projection collection, since it shouldn't project onto it's 561 // parent, where it will already be drawing. 562 projectionOutline = properties().getOutline().getPath(); 563 projectionChildren = &mProjectedNodes; 564 projectionTransform = &mat4::identity(); 565 } else { 566 if (!haveAppliedPropertiesToProjection) { 567 applyViewPropertyTransforms(localTransformFromProjectionSurface); 568 haveAppliedPropertiesToProjection = true; 569 } 570 projectionOutline = outlineOfProjectionSurface; 571 projectionChildren = compositedChildrenOfProjectionSurface; 572 projectionTransform = &localTransformFromProjectionSurface; 573 } 574 child->computeOrderingImpl(childOp, 575 projectionOutline, projectionChildren, projectionTransform); 576 } 577 } 578} 579 580class DeferOperationHandler { 581public: 582 DeferOperationHandler(DeferStateStruct& deferStruct, int level) 583 : mDeferStruct(deferStruct), mLevel(level) {} 584 inline void operator()(DisplayListOp* operation, int saveCount, bool clipToBounds) { 585 operation->defer(mDeferStruct, saveCount, mLevel, clipToBounds); 586 } 587 inline LinearAllocator& allocator() { return *(mDeferStruct.mAllocator); } 588 inline void startMark(const char* name) {} // do nothing 589 inline void endMark() {} 590 inline int level() { return mLevel; } 591 inline int replayFlags() { return mDeferStruct.mReplayFlags; } 592 inline SkPath* allocPathForFrame() { return mDeferStruct.allocPathForFrame(); } 593 594private: 595 DeferStateStruct& mDeferStruct; 596 const int mLevel; 597}; 598 599void RenderNode::defer(DeferStateStruct& deferStruct, const int level) { 600 DeferOperationHandler handler(deferStruct, level); 601 issueOperations<DeferOperationHandler>(deferStruct.mRenderer, handler); 602} 603 604class ReplayOperationHandler { 605public: 606 ReplayOperationHandler(ReplayStateStruct& replayStruct, int level) 607 : mReplayStruct(replayStruct), mLevel(level) {} 608 inline void operator()(DisplayListOp* operation, int saveCount, bool clipToBounds) { 609#if DEBUG_DISPLAY_LIST_OPS_AS_EVENTS 610 mReplayStruct.mRenderer.eventMark(operation->name()); 611#endif 612 operation->replay(mReplayStruct, saveCount, mLevel, clipToBounds); 613 } 614 inline LinearAllocator& allocator() { return *(mReplayStruct.mAllocator); } 615 inline void startMark(const char* name) { 616 mReplayStruct.mRenderer.startMark(name); 617 } 618 inline void endMark() { 619 mReplayStruct.mRenderer.endMark(); 620 } 621 inline int level() { return mLevel; } 622 inline int replayFlags() { return mReplayStruct.mReplayFlags; } 623 inline SkPath* allocPathForFrame() { return mReplayStruct.allocPathForFrame(); } 624 625private: 626 ReplayStateStruct& mReplayStruct; 627 const int mLevel; 628}; 629 630void RenderNode::replay(ReplayStateStruct& replayStruct, const int level) { 631 ReplayOperationHandler handler(replayStruct, level); 632 issueOperations<ReplayOperationHandler>(replayStruct.mRenderer, handler); 633} 634 635void RenderNode::buildZSortedChildList(const DisplayListData::Chunk& chunk, 636 Vector<ZDrawRenderNodeOpPair>& zTranslatedNodes) { 637 if (chunk.beginChildIndex == chunk.endChildIndex) return; 638 639 for (unsigned int i = chunk.beginChildIndex; i < chunk.endChildIndex; i++) { 640 DrawRenderNodeOp* childOp = mDisplayListData->children()[i]; 641 RenderNode* child = childOp->mRenderNode; 642 float childZ = child->properties().getZ(); 643 644 if (!MathUtils::isZero(childZ) && chunk.reorderChildren) { 645 zTranslatedNodes.add(ZDrawRenderNodeOpPair(childZ, childOp)); 646 childOp->mSkipInOrderDraw = true; 647 } else if (!child->properties().getProjectBackwards()) { 648 // regular, in order drawing DisplayList 649 childOp->mSkipInOrderDraw = false; 650 } 651 } 652 653 // Z sort any 3d children (stable-ness makes z compare fall back to standard drawing order) 654 std::stable_sort(zTranslatedNodes.begin(), zTranslatedNodes.end()); 655} 656 657template <class T> 658void RenderNode::issueDrawShadowOperation(const Matrix4& transformFromParent, T& handler) { 659 if (properties().getAlpha() <= 0.0f 660 || properties().getOutline().getAlpha() <= 0.0f 661 || !properties().getOutline().getPath()) { 662 // no shadow to draw 663 return; 664 } 665 666 mat4 shadowMatrixXY(transformFromParent); 667 applyViewPropertyTransforms(shadowMatrixXY); 668 669 // Z matrix needs actual 3d transformation, so mapped z values will be correct 670 mat4 shadowMatrixZ(transformFromParent); 671 applyViewPropertyTransforms(shadowMatrixZ, true); 672 673 const SkPath* casterOutlinePath = properties().getOutline().getPath(); 674 const SkPath* revealClipPath = properties().getRevealClip().getPath(); 675 if (revealClipPath && revealClipPath->isEmpty()) return; 676 677 float casterAlpha = properties().getAlpha() * properties().getOutline().getAlpha(); 678 679 const SkPath* outlinePath = casterOutlinePath; 680 if (revealClipPath) { 681 // if we can't simply use the caster's path directly, create a temporary one 682 SkPath* frameAllocatedPath = handler.allocPathForFrame(); 683 684 // intersect the outline with the convex reveal clip 685 Op(*casterOutlinePath, *revealClipPath, kIntersect_PathOp, frameAllocatedPath); 686 outlinePath = frameAllocatedPath; 687 } 688 689 DisplayListOp* shadowOp = new (handler.allocator()) DrawShadowOp( 690 shadowMatrixXY, shadowMatrixZ, casterAlpha, outlinePath); 691 handler(shadowOp, PROPERTY_SAVECOUNT, properties().getClipToBounds()); 692} 693 694#define SHADOW_DELTA 0.1f 695 696template <class T> 697void RenderNode::issueOperationsOf3dChildren(ChildrenSelectMode mode, 698 const Matrix4& initialTransform, const Vector<ZDrawRenderNodeOpPair>& zTranslatedNodes, 699 OpenGLRenderer& renderer, T& handler) { 700 const int size = zTranslatedNodes.size(); 701 if (size == 0 702 || (mode == kNegativeZChildren && zTranslatedNodes[0].key > 0.0f) 703 || (mode == kPositiveZChildren && zTranslatedNodes[size - 1].key < 0.0f)) { 704 // no 3d children to draw 705 return; 706 } 707 708 // Apply the base transform of the parent of the 3d children. This isolates 709 // 3d children of the current chunk from transformations made in previous chunks. 710 int rootRestoreTo = renderer.save(SkCanvas::kMatrix_SaveFlag); 711 renderer.setMatrix(initialTransform); 712 713 /** 714 * Draw shadows and (potential) casters mostly in order, but allow the shadows of casters 715 * with very similar Z heights to draw together. 716 * 717 * This way, if Views A & B have the same Z height and are both casting shadows, the shadows are 718 * underneath both, and neither's shadow is drawn on top of the other. 719 */ 720 const size_t nonNegativeIndex = findNonNegativeIndex(zTranslatedNodes); 721 size_t drawIndex, shadowIndex, endIndex; 722 if (mode == kNegativeZChildren) { 723 drawIndex = 0; 724 endIndex = nonNegativeIndex; 725 shadowIndex = endIndex; // draw no shadows 726 } else { 727 drawIndex = nonNegativeIndex; 728 endIndex = size; 729 shadowIndex = drawIndex; // potentially draw shadow for each pos Z child 730 } 731 732 DISPLAY_LIST_LOGD("%*s%d %s 3d children:", (handler.level() + 1) * 2, "", 733 endIndex - drawIndex, mode == kNegativeZChildren ? "negative" : "positive"); 734 735 float lastCasterZ = 0.0f; 736 while (shadowIndex < endIndex || drawIndex < endIndex) { 737 if (shadowIndex < endIndex) { 738 DrawRenderNodeOp* casterOp = zTranslatedNodes[shadowIndex].value; 739 RenderNode* caster = casterOp->mRenderNode; 740 const float casterZ = zTranslatedNodes[shadowIndex].key; 741 // attempt to render the shadow if the caster about to be drawn is its caster, 742 // OR if its caster's Z value is similar to the previous potential caster 743 if (shadowIndex == drawIndex || casterZ - lastCasterZ < SHADOW_DELTA) { 744 caster->issueDrawShadowOperation(casterOp->mTransformFromParent, handler); 745 746 lastCasterZ = casterZ; // must do this even if current caster not casting a shadow 747 shadowIndex++; 748 continue; 749 } 750 } 751 752 // only the actual child DL draw needs to be in save/restore, 753 // since it modifies the renderer's matrix 754 int restoreTo = renderer.save(SkCanvas::kMatrix_SaveFlag); 755 756 DrawRenderNodeOp* childOp = zTranslatedNodes[drawIndex].value; 757 RenderNode* child = childOp->mRenderNode; 758 759 renderer.concatMatrix(childOp->mTransformFromParent); 760 childOp->mSkipInOrderDraw = false; // this is horrible, I'm so sorry everyone 761 handler(childOp, renderer.getSaveCount() - 1, properties().getClipToBounds()); 762 childOp->mSkipInOrderDraw = true; 763 764 renderer.restoreToCount(restoreTo); 765 drawIndex++; 766 } 767 renderer.restoreToCount(rootRestoreTo); 768} 769 770template <class T> 771void RenderNode::issueOperationsOfProjectedChildren(OpenGLRenderer& renderer, T& handler) { 772 DISPLAY_LIST_LOGD("%*s%d projected children:", (handler.level() + 1) * 2, "", mProjectedNodes.size()); 773 const SkPath* projectionReceiverOutline = properties().getOutline().getPath(); 774 int restoreTo = renderer.getSaveCount(); 775 776 LinearAllocator& alloc = handler.allocator(); 777 handler(new (alloc) SaveOp(SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag), 778 PROPERTY_SAVECOUNT, properties().getClipToBounds()); 779 780 // Transform renderer to match background we're projecting onto 781 // (by offsetting canvas by translationX/Y of background rendernode, since only those are set) 782 const DisplayListOp* op = 783 (mDisplayListData->displayListOps[mDisplayListData->projectionReceiveIndex]); 784 const DrawRenderNodeOp* backgroundOp = reinterpret_cast<const DrawRenderNodeOp*>(op); 785 const RenderProperties& backgroundProps = backgroundOp->mRenderNode->properties(); 786 renderer.translate(backgroundProps.getTranslationX(), backgroundProps.getTranslationY()); 787 788 // If the projection reciever has an outline, we mask each of the projected rendernodes to it 789 // Either with clipRect, or special saveLayer masking 790 if (projectionReceiverOutline != NULL) { 791 const SkRect& outlineBounds = projectionReceiverOutline->getBounds(); 792 if (projectionReceiverOutline->isRect(NULL)) { 793 // mask to the rect outline simply with clipRect 794 ClipRectOp* clipOp = new (alloc) ClipRectOp( 795 outlineBounds.left(), outlineBounds.top(), 796 outlineBounds.right(), outlineBounds.bottom(), SkRegion::kIntersect_Op); 797 handler(clipOp, PROPERTY_SAVECOUNT, properties().getClipToBounds()); 798 } else { 799 // wrap the projected RenderNodes with a SaveLayer that will mask to the outline 800 SaveLayerOp* op = new (alloc) SaveLayerOp( 801 outlineBounds.left(), outlineBounds.top(), 802 outlineBounds.right(), outlineBounds.bottom(), 803 255, SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag | SkCanvas::kARGB_ClipLayer_SaveFlag); 804 op->setMask(projectionReceiverOutline); 805 handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds()); 806 807 /* TODO: add optimizations here to take advantage of placement/size of projected 808 * children (which may shrink saveLayer area significantly). This is dependent on 809 * passing actual drawing/dirtying bounds of projected content down to native. 810 */ 811 } 812 } 813 814 // draw projected nodes 815 for (size_t i = 0; i < mProjectedNodes.size(); i++) { 816 DrawRenderNodeOp* childOp = mProjectedNodes[i]; 817 818 // matrix save, concat, and restore can be done safely without allocating operations 819 int restoreTo = renderer.save(SkCanvas::kMatrix_SaveFlag); 820 renderer.concatMatrix(childOp->mTransformFromCompositingAncestor); 821 childOp->mSkipInOrderDraw = false; // this is horrible, I'm so sorry everyone 822 handler(childOp, renderer.getSaveCount() - 1, properties().getClipToBounds()); 823 childOp->mSkipInOrderDraw = true; 824 renderer.restoreToCount(restoreTo); 825 } 826 827 if (projectionReceiverOutline != NULL) { 828 handler(new (alloc) RestoreToCountOp(restoreTo), 829 PROPERTY_SAVECOUNT, properties().getClipToBounds()); 830 } 831} 832 833/** 834 * This function serves both defer and replay modes, and will organize the displayList's component 835 * operations for a single frame: 836 * 837 * Every 'simple' state operation that affects just the matrix and alpha (or other factors of 838 * DeferredDisplayState) may be issued directly to the renderer, but complex operations (with custom 839 * defer logic) and operations in displayListOps are issued through the 'handler' which handles the 840 * defer vs replay logic, per operation 841 */ 842template <class T> 843void RenderNode::issueOperations(OpenGLRenderer& renderer, T& handler) { 844 const int level = handler.level(); 845 if (mDisplayListData->isEmpty()) { 846 DISPLAY_LIST_LOGD("%*sEmpty display list (%p, %s)", level * 2, "", this, getName()); 847 return; 848 } 849 850 const bool drawLayer = (mLayer && (&renderer != mLayer->renderer)); 851 // If we are updating the contents of mLayer, we don't want to apply any of 852 // the RenderNode's properties to this issueOperations pass. Those will all 853 // be applied when the layer is drawn, aka when this is true. 854 const bool useViewProperties = (!mLayer || drawLayer); 855 if (useViewProperties) { 856 const Outline& outline = properties().getOutline(); 857 if (properties().getAlpha() <= 0 || (outline.getShouldClip() && outline.isEmpty())) { 858 DISPLAY_LIST_LOGD("%*sRejected display list (%p, %s)", level * 2, "", this, getName()); 859 return; 860 } 861 } 862 863 handler.startMark(getName()); 864 865#if DEBUG_DISPLAY_LIST 866 const Rect& clipRect = renderer.getLocalClipBounds(); 867 DISPLAY_LIST_LOGD("%*sStart display list (%p, %s), localClipBounds: %.0f, %.0f, %.0f, %.0f", 868 level * 2, "", this, getName(), 869 clipRect.left, clipRect.top, clipRect.right, clipRect.bottom); 870#endif 871 872 LinearAllocator& alloc = handler.allocator(); 873 int restoreTo = renderer.getSaveCount(); 874 handler(new (alloc) SaveOp(SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag), 875 PROPERTY_SAVECOUNT, properties().getClipToBounds()); 876 877 DISPLAY_LIST_LOGD("%*sSave %d %d", (level + 1) * 2, "", 878 SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag, restoreTo); 879 880 if (useViewProperties) { 881 setViewProperties<T>(renderer, handler); 882 } 883 884 bool quickRejected = properties().getClipToBounds() 885 && renderer.quickRejectConservative(0, 0, properties().getWidth(), properties().getHeight()); 886 if (!quickRejected) { 887 Matrix4 initialTransform(*(renderer.currentTransform())); 888 889 if (drawLayer) { 890 handler(new (alloc) DrawLayerOp(mLayer, 0, 0), 891 renderer.getSaveCount() - 1, properties().getClipToBounds()); 892 } else { 893 const int saveCountOffset = renderer.getSaveCount() - 1; 894 const int projectionReceiveIndex = mDisplayListData->projectionReceiveIndex; 895 DisplayListLogBuffer& logBuffer = DisplayListLogBuffer::getInstance(); 896 for (size_t chunkIndex = 0; chunkIndex < mDisplayListData->getChunks().size(); chunkIndex++) { 897 const DisplayListData::Chunk& chunk = mDisplayListData->getChunks()[chunkIndex]; 898 899 Vector<ZDrawRenderNodeOpPair> zTranslatedNodes; 900 buildZSortedChildList(chunk, zTranslatedNodes); 901 902 issueOperationsOf3dChildren(kNegativeZChildren, 903 initialTransform, zTranslatedNodes, renderer, handler); 904 905 906 for (int opIndex = chunk.beginOpIndex; opIndex < chunk.endOpIndex; opIndex++) { 907 DisplayListOp *op = mDisplayListData->displayListOps[opIndex]; 908#if DEBUG_DISPLAY_LIST 909 op->output(level + 1); 910#endif 911 logBuffer.writeCommand(level, op->name()); 912 handler(op, saveCountOffset, properties().getClipToBounds()); 913 914 if (CC_UNLIKELY(!mProjectedNodes.isEmpty() && opIndex == projectionReceiveIndex)) { 915 issueOperationsOfProjectedChildren(renderer, handler); 916 } 917 } 918 919 issueOperationsOf3dChildren(kPositiveZChildren, 920 initialTransform, zTranslatedNodes, renderer, handler); 921 } 922 } 923 } 924 925 DISPLAY_LIST_LOGD("%*sRestoreToCount %d", (level + 1) * 2, "", restoreTo); 926 handler(new (alloc) RestoreToCountOp(restoreTo), 927 PROPERTY_SAVECOUNT, properties().getClipToBounds()); 928 renderer.setOverrideLayerAlpha(1.0f); 929 930 DISPLAY_LIST_LOGD("%*sDone (%p, %s)", level * 2, "", this, getName()); 931 handler.endMark(); 932} 933 934} /* namespace uirenderer */ 935} /* namespace android */ 936