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