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