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