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