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