DisplayListOp.h revision d218a92c0afb8c0d98135b20b52ac87236e1c935
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#ifndef ANDROID_HWUI_DISPLAY_OPERATION_H
18#define ANDROID_HWUI_DISPLAY_OPERATION_H
19
20#ifndef LOG_TAG
21    #define LOG_TAG "OpenGLRenderer"
22#endif
23
24#include <SkXfermode.h>
25
26#include <private/hwui/DrawGlInfo.h>
27
28#include "OpenGLRenderer.h"
29#include "AssetAtlas.h"
30#include "DeferredDisplayList.h"
31#include "DisplayListRenderer.h"
32#include "UvMapper.h"
33#include "utils/LinearAllocator.h"
34
35#define CRASH() do { \
36    *(int *)(uintptr_t) 0xbbadbeef = 0; \
37    ((void(*)())0)(); /* More reliable, but doesn't say BBADBEEF */ \
38} while(false)
39
40// Use OP_LOG for logging with arglist, OP_LOGS if just printing char*
41#define OP_LOGS(s) OP_LOG("%s", (s))
42#define OP_LOG(s, ...) ALOGD( "%*s" s, level * 2, "", __VA_ARGS__ )
43
44namespace android {
45namespace uirenderer {
46
47/**
48 * Structure for storing canvas operations when they are recorded into a DisplayList, so that they
49 * may be replayed to an OpenGLRenderer.
50 *
51 * To avoid individual memory allocations, DisplayListOps may only be allocated into a
52 * LinearAllocator's managed memory buffers.  Each pointer held by a DisplayListOp is either a
53 * pointer into memory also allocated in the LinearAllocator (mostly for text and float buffers) or
54 * references a externally refcounted object (Sk... and Skia... objects). ~DisplayListOp() is
55 * never called as LinearAllocators are simply discarded, so no memory management should be done in
56 * this class.
57 */
58class DisplayListOp {
59public:
60    // These objects should always be allocated with a LinearAllocator, and never destroyed/deleted.
61    // standard new() intentionally not implemented, and delete/deconstructor should never be used.
62    virtual ~DisplayListOp() { CRASH(); }
63    static void operator delete(void* ptr) { CRASH(); }
64    /** static void* operator new(size_t size); PURPOSELY OMITTED **/
65    static void* operator new(size_t size, LinearAllocator& allocator) {
66        return allocator.alloc(size);
67    }
68
69    enum OpLogFlag {
70        kOpLogFlag_Recurse = 0x1,
71        kOpLogFlag_JSON = 0x2 // TODO: add?
72    };
73
74    virtual void defer(DeferStateStruct& deferStruct, int saveCount, int level,
75            bool useQuickReject) = 0;
76
77    virtual void replay(ReplayStateStruct& replayStruct, int saveCount, int level,
78            bool useQuickReject) = 0;
79
80    virtual void output(int level, uint32_t logFlags = 0) const = 0;
81
82    // NOTE: it would be nice to declare constants and overriding the implementation in each op to
83    // point at the constants, but that seems to require a .cpp file
84    virtual const char* name() = 0;
85};
86
87class StateOp : public DisplayListOp {
88public:
89    StateOp() {};
90
91    virtual ~StateOp() {}
92
93    virtual void defer(DeferStateStruct& deferStruct, int saveCount, int level,
94            bool useQuickReject) {
95        // default behavior only affects immediate, deferrable state, issue directly to renderer
96        applyState(deferStruct.mRenderer, saveCount);
97    }
98
99    /**
100     * State operations are applied directly to the renderer, but can cause the deferred drawing op
101     * list to flush
102     */
103    virtual void replay(ReplayStateStruct& replayStruct, int saveCount, int level,
104            bool useQuickReject) {
105        applyState(replayStruct.mRenderer, saveCount);
106    }
107
108    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const = 0;
109};
110
111class DrawOp : public DisplayListOp {
112friend class MergingDrawBatch;
113public:
114    DrawOp(const SkPaint* paint)
115            : mPaint(paint), mQuickRejected(false) {}
116
117    virtual void defer(DeferStateStruct& deferStruct, int saveCount, int level,
118            bool useQuickReject) {
119        if (mQuickRejected && CC_LIKELY(useQuickReject)) {
120            return;
121        }
122
123        deferStruct.mDeferredList.addDrawOp(deferStruct.mRenderer, this);
124    }
125
126    virtual void replay(ReplayStateStruct& replayStruct, int saveCount, int level,
127            bool useQuickReject) {
128        if (mQuickRejected && CC_LIKELY(useQuickReject)) {
129            return;
130        }
131
132        replayStruct.mDrawGlStatus |= applyDraw(replayStruct.mRenderer, replayStruct.mDirty);
133    }
134
135    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) = 0;
136
137    /**
138     * Draw multiple instances of an operation, must be overidden for operations that merge
139     *
140     * Currently guarantees certain similarities between ops (see MergingDrawBatch::canMergeWith),
141     * and pure translation transformations. Other guarantees of similarity should be enforced by
142     * reducing which operations are tagged as mergeable.
143     */
144    virtual status_t multiDraw(OpenGLRenderer& renderer, Rect& dirty,
145            const Vector<OpStatePair>& ops, const Rect& bounds) {
146        status_t status = DrawGlInfo::kStatusDone;
147        for (unsigned int i = 0; i < ops.size(); i++) {
148            renderer.restoreDisplayState(*(ops[i].state), true);
149            status |= ops[i].op->applyDraw(renderer, dirty);
150        }
151        return status;
152    }
153
154    /**
155     * When this method is invoked the state field is initialized to have the
156     * final rendering state. We can thus use it to process data as it will be
157     * used at draw time.
158     *
159     * Additionally, this method allows subclasses to provide defer-time preferences for batching
160     * and merging.
161     *
162     * if a subclass can set deferInfo.mergeable to true, it should implement multiDraw()
163     */
164    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo,
165            const DeferredDisplayState& state) {}
166
167    /**
168     * Query the conservative, local bounds (unmapped) bounds of the op.
169     *
170     * returns true if bounds exist
171     */
172    virtual bool getLocalBounds(const DrawModifiers& drawModifiers, Rect& localBounds) {
173        return false;
174    }
175
176    // TODO: better refine localbounds usage
177    void setQuickRejected(bool quickRejected) { mQuickRejected = quickRejected; }
178    bool getQuickRejected() { return mQuickRejected; }
179
180    inline int getPaintAlpha() const {
181        return OpenGLRenderer::getAlphaDirect(mPaint);
182    }
183
184    inline float strokeWidthOutset() {
185        // since anything AA stroke with less than 1.0 pixel width is drawn with an alpha-reduced
186        // 1.0 stroke, treat 1.0 as minimum.
187
188        // TODO: it would be nice if this could take scale into account, but scale isn't stable
189        // since higher levels of the view hierarchy can change scale out from underneath it.
190        return fmaxf(mPaint->getStrokeWidth(), 1) * 0.5f;
191    }
192
193protected:
194    const SkPaint* getPaint(OpenGLRenderer& renderer) {
195        return renderer.filterPaint(mPaint);
196    }
197
198    // Helper method for determining op opaqueness. Assumes op fills its bounds in local
199    // coordinates, and that paint's alpha is used
200    inline bool isOpaqueOverBounds(const DeferredDisplayState& state) {
201        // ensure that local bounds cover mapped bounds
202        if (!state.mMatrix.isSimple()) return false;
203
204        // check state/paint for transparency
205        if (state.mDrawModifiers.mShader ||
206                state.mAlpha != 1.0f ||
207                (mPaint && mPaint->getAlpha() != 0xFF)) return false;
208
209        SkXfermode::Mode mode = OpenGLRenderer::getXfermodeDirect(mPaint);
210        return (mode == SkXfermode::kSrcOver_Mode ||
211                mode == SkXfermode::kSrc_Mode);
212
213    }
214
215    const SkPaint* mPaint; // should be accessed via getPaint() when applying
216    bool mQuickRejected;
217};
218
219class DrawBoundedOp : public DrawOp {
220public:
221    DrawBoundedOp(float left, float top, float right, float bottom, const SkPaint* paint)
222            : DrawOp(paint), mLocalBounds(left, top, right, bottom) {}
223
224    DrawBoundedOp(const Rect& localBounds, const SkPaint* paint)
225            : DrawOp(paint), mLocalBounds(localBounds) {}
226
227    // Calculates bounds as smallest rect encompassing all points
228    // NOTE: requires at least 1 vertex, and doesn't account for stroke size (should be handled in
229    // subclass' constructor)
230    DrawBoundedOp(const float* points, int count, const SkPaint* paint)
231            : DrawOp(paint), mLocalBounds(points[0], points[1], points[0], points[1]) {
232        for (int i = 2; i < count; i += 2) {
233            mLocalBounds.left = fminf(mLocalBounds.left, points[i]);
234            mLocalBounds.right = fmaxf(mLocalBounds.right, points[i]);
235            mLocalBounds.top = fminf(mLocalBounds.top, points[i + 1]);
236            mLocalBounds.bottom = fmaxf(mLocalBounds.bottom, points[i + 1]);
237        }
238    }
239
240    // default empty constructor for bounds, to be overridden in child constructor body
241    DrawBoundedOp(const SkPaint* paint): DrawOp(paint) { }
242
243    bool getLocalBounds(const DrawModifiers& drawModifiers, Rect& localBounds) {
244        localBounds.set(mLocalBounds);
245        if (drawModifiers.mHasShadow) {
246            // TODO: inspect paint's looper directly
247            Rect shadow(mLocalBounds);
248            shadow.translate(drawModifiers.mShadowDx, drawModifiers.mShadowDy);
249            shadow.outset(drawModifiers.mShadowRadius);
250            localBounds.unionWith(shadow);
251        }
252        return true;
253    }
254
255protected:
256    Rect mLocalBounds; // displayed area in LOCAL coord. doesn't incorporate stroke, so check paint
257};
258
259///////////////////////////////////////////////////////////////////////////////
260// STATE OPERATIONS - these may affect the state of the canvas/renderer, but do
261//         not directly draw or alter output
262///////////////////////////////////////////////////////////////////////////////
263
264class SaveOp : public StateOp {
265public:
266    SaveOp(int flags)
267            : mFlags(flags) {}
268
269    virtual void defer(DeferStateStruct& deferStruct, int saveCount, int level,
270            bool useQuickReject) {
271        int newSaveCount = deferStruct.mRenderer.save(mFlags);
272        deferStruct.mDeferredList.addSave(deferStruct.mRenderer, this, newSaveCount);
273    }
274
275    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
276        renderer.save(mFlags);
277    }
278
279    virtual void output(int level, uint32_t logFlags) const {
280        OP_LOG("Save flags %x", mFlags);
281    }
282
283    virtual const char* name() { return "Save"; }
284
285    int getFlags() const { return mFlags; }
286private:
287    SaveOp() {}
288    DisplayListOp* reinit(int flags) {
289        mFlags = flags;
290        return this;
291    }
292
293    int mFlags;
294};
295
296class RestoreToCountOp : public StateOp {
297public:
298    RestoreToCountOp(int count)
299            : mCount(count) {}
300
301    virtual void defer(DeferStateStruct& deferStruct, int saveCount, int level,
302            bool useQuickReject) {
303        deferStruct.mDeferredList.addRestoreToCount(deferStruct.mRenderer,
304                this, saveCount + mCount);
305        deferStruct.mRenderer.restoreToCount(saveCount + mCount);
306    }
307
308    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
309        renderer.restoreToCount(saveCount + mCount);
310    }
311
312    virtual void output(int level, uint32_t logFlags) const {
313        OP_LOG("Restore to count %d", mCount);
314    }
315
316    virtual const char* name() { return "RestoreToCount"; }
317
318private:
319    RestoreToCountOp() {}
320    DisplayListOp* reinit(int count) {
321        mCount = count;
322        return this;
323    }
324
325    int mCount;
326};
327
328class SaveLayerOp : public StateOp {
329public:
330    SaveLayerOp(float left, float top, float right, float bottom,
331            int alpha, SkXfermode::Mode mode, int flags)
332            : mArea(left, top, right, bottom), mAlpha(alpha), mMode(mode), mFlags(flags) {}
333
334    virtual void defer(DeferStateStruct& deferStruct, int saveCount, int level,
335            bool useQuickReject) {
336        // NOTE: don't bother with actual saveLayer, instead issuing it at flush time
337        int newSaveCount = deferStruct.mRenderer.getSaveCount();
338        deferStruct.mDeferredList.addSaveLayer(deferStruct.mRenderer, this, newSaveCount);
339
340        // NOTE: don't issue full saveLayer, since that has side effects/is costly. instead just
341        // setup the snapshot for deferral, and re-issue the op at flush time
342        deferStruct.mRenderer.saveLayerDeferred(mArea.left, mArea.top, mArea.right, mArea.bottom,
343                mAlpha, mMode, mFlags);
344    }
345
346    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
347        renderer.saveLayer(mArea.left, mArea.top, mArea.right, mArea.bottom, mAlpha, mMode, mFlags);
348    }
349
350    virtual void output(int level, uint32_t logFlags) const {
351        OP_LOG("SaveLayer%s of area " RECT_STRING,
352                (isSaveLayerAlpha() ? "Alpha" : ""),RECT_ARGS(mArea));
353    }
354
355    virtual const char* name() { return isSaveLayerAlpha() ? "SaveLayerAlpha" : "SaveLayer"; }
356
357    int getFlags() { return mFlags; }
358
359private:
360    // Special case, reserved for direct DisplayList usage
361    SaveLayerOp() {}
362    DisplayListOp* reinit(float left, float top, float right, float bottom,
363            int alpha, SkXfermode::Mode mode, int flags) {
364        mArea.set(left, top, right, bottom);
365        mAlpha = alpha;
366        mMode = mode;
367        mFlags = flags;
368        return this;
369    }
370
371    bool isSaveLayerAlpha() const { return mAlpha < 255 && mMode == SkXfermode::kSrcOver_Mode; }
372    Rect mArea;
373    int mAlpha;
374    SkXfermode::Mode mMode;
375    int mFlags;
376};
377
378class TranslateOp : public StateOp {
379public:
380    TranslateOp(float dx, float dy)
381            : mDx(dx), mDy(dy) {}
382
383    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
384        renderer.translate(mDx, mDy);
385    }
386
387    virtual void output(int level, uint32_t logFlags) const {
388        OP_LOG("Translate by %f %f", mDx, mDy);
389    }
390
391    virtual const char* name() { return "Translate"; }
392
393private:
394    float mDx;
395    float mDy;
396};
397
398class RotateOp : public StateOp {
399public:
400    RotateOp(float degrees)
401            : mDegrees(degrees) {}
402
403    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
404        renderer.rotate(mDegrees);
405    }
406
407    virtual void output(int level, uint32_t logFlags) const {
408        OP_LOG("Rotate by %f degrees", mDegrees);
409    }
410
411    virtual const char* name() { return "Rotate"; }
412
413private:
414    float mDegrees;
415};
416
417class ScaleOp : public StateOp {
418public:
419    ScaleOp(float sx, float sy)
420            : mSx(sx), mSy(sy) {}
421
422    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
423        renderer.scale(mSx, mSy);
424    }
425
426    virtual void output(int level, uint32_t logFlags) const {
427        OP_LOG("Scale by %f %f", mSx, mSy);
428    }
429
430    virtual const char* name() { return "Scale"; }
431
432private:
433    float mSx;
434    float mSy;
435};
436
437class SkewOp : public StateOp {
438public:
439    SkewOp(float sx, float sy)
440            : mSx(sx), mSy(sy) {}
441
442    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
443        renderer.skew(mSx, mSy);
444    }
445
446    virtual void output(int level, uint32_t logFlags) const {
447        OP_LOG("Skew by %f %f", mSx, mSy);
448    }
449
450    virtual const char* name() { return "Skew"; }
451
452private:
453    float mSx;
454    float mSy;
455};
456
457class SetMatrixOp : public StateOp {
458public:
459    SetMatrixOp(const SkMatrix* matrix)
460            : mMatrix(matrix) {}
461
462    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
463        renderer.setMatrix(mMatrix);
464    }
465
466    virtual void output(int level, uint32_t logFlags) const {
467        if (mMatrix) {
468            OP_LOG("SetMatrix " MATRIX_STRING, MATRIX_ARGS(mMatrix));
469        } else {
470            OP_LOGS("SetMatrix (reset)");
471        }
472    }
473
474    virtual const char* name() { return "SetMatrix"; }
475
476private:
477    const SkMatrix* mMatrix;
478};
479
480class ConcatMatrixOp : public StateOp {
481public:
482    ConcatMatrixOp(const SkMatrix* matrix)
483            : mMatrix(matrix) {}
484
485    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
486        renderer.concatMatrix(mMatrix);
487    }
488
489    virtual void output(int level, uint32_t logFlags) const {
490        OP_LOG("ConcatMatrix " MATRIX_STRING, MATRIX_ARGS(mMatrix));
491    }
492
493    virtual const char* name() { return "ConcatMatrix"; }
494
495private:
496    const SkMatrix* mMatrix;
497};
498
499class ClipOp : public StateOp {
500public:
501    ClipOp(SkRegion::Op op) : mOp(op) {}
502
503    virtual void defer(DeferStateStruct& deferStruct, int saveCount, int level,
504            bool useQuickReject) {
505        // NOTE: must defer op BEFORE applying state, since it may read clip
506        deferStruct.mDeferredList.addClip(deferStruct.mRenderer, this);
507
508        // TODO: Can we avoid applying complex clips at defer time?
509        applyState(deferStruct.mRenderer, saveCount);
510    }
511
512    bool canCauseComplexClip() {
513        return ((mOp != SkRegion::kIntersect_Op) && (mOp != SkRegion::kReplace_Op)) || !isRect();
514    }
515
516protected:
517    ClipOp() {}
518    virtual bool isRect() { return false; }
519
520    SkRegion::Op mOp;
521};
522
523class ClipRectOp : public ClipOp {
524public:
525    ClipRectOp(float left, float top, float right, float bottom, SkRegion::Op op)
526            : ClipOp(op), mArea(left, top, right, bottom) {}
527
528    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
529        renderer.clipRect(mArea.left, mArea.top, mArea.right, mArea.bottom, mOp);
530    }
531
532    virtual void output(int level, uint32_t logFlags) const {
533        OP_LOG("ClipRect " RECT_STRING, RECT_ARGS(mArea));
534    }
535
536    virtual const char* name() { return "ClipRect"; }
537
538protected:
539    virtual bool isRect() { return true; }
540
541private:
542    ClipRectOp() {}
543    DisplayListOp* reinit(float left, float top, float right, float bottom, SkRegion::Op op) {
544        mOp = op;
545        mArea.set(left, top, right, bottom);
546        return this;
547    }
548
549    Rect mArea;
550};
551
552class ClipPathOp : public ClipOp {
553public:
554    ClipPathOp(const SkPath* path, SkRegion::Op op)
555            : ClipOp(op), mPath(path) {}
556
557    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
558        renderer.clipPath(mPath, mOp);
559    }
560
561    virtual void output(int level, uint32_t logFlags) const {
562        SkRect bounds = mPath->getBounds();
563        OP_LOG("ClipPath bounds " RECT_STRING,
564                bounds.left(), bounds.top(), bounds.right(), bounds.bottom());
565    }
566
567    virtual const char* name() { return "ClipPath"; }
568
569private:
570    const SkPath* mPath;
571};
572
573class ClipRegionOp : public ClipOp {
574public:
575    ClipRegionOp(const SkRegion* region, SkRegion::Op op)
576            : ClipOp(op), mRegion(region) {}
577
578    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
579        renderer.clipRegion(mRegion, mOp);
580    }
581
582    virtual void output(int level, uint32_t logFlags) const {
583        SkIRect bounds = mRegion->getBounds();
584        OP_LOG("ClipRegion bounds %d %d %d %d",
585                bounds.left(), bounds.top(), bounds.right(), bounds.bottom());
586    }
587
588    virtual const char* name() { return "ClipRegion"; }
589
590private:
591    const SkRegion* mRegion;
592};
593
594class ResetShaderOp : public StateOp {
595public:
596    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
597        renderer.resetShader();
598    }
599
600    virtual void output(int level, uint32_t logFlags) const {
601        OP_LOGS("ResetShader");
602    }
603
604    virtual const char* name() { return "ResetShader"; }
605};
606
607class SetupShaderOp : public StateOp {
608public:
609    SetupShaderOp(SkiaShader* shader)
610            : mShader(shader) {}
611    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
612        renderer.setupShader(mShader);
613    }
614
615    virtual void output(int level, uint32_t logFlags) const {
616        OP_LOG("SetupShader, shader %p", mShader);
617    }
618
619    virtual const char* name() { return "SetupShader"; }
620
621private:
622    SkiaShader* mShader;
623};
624
625class ResetColorFilterOp : public StateOp {
626public:
627    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
628        renderer.resetColorFilter();
629    }
630
631    virtual void output(int level, uint32_t logFlags) const {
632        OP_LOGS("ResetColorFilter");
633    }
634
635    virtual const char* name() { return "ResetColorFilter"; }
636};
637
638class SetupColorFilterOp : public StateOp {
639public:
640    SetupColorFilterOp(SkiaColorFilter* colorFilter)
641            : mColorFilter(colorFilter) {}
642
643    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
644        renderer.setupColorFilter(mColorFilter);
645    }
646
647    virtual void output(int level, uint32_t logFlags) const {
648        OP_LOG("SetupColorFilter, filter %p", mColorFilter);
649    }
650
651    virtual const char* name() { return "SetupColorFilter"; }
652
653private:
654    SkiaColorFilter* mColorFilter;
655};
656
657class ResetShadowOp : public StateOp {
658public:
659    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
660        renderer.resetShadow();
661    }
662
663    virtual void output(int level, uint32_t logFlags) const {
664        OP_LOGS("ResetShadow");
665    }
666
667    virtual const char* name() { return "ResetShadow"; }
668};
669
670class SetupShadowOp : public StateOp {
671public:
672    SetupShadowOp(float radius, float dx, float dy, int color)
673            : mRadius(radius), mDx(dx), mDy(dy), mColor(color) {}
674
675    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
676        renderer.setupShadow(mRadius, mDx, mDy, mColor);
677    }
678
679    virtual void output(int level, uint32_t logFlags) const {
680        OP_LOG("SetupShadow, radius %f, %f, %f, color %#x", mRadius, mDx, mDy, mColor);
681    }
682
683    virtual const char* name() { return "SetupShadow"; }
684
685private:
686    float mRadius;
687    float mDx;
688    float mDy;
689    int mColor;
690};
691
692class ResetPaintFilterOp : public StateOp {
693public:
694    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
695        renderer.resetPaintFilter();
696    }
697
698    virtual void output(int level, uint32_t logFlags) const {
699        OP_LOGS("ResetPaintFilter");
700    }
701
702    virtual const char* name() { return "ResetPaintFilter"; }
703};
704
705class SetupPaintFilterOp : public StateOp {
706public:
707    SetupPaintFilterOp(int clearBits, int setBits)
708            : mClearBits(clearBits), mSetBits(setBits) {}
709
710    virtual void applyState(OpenGLRenderer& renderer, int saveCount) const {
711        renderer.setupPaintFilter(mClearBits, mSetBits);
712    }
713
714    virtual void output(int level, uint32_t logFlags) const {
715        OP_LOG("SetupPaintFilter, clear %#x, set %#x", mClearBits, mSetBits);
716    }
717
718    virtual const char* name() { return "SetupPaintFilter"; }
719
720private:
721    int mClearBits;
722    int mSetBits;
723};
724
725///////////////////////////////////////////////////////////////////////////////
726// DRAW OPERATIONS - these are operations that can draw to the canvas's device
727///////////////////////////////////////////////////////////////////////////////
728
729class DrawBitmapOp : public DrawBoundedOp {
730public:
731    DrawBitmapOp(const SkBitmap* bitmap, float left, float top, const SkPaint* paint)
732            : DrawBoundedOp(left, top, left + bitmap->width(), top + bitmap->height(), paint),
733            mBitmap(bitmap), mAtlas(Caches::getInstance().assetAtlas) {
734        mEntry = mAtlas.getEntry(bitmap);
735        if (mEntry) {
736            mEntryGenerationId = mAtlas.getGenerationId();
737            mUvMapper = mEntry->uvMapper;
738        }
739    }
740
741    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
742        return renderer.drawBitmap(mBitmap, mLocalBounds.left, mLocalBounds.top,
743                getPaint(renderer));
744    }
745
746    AssetAtlas::Entry* getAtlasEntry() {
747        // The atlas entry is stale, let's get a new one
748        if (mEntry && mEntryGenerationId != mAtlas.getGenerationId()) {
749            mEntryGenerationId = mAtlas.getGenerationId();
750            mEntry = mAtlas.getEntry(mBitmap);
751            mUvMapper = mEntry->uvMapper;
752        }
753        return mEntry;
754    }
755
756#define SET_TEXTURE(ptr, posRect, offsetRect, texCoordsRect, xDim, yDim) \
757    TextureVertex::set(ptr++, posRect.xDim - offsetRect.left, posRect.yDim - offsetRect.top, \
758            texCoordsRect.xDim, texCoordsRect.yDim)
759
760    /**
761     * This multi-draw operation builds a mesh on the stack by generating a quad
762     * for each bitmap in the batch. This method is also responsible for dirtying
763     * the current layer, if any.
764     */
765    virtual status_t multiDraw(OpenGLRenderer& renderer, Rect& dirty,
766            const Vector<OpStatePair>& ops, const Rect& bounds) {
767        const DeferredDisplayState& firstState = *(ops[0].state);
768        renderer.restoreDisplayState(firstState, true); // restore all but the clip
769
770        TextureVertex vertices[6 * ops.size()];
771        TextureVertex* vertex = &vertices[0];
772
773        const bool hasLayer = renderer.hasLayer();
774        bool pureTranslate = true;
775
776        // TODO: manually handle rect clip for bitmaps by adjusting texCoords per op,
777        // and allowing them to be merged in getBatchId()
778        for (unsigned int i = 0; i < ops.size(); i++) {
779            const DeferredDisplayState& state = *(ops[i].state);
780            const Rect& opBounds = state.mBounds;
781            // When we reach multiDraw(), the matrix can be either
782            // pureTranslate or simple (translate and/or scale).
783            // If the matrix is not pureTranslate, then we have a scale
784            pureTranslate &= state.mMatrix.isPureTranslate();
785
786            Rect texCoords(0, 0, 1, 1);
787            ((DrawBitmapOp*) ops[i].op)->mUvMapper.map(texCoords);
788
789            SET_TEXTURE(vertex, opBounds, bounds, texCoords, left, top);
790            SET_TEXTURE(vertex, opBounds, bounds, texCoords, right, top);
791            SET_TEXTURE(vertex, opBounds, bounds, texCoords, left, bottom);
792
793            SET_TEXTURE(vertex, opBounds, bounds, texCoords, left, bottom);
794            SET_TEXTURE(vertex, opBounds, bounds, texCoords, right, top);
795            SET_TEXTURE(vertex, opBounds, bounds, texCoords, right, bottom);
796
797            if (hasLayer) {
798                renderer.dirtyLayer(opBounds.left, opBounds.top, opBounds.right, opBounds.bottom);
799            }
800        }
801
802        return renderer.drawBitmaps(mBitmap, mEntry, ops.size(), &vertices[0],
803                pureTranslate, bounds, mPaint);
804    }
805
806    virtual void output(int level, uint32_t logFlags) const {
807        OP_LOG("Draw bitmap %p at %f %f", mBitmap, mLocalBounds.left, mLocalBounds.top);
808    }
809
810    virtual const char* name() { return "DrawBitmap"; }
811
812    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo,
813            const DeferredDisplayState& state) {
814        deferInfo.batchId = DeferredDisplayList::kOpBatch_Bitmap;
815        deferInfo.mergeId = getAtlasEntry() ?
816                (mergeid_t) mEntry->getMergeId() : (mergeid_t) mBitmap;
817
818        // Don't merge non-simply transformed or neg scale ops, SET_TEXTURE doesn't handle rotation
819        // Don't merge A8 bitmaps - the paint's color isn't compared by mergeId, or in
820        // MergingDrawBatch::canMergeWith()
821        // TODO: support clipped bitmaps by handling them in SET_TEXTURE
822        deferInfo.mergeable = state.mMatrix.isSimple() && state.mMatrix.positiveScale() &&
823                !state.mClipSideFlags &&
824                OpenGLRenderer::getXfermodeDirect(mPaint) == SkXfermode::kSrcOver_Mode &&
825                (mBitmap->getConfig() != SkBitmap::kA8_Config);
826    }
827
828    const SkBitmap* bitmap() { return mBitmap; }
829protected:
830    const SkBitmap* mBitmap;
831    const AssetAtlas& mAtlas;
832    uint32_t mEntryGenerationId;
833    AssetAtlas::Entry* mEntry;
834    UvMapper mUvMapper;
835};
836
837class DrawBitmapMatrixOp : public DrawBoundedOp {
838public:
839    DrawBitmapMatrixOp(const SkBitmap* bitmap, const SkMatrix* matrix, const SkPaint* paint)
840            : DrawBoundedOp(paint), mBitmap(bitmap), mMatrix(matrix) {
841        mLocalBounds.set(0, 0, bitmap->width(), bitmap->height());
842        const mat4 transform(*matrix);
843        transform.mapRect(mLocalBounds);
844    }
845
846    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
847        return renderer.drawBitmap(mBitmap, mMatrix, getPaint(renderer));
848    }
849
850    virtual void output(int level, uint32_t logFlags) const {
851        OP_LOG("Draw bitmap %p matrix " MATRIX_STRING, mBitmap, MATRIX_ARGS(mMatrix));
852    }
853
854    virtual const char* name() { return "DrawBitmapMatrix"; }
855
856    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo,
857            const DeferredDisplayState& state) {
858        deferInfo.batchId = DeferredDisplayList::kOpBatch_Bitmap;
859    }
860
861private:
862    const SkBitmap* mBitmap;
863    const SkMatrix* mMatrix;
864};
865
866class DrawBitmapRectOp : public DrawBoundedOp {
867public:
868    DrawBitmapRectOp(const SkBitmap* bitmap,
869            float srcLeft, float srcTop, float srcRight, float srcBottom,
870            float dstLeft, float dstTop, float dstRight, float dstBottom, const SkPaint* paint)
871            : DrawBoundedOp(dstLeft, dstTop, dstRight, dstBottom, paint),
872            mBitmap(bitmap), mSrc(srcLeft, srcTop, srcRight, srcBottom) {}
873
874    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
875        return renderer.drawBitmap(mBitmap, mSrc.left, mSrc.top, mSrc.right, mSrc.bottom,
876                mLocalBounds.left, mLocalBounds.top, mLocalBounds.right, mLocalBounds.bottom,
877                getPaint(renderer));
878    }
879
880    virtual void output(int level, uint32_t logFlags) const {
881        OP_LOG("Draw bitmap %p src="RECT_STRING", dst="RECT_STRING,
882                mBitmap, RECT_ARGS(mSrc), RECT_ARGS(mLocalBounds));
883    }
884
885    virtual const char* name() { return "DrawBitmapRect"; }
886
887    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo,
888            const DeferredDisplayState& state) {
889        deferInfo.batchId = DeferredDisplayList::kOpBatch_Bitmap;
890    }
891
892private:
893    const SkBitmap* mBitmap;
894    Rect mSrc;
895};
896
897class DrawBitmapDataOp : public DrawBitmapOp {
898public:
899    DrawBitmapDataOp(const SkBitmap* bitmap, float left, float top, const SkPaint* paint)
900            : DrawBitmapOp(bitmap, left, top, paint) {}
901
902    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
903        return renderer.drawBitmapData(mBitmap, mLocalBounds.left,
904                mLocalBounds.top, getPaint(renderer));
905    }
906
907    virtual void output(int level, uint32_t logFlags) const {
908        OP_LOG("Draw bitmap %p", mBitmap);
909    }
910
911    virtual const char* name() { return "DrawBitmapData"; }
912
913    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo,
914            const DeferredDisplayState& state) {
915        deferInfo.batchId = DeferredDisplayList::kOpBatch_Bitmap;
916    }
917};
918
919class DrawBitmapMeshOp : public DrawBoundedOp {
920public:
921    DrawBitmapMeshOp(const SkBitmap* bitmap, int meshWidth, int meshHeight,
922            const float* vertices, const int* colors, const SkPaint* paint)
923            : DrawBoundedOp(vertices, 2 * (meshWidth + 1) * (meshHeight + 1), paint),
924            mBitmap(bitmap), mMeshWidth(meshWidth), mMeshHeight(meshHeight),
925            mVertices(vertices), mColors(colors) {}
926
927    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
928        return renderer.drawBitmapMesh(mBitmap, mMeshWidth, mMeshHeight,
929                mVertices, mColors, getPaint(renderer));
930    }
931
932    virtual void output(int level, uint32_t logFlags) const {
933        OP_LOG("Draw bitmap %p mesh %d x %d", mBitmap, mMeshWidth, mMeshHeight);
934    }
935
936    virtual const char* name() { return "DrawBitmapMesh"; }
937
938    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo,
939            const DeferredDisplayState& state) {
940        deferInfo.batchId = DeferredDisplayList::kOpBatch_Bitmap;
941    }
942
943private:
944    const SkBitmap* mBitmap;
945    int mMeshWidth;
946    int mMeshHeight;
947    const float* mVertices;
948    const int* mColors;
949};
950
951class DrawPatchOp : public DrawBoundedOp {
952public:
953    DrawPatchOp(const SkBitmap* bitmap, const Res_png_9patch* patch,
954            float left, float top, float right, float bottom, const SkPaint* paint)
955            : DrawBoundedOp(left, top, right, bottom, paint),
956            mBitmap(bitmap), mPatch(patch), mGenerationId(0), mMesh(NULL),
957            mAtlas(Caches::getInstance().assetAtlas) {
958        mEntry = mAtlas.getEntry(bitmap);
959        if (mEntry) {
960            mEntryGenerationId = mAtlas.getGenerationId();
961        }
962    };
963
964    AssetAtlas::Entry* getAtlasEntry() {
965        // The atlas entry is stale, let's get a new one
966        if (mEntry && mEntryGenerationId != mAtlas.getGenerationId()) {
967            mEntryGenerationId = mAtlas.getGenerationId();
968            mEntry = mAtlas.getEntry(mBitmap);
969        }
970        return mEntry;
971    }
972
973    const Patch* getMesh(OpenGLRenderer& renderer) {
974        if (!mMesh || renderer.getCaches().patchCache.getGenerationId() != mGenerationId) {
975            PatchCache& cache = renderer.getCaches().patchCache;
976            mMesh = cache.get(getAtlasEntry(), mBitmap->width(), mBitmap->height(),
977                    mLocalBounds.getWidth(), mLocalBounds.getHeight(), mPatch);
978            mGenerationId = cache.getGenerationId();
979        }
980        return mMesh;
981    }
982
983    /**
984     * This multi-draw operation builds an indexed mesh on the stack by copying
985     * and transforming the vertices of each 9-patch in the batch. This method
986     * is also responsible for dirtying the current layer, if any.
987     */
988    virtual status_t multiDraw(OpenGLRenderer& renderer, Rect& dirty,
989            const Vector<OpStatePair>& ops, const Rect& bounds) {
990        const DeferredDisplayState& firstState = *(ops[0].state);
991        renderer.restoreDisplayState(firstState, true); // restore all but the clip
992
993        // Batches will usually contain a small number of items so it's
994        // worth performing a first iteration to count the exact number
995        // of vertices we need in the new mesh
996        uint32_t totalVertices = 0;
997        for (unsigned int i = 0; i < ops.size(); i++) {
998            totalVertices += ((DrawPatchOp*) ops[i].op)->getMesh(renderer)->verticesCount;
999        }
1000
1001        const bool hasLayer = renderer.hasLayer();
1002
1003        uint32_t indexCount = 0;
1004
1005        TextureVertex vertices[totalVertices];
1006        TextureVertex* vertex = &vertices[0];
1007
1008        // Create a mesh that contains the transformed vertices for all the
1009        // 9-patch objects that are part of the batch. Note that onDefer()
1010        // enforces ops drawn by this function to have a pure translate or
1011        // identity matrix
1012        for (unsigned int i = 0; i < ops.size(); i++) {
1013            DrawPatchOp* patchOp = (DrawPatchOp*) ops[i].op;
1014            const DeferredDisplayState* state = ops[i].state;
1015            const Patch* opMesh = patchOp->getMesh(renderer);
1016            uint32_t vertexCount = opMesh->verticesCount;
1017            if (vertexCount == 0) continue;
1018
1019            // We use the bounds to know where to translate our vertices
1020            // Using patchOp->state.mBounds wouldn't work because these
1021            // bounds are clipped
1022            const float tx = (int) floorf(state->mMatrix.getTranslateX() +
1023                    patchOp->mLocalBounds.left + 0.5f);
1024            const float ty = (int) floorf(state->mMatrix.getTranslateY() +
1025                    patchOp->mLocalBounds.top + 0.5f);
1026
1027            // Copy & transform all the vertices for the current operation
1028            TextureVertex* opVertices = opMesh->vertices;
1029            for (uint32_t j = 0; j < vertexCount; j++, opVertices++) {
1030                TextureVertex::set(vertex++,
1031                        opVertices->x + tx, opVertices->y + ty,
1032                        opVertices->u, opVertices->v);
1033            }
1034
1035            // Dirty the current layer if possible. When the 9-patch does not
1036            // contain empty quads we can take a shortcut and simply set the
1037            // dirty rect to the object's bounds.
1038            if (hasLayer) {
1039                if (!opMesh->hasEmptyQuads) {
1040                    renderer.dirtyLayer(tx, ty,
1041                            tx + patchOp->mLocalBounds.getWidth(),
1042                            ty + patchOp->mLocalBounds.getHeight());
1043                } else {
1044                    const size_t count = opMesh->quads.size();
1045                    for (size_t i = 0; i < count; i++) {
1046                        const Rect& quadBounds = opMesh->quads[i];
1047                        const float x = tx + quadBounds.left;
1048                        const float y = ty + quadBounds.top;
1049                        renderer.dirtyLayer(x, y,
1050                                x + quadBounds.getWidth(), y + quadBounds.getHeight());
1051                    }
1052                }
1053            }
1054
1055            indexCount += opMesh->indexCount;
1056        }
1057
1058        return renderer.drawPatches(mBitmap, getAtlasEntry(),
1059                &vertices[0], indexCount, getPaint(renderer));
1060    }
1061
1062    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1063        // We're not calling the public variant of drawPatch() here
1064        // This method won't perform the quickReject() since we've already done it at this point
1065        return renderer.drawPatch(mBitmap, getMesh(renderer), getAtlasEntry(),
1066                mLocalBounds.left, mLocalBounds.top, mLocalBounds.right, mLocalBounds.bottom,
1067                getPaint(renderer));
1068    }
1069
1070    virtual void output(int level, uint32_t logFlags) const {
1071        OP_LOG("Draw patch "RECT_STRING, RECT_ARGS(mLocalBounds));
1072    }
1073
1074    virtual const char* name() { return "DrawPatch"; }
1075
1076    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo,
1077            const DeferredDisplayState& state) {
1078        deferInfo.batchId = DeferredDisplayList::kOpBatch_Patch;
1079        deferInfo.mergeId = getAtlasEntry() ? (mergeid_t) mEntry->getMergeId() : (mergeid_t) mBitmap;
1080        deferInfo.mergeable = state.mMatrix.isPureTranslate() &&
1081                OpenGLRenderer::getXfermodeDirect(mPaint) == SkXfermode::kSrcOver_Mode;
1082        deferInfo.opaqueOverBounds = isOpaqueOverBounds(state) && mBitmap->isOpaque();
1083    }
1084
1085private:
1086    const SkBitmap* mBitmap;
1087    const Res_png_9patch* mPatch;
1088
1089    uint32_t mGenerationId;
1090    const Patch* mMesh;
1091
1092    const AssetAtlas& mAtlas;
1093    uint32_t mEntryGenerationId;
1094    AssetAtlas::Entry* mEntry;
1095};
1096
1097class DrawColorOp : public DrawOp {
1098public:
1099    DrawColorOp(int color, SkXfermode::Mode mode)
1100            : DrawOp(NULL), mColor(color), mMode(mode) {};
1101
1102    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1103        return renderer.drawColor(mColor, mMode);
1104    }
1105
1106    virtual void output(int level, uint32_t logFlags) const {
1107        OP_LOG("Draw color %#x, mode %d", mColor, mMode);
1108    }
1109
1110    virtual const char* name() { return "DrawColor"; }
1111
1112private:
1113    int mColor;
1114    SkXfermode::Mode mMode;
1115};
1116
1117class DrawStrokableOp : public DrawBoundedOp {
1118public:
1119    DrawStrokableOp(float left, float top, float right, float bottom, const SkPaint* paint)
1120            : DrawBoundedOp(left, top, right, bottom, paint) {};
1121
1122    bool getLocalBounds(const DrawModifiers& drawModifiers, Rect& localBounds) {
1123        localBounds.set(mLocalBounds);
1124        if (mPaint && mPaint->getStyle() != SkPaint::kFill_Style) {
1125            localBounds.outset(strokeWidthOutset());
1126        }
1127        return true;
1128    }
1129
1130    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo,
1131            const DeferredDisplayState& state) {
1132        if (mPaint->getPathEffect()) {
1133            deferInfo.batchId = DeferredDisplayList::kOpBatch_AlphaMaskTexture;
1134        } else {
1135            deferInfo.batchId = mPaint->isAntiAlias() ?
1136                    DeferredDisplayList::kOpBatch_AlphaVertices :
1137                    DeferredDisplayList::kOpBatch_Vertices;
1138        }
1139    }
1140};
1141
1142class DrawRectOp : public DrawStrokableOp {
1143public:
1144    DrawRectOp(float left, float top, float right, float bottom, const SkPaint* paint)
1145            : DrawStrokableOp(left, top, right, bottom, paint) {}
1146
1147    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1148        return renderer.drawRect(mLocalBounds.left, mLocalBounds.top,
1149                mLocalBounds.right, mLocalBounds.bottom, getPaint(renderer));
1150    }
1151
1152    virtual void output(int level, uint32_t logFlags) const {
1153        OP_LOG("Draw Rect "RECT_STRING, RECT_ARGS(mLocalBounds));
1154    }
1155
1156    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo,
1157            const DeferredDisplayState& state) {
1158        DrawStrokableOp::onDefer(renderer, deferInfo, state);
1159        deferInfo.opaqueOverBounds = isOpaqueOverBounds(state) &&
1160                mPaint->getStyle() == SkPaint::kFill_Style;
1161    }
1162
1163    virtual const char* name() { return "DrawRect"; }
1164};
1165
1166class DrawRectsOp : public DrawBoundedOp {
1167public:
1168    DrawRectsOp(const float* rects, int count, const SkPaint* paint)
1169            : DrawBoundedOp(rects, count, paint),
1170            mRects(rects), mCount(count) {}
1171
1172    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1173        return renderer.drawRects(mRects, mCount, getPaint(renderer));
1174    }
1175
1176    virtual void output(int level, uint32_t logFlags) const {
1177        OP_LOG("Draw Rects count %d", mCount);
1178    }
1179
1180    virtual const char* name() { return "DrawRects"; }
1181
1182    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo,
1183            const DeferredDisplayState& state) {
1184        deferInfo.batchId = DeferredDisplayList::kOpBatch_Vertices;
1185    }
1186
1187private:
1188    const float* mRects;
1189    int mCount;
1190};
1191
1192class DrawRoundRectOp : public DrawStrokableOp {
1193public:
1194    DrawRoundRectOp(float left, float top, float right, float bottom,
1195            float rx, float ry, const SkPaint* paint)
1196            : DrawStrokableOp(left, top, right, bottom, paint), mRx(rx), mRy(ry) {}
1197
1198    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1199        return renderer.drawRoundRect(mLocalBounds.left, mLocalBounds.top,
1200                mLocalBounds.right, mLocalBounds.bottom, mRx, mRy, getPaint(renderer));
1201    }
1202
1203    virtual void output(int level, uint32_t logFlags) const {
1204        OP_LOG("Draw RoundRect "RECT_STRING", rx %f, ry %f", RECT_ARGS(mLocalBounds), mRx, mRy);
1205    }
1206
1207    virtual const char* name() { return "DrawRoundRect"; }
1208
1209private:
1210    float mRx;
1211    float mRy;
1212};
1213
1214class DrawCircleOp : public DrawStrokableOp {
1215public:
1216    DrawCircleOp(float x, float y, float radius, const SkPaint* paint)
1217            : DrawStrokableOp(x - radius, y - radius, x + radius, y + radius, paint),
1218            mX(x), mY(y), mRadius(radius) {}
1219
1220    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1221        return renderer.drawCircle(mX, mY, mRadius, getPaint(renderer));
1222    }
1223
1224    virtual void output(int level, uint32_t logFlags) const {
1225        OP_LOG("Draw Circle x %f, y %f, r %f", mX, mY, mRadius);
1226    }
1227
1228    virtual const char* name() { return "DrawCircle"; }
1229
1230private:
1231    float mX;
1232    float mY;
1233    float mRadius;
1234};
1235
1236class DrawOvalOp : public DrawStrokableOp {
1237public:
1238    DrawOvalOp(float left, float top, float right, float bottom, const SkPaint* paint)
1239            : DrawStrokableOp(left, top, right, bottom, paint) {}
1240
1241    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1242        return renderer.drawOval(mLocalBounds.left, mLocalBounds.top,
1243                mLocalBounds.right, mLocalBounds.bottom, getPaint(renderer));
1244    }
1245
1246    virtual void output(int level, uint32_t logFlags) const {
1247        OP_LOG("Draw Oval "RECT_STRING, RECT_ARGS(mLocalBounds));
1248    }
1249
1250    virtual const char* name() { return "DrawOval"; }
1251};
1252
1253class DrawArcOp : public DrawStrokableOp {
1254public:
1255    DrawArcOp(float left, float top, float right, float bottom,
1256            float startAngle, float sweepAngle, bool useCenter, const SkPaint* paint)
1257            : DrawStrokableOp(left, top, right, bottom, paint),
1258            mStartAngle(startAngle), mSweepAngle(sweepAngle), mUseCenter(useCenter) {}
1259
1260    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1261        return renderer.drawArc(mLocalBounds.left, mLocalBounds.top,
1262                mLocalBounds.right, mLocalBounds.bottom,
1263                mStartAngle, mSweepAngle, mUseCenter, getPaint(renderer));
1264    }
1265
1266    virtual void output(int level, uint32_t logFlags) const {
1267        OP_LOG("Draw Arc "RECT_STRING", start %f, sweep %f, useCenter %d",
1268                RECT_ARGS(mLocalBounds), mStartAngle, mSweepAngle, mUseCenter);
1269    }
1270
1271    virtual const char* name() { return "DrawArc"; }
1272
1273private:
1274    float mStartAngle;
1275    float mSweepAngle;
1276    bool mUseCenter;
1277};
1278
1279class DrawPathOp : public DrawBoundedOp {
1280public:
1281    DrawPathOp(const SkPath* path, const SkPaint* paint)
1282            : DrawBoundedOp(paint), mPath(path) {
1283        float left, top, offset;
1284        uint32_t width, height;
1285        PathCache::computePathBounds(path, paint, left, top, offset, width, height);
1286        left -= offset;
1287        top -= offset;
1288        mLocalBounds.set(left, top, left + width, top + height);
1289    }
1290
1291    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1292        return renderer.drawPath(mPath, getPaint(renderer));
1293    }
1294
1295    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo,
1296            const DeferredDisplayState& state) {
1297        const SkPaint* paint = getPaint(renderer);
1298        renderer.getCaches().pathCache.precache(mPath, paint);
1299
1300        deferInfo.batchId = DeferredDisplayList::kOpBatch_AlphaMaskTexture;
1301    }
1302
1303    virtual void output(int level, uint32_t logFlags) const {
1304        OP_LOG("Draw Path %p in "RECT_STRING, mPath, RECT_ARGS(mLocalBounds));
1305    }
1306
1307    virtual const char* name() { return "DrawPath"; }
1308
1309private:
1310    const SkPath* mPath;
1311};
1312
1313class DrawLinesOp : public DrawBoundedOp {
1314public:
1315    DrawLinesOp(const float* points, int count, const SkPaint* paint)
1316            : DrawBoundedOp(points, count, paint),
1317            mPoints(points), mCount(count) {
1318        mLocalBounds.outset(strokeWidthOutset());
1319    }
1320
1321    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1322        return renderer.drawLines(mPoints, mCount, getPaint(renderer));
1323    }
1324
1325    virtual void output(int level, uint32_t logFlags) const {
1326        OP_LOG("Draw Lines count %d", mCount);
1327    }
1328
1329    virtual const char* name() { return "DrawLines"; }
1330
1331    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo,
1332            const DeferredDisplayState& state) {
1333        deferInfo.batchId = mPaint->isAntiAlias() ?
1334                DeferredDisplayList::kOpBatch_AlphaVertices :
1335                DeferredDisplayList::kOpBatch_Vertices;
1336    }
1337
1338protected:
1339    const float* mPoints;
1340    int mCount;
1341};
1342
1343class DrawPointsOp : public DrawLinesOp {
1344public:
1345    DrawPointsOp(const float* points, int count, const SkPaint* paint)
1346            : DrawLinesOp(points, count, paint) {}
1347
1348    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1349        return renderer.drawPoints(mPoints, mCount, getPaint(renderer));
1350    }
1351
1352    virtual void output(int level, uint32_t logFlags) const {
1353        OP_LOG("Draw Points count %d", mCount);
1354    }
1355
1356    virtual const char* name() { return "DrawPoints"; }
1357};
1358
1359class DrawSomeTextOp : public DrawOp {
1360public:
1361    DrawSomeTextOp(const char* text, int bytesCount, int count, const SkPaint* paint)
1362            : DrawOp(paint), mText(text), mBytesCount(bytesCount), mCount(count) {};
1363
1364    virtual void output(int level, uint32_t logFlags) const {
1365        OP_LOG("Draw some text, %d bytes", mBytesCount);
1366    }
1367
1368    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo,
1369            const DeferredDisplayState& state) {
1370        const SkPaint* paint = getPaint(renderer);
1371        FontRenderer& fontRenderer = renderer.getCaches().fontRenderer->getFontRenderer(paint);
1372        fontRenderer.precache(paint, mText, mCount, mat4::identity());
1373
1374        deferInfo.batchId = mPaint->getColor() == 0xff000000 ?
1375                DeferredDisplayList::kOpBatch_Text :
1376                DeferredDisplayList::kOpBatch_ColorText;
1377    }
1378
1379protected:
1380    const char* mText;
1381    int mBytesCount;
1382    int mCount;
1383};
1384
1385class DrawTextOnPathOp : public DrawSomeTextOp {
1386public:
1387    DrawTextOnPathOp(const char* text, int bytesCount, int count,
1388            const SkPath* path, float hOffset, float vOffset, const SkPaint* paint)
1389            : DrawSomeTextOp(text, bytesCount, count, paint),
1390            mPath(path), mHOffset(hOffset), mVOffset(vOffset) {
1391        /* TODO: inherit from DrawBounded and init mLocalBounds */
1392    }
1393
1394    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1395        return renderer.drawTextOnPath(mText, mBytesCount, mCount, mPath,
1396                mHOffset, mVOffset, getPaint(renderer));
1397    }
1398
1399    virtual const char* name() { return "DrawTextOnPath"; }
1400
1401private:
1402    const SkPath* mPath;
1403    float mHOffset;
1404    float mVOffset;
1405};
1406
1407class DrawPosTextOp : public DrawSomeTextOp {
1408public:
1409    DrawPosTextOp(const char* text, int bytesCount, int count,
1410            const float* positions, const SkPaint* paint)
1411            : DrawSomeTextOp(text, bytesCount, count, paint), mPositions(positions) {
1412        /* TODO: inherit from DrawBounded and init mLocalBounds */
1413    }
1414
1415    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1416        return renderer.drawPosText(mText, mBytesCount, mCount, mPositions, getPaint(renderer));
1417    }
1418
1419    virtual const char* name() { return "DrawPosText"; }
1420
1421private:
1422    const float* mPositions;
1423};
1424
1425class DrawTextOp : public DrawBoundedOp {
1426public:
1427    DrawTextOp(const char* text, int bytesCount, int count, float x, float y,
1428            const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds)
1429            : DrawBoundedOp(bounds, paint), mText(text), mBytesCount(bytesCount), mCount(count),
1430            mX(x), mY(y), mPositions(positions), mTotalAdvance(totalAdvance) {
1431        memset(&mPrecacheTransform.data[0], 0xff, 16 * sizeof(float));
1432    }
1433
1434    virtual void onDefer(OpenGLRenderer& renderer, DeferInfo& deferInfo,
1435            const DeferredDisplayState& state) {
1436        const SkPaint* paint = getPaint(renderer);
1437        FontRenderer& fontRenderer = renderer.getCaches().fontRenderer->getFontRenderer(paint);
1438        const mat4& transform = renderer.findBestFontTransform(state.mMatrix);
1439        if (mPrecacheTransform != transform) {
1440            fontRenderer.precache(paint, mText, mCount, transform);
1441            mPrecacheTransform = transform;
1442        }
1443        deferInfo.batchId = mPaint->getColor() == 0xff000000 ?
1444                DeferredDisplayList::kOpBatch_Text :
1445                DeferredDisplayList::kOpBatch_ColorText;
1446
1447        deferInfo.mergeId = (mergeid_t)mPaint->getColor();
1448
1449        // don't merge decorated text - the decorations won't draw in order
1450        bool noDecorations = !(mPaint->getFlags() & (SkPaint::kUnderlineText_Flag |
1451                        SkPaint::kStrikeThruText_Flag));
1452        deferInfo.mergeable = state.mMatrix.isPureTranslate() && noDecorations &&
1453                OpenGLRenderer::getXfermodeDirect(mPaint) == SkXfermode::kSrcOver_Mode;
1454    }
1455
1456    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1457        Rect bounds;
1458        getLocalBounds(renderer.getDrawModifiers(), bounds);
1459        return renderer.drawText(mText, mBytesCount, mCount, mX, mY,
1460                mPositions, getPaint(renderer), mTotalAdvance, bounds);
1461    }
1462
1463    virtual status_t multiDraw(OpenGLRenderer& renderer, Rect& dirty,
1464            const Vector<OpStatePair>& ops, const Rect& bounds) {
1465        status_t status = DrawGlInfo::kStatusDone;
1466        for (unsigned int i = 0; i < ops.size(); i++) {
1467            const DeferredDisplayState& state = *(ops[i].state);
1468            DrawOpMode drawOpMode = (i == ops.size() - 1) ? kDrawOpMode_Flush : kDrawOpMode_Defer;
1469            renderer.restoreDisplayState(state, true); // restore all but the clip
1470
1471            DrawTextOp& op = *((DrawTextOp*)ops[i].op);
1472            // quickReject() will not occure in drawText() so we can use mLocalBounds
1473            // directly, we do not need to account for shadow by calling getLocalBounds()
1474            status |= renderer.drawText(op.mText, op.mBytesCount, op.mCount, op.mX, op.mY,
1475                    op.mPositions, op.getPaint(renderer), op.mTotalAdvance, op.mLocalBounds,
1476                    drawOpMode);
1477        }
1478        return status;
1479    }
1480
1481    virtual void output(int level, uint32_t logFlags) const {
1482        OP_LOG("Draw Text of count %d, bytes %d", mCount, mBytesCount);
1483    }
1484
1485    virtual const char* name() { return "DrawText"; }
1486
1487private:
1488    const char* mText;
1489    int mBytesCount;
1490    int mCount;
1491    float mX;
1492    float mY;
1493    const float* mPositions;
1494    float mTotalAdvance;
1495    mat4 mPrecacheTransform;
1496};
1497
1498///////////////////////////////////////////////////////////////////////////////
1499// SPECIAL DRAW OPERATIONS
1500///////////////////////////////////////////////////////////////////////////////
1501
1502class DrawFunctorOp : public DrawOp {
1503public:
1504    DrawFunctorOp(Functor* functor)
1505            : DrawOp(NULL), mFunctor(functor) {}
1506
1507    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1508        renderer.startMark("GL functor");
1509        status_t ret = renderer.callDrawGLFunction(mFunctor, dirty);
1510        renderer.endMark();
1511        return ret;
1512    }
1513
1514    virtual void output(int level, uint32_t logFlags) const {
1515        OP_LOG("Draw Functor %p", mFunctor);
1516    }
1517
1518    virtual const char* name() { return "DrawFunctor"; }
1519
1520private:
1521    Functor* mFunctor;
1522};
1523
1524class DrawDisplayListOp : public DrawBoundedOp {
1525    friend class DisplayList; // grant DisplayList access to info of child
1526public:
1527    DrawDisplayListOp(DisplayList* displayList, int flags, const mat4& transformFromParent)
1528            : DrawBoundedOp(0, 0, displayList->getWidth(), displayList->getHeight(), 0),
1529            mDisplayList(displayList), mFlags(flags), mTransformFromParent(transformFromParent) {}
1530
1531    virtual void defer(DeferStateStruct& deferStruct, int saveCount, int level,
1532            bool useQuickReject) {
1533        if (mDisplayList && mDisplayList->isRenderable() && !mSkipInOrderDraw) {
1534            mDisplayList->defer(deferStruct, level + 1);
1535        }
1536    }
1537    virtual void replay(ReplayStateStruct& replayStruct, int saveCount, int level,
1538            bool useQuickReject) {
1539        if (mDisplayList && mDisplayList->isRenderable() && !mSkipInOrderDraw) {
1540            mDisplayList->replay(replayStruct, level + 1);
1541        }
1542    }
1543
1544    // NOT USED since replay() is overridden
1545    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1546        return DrawGlInfo::kStatusDone;
1547    }
1548
1549    virtual void output(int level, uint32_t logFlags) const {
1550        OP_LOG("Draw Display List %p, flags %#x", mDisplayList, mFlags);
1551        if (mDisplayList && (logFlags & kOpLogFlag_Recurse)) {
1552            mDisplayList->output(level + 1);
1553        }
1554    }
1555
1556    virtual const char* name() { return "DrawDisplayList"; }
1557
1558private:
1559    DisplayList* mDisplayList;
1560    const int mFlags;
1561
1562    ///////////////////////////
1563    // Properties below are used by DisplayList::computeOrderingImpl() and iterate()
1564    ///////////////////////////
1565    /**
1566     * Records transform vs parent, used for computing total transform without rerunning DL contents
1567     */
1568    const mat4 mTransformFromParent;
1569
1570    /**
1571     * Holds the transformation between the 3d root ViewGroup and this DisplayList drawing
1572     * instance. Represents any translations / transformations done within the drawing of the 3d
1573     * root ViewGroup's draw, before the draw of the View represented by this DisplayList draw
1574     * instance.
1575     *
1576     * Note: doesn't include any transformation recorded within the DisplayList and its properties.
1577     */
1578    mat4 mTransformFrom3dRoot;
1579    bool mSkipInOrderDraw;
1580};
1581
1582/**
1583 * Not a canvas operation, used only by 3d / z ordering logic in DisplayList::iterate()
1584 */
1585class DrawShadowOp : public DrawOp {
1586public:
1587    DrawShadowOp(const mat4& casterTransform, float casterAlpha, float width, float height)
1588            : DrawOp(NULL), mCasterTransform(casterTransform), mCasterAlpha(casterAlpha),
1589            mWidth(width), mHeight(height) {}
1590
1591    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1592        return renderer.drawShadow(mCasterTransform, mCasterAlpha, mWidth, mHeight);
1593    }
1594
1595    virtual void output(int level, uint32_t logFlags) const {
1596        OP_LOG("DrawShadow of width %.2f, height %.2f", mWidth, mHeight);
1597    }
1598
1599    virtual const char* name() { return "DrawShadow"; }
1600
1601private:
1602    const mat4 mCasterTransform;
1603    const float mCasterAlpha;
1604    const float mWidth;
1605    const float mHeight;
1606};
1607
1608class DrawLayerOp : public DrawOp {
1609public:
1610    DrawLayerOp(Layer* layer, float x, float y)
1611            : DrawOp(NULL), mLayer(layer), mX(x), mY(y) {}
1612
1613    virtual status_t applyDraw(OpenGLRenderer& renderer, Rect& dirty) {
1614        return renderer.drawLayer(mLayer, mX, mY);
1615    }
1616
1617    virtual void output(int level, uint32_t logFlags) const {
1618        OP_LOG("Draw Layer %p at %f %f", mLayer, mX, mY);
1619    }
1620
1621    virtual const char* name() { return "DrawLayer"; }
1622
1623private:
1624    Layer* mLayer;
1625    float mX;
1626    float mY;
1627};
1628
1629}; // namespace uirenderer
1630}; // namespace android
1631
1632#endif // ANDROID_HWUI_DISPLAY_OPERATION_H
1633