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