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