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