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