RenderNode.cpp revision 34bf49e4de4c1994b5d9c19166606bc9b7ad1b9c
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(nullptr);
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, TreeObserver* observer) {
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(observer);
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        // TODO: remove now irrelevant, currently enqueued damage (respecting damage ordering)
323        // Or, ideally, maintain damage between frames on node/layer so ordering is always correct
324        RenderState& renderState = mLayer->renderState;
325        if (properties().fitsOnLayer()) {
326            mLayer = renderState.layerPool().resize(mLayer, getWidth(), getHeight());
327        } else {
328#else
329        if (!LayerRenderer::resizeLayer(mLayer, getWidth(), getHeight())) {
330#endif
331            destroyLayer(mLayer);
332            mLayer = nullptr;
333        }
334        damageSelf(info);
335        transformUpdateNeeded = true;
336    }
337
338    SkRect dirty;
339    info.damageAccumulator->peekAtDirty(&dirty);
340
341    if (!mLayer) {
342        Caches::getInstance().dumpMemoryUsage();
343        if (info.errorHandler) {
344            std::ostringstream err;
345            err << "Unable to create layer for " << getName();
346            const int maxTextureSize = Caches::getInstance().maxTextureSize;
347            if (getWidth() > maxTextureSize || getHeight() > maxTextureSize) {
348                err << ", size " << getWidth() << "x" << getHeight()
349                        << " exceeds max size " << maxTextureSize;
350            } else {
351                err << ", see logcat for more info";
352            }
353            info.errorHandler->onError(err.str());
354        }
355        return;
356    }
357
358    if (transformUpdateNeeded && mLayer) {
359        // update the transform in window of the layer to reset its origin wrt light source position
360        Matrix4 windowTransform;
361        info.damageAccumulator->computeCurrentTransform(&windowTransform);
362        mLayer->setWindowTransform(windowTransform);
363    }
364
365#if HWUI_NEW_OPS
366    info.layerUpdateQueue->enqueueLayerWithDamage(this, dirty);
367#else
368    if (dirty.intersect(0, 0, getWidth(), getHeight())) {
369        dirty.roundOut(&dirty);
370        mLayer->updateDeferred(this, dirty.fLeft, dirty.fTop, dirty.fRight, dirty.fBottom);
371    }
372    // This is not inside the above if because we may have called
373    // updateDeferred on a previous prepare pass that didn't have a renderer
374    if (info.renderer && mLayer->deferredUpdateScheduled) {
375        info.renderer->pushLayerUpdate(mLayer);
376    }
377#endif
378
379    // There might be prefetched layers that need to be accounted for.
380    // That might be us, so tell CanvasContext that this layer is in the
381    // tree and should not be destroyed.
382    info.canvasContext.markLayerInUse(this);
383}
384
385/**
386 * Traverse down the the draw tree to prepare for a frame.
387 *
388 * MODE_FULL = UI Thread-driven (thus properties must be synced), otherwise RT driven
389 *
390 * While traversing down the tree, functorsNeedLayer flag is set to true if anything that uses the
391 * stencil buffer may be needed. Views that use a functor to draw will be forced onto a layer.
392 */
393void RenderNode::prepareTreeImpl(TreeInfo& info, bool functorsNeedLayer) {
394    info.damageAccumulator->pushTransform(this);
395
396    if (info.mode == TreeInfo::MODE_FULL) {
397        pushStagingPropertiesChanges(info);
398    }
399    uint32_t animatorDirtyMask = 0;
400    if (CC_LIKELY(info.runAnimations)) {
401        animatorDirtyMask = mAnimatorManager.animate(info);
402    }
403
404    bool willHaveFunctor = false;
405    if (info.mode == TreeInfo::MODE_FULL && mStagingDisplayList) {
406        willHaveFunctor = !mStagingDisplayList->getFunctors().empty();
407    } else if (mDisplayList) {
408        willHaveFunctor = !mDisplayList->getFunctors().empty();
409    }
410    bool childFunctorsNeedLayer = mProperties.prepareForFunctorPresence(
411            willHaveFunctor, functorsNeedLayer);
412
413    if (CC_UNLIKELY(mPositionListener.get())) {
414        mPositionListener->onPositionUpdated(*this, info);
415    }
416
417    prepareLayer(info, animatorDirtyMask);
418    if (info.mode == TreeInfo::MODE_FULL) {
419        pushStagingDisplayListChanges(info);
420    }
421    prepareSubTree(info, childFunctorsNeedLayer, mDisplayList);
422    pushLayerUpdate(info);
423
424    info.damageAccumulator->popTransform();
425}
426
427void RenderNode::syncProperties() {
428    mProperties = mStagingProperties;
429}
430
431void RenderNode::pushStagingPropertiesChanges(TreeInfo& info) {
432    // Push the animators first so that setupStartValueIfNecessary() is called
433    // before properties() is trampled by stagingProperties(), as they are
434    // required by some animators.
435    if (CC_LIKELY(info.runAnimations)) {
436        mAnimatorManager.pushStaging();
437    }
438    if (mDirtyPropertyFields) {
439        mDirtyPropertyFields = 0;
440        damageSelf(info);
441        info.damageAccumulator->popTransform();
442        syncProperties();
443#if !HWUI_NEW_OPS
444        applyLayerPropertiesToLayer(info);
445#endif
446        // We could try to be clever and only re-damage if the matrix changed.
447        // However, we don't need to worry about that. The cost of over-damaging
448        // here is only going to be a single additional map rect of this node
449        // plus a rect join(). The parent's transform (and up) will only be
450        // performed once.
451        info.damageAccumulator->pushTransform(this);
452        damageSelf(info);
453    }
454}
455
456#if !HWUI_NEW_OPS
457void RenderNode::applyLayerPropertiesToLayer(TreeInfo& info) {
458    if (CC_LIKELY(!mLayer)) return;
459
460    const LayerProperties& props = properties().layerProperties();
461    mLayer->setAlpha(props.alpha(), props.xferMode());
462    mLayer->setColorFilter(props.colorFilter());
463    mLayer->setBlend(props.needsBlending());
464}
465#endif
466
467void RenderNode::syncDisplayList(TreeInfo* info) {
468    // Make sure we inc first so that we don't fluctuate between 0 and 1,
469    // which would thrash the layer cache
470    if (mStagingDisplayList) {
471        for (auto&& child : mStagingDisplayList->getChildren()) {
472            child->renderNode->incParentRefCount();
473        }
474    }
475    deleteDisplayList(info ? info->observer : nullptr, info);
476    mDisplayList = mStagingDisplayList;
477    mStagingDisplayList = nullptr;
478    if (mDisplayList) {
479        for (auto& iter : mDisplayList->getFunctors()) {
480            (*iter.functor)(DrawGlInfo::kModeSync, nullptr);
481        }
482        for (size_t i = 0; i < mDisplayList->getPushStagingFunctors().size(); i++) {
483            (*mDisplayList->getPushStagingFunctors()[i])();
484        }
485    }
486}
487
488void RenderNode::pushStagingDisplayListChanges(TreeInfo& info) {
489    if (mNeedsDisplayListSync) {
490        mNeedsDisplayListSync = false;
491        // Damage with the old display list first then the new one to catch any
492        // changes in isRenderable or, in the future, bounds
493        damageSelf(info);
494        syncDisplayList(&info);
495        damageSelf(info);
496    }
497}
498
499void RenderNode::deleteDisplayList(TreeObserver* observer, TreeInfo* info) {
500    if (mDisplayList) {
501        for (auto&& child : mDisplayList->getChildren()) {
502            child->renderNode->decParentRefCount(observer, info);
503        }
504    }
505    delete mDisplayList;
506    mDisplayList = nullptr;
507}
508
509void RenderNode::prepareSubTree(TreeInfo& info, bool functorsNeedLayer, DisplayList* subtree) {
510    if (subtree) {
511        TextureCache& cache = Caches::getInstance().textureCache;
512        info.out.hasFunctors |= subtree->getFunctors().size();
513        for (auto&& bitmapResource : subtree->getBitmapResources()) {
514            void* ownerToken = &info.canvasContext;
515            info.prepareTextures = cache.prefetchAndMarkInUse(ownerToken, bitmapResource);
516        }
517        for (auto&& op : subtree->getChildren()) {
518            RenderNode* childNode = op->renderNode;
519#if HWUI_NEW_OPS
520            info.damageAccumulator->pushTransform(&op->localMatrix);
521            bool childFunctorsNeedLayer = functorsNeedLayer; // TODO! || op->mRecordedWithPotentialStencilClip;
522#else
523            info.damageAccumulator->pushTransform(&op->localMatrix);
524            bool childFunctorsNeedLayer = functorsNeedLayer
525                    // Recorded with non-rect clip, or canvas-rotated by parent
526                    || op->mRecordedWithPotentialStencilClip;
527#endif
528            childNode->prepareTreeImpl(info, childFunctorsNeedLayer);
529            info.damageAccumulator->popTransform();
530        }
531    }
532}
533
534void RenderNode::destroyHardwareResources(TreeObserver* observer, TreeInfo* info) {
535    if (mLayer) {
536        destroyLayer(mLayer);
537        mLayer = nullptr;
538    }
539    if (mDisplayList) {
540        for (auto&& child : mDisplayList->getChildren()) {
541            child->renderNode->destroyHardwareResources(observer, info);
542        }
543        if (mNeedsDisplayListSync) {
544            // Next prepare tree we are going to push a new display list, so we can
545            // drop our current one now
546            deleteDisplayList(observer, info);
547        }
548    }
549}
550
551void RenderNode::decParentRefCount(TreeObserver* observer, TreeInfo* info) {
552    LOG_ALWAYS_FATAL_IF(!mParentCount, "already 0!");
553    mParentCount--;
554    if (!mParentCount) {
555        if (observer) {
556            observer->onMaybeRemovedFromTree(this);
557        }
558        if (CC_UNLIKELY(mPositionListener.get())) {
559            mPositionListener->onPositionLost(*this, info);
560        }
561        // If a child of ours is being attached to our parent then this will incorrectly
562        // destroy its hardware resources. However, this situation is highly unlikely
563        // and the failure is "just" that the layer is re-created, so this should
564        // be safe enough
565        destroyHardwareResources(observer, info);
566    }
567}
568
569/*
570 * For property operations, we pass a savecount of 0, since the operations aren't part of the
571 * displaylist, and thus don't have to compensate for the record-time/playback-time discrepancy in
572 * base saveCount (i.e., how RestoreToCount uses saveCount + properties().getCount())
573 */
574#define PROPERTY_SAVECOUNT 0
575
576template <class T>
577void RenderNode::setViewProperties(OpenGLRenderer& renderer, T& handler) {
578#if DEBUG_DISPLAY_LIST
579    properties().debugOutputProperties(handler.level() + 1);
580#endif
581    if (properties().getLeft() != 0 || properties().getTop() != 0) {
582        renderer.translate(properties().getLeft(), properties().getTop());
583    }
584    if (properties().getStaticMatrix()) {
585        renderer.concatMatrix(*properties().getStaticMatrix());
586    } else if (properties().getAnimationMatrix()) {
587        renderer.concatMatrix(*properties().getAnimationMatrix());
588    }
589    if (properties().hasTransformMatrix()) {
590        if (properties().isTransformTranslateOnly()) {
591            renderer.translate(properties().getTranslationX(), properties().getTranslationY());
592        } else {
593            renderer.concatMatrix(*properties().getTransformMatrix());
594        }
595    }
596    const bool isLayer = properties().effectiveLayerType() != LayerType::None;
597    int clipFlags = properties().getClippingFlags();
598    if (properties().getAlpha() < 1) {
599        if (isLayer) {
600            clipFlags &= ~CLIP_TO_BOUNDS; // bounds clipping done by layer
601        }
602        if (CC_LIKELY(isLayer || !properties().getHasOverlappingRendering())) {
603            // simply scale rendering content's alpha
604            renderer.scaleAlpha(properties().getAlpha());
605        } else {
606            // savelayer needed to create an offscreen buffer
607            Rect layerBounds(0, 0, getWidth(), getHeight());
608            if (clipFlags) {
609                properties().getClippingRectForFlags(clipFlags, &layerBounds);
610                clipFlags = 0; // all clipping done by savelayer
611            }
612            SaveLayerOp* op = new (handler.allocator()) SaveLayerOp(
613                    layerBounds.left, layerBounds.top,
614                    layerBounds.right, layerBounds.bottom,
615                    (int) (properties().getAlpha() * 255),
616                    SaveFlags::HasAlphaLayer | SaveFlags::ClipToLayer);
617            handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds());
618        }
619
620        if (CC_UNLIKELY(ATRACE_ENABLED() && properties().promotedToLayer())) {
621            // pretend alpha always causes savelayer to warn about
622            // performance problem affecting old versions
623            ATRACE_FORMAT("%s alpha caused saveLayer %dx%d", getName(),
624                    static_cast<int>(getWidth()),
625                    static_cast<int>(getHeight()));
626        }
627    }
628    if (clipFlags) {
629        Rect clipRect;
630        properties().getClippingRectForFlags(clipFlags, &clipRect);
631        ClipRectOp* op = new (handler.allocator()) ClipRectOp(
632                clipRect.left, clipRect.top, clipRect.right, clipRect.bottom,
633                SkRegion::kIntersect_Op);
634        handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds());
635    }
636
637    // TODO: support nesting round rect clips
638    if (mProperties.getRevealClip().willClip()) {
639        Rect bounds;
640        mProperties.getRevealClip().getBounds(&bounds);
641        renderer.setClippingRoundRect(handler.allocator(), bounds, mProperties.getRevealClip().getRadius());
642    } else if (mProperties.getOutline().willClip()) {
643        renderer.setClippingOutline(handler.allocator(), &(mProperties.getOutline()));
644    }
645}
646
647/**
648 * Apply property-based transformations to input matrix
649 *
650 * If true3dTransform is set to true, the transform applied to the input matrix will use true 4x4
651 * matrix computation instead of the Skia 3x3 matrix + camera hackery.
652 */
653void RenderNode::applyViewPropertyTransforms(mat4& matrix, bool true3dTransform) const {
654    if (properties().getLeft() != 0 || properties().getTop() != 0) {
655        matrix.translate(properties().getLeft(), properties().getTop());
656    }
657    if (properties().getStaticMatrix()) {
658        mat4 stat(*properties().getStaticMatrix());
659        matrix.multiply(stat);
660    } else if (properties().getAnimationMatrix()) {
661        mat4 anim(*properties().getAnimationMatrix());
662        matrix.multiply(anim);
663    }
664
665    bool applyTranslationZ = true3dTransform && !MathUtils::isZero(properties().getZ());
666    if (properties().hasTransformMatrix() || applyTranslationZ) {
667        if (properties().isTransformTranslateOnly()) {
668            matrix.translate(properties().getTranslationX(), properties().getTranslationY(),
669                    true3dTransform ? properties().getZ() : 0.0f);
670        } else {
671            if (!true3dTransform) {
672                matrix.multiply(*properties().getTransformMatrix());
673            } else {
674                mat4 true3dMat;
675                true3dMat.loadTranslate(
676                        properties().getPivotX() + properties().getTranslationX(),
677                        properties().getPivotY() + properties().getTranslationY(),
678                        properties().getZ());
679                true3dMat.rotate(properties().getRotationX(), 1, 0, 0);
680                true3dMat.rotate(properties().getRotationY(), 0, 1, 0);
681                true3dMat.rotate(properties().getRotation(), 0, 0, 1);
682                true3dMat.scale(properties().getScaleX(), properties().getScaleY(), 1);
683                true3dMat.translate(-properties().getPivotX(), -properties().getPivotY());
684
685                matrix.multiply(true3dMat);
686            }
687        }
688    }
689}
690
691/**
692 * Organizes the DisplayList hierarchy to prepare for background projection reordering.
693 *
694 * This should be called before a call to defer() or drawDisplayList()
695 *
696 * Each DisplayList that serves as a 3d root builds its list of composited children,
697 * which are flagged to not draw in the standard draw loop.
698 */
699void RenderNode::computeOrdering() {
700    ATRACE_CALL();
701    mProjectedNodes.clear();
702
703    // TODO: create temporary DDLOp and call computeOrderingImpl on top DisplayList so that
704    // transform properties are applied correctly to top level children
705    if (mDisplayList == nullptr) return;
706    for (unsigned int i = 0; i < mDisplayList->getChildren().size(); i++) {
707        renderNodeOp_t* childOp = mDisplayList->getChildren()[i];
708        childOp->renderNode->computeOrderingImpl(childOp, &mProjectedNodes, &mat4::identity());
709    }
710}
711
712void RenderNode::computeOrderingImpl(
713        renderNodeOp_t* opState,
714        std::vector<renderNodeOp_t*>* compositedChildrenOfProjectionSurface,
715        const mat4* transformFromProjectionSurface) {
716    mProjectedNodes.clear();
717    if (mDisplayList == nullptr || mDisplayList->isEmpty()) return;
718
719    // TODO: should avoid this calculation in most cases
720    // TODO: just calculate single matrix, down to all leaf composited elements
721    Matrix4 localTransformFromProjectionSurface(*transformFromProjectionSurface);
722    localTransformFromProjectionSurface.multiply(opState->localMatrix);
723
724    if (properties().getProjectBackwards()) {
725        // composited projectee, flag for out of order draw, save matrix, and store in proj surface
726        opState->skipInOrderDraw = true;
727        opState->transformFromCompositingAncestor = localTransformFromProjectionSurface;
728        compositedChildrenOfProjectionSurface->push_back(opState);
729    } else {
730        // standard in order draw
731        opState->skipInOrderDraw = false;
732    }
733
734    if (mDisplayList->getChildren().size() > 0) {
735        const bool isProjectionReceiver = mDisplayList->projectionReceiveIndex >= 0;
736        bool haveAppliedPropertiesToProjection = false;
737        for (unsigned int i = 0; i < mDisplayList->getChildren().size(); i++) {
738            renderNodeOp_t* childOp = mDisplayList->getChildren()[i];
739            RenderNode* child = childOp->renderNode;
740
741            std::vector<renderNodeOp_t*>* projectionChildren = nullptr;
742            const mat4* projectionTransform = nullptr;
743            if (isProjectionReceiver && !child->properties().getProjectBackwards()) {
744                // if receiving projections, collect projecting descendant
745
746                // Note that if a direct descendant is projecting backwards, we pass its
747                // grandparent projection collection, since it shouldn't project onto its
748                // parent, where it will already be drawing.
749                projectionChildren = &mProjectedNodes;
750                projectionTransform = &mat4::identity();
751            } else {
752                if (!haveAppliedPropertiesToProjection) {
753                    applyViewPropertyTransforms(localTransformFromProjectionSurface);
754                    haveAppliedPropertiesToProjection = true;
755                }
756                projectionChildren = compositedChildrenOfProjectionSurface;
757                projectionTransform = &localTransformFromProjectionSurface;
758            }
759            child->computeOrderingImpl(childOp, projectionChildren, projectionTransform);
760        }
761    }
762}
763
764class DeferOperationHandler {
765public:
766    DeferOperationHandler(DeferStateStruct& deferStruct, int level)
767        : mDeferStruct(deferStruct), mLevel(level) {}
768    inline void operator()(DisplayListOp* operation, int saveCount, bool clipToBounds) {
769        operation->defer(mDeferStruct, saveCount, mLevel, clipToBounds);
770    }
771    inline LinearAllocator& allocator() { return *(mDeferStruct.mAllocator); }
772    inline void startMark(const char* name) {} // do nothing
773    inline void endMark() {}
774    inline int level() { return mLevel; }
775    inline int replayFlags() { return mDeferStruct.mReplayFlags; }
776    inline SkPath* allocPathForFrame() { return mDeferStruct.allocPathForFrame(); }
777
778private:
779    DeferStateStruct& mDeferStruct;
780    const int mLevel;
781};
782
783void RenderNode::defer(DeferStateStruct& deferStruct, const int level) {
784    DeferOperationHandler handler(deferStruct, level);
785    issueOperations<DeferOperationHandler>(deferStruct.mRenderer, handler);
786}
787
788class ReplayOperationHandler {
789public:
790    ReplayOperationHandler(ReplayStateStruct& replayStruct, int level)
791        : mReplayStruct(replayStruct), mLevel(level) {}
792    inline void operator()(DisplayListOp* operation, int saveCount, bool clipToBounds) {
793#if DEBUG_DISPLAY_LIST_OPS_AS_EVENTS
794        mReplayStruct.mRenderer.eventMark(operation->name());
795#endif
796        operation->replay(mReplayStruct, saveCount, mLevel, clipToBounds);
797    }
798    inline LinearAllocator& allocator() { return *(mReplayStruct.mAllocator); }
799    inline void startMark(const char* name) {
800        mReplayStruct.mRenderer.startMark(name);
801    }
802    inline void endMark() {
803        mReplayStruct.mRenderer.endMark();
804    }
805    inline int level() { return mLevel; }
806    inline int replayFlags() { return mReplayStruct.mReplayFlags; }
807    inline SkPath* allocPathForFrame() { return mReplayStruct.allocPathForFrame(); }
808
809private:
810    ReplayStateStruct& mReplayStruct;
811    const int mLevel;
812};
813
814void RenderNode::replay(ReplayStateStruct& replayStruct, const int level) {
815    ReplayOperationHandler handler(replayStruct, level);
816    issueOperations<ReplayOperationHandler>(replayStruct.mRenderer, handler);
817}
818
819void RenderNode::buildZSortedChildList(const DisplayList::Chunk& chunk,
820        std::vector<ZDrawRenderNodeOpPair>& zTranslatedNodes) {
821#if !HWUI_NEW_OPS
822    if (chunk.beginChildIndex == chunk.endChildIndex) return;
823
824    for (unsigned int i = chunk.beginChildIndex; i < chunk.endChildIndex; i++) {
825        DrawRenderNodeOp* childOp = mDisplayList->getChildren()[i];
826        RenderNode* child = childOp->renderNode;
827        float childZ = child->properties().getZ();
828
829        if (!MathUtils::isZero(childZ) && chunk.reorderChildren) {
830            zTranslatedNodes.push_back(ZDrawRenderNodeOpPair(childZ, childOp));
831            childOp->skipInOrderDraw = true;
832        } else if (!child->properties().getProjectBackwards()) {
833            // regular, in order drawing DisplayList
834            childOp->skipInOrderDraw = false;
835        }
836    }
837
838    // Z sort any 3d children (stable-ness makes z compare fall back to standard drawing order)
839    std::stable_sort(zTranslatedNodes.begin(), zTranslatedNodes.end());
840#endif
841}
842
843template <class T>
844void RenderNode::issueDrawShadowOperation(const Matrix4& transformFromParent, T& handler) {
845    if (properties().getAlpha() <= 0.0f
846            || properties().getOutline().getAlpha() <= 0.0f
847            || !properties().getOutline().getPath()
848            || properties().getScaleX() == 0
849            || properties().getScaleY() == 0) {
850        // no shadow to draw
851        return;
852    }
853
854    mat4 shadowMatrixXY(transformFromParent);
855    applyViewPropertyTransforms(shadowMatrixXY);
856
857    // Z matrix needs actual 3d transformation, so mapped z values will be correct
858    mat4 shadowMatrixZ(transformFromParent);
859    applyViewPropertyTransforms(shadowMatrixZ, true);
860
861    const SkPath* casterOutlinePath = properties().getOutline().getPath();
862    const SkPath* revealClipPath = properties().getRevealClip().getPath();
863    if (revealClipPath && revealClipPath->isEmpty()) return;
864
865    float casterAlpha = properties().getAlpha() * properties().getOutline().getAlpha();
866
867
868    // holds temporary SkPath to store the result of intersections
869    SkPath* frameAllocatedPath = nullptr;
870    const SkPath* outlinePath = casterOutlinePath;
871
872    // intersect the outline with the reveal clip, if present
873    if (revealClipPath) {
874        frameAllocatedPath = handler.allocPathForFrame();
875
876        Op(*outlinePath, *revealClipPath, kIntersect_SkPathOp, frameAllocatedPath);
877        outlinePath = frameAllocatedPath;
878    }
879
880    // intersect the outline with the clipBounds, if present
881    if (properties().getClippingFlags() & CLIP_TO_CLIP_BOUNDS) {
882        if (!frameAllocatedPath) {
883            frameAllocatedPath = handler.allocPathForFrame();
884        }
885
886        Rect clipBounds;
887        properties().getClippingRectForFlags(CLIP_TO_CLIP_BOUNDS, &clipBounds);
888        SkPath clipBoundsPath;
889        clipBoundsPath.addRect(clipBounds.left, clipBounds.top,
890                clipBounds.right, clipBounds.bottom);
891
892        Op(*outlinePath, clipBoundsPath, kIntersect_SkPathOp, frameAllocatedPath);
893        outlinePath = frameAllocatedPath;
894    }
895
896    DisplayListOp* shadowOp  = new (handler.allocator()) DrawShadowOp(
897            shadowMatrixXY, shadowMatrixZ, casterAlpha, outlinePath);
898    handler(shadowOp, PROPERTY_SAVECOUNT, properties().getClipToBounds());
899}
900
901#define SHADOW_DELTA 0.1f
902
903template <class T>
904void RenderNode::issueOperationsOf3dChildren(ChildrenSelectMode mode,
905        const Matrix4& initialTransform, const std::vector<ZDrawRenderNodeOpPair>& zTranslatedNodes,
906        OpenGLRenderer& renderer, T& handler) {
907    const int size = zTranslatedNodes.size();
908    if (size == 0
909            || (mode == ChildrenSelectMode::NegativeZChildren && zTranslatedNodes[0].key > 0.0f)
910            || (mode == ChildrenSelectMode::PositiveZChildren && zTranslatedNodes[size - 1].key < 0.0f)) {
911        // no 3d children to draw
912        return;
913    }
914
915    // Apply the base transform of the parent of the 3d children. This isolates
916    // 3d children of the current chunk from transformations made in previous chunks.
917    int rootRestoreTo = renderer.save(SaveFlags::Matrix);
918    renderer.setGlobalMatrix(initialTransform);
919
920    /**
921     * Draw shadows and (potential) casters mostly in order, but allow the shadows of casters
922     * with very similar Z heights to draw together.
923     *
924     * This way, if Views A & B have the same Z height and are both casting shadows, the shadows are
925     * underneath both, and neither's shadow is drawn on top of the other.
926     */
927    const size_t nonNegativeIndex = findNonNegativeIndex(zTranslatedNodes);
928    size_t drawIndex, shadowIndex, endIndex;
929    if (mode == ChildrenSelectMode::NegativeZChildren) {
930        drawIndex = 0;
931        endIndex = nonNegativeIndex;
932        shadowIndex = endIndex; // draw no shadows
933    } else {
934        drawIndex = nonNegativeIndex;
935        endIndex = size;
936        shadowIndex = drawIndex; // potentially draw shadow for each pos Z child
937    }
938
939    DISPLAY_LIST_LOGD("%*s%d %s 3d children:", (handler.level() + 1) * 2, "",
940            endIndex - drawIndex, mode == kNegativeZChildren ? "negative" : "positive");
941
942    float lastCasterZ = 0.0f;
943    while (shadowIndex < endIndex || drawIndex < endIndex) {
944        if (shadowIndex < endIndex) {
945            DrawRenderNodeOp* casterOp = zTranslatedNodes[shadowIndex].value;
946            RenderNode* caster = casterOp->renderNode;
947            const float casterZ = zTranslatedNodes[shadowIndex].key;
948            // attempt to render the shadow if the caster about to be drawn is its caster,
949            // OR if its caster's Z value is similar to the previous potential caster
950            if (shadowIndex == drawIndex || casterZ - lastCasterZ < SHADOW_DELTA) {
951                caster->issueDrawShadowOperation(casterOp->localMatrix, handler);
952
953                lastCasterZ = casterZ; // must do this even if current caster not casting a shadow
954                shadowIndex++;
955                continue;
956            }
957        }
958
959        // only the actual child DL draw needs to be in save/restore,
960        // since it modifies the renderer's matrix
961        int restoreTo = renderer.save(SaveFlags::Matrix);
962
963        DrawRenderNodeOp* childOp = zTranslatedNodes[drawIndex].value;
964
965        renderer.concatMatrix(childOp->localMatrix);
966        childOp->skipInOrderDraw = false; // this is horrible, I'm so sorry everyone
967        handler(childOp, renderer.getSaveCount() - 1, properties().getClipToBounds());
968        childOp->skipInOrderDraw = true;
969
970        renderer.restoreToCount(restoreTo);
971        drawIndex++;
972    }
973    renderer.restoreToCount(rootRestoreTo);
974}
975
976template <class T>
977void RenderNode::issueOperationsOfProjectedChildren(OpenGLRenderer& renderer, T& handler) {
978    DISPLAY_LIST_LOGD("%*s%d projected children:", (handler.level() + 1) * 2, "", mProjectedNodes.size());
979    const SkPath* projectionReceiverOutline = properties().getOutline().getPath();
980    int restoreTo = renderer.getSaveCount();
981
982    LinearAllocator& alloc = handler.allocator();
983    handler(new (alloc) SaveOp(SaveFlags::MatrixClip),
984            PROPERTY_SAVECOUNT, properties().getClipToBounds());
985
986    // Transform renderer to match background we're projecting onto
987    // (by offsetting canvas by translationX/Y of background rendernode, since only those are set)
988    const DisplayListOp* op =
989#if HWUI_NEW_OPS
990            nullptr;
991    LOG_ALWAYS_FATAL("unsupported");
992#else
993            (mDisplayList->getOps()[mDisplayList->projectionReceiveIndex]);
994#endif
995    const DrawRenderNodeOp* backgroundOp = reinterpret_cast<const DrawRenderNodeOp*>(op);
996    const RenderProperties& backgroundProps = backgroundOp->renderNode->properties();
997    renderer.translate(backgroundProps.getTranslationX(), backgroundProps.getTranslationY());
998
999    // If the projection receiver has an outline, we mask projected content to it
1000    // (which we know, apriori, are all tessellated paths)
1001    renderer.setProjectionPathMask(alloc, projectionReceiverOutline);
1002
1003    // draw projected nodes
1004    for (size_t i = 0; i < mProjectedNodes.size(); i++) {
1005        renderNodeOp_t* childOp = mProjectedNodes[i];
1006
1007        // matrix save, concat, and restore can be done safely without allocating operations
1008        int restoreTo = renderer.save(SaveFlags::Matrix);
1009        renderer.concatMatrix(childOp->transformFromCompositingAncestor);
1010        childOp->skipInOrderDraw = false; // this is horrible, I'm so sorry everyone
1011        handler(childOp, renderer.getSaveCount() - 1, properties().getClipToBounds());
1012        childOp->skipInOrderDraw = true;
1013        renderer.restoreToCount(restoreTo);
1014    }
1015
1016    handler(new (alloc) RestoreToCountOp(restoreTo),
1017            PROPERTY_SAVECOUNT, properties().getClipToBounds());
1018}
1019
1020/**
1021 * This function serves both defer and replay modes, and will organize the displayList's component
1022 * operations for a single frame:
1023 *
1024 * Every 'simple' state operation that affects just the matrix and alpha (or other factors of
1025 * DeferredDisplayState) may be issued directly to the renderer, but complex operations (with custom
1026 * defer logic) and operations in displayListOps are issued through the 'handler' which handles the
1027 * defer vs replay logic, per operation
1028 */
1029template <class T>
1030void RenderNode::issueOperations(OpenGLRenderer& renderer, T& handler) {
1031    if (mDisplayList->isEmpty()) {
1032        DISPLAY_LIST_LOGD("%*sEmpty display list (%p, %s)", handler.level() * 2, "",
1033                this, getName());
1034        return;
1035    }
1036
1037#if HWUI_NEW_OPS
1038    const bool drawLayer = false;
1039#else
1040    const bool drawLayer = (mLayer && (&renderer != mLayer->renderer.get()));
1041#endif
1042    // If we are updating the contents of mLayer, we don't want to apply any of
1043    // the RenderNode's properties to this issueOperations pass. Those will all
1044    // be applied when the layer is drawn, aka when this is true.
1045    const bool useViewProperties = (!mLayer || drawLayer);
1046    if (useViewProperties) {
1047        const Outline& outline = properties().getOutline();
1048        if (properties().getAlpha() <= 0
1049                || (outline.getShouldClip() && outline.isEmpty())
1050                || properties().getScaleX() == 0
1051                || properties().getScaleY() == 0) {
1052            DISPLAY_LIST_LOGD("%*sRejected display list (%p, %s)", handler.level() * 2, "",
1053                    this, getName());
1054            return;
1055        }
1056    }
1057
1058    handler.startMark(getName());
1059
1060#if DEBUG_DISPLAY_LIST
1061    const Rect& clipRect = renderer.getLocalClipBounds();
1062    DISPLAY_LIST_LOGD("%*sStart display list (%p, %s), localClipBounds: %.0f, %.0f, %.0f, %.0f",
1063            handler.level() * 2, "", this, getName(),
1064            clipRect.left, clipRect.top, clipRect.right, clipRect.bottom);
1065#endif
1066
1067    LinearAllocator& alloc = handler.allocator();
1068    int restoreTo = renderer.getSaveCount();
1069    handler(new (alloc) SaveOp(SaveFlags::MatrixClip),
1070            PROPERTY_SAVECOUNT, properties().getClipToBounds());
1071
1072    DISPLAY_LIST_LOGD("%*sSave %d %d", (handler.level() + 1) * 2, "",
1073            SaveFlags::MatrixClip, restoreTo);
1074
1075    if (useViewProperties) {
1076        setViewProperties<T>(renderer, handler);
1077    }
1078
1079#if HWUI_NEW_OPS
1080    LOG_ALWAYS_FATAL("legacy op traversal not supported");
1081#else
1082    bool quickRejected = properties().getClipToBounds()
1083            && renderer.quickRejectConservative(0, 0, properties().getWidth(), properties().getHeight());
1084    if (!quickRejected) {
1085        Matrix4 initialTransform(*(renderer.currentTransform()));
1086        renderer.setBaseTransform(initialTransform);
1087
1088        if (drawLayer) {
1089            handler(new (alloc) DrawLayerOp(mLayer),
1090                    renderer.getSaveCount() - 1, properties().getClipToBounds());
1091        } else {
1092            const int saveCountOffset = renderer.getSaveCount() - 1;
1093            const int projectionReceiveIndex = mDisplayList->projectionReceiveIndex;
1094            for (size_t chunkIndex = 0; chunkIndex < mDisplayList->getChunks().size(); chunkIndex++) {
1095                const DisplayList::Chunk& chunk = mDisplayList->getChunks()[chunkIndex];
1096
1097                std::vector<ZDrawRenderNodeOpPair> zTranslatedNodes;
1098                buildZSortedChildList(chunk, zTranslatedNodes);
1099
1100                issueOperationsOf3dChildren(ChildrenSelectMode::NegativeZChildren,
1101                        initialTransform, zTranslatedNodes, renderer, handler);
1102
1103                for (size_t opIndex = chunk.beginOpIndex; opIndex < chunk.endOpIndex; opIndex++) {
1104                    DisplayListOp *op = mDisplayList->getOps()[opIndex];
1105#if DEBUG_DISPLAY_LIST
1106                    op->output(handler.level() + 1);
1107#endif
1108                    handler(op, saveCountOffset, properties().getClipToBounds());
1109
1110                    if (CC_UNLIKELY(!mProjectedNodes.empty() && projectionReceiveIndex >= 0 &&
1111                        opIndex == static_cast<size_t>(projectionReceiveIndex))) {
1112                        issueOperationsOfProjectedChildren(renderer, handler);
1113                    }
1114                }
1115
1116                issueOperationsOf3dChildren(ChildrenSelectMode::PositiveZChildren,
1117                        initialTransform, zTranslatedNodes, renderer, handler);
1118            }
1119        }
1120    }
1121#endif
1122
1123    DISPLAY_LIST_LOGD("%*sRestoreToCount %d", (handler.level() + 1) * 2, "", restoreTo);
1124    handler(new (alloc) RestoreToCountOp(restoreTo),
1125            PROPERTY_SAVECOUNT, properties().getClipToBounds());
1126
1127    DISPLAY_LIST_LOGD("%*sDone (%p, %s)", handler.level() * 2, "", this, getName());
1128    handler.endMark();
1129}
1130
1131} /* namespace uirenderer */
1132} /* namespace android */
1133