RenderNode.cpp revision 91eff22b5d7f8fe551bae01331948858ce932a96
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#include "RenderNode.h" 18 19#include "DamageAccumulator.h" 20#include "Debug.h" 21#if HWUI_NEW_OPS 22#include "BakedOpRenderer.h" 23#include "RecordedOp.h" 24#include "OpDumper.h" 25#endif 26#include "DisplayListOp.h" 27#include "LayerRenderer.h" 28#include "OpenGLRenderer.h" 29#include "TreeInfo.h" 30#include "utils/MathUtils.h" 31#include "utils/TraceUtils.h" 32#include "renderthread/CanvasContext.h" 33 34#include "protos/hwui.pb.h" 35#include "protos/ProtoHelpers.h" 36 37#include <algorithm> 38#include <sstream> 39#include <string> 40 41namespace android { 42namespace uirenderer { 43 44void RenderNode::debugDumpLayers(const char* prefix) { 45#if HWUI_NEW_OPS 46 LOG_ALWAYS_FATAL("TODO: dump layer"); 47#else 48 if (mLayer) { 49 ALOGD("%sNode %p (%s) has layer %p (fbo = %u, wasBuildLayered = %s)", 50 prefix, this, getName(), mLayer, mLayer->getFbo(), 51 mLayer->wasBuildLayered ? "true" : "false"); 52 } 53#endif 54 if (mDisplayList) { 55 for (auto&& child : mDisplayList->getChildren()) { 56 child->renderNode->debugDumpLayers(prefix); 57 } 58 } 59} 60 61RenderNode::RenderNode() 62 : mDirtyPropertyFields(0) 63 , mNeedsDisplayListSync(false) 64 , mDisplayList(nullptr) 65 , mStagingDisplayList(nullptr) 66 , mAnimatorManager(*this) 67 , mParentCount(0) { 68} 69 70RenderNode::~RenderNode() { 71 deleteDisplayList(); 72 delete mStagingDisplayList; 73#if HWUI_NEW_OPS 74 LOG_ALWAYS_FATAL_IF(mLayer, "layer missed detachment!"); 75#else 76 if (mLayer) { 77 ALOGW("Memory Warning: Layer %p missed its detachment, held on to for far too long!", mLayer); 78 mLayer->postDecStrong(); 79 mLayer = nullptr; 80 } 81#endif 82} 83 84void RenderNode::setStagingDisplayList(DisplayList* displayList) { 85 mNeedsDisplayListSync = true; 86 delete mStagingDisplayList; 87 mStagingDisplayList = displayList; 88 // If mParentCount == 0 we are the sole reference to this RenderNode, 89 // so immediately free the old display list 90 if (!mParentCount && !mStagingDisplayList) { 91 deleteDisplayList(); 92 } 93} 94 95/** 96 * This function is a simplified version of replay(), where we simply retrieve and log the 97 * display list. This function should remain in sync with the replay() function. 98 */ 99#if HWUI_NEW_OPS 100void RenderNode::output(uint32_t level, const char* label) { 101 ALOGD("%s (%s %p%s%s%s%s%s)", 102 label, 103 getName(), 104 this, 105 (MathUtils::isZero(properties().getAlpha()) ? ", zero alpha" : ""), 106 (properties().hasShadow() ? ", casting shadow" : ""), 107 (isRenderable() ? "" : ", empty"), 108 (properties().getProjectBackwards() ? ", projected" : ""), 109 (mLayer != nullptr ? ", on HW Layer" : "")); 110 properties().debugOutputProperties(level + 1); 111 112 if (mDisplayList) { 113 for (auto&& op : mDisplayList->getOps()) { 114 std::stringstream strout; 115 OpDumper::dump(*op, strout, level + 1); 116 if (op->opId == RecordedOpId::RenderNodeOp) { 117 auto rnOp = reinterpret_cast<const RenderNodeOp*>(op); 118 rnOp->renderNode->output(level + 1, strout.str().c_str()); 119 } else { 120 ALOGD("%s", strout.str().c_str()); 121 } 122 } 123 } 124 ALOGD("%*s/RenderNode(%s %p)", level * 2, "", getName(), this); 125} 126#else 127void RenderNode::output(uint32_t level) { 128 ALOGD("%*sStart display list (%p, %s%s%s%s%s%s)", (level - 1) * 2, "", this, 129 getName(), 130 (MathUtils::isZero(properties().getAlpha()) ? ", zero alpha" : ""), 131 (properties().hasShadow() ? ", casting shadow" : ""), 132 (isRenderable() ? "" : ", empty"), 133 (properties().getProjectBackwards() ? ", projected" : ""), 134 (mLayer != nullptr ? ", on HW Layer" : "")); 135 ALOGD("%*s%s %d", level * 2, "", "Save", SaveFlags::MatrixClip); 136 properties().debugOutputProperties(level); 137 if (mDisplayList) { 138 // TODO: consider printing the chunk boundaries here 139 for (auto&& op : mDisplayList->getOps()) { 140 op->output(level, DisplayListOp::kOpLogFlag_Recurse); 141 } 142 } 143 ALOGD("%*sDone (%p, %s)", (level - 1) * 2, "", this, getName()); 144 } 145#endif 146 147void RenderNode::copyTo(proto::RenderNode *pnode) { 148 pnode->set_id(static_cast<uint64_t>( 149 reinterpret_cast<uintptr_t>(this))); 150 pnode->set_name(mName.string(), mName.length()); 151 152 proto::RenderProperties* pprops = pnode->mutable_properties(); 153 pprops->set_left(properties().getLeft()); 154 pprops->set_top(properties().getTop()); 155 pprops->set_right(properties().getRight()); 156 pprops->set_bottom(properties().getBottom()); 157 pprops->set_clip_flags(properties().getClippingFlags()); 158 pprops->set_alpha(properties().getAlpha()); 159 pprops->set_translation_x(properties().getTranslationX()); 160 pprops->set_translation_y(properties().getTranslationY()); 161 pprops->set_translation_z(properties().getTranslationZ()); 162 pprops->set_elevation(properties().getElevation()); 163 pprops->set_rotation(properties().getRotation()); 164 pprops->set_rotation_x(properties().getRotationX()); 165 pprops->set_rotation_y(properties().getRotationY()); 166 pprops->set_scale_x(properties().getScaleX()); 167 pprops->set_scale_y(properties().getScaleY()); 168 pprops->set_pivot_x(properties().getPivotX()); 169 pprops->set_pivot_y(properties().getPivotY()); 170 pprops->set_has_overlapping_rendering(properties().getHasOverlappingRendering()); 171 pprops->set_pivot_explicitly_set(properties().isPivotExplicitlySet()); 172 pprops->set_project_backwards(properties().getProjectBackwards()); 173 pprops->set_projection_receiver(properties().isProjectionReceiver()); 174 set(pprops->mutable_clip_bounds(), properties().getClipBounds()); 175 176 const Outline& outline = properties().getOutline(); 177 if (outline.getType() != Outline::Type::None) { 178 proto::Outline* poutline = pprops->mutable_outline(); 179 poutline->clear_path(); 180 if (outline.getType() == Outline::Type::Empty) { 181 poutline->set_type(proto::Outline_Type_Empty); 182 } else if (outline.getType() == Outline::Type::ConvexPath) { 183 poutline->set_type(proto::Outline_Type_ConvexPath); 184 if (const SkPath* path = outline.getPath()) { 185 set(poutline->mutable_path(), *path); 186 } 187 } else if (outline.getType() == Outline::Type::RoundRect) { 188 poutline->set_type(proto::Outline_Type_RoundRect); 189 } else { 190 ALOGW("Uknown outline type! %d", static_cast<int>(outline.getType())); 191 poutline->set_type(proto::Outline_Type_None); 192 } 193 poutline->set_should_clip(outline.getShouldClip()); 194 poutline->set_alpha(outline.getAlpha()); 195 poutline->set_radius(outline.getRadius()); 196 set(poutline->mutable_bounds(), outline.getBounds()); 197 } else { 198 pprops->clear_outline(); 199 } 200 201 const RevealClip& revealClip = properties().getRevealClip(); 202 if (revealClip.willClip()) { 203 proto::RevealClip* prevealClip = pprops->mutable_reveal_clip(); 204 prevealClip->set_x(revealClip.getX()); 205 prevealClip->set_y(revealClip.getY()); 206 prevealClip->set_radius(revealClip.getRadius()); 207 } else { 208 pprops->clear_reveal_clip(); 209 } 210 211 pnode->clear_children(); 212 if (mDisplayList) { 213 for (auto&& child : mDisplayList->getChildren()) { 214 child->renderNode->copyTo(pnode->add_children()); 215 } 216 } 217} 218 219int RenderNode::getDebugSize() { 220 int size = sizeof(RenderNode); 221 if (mStagingDisplayList) { 222 size += mStagingDisplayList->getUsedSize(); 223 } 224 if (mDisplayList && mDisplayList != mStagingDisplayList) { 225 size += mDisplayList->getUsedSize(); 226 } 227 return size; 228} 229 230void RenderNode::prepareTree(TreeInfo& info) { 231 ATRACE_CALL(); 232 LOG_ALWAYS_FATAL_IF(!info.damageAccumulator, "DamageAccumulator missing"); 233 234 // Functors don't correctly handle stencil usage of overdraw debugging - shove 'em in a layer. 235 bool functorsNeedLayer = Properties::debugOverdraw; 236 237 prepareTreeImpl(info, functorsNeedLayer); 238} 239 240void RenderNode::addAnimator(const sp<BaseRenderNodeAnimator>& animator) { 241 mAnimatorManager.addAnimator(animator); 242} 243 244void RenderNode::removeAnimator(const sp<BaseRenderNodeAnimator>& animator) { 245 mAnimatorManager.removeAnimator(animator); 246} 247 248void RenderNode::damageSelf(TreeInfo& info) { 249 if (isRenderable()) { 250 if (properties().getClipDamageToBounds()) { 251 info.damageAccumulator->dirty(0, 0, properties().getWidth(), properties().getHeight()); 252 } else { 253 // Hope this is big enough? 254 // TODO: Get this from the display list ops or something 255 info.damageAccumulator->dirty(DIRTY_MIN, DIRTY_MIN, DIRTY_MAX, DIRTY_MAX); 256 } 257 } 258} 259 260void RenderNode::prepareLayer(TreeInfo& info, uint32_t dirtyMask) { 261 LayerType layerType = properties().effectiveLayerType(); 262 if (CC_UNLIKELY(layerType == LayerType::RenderLayer)) { 263 // Damage applied so far needs to affect our parent, but does not require 264 // the layer to be updated. So we pop/push here to clear out the current 265 // damage and get a clean state for display list or children updates to 266 // affect, which will require the layer to be updated 267 info.damageAccumulator->popTransform(); 268 info.damageAccumulator->pushTransform(this); 269 if (dirtyMask & DISPLAY_LIST) { 270 damageSelf(info); 271 } 272 } 273} 274 275static layer_t* createLayer(RenderState& renderState, uint32_t width, uint32_t height) { 276#if HWUI_NEW_OPS 277 return renderState.layerPool().get(renderState, width, height); 278#else 279 return LayerRenderer::createRenderLayer(renderState, width, height); 280#endif 281} 282 283static void destroyLayer(layer_t* layer) { 284#if HWUI_NEW_OPS 285 RenderState& renderState = layer->renderState; 286 renderState.layerPool().putOrDelete(layer); 287#else 288 LayerRenderer::destroyLayer(layer); 289#endif 290} 291 292static bool layerMatchesWidthAndHeight(layer_t* layer, int width, int height) { 293#if HWUI_NEW_OPS 294 return layer->viewportWidth == (uint32_t) width && layer->viewportHeight == (uint32_t)height; 295#else 296 return layer->layer.getWidth() == width && layer->layer.getHeight() == height; 297#endif 298} 299 300void RenderNode::pushLayerUpdate(TreeInfo& info) { 301 LayerType layerType = properties().effectiveLayerType(); 302 // If we are not a layer OR we cannot be rendered (eg, view was detached) 303 // we need to destroy any Layers we may have had previously 304 if (CC_LIKELY(layerType != LayerType::RenderLayer) || CC_UNLIKELY(!isRenderable())) { 305 if (CC_UNLIKELY(mLayer)) { 306 destroyLayer(mLayer); 307 mLayer = nullptr; 308 } 309 return; 310 } 311 312 bool transformUpdateNeeded = false; 313 if (!mLayer) { 314 mLayer = createLayer(info.canvasContext.getRenderState(), getWidth(), getHeight()); 315#if !HWUI_NEW_OPS 316 applyLayerPropertiesToLayer(info); 317#endif 318 damageSelf(info); 319 transformUpdateNeeded = true; 320 } else if (!layerMatchesWidthAndHeight(mLayer, getWidth(), getHeight())) { 321#if HWUI_NEW_OPS 322 RenderState& renderState = mLayer->renderState; 323 if (properties().fitsOnLayer()) { 324 mLayer = renderState.layerPool().resize(mLayer, getWidth(), getHeight()); 325 } else { 326#else 327 if (!LayerRenderer::resizeLayer(mLayer, getWidth(), getHeight())) { 328#endif 329 destroyLayer(mLayer); 330 mLayer = nullptr; 331 } 332 damageSelf(info); 333 transformUpdateNeeded = true; 334 } 335 336 SkRect dirty; 337 info.damageAccumulator->peekAtDirty(&dirty); 338 339 if (!mLayer) { 340 Caches::getInstance().dumpMemoryUsage(); 341 if (info.errorHandler) { 342 std::ostringstream err; 343 err << "Unable to create layer for " << getName(); 344 const int maxTextureSize = Caches::getInstance().maxTextureSize; 345 if (getWidth() > maxTextureSize || getHeight() > maxTextureSize) { 346 err << ", size " << getWidth() << "x" << getHeight() 347 << " exceeds max size " << maxTextureSize; 348 } else { 349 err << ", see logcat for more info"; 350 } 351 info.errorHandler->onError(err.str()); 352 } 353 return; 354 } 355 356 if (transformUpdateNeeded && mLayer) { 357 // update the transform in window of the layer to reset its origin wrt light source position 358 Matrix4 windowTransform; 359 info.damageAccumulator->computeCurrentTransform(&windowTransform); 360 mLayer->setWindowTransform(windowTransform); 361 } 362 363#if HWUI_NEW_OPS 364 info.layerUpdateQueue->enqueueLayerWithDamage(this, dirty); 365#else 366 if (dirty.intersect(0, 0, getWidth(), getHeight())) { 367 dirty.roundOut(&dirty); 368 mLayer->updateDeferred(this, dirty.fLeft, dirty.fTop, dirty.fRight, dirty.fBottom); 369 } 370 // This is not inside the above if because we may have called 371 // updateDeferred on a previous prepare pass that didn't have a renderer 372 if (info.renderer && mLayer->deferredUpdateScheduled) { 373 info.renderer->pushLayerUpdate(mLayer); 374 } 375#endif 376 377 // There might be prefetched layers that need to be accounted for. 378 // That might be us, so tell CanvasContext that this layer is in the 379 // tree and should not be destroyed. 380 info.canvasContext.markLayerInUse(this); 381} 382 383/** 384 * Traverse down the the draw tree to prepare for a frame. 385 * 386 * MODE_FULL = UI Thread-driven (thus properties must be synced), otherwise RT driven 387 * 388 * While traversing down the tree, functorsNeedLayer flag is set to true if anything that uses the 389 * stencil buffer may be needed. Views that use a functor to draw will be forced onto a layer. 390 */ 391void RenderNode::prepareTreeImpl(TreeInfo& info, bool functorsNeedLayer) { 392 info.damageAccumulator->pushTransform(this); 393 394 if (info.mode == TreeInfo::MODE_FULL) { 395 pushStagingPropertiesChanges(info); 396 } 397 uint32_t animatorDirtyMask = 0; 398 if (CC_LIKELY(info.runAnimations)) { 399 animatorDirtyMask = mAnimatorManager.animate(info); 400 } 401 402 bool willHaveFunctor = false; 403 if (info.mode == TreeInfo::MODE_FULL && mStagingDisplayList) { 404 willHaveFunctor = !mStagingDisplayList->getFunctors().empty(); 405 } else if (mDisplayList) { 406 willHaveFunctor = !mDisplayList->getFunctors().empty(); 407 } 408 bool childFunctorsNeedLayer = mProperties.prepareForFunctorPresence( 409 willHaveFunctor, functorsNeedLayer); 410 411 if (CC_UNLIKELY(mPositionListener.get())) { 412 mPositionListener->onPositionUpdated(*this, info); 413 } 414 415 prepareLayer(info, animatorDirtyMask); 416 if (info.mode == TreeInfo::MODE_FULL) { 417 pushStagingDisplayListChanges(info); 418 } 419 prepareSubTree(info, childFunctorsNeedLayer, mDisplayList); 420 pushLayerUpdate(info); 421 422 info.damageAccumulator->popTransform(); 423} 424 425void RenderNode::syncProperties() { 426 mProperties = mStagingProperties; 427} 428 429void RenderNode::pushStagingPropertiesChanges(TreeInfo& info) { 430 // Push the animators first so that setupStartValueIfNecessary() is called 431 // before properties() is trampled by stagingProperties(), as they are 432 // required by some animators. 433 if (CC_LIKELY(info.runAnimations)) { 434 mAnimatorManager.pushStaging(); 435 } 436 if (mDirtyPropertyFields) { 437 mDirtyPropertyFields = 0; 438 damageSelf(info); 439 info.damageAccumulator->popTransform(); 440 syncProperties(); 441#if !HWUI_NEW_OPS 442 applyLayerPropertiesToLayer(info); 443#endif 444 // We could try to be clever and only re-damage if the matrix changed. 445 // However, we don't need to worry about that. The cost of over-damaging 446 // here is only going to be a single additional map rect of this node 447 // plus a rect join(). The parent's transform (and up) will only be 448 // performed once. 449 info.damageAccumulator->pushTransform(this); 450 damageSelf(info); 451 } 452} 453 454#if !HWUI_NEW_OPS 455void RenderNode::applyLayerPropertiesToLayer(TreeInfo& info) { 456 if (CC_LIKELY(!mLayer)) return; 457 458 const LayerProperties& props = properties().layerProperties(); 459 mLayer->setAlpha(props.alpha(), props.xferMode()); 460 mLayer->setColorFilter(props.colorFilter()); 461 mLayer->setBlend(props.needsBlending()); 462} 463#endif 464 465void RenderNode::syncDisplayList() { 466 // Make sure we inc first so that we don't fluctuate between 0 and 1, 467 // which would thrash the layer cache 468 if (mStagingDisplayList) { 469 for (auto&& child : mStagingDisplayList->getChildren()) { 470 child->renderNode->incParentRefCount(); 471 } 472 } 473 deleteDisplayList(); 474 mDisplayList = mStagingDisplayList; 475 mStagingDisplayList = nullptr; 476 if (mDisplayList) { 477 for (size_t i = 0; i < mDisplayList->getFunctors().size(); i++) { 478 (*mDisplayList->getFunctors()[i])(DrawGlInfo::kModeSync, nullptr); 479 } 480 } 481} 482 483void RenderNode::pushStagingDisplayListChanges(TreeInfo& info) { 484 if (mNeedsDisplayListSync) { 485 mNeedsDisplayListSync = false; 486 // Damage with the old display list first then the new one to catch any 487 // changes in isRenderable or, in the future, bounds 488 damageSelf(info); 489 syncDisplayList(); 490 damageSelf(info); 491 } 492} 493 494void RenderNode::deleteDisplayList() { 495 if (mDisplayList) { 496 for (auto&& child : mDisplayList->getChildren()) { 497 child->renderNode->decParentRefCount(); 498 } 499 } 500 delete mDisplayList; 501 mDisplayList = nullptr; 502} 503 504void RenderNode::prepareSubTree(TreeInfo& info, bool functorsNeedLayer, DisplayList* subtree) { 505 if (subtree) { 506 TextureCache& cache = Caches::getInstance().textureCache; 507 info.out.hasFunctors |= subtree->getFunctors().size(); 508 for (auto&& bitmapResource : subtree->getBitmapResources()) { 509 void* ownerToken = &info.canvasContext; 510 info.prepareTextures = cache.prefetchAndMarkInUse(ownerToken, bitmapResource); 511 } 512 for (auto&& op : subtree->getChildren()) { 513 RenderNode* childNode = op->renderNode; 514#if HWUI_NEW_OPS 515 info.damageAccumulator->pushTransform(&op->localMatrix); 516 bool childFunctorsNeedLayer = functorsNeedLayer; // TODO! || op->mRecordedWithPotentialStencilClip; 517#else 518 info.damageAccumulator->pushTransform(&op->localMatrix); 519 bool childFunctorsNeedLayer = functorsNeedLayer 520 // Recorded with non-rect clip, or canvas-rotated by parent 521 || op->mRecordedWithPotentialStencilClip; 522#endif 523 childNode->prepareTreeImpl(info, childFunctorsNeedLayer); 524 info.damageAccumulator->popTransform(); 525 } 526 } 527} 528 529void RenderNode::destroyHardwareResources() { 530 if (mLayer) { 531 destroyLayer(mLayer); 532 mLayer = nullptr; 533 } 534 if (mDisplayList) { 535 for (auto&& child : mDisplayList->getChildren()) { 536 child->renderNode->destroyHardwareResources(); 537 } 538 if (mNeedsDisplayListSync) { 539 // Next prepare tree we are going to push a new display list, so we can 540 // drop our current one now 541 deleteDisplayList(); 542 } 543 } 544} 545 546void RenderNode::decParentRefCount() { 547 LOG_ALWAYS_FATAL_IF(!mParentCount, "already 0!"); 548 mParentCount--; 549 if (!mParentCount) { 550 // If a child of ours is being attached to our parent then this will incorrectly 551 // destroy its hardware resources. However, this situation is highly unlikely 552 // and the failure is "just" that the layer is re-created, so this should 553 // be safe enough 554 destroyHardwareResources(); 555 } 556} 557 558/* 559 * For property operations, we pass a savecount of 0, since the operations aren't part of the 560 * displaylist, and thus don't have to compensate for the record-time/playback-time discrepancy in 561 * base saveCount (i.e., how RestoreToCount uses saveCount + properties().getCount()) 562 */ 563#define PROPERTY_SAVECOUNT 0 564 565template <class T> 566void RenderNode::setViewProperties(OpenGLRenderer& renderer, T& handler) { 567#if DEBUG_DISPLAY_LIST 568 properties().debugOutputProperties(handler.level() + 1); 569#endif 570 if (properties().getLeft() != 0 || properties().getTop() != 0) { 571 renderer.translate(properties().getLeft(), properties().getTop()); 572 } 573 if (properties().getStaticMatrix()) { 574 renderer.concatMatrix(*properties().getStaticMatrix()); 575 } else if (properties().getAnimationMatrix()) { 576 renderer.concatMatrix(*properties().getAnimationMatrix()); 577 } 578 if (properties().hasTransformMatrix()) { 579 if (properties().isTransformTranslateOnly()) { 580 renderer.translate(properties().getTranslationX(), properties().getTranslationY()); 581 } else { 582 renderer.concatMatrix(*properties().getTransformMatrix()); 583 } 584 } 585 const bool isLayer = properties().effectiveLayerType() != LayerType::None; 586 int clipFlags = properties().getClippingFlags(); 587 if (properties().getAlpha() < 1) { 588 if (isLayer) { 589 clipFlags &= ~CLIP_TO_BOUNDS; // bounds clipping done by layer 590 } 591 if (CC_LIKELY(isLayer || !properties().getHasOverlappingRendering())) { 592 // simply scale rendering content's alpha 593 renderer.scaleAlpha(properties().getAlpha()); 594 } else { 595 // savelayer needed to create an offscreen buffer 596 Rect layerBounds(0, 0, getWidth(), getHeight()); 597 if (clipFlags) { 598 properties().getClippingRectForFlags(clipFlags, &layerBounds); 599 clipFlags = 0; // all clipping done by savelayer 600 } 601 SaveLayerOp* op = new (handler.allocator()) SaveLayerOp( 602 layerBounds.left, layerBounds.top, 603 layerBounds.right, layerBounds.bottom, 604 (int) (properties().getAlpha() * 255), 605 SaveFlags::HasAlphaLayer | SaveFlags::ClipToLayer); 606 handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds()); 607 } 608 609 if (CC_UNLIKELY(ATRACE_ENABLED() && properties().promotedToLayer())) { 610 // pretend alpha always causes savelayer to warn about 611 // performance problem affecting old versions 612 ATRACE_FORMAT("%s alpha caused saveLayer %dx%d", getName(), 613 static_cast<int>(getWidth()), 614 static_cast<int>(getHeight())); 615 } 616 } 617 if (clipFlags) { 618 Rect clipRect; 619 properties().getClippingRectForFlags(clipFlags, &clipRect); 620 ClipRectOp* op = new (handler.allocator()) ClipRectOp( 621 clipRect.left, clipRect.top, clipRect.right, clipRect.bottom, 622 SkRegion::kIntersect_Op); 623 handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds()); 624 } 625 626 // TODO: support nesting round rect clips 627 if (mProperties.getRevealClip().willClip()) { 628 Rect bounds; 629 mProperties.getRevealClip().getBounds(&bounds); 630 renderer.setClippingRoundRect(handler.allocator(), bounds, mProperties.getRevealClip().getRadius()); 631 } else if (mProperties.getOutline().willClip()) { 632 renderer.setClippingOutline(handler.allocator(), &(mProperties.getOutline())); 633 } 634} 635 636/** 637 * Apply property-based transformations to input matrix 638 * 639 * If true3dTransform is set to true, the transform applied to the input matrix will use true 4x4 640 * matrix computation instead of the Skia 3x3 matrix + camera hackery. 641 */ 642void RenderNode::applyViewPropertyTransforms(mat4& matrix, bool true3dTransform) const { 643 if (properties().getLeft() != 0 || properties().getTop() != 0) { 644 matrix.translate(properties().getLeft(), properties().getTop()); 645 } 646 if (properties().getStaticMatrix()) { 647 mat4 stat(*properties().getStaticMatrix()); 648 matrix.multiply(stat); 649 } else if (properties().getAnimationMatrix()) { 650 mat4 anim(*properties().getAnimationMatrix()); 651 matrix.multiply(anim); 652 } 653 654 bool applyTranslationZ = true3dTransform && !MathUtils::isZero(properties().getZ()); 655 if (properties().hasTransformMatrix() || applyTranslationZ) { 656 if (properties().isTransformTranslateOnly()) { 657 matrix.translate(properties().getTranslationX(), properties().getTranslationY(), 658 true3dTransform ? properties().getZ() : 0.0f); 659 } else { 660 if (!true3dTransform) { 661 matrix.multiply(*properties().getTransformMatrix()); 662 } else { 663 mat4 true3dMat; 664 true3dMat.loadTranslate( 665 properties().getPivotX() + properties().getTranslationX(), 666 properties().getPivotY() + properties().getTranslationY(), 667 properties().getZ()); 668 true3dMat.rotate(properties().getRotationX(), 1, 0, 0); 669 true3dMat.rotate(properties().getRotationY(), 0, 1, 0); 670 true3dMat.rotate(properties().getRotation(), 0, 0, 1); 671 true3dMat.scale(properties().getScaleX(), properties().getScaleY(), 1); 672 true3dMat.translate(-properties().getPivotX(), -properties().getPivotY()); 673 674 matrix.multiply(true3dMat); 675 } 676 } 677 } 678} 679 680/** 681 * Organizes the DisplayList hierarchy to prepare for background projection reordering. 682 * 683 * This should be called before a call to defer() or drawDisplayList() 684 * 685 * Each DisplayList that serves as a 3d root builds its list of composited children, 686 * which are flagged to not draw in the standard draw loop. 687 */ 688void RenderNode::computeOrdering() { 689 ATRACE_CALL(); 690 mProjectedNodes.clear(); 691 692 // TODO: create temporary DDLOp and call computeOrderingImpl on top DisplayList so that 693 // transform properties are applied correctly to top level children 694 if (mDisplayList == nullptr) return; 695 for (unsigned int i = 0; i < mDisplayList->getChildren().size(); i++) { 696 renderNodeOp_t* childOp = mDisplayList->getChildren()[i]; 697 childOp->renderNode->computeOrderingImpl(childOp, &mProjectedNodes, &mat4::identity()); 698 } 699} 700 701void RenderNode::computeOrderingImpl( 702 renderNodeOp_t* opState, 703 std::vector<renderNodeOp_t*>* compositedChildrenOfProjectionSurface, 704 const mat4* transformFromProjectionSurface) { 705 mProjectedNodes.clear(); 706 if (mDisplayList == nullptr || mDisplayList->isEmpty()) return; 707 708 // TODO: should avoid this calculation in most cases 709 // TODO: just calculate single matrix, down to all leaf composited elements 710 Matrix4 localTransformFromProjectionSurface(*transformFromProjectionSurface); 711 localTransformFromProjectionSurface.multiply(opState->localMatrix); 712 713 if (properties().getProjectBackwards()) { 714 // composited projectee, flag for out of order draw, save matrix, and store in proj surface 715 opState->skipInOrderDraw = true; 716 opState->transformFromCompositingAncestor = localTransformFromProjectionSurface; 717 compositedChildrenOfProjectionSurface->push_back(opState); 718 } else { 719 // standard in order draw 720 opState->skipInOrderDraw = false; 721 } 722 723 if (mDisplayList->getChildren().size() > 0) { 724 const bool isProjectionReceiver = mDisplayList->projectionReceiveIndex >= 0; 725 bool haveAppliedPropertiesToProjection = false; 726 for (unsigned int i = 0; i < mDisplayList->getChildren().size(); i++) { 727 renderNodeOp_t* childOp = mDisplayList->getChildren()[i]; 728 RenderNode* child = childOp->renderNode; 729 730 std::vector<renderNodeOp_t*>* projectionChildren = nullptr; 731 const mat4* projectionTransform = nullptr; 732 if (isProjectionReceiver && !child->properties().getProjectBackwards()) { 733 // if receiving projections, collect projecting descendant 734 735 // Note that if a direct descendant is projecting backwards, we pass its 736 // grandparent projection collection, since it shouldn't project onto its 737 // parent, where it will already be drawing. 738 projectionChildren = &mProjectedNodes; 739 projectionTransform = &mat4::identity(); 740 } else { 741 if (!haveAppliedPropertiesToProjection) { 742 applyViewPropertyTransforms(localTransformFromProjectionSurface); 743 haveAppliedPropertiesToProjection = true; 744 } 745 projectionChildren = compositedChildrenOfProjectionSurface; 746 projectionTransform = &localTransformFromProjectionSurface; 747 } 748 child->computeOrderingImpl(childOp, projectionChildren, projectionTransform); 749 } 750 } 751} 752 753class DeferOperationHandler { 754public: 755 DeferOperationHandler(DeferStateStruct& deferStruct, int level) 756 : mDeferStruct(deferStruct), mLevel(level) {} 757 inline void operator()(DisplayListOp* operation, int saveCount, bool clipToBounds) { 758 operation->defer(mDeferStruct, saveCount, mLevel, clipToBounds); 759 } 760 inline LinearAllocator& allocator() { return *(mDeferStruct.mAllocator); } 761 inline void startMark(const char* name) {} // do nothing 762 inline void endMark() {} 763 inline int level() { return mLevel; } 764 inline int replayFlags() { return mDeferStruct.mReplayFlags; } 765 inline SkPath* allocPathForFrame() { return mDeferStruct.allocPathForFrame(); } 766 767private: 768 DeferStateStruct& mDeferStruct; 769 const int mLevel; 770}; 771 772void RenderNode::defer(DeferStateStruct& deferStruct, const int level) { 773 DeferOperationHandler handler(deferStruct, level); 774 issueOperations<DeferOperationHandler>(deferStruct.mRenderer, handler); 775} 776 777class ReplayOperationHandler { 778public: 779 ReplayOperationHandler(ReplayStateStruct& replayStruct, int level) 780 : mReplayStruct(replayStruct), mLevel(level) {} 781 inline void operator()(DisplayListOp* operation, int saveCount, bool clipToBounds) { 782#if DEBUG_DISPLAY_LIST_OPS_AS_EVENTS 783 mReplayStruct.mRenderer.eventMark(operation->name()); 784#endif 785 operation->replay(mReplayStruct, saveCount, mLevel, clipToBounds); 786 } 787 inline LinearAllocator& allocator() { return *(mReplayStruct.mAllocator); } 788 inline void startMark(const char* name) { 789 mReplayStruct.mRenderer.startMark(name); 790 } 791 inline void endMark() { 792 mReplayStruct.mRenderer.endMark(); 793 } 794 inline int level() { return mLevel; } 795 inline int replayFlags() { return mReplayStruct.mReplayFlags; } 796 inline SkPath* allocPathForFrame() { return mReplayStruct.allocPathForFrame(); } 797 798private: 799 ReplayStateStruct& mReplayStruct; 800 const int mLevel; 801}; 802 803void RenderNode::replay(ReplayStateStruct& replayStruct, const int level) { 804 ReplayOperationHandler handler(replayStruct, level); 805 issueOperations<ReplayOperationHandler>(replayStruct.mRenderer, handler); 806} 807 808void RenderNode::buildZSortedChildList(const DisplayList::Chunk& chunk, 809 std::vector<ZDrawRenderNodeOpPair>& zTranslatedNodes) { 810#if !HWUI_NEW_OPS 811 if (chunk.beginChildIndex == chunk.endChildIndex) return; 812 813 for (unsigned int i = chunk.beginChildIndex; i < chunk.endChildIndex; i++) { 814 DrawRenderNodeOp* childOp = mDisplayList->getChildren()[i]; 815 RenderNode* child = childOp->renderNode; 816 float childZ = child->properties().getZ(); 817 818 if (!MathUtils::isZero(childZ) && chunk.reorderChildren) { 819 zTranslatedNodes.push_back(ZDrawRenderNodeOpPair(childZ, childOp)); 820 childOp->skipInOrderDraw = true; 821 } else if (!child->properties().getProjectBackwards()) { 822 // regular, in order drawing DisplayList 823 childOp->skipInOrderDraw = false; 824 } 825 } 826 827 // Z sort any 3d children (stable-ness makes z compare fall back to standard drawing order) 828 std::stable_sort(zTranslatedNodes.begin(), zTranslatedNodes.end()); 829#endif 830} 831 832template <class T> 833void RenderNode::issueDrawShadowOperation(const Matrix4& transformFromParent, T& handler) { 834 if (properties().getAlpha() <= 0.0f 835 || properties().getOutline().getAlpha() <= 0.0f 836 || !properties().getOutline().getPath() 837 || properties().getScaleX() == 0 838 || properties().getScaleY() == 0) { 839 // no shadow to draw 840 return; 841 } 842 843 mat4 shadowMatrixXY(transformFromParent); 844 applyViewPropertyTransforms(shadowMatrixXY); 845 846 // Z matrix needs actual 3d transformation, so mapped z values will be correct 847 mat4 shadowMatrixZ(transformFromParent); 848 applyViewPropertyTransforms(shadowMatrixZ, true); 849 850 const SkPath* casterOutlinePath = properties().getOutline().getPath(); 851 const SkPath* revealClipPath = properties().getRevealClip().getPath(); 852 if (revealClipPath && revealClipPath->isEmpty()) return; 853 854 float casterAlpha = properties().getAlpha() * properties().getOutline().getAlpha(); 855 856 857 // holds temporary SkPath to store the result of intersections 858 SkPath* frameAllocatedPath = nullptr; 859 const SkPath* outlinePath = casterOutlinePath; 860 861 // intersect the outline with the reveal clip, if present 862 if (revealClipPath) { 863 frameAllocatedPath = handler.allocPathForFrame(); 864 865 Op(*outlinePath, *revealClipPath, kIntersect_SkPathOp, frameAllocatedPath); 866 outlinePath = frameAllocatedPath; 867 } 868 869 // intersect the outline with the clipBounds, if present 870 if (properties().getClippingFlags() & CLIP_TO_CLIP_BOUNDS) { 871 if (!frameAllocatedPath) { 872 frameAllocatedPath = handler.allocPathForFrame(); 873 } 874 875 Rect clipBounds; 876 properties().getClippingRectForFlags(CLIP_TO_CLIP_BOUNDS, &clipBounds); 877 SkPath clipBoundsPath; 878 clipBoundsPath.addRect(clipBounds.left, clipBounds.top, 879 clipBounds.right, clipBounds.bottom); 880 881 Op(*outlinePath, clipBoundsPath, kIntersect_SkPathOp, frameAllocatedPath); 882 outlinePath = frameAllocatedPath; 883 } 884 885 DisplayListOp* shadowOp = new (handler.allocator()) DrawShadowOp( 886 shadowMatrixXY, shadowMatrixZ, casterAlpha, outlinePath); 887 handler(shadowOp, PROPERTY_SAVECOUNT, properties().getClipToBounds()); 888} 889 890#define SHADOW_DELTA 0.1f 891 892template <class T> 893void RenderNode::issueOperationsOf3dChildren(ChildrenSelectMode mode, 894 const Matrix4& initialTransform, const std::vector<ZDrawRenderNodeOpPair>& zTranslatedNodes, 895 OpenGLRenderer& renderer, T& handler) { 896 const int size = zTranslatedNodes.size(); 897 if (size == 0 898 || (mode == ChildrenSelectMode::NegativeZChildren && zTranslatedNodes[0].key > 0.0f) 899 || (mode == ChildrenSelectMode::PositiveZChildren && zTranslatedNodes[size - 1].key < 0.0f)) { 900 // no 3d children to draw 901 return; 902 } 903 904 // Apply the base transform of the parent of the 3d children. This isolates 905 // 3d children of the current chunk from transformations made in previous chunks. 906 int rootRestoreTo = renderer.save(SaveFlags::Matrix); 907 renderer.setGlobalMatrix(initialTransform); 908 909 /** 910 * Draw shadows and (potential) casters mostly in order, but allow the shadows of casters 911 * with very similar Z heights to draw together. 912 * 913 * This way, if Views A & B have the same Z height and are both casting shadows, the shadows are 914 * underneath both, and neither's shadow is drawn on top of the other. 915 */ 916 const size_t nonNegativeIndex = findNonNegativeIndex(zTranslatedNodes); 917 size_t drawIndex, shadowIndex, endIndex; 918 if (mode == ChildrenSelectMode::NegativeZChildren) { 919 drawIndex = 0; 920 endIndex = nonNegativeIndex; 921 shadowIndex = endIndex; // draw no shadows 922 } else { 923 drawIndex = nonNegativeIndex; 924 endIndex = size; 925 shadowIndex = drawIndex; // potentially draw shadow for each pos Z child 926 } 927 928 DISPLAY_LIST_LOGD("%*s%d %s 3d children:", (handler.level() + 1) * 2, "", 929 endIndex - drawIndex, mode == kNegativeZChildren ? "negative" : "positive"); 930 931 float lastCasterZ = 0.0f; 932 while (shadowIndex < endIndex || drawIndex < endIndex) { 933 if (shadowIndex < endIndex) { 934 DrawRenderNodeOp* casterOp = zTranslatedNodes[shadowIndex].value; 935 RenderNode* caster = casterOp->renderNode; 936 const float casterZ = zTranslatedNodes[shadowIndex].key; 937 // attempt to render the shadow if the caster about to be drawn is its caster, 938 // OR if its caster's Z value is similar to the previous potential caster 939 if (shadowIndex == drawIndex || casterZ - lastCasterZ < SHADOW_DELTA) { 940 caster->issueDrawShadowOperation(casterOp->localMatrix, handler); 941 942 lastCasterZ = casterZ; // must do this even if current caster not casting a shadow 943 shadowIndex++; 944 continue; 945 } 946 } 947 948 // only the actual child DL draw needs to be in save/restore, 949 // since it modifies the renderer's matrix 950 int restoreTo = renderer.save(SaveFlags::Matrix); 951 952 DrawRenderNodeOp* childOp = zTranslatedNodes[drawIndex].value; 953 954 renderer.concatMatrix(childOp->localMatrix); 955 childOp->skipInOrderDraw = false; // this is horrible, I'm so sorry everyone 956 handler(childOp, renderer.getSaveCount() - 1, properties().getClipToBounds()); 957 childOp->skipInOrderDraw = true; 958 959 renderer.restoreToCount(restoreTo); 960 drawIndex++; 961 } 962 renderer.restoreToCount(rootRestoreTo); 963} 964 965template <class T> 966void RenderNode::issueOperationsOfProjectedChildren(OpenGLRenderer& renderer, T& handler) { 967 DISPLAY_LIST_LOGD("%*s%d projected children:", (handler.level() + 1) * 2, "", mProjectedNodes.size()); 968 const SkPath* projectionReceiverOutline = properties().getOutline().getPath(); 969 int restoreTo = renderer.getSaveCount(); 970 971 LinearAllocator& alloc = handler.allocator(); 972 handler(new (alloc) SaveOp(SaveFlags::MatrixClip), 973 PROPERTY_SAVECOUNT, properties().getClipToBounds()); 974 975 // Transform renderer to match background we're projecting onto 976 // (by offsetting canvas by translationX/Y of background rendernode, since only those are set) 977 const DisplayListOp* op = 978#if HWUI_NEW_OPS 979 nullptr; 980 LOG_ALWAYS_FATAL("unsupported"); 981#else 982 (mDisplayList->getOps()[mDisplayList->projectionReceiveIndex]); 983#endif 984 const DrawRenderNodeOp* backgroundOp = reinterpret_cast<const DrawRenderNodeOp*>(op); 985 const RenderProperties& backgroundProps = backgroundOp->renderNode->properties(); 986 renderer.translate(backgroundProps.getTranslationX(), backgroundProps.getTranslationY()); 987 988 // If the projection receiver has an outline, we mask projected content to it 989 // (which we know, apriori, are all tessellated paths) 990 renderer.setProjectionPathMask(alloc, projectionReceiverOutline); 991 992 // draw projected nodes 993 for (size_t i = 0; i < mProjectedNodes.size(); i++) { 994 renderNodeOp_t* childOp = mProjectedNodes[i]; 995 996 // matrix save, concat, and restore can be done safely without allocating operations 997 int restoreTo = renderer.save(SaveFlags::Matrix); 998 renderer.concatMatrix(childOp->transformFromCompositingAncestor); 999 childOp->skipInOrderDraw = false; // this is horrible, I'm so sorry everyone 1000 handler(childOp, renderer.getSaveCount() - 1, properties().getClipToBounds()); 1001 childOp->skipInOrderDraw = true; 1002 renderer.restoreToCount(restoreTo); 1003 } 1004 1005 handler(new (alloc) RestoreToCountOp(restoreTo), 1006 PROPERTY_SAVECOUNT, properties().getClipToBounds()); 1007} 1008 1009/** 1010 * This function serves both defer and replay modes, and will organize the displayList's component 1011 * operations for a single frame: 1012 * 1013 * Every 'simple' state operation that affects just the matrix and alpha (or other factors of 1014 * DeferredDisplayState) may be issued directly to the renderer, but complex operations (with custom 1015 * defer logic) and operations in displayListOps are issued through the 'handler' which handles the 1016 * defer vs replay logic, per operation 1017 */ 1018template <class T> 1019void RenderNode::issueOperations(OpenGLRenderer& renderer, T& handler) { 1020 if (mDisplayList->isEmpty()) { 1021 DISPLAY_LIST_LOGD("%*sEmpty display list (%p, %s)", handler.level() * 2, "", 1022 this, getName()); 1023 return; 1024 } 1025 1026#if HWUI_NEW_OPS 1027 const bool drawLayer = false; 1028#else 1029 const bool drawLayer = (mLayer && (&renderer != mLayer->renderer.get())); 1030#endif 1031 // If we are updating the contents of mLayer, we don't want to apply any of 1032 // the RenderNode's properties to this issueOperations pass. Those will all 1033 // be applied when the layer is drawn, aka when this is true. 1034 const bool useViewProperties = (!mLayer || drawLayer); 1035 if (useViewProperties) { 1036 const Outline& outline = properties().getOutline(); 1037 if (properties().getAlpha() <= 0 1038 || (outline.getShouldClip() && outline.isEmpty()) 1039 || properties().getScaleX() == 0 1040 || properties().getScaleY() == 0) { 1041 DISPLAY_LIST_LOGD("%*sRejected display list (%p, %s)", handler.level() * 2, "", 1042 this, getName()); 1043 return; 1044 } 1045 } 1046 1047 handler.startMark(getName()); 1048 1049#if DEBUG_DISPLAY_LIST 1050 const Rect& clipRect = renderer.getLocalClipBounds(); 1051 DISPLAY_LIST_LOGD("%*sStart display list (%p, %s), localClipBounds: %.0f, %.0f, %.0f, %.0f", 1052 handler.level() * 2, "", this, getName(), 1053 clipRect.left, clipRect.top, clipRect.right, clipRect.bottom); 1054#endif 1055 1056 LinearAllocator& alloc = handler.allocator(); 1057 int restoreTo = renderer.getSaveCount(); 1058 handler(new (alloc) SaveOp(SaveFlags::MatrixClip), 1059 PROPERTY_SAVECOUNT, properties().getClipToBounds()); 1060 1061 DISPLAY_LIST_LOGD("%*sSave %d %d", (handler.level() + 1) * 2, "", 1062 SaveFlags::MatrixClip, restoreTo); 1063 1064 if (useViewProperties) { 1065 setViewProperties<T>(renderer, handler); 1066 } 1067 1068#if HWUI_NEW_OPS 1069 LOG_ALWAYS_FATAL("legacy op traversal not supported"); 1070#else 1071 bool quickRejected = properties().getClipToBounds() 1072 && renderer.quickRejectConservative(0, 0, properties().getWidth(), properties().getHeight()); 1073 if (!quickRejected) { 1074 Matrix4 initialTransform(*(renderer.currentTransform())); 1075 renderer.setBaseTransform(initialTransform); 1076 1077 if (drawLayer) { 1078 handler(new (alloc) DrawLayerOp(mLayer), 1079 renderer.getSaveCount() - 1, properties().getClipToBounds()); 1080 } else { 1081 const int saveCountOffset = renderer.getSaveCount() - 1; 1082 const int projectionReceiveIndex = mDisplayList->projectionReceiveIndex; 1083 for (size_t chunkIndex = 0; chunkIndex < mDisplayList->getChunks().size(); chunkIndex++) { 1084 const DisplayList::Chunk& chunk = mDisplayList->getChunks()[chunkIndex]; 1085 1086 std::vector<ZDrawRenderNodeOpPair> zTranslatedNodes; 1087 buildZSortedChildList(chunk, zTranslatedNodes); 1088 1089 issueOperationsOf3dChildren(ChildrenSelectMode::NegativeZChildren, 1090 initialTransform, zTranslatedNodes, renderer, handler); 1091 1092 for (size_t opIndex = chunk.beginOpIndex; opIndex < chunk.endOpIndex; opIndex++) { 1093 DisplayListOp *op = mDisplayList->getOps()[opIndex]; 1094#if DEBUG_DISPLAY_LIST 1095 op->output(handler.level() + 1); 1096#endif 1097 handler(op, saveCountOffset, properties().getClipToBounds()); 1098 1099 if (CC_UNLIKELY(!mProjectedNodes.empty() && projectionReceiveIndex >= 0 && 1100 opIndex == static_cast<size_t>(projectionReceiveIndex))) { 1101 issueOperationsOfProjectedChildren(renderer, handler); 1102 } 1103 } 1104 1105 issueOperationsOf3dChildren(ChildrenSelectMode::PositiveZChildren, 1106 initialTransform, zTranslatedNodes, renderer, handler); 1107 } 1108 } 1109 } 1110#endif 1111 1112 DISPLAY_LIST_LOGD("%*sRestoreToCount %d", (handler.level() + 1) * 2, "", restoreTo); 1113 handler(new (alloc) RestoreToCountOp(restoreTo), 1114 PROPERTY_SAVECOUNT, properties().getClipToBounds()); 1115 1116 DISPLAY_LIST_LOGD("%*sDone (%p, %s)", handler.level() * 2, "", this, getName()); 1117 handler.endMark(); 1118} 1119 1120} /* namespace uirenderer */ 1121} /* namespace android */ 1122