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