OpenGLRenderer.cpp revision 3a1bffa835f279628e50385af3c85789bc737f64
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "OpenGLRenderer"
18
19#include <stdlib.h>
20#include <stdint.h>
21#include <sys/types.h>
22
23#include <SkCanvas.h>
24#include <SkTypeface.h>
25
26#include <utils/Log.h>
27#include <utils/StopWatch.h>
28
29#include <private/hwui/DrawGlInfo.h>
30
31#include <ui/Rect.h>
32
33#include "OpenGLRenderer.h"
34#include "DeferredDisplayList.h"
35#include "DisplayListRenderer.h"
36#include "Fence.h"
37#include "PathTessellator.h"
38#include "Properties.h"
39#include "Vector.h"
40
41namespace android {
42namespace uirenderer {
43
44///////////////////////////////////////////////////////////////////////////////
45// Defines
46///////////////////////////////////////////////////////////////////////////////
47
48#define RAD_TO_DEG (180.0f / 3.14159265f)
49#define MIN_ANGLE 0.001f
50
51#define ALPHA_THRESHOLD 0
52
53#define FILTER(paint) (!paint || paint->isFilterBitmap() ? GL_LINEAR : GL_NEAREST)
54
55///////////////////////////////////////////////////////////////////////////////
56// Globals
57///////////////////////////////////////////////////////////////////////////////
58
59/**
60 * Structure mapping Skia xfermodes to OpenGL blending factors.
61 */
62struct Blender {
63    SkXfermode::Mode mode;
64    GLenum src;
65    GLenum dst;
66}; // struct Blender
67
68// In this array, the index of each Blender equals the value of the first
69// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
70static const Blender gBlends[] = {
71    { SkXfermode::kClear_Mode,    GL_ZERO,                GL_ONE_MINUS_SRC_ALPHA },
72    { SkXfermode::kSrc_Mode,      GL_ONE,                 GL_ZERO },
73    { SkXfermode::kDst_Mode,      GL_ZERO,                GL_ONE },
74    { SkXfermode::kSrcOver_Mode,  GL_ONE,                 GL_ONE_MINUS_SRC_ALPHA },
75    { SkXfermode::kDstOver_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_ONE },
76    { SkXfermode::kSrcIn_Mode,    GL_DST_ALPHA,           GL_ZERO },
77    { SkXfermode::kDstIn_Mode,    GL_ZERO,                GL_SRC_ALPHA },
78    { SkXfermode::kSrcOut_Mode,   GL_ONE_MINUS_DST_ALPHA, GL_ZERO },
79    { SkXfermode::kDstOut_Mode,   GL_ZERO,                GL_ONE_MINUS_SRC_ALPHA },
80    { SkXfermode::kSrcATop_Mode,  GL_DST_ALPHA,           GL_ONE_MINUS_SRC_ALPHA },
81    { SkXfermode::kDstATop_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA },
82    { SkXfermode::kXor_Mode,      GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA },
83    { SkXfermode::kPlus_Mode,     GL_ONE,                 GL_ONE },
84    { SkXfermode::kModulate_Mode, GL_ZERO,                GL_SRC_COLOR },
85    { SkXfermode::kScreen_Mode,   GL_ONE,                 GL_ONE_MINUS_SRC_COLOR }
86};
87
88// This array contains the swapped version of each SkXfermode. For instance
89// this array's SrcOver blending mode is actually DstOver. You can refer to
90// createLayer() for more information on the purpose of this array.
91static const Blender gBlendsSwap[] = {
92    { SkXfermode::kClear_Mode,    GL_ONE_MINUS_DST_ALPHA, GL_ZERO },
93    { SkXfermode::kSrc_Mode,      GL_ZERO,                GL_ONE },
94    { SkXfermode::kDst_Mode,      GL_ONE,                 GL_ZERO },
95    { SkXfermode::kSrcOver_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_ONE },
96    { SkXfermode::kDstOver_Mode,  GL_ONE,                 GL_ONE_MINUS_SRC_ALPHA },
97    { SkXfermode::kSrcIn_Mode,    GL_ZERO,                GL_SRC_ALPHA },
98    { SkXfermode::kDstIn_Mode,    GL_DST_ALPHA,           GL_ZERO },
99    { SkXfermode::kSrcOut_Mode,   GL_ZERO,                GL_ONE_MINUS_SRC_ALPHA },
100    { SkXfermode::kDstOut_Mode,   GL_ONE_MINUS_DST_ALPHA, GL_ZERO },
101    { SkXfermode::kSrcATop_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA },
102    { SkXfermode::kDstATop_Mode,  GL_DST_ALPHA,           GL_ONE_MINUS_SRC_ALPHA },
103    { SkXfermode::kXor_Mode,      GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA },
104    { SkXfermode::kPlus_Mode,     GL_ONE,                 GL_ONE },
105    { SkXfermode::kModulate_Mode, GL_DST_COLOR,           GL_ZERO },
106    { SkXfermode::kScreen_Mode,   GL_ONE_MINUS_DST_COLOR, GL_ONE }
107};
108
109///////////////////////////////////////////////////////////////////////////////
110// Functions
111///////////////////////////////////////////////////////////////////////////////
112
113template<typename T>
114static inline T min(T a, T b) {
115    return a < b ? a : b;
116}
117
118///////////////////////////////////////////////////////////////////////////////
119// Constructors/destructor
120///////////////////////////////////////////////////////////////////////////////
121
122OpenGLRenderer::OpenGLRenderer():
123        mCaches(Caches::getInstance()), mExtensions(Extensions::getInstance()) {
124    // *set* draw modifiers to be 0
125    memset(&mDrawModifiers, 0, sizeof(mDrawModifiers));
126    mDrawModifiers.mOverrideLayerAlpha = 1.0f;
127
128    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
129
130    mFirstSnapshot = new Snapshot;
131    mFrameStarted = false;
132    mCountOverdraw = false;
133
134    mScissorOptimizationDisabled = false;
135}
136
137OpenGLRenderer::~OpenGLRenderer() {
138    // The context has already been destroyed at this point, do not call
139    // GL APIs. All GL state should be kept in Caches.h
140}
141
142void OpenGLRenderer::initProperties() {
143    char property[PROPERTY_VALUE_MAX];
144    if (property_get(PROPERTY_DISABLE_SCISSOR_OPTIMIZATION, property, "false")) {
145        mScissorOptimizationDisabled = !strcasecmp(property, "true");
146        INIT_LOGD("  Scissor optimization %s",
147                mScissorOptimizationDisabled ? "disabled" : "enabled");
148    } else {
149        INIT_LOGD("  Scissor optimization enabled");
150    }
151}
152
153///////////////////////////////////////////////////////////////////////////////
154// Setup
155///////////////////////////////////////////////////////////////////////////////
156
157void OpenGLRenderer::setName(const char* name) {
158    if (name) {
159        mName.setTo(name);
160    } else {
161        mName.clear();
162    }
163}
164
165const char* OpenGLRenderer::getName() const {
166    return mName.string();
167}
168
169bool OpenGLRenderer::isDeferred() {
170    return false;
171}
172
173void OpenGLRenderer::setViewport(int width, int height) {
174    initViewport(width, height);
175
176    glDisable(GL_DITHER);
177    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
178
179    glEnableVertexAttribArray(Program::kBindingPosition);
180}
181
182void OpenGLRenderer::initViewport(int width, int height) {
183    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
184
185    mWidth = width;
186    mHeight = height;
187
188    mFirstSnapshot->height = height;
189    mFirstSnapshot->viewport.set(0, 0, width, height);
190}
191
192void OpenGLRenderer::setupFrameState(float left, float top,
193        float right, float bottom, bool opaque) {
194    mCaches.clearGarbage();
195
196    mOpaque = opaque;
197    mSnapshot = new Snapshot(mFirstSnapshot,
198            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
199    mSnapshot->fbo = getTargetFbo();
200    mSaveCount = 1;
201
202    mSnapshot->setClip(left, top, right, bottom);
203    mTilingClip.set(left, top, right, bottom);
204}
205
206status_t OpenGLRenderer::startFrame() {
207    if (mFrameStarted) return DrawGlInfo::kStatusDone;
208    mFrameStarted = true;
209
210    mDirtyClip = true;
211
212    discardFramebuffer(mTilingClip.left, mTilingClip.top, mTilingClip.right, mTilingClip.bottom);
213
214    glViewport(0, 0, mWidth, mHeight);
215
216    // Functors break the tiling extension in pretty spectacular ways
217    // This ensures we don't use tiling when a functor is going to be
218    // invoked during the frame
219    mSuppressTiling = mCaches.hasRegisteredFunctors();
220
221    startTiling(mSnapshot, true);
222
223    debugOverdraw(true, true);
224
225    return clear(mTilingClip.left, mTilingClip.top,
226            mTilingClip.right, mTilingClip.bottom, mOpaque);
227}
228
229status_t OpenGLRenderer::prepare(bool opaque) {
230    return prepareDirty(0.0f, 0.0f, mWidth, mHeight, opaque);
231}
232
233status_t OpenGLRenderer::prepareDirty(float left, float top,
234        float right, float bottom, bool opaque) {
235
236    setupFrameState(left, top, right, bottom, opaque);
237
238    // Layer renderers will start the frame immediately
239    // The framebuffer renderer will first defer the display list
240    // for each layer and wait until the first drawing command
241    // to start the frame
242    if (mSnapshot->fbo == 0) {
243        syncState();
244        updateLayers();
245    } else {
246        return startFrame();
247    }
248
249    return DrawGlInfo::kStatusDone;
250}
251
252void OpenGLRenderer::discardFramebuffer(float left, float top, float right, float bottom) {
253    // If we know that we are going to redraw the entire framebuffer,
254    // perform a discard to let the driver know we don't need to preserve
255    // the back buffer for this frame.
256    if (mExtensions.hasDiscardFramebuffer() &&
257            left <= 0.0f && top <= 0.0f && right >= mWidth && bottom >= mHeight) {
258        const bool isFbo = getTargetFbo() == 0;
259        const GLenum attachments[] = {
260                isFbo ? (const GLenum) GL_COLOR_EXT : (const GLenum) GL_COLOR_ATTACHMENT0,
261                isFbo ? (const GLenum) GL_STENCIL_EXT : (const GLenum) GL_STENCIL_ATTACHMENT };
262        glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments);
263    }
264}
265
266status_t OpenGLRenderer::clear(float left, float top, float right, float bottom, bool opaque) {
267    if (!opaque || mCountOverdraw) {
268        mCaches.enableScissor();
269        mCaches.setScissor(left, mSnapshot->height - bottom, right - left, bottom - top);
270        glClear(GL_COLOR_BUFFER_BIT);
271        return DrawGlInfo::kStatusDrew;
272    }
273
274    mCaches.resetScissor();
275    return DrawGlInfo::kStatusDone;
276}
277
278void OpenGLRenderer::syncState() {
279    if (mCaches.blend) {
280        glEnable(GL_BLEND);
281    } else {
282        glDisable(GL_BLEND);
283    }
284}
285
286void OpenGLRenderer::startTiling(const sp<Snapshot>& s, bool opaque) {
287    if (!mSuppressTiling) {
288        Rect* clip = &mTilingClip;
289        if (s->flags & Snapshot::kFlagFboTarget) {
290            clip = &(s->layer->clipRect);
291        }
292
293        startTiling(*clip, s->height, opaque);
294    }
295}
296
297void OpenGLRenderer::startTiling(const Rect& clip, int windowHeight, bool opaque) {
298    if (!mSuppressTiling) {
299        mCaches.startTiling(clip.left, windowHeight - clip.bottom,
300                clip.right - clip.left, clip.bottom - clip.top, opaque);
301    }
302}
303
304void OpenGLRenderer::endTiling() {
305    if (!mSuppressTiling) mCaches.endTiling();
306}
307
308void OpenGLRenderer::finish() {
309    renderOverdraw();
310    endTiling();
311
312    // When finish() is invoked on FBO 0 we've reached the end
313    // of the current frame
314    if (getTargetFbo() == 0) {
315        mCaches.pathCache.trim();
316    }
317
318    if (!suppressErrorChecks()) {
319#if DEBUG_OPENGL
320        GLenum status = GL_NO_ERROR;
321        while ((status = glGetError()) != GL_NO_ERROR) {
322            ALOGD("GL error from OpenGLRenderer: 0x%x", status);
323            switch (status) {
324                case GL_INVALID_ENUM:
325                    ALOGE("  GL_INVALID_ENUM");
326                    break;
327                case GL_INVALID_VALUE:
328                    ALOGE("  GL_INVALID_VALUE");
329                    break;
330                case GL_INVALID_OPERATION:
331                    ALOGE("  GL_INVALID_OPERATION");
332                    break;
333                case GL_OUT_OF_MEMORY:
334                    ALOGE("  Out of memory!");
335                    break;
336            }
337        }
338#endif
339
340#if DEBUG_MEMORY_USAGE
341        mCaches.dumpMemoryUsage();
342#else
343        if (mCaches.getDebugLevel() & kDebugMemory) {
344            mCaches.dumpMemoryUsage();
345        }
346#endif
347    }
348
349    if (mCountOverdraw) {
350        countOverdraw();
351    }
352
353    mFrameStarted = false;
354}
355
356void OpenGLRenderer::interrupt() {
357    if (mCaches.currentProgram) {
358        if (mCaches.currentProgram->isInUse()) {
359            mCaches.currentProgram->remove();
360            mCaches.currentProgram = NULL;
361        }
362    }
363    mCaches.resetActiveTexture();
364    mCaches.unbindMeshBuffer();
365    mCaches.unbindIndicesBuffer();
366    mCaches.resetVertexPointers();
367    mCaches.disableTexCoordsVertexArray();
368    debugOverdraw(false, false);
369}
370
371void OpenGLRenderer::resume() {
372    sp<Snapshot> snapshot = (mSnapshot != NULL) ? mSnapshot : mFirstSnapshot;
373    glViewport(0, 0, snapshot->viewport.getWidth(), snapshot->viewport.getHeight());
374    glBindFramebuffer(GL_FRAMEBUFFER, snapshot->fbo);
375    debugOverdraw(true, false);
376
377    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
378
379    mCaches.scissorEnabled = glIsEnabled(GL_SCISSOR_TEST);
380    mCaches.enableScissor();
381    mCaches.resetScissor();
382    dirtyClip();
383
384    mCaches.activeTexture(0);
385    mCaches.resetBoundTextures();
386
387    mCaches.blend = true;
388    glEnable(GL_BLEND);
389    glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
390    glBlendEquation(GL_FUNC_ADD);
391}
392
393void OpenGLRenderer::resumeAfterLayer() {
394    sp<Snapshot> snapshot = (mSnapshot != NULL) ? mSnapshot : mFirstSnapshot;
395    glViewport(0, 0, snapshot->viewport.getWidth(), snapshot->viewport.getHeight());
396    glBindFramebuffer(GL_FRAMEBUFFER, snapshot->fbo);
397    debugOverdraw(true, false);
398
399    mCaches.resetScissor();
400    dirtyClip();
401}
402
403void OpenGLRenderer::detachFunctor(Functor* functor) {
404    mFunctors.remove(functor);
405}
406
407void OpenGLRenderer::attachFunctor(Functor* functor) {
408    mFunctors.add(functor);
409}
410
411status_t OpenGLRenderer::invokeFunctors(Rect& dirty) {
412    status_t result = DrawGlInfo::kStatusDone;
413    size_t count = mFunctors.size();
414
415    if (count > 0) {
416        interrupt();
417        SortedVector<Functor*> functors(mFunctors);
418        mFunctors.clear();
419
420        DrawGlInfo info;
421        info.clipLeft = 0;
422        info.clipTop = 0;
423        info.clipRight = 0;
424        info.clipBottom = 0;
425        info.isLayer = false;
426        info.width = 0;
427        info.height = 0;
428        memset(info.transform, 0, sizeof(float) * 16);
429
430        for (size_t i = 0; i < count; i++) {
431            Functor* f = functors.itemAt(i);
432            result |= (*f)(DrawGlInfo::kModeProcess, &info);
433
434            if (result & DrawGlInfo::kStatusDraw) {
435                Rect localDirty(info.dirtyLeft, info.dirtyTop, info.dirtyRight, info.dirtyBottom);
436                dirty.unionWith(localDirty);
437            }
438
439            if (result & DrawGlInfo::kStatusInvoke) {
440                mFunctors.add(f);
441            }
442        }
443        resume();
444    }
445
446    return result;
447}
448
449status_t OpenGLRenderer::callDrawGLFunction(Functor* functor, Rect& dirty) {
450    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
451
452    detachFunctor(functor);
453
454
455    Rect clip(*mSnapshot->clipRect);
456    clip.snapToPixelBoundaries();
457
458    // Since we don't know what the functor will draw, let's dirty
459    // tne entire clip region
460    if (hasLayer()) {
461        dirtyLayerUnchecked(clip, getRegion());
462    }
463
464    DrawGlInfo info;
465    info.clipLeft = clip.left;
466    info.clipTop = clip.top;
467    info.clipRight = clip.right;
468    info.clipBottom = clip.bottom;
469    info.isLayer = hasLayer();
470    info.width = getSnapshot()->viewport.getWidth();
471    info.height = getSnapshot()->height;
472    getSnapshot()->transform->copyTo(&info.transform[0]);
473
474    bool dirtyClip = mDirtyClip;
475    // setup GL state for functor
476    if (mDirtyClip) {
477        setStencilFromClip(); // can issue draws, so must precede enableScissor()/interrupt()
478    }
479    if (mCaches.enableScissor() || dirtyClip) {
480        setScissorFromClip();
481    }
482    interrupt();
483
484    // call functor immediately after GL state setup
485    status_t result = (*functor)(DrawGlInfo::kModeDraw, &info);
486
487    if (result != DrawGlInfo::kStatusDone) {
488        Rect localDirty(info.dirtyLeft, info.dirtyTop, info.dirtyRight, info.dirtyBottom);
489        dirty.unionWith(localDirty);
490
491        if (result & DrawGlInfo::kStatusInvoke) {
492            mFunctors.add(functor);
493        }
494    }
495
496    resume();
497    return result | DrawGlInfo::kStatusDrew;
498}
499
500///////////////////////////////////////////////////////////////////////////////
501// Debug
502///////////////////////////////////////////////////////////////////////////////
503
504void OpenGLRenderer::eventMark(const char* name) const {
505    mCaches.eventMark(0, name);
506}
507
508void OpenGLRenderer::startMark(const char* name) const {
509    mCaches.startMark(0, name);
510}
511
512void OpenGLRenderer::endMark() const {
513    mCaches.endMark();
514}
515
516void OpenGLRenderer::debugOverdraw(bool enable, bool clear) {
517    if (mCaches.debugOverdraw && getTargetFbo() == 0) {
518        if (clear) {
519            mCaches.disableScissor();
520            mCaches.stencil.clear();
521        }
522        if (enable) {
523            mCaches.stencil.enableDebugWrite();
524        } else {
525            mCaches.stencil.disable();
526        }
527    }
528}
529
530void OpenGLRenderer::renderOverdraw() {
531    if (mCaches.debugOverdraw && getTargetFbo() == 0) {
532        const Rect* clip = &mTilingClip;
533
534        mCaches.enableScissor();
535        mCaches.setScissor(clip->left, mFirstSnapshot->height - clip->bottom,
536                clip->right - clip->left, clip->bottom - clip->top);
537
538        // 1x overdraw
539        mCaches.stencil.enableDebugTest(2);
540        drawColor(mCaches.getOverdrawColor(1), SkXfermode::kSrcOver_Mode);
541
542        // 2x overdraw
543        mCaches.stencil.enableDebugTest(3);
544        drawColor(mCaches.getOverdrawColor(2), SkXfermode::kSrcOver_Mode);
545
546        // 3x overdraw
547        mCaches.stencil.enableDebugTest(4);
548        drawColor(mCaches.getOverdrawColor(3), SkXfermode::kSrcOver_Mode);
549
550        // 4x overdraw and higher
551        mCaches.stencil.enableDebugTest(4, true);
552        drawColor(mCaches.getOverdrawColor(4), SkXfermode::kSrcOver_Mode);
553
554        mCaches.stencil.disable();
555    }
556}
557
558void OpenGLRenderer::countOverdraw() {
559    size_t count = mWidth * mHeight;
560    uint32_t* buffer = new uint32_t[count];
561    glReadPixels(0, 0, mWidth, mHeight, GL_RGBA, GL_UNSIGNED_BYTE, &buffer[0]);
562
563    size_t total = 0;
564    for (size_t i = 0; i < count; i++) {
565        total += buffer[i] & 0xff;
566    }
567
568    mOverdraw = total / float(count);
569
570    delete[] buffer;
571}
572
573///////////////////////////////////////////////////////////////////////////////
574// Layers
575///////////////////////////////////////////////////////////////////////////////
576
577bool OpenGLRenderer::updateLayer(Layer* layer, bool inFrame) {
578    if (layer->deferredUpdateScheduled && layer->renderer &&
579            layer->displayList && layer->displayList->isRenderable()) {
580        ATRACE_CALL();
581
582        Rect& dirty = layer->dirtyRect;
583
584        if (inFrame) {
585            endTiling();
586            debugOverdraw(false, false);
587        }
588
589        if (CC_UNLIKELY(inFrame || mCaches.drawDeferDisabled)) {
590            layer->render();
591        } else {
592            layer->defer();
593        }
594
595        if (inFrame) {
596            resumeAfterLayer();
597            startTiling(mSnapshot);
598        }
599
600        layer->debugDrawUpdate = mCaches.debugLayersUpdates;
601        layer->hasDrawnSinceUpdate = false;
602
603        return true;
604    }
605
606    return false;
607}
608
609void OpenGLRenderer::updateLayers() {
610    // If draw deferring is enabled this method will simply defer
611    // the display list of each individual layer. The layers remain
612    // in the layer updates list which will be cleared by flushLayers().
613    int count = mLayerUpdates.size();
614    if (count > 0) {
615        if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
616            startMark("Layer Updates");
617        } else {
618            startMark("Defer Layer Updates");
619        }
620
621        // Note: it is very important to update the layers in order
622        for (int i = 0; i < count; i++) {
623            Layer* layer = mLayerUpdates.itemAt(i);
624            updateLayer(layer, false);
625            if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
626                mCaches.resourceCache.decrementRefcount(layer);
627            }
628        }
629
630        if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
631            mLayerUpdates.clear();
632            glBindFramebuffer(GL_FRAMEBUFFER, getTargetFbo());
633        }
634        endMark();
635    }
636}
637
638void OpenGLRenderer::flushLayers() {
639    int count = mLayerUpdates.size();
640    if (count > 0) {
641        startMark("Apply Layer Updates");
642        char layerName[12];
643
644        // Note: it is very important to update the layers in order
645        for (int i = 0; i < count; i++) {
646            sprintf(layerName, "Layer #%d", i);
647            startMark(layerName);
648
649            ATRACE_BEGIN("flushLayer");
650            Layer* layer = mLayerUpdates.itemAt(i);
651            layer->flush();
652            ATRACE_END();
653
654            mCaches.resourceCache.decrementRefcount(layer);
655
656            endMark();
657        }
658
659        mLayerUpdates.clear();
660        glBindFramebuffer(GL_FRAMEBUFFER, getTargetFbo());
661
662        endMark();
663    }
664}
665
666void OpenGLRenderer::pushLayerUpdate(Layer* layer) {
667    if (layer) {
668        // Make sure we don't introduce duplicates.
669        // SortedVector would do this automatically but we need to respect
670        // the insertion order. The linear search is not an issue since
671        // this list is usually very short (typically one item, at most a few)
672        for (int i = mLayerUpdates.size() - 1; i >= 0; i--) {
673            if (mLayerUpdates.itemAt(i) == layer) {
674                return;
675            }
676        }
677        mLayerUpdates.push_back(layer);
678        mCaches.resourceCache.incrementRefcount(layer);
679    }
680}
681
682void OpenGLRenderer::cancelLayerUpdate(Layer* layer) {
683    if (layer) {
684        for (int i = mLayerUpdates.size() - 1; i >= 0; i--) {
685            if (mLayerUpdates.itemAt(i) == layer) {
686                mLayerUpdates.removeAt(i);
687                mCaches.resourceCache.decrementRefcount(layer);
688                break;
689            }
690        }
691    }
692}
693
694void OpenGLRenderer::clearLayerUpdates() {
695    size_t count = mLayerUpdates.size();
696    if (count > 0) {
697        mCaches.resourceCache.lock();
698        for (size_t i = 0; i < count; i++) {
699            mCaches.resourceCache.decrementRefcountLocked(mLayerUpdates.itemAt(i));
700        }
701        mCaches.resourceCache.unlock();
702        mLayerUpdates.clear();
703    }
704}
705
706void OpenGLRenderer::flushLayerUpdates() {
707    syncState();
708    updateLayers();
709    flushLayers();
710    // Wait for all the layer updates to be executed
711    AutoFence fence;
712}
713
714///////////////////////////////////////////////////////////////////////////////
715// State management
716///////////////////////////////////////////////////////////////////////////////
717
718int OpenGLRenderer::getSaveCount() const {
719    return mSaveCount;
720}
721
722int OpenGLRenderer::save(int flags) {
723    return saveSnapshot(flags);
724}
725
726void OpenGLRenderer::restore() {
727    if (mSaveCount > 1) {
728        restoreSnapshot();
729    }
730}
731
732void OpenGLRenderer::restoreToCount(int saveCount) {
733    if (saveCount < 1) saveCount = 1;
734
735    while (mSaveCount > saveCount) {
736        restoreSnapshot();
737    }
738}
739
740int OpenGLRenderer::saveSnapshot(int flags) {
741    mSnapshot = new Snapshot(mSnapshot, flags);
742    return mSaveCount++;
743}
744
745bool OpenGLRenderer::restoreSnapshot() {
746    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
747    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
748    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
749
750    sp<Snapshot> current = mSnapshot;
751    sp<Snapshot> previous = mSnapshot->previous;
752
753    if (restoreOrtho) {
754        Rect& r = previous->viewport;
755        glViewport(r.left, r.top, r.right, r.bottom);
756        mOrthoMatrix.load(current->orthoMatrix);
757    }
758
759    mSaveCount--;
760    mSnapshot = previous;
761
762    if (restoreClip) {
763        dirtyClip();
764    }
765
766    if (restoreLayer) {
767        endMark(); // Savelayer
768        startMark("ComposeLayer");
769        composeLayer(current, previous);
770        endMark();
771    }
772
773    return restoreClip;
774}
775
776///////////////////////////////////////////////////////////////////////////////
777// Layers
778///////////////////////////////////////////////////////////////////////////////
779
780int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
781        int alpha, SkXfermode::Mode mode, int flags) {
782    const GLuint previousFbo = mSnapshot->fbo;
783    const int count = saveSnapshot(flags);
784
785    if (!mSnapshot->isIgnored()) {
786        createLayer(left, top, right, bottom, alpha, mode, flags, previousFbo);
787    }
788
789    return count;
790}
791
792void OpenGLRenderer::calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer) {
793    const Rect untransformedBounds(bounds);
794
795    currentTransform().mapRect(bounds);
796
797    // Layers only make sense if they are in the framebuffer's bounds
798    if (bounds.intersect(*mSnapshot->clipRect)) {
799        // We cannot work with sub-pixels in this case
800        bounds.snapToPixelBoundaries();
801
802        // When the layer is not an FBO, we may use glCopyTexImage so we
803        // need to make sure the layer does not extend outside the bounds
804        // of the framebuffer
805        if (!bounds.intersect(mSnapshot->previous->viewport)) {
806            bounds.setEmpty();
807        } else if (fboLayer) {
808            clip.set(bounds);
809            mat4 inverse;
810            inverse.loadInverse(currentTransform());
811            inverse.mapRect(clip);
812            clip.snapToPixelBoundaries();
813            if (clip.intersect(untransformedBounds)) {
814                clip.translate(-untransformedBounds.left, -untransformedBounds.top);
815                bounds.set(untransformedBounds);
816            } else {
817                clip.setEmpty();
818            }
819        }
820    } else {
821        bounds.setEmpty();
822    }
823}
824
825void OpenGLRenderer::updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip,
826        bool fboLayer, int alpha) {
827    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
828            bounds.getHeight() > mCaches.maxTextureSize ||
829            (fboLayer && clip.isEmpty())) {
830        mSnapshot->empty = fboLayer;
831    } else {
832        mSnapshot->invisible = mSnapshot->invisible || (alpha <= ALPHA_THRESHOLD && fboLayer);
833    }
834}
835
836int OpenGLRenderer::saveLayerDeferred(float left, float top, float right, float bottom,
837        int alpha, SkXfermode::Mode mode, int flags) {
838    const GLuint previousFbo = mSnapshot->fbo;
839    const int count = saveSnapshot(flags);
840
841    if (!mSnapshot->isIgnored() && (flags & SkCanvas::kClipToLayer_SaveFlag)) {
842        // initialize the snapshot as though it almost represents an FBO layer so deferred draw
843        // operations will be able to store and restore the current clip and transform info, and
844        // quick rejection will be correct (for display lists)
845
846        Rect bounds(left, top, right, bottom);
847        Rect clip;
848        calculateLayerBoundsAndClip(bounds, clip, true);
849        updateSnapshotIgnoreForLayer(bounds, clip, true, alpha);
850
851        if (!mSnapshot->isIgnored()) {
852            mSnapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
853            mSnapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
854            mSnapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
855        }
856    }
857
858    return count;
859}
860
861
862/**
863 * Layers are viewed by Skia are slightly different than layers in image editing
864 * programs (for instance.) When a layer is created, previously created layers
865 * and the frame buffer still receive every drawing command. For instance, if a
866 * layer is created and a shape intersecting the bounds of the layers and the
867 * framebuffer is draw, the shape will be drawn on both (unless the layer was
868 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
869 *
870 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
871 * texture. Unfortunately, this is inefficient as it requires every primitive to
872 * be drawn n + 1 times, where n is the number of active layers. In practice this
873 * means, for every primitive:
874 *   - Switch active frame buffer
875 *   - Change viewport, clip and projection matrix
876 *   - Issue the drawing
877 *
878 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
879 * To avoid this, layers are implemented in a different way here, at least in the
880 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
881 * is set. When this flag is set we can redirect all drawing operations into a
882 * single FBO.
883 *
884 * This implementation relies on the frame buffer being at least RGBA 8888. When
885 * a layer is created, only a texture is created, not an FBO. The content of the
886 * frame buffer contained within the layer's bounds is copied into this texture
887 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
888 * buffer and drawing continues as normal. This technique therefore treats the
889 * frame buffer as a scratch buffer for the layers.
890 *
891 * To compose the layers back onto the frame buffer, each layer texture
892 * (containing the original frame buffer data) is drawn as a simple quad over
893 * the frame buffer. The trick is that the quad is set as the composition
894 * destination in the blending equation, and the frame buffer becomes the source
895 * of the composition.
896 *
897 * Drawing layers with an alpha value requires an extra step before composition.
898 * An empty quad is drawn over the layer's region in the frame buffer. This quad
899 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
900 * quad is used to multiply the colors in the frame buffer. This is achieved by
901 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
902 * GL_ZERO, GL_SRC_ALPHA.
903 *
904 * Because glCopyTexImage2D() can be slow, an alternative implementation might
905 * be use to draw a single clipped layer. The implementation described above
906 * is correct in every case.
907 *
908 * (1) The frame buffer is actually not cleared right away. To allow the GPU
909 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
910 *     buffer is left untouched until the first drawing operation. Only when
911 *     something actually gets drawn are the layers regions cleared.
912 */
913bool OpenGLRenderer::createLayer(float left, float top, float right, float bottom,
914        int alpha, SkXfermode::Mode mode, int flags, GLuint previousFbo) {
915    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
916    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
917
918    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
919
920    // Window coordinates of the layer
921    Rect clip;
922    Rect bounds(left, top, right, bottom);
923    calculateLayerBoundsAndClip(bounds, clip, fboLayer);
924    updateSnapshotIgnoreForLayer(bounds, clip, fboLayer, alpha);
925
926    // Bail out if we won't draw in this snapshot
927    if (mSnapshot->isIgnored()) {
928        return false;
929    }
930
931    mCaches.activeTexture(0);
932    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
933    if (!layer) {
934        return false;
935    }
936
937    layer->setAlpha(alpha, mode);
938    layer->layer.set(bounds);
939    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->getHeight()),
940            bounds.getWidth() / float(layer->getWidth()), 0.0f);
941    layer->setColorFilter(mDrawModifiers.mColorFilter);
942    layer->setBlend(true);
943    layer->setDirty(false);
944
945    // Save the layer in the snapshot
946    mSnapshot->flags |= Snapshot::kFlagIsLayer;
947    mSnapshot->layer = layer;
948
949    startMark("SaveLayer");
950    if (fboLayer) {
951        return createFboLayer(layer, bounds, clip, previousFbo);
952    } else {
953        // Copy the framebuffer into the layer
954        layer->bindTexture();
955        if (!bounds.isEmpty()) {
956            if (layer->isEmpty()) {
957                // Workaround for some GL drivers. When reading pixels lying outside
958                // of the window we should get undefined values for those pixels.
959                // Unfortunately some drivers will turn the entire target texture black
960                // when reading outside of the window.
961                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->getWidth(), layer->getHeight(),
962                        0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
963                layer->setEmpty(false);
964            }
965
966            glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left,
967                    mSnapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight());
968
969            // Enqueue the buffer coordinates to clear the corresponding region later
970            mLayers.push(new Rect(bounds));
971        }
972    }
973
974    return true;
975}
976
977bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, Rect& clip, GLuint previousFbo) {
978    layer->clipRect.set(clip);
979    layer->setFbo(mCaches.fboCache.get());
980
981    mSnapshot->region = &mSnapshot->layer->region;
982    mSnapshot->flags |= Snapshot::kFlagFboTarget | Snapshot::kFlagIsFboLayer |
983            Snapshot::kFlagDirtyOrtho;
984    mSnapshot->fbo = layer->getFbo();
985    mSnapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
986    mSnapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
987    mSnapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
988    mSnapshot->height = bounds.getHeight();
989    mSnapshot->orthoMatrix.load(mOrthoMatrix);
990
991    endTiling();
992    debugOverdraw(false, false);
993    // Bind texture to FBO
994    glBindFramebuffer(GL_FRAMEBUFFER, layer->getFbo());
995    layer->bindTexture();
996
997    // Initialize the texture if needed
998    if (layer->isEmpty()) {
999        layer->allocateTexture();
1000        layer->setEmpty(false);
1001    }
1002
1003    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
1004            layer->getTexture(), 0);
1005
1006    startTiling(mSnapshot, true);
1007
1008    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
1009    mCaches.enableScissor();
1010    mCaches.setScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
1011            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
1012    glClear(GL_COLOR_BUFFER_BIT);
1013
1014    dirtyClip();
1015
1016    // Change the ortho projection
1017    glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
1018    mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
1019
1020    return true;
1021}
1022
1023/**
1024 * Read the documentation of createLayer() before doing anything in this method.
1025 */
1026void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
1027    if (!current->layer) {
1028        ALOGE("Attempting to compose a layer that does not exist");
1029        return;
1030    }
1031
1032    Layer* layer = current->layer;
1033    const Rect& rect = layer->layer;
1034    const bool fboLayer = current->flags & Snapshot::kFlagIsFboLayer;
1035
1036    bool clipRequired = false;
1037    quickRejectNoScissor(rect, &clipRequired); // safely ignore return, should never be rejected
1038    mCaches.setScissorEnabled(mScissorOptimizationDisabled || clipRequired);
1039
1040    if (fboLayer) {
1041        endTiling();
1042
1043        // Detach the texture from the FBO
1044        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
1045
1046        layer->removeFbo(false);
1047
1048        // Unbind current FBO and restore previous one
1049        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
1050        debugOverdraw(true, false);
1051
1052        startTiling(previous);
1053    }
1054
1055    if (!fboLayer && layer->getAlpha() < 255) {
1056        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
1057                layer->getAlpha() << 24, SkXfermode::kDstIn_Mode, true);
1058        // Required below, composeLayerRect() will divide by 255
1059        layer->setAlpha(255);
1060    }
1061
1062    mCaches.unbindMeshBuffer();
1063
1064    mCaches.activeTexture(0);
1065
1066    // When the layer is stored in an FBO, we can save a bit of fillrate by
1067    // drawing only the dirty region
1068    if (fboLayer) {
1069        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform);
1070        if (layer->getColorFilter()) {
1071            setupColorFilter(layer->getColorFilter());
1072        }
1073        composeLayerRegion(layer, rect);
1074        if (layer->getColorFilter()) {
1075            resetColorFilter();
1076        }
1077    } else if (!rect.isEmpty()) {
1078        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
1079
1080        save(0);
1081        // the layer contains screen buffer content that shouldn't be alpha modulated
1082        // (and any necessary alpha modulation was handled drawing into the layer)
1083        mSnapshot->alpha = 1.0f;
1084        composeLayerRect(layer, rect, true);
1085        restore();
1086    }
1087
1088    dirtyClip();
1089
1090    // Failing to add the layer to the cache should happen only if the layer is too large
1091    if (!mCaches.layerCache.put(layer)) {
1092        LAYER_LOGD("Deleting layer");
1093        Caches::getInstance().resourceCache.decrementRefcount(layer);
1094    }
1095}
1096
1097void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) {
1098    float alpha = getLayerAlpha(layer);
1099
1100    setupDraw();
1101    if (layer->getRenderTarget() == GL_TEXTURE_2D) {
1102        setupDrawWithTexture();
1103    } else {
1104        setupDrawWithExternalTexture();
1105    }
1106    setupDrawTextureTransform();
1107    setupDrawColor(alpha, alpha, alpha, alpha);
1108    setupDrawColorFilter();
1109    setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode());
1110    setupDrawProgram();
1111    setupDrawPureColorUniforms();
1112    setupDrawColorFilterUniforms();
1113    if (layer->getRenderTarget() == GL_TEXTURE_2D) {
1114        setupDrawTexture(layer->getTexture());
1115    } else {
1116        setupDrawExternalTexture(layer->getTexture());
1117    }
1118    if (currentTransform().isPureTranslate() &&
1119            layer->getWidth() == (uint32_t) rect.getWidth() &&
1120            layer->getHeight() == (uint32_t) rect.getHeight()) {
1121        const float x = (int) floorf(rect.left + currentTransform().getTranslateX() + 0.5f);
1122        const float y = (int) floorf(rect.top + currentTransform().getTranslateY() + 0.5f);
1123
1124        layer->setFilter(GL_NEAREST);
1125        setupDrawModelView(x, y, x + rect.getWidth(), y + rect.getHeight(), true);
1126    } else {
1127        layer->setFilter(GL_LINEAR);
1128        setupDrawModelView(rect.left, rect.top, rect.right, rect.bottom);
1129    }
1130    setupDrawTextureTransformUniforms(layer->getTexTransform());
1131    setupDrawMesh(&mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]);
1132
1133    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1134}
1135
1136void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
1137    if (!layer->isTextureLayer()) {
1138        const Rect& texCoords = layer->texCoords;
1139        resetDrawTextureTexCoords(texCoords.left, texCoords.top,
1140                texCoords.right, texCoords.bottom);
1141
1142        float x = rect.left;
1143        float y = rect.top;
1144        bool simpleTransform = currentTransform().isPureTranslate() &&
1145                layer->getWidth() == (uint32_t) rect.getWidth() &&
1146                layer->getHeight() == (uint32_t) rect.getHeight();
1147
1148        if (simpleTransform) {
1149            // When we're swapping, the layer is already in screen coordinates
1150            if (!swap) {
1151                x = (int) floorf(rect.left + currentTransform().getTranslateX() + 0.5f);
1152                y = (int) floorf(rect.top + currentTransform().getTranslateY() + 0.5f);
1153            }
1154
1155            layer->setFilter(GL_NEAREST, true);
1156        } else {
1157            layer->setFilter(GL_LINEAR, true);
1158        }
1159
1160        float alpha = getLayerAlpha(layer);
1161        bool blend = layer->isBlend() || alpha < 1.0f;
1162        drawTextureMesh(x, y, x + rect.getWidth(), y + rect.getHeight(),
1163                layer->getTexture(), alpha, layer->getMode(), blend,
1164                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1165                GL_TRIANGLE_STRIP, gMeshCount, swap, swap || simpleTransform);
1166
1167        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1168    } else {
1169        resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f);
1170        drawTextureLayer(layer, rect);
1171        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1172    }
1173}
1174
1175/**
1176 * Issues the command X, and if we're composing a save layer to the fbo or drawing a newly updated
1177 * hardware layer with overdraw debug on, draws again to the stencil only, so that these draw
1178 * operations are correctly counted twice for overdraw. NOTE: assumes composeLayerRegion only used
1179 * by saveLayer's restore
1180 */
1181#define DRAW_DOUBLE_STENCIL_IF(COND, DRAW_COMMAND) {                             \
1182        DRAW_COMMAND;                                                            \
1183        if (CC_UNLIKELY(mCaches.debugOverdraw && getTargetFbo() == 0 && COND)) { \
1184            glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);                 \
1185            DRAW_COMMAND;                                                        \
1186            glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);                     \
1187        }                                                                        \
1188    }
1189
1190#define DRAW_DOUBLE_STENCIL(DRAW_COMMAND) DRAW_DOUBLE_STENCIL_IF(true, DRAW_COMMAND)
1191
1192void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
1193    if (layer->region.isRect()) {
1194        layer->setRegionAsRect();
1195
1196        DRAW_DOUBLE_STENCIL(composeLayerRect(layer, layer->regionRect));
1197
1198        layer->region.clear();
1199        return;
1200    }
1201
1202    if (CC_LIKELY(!layer->region.isEmpty())) {
1203        size_t count;
1204        const android::Rect* rects;
1205        Region safeRegion;
1206        if (CC_LIKELY(hasRectToRectTransform())) {
1207            rects = layer->region.getArray(&count);
1208        } else {
1209            safeRegion = Region::createTJunctionFreeRegion(layer->region);
1210            rects = safeRegion.getArray(&count);
1211        }
1212
1213        const float alpha = getLayerAlpha(layer);
1214        const float texX = 1.0f / float(layer->getWidth());
1215        const float texY = 1.0f / float(layer->getHeight());
1216        const float height = rect.getHeight();
1217
1218        setupDraw();
1219
1220        // We must get (and therefore bind) the region mesh buffer
1221        // after we setup drawing in case we need to mess with the
1222        // stencil buffer in setupDraw()
1223        TextureVertex* mesh = mCaches.getRegionMesh();
1224        uint32_t numQuads = 0;
1225
1226        setupDrawWithTexture();
1227        setupDrawColor(alpha, alpha, alpha, alpha);
1228        setupDrawColorFilter();
1229        setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode(), false);
1230        setupDrawProgram();
1231        setupDrawDirtyRegionsDisabled();
1232        setupDrawPureColorUniforms();
1233        setupDrawColorFilterUniforms();
1234        setupDrawTexture(layer->getTexture());
1235        if (currentTransform().isPureTranslate()) {
1236            const float x = (int) floorf(rect.left + currentTransform().getTranslateX() + 0.5f);
1237            const float y = (int) floorf(rect.top + currentTransform().getTranslateY() + 0.5f);
1238
1239            layer->setFilter(GL_NEAREST);
1240            setupDrawModelViewTranslate(x, y, x + rect.getWidth(), y + rect.getHeight(), true);
1241        } else {
1242            layer->setFilter(GL_LINEAR);
1243            setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
1244        }
1245        setupDrawMeshIndices(&mesh[0].position[0], &mesh[0].texture[0]);
1246
1247        for (size_t i = 0; i < count; i++) {
1248            const android::Rect* r = &rects[i];
1249
1250            const float u1 = r->left * texX;
1251            const float v1 = (height - r->top) * texY;
1252            const float u2 = r->right * texX;
1253            const float v2 = (height - r->bottom) * texY;
1254
1255            // TODO: Reject quads outside of the clip
1256            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
1257            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
1258            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
1259            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
1260
1261            numQuads++;
1262
1263            if (numQuads >= gMaxNumberOfQuads) {
1264                DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6,
1265                                GL_UNSIGNED_SHORT, NULL));
1266                numQuads = 0;
1267                mesh = mCaches.getRegionMesh();
1268            }
1269        }
1270
1271        if (numQuads > 0) {
1272            DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6,
1273                            GL_UNSIGNED_SHORT, NULL));
1274        }
1275
1276#if DEBUG_LAYERS_AS_REGIONS
1277        drawRegionRects(layer->region);
1278#endif
1279
1280        layer->region.clear();
1281    }
1282}
1283
1284void OpenGLRenderer::drawRegionRects(const Region& region) {
1285#if DEBUG_LAYERS_AS_REGIONS
1286    size_t count;
1287    const android::Rect* rects = region.getArray(&count);
1288
1289    uint32_t colors[] = {
1290            0x7fff0000, 0x7f00ff00,
1291            0x7f0000ff, 0x7fff00ff,
1292    };
1293
1294    int offset = 0;
1295    int32_t top = rects[0].top;
1296
1297    for (size_t i = 0; i < count; i++) {
1298        if (top != rects[i].top) {
1299            offset ^= 0x2;
1300            top = rects[i].top;
1301        }
1302
1303        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
1304        drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
1305                SkXfermode::kSrcOver_Mode);
1306    }
1307#endif
1308}
1309
1310void OpenGLRenderer::drawRegionRects(const SkRegion& region, int color,
1311        SkXfermode::Mode mode, bool dirty) {
1312    Vector<float> rects;
1313
1314    SkRegion::Iterator it(region);
1315    while (!it.done()) {
1316        const SkIRect& r = it.rect();
1317        rects.push(r.fLeft);
1318        rects.push(r.fTop);
1319        rects.push(r.fRight);
1320        rects.push(r.fBottom);
1321        it.next();
1322    }
1323
1324    drawColorRects(rects.array(), rects.size(), color, mode, true, dirty, false);
1325}
1326
1327void OpenGLRenderer::dirtyLayer(const float left, const float top,
1328        const float right, const float bottom, const mat4 transform) {
1329    if (hasLayer()) {
1330        Rect bounds(left, top, right, bottom);
1331        transform.mapRect(bounds);
1332        dirtyLayerUnchecked(bounds, getRegion());
1333    }
1334}
1335
1336void OpenGLRenderer::dirtyLayer(const float left, const float top,
1337        const float right, const float bottom) {
1338    if (hasLayer()) {
1339        Rect bounds(left, top, right, bottom);
1340        dirtyLayerUnchecked(bounds, getRegion());
1341    }
1342}
1343
1344void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
1345    if (bounds.intersect(*mSnapshot->clipRect)) {
1346        bounds.snapToPixelBoundaries();
1347        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
1348        if (!dirty.isEmpty()) {
1349            region->orSelf(dirty);
1350        }
1351    }
1352}
1353
1354void OpenGLRenderer::drawIndexedQuads(Vertex* mesh, GLsizei quadsCount) {
1355    GLsizei elementsCount = quadsCount * 6;
1356    while (elementsCount > 0) {
1357        GLsizei drawCount = min(elementsCount, (GLsizei) gMaxNumberOfQuads * 6);
1358
1359        setupDrawIndexedVertices(&mesh[0].position[0]);
1360        glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, NULL);
1361
1362        elementsCount -= drawCount;
1363        // Though there are 4 vertices in a quad, we use 6 indices per
1364        // quad to draw with GL_TRIANGLES
1365        mesh += (drawCount / 6) * 4;
1366    }
1367}
1368
1369void OpenGLRenderer::clearLayerRegions() {
1370    const size_t count = mLayers.size();
1371    if (count == 0) return;
1372
1373    if (!mSnapshot->isIgnored()) {
1374        // Doing several glScissor/glClear here can negatively impact
1375        // GPUs with a tiler architecture, instead we draw quads with
1376        // the Clear blending mode
1377
1378        // The list contains bounds that have already been clipped
1379        // against their initial clip rect, and the current clip
1380        // is likely different so we need to disable clipping here
1381        bool scissorChanged = mCaches.disableScissor();
1382
1383        Vertex mesh[count * 4];
1384        Vertex* vertex = mesh;
1385
1386        for (uint32_t i = 0; i < count; i++) {
1387            Rect* bounds = mLayers.itemAt(i);
1388
1389            Vertex::set(vertex++, bounds->left, bounds->top);
1390            Vertex::set(vertex++, bounds->right, bounds->top);
1391            Vertex::set(vertex++, bounds->left, bounds->bottom);
1392            Vertex::set(vertex++, bounds->right, bounds->bottom);
1393
1394            delete bounds;
1395        }
1396        // We must clear the list of dirty rects before we
1397        // call setupDraw() to prevent stencil setup to do
1398        // the same thing again
1399        mLayers.clear();
1400
1401        setupDraw(false);
1402        setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f);
1403        setupDrawBlending(true, SkXfermode::kClear_Mode);
1404        setupDrawProgram();
1405        setupDrawPureColorUniforms();
1406        setupDrawModelViewTranslate(0.0f, 0.0f, 0.0f, 0.0f, true);
1407
1408        drawIndexedQuads(&mesh[0], count);
1409
1410        if (scissorChanged) mCaches.enableScissor();
1411    } else {
1412        for (uint32_t i = 0; i < count; i++) {
1413            delete mLayers.itemAt(i);
1414        }
1415        mLayers.clear();
1416    }
1417}
1418
1419///////////////////////////////////////////////////////////////////////////////
1420// State Deferral
1421///////////////////////////////////////////////////////////////////////////////
1422
1423bool OpenGLRenderer::storeDisplayState(DeferredDisplayState& state, int stateDeferFlags) {
1424    const Rect& currentClip = *(mSnapshot->clipRect);
1425    const mat4& currentMatrix = *(mSnapshot->transform);
1426
1427    if (stateDeferFlags & kStateDeferFlag_Draw) {
1428        // state has bounds initialized in local coordinates
1429        if (!state.mBounds.isEmpty()) {
1430            currentMatrix.mapRect(state.mBounds);
1431            Rect clippedBounds(state.mBounds);
1432            // NOTE: if we ever want to use this clipping info to drive whether the scissor
1433            // is used, it should more closely duplicate the quickReject logic (in how it uses
1434            // snapToPixelBoundaries)
1435
1436            if(!clippedBounds.intersect(currentClip)) {
1437                // quick rejected
1438                return true;
1439            }
1440
1441            state.mClipSideFlags = kClipSide_None;
1442            if (!currentClip.contains(state.mBounds)) {
1443                int& flags = state.mClipSideFlags;
1444                // op partially clipped, so record which sides are clipped for clip-aware merging
1445                if (currentClip.left > state.mBounds.left) flags |= kClipSide_Left;
1446                if (currentClip.top > state.mBounds.top) flags |= kClipSide_Top;
1447                if (currentClip.right < state.mBounds.right) flags |= kClipSide_Right;
1448                if (currentClip.bottom < state.mBounds.bottom) flags |= kClipSide_Bottom;
1449            }
1450            state.mBounds.set(clippedBounds);
1451        } else {
1452            // Empty bounds implies size unknown. Label op as conservatively clipped to disable
1453            // overdraw avoidance (since we don't know what it overlaps)
1454            state.mClipSideFlags = kClipSide_ConservativeFull;
1455            state.mBounds.set(currentClip);
1456        }
1457    }
1458
1459    state.mClipValid = (stateDeferFlags & kStateDeferFlag_Clip);
1460    if (state.mClipValid) {
1461        state.mClip.set(currentClip);
1462    }
1463
1464    // Transform, drawModifiers, and alpha always deferred, since they are used by state operations
1465    // (Note: saveLayer/restore use colorFilter and alpha, so we just save restore everything)
1466    state.mMatrix.load(currentMatrix);
1467    state.mDrawModifiers = mDrawModifiers;
1468    state.mAlpha = mSnapshot->alpha;
1469    return false;
1470}
1471
1472void OpenGLRenderer::restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore) {
1473    currentTransform().load(state.mMatrix);
1474    mDrawModifiers = state.mDrawModifiers;
1475    mSnapshot->alpha = state.mAlpha;
1476
1477    if (state.mClipValid && !skipClipRestore) {
1478        mSnapshot->setClip(state.mClip.left, state.mClip.top,
1479                state.mClip.right, state.mClip.bottom);
1480        dirtyClip();
1481    }
1482}
1483
1484/**
1485 * Merged multidraw (such as in drawText and drawBitmaps rely on the fact that no clipping is done
1486 * in the draw path. Instead, clipping is done ahead of time - either as a single clip rect (when at
1487 * least one op is clipped), or disabled entirely (because no merged op is clipped)
1488 *
1489 * This method should be called when restoreDisplayState() won't be restoring the clip
1490 */
1491void OpenGLRenderer::setupMergedMultiDraw(const Rect* clipRect) {
1492    if (clipRect != NULL) {
1493        mSnapshot->setClip(clipRect->left, clipRect->top, clipRect->right, clipRect->bottom);
1494    } else {
1495        mSnapshot->setClip(0, 0, mWidth, mHeight);
1496    }
1497    dirtyClip();
1498    mCaches.setScissorEnabled(clipRect != NULL || mScissorOptimizationDisabled);
1499}
1500
1501///////////////////////////////////////////////////////////////////////////////
1502// Transforms
1503///////////////////////////////////////////////////////////////////////////////
1504
1505void OpenGLRenderer::translate(float dx, float dy) {
1506    currentTransform().translate(dx, dy);
1507}
1508
1509void OpenGLRenderer::rotate(float degrees) {
1510    currentTransform().rotate(degrees, 0.0f, 0.0f, 1.0f);
1511}
1512
1513void OpenGLRenderer::scale(float sx, float sy) {
1514    currentTransform().scale(sx, sy, 1.0f);
1515}
1516
1517void OpenGLRenderer::skew(float sx, float sy) {
1518    currentTransform().skew(sx, sy);
1519}
1520
1521void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
1522    if (matrix) {
1523        currentTransform().load(*matrix);
1524    } else {
1525        currentTransform().loadIdentity();
1526    }
1527}
1528
1529bool OpenGLRenderer::hasRectToRectTransform() {
1530    return CC_LIKELY(currentTransform().rectToRect());
1531}
1532
1533void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
1534    currentTransform().copyTo(*matrix);
1535}
1536
1537void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
1538    SkMatrix transform;
1539    currentTransform().copyTo(transform);
1540    transform.preConcat(*matrix);
1541    currentTransform().load(transform);
1542}
1543
1544///////////////////////////////////////////////////////////////////////////////
1545// Clipping
1546///////////////////////////////////////////////////////////////////////////////
1547
1548void OpenGLRenderer::setScissorFromClip() {
1549    Rect clip(*mSnapshot->clipRect);
1550    clip.snapToPixelBoundaries();
1551
1552    if (mCaches.setScissor(clip.left, mSnapshot->height - clip.bottom,
1553            clip.getWidth(), clip.getHeight())) {
1554        mDirtyClip = false;
1555    }
1556}
1557
1558void OpenGLRenderer::ensureStencilBuffer() {
1559    // Thanks to the mismatch between EGL and OpenGL ES FBO we
1560    // cannot attach a stencil buffer to fbo0 dynamically. Let's
1561    // just hope we have one when hasLayer() returns false.
1562    if (hasLayer()) {
1563        attachStencilBufferToLayer(mSnapshot->layer);
1564    }
1565}
1566
1567void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) {
1568    // The layer's FBO is already bound when we reach this stage
1569    if (!layer->getStencilRenderBuffer()) {
1570        // GL_QCOM_tiled_rendering doesn't like it if a renderbuffer
1571        // is attached after we initiated tiling. We must turn it off,
1572        // attach the new render buffer then turn tiling back on
1573        endTiling();
1574
1575        RenderBuffer* buffer = mCaches.renderBufferCache.get(
1576                Stencil::getSmallestStencilFormat(), layer->getWidth(), layer->getHeight());
1577        layer->setStencilRenderBuffer(buffer);
1578
1579        startTiling(layer->clipRect, layer->layer.getHeight());
1580    }
1581}
1582
1583void OpenGLRenderer::setStencilFromClip() {
1584    if (!mCaches.debugOverdraw) {
1585        if (!mSnapshot->clipRegion->isEmpty()) {
1586            // NOTE: The order here is important, we must set dirtyClip to false
1587            //       before any draw call to avoid calling back into this method
1588            mDirtyClip = false;
1589
1590            ensureStencilBuffer();
1591
1592            mCaches.stencil.enableWrite();
1593
1594            // Clear the stencil but first make sure we restrict drawing
1595            // to the region's bounds
1596            bool resetScissor = mCaches.enableScissor();
1597            if (resetScissor) {
1598                // The scissor was not set so we now need to update it
1599                setScissorFromClip();
1600            }
1601            mCaches.stencil.clear();
1602            if (resetScissor) mCaches.disableScissor();
1603
1604            // NOTE: We could use the region contour path to generate a smaller mesh
1605            //       Since we are using the stencil we could use the red book path
1606            //       drawing technique. It might increase bandwidth usage though.
1607
1608            // The last parameter is important: we are not drawing in the color buffer
1609            // so we don't want to dirty the current layer, if any
1610            drawRegionRects(*mSnapshot->clipRegion, 0xff000000, SkXfermode::kSrc_Mode, false);
1611
1612            mCaches.stencil.enableTest();
1613
1614            // Draw the region used to generate the stencil if the appropriate debug
1615            // mode is enabled
1616            if (mCaches.debugStencilClip == Caches::kStencilShowRegion) {
1617                drawRegionRects(*mSnapshot->clipRegion, 0x7f0000ff, SkXfermode::kSrcOver_Mode);
1618            }
1619        } else {
1620            mCaches.stencil.disable();
1621        }
1622    }
1623}
1624
1625const Rect& OpenGLRenderer::getClipBounds() {
1626    return mSnapshot->getLocalClip();
1627}
1628
1629bool OpenGLRenderer::quickRejectNoScissor(float left, float top, float right, float bottom,
1630        bool snapOut, bool* clipRequired) {
1631    if (mSnapshot->isIgnored() || bottom <= top || right <= left) {
1632        return true;
1633    }
1634
1635    Rect r(left, top, right, bottom);
1636    currentTransform().mapRect(r);
1637    r.snapGeometryToPixelBoundaries(snapOut);
1638
1639    Rect clipRect(*mSnapshot->clipRect);
1640    clipRect.snapToPixelBoundaries();
1641
1642    if (!clipRect.intersects(r)) return true;
1643
1644    if (clipRequired) *clipRequired = !clipRect.contains(r);
1645    return false;
1646}
1647
1648bool OpenGLRenderer::quickRejectPreStroke(float left, float top, float right, float bottom,
1649        SkPaint* paint) {
1650    // AA geometry will likely have a ramp around it (not accounted for in local bounds). Snap out
1651    // the final mapped rect to ensure correct clipping behavior for the ramp.
1652    bool snapOut = paint->isAntiAlias();
1653
1654    if (paint->getStyle() != SkPaint::kFill_Style) {
1655        float outset = paint->getStrokeWidth() * 0.5f;
1656        return quickReject(left - outset, top - outset, right + outset, bottom + outset, snapOut);
1657    } else {
1658        return quickReject(left, top, right, bottom, snapOut);
1659    }
1660}
1661
1662bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom, bool snapOut) {
1663    bool clipRequired = false;
1664    if (quickRejectNoScissor(left, top, right, bottom, snapOut, &clipRequired)) {
1665        return true;
1666    }
1667
1668    if (!isDeferred()) {
1669        mCaches.setScissorEnabled(mScissorOptimizationDisabled || clipRequired);
1670    }
1671    return false;
1672}
1673
1674void OpenGLRenderer::debugClip() {
1675#if DEBUG_CLIP_REGIONS
1676    if (!isDeferred() && !mSnapshot->clipRegion->isEmpty()) {
1677        drawRegionRects(*mSnapshot->clipRegion, 0x7f00ff00, SkXfermode::kSrcOver_Mode);
1678    }
1679#endif
1680}
1681
1682bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
1683    if (CC_LIKELY(currentTransform().rectToRect())) {
1684        bool clipped = mSnapshot->clip(left, top, right, bottom, op);
1685        if (clipped) {
1686            dirtyClip();
1687        }
1688        return !mSnapshot->clipRect->isEmpty();
1689    }
1690
1691    SkPath path;
1692    path.addRect(left, top, right, bottom);
1693
1694    return OpenGLRenderer::clipPath(&path, op);
1695}
1696
1697bool OpenGLRenderer::clipPath(SkPath* path, SkRegion::Op op) {
1698    SkMatrix transform;
1699    currentTransform().copyTo(transform);
1700
1701    SkPath transformed;
1702    path->transform(transform, &transformed);
1703
1704    SkRegion clip;
1705    if (!mSnapshot->previous->clipRegion->isEmpty()) {
1706        clip.setRegion(*mSnapshot->previous->clipRegion);
1707    } else {
1708        if (mSnapshot->previous == mFirstSnapshot) {
1709            clip.setRect(0, 0, mWidth, mHeight);
1710        } else {
1711            Rect* bounds = mSnapshot->previous->clipRect;
1712            clip.setRect(bounds->left, bounds->top, bounds->right, bounds->bottom);
1713        }
1714    }
1715
1716    SkRegion region;
1717    region.setPath(transformed, clip);
1718
1719    bool clipped = mSnapshot->clipRegionTransformed(region, op);
1720    if (clipped) {
1721        dirtyClip();
1722    }
1723    return !mSnapshot->clipRect->isEmpty();
1724}
1725
1726bool OpenGLRenderer::clipRegion(SkRegion* region, SkRegion::Op op) {
1727    bool clipped = mSnapshot->clipRegionTransformed(*region, op);
1728    if (clipped) {
1729        dirtyClip();
1730    }
1731    return !mSnapshot->clipRect->isEmpty();
1732}
1733
1734Rect* OpenGLRenderer::getClipRect() {
1735    return mSnapshot->clipRect;
1736}
1737
1738///////////////////////////////////////////////////////////////////////////////
1739// Drawing commands
1740///////////////////////////////////////////////////////////////////////////////
1741
1742void OpenGLRenderer::setupDraw(bool clear) {
1743    // TODO: It would be best if we could do this before quickReject()
1744    //       changes the scissor test state
1745    if (clear) clearLayerRegions();
1746    // Make sure setScissor & setStencil happen at the beginning of
1747    // this method
1748    if (mDirtyClip) {
1749        if (mCaches.scissorEnabled) {
1750            setScissorFromClip();
1751        }
1752        setStencilFromClip();
1753    }
1754
1755    mDescription.reset();
1756
1757    mSetShaderColor = false;
1758    mColorSet = false;
1759    mColorA = mColorR = mColorG = mColorB = 0.0f;
1760    mTextureUnit = 0;
1761    mTrackDirtyRegions = true;
1762
1763    // Enable debug highlight when what we're about to draw is tested against
1764    // the stencil buffer and if stencil highlight debugging is on
1765    mDescription.hasDebugHighlight = !mCaches.debugOverdraw &&
1766            mCaches.debugStencilClip == Caches::kStencilShowHighlight &&
1767            mCaches.stencil.isTestEnabled();
1768
1769    mDescription.emulateStencil = mCountOverdraw;
1770}
1771
1772void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
1773    mDescription.hasTexture = true;
1774    mDescription.hasAlpha8Texture = isAlpha8;
1775}
1776
1777void OpenGLRenderer::setupDrawWithTextureAndColor(bool isAlpha8) {
1778    mDescription.hasTexture = true;
1779    mDescription.hasColors = true;
1780    mDescription.hasAlpha8Texture = isAlpha8;
1781}
1782
1783void OpenGLRenderer::setupDrawWithExternalTexture() {
1784    mDescription.hasExternalTexture = true;
1785}
1786
1787void OpenGLRenderer::setupDrawNoTexture() {
1788    mCaches.disableTexCoordsVertexArray();
1789}
1790
1791void OpenGLRenderer::setupDrawAA() {
1792    mDescription.isAA = true;
1793}
1794
1795void OpenGLRenderer::setupDrawColor(int color, int alpha) {
1796    mColorA = alpha / 255.0f;
1797    mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1798    mColorG = mColorA * ((color >>  8) & 0xFF) / 255.0f;
1799    mColorB = mColorA * ((color      ) & 0xFF) / 255.0f;
1800    mColorSet = true;
1801    mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA);
1802}
1803
1804void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
1805    mColorA = alpha / 255.0f;
1806    mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1807    mColorG = mColorA * ((color >>  8) & 0xFF) / 255.0f;
1808    mColorB = mColorA * ((color      ) & 0xFF) / 255.0f;
1809    mColorSet = true;
1810    mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
1811}
1812
1813void OpenGLRenderer::setupDrawTextGamma(const SkPaint* paint) {
1814    mCaches.fontRenderer->describe(mDescription, paint);
1815}
1816
1817void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
1818    mColorA = a;
1819    mColorR = r;
1820    mColorG = g;
1821    mColorB = b;
1822    mColorSet = true;
1823    mSetShaderColor = mDescription.setColor(r, g, b, a);
1824}
1825
1826void OpenGLRenderer::setupDrawShader() {
1827    if (mDrawModifiers.mShader) {
1828        mDrawModifiers.mShader->describe(mDescription, mExtensions);
1829    }
1830}
1831
1832void OpenGLRenderer::setupDrawColorFilter() {
1833    if (mDrawModifiers.mColorFilter) {
1834        mDrawModifiers.mColorFilter->describe(mDescription, mExtensions);
1835    }
1836}
1837
1838void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
1839    if (mColorSet && mode == SkXfermode::kClear_Mode) {
1840        mColorA = 1.0f;
1841        mColorR = mColorG = mColorB = 0.0f;
1842        mSetShaderColor = mDescription.modulate = true;
1843    }
1844}
1845
1846void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) {
1847    // When the blending mode is kClear_Mode, we need to use a modulate color
1848    // argb=1,0,0,0
1849    accountForClear(mode);
1850    bool blend = (mColorSet && mColorA < 1.0f) ||
1851            (mDrawModifiers.mShader && mDrawModifiers.mShader->blend());
1852    chooseBlending(blend, mode, mDescription, swapSrcDst);
1853}
1854
1855void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) {
1856    // When the blending mode is kClear_Mode, we need to use a modulate color
1857    // argb=1,0,0,0
1858    accountForClear(mode);
1859    blend |= (mColorSet && mColorA < 1.0f) ||
1860            (mDrawModifiers.mShader && mDrawModifiers.mShader->blend()) ||
1861            (mDrawModifiers.mColorFilter && mDrawModifiers.mColorFilter->blend());
1862    chooseBlending(blend, mode, mDescription, swapSrcDst);
1863}
1864
1865void OpenGLRenderer::setupDrawProgram() {
1866    useProgram(mCaches.programCache.get(mDescription));
1867}
1868
1869void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
1870    mTrackDirtyRegions = false;
1871}
1872
1873void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom,
1874        bool ignoreTransform) {
1875    mModelView.loadTranslate(left, top, 0.0f);
1876    if (!ignoreTransform) {
1877        mCaches.currentProgram->set(mOrthoMatrix, mModelView, currentTransform());
1878        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, currentTransform());
1879    } else {
1880        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mat4::identity());
1881        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
1882    }
1883}
1884
1885void OpenGLRenderer::setupDrawModelViewIdentity(bool offset) {
1886    mCaches.currentProgram->set(mOrthoMatrix, mat4::identity(), currentTransform(), offset);
1887}
1888
1889void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom,
1890        bool ignoreTransform, bool ignoreModelView) {
1891    if (!ignoreModelView) {
1892        mModelView.loadTranslate(left, top, 0.0f);
1893        mModelView.scale(right - left, bottom - top, 1.0f);
1894    } else {
1895        mModelView.loadIdentity();
1896    }
1897    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
1898    if (!ignoreTransform) {
1899        mCaches.currentProgram->set(mOrthoMatrix, mModelView, currentTransform());
1900        if (mTrackDirtyRegions && dirty) {
1901            dirtyLayer(left, top, right, bottom, currentTransform());
1902        }
1903    } else {
1904        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mat4::identity());
1905        if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom);
1906    }
1907}
1908
1909void OpenGLRenderer::setupDrawColorUniforms() {
1910    if ((mColorSet && !mDrawModifiers.mShader) || (mDrawModifiers.mShader && mSetShaderColor)) {
1911        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1912    }
1913}
1914
1915void OpenGLRenderer::setupDrawPureColorUniforms() {
1916    if (mSetShaderColor) {
1917        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1918    }
1919}
1920
1921void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
1922    if (mDrawModifiers.mShader) {
1923        if (ignoreTransform) {
1924            mModelView.loadInverse(currentTransform());
1925        }
1926        mDrawModifiers.mShader->setupProgram(mCaches.currentProgram,
1927                mModelView, *mSnapshot, &mTextureUnit);
1928    }
1929}
1930
1931void OpenGLRenderer::setupDrawShaderIdentityUniforms() {
1932    if (mDrawModifiers.mShader) {
1933        mDrawModifiers.mShader->setupProgram(mCaches.currentProgram,
1934                mat4::identity(), *mSnapshot, &mTextureUnit);
1935    }
1936}
1937
1938void OpenGLRenderer::setupDrawColorFilterUniforms() {
1939    if (mDrawModifiers.mColorFilter) {
1940        mDrawModifiers.mColorFilter->setupProgram(mCaches.currentProgram);
1941    }
1942}
1943
1944void OpenGLRenderer::setupDrawTextGammaUniforms() {
1945    mCaches.fontRenderer->setupProgram(mDescription, mCaches.currentProgram);
1946}
1947
1948void OpenGLRenderer::setupDrawSimpleMesh() {
1949    bool force = mCaches.bindMeshBuffer();
1950    mCaches.bindPositionVertexPointer(force, 0);
1951    mCaches.unbindIndicesBuffer();
1952}
1953
1954void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1955    if (texture) bindTexture(texture);
1956    mTextureUnit++;
1957    mCaches.enableTexCoordsVertexArray();
1958}
1959
1960void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) {
1961    bindExternalTexture(texture);
1962    mTextureUnit++;
1963    mCaches.enableTexCoordsVertexArray();
1964}
1965
1966void OpenGLRenderer::setupDrawTextureTransform() {
1967    mDescription.hasTextureTransform = true;
1968}
1969
1970void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) {
1971    glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1,
1972            GL_FALSE, &transform.data[0]);
1973}
1974
1975void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1976    bool force = false;
1977    if (!vertices || vbo) {
1978        force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1979    } else {
1980        force = mCaches.unbindMeshBuffer();
1981    }
1982
1983    mCaches.bindPositionVertexPointer(force, vertices);
1984    if (mCaches.currentProgram->texCoords >= 0) {
1985        mCaches.bindTexCoordsVertexPointer(force, texCoords);
1986    }
1987
1988    mCaches.unbindIndicesBuffer();
1989}
1990
1991void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLvoid* colors) {
1992    bool force = mCaches.unbindMeshBuffer();
1993    GLsizei stride = sizeof(ColorTextureVertex);
1994
1995    mCaches.bindPositionVertexPointer(force, vertices, stride);
1996    if (mCaches.currentProgram->texCoords >= 0) {
1997        mCaches.bindTexCoordsVertexPointer(force, texCoords, stride);
1998    }
1999    int slot = mCaches.currentProgram->getAttrib("colors");
2000    if (slot >= 0) {
2001        glEnableVertexAttribArray(slot);
2002        glVertexAttribPointer(slot, 4, GL_FLOAT, GL_FALSE, stride, colors);
2003    }
2004
2005    mCaches.unbindIndicesBuffer();
2006}
2007
2008void OpenGLRenderer::setupDrawMeshIndices(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
2009    bool force = false;
2010    // If vbo is != 0 we want to treat the vertices parameter as an offset inside
2011    // a VBO. However, if vertices is set to NULL and vbo == 0 then we want to
2012    // use the default VBO found in Caches
2013    if (!vertices || vbo) {
2014        force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
2015    } else {
2016        force = mCaches.unbindMeshBuffer();
2017    }
2018    mCaches.bindIndicesBuffer();
2019
2020    mCaches.bindPositionVertexPointer(force, vertices);
2021    if (mCaches.currentProgram->texCoords >= 0) {
2022        mCaches.bindTexCoordsVertexPointer(force, texCoords);
2023    }
2024}
2025
2026void OpenGLRenderer::setupDrawIndexedVertices(GLvoid* vertices) {
2027    bool force = mCaches.unbindMeshBuffer();
2028    mCaches.bindIndicesBuffer();
2029    mCaches.bindPositionVertexPointer(force, vertices, gVertexStride);
2030}
2031
2032///////////////////////////////////////////////////////////////////////////////
2033// Drawing
2034///////////////////////////////////////////////////////////////////////////////
2035
2036status_t OpenGLRenderer::drawDisplayList(DisplayList* displayList, Rect& dirty,
2037        int32_t replayFlags) {
2038    status_t status;
2039    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
2040    // will be performed by the display list itself
2041    if (displayList && displayList->isRenderable()) {
2042        if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
2043            status = startFrame();
2044            ReplayStateStruct replayStruct(*this, dirty, replayFlags);
2045            displayList->replay(replayStruct, 0);
2046            return status | replayStruct.mDrawGlStatus;
2047        }
2048
2049        bool avoidOverdraw = !mCaches.debugOverdraw && !mCountOverdraw; // shh, don't tell devs!
2050        DeferredDisplayList deferredList(*(mSnapshot->clipRect), avoidOverdraw);
2051        DeferStateStruct deferStruct(deferredList, *this, replayFlags);
2052        displayList->defer(deferStruct, 0);
2053
2054        flushLayers();
2055        status = startFrame();
2056
2057        return status | deferredList.flush(*this, dirty);
2058    }
2059
2060    // Even if there is no drawing command(Ex: invisible),
2061    // it still needs startFrame to clear buffer and start tiling.
2062    return startFrame();
2063}
2064
2065void OpenGLRenderer::outputDisplayList(DisplayList* displayList) {
2066    if (displayList) {
2067        displayList->output(1);
2068    }
2069}
2070
2071void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint) {
2072    int alpha;
2073    SkXfermode::Mode mode;
2074    getAlphaAndMode(paint, &alpha, &mode);
2075
2076    int color = paint != NULL ? paint->getColor() : 0;
2077
2078    float x = left;
2079    float y = top;
2080
2081    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2082
2083    bool ignoreTransform = false;
2084    if (currentTransform().isPureTranslate()) {
2085        x = (int) floorf(left + currentTransform().getTranslateX() + 0.5f);
2086        y = (int) floorf(top + currentTransform().getTranslateY() + 0.5f);
2087        ignoreTransform = true;
2088
2089        texture->setFilter(GL_NEAREST, true);
2090    } else {
2091        texture->setFilter(FILTER(paint), true);
2092    }
2093
2094    // No need to check for a UV mapper on the texture object, only ARGB_8888
2095    // bitmaps get packed in the atlas
2096    drawAlpha8TextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
2097            paint != NULL, color, alpha, mode, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
2098            GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform);
2099}
2100
2101/**
2102 * Important note: this method is intended to draw batches of bitmaps and
2103 * will not set the scissor enable or dirty the current layer, if any.
2104 * The caller is responsible for properly dirtying the current layer.
2105 */
2106status_t OpenGLRenderer::drawBitmaps(SkBitmap* bitmap, AssetAtlas::Entry* entry, int bitmapCount,
2107        TextureVertex* vertices, bool pureTranslate, const Rect& bounds, SkPaint* paint) {
2108    mCaches.activeTexture(0);
2109    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
2110    if (!texture) return DrawGlInfo::kStatusDone;
2111
2112    const AutoTexture autoCleanup(texture);
2113
2114    int alpha;
2115    SkXfermode::Mode mode;
2116    getAlphaAndMode(paint, &alpha, &mode);
2117
2118    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2119    texture->setFilter(pureTranslate ? GL_NEAREST : FILTER(paint), true);
2120
2121    const float x = (int) floorf(bounds.left + 0.5f);
2122    const float y = (int) floorf(bounds.top + 0.5f);
2123    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
2124        int color = paint != NULL ? paint->getColor() : 0;
2125        drawAlpha8TextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
2126                texture->id, paint != NULL, color, alpha, mode,
2127                &vertices[0].position[0], &vertices[0].texture[0],
2128                GL_TRIANGLES, bitmapCount * 6, true, true, false);
2129    } else {
2130        drawTextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
2131                texture->id, alpha / 255.0f, mode, texture->blend,
2132                &vertices[0].position[0], &vertices[0].texture[0],
2133                GL_TRIANGLES, bitmapCount * 6, false, true, 0, true, false);
2134    }
2135
2136    return DrawGlInfo::kStatusDrew;
2137}
2138
2139status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
2140    const float right = left + bitmap->width();
2141    const float bottom = top + bitmap->height();
2142
2143    if (quickReject(left, top, right, bottom)) {
2144        return DrawGlInfo::kStatusDone;
2145    }
2146
2147    mCaches.activeTexture(0);
2148    Texture* texture = getTexture(bitmap);
2149    if (!texture) return DrawGlInfo::kStatusDone;
2150    const AutoTexture autoCleanup(texture);
2151
2152    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
2153        drawAlphaBitmap(texture, left, top, paint);
2154    } else {
2155        drawTextureRect(left, top, right, bottom, texture, paint);
2156    }
2157
2158    return DrawGlInfo::kStatusDrew;
2159}
2160
2161status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
2162    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
2163    const mat4 transform(*matrix);
2164    transform.mapRect(r);
2165
2166    if (quickReject(r.left, r.top, r.right, r.bottom)) {
2167        return DrawGlInfo::kStatusDone;
2168    }
2169
2170    mCaches.activeTexture(0);
2171    Texture* texture = getTexture(bitmap);
2172    if (!texture) return DrawGlInfo::kStatusDone;
2173    const AutoTexture autoCleanup(texture);
2174
2175    // This could be done in a cheaper way, all we need is pass the matrix
2176    // to the vertex shader. The save/restore is a bit overkill.
2177    save(SkCanvas::kMatrix_SaveFlag);
2178    concatMatrix(matrix);
2179    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
2180        drawAlphaBitmap(texture, 0.0f, 0.0f, paint);
2181    } else {
2182        drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
2183    }
2184    restore();
2185
2186    return DrawGlInfo::kStatusDrew;
2187}
2188
2189status_t OpenGLRenderer::drawBitmapData(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
2190    const float right = left + bitmap->width();
2191    const float bottom = top + bitmap->height();
2192
2193    if (quickReject(left, top, right, bottom)) {
2194        return DrawGlInfo::kStatusDone;
2195    }
2196
2197    mCaches.activeTexture(0);
2198    Texture* texture = mCaches.textureCache.getTransient(bitmap);
2199    const AutoTexture autoCleanup(texture);
2200
2201    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
2202        drawAlphaBitmap(texture, left, top, paint);
2203    } else {
2204        drawTextureRect(left, top, right, bottom, texture, paint);
2205    }
2206
2207    return DrawGlInfo::kStatusDrew;
2208}
2209
2210status_t OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
2211        float* vertices, int* colors, SkPaint* paint) {
2212    if (!vertices || mSnapshot->isIgnored()) {
2213        return DrawGlInfo::kStatusDone;
2214    }
2215
2216    // TODO: use quickReject on bounds from vertices
2217    mCaches.enableScissor();
2218
2219    float left = FLT_MAX;
2220    float top = FLT_MAX;
2221    float right = FLT_MIN;
2222    float bottom = FLT_MIN;
2223
2224    const uint32_t count = meshWidth * meshHeight * 6;
2225
2226    ColorTextureVertex mesh[count];
2227    ColorTextureVertex* vertex = mesh;
2228
2229    bool cleanupColors = false;
2230    if (!colors) {
2231        uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1);
2232        colors = new int[colorsCount];
2233        memset(colors, 0xff, colorsCount * sizeof(int));
2234        cleanupColors = true;
2235    }
2236
2237    mCaches.activeTexture(0);
2238    Texture* texture = mCaches.assetAtlas.getEntryTexture(bitmap);
2239    const UvMapper& mapper(getMapper(texture));
2240
2241    for (int32_t y = 0; y < meshHeight; y++) {
2242        for (int32_t x = 0; x < meshWidth; x++) {
2243            uint32_t i = (y * (meshWidth + 1) + x) * 2;
2244
2245            float u1 = float(x) / meshWidth;
2246            float u2 = float(x + 1) / meshWidth;
2247            float v1 = float(y) / meshHeight;
2248            float v2 = float(y + 1) / meshHeight;
2249
2250            mapper.map(u1, v1, u2, v2);
2251
2252            int ax = i + (meshWidth + 1) * 2;
2253            int ay = ax + 1;
2254            int bx = i;
2255            int by = bx + 1;
2256            int cx = i + 2;
2257            int cy = cx + 1;
2258            int dx = i + (meshWidth + 1) * 2 + 2;
2259            int dy = dx + 1;
2260
2261            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
2262            ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]);
2263            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
2264
2265            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
2266            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
2267            ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]);
2268
2269            left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
2270            top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
2271            right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
2272            bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
2273        }
2274    }
2275
2276    if (quickReject(left, top, right, bottom)) {
2277        if (cleanupColors) delete[] colors;
2278        return DrawGlInfo::kStatusDone;
2279    }
2280
2281    if (!texture) {
2282        texture = mCaches.textureCache.get(bitmap);
2283        if (!texture) {
2284            if (cleanupColors) delete[] colors;
2285            return DrawGlInfo::kStatusDone;
2286        }
2287    }
2288    const AutoTexture autoCleanup(texture);
2289
2290    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2291    texture->setFilter(FILTER(paint), true);
2292
2293    int alpha;
2294    SkXfermode::Mode mode;
2295    getAlphaAndMode(paint, &alpha, &mode);
2296
2297    float a = alpha / 255.0f;
2298
2299    if (hasLayer()) {
2300        dirtyLayer(left, top, right, bottom, currentTransform());
2301    }
2302
2303    setupDraw();
2304    setupDrawWithTextureAndColor();
2305    setupDrawColor(a, a, a, a);
2306    setupDrawColorFilter();
2307    setupDrawBlending(true, mode, false);
2308    setupDrawProgram();
2309    setupDrawDirtyRegionsDisabled();
2310    setupDrawModelView(0.0f, 0.0f, 1.0f, 1.0f, false);
2311    setupDrawTexture(texture->id);
2312    setupDrawPureColorUniforms();
2313    setupDrawColorFilterUniforms();
2314    setupDrawMesh(&mesh[0].position[0], &mesh[0].texture[0], &mesh[0].color[0]);
2315
2316    glDrawArrays(GL_TRIANGLES, 0, count);
2317
2318    int slot = mCaches.currentProgram->getAttrib("colors");
2319    if (slot >= 0) {
2320        glDisableVertexAttribArray(slot);
2321    }
2322
2323    if (cleanupColors) delete[] colors;
2324
2325    return DrawGlInfo::kStatusDrew;
2326}
2327
2328status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
2329         float srcLeft, float srcTop, float srcRight, float srcBottom,
2330         float dstLeft, float dstTop, float dstRight, float dstBottom,
2331         SkPaint* paint) {
2332    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
2333        return DrawGlInfo::kStatusDone;
2334    }
2335
2336    mCaches.activeTexture(0);
2337    Texture* texture = getTexture(bitmap);
2338    if (!texture) return DrawGlInfo::kStatusDone;
2339    const AutoTexture autoCleanup(texture);
2340
2341    const float width = texture->width;
2342    const float height = texture->height;
2343
2344    float u1 = fmax(0.0f, srcLeft / width);
2345    float v1 = fmax(0.0f, srcTop / height);
2346    float u2 = fmin(1.0f, srcRight / width);
2347    float v2 = fmin(1.0f, srcBottom / height);
2348
2349    getMapper(texture).map(u1, v1, u2, v2);
2350
2351    mCaches.unbindMeshBuffer();
2352    resetDrawTextureTexCoords(u1, v1, u2, v2);
2353
2354    int alpha;
2355    SkXfermode::Mode mode;
2356    getAlphaAndMode(paint, &alpha, &mode);
2357
2358    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2359
2360    float scaleX = (dstRight - dstLeft) / (srcRight - srcLeft);
2361    float scaleY = (dstBottom - dstTop) / (srcBottom - srcTop);
2362
2363    bool scaled = scaleX != 1.0f || scaleY != 1.0f;
2364    // Apply a scale transform on the canvas only when a shader is in use
2365    // Skia handles the ratio between the dst and src rects as a scale factor
2366    // when a shader is set
2367    bool useScaleTransform = mDrawModifiers.mShader && scaled;
2368    bool ignoreTransform = false;
2369
2370    if (CC_LIKELY(currentTransform().isPureTranslate() && !useScaleTransform)) {
2371        float x = (int) floorf(dstLeft + currentTransform().getTranslateX() + 0.5f);
2372        float y = (int) floorf(dstTop + currentTransform().getTranslateY() + 0.5f);
2373
2374        dstRight = x + (dstRight - dstLeft);
2375        dstBottom = y + (dstBottom - dstTop);
2376
2377        dstLeft = x;
2378        dstTop = y;
2379
2380        texture->setFilter(scaled ? FILTER(paint) : GL_NEAREST, true);
2381        ignoreTransform = true;
2382    } else {
2383        texture->setFilter(FILTER(paint), true);
2384    }
2385
2386    if (CC_UNLIKELY(useScaleTransform)) {
2387        save(SkCanvas::kMatrix_SaveFlag);
2388        translate(dstLeft, dstTop);
2389        scale(scaleX, scaleY);
2390
2391        dstLeft = 0.0f;
2392        dstTop = 0.0f;
2393
2394        dstRight = srcRight - srcLeft;
2395        dstBottom = srcBottom - srcTop;
2396    }
2397
2398    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
2399        int color = paint ? paint->getColor() : 0;
2400        drawAlpha8TextureMesh(dstLeft, dstTop, dstRight, dstBottom,
2401                texture->id, paint != NULL, color, alpha, mode,
2402                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
2403                GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform);
2404    } else {
2405        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom,
2406                texture->id, alpha / 255.0f, mode, texture->blend,
2407                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
2408                GL_TRIANGLE_STRIP, gMeshCount, false, ignoreTransform);
2409    }
2410
2411    if (CC_UNLIKELY(useScaleTransform)) {
2412        restore();
2413    }
2414
2415    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
2416
2417    return DrawGlInfo::kStatusDrew;
2418}
2419
2420status_t OpenGLRenderer::drawPatch(SkBitmap* bitmap, Res_png_9patch* patch,
2421        float left, float top, float right, float bottom, SkPaint* paint) {
2422    if (quickReject(left, top, right, bottom)) {
2423        return DrawGlInfo::kStatusDone;
2424    }
2425
2426    AssetAtlas::Entry* entry = mCaches.assetAtlas.getEntry(bitmap);
2427    const Patch* mesh = mCaches.patchCache.get(entry, bitmap->width(), bitmap->height(),
2428            right - left, bottom - top, patch);
2429
2430    return drawPatch(bitmap, mesh, entry, left, top, right, bottom, paint);
2431}
2432
2433status_t OpenGLRenderer::drawPatch(SkBitmap* bitmap, const Patch* mesh, AssetAtlas::Entry* entry,
2434        float left, float top, float right, float bottom, SkPaint* paint) {
2435    if (quickReject(left, top, right, bottom)) {
2436        return DrawGlInfo::kStatusDone;
2437    }
2438
2439    if (CC_LIKELY(mesh && mesh->verticesCount > 0)) {
2440        mCaches.activeTexture(0);
2441        Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
2442        if (!texture) return DrawGlInfo::kStatusDone;
2443        const AutoTexture autoCleanup(texture);
2444
2445        texture->setWrap(GL_CLAMP_TO_EDGE, true);
2446        texture->setFilter(GL_LINEAR, true);
2447
2448        int alpha;
2449        SkXfermode::Mode mode;
2450        getAlphaAndMode(paint, &alpha, &mode);
2451
2452        const bool pureTranslate = currentTransform().isPureTranslate();
2453        // Mark the current layer dirty where we are going to draw the patch
2454        if (hasLayer() && mesh->hasEmptyQuads) {
2455            const float offsetX = left + currentTransform().getTranslateX();
2456            const float offsetY = top + currentTransform().getTranslateY();
2457            const size_t count = mesh->quads.size();
2458            for (size_t i = 0; i < count; i++) {
2459                const Rect& bounds = mesh->quads.itemAt(i);
2460                if (CC_LIKELY(pureTranslate)) {
2461                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
2462                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
2463                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
2464                } else {
2465                    dirtyLayer(left + bounds.left, top + bounds.top,
2466                            left + bounds.right, top + bounds.bottom, currentTransform());
2467                }
2468            }
2469        }
2470
2471        if (CC_LIKELY(pureTranslate)) {
2472            const float x = (int) floorf(left + currentTransform().getTranslateX() + 0.5f);
2473            const float y = (int) floorf(top + currentTransform().getTranslateY() + 0.5f);
2474
2475            right = x + right - left;
2476            bottom = y + bottom - top;
2477            drawIndexedTextureMesh(x, y, right, bottom, texture->id, alpha / 255.0f,
2478                    mode, texture->blend, (GLvoid*) mesh->offset, (GLvoid*) mesh->textureOffset,
2479                    GL_TRIANGLES, mesh->indexCount, false, true,
2480                    mCaches.patchCache.getMeshBuffer(), true, !mesh->hasEmptyQuads);
2481        } else {
2482            drawIndexedTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
2483                    mode, texture->blend, (GLvoid*) mesh->offset, (GLvoid*) mesh->textureOffset,
2484                    GL_TRIANGLES, mesh->indexCount, false, false,
2485                    mCaches.patchCache.getMeshBuffer(), true, !mesh->hasEmptyQuads);
2486        }
2487    }
2488
2489    return DrawGlInfo::kStatusDrew;
2490}
2491
2492/**
2493 * Important note: this method is intended to draw batches of 9-patch objects and
2494 * will not set the scissor enable or dirty the current layer, if any.
2495 * The caller is responsible for properly dirtying the current layer.
2496 */
2497status_t OpenGLRenderer::drawPatches(SkBitmap* bitmap, AssetAtlas::Entry* entry,
2498        TextureVertex* vertices, uint32_t indexCount, SkPaint* paint) {
2499    mCaches.activeTexture(0);
2500    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
2501    if (!texture) return DrawGlInfo::kStatusDone;
2502    const AutoTexture autoCleanup(texture);
2503
2504    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2505    texture->setFilter(GL_LINEAR, true);
2506
2507    int alpha;
2508    SkXfermode::Mode mode;
2509    getAlphaAndMode(paint, &alpha, &mode);
2510
2511    drawIndexedTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f,
2512            mode, texture->blend, &vertices[0].position[0], &vertices[0].texture[0],
2513            GL_TRIANGLES, indexCount, false, true, 0, true, false);
2514
2515    return DrawGlInfo::kStatusDrew;
2516}
2517
2518status_t OpenGLRenderer::drawVertexBuffer(const VertexBuffer& vertexBuffer, SkPaint* paint,
2519        bool useOffset) {
2520    if (!vertexBuffer.getVertexCount()) {
2521        // no vertices to draw
2522        return DrawGlInfo::kStatusDone;
2523    }
2524
2525    int color = paint->getColor();
2526    SkXfermode::Mode mode = getXfermode(paint->getXfermode());
2527    bool isAA = paint->isAntiAlias();
2528
2529    setupDraw();
2530    setupDrawNoTexture();
2531    if (isAA) setupDrawAA();
2532    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
2533    setupDrawColorFilter();
2534    setupDrawShader();
2535    setupDrawBlending(isAA, mode);
2536    setupDrawProgram();
2537    setupDrawModelViewIdentity(useOffset);
2538    setupDrawColorUniforms();
2539    setupDrawColorFilterUniforms();
2540    setupDrawShaderIdentityUniforms();
2541
2542    void* vertices = vertexBuffer.getBuffer();
2543    bool force = mCaches.unbindMeshBuffer();
2544    mCaches.bindPositionVertexPointer(true, vertices, isAA ? gAlphaVertexStride : gVertexStride);
2545    mCaches.resetTexCoordsVertexPointer();
2546    mCaches.unbindIndicesBuffer();
2547
2548    int alphaSlot = -1;
2549    if (isAA) {
2550        void* alphaCoords = ((GLbyte*) vertices) + gVertexAlphaOffset;
2551        alphaSlot = mCaches.currentProgram->getAttrib("vtxAlpha");
2552
2553        // TODO: avoid enable/disable in back to back uses of the alpha attribute
2554        glEnableVertexAttribArray(alphaSlot);
2555        glVertexAttribPointer(alphaSlot, 1, GL_FLOAT, GL_FALSE, gAlphaVertexStride, alphaCoords);
2556    }
2557
2558    glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexBuffer.getVertexCount());
2559
2560    if (isAA) {
2561        glDisableVertexAttribArray(alphaSlot);
2562    }
2563
2564    return DrawGlInfo::kStatusDrew;
2565}
2566
2567/**
2568 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to
2569 * that of AA lines in the drawLines() function.  We expand the convex path by a half pixel in
2570 * screen space in all directions. However, instead of using a fragment shader to compute the
2571 * translucency of the color from its position, we simply use a varying parameter to define how far
2572 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used.
2573 *
2574 * Doesn't yet support joins, caps, or path effects.
2575 */
2576status_t OpenGLRenderer::drawConvexPath(const SkPath& path, SkPaint* paint) {
2577    VertexBuffer vertexBuffer;
2578    // TODO: try clipping large paths to viewport
2579    PathTessellator::tessellatePath(path, paint, mSnapshot->transform, vertexBuffer);
2580
2581    if (hasLayer()) {
2582        SkRect bounds = path.getBounds();
2583        PathTessellator::expandBoundsForStroke(bounds, paint, false);
2584        dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, currentTransform());
2585    }
2586
2587    return drawVertexBuffer(vertexBuffer, paint);
2588}
2589
2590/**
2591 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha
2592 * and additional geometry for defining an alpha slope perimeter.
2593 *
2594 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some
2595 * unexpected results, and may vary between hardware devices. Previously we used a varying-base
2596 * in-shader alpha region, but found it to be taxing on some GPUs.
2597 *
2598 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce
2599 * memory transfer by removing need for degenerate vertices.
2600 */
2601status_t OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
2602    if (mSnapshot->isIgnored() || count < 4) return DrawGlInfo::kStatusDone;
2603
2604    count &= ~0x3; // round down to nearest four
2605
2606    VertexBuffer buffer;
2607    SkRect bounds;
2608    PathTessellator::tessellateLines(points, count, paint, mSnapshot->transform, bounds, buffer);
2609
2610    if (quickReject(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom)) {
2611        return DrawGlInfo::kStatusDone;
2612    }
2613
2614    dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, currentTransform());
2615
2616    bool useOffset = !paint->isAntiAlias();
2617    return drawVertexBuffer(buffer, paint, useOffset);
2618}
2619
2620status_t OpenGLRenderer::drawPoints(float* points, int count, SkPaint* paint) {
2621    if (mSnapshot->isIgnored() || count < 2) return DrawGlInfo::kStatusDone;
2622
2623    count &= ~0x1; // round down to nearest two
2624
2625    VertexBuffer buffer;
2626    SkRect bounds;
2627    PathTessellator::tessellatePoints(points, count, paint, mSnapshot->transform, bounds, buffer);
2628
2629    if (quickReject(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom)) {
2630        return DrawGlInfo::kStatusDone;
2631    }
2632
2633    dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, currentTransform());
2634
2635    bool useOffset = !paint->isAntiAlias();
2636    return drawVertexBuffer(buffer, paint, useOffset);
2637}
2638
2639status_t OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
2640    // No need to check against the clip, we fill the clip region
2641    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2642
2643    Rect& clip(*mSnapshot->clipRect);
2644    clip.snapToPixelBoundaries();
2645
2646    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
2647
2648    return DrawGlInfo::kStatusDrew;
2649}
2650
2651status_t OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture,
2652        SkPaint* paint) {
2653    if (!texture) return DrawGlInfo::kStatusDone;
2654    const AutoTexture autoCleanup(texture);
2655
2656    const float x = left + texture->left - texture->offset;
2657    const float y = top + texture->top - texture->offset;
2658
2659    drawPathTexture(texture, x, y, paint);
2660
2661    return DrawGlInfo::kStatusDrew;
2662}
2663
2664status_t OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
2665        float rx, float ry, SkPaint* p) {
2666    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p) ||
2667            (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) {
2668        return DrawGlInfo::kStatusDone;
2669    }
2670
2671    if (p->getPathEffect() != 0) {
2672        mCaches.activeTexture(0);
2673        const PathTexture* texture = mCaches.pathCache.getRoundRect(
2674                right - left, bottom - top, rx, ry, p);
2675        return drawShape(left, top, texture, p);
2676    }
2677
2678    SkPath path;
2679    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2680    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2681        float outset = p->getStrokeWidth() / 2;
2682        rect.outset(outset, outset);
2683        rx += outset;
2684        ry += outset;
2685    }
2686    path.addRoundRect(rect, rx, ry);
2687    return drawConvexPath(path, p);
2688}
2689
2690status_t OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* p) {
2691    if (mSnapshot->isIgnored() || quickRejectPreStroke(x - radius, y - radius,
2692            x + radius, y + radius, p) ||
2693            (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) {
2694        return DrawGlInfo::kStatusDone;
2695    }
2696    if (p->getPathEffect() != 0) {
2697        mCaches.activeTexture(0);
2698        const PathTexture* texture = mCaches.pathCache.getCircle(radius, p);
2699        return drawShape(x - radius, y - radius, texture, p);
2700    }
2701
2702    SkPath path;
2703    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2704        path.addCircle(x, y, radius + p->getStrokeWidth() / 2);
2705    } else {
2706        path.addCircle(x, y, radius);
2707    }
2708    return drawConvexPath(path, p);
2709}
2710
2711status_t OpenGLRenderer::drawOval(float left, float top, float right, float bottom,
2712        SkPaint* p) {
2713    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p) ||
2714            (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) {
2715        return DrawGlInfo::kStatusDone;
2716    }
2717
2718    if (p->getPathEffect() != 0) {
2719        mCaches.activeTexture(0);
2720        const PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p);
2721        return drawShape(left, top, texture, p);
2722    }
2723
2724    SkPath path;
2725    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2726    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2727        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2728    }
2729    path.addOval(rect);
2730    return drawConvexPath(path, p);
2731}
2732
2733status_t OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
2734        float startAngle, float sweepAngle, bool useCenter, SkPaint* p) {
2735    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p) ||
2736            (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) {
2737        return DrawGlInfo::kStatusDone;
2738    }
2739
2740    if (fabs(sweepAngle) >= 360.0f) {
2741        return drawOval(left, top, right, bottom, p);
2742    }
2743
2744    // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180)
2745    if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != 0 || useCenter) {
2746        mCaches.activeTexture(0);
2747        const PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top,
2748                startAngle, sweepAngle, useCenter, p);
2749        return drawShape(left, top, texture, p);
2750    }
2751
2752    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2753    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2754        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2755    }
2756
2757    SkPath path;
2758    if (useCenter) {
2759        path.moveTo(rect.centerX(), rect.centerY());
2760    }
2761    path.arcTo(rect, startAngle, sweepAngle, !useCenter);
2762    if (useCenter) {
2763        path.close();
2764    }
2765    return drawConvexPath(path, p);
2766}
2767
2768// See SkPaintDefaults.h
2769#define SkPaintDefaults_MiterLimit SkIntToScalar(4)
2770
2771status_t OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
2772    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p) ||
2773            (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) {
2774        return DrawGlInfo::kStatusDone;
2775    }
2776
2777    if (p->getStyle() != SkPaint::kFill_Style) {
2778        // only fill style is supported by drawConvexPath, since others have to handle joins
2779        if (p->getPathEffect() != 0 || p->getStrokeJoin() != SkPaint::kMiter_Join ||
2780                p->getStrokeMiter() != SkPaintDefaults_MiterLimit) {
2781            mCaches.activeTexture(0);
2782            const PathTexture* texture =
2783                    mCaches.pathCache.getRect(right - left, bottom - top, p);
2784            return drawShape(left, top, texture, p);
2785        }
2786
2787        SkPath path;
2788        SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2789        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2790            rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2791        }
2792        path.addRect(rect);
2793        return drawConvexPath(path, p);
2794    }
2795
2796    if (p->isAntiAlias() && !currentTransform().isSimple()) {
2797        SkPath path;
2798        path.addRect(left, top, right, bottom);
2799        return drawConvexPath(path, p);
2800    } else {
2801        drawColorRect(left, top, right, bottom, p->getColor(), getXfermode(p->getXfermode()));
2802        return DrawGlInfo::kStatusDrew;
2803    }
2804}
2805
2806void OpenGLRenderer::drawTextShadow(SkPaint* paint, const char* text, int bytesCount, int count,
2807        const float* positions, FontRenderer& fontRenderer, int alpha, SkXfermode::Mode mode,
2808        float x, float y) {
2809    mCaches.activeTexture(0);
2810
2811    // NOTE: The drop shadow will not perform gamma correction
2812    //       if shader-based correction is enabled
2813    mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2814    const ShadowTexture* shadow = mCaches.dropShadowCache.get(
2815            paint, text, bytesCount, count, mDrawModifiers.mShadowRadius, positions);
2816    // If the drop shadow exceeds the max texture size or couldn't be
2817    // allocated, skip drawing
2818    if (!shadow) return;
2819    const AutoTexture autoCleanup(shadow);
2820
2821    const float sx = x - shadow->left + mDrawModifiers.mShadowDx;
2822    const float sy = y - shadow->top + mDrawModifiers.mShadowDy;
2823
2824    const int shadowAlpha = ((mDrawModifiers.mShadowColor >> 24) & 0xFF) * mSnapshot->alpha;
2825    int shadowColor = mDrawModifiers.mShadowColor;
2826    if (mDrawModifiers.mShader) {
2827        shadowColor = 0xffffffff;
2828    }
2829
2830    setupDraw();
2831    setupDrawWithTexture(true);
2832    setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
2833    setupDrawColorFilter();
2834    setupDrawShader();
2835    setupDrawBlending(true, mode);
2836    setupDrawProgram();
2837    setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height);
2838    setupDrawTexture(shadow->id);
2839    setupDrawPureColorUniforms();
2840    setupDrawColorFilterUniforms();
2841    setupDrawShaderUniforms();
2842    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2843
2844    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2845}
2846
2847bool OpenGLRenderer::canSkipText(const SkPaint* paint) const {
2848    float alpha = (mDrawModifiers.mHasShadow ? 1.0f : paint->getAlpha()) * mSnapshot->alpha;
2849    return alpha == 0.0f && getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode;
2850}
2851
2852status_t OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count,
2853        const float* positions, SkPaint* paint) {
2854    if (text == NULL || count == 0 || mSnapshot->isIgnored() || canSkipText(paint)) {
2855        return DrawGlInfo::kStatusDone;
2856    }
2857
2858    // NOTE: Skia does not support perspective transform on drawPosText yet
2859    if (!currentTransform().isSimple()) {
2860        return DrawGlInfo::kStatusDone;
2861    }
2862
2863    mCaches.enableScissor();
2864
2865    float x = 0.0f;
2866    float y = 0.0f;
2867    const bool pureTranslate = currentTransform().isPureTranslate();
2868    if (pureTranslate) {
2869        x = (int) floorf(x + currentTransform().getTranslateX() + 0.5f);
2870        y = (int) floorf(y + currentTransform().getTranslateY() + 0.5f);
2871    }
2872
2873    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2874    fontRenderer.setFont(paint, mat4::identity());
2875
2876    int alpha;
2877    SkXfermode::Mode mode;
2878    getAlphaAndMode(paint, &alpha, &mode);
2879
2880    if (CC_UNLIKELY(mDrawModifiers.mHasShadow)) {
2881        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2882                alpha, mode, 0.0f, 0.0f);
2883    }
2884
2885    // Pick the appropriate texture filtering
2886    bool linearFilter = currentTransform().changesBounds();
2887    if (pureTranslate && !linearFilter) {
2888        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2889    }
2890    fontRenderer.setTextureFiltering(linearFilter);
2891
2892    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
2893    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2894
2895    const bool hasActiveLayer = hasLayer();
2896
2897    TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2898    if (fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2899            positions, hasActiveLayer ? &bounds : NULL, &functor)) {
2900        if (hasActiveLayer) {
2901            if (!pureTranslate) {
2902                currentTransform().mapRect(bounds);
2903            }
2904            dirtyLayerUnchecked(bounds, getRegion());
2905        }
2906    }
2907
2908    return DrawGlInfo::kStatusDrew;
2909}
2910
2911mat4 OpenGLRenderer::findBestFontTransform(const mat4& transform) const {
2912    mat4 fontTransform;
2913    if (CC_LIKELY(transform.isPureTranslate())) {
2914        fontTransform = mat4::identity();
2915    } else {
2916        if (CC_UNLIKELY(transform.isPerspective())) {
2917            fontTransform = mat4::identity();
2918        } else {
2919            float sx, sy;
2920            currentTransform().decomposeScale(sx, sy);
2921            fontTransform.loadScale(sx, sy, 1.0f);
2922        }
2923    }
2924    return fontTransform;
2925}
2926
2927status_t OpenGLRenderer::drawText(const char* text, int bytesCount, int count, float x, float y,
2928        const float* positions, SkPaint* paint, float totalAdvance, const Rect& bounds,
2929        DrawOpMode drawOpMode) {
2930
2931    if (drawOpMode == kDrawOpMode_Immediate) {
2932        // The checks for corner-case ignorable text and quick rejection is only done for immediate
2933        // drawing as ops from DeferredDisplayList are already filtered for these
2934        if (text == NULL || count == 0 || mSnapshot->isIgnored() || canSkipText(paint) ||
2935                quickReject(bounds)) {
2936            return DrawGlInfo::kStatusDone;
2937        }
2938    }
2939
2940    const float oldX = x;
2941    const float oldY = y;
2942
2943    const mat4& transform = currentTransform();
2944    const bool pureTranslate = transform.isPureTranslate();
2945
2946    if (CC_LIKELY(pureTranslate)) {
2947        x = (int) floorf(x + transform.getTranslateX() + 0.5f);
2948        y = (int) floorf(y + transform.getTranslateY() + 0.5f);
2949    }
2950
2951    int alpha;
2952    SkXfermode::Mode mode;
2953    getAlphaAndMode(paint, &alpha, &mode);
2954
2955    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2956
2957    if (CC_UNLIKELY(mDrawModifiers.mHasShadow)) {
2958        fontRenderer.setFont(paint, mat4::identity());
2959        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2960                alpha, mode, oldX, oldY);
2961    }
2962
2963    const bool hasActiveLayer = hasLayer();
2964
2965    // We only pass a partial transform to the font renderer. That partial
2966    // matrix defines how glyphs are rasterized. Typically we want glyphs
2967    // to be rasterized at their final size on screen, which means the partial
2968    // matrix needs to take the scale factor into account.
2969    // When a partial matrix is used to transform glyphs during rasterization,
2970    // the mesh is generated with the inverse transform (in the case of scale,
2971    // the mesh is generated at 1.0 / scale for instance.) This allows us to
2972    // apply the full transform matrix at draw time in the vertex shader.
2973    // Applying the full matrix in the shader is the easiest way to handle
2974    // rotation and perspective and allows us to always generated quads in the
2975    // font renderer which greatly simplifies the code, clipping in particular.
2976    mat4 fontTransform = findBestFontTransform(transform);
2977    fontRenderer.setFont(paint, fontTransform);
2978
2979    // Pick the appropriate texture filtering
2980    bool linearFilter = !pureTranslate || fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2981    fontRenderer.setTextureFiltering(linearFilter);
2982
2983    // TODO: Implement better clipping for scaled/rotated text
2984    const Rect* clip = !pureTranslate ? NULL : mSnapshot->clipRect;
2985    Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2986
2987    bool status;
2988    TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2989
2990    // don't call issuedrawcommand, do it at end of batch
2991    bool forceFinish = (drawOpMode != kDrawOpMode_Defer);
2992    if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) {
2993        SkPaint paintCopy(*paint);
2994        paintCopy.setTextAlign(SkPaint::kLeft_Align);
2995        status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y,
2996                positions, hasActiveLayer ? &layerBounds : NULL, &functor, forceFinish);
2997    } else {
2998        status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2999                positions, hasActiveLayer ? &layerBounds : NULL, &functor, forceFinish);
3000    }
3001
3002    if ((status || drawOpMode != kDrawOpMode_Immediate) && hasActiveLayer) {
3003        if (!pureTranslate) {
3004            transform.mapRect(layerBounds);
3005        }
3006        dirtyLayerUnchecked(layerBounds, getRegion());
3007    }
3008
3009    drawTextDecorations(text, bytesCount, totalAdvance, oldX, oldY, paint);
3010
3011    return DrawGlInfo::kStatusDrew;
3012}
3013
3014status_t OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count, SkPath* path,
3015        float hOffset, float vOffset, SkPaint* paint) {
3016    if (text == NULL || count == 0 || mSnapshot->isIgnored() || canSkipText(paint)) {
3017        return DrawGlInfo::kStatusDone;
3018    }
3019
3020    // TODO: avoid scissor by calculating maximum bounds using path bounds + font metrics
3021    mCaches.enableScissor();
3022
3023    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
3024    fontRenderer.setFont(paint, mat4::identity());
3025    fontRenderer.setTextureFiltering(true);
3026
3027    int alpha;
3028    SkXfermode::Mode mode;
3029    getAlphaAndMode(paint, &alpha, &mode);
3030    TextSetupFunctor functor(this, 0.0f, 0.0f, false, alpha, mode, paint);
3031
3032    const Rect* clip = &mSnapshot->getLocalClip();
3033    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
3034
3035    const bool hasActiveLayer = hasLayer();
3036
3037    if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path,
3038            hOffset, vOffset, hasActiveLayer ? &bounds : NULL, &functor)) {
3039        if (hasActiveLayer) {
3040            currentTransform().mapRect(bounds);
3041            dirtyLayerUnchecked(bounds, getRegion());
3042        }
3043    }
3044
3045    return DrawGlInfo::kStatusDrew;
3046}
3047
3048status_t OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
3049    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
3050
3051    mCaches.activeTexture(0);
3052
3053    const PathTexture* texture = mCaches.pathCache.get(path, paint);
3054    if (!texture) return DrawGlInfo::kStatusDone;
3055    const AutoTexture autoCleanup(texture);
3056
3057    const float x = texture->left - texture->offset;
3058    const float y = texture->top - texture->offset;
3059
3060    drawPathTexture(texture, x, y, paint);
3061
3062    return DrawGlInfo::kStatusDrew;
3063}
3064
3065status_t OpenGLRenderer::drawLayer(Layer* layer, float x, float y) {
3066    if (!layer) {
3067        return DrawGlInfo::kStatusDone;
3068    }
3069
3070    mat4* transform = NULL;
3071    if (layer->isTextureLayer()) {
3072        transform = &layer->getTransform();
3073        if (!transform->isIdentity()) {
3074            save(0);
3075            currentTransform().multiply(*transform);
3076        }
3077    }
3078
3079    bool clipRequired = false;
3080    const bool rejected = quickRejectNoScissor(x, y,
3081            x + layer->layer.getWidth(), y + layer->layer.getHeight(), false, &clipRequired);
3082
3083    if (rejected) {
3084        if (transform && !transform->isIdentity()) {
3085            restore();
3086        }
3087        return DrawGlInfo::kStatusDone;
3088    }
3089
3090    updateLayer(layer, true);
3091
3092    mCaches.setScissorEnabled(mScissorOptimizationDisabled || clipRequired);
3093    mCaches.activeTexture(0);
3094
3095    if (CC_LIKELY(!layer->region.isEmpty())) {
3096        SkiaColorFilter* oldFilter = mDrawModifiers.mColorFilter;
3097        mDrawModifiers.mColorFilter = layer->getColorFilter();
3098
3099        if (layer->region.isRect()) {
3100            DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
3101                    composeLayerRect(layer, layer->regionRect));
3102        } else if (layer->mesh) {
3103            const float a = getLayerAlpha(layer);
3104            setupDraw();
3105            setupDrawWithTexture();
3106            setupDrawColor(a, a, a, a);
3107            setupDrawColorFilter();
3108            setupDrawBlending(layer->isBlend() || a < 1.0f, layer->getMode(), false);
3109            setupDrawProgram();
3110            setupDrawPureColorUniforms();
3111            setupDrawColorFilterUniforms();
3112            setupDrawTexture(layer->getTexture());
3113            if (CC_LIKELY(currentTransform().isPureTranslate())) {
3114                int tx = (int) floorf(x + currentTransform().getTranslateX() + 0.5f);
3115                int ty = (int) floorf(y + currentTransform().getTranslateY() + 0.5f);
3116
3117                layer->setFilter(GL_NEAREST);
3118                setupDrawModelViewTranslate(tx, ty,
3119                        tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true);
3120            } else {
3121                layer->setFilter(GL_LINEAR);
3122                setupDrawModelViewTranslate(x, y,
3123                        x + layer->layer.getWidth(), y + layer->layer.getHeight());
3124            }
3125
3126            TextureVertex* mesh = &layer->mesh[0];
3127            GLsizei elementsCount = layer->meshElementCount;
3128
3129            while (elementsCount > 0) {
3130                GLsizei drawCount = min(elementsCount, (GLsizei) gMaxNumberOfQuads * 6);
3131
3132                setupDrawMeshIndices(&mesh[0].position[0], &mesh[0].texture[0]);
3133                DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
3134                        glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, NULL));
3135
3136                elementsCount -= drawCount;
3137                // Though there are 4 vertices in a quad, we use 6 indices per
3138                // quad to draw with GL_TRIANGLES
3139                mesh += (drawCount / 6) * 4;
3140            }
3141
3142#if DEBUG_LAYERS_AS_REGIONS
3143            drawRegionRects(layer->region);
3144#endif
3145        }
3146
3147        mDrawModifiers.mColorFilter = oldFilter;
3148
3149        if (layer->debugDrawUpdate) {
3150            layer->debugDrawUpdate = false;
3151            drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(),
3152                    0x7f00ff00, SkXfermode::kSrcOver_Mode);
3153        }
3154    }
3155    layer->hasDrawnSinceUpdate = true;
3156
3157    if (transform && !transform->isIdentity()) {
3158        restore();
3159    }
3160
3161    return DrawGlInfo::kStatusDrew;
3162}
3163
3164///////////////////////////////////////////////////////////////////////////////
3165// Shaders
3166///////////////////////////////////////////////////////////////////////////////
3167
3168void OpenGLRenderer::resetShader() {
3169    mDrawModifiers.mShader = NULL;
3170}
3171
3172void OpenGLRenderer::setupShader(SkiaShader* shader) {
3173    mDrawModifiers.mShader = shader;
3174    if (mDrawModifiers.mShader) {
3175        mDrawModifiers.mShader->setCaches(mCaches);
3176    }
3177}
3178
3179///////////////////////////////////////////////////////////////////////////////
3180// Color filters
3181///////////////////////////////////////////////////////////////////////////////
3182
3183void OpenGLRenderer::resetColorFilter() {
3184    mDrawModifiers.mColorFilter = NULL;
3185}
3186
3187void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
3188    mDrawModifiers.mColorFilter = filter;
3189}
3190
3191///////////////////////////////////////////////////////////////////////////////
3192// Drop shadow
3193///////////////////////////////////////////////////////////////////////////////
3194
3195void OpenGLRenderer::resetShadow() {
3196    mDrawModifiers.mHasShadow = false;
3197}
3198
3199void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
3200    mDrawModifiers.mHasShadow = true;
3201    mDrawModifiers.mShadowRadius = radius;
3202    mDrawModifiers.mShadowDx = dx;
3203    mDrawModifiers.mShadowDy = dy;
3204    mDrawModifiers.mShadowColor = color;
3205}
3206
3207///////////////////////////////////////////////////////////////////////////////
3208// Draw filters
3209///////////////////////////////////////////////////////////////////////////////
3210
3211void OpenGLRenderer::resetPaintFilter() {
3212    // when clearing the PaintFilter, the masks should also be cleared for simple DrawModifier
3213    // comparison, see MergingDrawBatch::canMergeWith
3214    mDrawModifiers.mHasDrawFilter = false;
3215    mDrawModifiers.mPaintFilterClearBits = 0;
3216    mDrawModifiers.mPaintFilterSetBits = 0;
3217}
3218
3219void OpenGLRenderer::setupPaintFilter(int clearBits, int setBits) {
3220    mDrawModifiers.mHasDrawFilter = true;
3221    mDrawModifiers.mPaintFilterClearBits = clearBits & SkPaint::kAllFlags;
3222    mDrawModifiers.mPaintFilterSetBits = setBits & SkPaint::kAllFlags;
3223}
3224
3225SkPaint* OpenGLRenderer::filterPaint(SkPaint* paint) {
3226    if (CC_LIKELY(!mDrawModifiers.mHasDrawFilter || !paint)) {
3227        return paint;
3228    }
3229
3230    uint32_t flags = paint->getFlags();
3231
3232    mFilteredPaint = *paint;
3233    mFilteredPaint.setFlags((flags & ~mDrawModifiers.mPaintFilterClearBits) |
3234            mDrawModifiers.mPaintFilterSetBits);
3235
3236    return &mFilteredPaint;
3237}
3238
3239///////////////////////////////////////////////////////////////////////////////
3240// Drawing implementation
3241///////////////////////////////////////////////////////////////////////////////
3242
3243Texture* OpenGLRenderer::getTexture(SkBitmap* bitmap) {
3244    Texture* texture = mCaches.assetAtlas.getEntryTexture(bitmap);
3245    if (!texture) {
3246        return mCaches.textureCache.get(bitmap);
3247    }
3248    return texture;
3249}
3250
3251void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
3252        float x, float y, SkPaint* paint) {
3253    if (quickReject(x, y, x + texture->width, y + texture->height)) {
3254        return;
3255    }
3256
3257    int alpha;
3258    SkXfermode::Mode mode;
3259    getAlphaAndMode(paint, &alpha, &mode);
3260
3261    setupDraw();
3262    setupDrawWithTexture(true);
3263    setupDrawAlpha8Color(paint->getColor(), alpha);
3264    setupDrawColorFilter();
3265    setupDrawShader();
3266    setupDrawBlending(true, mode);
3267    setupDrawProgram();
3268    setupDrawModelView(x, y, x + texture->width, y + texture->height);
3269    setupDrawTexture(texture->id);
3270    setupDrawPureColorUniforms();
3271    setupDrawColorFilterUniforms();
3272    setupDrawShaderUniforms();
3273    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
3274
3275    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
3276}
3277
3278// Same values used by Skia
3279#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
3280#define kStdUnderline_Offset    (1.0f / 9.0f)
3281#define kStdUnderline_Thickness (1.0f / 18.0f)
3282
3283void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float underlineWidth,
3284        float x, float y, SkPaint* paint) {
3285    // Handle underline and strike-through
3286    uint32_t flags = paint->getFlags();
3287    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
3288        SkPaint paintCopy(*paint);
3289
3290        if (CC_LIKELY(underlineWidth > 0.0f)) {
3291            const float textSize = paintCopy.getTextSize();
3292            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
3293
3294            const float left = x;
3295            float top = 0.0f;
3296
3297            int linesCount = 0;
3298            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
3299            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
3300
3301            const int pointsCount = 4 * linesCount;
3302            float points[pointsCount];
3303            int currentPoint = 0;
3304
3305            if (flags & SkPaint::kUnderlineText_Flag) {
3306                top = y + textSize * kStdUnderline_Offset;
3307                points[currentPoint++] = left;
3308                points[currentPoint++] = top;
3309                points[currentPoint++] = left + underlineWidth;
3310                points[currentPoint++] = top;
3311            }
3312
3313            if (flags & SkPaint::kStrikeThruText_Flag) {
3314                top = y + textSize * kStdStrikeThru_Offset;
3315                points[currentPoint++] = left;
3316                points[currentPoint++] = top;
3317                points[currentPoint++] = left + underlineWidth;
3318                points[currentPoint++] = top;
3319            }
3320
3321            paintCopy.setStrokeWidth(strokeWidth);
3322
3323            drawLines(&points[0], pointsCount, &paintCopy);
3324        }
3325    }
3326}
3327
3328status_t OpenGLRenderer::drawRects(const float* rects, int count, SkPaint* paint) {
3329    if (mSnapshot->isIgnored()) {
3330        return DrawGlInfo::kStatusDone;
3331    }
3332
3333    int color = paint->getColor();
3334    // If a shader is set, preserve only the alpha
3335    if (mDrawModifiers.mShader) {
3336        color |= 0x00ffffff;
3337    }
3338    SkXfermode::Mode mode = getXfermode(paint->getXfermode());
3339
3340    return drawColorRects(rects, count, color, mode);
3341}
3342
3343status_t OpenGLRenderer::drawColorRects(const float* rects, int count, int color,
3344        SkXfermode::Mode mode, bool ignoreTransform, bool dirty, bool clip) {
3345    if (count == 0) {
3346        return DrawGlInfo::kStatusDone;
3347    }
3348
3349    float left = FLT_MAX;
3350    float top = FLT_MAX;
3351    float right = FLT_MIN;
3352    float bottom = FLT_MIN;
3353
3354    Vertex mesh[count];
3355    Vertex* vertex = mesh;
3356
3357    for (int index = 0; index < count; index += 4) {
3358        float l = rects[index + 0];
3359        float t = rects[index + 1];
3360        float r = rects[index + 2];
3361        float b = rects[index + 3];
3362
3363        Vertex::set(vertex++, l, t);
3364        Vertex::set(vertex++, r, t);
3365        Vertex::set(vertex++, l, b);
3366        Vertex::set(vertex++, r, b);
3367
3368        left = fminf(left, l);
3369        top = fminf(top, t);
3370        right = fmaxf(right, r);
3371        bottom = fmaxf(bottom, b);
3372    }
3373
3374    if (clip && quickReject(left, top, right, bottom)) {
3375        return DrawGlInfo::kStatusDone;
3376    }
3377
3378    setupDraw();
3379    setupDrawNoTexture();
3380    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
3381    setupDrawShader();
3382    setupDrawColorFilter();
3383    setupDrawBlending(mode);
3384    setupDrawProgram();
3385    setupDrawDirtyRegionsDisabled();
3386    setupDrawModelView(0.0f, 0.0f, 1.0f, 1.0f, ignoreTransform, true);
3387    setupDrawColorUniforms();
3388    setupDrawShaderUniforms();
3389    setupDrawColorFilterUniforms();
3390
3391    if (dirty && hasLayer()) {
3392        dirtyLayer(left, top, right, bottom, currentTransform());
3393    }
3394
3395    drawIndexedQuads(&mesh[0], count / 4);
3396
3397    return DrawGlInfo::kStatusDrew;
3398}
3399
3400void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
3401        int color, SkXfermode::Mode mode, bool ignoreTransform) {
3402    // If a shader is set, preserve only the alpha
3403    if (mDrawModifiers.mShader) {
3404        color |= 0x00ffffff;
3405    }
3406
3407    setupDraw();
3408    setupDrawNoTexture();
3409    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
3410    setupDrawShader();
3411    setupDrawColorFilter();
3412    setupDrawBlending(mode);
3413    setupDrawProgram();
3414    setupDrawModelView(left, top, right, bottom, ignoreTransform);
3415    setupDrawColorUniforms();
3416    setupDrawShaderUniforms(ignoreTransform);
3417    setupDrawColorFilterUniforms();
3418    setupDrawSimpleMesh();
3419
3420    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
3421}
3422
3423void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3424        Texture* texture, SkPaint* paint) {
3425    int alpha;
3426    SkXfermode::Mode mode;
3427    getAlphaAndMode(paint, &alpha, &mode);
3428
3429    texture->setWrap(GL_CLAMP_TO_EDGE, true);
3430
3431    GLvoid* vertices = (GLvoid*) NULL;
3432    GLvoid* texCoords = (GLvoid*) gMeshTextureOffset;
3433
3434    if (texture->uvMapper) {
3435        vertices = &mMeshVertices[0].position[0];
3436        texCoords = &mMeshVertices[0].texture[0];
3437
3438        Rect uvs(0.0f, 0.0f, 1.0f, 1.0f);
3439        texture->uvMapper->map(uvs);
3440
3441        resetDrawTextureTexCoords(uvs.left, uvs.top, uvs.right, uvs.bottom);
3442    }
3443
3444    if (CC_LIKELY(currentTransform().isPureTranslate())) {
3445        const float x = (int) floorf(left + currentTransform().getTranslateX() + 0.5f);
3446        const float y = (int) floorf(top + currentTransform().getTranslateY() + 0.5f);
3447
3448        texture->setFilter(GL_NEAREST, true);
3449        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
3450                alpha / 255.0f, mode, texture->blend, vertices, texCoords,
3451                GL_TRIANGLE_STRIP, gMeshCount, false, true);
3452    } else {
3453        texture->setFilter(FILTER(paint), true);
3454        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
3455                texture->blend, vertices, texCoords, GL_TRIANGLE_STRIP, gMeshCount);
3456    }
3457
3458    if (texture->uvMapper) {
3459        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
3460    }
3461}
3462
3463void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3464        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
3465    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
3466            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
3467}
3468
3469void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
3470        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
3471        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3472        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
3473
3474    setupDraw();
3475    setupDrawWithTexture();
3476    setupDrawColor(alpha, alpha, alpha, alpha);
3477    setupDrawColorFilter();
3478    setupDrawBlending(blend, mode, swapSrcDst);
3479    setupDrawProgram();
3480    if (!dirty) setupDrawDirtyRegionsDisabled();
3481    if (!ignoreScale) {
3482        setupDrawModelView(left, top, right, bottom, ignoreTransform);
3483    } else {
3484        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
3485    }
3486    setupDrawTexture(texture);
3487    setupDrawPureColorUniforms();
3488    setupDrawColorFilterUniforms();
3489    setupDrawMesh(vertices, texCoords, vbo);
3490
3491    glDrawArrays(drawMode, 0, elementsCount);
3492}
3493
3494void OpenGLRenderer::drawIndexedTextureMesh(float left, float top, float right, float bottom,
3495        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
3496        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3497        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
3498
3499    setupDraw();
3500    setupDrawWithTexture();
3501    setupDrawColor(alpha, alpha, alpha, alpha);
3502    setupDrawColorFilter();
3503    setupDrawBlending(blend, mode, swapSrcDst);
3504    setupDrawProgram();
3505    if (!dirty) setupDrawDirtyRegionsDisabled();
3506    if (!ignoreScale) {
3507        setupDrawModelView(left, top, right, bottom, ignoreTransform);
3508    } else {
3509        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
3510    }
3511    setupDrawTexture(texture);
3512    setupDrawPureColorUniforms();
3513    setupDrawColorFilterUniforms();
3514    setupDrawMeshIndices(vertices, texCoords, vbo);
3515
3516    glDrawElements(drawMode, elementsCount, GL_UNSIGNED_SHORT, NULL);
3517}
3518
3519void OpenGLRenderer::drawAlpha8TextureMesh(float left, float top, float right, float bottom,
3520        GLuint texture, bool hasColor, int color, int alpha, SkXfermode::Mode mode,
3521        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3522        bool ignoreTransform, bool ignoreScale, bool dirty) {
3523
3524    setupDraw();
3525    setupDrawWithTexture(true);
3526    if (hasColor) {
3527        setupDrawAlpha8Color(color, alpha);
3528    }
3529    setupDrawColorFilter();
3530    setupDrawShader();
3531    setupDrawBlending(true, mode);
3532    setupDrawProgram();
3533    if (!dirty) setupDrawDirtyRegionsDisabled();
3534    if (!ignoreScale) {
3535        setupDrawModelView(left, top, right, bottom, ignoreTransform);
3536    } else {
3537        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
3538    }
3539    setupDrawTexture(texture);
3540    setupDrawPureColorUniforms();
3541    setupDrawColorFilterUniforms();
3542    setupDrawShaderUniforms();
3543    setupDrawMesh(vertices, texCoords);
3544
3545    glDrawArrays(drawMode, 0, elementsCount);
3546}
3547
3548void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
3549        ProgramDescription& description, bool swapSrcDst) {
3550    if (mCountOverdraw) {
3551        if (!mCaches.blend) glEnable(GL_BLEND);
3552        if (mCaches.lastSrcMode != GL_ONE || mCaches.lastDstMode != GL_ONE) {
3553            glBlendFunc(GL_ONE, GL_ONE);
3554        }
3555
3556        mCaches.blend = true;
3557        mCaches.lastSrcMode = GL_ONE;
3558        mCaches.lastDstMode = GL_ONE;
3559
3560        return;
3561    }
3562
3563    blend = blend || mode != SkXfermode::kSrcOver_Mode;
3564
3565    if (blend) {
3566        // These blend modes are not supported by OpenGL directly and have
3567        // to be implemented using shaders. Since the shader will perform
3568        // the blending, turn blending off here
3569        // If the blend mode cannot be implemented using shaders, fall
3570        // back to the default SrcOver blend mode instead
3571        if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) {
3572            if (CC_UNLIKELY(mExtensions.hasFramebufferFetch())) {
3573                description.framebufferMode = mode;
3574                description.swapSrcDst = swapSrcDst;
3575
3576                if (mCaches.blend) {
3577                    glDisable(GL_BLEND);
3578                    mCaches.blend = false;
3579                }
3580
3581                return;
3582            } else {
3583                mode = SkXfermode::kSrcOver_Mode;
3584            }
3585        }
3586
3587        if (!mCaches.blend) {
3588            glEnable(GL_BLEND);
3589        }
3590
3591        GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
3592        GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
3593
3594        if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
3595            glBlendFunc(sourceMode, destMode);
3596            mCaches.lastSrcMode = sourceMode;
3597            mCaches.lastDstMode = destMode;
3598        }
3599    } else if (mCaches.blend) {
3600        glDisable(GL_BLEND);
3601    }
3602    mCaches.blend = blend;
3603}
3604
3605bool OpenGLRenderer::useProgram(Program* program) {
3606    if (!program->isInUse()) {
3607        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
3608        program->use();
3609        mCaches.currentProgram = program;
3610        return false;
3611    }
3612    return true;
3613}
3614
3615void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
3616    TextureVertex* v = &mMeshVertices[0];
3617    TextureVertex::setUV(v++, u1, v1);
3618    TextureVertex::setUV(v++, u2, v1);
3619    TextureVertex::setUV(v++, u1, v2);
3620    TextureVertex::setUV(v++, u2, v2);
3621}
3622
3623void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) const {
3624    getAlphaAndModeDirect(paint, alpha,  mode);
3625    if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) {
3626        // if drawing a layer, ignore the paint's alpha
3627        *alpha = mDrawModifiers.mOverrideLayerAlpha * 255;
3628    }
3629    *alpha *= mSnapshot->alpha;
3630}
3631
3632float OpenGLRenderer::getLayerAlpha(Layer* layer) const {
3633    float alpha;
3634    if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) {
3635        alpha = mDrawModifiers.mOverrideLayerAlpha;
3636    } else {
3637        alpha = layer->getAlpha() / 255.0f;
3638    }
3639    return alpha * mSnapshot->alpha;
3640}
3641
3642}; // namespace uirenderer
3643}; // namespace android
3644