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