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