DeferredDisplayList.cpp revision d41c4d8c732095ae99c955b6b82f7306633004b1
1/*
2 * Copyright (C) 2013 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 LOG_TAG "OpenGLRenderer"
18#define ATRACE_TAG ATRACE_TAG_VIEW
19
20#include <SkCanvas.h>
21
22#include <utils/Trace.h>
23#include <ui/Rect.h>
24#include <ui/Region.h>
25
26#include "Caches.h"
27#include "Debug.h"
28#include "DeferredDisplayList.h"
29#include "DisplayListOp.h"
30#include "OpenGLRenderer.h"
31#include "utils/MathUtils.h"
32
33#if DEBUG_DEFER
34    #define DEFER_LOGD(...) ALOGD(__VA_ARGS__)
35#else
36    #define DEFER_LOGD(...)
37#endif
38
39namespace android {
40namespace uirenderer {
41
42// Depth of the save stack at the beginning of batch playback at flush time
43#define FLUSH_SAVE_STACK_DEPTH 2
44
45#define DEBUG_COLOR_BARRIER          0x1f000000
46#define DEBUG_COLOR_MERGEDBATCH      0x5f7f7fff
47#define DEBUG_COLOR_MERGEDBATCH_SOLO 0x5f7fff7f
48
49/////////////////////////////////////////////////////////////////////////////////
50// Operation Batches
51/////////////////////////////////////////////////////////////////////////////////
52
53class Batch {
54public:
55    virtual void replay(OpenGLRenderer& renderer, Rect& dirty, int index) = 0;
56    virtual ~Batch() {}
57    virtual bool purelyDrawBatch() { return false; }
58    virtual bool coversBounds(const Rect& bounds) { return false; }
59};
60
61class DrawBatch : public Batch {
62public:
63    DrawBatch(const DeferInfo& deferInfo) : mAllOpsOpaque(true),
64            mBatchId(deferInfo.batchId), mMergeId(deferInfo.mergeId) {
65        mOps.clear();
66    }
67
68    virtual ~DrawBatch() { mOps.clear(); }
69
70    virtual void add(DrawOp* op, const DeferredDisplayState* state, bool opaqueOverBounds) {
71        // NOTE: ignore empty bounds special case, since we don't merge across those ops
72        mBounds.unionWith(state->mBounds);
73        mAllOpsOpaque &= opaqueOverBounds;
74        mOps.add(OpStatePair(op, state));
75    }
76
77    bool intersects(const Rect& rect) {
78        if (!rect.intersects(mBounds)) return false;
79
80        for (unsigned int i = 0; i < mOps.size(); i++) {
81            if (rect.intersects(mOps[i].state->mBounds)) {
82#if DEBUG_DEFER
83                DEFER_LOGD("op intersects with op %p with bounds %f %f %f %f:", mOps[i].op,
84                        mOps[i].state->mBounds.left, mOps[i].state->mBounds.top,
85                        mOps[i].state->mBounds.right, mOps[i].state->mBounds.bottom);
86                mOps[i].op->output(2);
87#endif
88                return true;
89            }
90        }
91        return false;
92    }
93
94    virtual void replay(OpenGLRenderer& renderer, Rect& dirty, int index) override {
95        DEFER_LOGD("%d  replaying DrawBatch %p, with %d ops (batch id %x, merge id %p)",
96                index, this, mOps.size(), getBatchId(), getMergeId());
97
98        DisplayListLogBuffer& logBuffer = DisplayListLogBuffer::getInstance();
99        for (unsigned int i = 0; i < mOps.size(); i++) {
100            DrawOp* op = mOps[i].op;
101            const DeferredDisplayState* state = mOps[i].state;
102            renderer.restoreDisplayState(*state);
103
104#if DEBUG_DISPLAY_LIST_OPS_AS_EVENTS
105            renderer.eventMark(op->name());
106#endif
107            logBuffer.writeCommand(0, op->name());
108            op->applyDraw(renderer, dirty);
109
110#if DEBUG_MERGE_BEHAVIOR
111            const Rect& bounds = state->mBounds;
112            int batchColor = 0x1f000000;
113            if (getBatchId() & 0x1) batchColor |= 0x0000ff;
114            if (getBatchId() & 0x2) batchColor |= 0x00ff00;
115            if (getBatchId() & 0x4) batchColor |= 0xff0000;
116            renderer.drawScreenSpaceColorRect(bounds.left, bounds.top, bounds.right, bounds.bottom,
117                    batchColor);
118#endif
119        }
120    }
121
122    virtual bool purelyDrawBatch() override { return true; }
123
124    virtual bool coversBounds(const Rect& bounds) override {
125        if (CC_LIKELY(!mAllOpsOpaque || !mBounds.contains(bounds) || count() == 1)) return false;
126
127        Region uncovered(android::Rect(bounds.left, bounds.top, bounds.right, bounds.bottom));
128        for (unsigned int i = 0; i < mOps.size(); i++) {
129            const Rect &r = mOps[i].state->mBounds;
130            uncovered.subtractSelf(android::Rect(r.left, r.top, r.right, r.bottom));
131        }
132        return uncovered.isEmpty();
133    }
134
135    inline int getBatchId() const { return mBatchId; }
136    inline mergeid_t getMergeId() const { return mMergeId; }
137    inline int count() const { return mOps.size(); }
138
139protected:
140    Vector<OpStatePair> mOps;
141    Rect mBounds; // union of bounds of contained ops
142private:
143    bool mAllOpsOpaque;
144    int mBatchId;
145    mergeid_t mMergeId;
146};
147
148class MergingDrawBatch : public DrawBatch {
149public:
150    MergingDrawBatch(DeferInfo& deferInfo, int width, int height) :
151            DrawBatch(deferInfo), mClipRect(width, height),
152            mClipSideFlags(kClipSide_None) {}
153
154    /*
155     * Helper for determining if a new op can merge with a MergingDrawBatch based on their bounds
156     * and clip side flags. Positive bounds delta means new bounds fit in old.
157     */
158    static inline bool checkSide(const int currentFlags, const int newFlags, const int side,
159            float boundsDelta) {
160        bool currentClipExists = currentFlags & side;
161        bool newClipExists = newFlags & side;
162
163        // if current is clipped, we must be able to fit new bounds in current
164        if (boundsDelta > 0 && currentClipExists) return false;
165
166        // if new is clipped, we must be able to fit current bounds in new
167        if (boundsDelta < 0 && newClipExists) return false;
168
169        return true;
170    }
171
172    /*
173     * Checks if a (mergeable) op can be merged into this batch
174     *
175     * If true, the op's multiDraw must be guaranteed to handle both ops simultaneously, so it is
176     * important to consider all paint attributes used in the draw calls in deciding both a) if an
177     * op tries to merge at all, and b) if the op can merge with another set of ops
178     *
179     * False positives can lead to information from the paints of subsequent merged operations being
180     * dropped, so we make simplifying qualifications on the ops that can merge, per op type.
181     */
182    bool canMergeWith(const DrawOp* op, const DeferredDisplayState* state) {
183        bool isTextBatch = getBatchId() == DeferredDisplayList::kOpBatch_Text ||
184                getBatchId() == DeferredDisplayList::kOpBatch_ColorText;
185
186        // Overlapping other operations is only allowed for text without shadow. For other ops,
187        // multiDraw isn't guaranteed to overdraw correctly
188        if (!isTextBatch || op->hasTextShadow()) {
189            if (intersects(state->mBounds)) return false;
190        }
191        const DeferredDisplayState* lhs = state;
192        const DeferredDisplayState* rhs = mOps[0].state;
193
194        if (!MathUtils::areEqual(lhs->mAlpha, rhs->mAlpha)) return false;
195
196        // Identical round rect clip state means both ops will clip in the same way, or not at all.
197        // As the state objects are const, we can compare their pointers to determine mergeability
198        if (lhs->mRoundRectClipState != rhs->mRoundRectClipState) return false;
199
200        /* Clipping compatibility check
201         *
202         * Exploits the fact that if a op or batch is clipped on a side, its bounds will equal its
203         * clip for that side.
204         */
205        const int currentFlags = mClipSideFlags;
206        const int newFlags = state->mClipSideFlags;
207        if (currentFlags != kClipSide_None || newFlags != kClipSide_None) {
208            const Rect& opBounds = state->mBounds;
209            float boundsDelta = mBounds.left - opBounds.left;
210            if (!checkSide(currentFlags, newFlags, kClipSide_Left, boundsDelta)) return false;
211            boundsDelta = mBounds.top - opBounds.top;
212            if (!checkSide(currentFlags, newFlags, kClipSide_Top, boundsDelta)) return false;
213
214            // right and bottom delta calculation reversed to account for direction
215            boundsDelta = opBounds.right - mBounds.right;
216            if (!checkSide(currentFlags, newFlags, kClipSide_Right, boundsDelta)) return false;
217            boundsDelta = opBounds.bottom - mBounds.bottom;
218            if (!checkSide(currentFlags, newFlags, kClipSide_Bottom, boundsDelta)) return false;
219        }
220
221        // if paints are equal, then modifiers + paint attribs don't need to be compared
222        if (op->mPaint == mOps[0].op->mPaint) return true;
223
224        if (op->getPaintAlpha() != mOps[0].op->getPaintAlpha()) return false;
225
226        if (op->mPaint && mOps[0].op->mPaint &&
227            op->mPaint->getColorFilter() != mOps[0].op->mPaint->getColorFilter()) {
228            return false;
229        }
230
231        if (op->mPaint && mOps[0].op->mPaint &&
232            op->mPaint->getShader() != mOps[0].op->mPaint->getShader()) {
233            return false;
234        }
235
236        return true;
237    }
238
239    virtual void add(DrawOp* op, const DeferredDisplayState* state,
240            bool opaqueOverBounds) override {
241        DrawBatch::add(op, state, opaqueOverBounds);
242
243        const int newClipSideFlags = state->mClipSideFlags;
244        mClipSideFlags |= newClipSideFlags;
245        if (newClipSideFlags & kClipSide_Left) mClipRect.left = state->mClip.left;
246        if (newClipSideFlags & kClipSide_Top) mClipRect.top = state->mClip.top;
247        if (newClipSideFlags & kClipSide_Right) mClipRect.right = state->mClip.right;
248        if (newClipSideFlags & kClipSide_Bottom) mClipRect.bottom = state->mClip.bottom;
249    }
250
251    virtual void replay(OpenGLRenderer& renderer, Rect& dirty, int index) override {
252        DEFER_LOGD("%d  replaying MergingDrawBatch %p, with %d ops,"
253                " clip flags %x (batch id %x, merge id %p)",
254                index, this, mOps.size(), mClipSideFlags, getBatchId(), getMergeId());
255        if (mOps.size() == 1) {
256            DrawBatch::replay(renderer, dirty, -1);
257            return;
258        }
259
260        // clipping in the merged case is done ahead of time since all ops share the clip (if any)
261        renderer.setupMergedMultiDraw(mClipSideFlags ? &mClipRect : nullptr);
262
263        DrawOp* op = mOps[0].op;
264        DisplayListLogBuffer& buffer = DisplayListLogBuffer::getInstance();
265        buffer.writeCommand(0, "multiDraw");
266        buffer.writeCommand(1, op->name());
267
268#if DEBUG_DISPLAY_LIST_OPS_AS_EVENTS
269        renderer.eventMark("multiDraw");
270        renderer.eventMark(op->name());
271#endif
272        op->multiDraw(renderer, dirty, mOps, mBounds);
273
274#if DEBUG_MERGE_BEHAVIOR
275        renderer.drawScreenSpaceColorRect(mBounds.left, mBounds.top, mBounds.right, mBounds.bottom,
276                DEBUG_COLOR_MERGEDBATCH);
277#endif
278    }
279
280private:
281    /*
282     * Contains the effective clip rect shared by all merged ops. Initialized to the layer viewport,
283     * it will shrink if an op must be clipped on a certain side. The clipped sides are reflected in
284     * mClipSideFlags.
285     */
286    Rect mClipRect;
287    int mClipSideFlags;
288};
289
290class StateOpBatch : public Batch {
291public:
292    // creates a single operation batch
293    StateOpBatch(const StateOp* op, const DeferredDisplayState* state) : mOp(op), mState(state) {}
294
295    virtual void replay(OpenGLRenderer& renderer, Rect& dirty, int index) override {
296        DEFER_LOGD("replaying state op batch %p", this);
297        renderer.restoreDisplayState(*mState);
298
299        // use invalid save count because it won't be used at flush time - RestoreToCountOp is the
300        // only one to use it, and we don't use that class at flush time, instead calling
301        // renderer.restoreToCount directly
302        int saveCount = -1;
303        mOp->applyState(renderer, saveCount);
304    }
305
306private:
307    const StateOp* mOp;
308    const DeferredDisplayState* mState;
309};
310
311class RestoreToCountBatch : public Batch {
312public:
313    RestoreToCountBatch(const StateOp* op, const DeferredDisplayState* state, int restoreCount) :
314            mState(state), mRestoreCount(restoreCount) {}
315
316    virtual void replay(OpenGLRenderer& renderer, Rect& dirty, int index) override {
317        DEFER_LOGD("batch %p restoring to count %d", this, mRestoreCount);
318
319        renderer.restoreDisplayState(*mState);
320        renderer.restoreToCount(mRestoreCount);
321    }
322
323private:
324    // we use the state storage for the RestoreToCountOp, but don't replay the op itself
325    const DeferredDisplayState* mState;
326
327    /*
328     * The count used here represents the flush() time saveCount. This is as opposed to the
329     * DisplayList record time, or defer() time values (which are RestoreToCountOp's mCount, and
330     * (saveCount + mCount) respectively). Since the count is different from the original
331     * RestoreToCountOp, we don't store a pointer to the op, as elsewhere.
332     */
333    const int mRestoreCount;
334};
335
336#if DEBUG_MERGE_BEHAVIOR
337class BarrierDebugBatch : public Batch {
338    virtual void replay(OpenGLRenderer& renderer, Rect& dirty, int index) {
339        renderer.drawScreenSpaceColorRect(0, 0, 10000, 10000, DEBUG_COLOR_BARRIER);
340    }
341};
342#endif
343
344/////////////////////////////////////////////////////////////////////////////////
345// DeferredDisplayList
346/////////////////////////////////////////////////////////////////////////////////
347
348void DeferredDisplayList::resetBatchingState() {
349    for (int i = 0; i < kOpBatch_Count; i++) {
350        mBatchLookup[i] = nullptr;
351        mMergingBatches[i].clear();
352    }
353#if DEBUG_MERGE_BEHAVIOR
354    if (mBatches.size() != 0) {
355        mBatches.add(new BarrierDebugBatch());
356    }
357#endif
358    mEarliestBatchIndex = mBatches.size();
359}
360
361void DeferredDisplayList::clear() {
362    resetBatchingState();
363    mComplexClipStackStart = -1;
364
365    for (unsigned int i = 0; i < mBatches.size(); i++) {
366        delete mBatches[i];
367    }
368    mBatches.clear();
369    mSaveStack.clear();
370    mEarliestBatchIndex = 0;
371    mEarliestUnclearedIndex = 0;
372}
373
374/////////////////////////////////////////////////////////////////////////////////
375// Operation adding
376/////////////////////////////////////////////////////////////////////////////////
377
378int DeferredDisplayList::getStateOpDeferFlags() const {
379    // For both clipOp and save(Layer)Op, we don't want to save drawing info, and only want to save
380    // the clip if we aren't recording a complex clip (and can thus trust it to be a rect)
381    return recordingComplexClip() ? 0 : kStateDeferFlag_Clip;
382}
383
384int DeferredDisplayList::getDrawOpDeferFlags() const {
385    return kStateDeferFlag_Draw | getStateOpDeferFlags();
386}
387
388/**
389 * When an clipping operation occurs that could cause a complex clip, record the operation and all
390 * subsequent clipOps, save/restores (if the clip flag is set). During a flush, instead of loading
391 * the clip from deferred state, we play back all of the relevant state operations that generated
392 * the complex clip.
393 *
394 * Note that we don't need to record the associated restore operation, since operations at defer
395 * time record whether they should store the renderer's current clip
396 */
397void DeferredDisplayList::addClip(OpenGLRenderer& renderer, ClipOp* op) {
398    if (recordingComplexClip() || op->canCauseComplexClip() || !renderer.hasRectToRectTransform()) {
399        DEFER_LOGD("%p Received complex clip operation %p", this, op);
400
401        // NOTE: defer clip op before setting mComplexClipStackStart so previous clip is recorded
402        storeStateOpBarrier(renderer, op);
403
404        if (!recordingComplexClip()) {
405            mComplexClipStackStart = renderer.getSaveCount() - 1;
406            DEFER_LOGD("    Starting complex clip region, start is %d", mComplexClipStackStart);
407        }
408    }
409}
410
411/**
412 * For now, we record save layer operations as barriers in the batch list, preventing drawing
413 * operations from reordering around the saveLayer and it's associated restore()
414 *
415 * In the future, we should send saveLayer commands (if they can be played out of order) and their
416 * contained drawing operations to a seperate list of batches, so that they may draw at the
417 * beginning of the frame. This would avoid targetting and removing an FBO in the middle of a frame.
418 *
419 * saveLayer operations should be pulled to the beginning of the frame if the canvas doesn't have a
420 * complex clip, and if the flags (kClip_SaveFlag & kClipToLayer_SaveFlag) are set.
421 */
422void DeferredDisplayList::addSaveLayer(OpenGLRenderer& renderer,
423        SaveLayerOp* op, int newSaveCount) {
424    DEFER_LOGD("%p adding saveLayerOp %p, flags %x, new count %d",
425            this, op, op->getFlags(), newSaveCount);
426
427    storeStateOpBarrier(renderer, op);
428    mSaveStack.push(newSaveCount);
429}
430
431/**
432 * Takes save op and it's return value - the new save count - and stores it into the stream as a
433 * barrier if it's needed to properly modify a complex clip
434 */
435void DeferredDisplayList::addSave(OpenGLRenderer& renderer, SaveOp* op, int newSaveCount) {
436    int saveFlags = op->getFlags();
437    DEFER_LOGD("%p adding saveOp %p, flags %x, new count %d", this, op, saveFlags, newSaveCount);
438
439    if (recordingComplexClip() && (saveFlags & SkCanvas::kClip_SaveFlag)) {
440        // store and replay the save operation, as it may be needed to correctly playback the clip
441        DEFER_LOGD("    adding save barrier with new save count %d", newSaveCount);
442        storeStateOpBarrier(renderer, op);
443        mSaveStack.push(newSaveCount);
444    }
445}
446
447/**
448 * saveLayer() commands must be associated with a restoreToCount batch that will clean up and draw
449 * the layer in the deferred list
450 *
451 * other save() commands which occur as children of a snapshot with complex clip will be deferred,
452 * and must be restored
453 *
454 * Either will act as a barrier to draw operation reordering, as we want to play back layer
455 * save/restore and complex canvas modifications (including save/restore) in order.
456 */
457void DeferredDisplayList::addRestoreToCount(OpenGLRenderer& renderer, StateOp* op,
458        int newSaveCount) {
459    DEFER_LOGD("%p addRestoreToCount %d", this, newSaveCount);
460
461    if (recordingComplexClip() && newSaveCount <= mComplexClipStackStart) {
462        mComplexClipStackStart = -1;
463        resetBatchingState();
464    }
465
466    if (mSaveStack.isEmpty() || newSaveCount > mSaveStack.top()) {
467        return;
468    }
469
470    while (!mSaveStack.isEmpty() && mSaveStack.top() >= newSaveCount) mSaveStack.pop();
471
472    storeRestoreToCountBarrier(renderer, op, mSaveStack.size() + FLUSH_SAVE_STACK_DEPTH);
473}
474
475void DeferredDisplayList::addDrawOp(OpenGLRenderer& renderer, DrawOp* op) {
476    /* 1: op calculates local bounds */
477    DeferredDisplayState* const state = createState();
478    if (op->getLocalBounds(state->mBounds)) {
479        if (state->mBounds.isEmpty()) {
480            // valid empty bounds, don't bother deferring
481            tryRecycleState(state);
482            return;
483        }
484    } else {
485        state->mBounds.setEmpty();
486    }
487
488    /* 2: renderer calculates global bounds + stores state */
489    if (renderer.storeDisplayState(*state, getDrawOpDeferFlags())) {
490        tryRecycleState(state);
491        return; // quick rejected
492    }
493
494    /* 3: ask op for defer info, given renderer state */
495    DeferInfo deferInfo;
496    op->onDefer(renderer, deferInfo, *state);
497
498    // complex clip has a complex set of expectations on the renderer state - for now, avoid taking
499    // the merge path in those cases
500    deferInfo.mergeable &= !recordingComplexClip();
501    deferInfo.opaqueOverBounds &= !recordingComplexClip() && mSaveStack.isEmpty();
502
503    if (CC_LIKELY(mAvoidOverdraw) && mBatches.size() &&
504            state->mClipSideFlags != kClipSide_ConservativeFull &&
505            deferInfo.opaqueOverBounds && state->mBounds.contains(mBounds)) {
506        // avoid overdraw by resetting drawing state + discarding drawing ops
507        discardDrawingBatches(mBatches.size() - 1);
508        resetBatchingState();
509    }
510
511    if (CC_UNLIKELY(renderer.getCaches().drawReorderDisabled)) {
512        // TODO: elegant way to reuse batches?
513        DrawBatch* b = new DrawBatch(deferInfo);
514        b->add(op, state, deferInfo.opaqueOverBounds);
515        mBatches.add(b);
516        return;
517    }
518
519    // find the latest batch of the new op's type, and try to merge the new op into it
520    DrawBatch* targetBatch = nullptr;
521
522    // insertion point of a new batch, will hopefully be immediately after similar batch
523    // (eventually, should be similar shader)
524    int insertBatchIndex = mBatches.size();
525    if (!mBatches.isEmpty()) {
526        if (state->mBounds.isEmpty()) {
527            // don't know the bounds for op, so add to last batch and start from scratch on next op
528            DrawBatch* b = new DrawBatch(deferInfo);
529            b->add(op, state, deferInfo.opaqueOverBounds);
530            mBatches.add(b);
531            resetBatchingState();
532#if DEBUG_DEFER
533            DEFER_LOGD("Warning: Encountered op with empty bounds, resetting batches");
534            op->output(2);
535#endif
536            return;
537        }
538
539        if (deferInfo.mergeable) {
540            // Try to merge with any existing batch with same mergeId.
541            if (mMergingBatches[deferInfo.batchId].get(deferInfo.mergeId, targetBatch)) {
542                if (!((MergingDrawBatch*) targetBatch)->canMergeWith(op, state)) {
543                    targetBatch = nullptr;
544                }
545            }
546        } else {
547            // join with similar, non-merging batch
548            targetBatch = (DrawBatch*)mBatchLookup[deferInfo.batchId];
549        }
550
551        if (targetBatch || deferInfo.mergeable) {
552            // iterate back toward target to see if anything drawn since should overlap the new op
553            // if no target, merging ops still interate to find similar batch to insert after
554            for (int i = mBatches.size() - 1; i >= mEarliestBatchIndex; i--) {
555                DrawBatch* overBatch = (DrawBatch*)mBatches[i];
556
557                if (overBatch == targetBatch) break;
558
559                // TODO: also consider shader shared between batch types
560                if (deferInfo.batchId == overBatch->getBatchId()) {
561                    insertBatchIndex = i + 1;
562                    if (!targetBatch) break; // found insert position, quit
563                }
564
565                if (overBatch->intersects(state->mBounds)) {
566                    // NOTE: it may be possible to optimize for special cases where two operations
567                    // of the same batch/paint could swap order, such as with a non-mergeable
568                    // (clipped) and a mergeable text operation
569                    targetBatch = nullptr;
570#if DEBUG_DEFER
571                    DEFER_LOGD("op couldn't join batch %p, was intersected by batch %d",
572                            targetBatch, i);
573                    op->output(2);
574#endif
575                    break;
576                }
577            }
578        }
579    }
580
581    if (!targetBatch) {
582        if (deferInfo.mergeable) {
583            targetBatch = new MergingDrawBatch(deferInfo,
584                    renderer.getViewportWidth(), renderer.getViewportHeight());
585            mMergingBatches[deferInfo.batchId].put(deferInfo.mergeId, targetBatch);
586        } else {
587            targetBatch = new DrawBatch(deferInfo);
588            mBatchLookup[deferInfo.batchId] = targetBatch;
589        }
590
591        DEFER_LOGD("creating %singBatch %p, bid %x, at %d",
592                deferInfo.mergeable ? "Merg" : "Draw",
593                targetBatch, deferInfo.batchId, insertBatchIndex);
594        mBatches.insertAt(targetBatch, insertBatchIndex);
595    }
596
597    targetBatch->add(op, state, deferInfo.opaqueOverBounds);
598}
599
600void DeferredDisplayList::storeStateOpBarrier(OpenGLRenderer& renderer, StateOp* op) {
601    DEFER_LOGD("%p adding state op barrier at pos %d", this, mBatches.size());
602
603    DeferredDisplayState* state = createState();
604    renderer.storeDisplayState(*state, getStateOpDeferFlags());
605    mBatches.add(new StateOpBatch(op, state));
606    resetBatchingState();
607}
608
609void DeferredDisplayList::storeRestoreToCountBarrier(OpenGLRenderer& renderer, StateOp* op,
610        int newSaveCount) {
611    DEFER_LOGD("%p adding restore to count %d barrier, pos %d",
612            this, newSaveCount, mBatches.size());
613
614    // store displayState for the restore operation, as it may be associated with a saveLayer that
615    // doesn't have kClip_SaveFlag set
616    DeferredDisplayState* state = createState();
617    renderer.storeDisplayState(*state, getStateOpDeferFlags());
618    mBatches.add(new RestoreToCountBatch(op, state, newSaveCount));
619    resetBatchingState();
620}
621
622/////////////////////////////////////////////////////////////////////////////////
623// Replay / flush
624/////////////////////////////////////////////////////////////////////////////////
625
626static void replayBatchList(const Vector<Batch*>& batchList,
627        OpenGLRenderer& renderer, Rect& dirty) {
628
629    for (unsigned int i = 0; i < batchList.size(); i++) {
630        if (batchList[i]) {
631            batchList[i]->replay(renderer, dirty, i);
632        }
633    }
634    DEFER_LOGD("--flushed, drew %d batches", batchList.size());
635}
636
637void DeferredDisplayList::flush(OpenGLRenderer& renderer, Rect& dirty) {
638    ATRACE_NAME("flush drawing commands");
639    Caches::getInstance().fontRenderer->endPrecaching();
640
641    if (isEmpty()) return; // nothing to flush
642    renderer.restoreToCount(1);
643
644    DEFER_LOGD("--flushing");
645    renderer.eventMark("Flush");
646
647    // save and restore (with draw modifiers) so that reordering doesn't affect final state
648    DrawModifiers restoreDrawModifiers = renderer.getDrawModifiers();
649    renderer.save(SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
650
651    if (CC_LIKELY(mAvoidOverdraw)) {
652        for (unsigned int i = 1; i < mBatches.size(); i++) {
653            if (mBatches[i] && mBatches[i]->coversBounds(mBounds)) {
654                discardDrawingBatches(i - 1);
655            }
656        }
657    }
658    // NOTE: depth of the save stack at this point, before playback, should be reflected in
659    // FLUSH_SAVE_STACK_DEPTH, so that save/restores match up correctly
660    replayBatchList(mBatches, renderer, dirty);
661
662    renderer.restoreToCount(1);
663    renderer.setDrawModifiers(restoreDrawModifiers);
664
665    DEFER_LOGD("--flush complete, returning %x", status);
666    clear();
667}
668
669void DeferredDisplayList::discardDrawingBatches(const unsigned int maxIndex) {
670    for (unsigned int i = mEarliestUnclearedIndex; i <= maxIndex; i++) {
671        // leave deferred state ops alone for simplicity (empty save restore pairs may now exist)
672        if (mBatches[i] && mBatches[i]->purelyDrawBatch()) {
673            delete mBatches[i];
674            mBatches.replaceAt(nullptr, i);
675        }
676    }
677    mEarliestUnclearedIndex = maxIndex + 1;
678}
679
680}; // namespace uirenderer
681}; // namespace android
682