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