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