OpenGLRenderer.cpp revision 9757ac0b9d62f6aea5e47cfb375f445c78bb7897
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->getForceFilter() &&
1072            layer->getWidth() == (uint32_t) rect.getWidth() &&
1073            layer->getHeight() == (uint32_t) rect.getHeight()) {
1074        const float x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f);
1075        const float y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f);
1076
1077        layer->setFilter(GL_NEAREST);
1078        setupDrawModelView(kModelViewMode_TranslateAndScale, false,
1079                x, y, x + rect.getWidth(), y + rect.getHeight(), true);
1080    } else {
1081        layer->setFilter(GL_LINEAR);
1082        setupDrawModelView(kModelViewMode_TranslateAndScale, false,
1083                rect.left, rect.top, rect.right, rect.bottom);
1084    }
1085    setupDrawTextureTransformUniforms(layer->getTexTransform());
1086    setupDrawMesh(&mMeshVertices[0].x, &mMeshVertices[0].u);
1087
1088    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1089}
1090
1091void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
1092    if (!layer->isTextureLayer()) {
1093        const Rect& texCoords = layer->texCoords;
1094        resetDrawTextureTexCoords(texCoords.left, texCoords.top,
1095                texCoords.right, texCoords.bottom);
1096
1097        float x = rect.left;
1098        float y = rect.top;
1099        bool simpleTransform = currentTransform()->isPureTranslate() &&
1100                layer->getWidth() == (uint32_t) rect.getWidth() &&
1101                layer->getHeight() == (uint32_t) rect.getHeight();
1102
1103        if (simpleTransform) {
1104            // When we're swapping, the layer is already in screen coordinates
1105            if (!swap) {
1106                x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f);
1107                y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f);
1108            }
1109
1110            layer->setFilter(GL_NEAREST, true);
1111        } else {
1112            layer->setFilter(GL_LINEAR, true);
1113        }
1114
1115        SkPaint layerPaint;
1116        layerPaint.setAlpha(getLayerAlpha(layer) * 255);
1117        layerPaint.setXfermodeMode(layer->getMode());
1118        layerPaint.setColorFilter(layer->getColorFilter());
1119
1120        bool blend = layer->isBlend() || getLayerAlpha(layer) < 1.0f;
1121        drawTextureMesh(x, y, x + rect.getWidth(), y + rect.getHeight(),
1122                layer->getTexture(), &layerPaint, blend,
1123                &mMeshVertices[0].x, &mMeshVertices[0].u,
1124                GL_TRIANGLE_STRIP, gMeshCount, swap, swap || simpleTransform);
1125
1126        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1127    } else {
1128        resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f);
1129        drawTextureLayer(layer, rect);
1130        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1131    }
1132}
1133
1134/**
1135 * Issues the command X, and if we're composing a save layer to the fbo or drawing a newly updated
1136 * hardware layer with overdraw debug on, draws again to the stencil only, so that these draw
1137 * operations are correctly counted twice for overdraw. NOTE: assumes composeLayerRegion only used
1138 * by saveLayer's restore
1139 */
1140#define DRAW_DOUBLE_STENCIL_IF(COND, DRAW_COMMAND) {                             \
1141        DRAW_COMMAND;                                                            \
1142        if (CC_UNLIKELY(mCaches.debugOverdraw && getTargetFbo() == 0 && COND)) { \
1143            glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);                 \
1144            DRAW_COMMAND;                                                        \
1145            glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);                     \
1146        }                                                                        \
1147    }
1148
1149#define DRAW_DOUBLE_STENCIL(DRAW_COMMAND) DRAW_DOUBLE_STENCIL_IF(true, DRAW_COMMAND)
1150
1151void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
1152    if (layer->region.isRect()) {
1153        layer->setRegionAsRect();
1154
1155        DRAW_DOUBLE_STENCIL(composeLayerRect(layer, layer->regionRect));
1156
1157        layer->region.clear();
1158        return;
1159    }
1160
1161    if (CC_LIKELY(!layer->region.isEmpty())) {
1162        size_t count;
1163        const android::Rect* rects;
1164        Region safeRegion;
1165        if (CC_LIKELY(hasRectToRectTransform())) {
1166            rects = layer->region.getArray(&count);
1167        } else {
1168            safeRegion = Region::createTJunctionFreeRegion(layer->region);
1169            rects = safeRegion.getArray(&count);
1170        }
1171
1172        const float alpha = getLayerAlpha(layer);
1173        const float texX = 1.0f / float(layer->getWidth());
1174        const float texY = 1.0f / float(layer->getHeight());
1175        const float height = rect.getHeight();
1176
1177        setupDraw();
1178
1179        // We must get (and therefore bind) the region mesh buffer
1180        // after we setup drawing in case we need to mess with the
1181        // stencil buffer in setupDraw()
1182        TextureVertex* mesh = mCaches.getRegionMesh();
1183        uint32_t numQuads = 0;
1184
1185        setupDrawWithTexture();
1186        setupDrawColor(alpha, alpha, alpha, alpha);
1187        setupDrawColorFilter(layer->getColorFilter());
1188        setupDrawBlending(layer);
1189        setupDrawProgram();
1190        setupDrawDirtyRegionsDisabled();
1191        setupDrawPureColorUniforms();
1192        setupDrawColorFilterUniforms(layer->getColorFilter());
1193        setupDrawTexture(layer->getTexture());
1194        if (currentTransform()->isPureTranslate()) {
1195            const float x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f);
1196            const float y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f);
1197
1198            layer->setFilter(GL_NEAREST);
1199            setupDrawModelView(kModelViewMode_Translate, false,
1200                    x, y, x + rect.getWidth(), y + rect.getHeight(), true);
1201        } else {
1202            layer->setFilter(GL_LINEAR);
1203            setupDrawModelView(kModelViewMode_Translate, false,
1204                    rect.left, rect.top, rect.right, rect.bottom);
1205        }
1206        setupDrawMeshIndices(&mesh[0].x, &mesh[0].u);
1207
1208        for (size_t i = 0; i < count; i++) {
1209            const android::Rect* r = &rects[i];
1210
1211            const float u1 = r->left * texX;
1212            const float v1 = (height - r->top) * texY;
1213            const float u2 = r->right * texX;
1214            const float v2 = (height - r->bottom) * texY;
1215
1216            // TODO: Reject quads outside of the clip
1217            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
1218            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
1219            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
1220            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
1221
1222            numQuads++;
1223
1224            if (numQuads >= gMaxNumberOfQuads) {
1225                DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6,
1226                                GL_UNSIGNED_SHORT, NULL));
1227                numQuads = 0;
1228                mesh = mCaches.getRegionMesh();
1229            }
1230        }
1231
1232        if (numQuads > 0) {
1233            DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6,
1234                            GL_UNSIGNED_SHORT, NULL));
1235        }
1236
1237#if DEBUG_LAYERS_AS_REGIONS
1238        drawRegionRectsDebug(layer->region);
1239#endif
1240
1241        layer->region.clear();
1242    }
1243}
1244
1245#if DEBUG_LAYERS_AS_REGIONS
1246void OpenGLRenderer::drawRegionRectsDebug(const Region& region) {
1247    size_t count;
1248    const android::Rect* rects = region.getArray(&count);
1249
1250    uint32_t colors[] = {
1251            0x7fff0000, 0x7f00ff00,
1252            0x7f0000ff, 0x7fff00ff,
1253    };
1254
1255    int offset = 0;
1256    int32_t top = rects[0].top;
1257
1258    for (size_t i = 0; i < count; i++) {
1259        if (top != rects[i].top) {
1260            offset ^= 0x2;
1261            top = rects[i].top;
1262        }
1263
1264        SkPaint paint;
1265        paint.setColor(colors[offset + (i & 0x1)]);
1266        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
1267        drawColorRect(r.left, r.top, r.right, r.bottom, paint);
1268    }
1269}
1270#endif
1271
1272void OpenGLRenderer::drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty) {
1273    Vector<float> rects;
1274
1275    SkRegion::Iterator it(region);
1276    while (!it.done()) {
1277        const SkIRect& r = it.rect();
1278        rects.push(r.fLeft);
1279        rects.push(r.fTop);
1280        rects.push(r.fRight);
1281        rects.push(r.fBottom);
1282        it.next();
1283    }
1284
1285    drawColorRects(rects.array(), rects.size(), &paint, true, dirty, false);
1286}
1287
1288void OpenGLRenderer::dirtyLayer(const float left, const float top,
1289        const float right, const float bottom, const mat4 transform) {
1290    if (hasLayer()) {
1291        Rect bounds(left, top, right, bottom);
1292        transform.mapRect(bounds);
1293        dirtyLayerUnchecked(bounds, getRegion());
1294    }
1295}
1296
1297void OpenGLRenderer::dirtyLayer(const float left, const float top,
1298        const float right, const float bottom) {
1299    if (hasLayer()) {
1300        Rect bounds(left, top, right, bottom);
1301        dirtyLayerUnchecked(bounds, getRegion());
1302    }
1303}
1304
1305void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
1306    if (bounds.intersect(*currentClipRect())) {
1307        bounds.snapToPixelBoundaries();
1308        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
1309        if (!dirty.isEmpty()) {
1310            region->orSelf(dirty);
1311        }
1312    }
1313}
1314
1315void OpenGLRenderer::issueIndexedQuadDraw(Vertex* mesh, GLsizei quadsCount) {
1316    GLsizei elementsCount = quadsCount * 6;
1317    while (elementsCount > 0) {
1318        GLsizei drawCount = min(elementsCount, (GLsizei) gMaxNumberOfQuads * 6);
1319
1320        setupDrawIndexedVertices(&mesh[0].x);
1321        glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, NULL);
1322
1323        elementsCount -= drawCount;
1324        // Though there are 4 vertices in a quad, we use 6 indices per
1325        // quad to draw with GL_TRIANGLES
1326        mesh += (drawCount / 6) * 4;
1327    }
1328}
1329
1330void OpenGLRenderer::clearLayerRegions() {
1331    const size_t count = mLayers.size();
1332    if (count == 0) return;
1333
1334    if (!currentSnapshot()->isIgnored()) {
1335        // Doing several glScissor/glClear here can negatively impact
1336        // GPUs with a tiler architecture, instead we draw quads with
1337        // the Clear blending mode
1338
1339        // The list contains bounds that have already been clipped
1340        // against their initial clip rect, and the current clip
1341        // is likely different so we need to disable clipping here
1342        bool scissorChanged = mCaches.disableScissor();
1343
1344        Vertex mesh[count * 4];
1345        Vertex* vertex = mesh;
1346
1347        for (uint32_t i = 0; i < count; i++) {
1348            Rect* bounds = mLayers.itemAt(i);
1349
1350            Vertex::set(vertex++, bounds->left, bounds->top);
1351            Vertex::set(vertex++, bounds->right, bounds->top);
1352            Vertex::set(vertex++, bounds->left, bounds->bottom);
1353            Vertex::set(vertex++, bounds->right, bounds->bottom);
1354
1355            delete bounds;
1356        }
1357        // We must clear the list of dirty rects before we
1358        // call setupDraw() to prevent stencil setup to do
1359        // the same thing again
1360        mLayers.clear();
1361
1362        SkPaint clearPaint;
1363        clearPaint.setXfermodeMode(SkXfermode::kClear_Mode);
1364
1365        setupDraw(false);
1366        setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f);
1367        setupDrawBlending(&clearPaint, true);
1368        setupDrawProgram();
1369        setupDrawPureColorUniforms();
1370        setupDrawModelView(kModelViewMode_Translate, false,
1371                0.0f, 0.0f, 0.0f, 0.0f, true);
1372
1373        issueIndexedQuadDraw(&mesh[0], count);
1374
1375        if (scissorChanged) mCaches.enableScissor();
1376    } else {
1377        for (uint32_t i = 0; i < count; i++) {
1378            delete mLayers.itemAt(i);
1379        }
1380        mLayers.clear();
1381    }
1382}
1383
1384///////////////////////////////////////////////////////////////////////////////
1385// State Deferral
1386///////////////////////////////////////////////////////////////////////////////
1387
1388bool OpenGLRenderer::storeDisplayState(DeferredDisplayState& state, int stateDeferFlags) {
1389    const Rect* currentClip = currentClipRect();
1390    const mat4* currentMatrix = currentTransform();
1391
1392    if (stateDeferFlags & kStateDeferFlag_Draw) {
1393        // state has bounds initialized in local coordinates
1394        if (!state.mBounds.isEmpty()) {
1395            currentMatrix->mapRect(state.mBounds);
1396            Rect clippedBounds(state.mBounds);
1397            // NOTE: if we ever want to use this clipping info to drive whether the scissor
1398            // is used, it should more closely duplicate the quickReject logic (in how it uses
1399            // snapToPixelBoundaries)
1400
1401            if(!clippedBounds.intersect(*currentClip)) {
1402                // quick rejected
1403                return true;
1404            }
1405
1406            state.mClipSideFlags = kClipSide_None;
1407            if (!currentClip->contains(state.mBounds)) {
1408                int& flags = state.mClipSideFlags;
1409                // op partially clipped, so record which sides are clipped for clip-aware merging
1410                if (currentClip->left > state.mBounds.left) flags |= kClipSide_Left;
1411                if (currentClip->top > state.mBounds.top) flags |= kClipSide_Top;
1412                if (currentClip->right < state.mBounds.right) flags |= kClipSide_Right;
1413                if (currentClip->bottom < state.mBounds.bottom) flags |= kClipSide_Bottom;
1414            }
1415            state.mBounds.set(clippedBounds);
1416        } else {
1417            // Empty bounds implies size unknown. Label op as conservatively clipped to disable
1418            // overdraw avoidance (since we don't know what it overlaps)
1419            state.mClipSideFlags = kClipSide_ConservativeFull;
1420            state.mBounds.set(*currentClip);
1421        }
1422    }
1423
1424    state.mClipValid = (stateDeferFlags & kStateDeferFlag_Clip);
1425    if (state.mClipValid) {
1426        state.mClip.set(*currentClip);
1427    }
1428
1429    // Transform, drawModifiers, and alpha always deferred, since they are used by state operations
1430    // (Note: saveLayer/restore use colorFilter and alpha, so we just save restore everything)
1431    state.mMatrix.load(*currentMatrix);
1432    state.mDrawModifiers = mDrawModifiers;
1433    state.mAlpha = currentSnapshot()->alpha;
1434    return false;
1435}
1436
1437void OpenGLRenderer::restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore) {
1438    setMatrix(state.mMatrix);
1439    mSnapshot->alpha = state.mAlpha;
1440    mDrawModifiers = state.mDrawModifiers;
1441
1442    if (state.mClipValid && !skipClipRestore) {
1443        mSnapshot->setClip(state.mClip.left, state.mClip.top,
1444                state.mClip.right, state.mClip.bottom);
1445        dirtyClip();
1446    }
1447}
1448
1449/**
1450 * Merged multidraw (such as in drawText and drawBitmaps rely on the fact that no clipping is done
1451 * in the draw path. Instead, clipping is done ahead of time - either as a single clip rect (when at
1452 * least one op is clipped), or disabled entirely (because no merged op is clipped)
1453 *
1454 * This method should be called when restoreDisplayState() won't be restoring the clip
1455 */
1456void OpenGLRenderer::setupMergedMultiDraw(const Rect* clipRect) {
1457    if (clipRect != NULL) {
1458        mSnapshot->setClip(clipRect->left, clipRect->top, clipRect->right, clipRect->bottom);
1459    } else {
1460        mSnapshot->setClip(0, 0, getWidth(), getHeight());
1461    }
1462    dirtyClip();
1463    mCaches.setScissorEnabled(clipRect != NULL || mScissorOptimizationDisabled);
1464}
1465
1466///////////////////////////////////////////////////////////////////////////////
1467// Clipping
1468///////////////////////////////////////////////////////////////////////////////
1469
1470void OpenGLRenderer::setScissorFromClip() {
1471    Rect clip(*currentClipRect());
1472    clip.snapToPixelBoundaries();
1473
1474    if (mCaches.setScissor(clip.left, currentSnapshot()->height - clip.bottom,
1475            clip.getWidth(), clip.getHeight())) {
1476        mDirtyClip = false;
1477    }
1478}
1479
1480void OpenGLRenderer::ensureStencilBuffer() {
1481    // Thanks to the mismatch between EGL and OpenGL ES FBO we
1482    // cannot attach a stencil buffer to fbo0 dynamically. Let's
1483    // just hope we have one when hasLayer() returns false.
1484    if (hasLayer()) {
1485        attachStencilBufferToLayer(currentSnapshot()->layer);
1486    }
1487}
1488
1489void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) {
1490    // The layer's FBO is already bound when we reach this stage
1491    if (!layer->getStencilRenderBuffer()) {
1492        // GL_QCOM_tiled_rendering doesn't like it if a renderbuffer
1493        // is attached after we initiated tiling. We must turn it off,
1494        // attach the new render buffer then turn tiling back on
1495        endTiling();
1496
1497        RenderBuffer* buffer = mCaches.renderBufferCache.get(
1498                Stencil::getSmallestStencilFormat(), layer->getWidth(), layer->getHeight());
1499        layer->setStencilRenderBuffer(buffer);
1500
1501        startTiling(layer->clipRect, layer->layer.getHeight());
1502    }
1503}
1504
1505void OpenGLRenderer::setStencilFromClip() {
1506    if (!mCaches.debugOverdraw) {
1507        if (!currentSnapshot()->clipRegion->isEmpty()) {
1508            // NOTE: The order here is important, we must set dirtyClip to false
1509            //       before any draw call to avoid calling back into this method
1510            mDirtyClip = false;
1511
1512            ensureStencilBuffer();
1513
1514            mCaches.stencil.enableWrite();
1515
1516            // Clear the stencil but first make sure we restrict drawing
1517            // to the region's bounds
1518            bool resetScissor = mCaches.enableScissor();
1519            if (resetScissor) {
1520                // The scissor was not set so we now need to update it
1521                setScissorFromClip();
1522            }
1523            mCaches.stencil.clear();
1524            if (resetScissor) mCaches.disableScissor();
1525
1526            SkPaint paint;
1527            paint.setColor(0xff000000);
1528            paint.setXfermodeMode(SkXfermode::kSrc_Mode);
1529
1530            // NOTE: We could use the region contour path to generate a smaller mesh
1531            //       Since we are using the stencil we could use the red book path
1532            //       drawing technique. It might increase bandwidth usage though.
1533
1534            // The last parameter is important: we are not drawing in the color buffer
1535            // so we don't want to dirty the current layer, if any
1536            drawRegionRects(*(currentSnapshot()->clipRegion), paint, false);
1537
1538            mCaches.stencil.enableTest();
1539
1540            // Draw the region used to generate the stencil if the appropriate debug
1541            // mode is enabled
1542            if (mCaches.debugStencilClip == Caches::kStencilShowRegion) {
1543                paint.setColor(0x7f0000ff);
1544                paint.setXfermodeMode(SkXfermode::kSrcOver_Mode);
1545                drawRegionRects(*(currentSnapshot()->clipRegion), paint);
1546            }
1547        } else {
1548            mCaches.stencil.disable();
1549        }
1550    }
1551}
1552
1553/**
1554 * Returns false and sets scissor enable based upon bounds if drawing won't be clipped out.
1555 *
1556 * @param paint if not null, the bounds will be expanded to account for stroke depending on paint
1557 *         style, and tessellated AA ramp
1558 */
1559bool OpenGLRenderer::quickRejectSetupScissor(float left, float top, float right, float bottom,
1560        const SkPaint* paint) {
1561    bool clipRequired = false;
1562    bool snapOut = paint && paint->isAntiAlias();
1563
1564    if (paint && paint->getStyle() != SkPaint::kFill_Style) {
1565        float outset = paint->getStrokeWidth() * 0.5f;
1566        left -= outset;
1567        top -= outset;
1568        right += outset;
1569        bottom += outset;
1570    }
1571
1572    if (calculateQuickRejectForScissor(left, top, right, bottom, &clipRequired, snapOut)) {
1573        return true;
1574    }
1575
1576    if (!isRecording()) {
1577        // not quick rejected, so enable the scissor if clipRequired
1578        mCaches.setScissorEnabled(mScissorOptimizationDisabled || clipRequired);
1579    }
1580    return false;
1581}
1582
1583void OpenGLRenderer::debugClip() {
1584#if DEBUG_CLIP_REGIONS
1585    if (!isRecording() && !currentSnapshot()->clipRegion->isEmpty()) {
1586        SkPaint paint;
1587        paint.setColor(0x7f00ff00);
1588        drawRegionRects(*(currentSnapshot()->clipRegion, paint);
1589
1590    }
1591#endif
1592}
1593
1594///////////////////////////////////////////////////////////////////////////////
1595// Drawing commands
1596///////////////////////////////////////////////////////////////////////////////
1597
1598void OpenGLRenderer::setupDraw(bool clear) {
1599    // TODO: It would be best if we could do this before quickRejectSetupScissor()
1600    //       changes the scissor test state
1601    if (clear) clearLayerRegions();
1602    // Make sure setScissor & setStencil happen at the beginning of
1603    // this method
1604    if (mDirtyClip) {
1605        if (mCaches.scissorEnabled) {
1606            setScissorFromClip();
1607        }
1608        setStencilFromClip();
1609    }
1610
1611    mDescription.reset();
1612
1613    mSetShaderColor = false;
1614    mColorSet = false;
1615    mColorA = mColorR = mColorG = mColorB = 0.0f;
1616    mTextureUnit = 0;
1617    mTrackDirtyRegions = true;
1618
1619    // Enable debug highlight when what we're about to draw is tested against
1620    // the stencil buffer and if stencil highlight debugging is on
1621    mDescription.hasDebugHighlight = !mCaches.debugOverdraw &&
1622            mCaches.debugStencilClip == Caches::kStencilShowHighlight &&
1623            mCaches.stencil.isTestEnabled();
1624
1625    mDescription.emulateStencil = mCountOverdraw;
1626}
1627
1628void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
1629    mDescription.hasTexture = true;
1630    mDescription.hasAlpha8Texture = isAlpha8;
1631}
1632
1633void OpenGLRenderer::setupDrawWithTextureAndColor(bool isAlpha8) {
1634    mDescription.hasTexture = true;
1635    mDescription.hasColors = true;
1636    mDescription.hasAlpha8Texture = isAlpha8;
1637}
1638
1639void OpenGLRenderer::setupDrawWithExternalTexture() {
1640    mDescription.hasExternalTexture = true;
1641}
1642
1643void OpenGLRenderer::setupDrawNoTexture() {
1644    mCaches.disableTexCoordsVertexArray();
1645}
1646
1647void OpenGLRenderer::setupDrawAA() {
1648    mDescription.isAA = true;
1649}
1650
1651void OpenGLRenderer::setupDrawColor(int color, int alpha) {
1652    mColorA = alpha / 255.0f;
1653    mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1654    mColorG = mColorA * ((color >>  8) & 0xFF) / 255.0f;
1655    mColorB = mColorA * ((color      ) & 0xFF) / 255.0f;
1656    mColorSet = true;
1657    mSetShaderColor = mDescription.setColorModulate(mColorA);
1658}
1659
1660void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
1661    mColorA = alpha / 255.0f;
1662    mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1663    mColorG = mColorA * ((color >>  8) & 0xFF) / 255.0f;
1664    mColorB = mColorA * ((color      ) & 0xFF) / 255.0f;
1665    mColorSet = true;
1666    mSetShaderColor = mDescription.setAlpha8ColorModulate(mColorR, mColorG, mColorB, mColorA);
1667}
1668
1669void OpenGLRenderer::setupDrawTextGamma(const SkPaint* paint) {
1670    mCaches.fontRenderer->describe(mDescription, paint);
1671}
1672
1673void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
1674    mColorA = a;
1675    mColorR = r;
1676    mColorG = g;
1677    mColorB = b;
1678    mColorSet = true;
1679    mSetShaderColor = mDescription.setColorModulate(a);
1680}
1681
1682void OpenGLRenderer::setupDrawShader() {
1683    if (mDrawModifiers.mShader) {
1684        mDrawModifiers.mShader->describe(mDescription, mExtensions);
1685    }
1686}
1687
1688void OpenGLRenderer::setupDrawColorFilter(const SkColorFilter* filter) {
1689    if (filter == NULL) {
1690        return;
1691    }
1692
1693    SkXfermode::Mode mode;
1694    if (filter->asColorMode(NULL, &mode)) {
1695        mDescription.colorOp = ProgramDescription::kColorBlend;
1696        mDescription.colorMode = mode;
1697    } else if (filter->asColorMatrix(NULL)) {
1698        mDescription.colorOp = ProgramDescription::kColorMatrix;
1699    }
1700}
1701
1702void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
1703    if (mColorSet && mode == SkXfermode::kClear_Mode) {
1704        mColorA = 1.0f;
1705        mColorR = mColorG = mColorB = 0.0f;
1706        mSetShaderColor = mDescription.modulate = true;
1707    }
1708}
1709
1710void OpenGLRenderer::setupDrawBlending(const Layer* layer, bool swapSrcDst) {
1711    SkXfermode::Mode mode = layer->getMode();
1712    // When the blending mode is kClear_Mode, we need to use a modulate color
1713    // argb=1,0,0,0
1714    accountForClear(mode);
1715    bool blend = layer->isBlend() || getLayerAlpha(layer) < 1.0f ||
1716            (mColorSet && mColorA < 1.0f) ||
1717            (mDrawModifiers.mShader && mDrawModifiers.mShader->blend()) ||
1718            layer->getColorFilter();
1719    chooseBlending(blend, mode, mDescription, swapSrcDst);
1720}
1721
1722void OpenGLRenderer::setupDrawBlending(const SkPaint* paint, bool blend, bool swapSrcDst) {
1723    SkXfermode::Mode mode = getXfermodeDirect(paint);
1724    // When the blending mode is kClear_Mode, we need to use a modulate color
1725    // argb=1,0,0,0
1726    accountForClear(mode);
1727    blend |= (mColorSet && mColorA < 1.0f) ||
1728            (mDrawModifiers.mShader && mDrawModifiers.mShader->blend()) ||
1729            (paint && paint->getColorFilter());
1730    chooseBlending(blend, mode, mDescription, swapSrcDst);
1731}
1732
1733void OpenGLRenderer::setupDrawProgram() {
1734    useProgram(mCaches.programCache.get(mDescription));
1735}
1736
1737void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
1738    mTrackDirtyRegions = false;
1739}
1740
1741void OpenGLRenderer::setupDrawModelView(ModelViewMode mode, bool offset,
1742        float left, float top, float right, float bottom, bool ignoreTransform) {
1743    mModelView.loadTranslate(left, top, 0.0f);
1744    if (mode == kModelViewMode_TranslateAndScale) {
1745        mModelView.scale(right - left, bottom - top, 1.0f);
1746    }
1747
1748    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
1749    if (!ignoreTransform) {
1750        mCaches.currentProgram->set(mViewProjMatrix, mModelView, *currentTransform(), offset);
1751        if (dirty && mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *currentTransform());
1752    } else {
1753        mCaches.currentProgram->set(mViewProjMatrix, mModelView, mat4::identity(), offset);
1754        if (dirty && mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
1755    }
1756}
1757
1758void OpenGLRenderer::setupDrawColorUniforms() {
1759    if ((mColorSet && !mDrawModifiers.mShader) || (mDrawModifiers.mShader && mSetShaderColor)) {
1760        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1761    }
1762}
1763
1764void OpenGLRenderer::setupDrawPureColorUniforms() {
1765    if (mSetShaderColor) {
1766        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1767    }
1768}
1769
1770void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
1771    if (mDrawModifiers.mShader) {
1772        if (ignoreTransform) {
1773            // if ignoreTransform=true was passed to setupDrawModelView, undo currentTransform()
1774            // because it was built into modelView / the geometry, and the SkiaShader needs to
1775            // compensate.
1776            mat4 modelViewWithoutTransform;
1777            modelViewWithoutTransform.loadInverse(*currentTransform());
1778            modelViewWithoutTransform.multiply(mModelView);
1779            mModelView.load(modelViewWithoutTransform);
1780        }
1781        mDrawModifiers.mShader->setupProgram(mCaches.currentProgram,
1782                mModelView, *mSnapshot, &mTextureUnit);
1783    }
1784}
1785
1786void OpenGLRenderer::setupDrawColorFilterUniforms(const SkColorFilter* filter) {
1787    if (NULL == filter) {
1788        return;
1789    }
1790
1791    SkColor color;
1792    SkXfermode::Mode mode;
1793    if (filter->asColorMode(&color, &mode)) {
1794        const int alpha = SkColorGetA(color);
1795        const GLfloat a = alpha / 255.0f;
1796        const GLfloat r = a * SkColorGetR(color) / 255.0f;
1797        const GLfloat g = a * SkColorGetG(color) / 255.0f;
1798        const GLfloat b = a * SkColorGetB(color) / 255.0f;
1799        glUniform4f(mCaches.currentProgram->getUniform("colorBlend"), r, g, b, a);
1800        return;
1801    }
1802
1803    SkScalar srcColorMatrix[20];
1804    if (filter->asColorMatrix(srcColorMatrix)) {
1805
1806        float colorMatrix[16];
1807        memcpy(colorMatrix, srcColorMatrix, 4 * sizeof(float));
1808        memcpy(&colorMatrix[4], &srcColorMatrix[5], 4 * sizeof(float));
1809        memcpy(&colorMatrix[8], &srcColorMatrix[10], 4 * sizeof(float));
1810        memcpy(&colorMatrix[12], &srcColorMatrix[15], 4 * sizeof(float));
1811
1812        // Skia uses the range [0..255] for the addition vector, but we need
1813        // the [0..1] range to apply the vector in GLSL
1814        float colorVector[4];
1815        colorVector[0] = srcColorMatrix[4] / 255.0f;
1816        colorVector[1] = srcColorMatrix[9] / 255.0f;
1817        colorVector[2] = srcColorMatrix[14] / 255.0f;
1818        colorVector[3] = srcColorMatrix[19] / 255.0f;
1819
1820        glUniformMatrix4fv(mCaches.currentProgram->getUniform("colorMatrix"), 1,
1821                GL_FALSE, colorMatrix);
1822        glUniform4fv(mCaches.currentProgram->getUniform("colorMatrixVector"), 1, colorVector);
1823        return;
1824    }
1825
1826    // it is an error if we ever get here
1827}
1828
1829void OpenGLRenderer::setupDrawTextGammaUniforms() {
1830    mCaches.fontRenderer->setupProgram(mDescription, mCaches.currentProgram);
1831}
1832
1833void OpenGLRenderer::setupDrawSimpleMesh() {
1834    bool force = mCaches.bindMeshBuffer();
1835    mCaches.bindPositionVertexPointer(force, 0);
1836    mCaches.unbindIndicesBuffer();
1837}
1838
1839void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1840    if (texture) bindTexture(texture);
1841    mTextureUnit++;
1842    mCaches.enableTexCoordsVertexArray();
1843}
1844
1845void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) {
1846    bindExternalTexture(texture);
1847    mTextureUnit++;
1848    mCaches.enableTexCoordsVertexArray();
1849}
1850
1851void OpenGLRenderer::setupDrawTextureTransform() {
1852    mDescription.hasTextureTransform = true;
1853}
1854
1855void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) {
1856    glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1,
1857            GL_FALSE, &transform.data[0]);
1858}
1859
1860void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices,
1861        const GLvoid* texCoords, GLuint vbo) {
1862    bool force = false;
1863    if (!vertices || vbo) {
1864        force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1865    } else {
1866        force = mCaches.unbindMeshBuffer();
1867    }
1868
1869    mCaches.bindPositionVertexPointer(force, vertices);
1870    if (mCaches.currentProgram->texCoords >= 0) {
1871        mCaches.bindTexCoordsVertexPointer(force, texCoords);
1872    }
1873
1874    mCaches.unbindIndicesBuffer();
1875}
1876
1877void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices,
1878        const GLvoid* texCoords, const GLvoid* colors) {
1879    bool force = mCaches.unbindMeshBuffer();
1880    GLsizei stride = sizeof(ColorTextureVertex);
1881
1882    mCaches.bindPositionVertexPointer(force, vertices, stride);
1883    if (mCaches.currentProgram->texCoords >= 0) {
1884        mCaches.bindTexCoordsVertexPointer(force, texCoords, stride);
1885    }
1886    int slot = mCaches.currentProgram->getAttrib("colors");
1887    if (slot >= 0) {
1888        glEnableVertexAttribArray(slot);
1889        glVertexAttribPointer(slot, 4, GL_FLOAT, GL_FALSE, stride, colors);
1890    }
1891
1892    mCaches.unbindIndicesBuffer();
1893}
1894
1895void OpenGLRenderer::setupDrawMeshIndices(const GLvoid* vertices,
1896        const GLvoid* texCoords, GLuint vbo) {
1897    bool force = false;
1898    // If vbo is != 0 we want to treat the vertices parameter as an offset inside
1899    // a VBO. However, if vertices is set to NULL and vbo == 0 then we want to
1900    // use the default VBO found in Caches
1901    if (!vertices || vbo) {
1902        force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1903    } else {
1904        force = mCaches.unbindMeshBuffer();
1905    }
1906    mCaches.bindIndicesBuffer();
1907
1908    mCaches.bindPositionVertexPointer(force, vertices);
1909    if (mCaches.currentProgram->texCoords >= 0) {
1910        mCaches.bindTexCoordsVertexPointer(force, texCoords);
1911    }
1912}
1913
1914void OpenGLRenderer::setupDrawIndexedVertices(GLvoid* vertices) {
1915    bool force = mCaches.unbindMeshBuffer();
1916    mCaches.bindIndicesBuffer();
1917    mCaches.bindPositionVertexPointer(force, vertices, gVertexStride);
1918}
1919
1920///////////////////////////////////////////////////////////////////////////////
1921// Drawing
1922///////////////////////////////////////////////////////////////////////////////
1923
1924status_t OpenGLRenderer::drawDisplayList(DisplayList* displayList, Rect& dirty,
1925        int32_t replayFlags) {
1926    status_t status;
1927
1928    if (mCaches.propertyDirtyViewport) {
1929        // force recalc of view/proj matrices
1930        setViewport(getWidth(), getHeight());
1931        mCaches.propertyDirtyViewport = false;
1932    }
1933
1934    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1935    // will be performed by the display list itself
1936    if (displayList && displayList->isRenderable()) {
1937        // compute 3d ordering
1938        displayList->computeOrdering();
1939        if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
1940            status = startFrame();
1941            ReplayStateStruct replayStruct(*this, dirty, replayFlags);
1942            displayList->replay(replayStruct, 0);
1943            return status | replayStruct.mDrawGlStatus;
1944        }
1945
1946        bool avoidOverdraw = !mCaches.debugOverdraw && !mCountOverdraw; // shh, don't tell devs!
1947        DeferredDisplayList deferredList(*currentClipRect(), avoidOverdraw);
1948        DeferStateStruct deferStruct(deferredList, *this, replayFlags);
1949        displayList->defer(deferStruct, 0);
1950
1951        flushLayers();
1952        status = startFrame();
1953
1954        return deferredList.flush(*this, dirty) | status;
1955    }
1956
1957    return DrawGlInfo::kStatusDone;
1958}
1959
1960void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, const SkPaint* paint) {
1961    int color = paint != NULL ? paint->getColor() : 0;
1962
1963    float x = left;
1964    float y = top;
1965
1966    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1967
1968    bool ignoreTransform = false;
1969    if (currentTransform()->isPureTranslate()) {
1970        x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f);
1971        y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f);
1972        ignoreTransform = true;
1973
1974        texture->setFilter(GL_NEAREST, true);
1975    } else {
1976        texture->setFilter(FILTER(paint), true);
1977    }
1978
1979    // No need to check for a UV mapper on the texture object, only ARGB_8888
1980    // bitmaps get packed in the atlas
1981    drawAlpha8TextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
1982            paint, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
1983            GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform);
1984}
1985
1986/**
1987 * Important note: this method is intended to draw batches of bitmaps and
1988 * will not set the scissor enable or dirty the current layer, if any.
1989 * The caller is responsible for properly dirtying the current layer.
1990 */
1991status_t OpenGLRenderer::drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
1992        int bitmapCount, TextureVertex* vertices, bool pureTranslate,
1993        const Rect& bounds, const SkPaint* paint) {
1994    mCaches.activeTexture(0);
1995    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
1996    if (!texture) return DrawGlInfo::kStatusDone;
1997
1998    const AutoTexture autoCleanup(texture);
1999
2000    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2001    texture->setFilter(pureTranslate ? GL_NEAREST : FILTER(paint), true);
2002
2003    const float x = (int) floorf(bounds.left + 0.5f);
2004    const float y = (int) floorf(bounds.top + 0.5f);
2005    if (CC_UNLIKELY(bitmap->config() == SkBitmap::kA8_Config)) {
2006        drawAlpha8TextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
2007                texture->id, paint, &vertices[0].x, &vertices[0].u,
2008                GL_TRIANGLES, bitmapCount * 6, true,
2009                kModelViewMode_Translate, false);
2010    } else {
2011        drawTextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
2012                texture->id, paint, texture->blend, &vertices[0].x, &vertices[0].u,
2013                GL_TRIANGLES, bitmapCount * 6, false, true, 0,
2014                kModelViewMode_Translate, false);
2015    }
2016
2017    return DrawGlInfo::kStatusDrew;
2018}
2019
2020status_t OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, float left, float top,
2021        const SkPaint* paint) {
2022    const float right = left + bitmap->width();
2023    const float bottom = top + bitmap->height();
2024
2025    if (quickRejectSetupScissor(left, top, right, bottom)) {
2026        return DrawGlInfo::kStatusDone;
2027    }
2028
2029    mCaches.activeTexture(0);
2030    Texture* texture = getTexture(bitmap);
2031    if (!texture) return DrawGlInfo::kStatusDone;
2032    const AutoTexture autoCleanup(texture);
2033
2034    if (CC_UNLIKELY(bitmap->config() == SkBitmap::kA8_Config)) {
2035        drawAlphaBitmap(texture, left, top, paint);
2036    } else {
2037        drawTextureRect(left, top, right, bottom, texture, paint);
2038    }
2039
2040    return DrawGlInfo::kStatusDrew;
2041}
2042
2043status_t OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, const SkMatrix* matrix,
2044        const SkPaint* paint) {
2045    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
2046    const mat4 transform(*matrix);
2047    transform.mapRect(r);
2048
2049    if (quickRejectSetupScissor(r.left, r.top, r.right, r.bottom)) {
2050        return DrawGlInfo::kStatusDone;
2051    }
2052
2053    mCaches.activeTexture(0);
2054    Texture* texture = getTexture(bitmap);
2055    if (!texture) return DrawGlInfo::kStatusDone;
2056    const AutoTexture autoCleanup(texture);
2057
2058    // This could be done in a cheaper way, all we need is pass the matrix
2059    // to the vertex shader. The save/restore is a bit overkill.
2060    save(SkCanvas::kMatrix_SaveFlag);
2061    concatMatrix(matrix);
2062    if (CC_UNLIKELY(bitmap->config() == SkBitmap::kA8_Config)) {
2063        drawAlphaBitmap(texture, 0.0f, 0.0f, paint);
2064    } else {
2065        drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
2066    }
2067    restore();
2068
2069    return DrawGlInfo::kStatusDrew;
2070}
2071
2072status_t OpenGLRenderer::drawBitmapData(const SkBitmap* bitmap, float left, float top,
2073        const SkPaint* paint) {
2074    const float right = left + bitmap->width();
2075    const float bottom = top + bitmap->height();
2076
2077    if (quickRejectSetupScissor(left, top, right, bottom)) {
2078        return DrawGlInfo::kStatusDone;
2079    }
2080
2081    mCaches.activeTexture(0);
2082    Texture* texture = mCaches.textureCache.getTransient(bitmap);
2083    const AutoTexture autoCleanup(texture);
2084
2085    if (CC_UNLIKELY(bitmap->config() == SkBitmap::kA8_Config)) {
2086        drawAlphaBitmap(texture, left, top, paint);
2087    } else {
2088        drawTextureRect(left, top, right, bottom, texture, paint);
2089    }
2090
2091    return DrawGlInfo::kStatusDrew;
2092}
2093
2094status_t OpenGLRenderer::drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight,
2095        const float* vertices, const int* colors, const SkPaint* paint) {
2096    if (!vertices || currentSnapshot()->isIgnored()) {
2097        return DrawGlInfo::kStatusDone;
2098    }
2099
2100    // TODO: use quickReject on bounds from vertices
2101    mCaches.enableScissor();
2102
2103    float left = FLT_MAX;
2104    float top = FLT_MAX;
2105    float right = FLT_MIN;
2106    float bottom = FLT_MIN;
2107
2108    const uint32_t count = meshWidth * meshHeight * 6;
2109
2110    Vector<ColorTextureVertex> mesh; // TODO: use C++11 unique_ptr
2111    mesh.setCapacity(count);
2112    ColorTextureVertex* vertex = mesh.editArray();
2113
2114    bool cleanupColors = false;
2115    if (!colors) {
2116        uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1);
2117        int* newColors = new int[colorsCount];
2118        memset(newColors, 0xff, colorsCount * sizeof(int));
2119        colors = newColors;
2120        cleanupColors = true;
2121    }
2122
2123    mCaches.activeTexture(0);
2124    Texture* texture = mCaches.assetAtlas.getEntryTexture(bitmap);
2125    const UvMapper& mapper(getMapper(texture));
2126
2127    for (int32_t y = 0; y < meshHeight; y++) {
2128        for (int32_t x = 0; x < meshWidth; x++) {
2129            uint32_t i = (y * (meshWidth + 1) + x) * 2;
2130
2131            float u1 = float(x) / meshWidth;
2132            float u2 = float(x + 1) / meshWidth;
2133            float v1 = float(y) / meshHeight;
2134            float v2 = float(y + 1) / meshHeight;
2135
2136            mapper.map(u1, v1, u2, v2);
2137
2138            int ax = i + (meshWidth + 1) * 2;
2139            int ay = ax + 1;
2140            int bx = i;
2141            int by = bx + 1;
2142            int cx = i + 2;
2143            int cy = cx + 1;
2144            int dx = i + (meshWidth + 1) * 2 + 2;
2145            int dy = dx + 1;
2146
2147            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
2148            ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]);
2149            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
2150
2151            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
2152            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
2153            ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]);
2154
2155            left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
2156            top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
2157            right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
2158            bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
2159        }
2160    }
2161
2162    if (quickRejectSetupScissor(left, top, right, bottom)) {
2163        if (cleanupColors) delete[] colors;
2164        return DrawGlInfo::kStatusDone;
2165    }
2166
2167    if (!texture) {
2168        texture = mCaches.textureCache.get(bitmap);
2169        if (!texture) {
2170            if (cleanupColors) delete[] colors;
2171            return DrawGlInfo::kStatusDone;
2172        }
2173    }
2174    const AutoTexture autoCleanup(texture);
2175
2176    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2177    texture->setFilter(FILTER(paint), true);
2178
2179    int alpha;
2180    SkXfermode::Mode mode;
2181    getAlphaAndMode(paint, &alpha, &mode);
2182
2183    float a = alpha / 255.0f;
2184
2185    if (hasLayer()) {
2186        dirtyLayer(left, top, right, bottom, *currentTransform());
2187    }
2188
2189    setupDraw();
2190    setupDrawWithTextureAndColor();
2191    setupDrawColor(a, a, a, a);
2192    setupDrawColorFilter(getColorFilter(paint));
2193    setupDrawBlending(paint, true);
2194    setupDrawProgram();
2195    setupDrawDirtyRegionsDisabled();
2196    setupDrawModelView(kModelViewMode_TranslateAndScale, false, 0.0f, 0.0f, 1.0f, 1.0f);
2197    setupDrawTexture(texture->id);
2198    setupDrawPureColorUniforms();
2199    setupDrawColorFilterUniforms(getColorFilter(paint));
2200    setupDrawMesh(&mesh[0].x, &mesh[0].u, &mesh[0].r);
2201
2202    glDrawArrays(GL_TRIANGLES, 0, count);
2203
2204    int slot = mCaches.currentProgram->getAttrib("colors");
2205    if (slot >= 0) {
2206        glDisableVertexAttribArray(slot);
2207    }
2208
2209    if (cleanupColors) delete[] colors;
2210
2211    return DrawGlInfo::kStatusDrew;
2212}
2213
2214status_t OpenGLRenderer::drawBitmap(const SkBitmap* bitmap,
2215         float srcLeft, float srcTop, float srcRight, float srcBottom,
2216         float dstLeft, float dstTop, float dstRight, float dstBottom,
2217         const SkPaint* paint) {
2218    if (quickRejectSetupScissor(dstLeft, dstTop, dstRight, dstBottom)) {
2219        return DrawGlInfo::kStatusDone;
2220    }
2221
2222    mCaches.activeTexture(0);
2223    Texture* texture = getTexture(bitmap);
2224    if (!texture) return DrawGlInfo::kStatusDone;
2225    const AutoTexture autoCleanup(texture);
2226
2227    const float width = texture->width;
2228    const float height = texture->height;
2229
2230    float u1 = fmax(0.0f, srcLeft / width);
2231    float v1 = fmax(0.0f, srcTop / height);
2232    float u2 = fmin(1.0f, srcRight / width);
2233    float v2 = fmin(1.0f, srcBottom / height);
2234
2235    getMapper(texture).map(u1, v1, u2, v2);
2236
2237    mCaches.unbindMeshBuffer();
2238    resetDrawTextureTexCoords(u1, v1, u2, v2);
2239
2240    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2241
2242    float scaleX = (dstRight - dstLeft) / (srcRight - srcLeft);
2243    float scaleY = (dstBottom - dstTop) / (srcBottom - srcTop);
2244
2245    bool scaled = scaleX != 1.0f || scaleY != 1.0f;
2246    // Apply a scale transform on the canvas only when a shader is in use
2247    // Skia handles the ratio between the dst and src rects as a scale factor
2248    // when a shader is set
2249    bool useScaleTransform = mDrawModifiers.mShader && scaled;
2250    bool ignoreTransform = false;
2251
2252    if (CC_LIKELY(currentTransform()->isPureTranslate() && !useScaleTransform)) {
2253        float x = (int) floorf(dstLeft + currentTransform()->getTranslateX() + 0.5f);
2254        float y = (int) floorf(dstTop + currentTransform()->getTranslateY() + 0.5f);
2255
2256        dstRight = x + (dstRight - dstLeft);
2257        dstBottom = y + (dstBottom - dstTop);
2258
2259        dstLeft = x;
2260        dstTop = y;
2261
2262        texture->setFilter(scaled ? FILTER(paint) : GL_NEAREST, true);
2263        ignoreTransform = true;
2264    } else {
2265        texture->setFilter(FILTER(paint), true);
2266    }
2267
2268    if (CC_UNLIKELY(useScaleTransform)) {
2269        save(SkCanvas::kMatrix_SaveFlag);
2270        translate(dstLeft, dstTop);
2271        scale(scaleX, scaleY);
2272
2273        dstLeft = 0.0f;
2274        dstTop = 0.0f;
2275
2276        dstRight = srcRight - srcLeft;
2277        dstBottom = srcBottom - srcTop;
2278    }
2279
2280    if (CC_UNLIKELY(bitmap->config() == SkBitmap::kA8_Config)) {
2281        drawAlpha8TextureMesh(dstLeft, dstTop, dstRight, dstBottom,
2282                texture->id, paint,
2283                &mMeshVertices[0].x, &mMeshVertices[0].u,
2284                GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform);
2285    } else {
2286        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom,
2287                texture->id, paint, texture->blend,
2288                &mMeshVertices[0].x, &mMeshVertices[0].u,
2289                GL_TRIANGLE_STRIP, gMeshCount, false, ignoreTransform);
2290    }
2291
2292    if (CC_UNLIKELY(useScaleTransform)) {
2293        restore();
2294    }
2295
2296    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
2297
2298    return DrawGlInfo::kStatusDrew;
2299}
2300
2301status_t OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Res_png_9patch* patch,
2302        float left, float top, float right, float bottom, const SkPaint* paint) {
2303    if (quickRejectSetupScissor(left, top, right, bottom)) {
2304        return DrawGlInfo::kStatusDone;
2305    }
2306
2307    AssetAtlas::Entry* entry = mCaches.assetAtlas.getEntry(bitmap);
2308    const Patch* mesh = mCaches.patchCache.get(entry, bitmap->width(), bitmap->height(),
2309            right - left, bottom - top, patch);
2310
2311    return drawPatch(bitmap, mesh, entry, left, top, right, bottom, paint);
2312}
2313
2314status_t OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Patch* mesh,
2315        AssetAtlas::Entry* entry, float left, float top, float right, float bottom,
2316        const SkPaint* paint) {
2317    if (quickRejectSetupScissor(left, top, right, bottom)) {
2318        return DrawGlInfo::kStatusDone;
2319    }
2320
2321    if (CC_LIKELY(mesh && mesh->verticesCount > 0)) {
2322        mCaches.activeTexture(0);
2323        Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
2324        if (!texture) return DrawGlInfo::kStatusDone;
2325        const AutoTexture autoCleanup(texture);
2326
2327        texture->setWrap(GL_CLAMP_TO_EDGE, true);
2328        texture->setFilter(GL_LINEAR, true);
2329
2330        const bool pureTranslate = currentTransform()->isPureTranslate();
2331        // Mark the current layer dirty where we are going to draw the patch
2332        if (hasLayer() && mesh->hasEmptyQuads) {
2333            const float offsetX = left + currentTransform()->getTranslateX();
2334            const float offsetY = top + currentTransform()->getTranslateY();
2335            const size_t count = mesh->quads.size();
2336            for (size_t i = 0; i < count; i++) {
2337                const Rect& bounds = mesh->quads.itemAt(i);
2338                if (CC_LIKELY(pureTranslate)) {
2339                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
2340                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
2341                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
2342                } else {
2343                    dirtyLayer(left + bounds.left, top + bounds.top,
2344                            left + bounds.right, top + bounds.bottom, *currentTransform());
2345                }
2346            }
2347        }
2348
2349        bool ignoreTransform = false;
2350        if (CC_LIKELY(pureTranslate)) {
2351            const float x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f);
2352            const float y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f);
2353
2354            right = x + right - left;
2355            bottom = y + bottom - top;
2356            left = x;
2357            top = y;
2358            ignoreTransform = true;
2359        }
2360        drawIndexedTextureMesh(left, top, right, bottom, texture->id, paint,
2361                texture->blend, (GLvoid*) mesh->offset, (GLvoid*) mesh->textureOffset,
2362                GL_TRIANGLES, mesh->indexCount, false, ignoreTransform,
2363                mCaches.patchCache.getMeshBuffer(), kModelViewMode_Translate, !mesh->hasEmptyQuads);
2364    }
2365
2366    return DrawGlInfo::kStatusDrew;
2367}
2368
2369/**
2370 * Important note: this method is intended to draw batches of 9-patch objects and
2371 * will not set the scissor enable or dirty the current layer, if any.
2372 * The caller is responsible for properly dirtying the current layer.
2373 */
2374status_t OpenGLRenderer::drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
2375        TextureVertex* vertices, uint32_t indexCount, const SkPaint* paint) {
2376    mCaches.activeTexture(0);
2377    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
2378    if (!texture) return DrawGlInfo::kStatusDone;
2379    const AutoTexture autoCleanup(texture);
2380
2381    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2382    texture->setFilter(GL_LINEAR, true);
2383
2384    drawIndexedTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, paint,
2385            texture->blend, &vertices[0].x, &vertices[0].u,
2386            GL_TRIANGLES, indexCount, false, true, 0, kModelViewMode_Translate, false);
2387
2388    return DrawGlInfo::kStatusDrew;
2389}
2390
2391status_t OpenGLRenderer::drawVertexBuffer(const VertexBuffer& vertexBuffer, const SkPaint* paint,
2392        bool useOffset) {
2393    // not missing call to quickReject/dirtyLayer, always done at a higher level
2394
2395    if (!vertexBuffer.getVertexCount()) {
2396        // no vertices to draw
2397        return DrawGlInfo::kStatusDone;
2398    }
2399
2400    int color = paint->getColor();
2401    bool isAA = paint->isAntiAlias();
2402
2403    setupDraw();
2404    setupDrawNoTexture();
2405    if (isAA) setupDrawAA();
2406    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
2407    setupDrawColorFilter(getColorFilter(paint));
2408    setupDrawShader();
2409    setupDrawBlending(paint, isAA);
2410    setupDrawProgram();
2411    setupDrawModelView(kModelViewMode_Translate, useOffset, 0, 0, 0, 0);
2412    setupDrawColorUniforms();
2413    setupDrawColorFilterUniforms(getColorFilter(paint));
2414    setupDrawShaderUniforms();
2415
2416    const void* vertices = vertexBuffer.getBuffer();
2417    bool force = mCaches.unbindMeshBuffer();
2418    mCaches.bindPositionVertexPointer(true, vertices, isAA ? gAlphaVertexStride : gVertexStride);
2419    mCaches.resetTexCoordsVertexPointer();
2420    mCaches.unbindIndicesBuffer();
2421
2422    int alphaSlot = -1;
2423    if (isAA) {
2424        void* alphaCoords = ((GLbyte*) vertices) + gVertexAlphaOffset;
2425        alphaSlot = mCaches.currentProgram->getAttrib("vtxAlpha");
2426
2427        // TODO: avoid enable/disable in back to back uses of the alpha attribute
2428        glEnableVertexAttribArray(alphaSlot);
2429        glVertexAttribPointer(alphaSlot, 1, GL_FLOAT, GL_FALSE, gAlphaVertexStride, alphaCoords);
2430    }
2431
2432    glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexBuffer.getVertexCount());
2433
2434    if (isAA) {
2435        glDisableVertexAttribArray(alphaSlot);
2436    }
2437
2438    return DrawGlInfo::kStatusDrew;
2439}
2440
2441/**
2442 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to
2443 * that of AA lines in the drawLines() function.  We expand the convex path by a half pixel in
2444 * screen space in all directions. However, instead of using a fragment shader to compute the
2445 * translucency of the color from its position, we simply use a varying parameter to define how far
2446 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used.
2447 *
2448 * Doesn't yet support joins, caps, or path effects.
2449 */
2450status_t OpenGLRenderer::drawConvexPath(const SkPath& path, const SkPaint* paint) {
2451    VertexBuffer vertexBuffer;
2452    // TODO: try clipping large paths to viewport
2453    PathTessellator::tessellatePath(path, paint, *currentTransform(), vertexBuffer);
2454
2455    if (hasLayer()) {
2456        SkRect bounds = path.getBounds();
2457        PathTessellator::expandBoundsForStroke(bounds, paint);
2458        dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, *currentTransform());
2459    }
2460
2461    return drawVertexBuffer(vertexBuffer, paint);
2462}
2463
2464/**
2465 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha
2466 * and additional geometry for defining an alpha slope perimeter.
2467 *
2468 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some
2469 * unexpected results, and may vary between hardware devices. Previously we used a varying-base
2470 * in-shader alpha region, but found it to be taxing on some GPUs.
2471 *
2472 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce
2473 * memory transfer by removing need for degenerate vertices.
2474 */
2475status_t OpenGLRenderer::drawLines(const float* points, int count, const SkPaint* paint) {
2476    if (currentSnapshot()->isIgnored() || count < 4) return DrawGlInfo::kStatusDone;
2477
2478    count &= ~0x3; // round down to nearest four
2479
2480    VertexBuffer buffer;
2481    SkRect bounds;
2482    PathTessellator::tessellateLines(points, count, paint, *currentTransform(), bounds, buffer);
2483
2484    // can't pass paint, since style would be checked for outset. outset done by tessellation.
2485    if (quickRejectSetupScissor(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom)) {
2486        return DrawGlInfo::kStatusDone;
2487    }
2488
2489    dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, *currentTransform());
2490
2491    bool useOffset = !paint->isAntiAlias();
2492    return drawVertexBuffer(buffer, paint, useOffset);
2493}
2494
2495status_t OpenGLRenderer::drawPoints(const float* points, int count, const SkPaint* paint) {
2496    if (currentSnapshot()->isIgnored() || count < 2) return DrawGlInfo::kStatusDone;
2497
2498    count &= ~0x1; // round down to nearest two
2499
2500    VertexBuffer buffer;
2501    SkRect bounds;
2502    PathTessellator::tessellatePoints(points, count, paint, *currentTransform(), bounds, buffer);
2503
2504    // can't pass paint, since style would be checked for outset. outset done by tessellation.
2505    if (quickRejectSetupScissor(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom)) {
2506        return DrawGlInfo::kStatusDone;
2507    }
2508
2509    dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, *currentTransform());
2510
2511    bool useOffset = !paint->isAntiAlias();
2512    return drawVertexBuffer(buffer, paint, useOffset);
2513}
2514
2515status_t OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
2516    // No need to check against the clip, we fill the clip region
2517    if (currentSnapshot()->isIgnored()) return DrawGlInfo::kStatusDone;
2518
2519    Rect clip(*currentClipRect());
2520    clip.snapToPixelBoundaries();
2521
2522    SkPaint paint;
2523    paint.setColor(color);
2524    paint.setXfermodeMode(mode);
2525
2526    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, &paint, true);
2527
2528    return DrawGlInfo::kStatusDrew;
2529}
2530
2531status_t OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture,
2532        const SkPaint* paint) {
2533    if (!texture) return DrawGlInfo::kStatusDone;
2534    const AutoTexture autoCleanup(texture);
2535
2536    const float x = left + texture->left - texture->offset;
2537    const float y = top + texture->top - texture->offset;
2538
2539    drawPathTexture(texture, x, y, paint);
2540
2541    return DrawGlInfo::kStatusDrew;
2542}
2543
2544status_t OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
2545        float rx, float ry, const SkPaint* p) {
2546    if (currentSnapshot()->isIgnored() || quickRejectSetupScissor(left, top, right, bottom, p) ||
2547            (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) {
2548        return DrawGlInfo::kStatusDone;
2549    }
2550
2551    if (p->getPathEffect() != 0) {
2552        mCaches.activeTexture(0);
2553        const PathTexture* texture = mCaches.pathCache.getRoundRect(
2554                right - left, bottom - top, rx, ry, p);
2555        return drawShape(left, top, texture, p);
2556    }
2557
2558    SkPath path;
2559    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2560    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2561        float outset = p->getStrokeWidth() / 2;
2562        rect.outset(outset, outset);
2563        rx += outset;
2564        ry += outset;
2565    }
2566    path.addRoundRect(rect, rx, ry);
2567    return drawConvexPath(path, p);
2568}
2569
2570status_t OpenGLRenderer::drawCircle(float x, float y, float radius, const SkPaint* p) {
2571    if (currentSnapshot()->isIgnored() || quickRejectSetupScissor(x - radius, y - radius,
2572            x + radius, y + radius, p) ||
2573            (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) {
2574        return DrawGlInfo::kStatusDone;
2575    }
2576    if (p->getPathEffect() != 0) {
2577        mCaches.activeTexture(0);
2578        const PathTexture* texture = mCaches.pathCache.getCircle(radius, p);
2579        return drawShape(x - radius, y - radius, texture, p);
2580    }
2581
2582    SkPath path;
2583    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2584        path.addCircle(x, y, radius + p->getStrokeWidth() / 2);
2585    } else {
2586        path.addCircle(x, y, radius);
2587    }
2588    return drawConvexPath(path, p);
2589}
2590
2591status_t OpenGLRenderer::drawOval(float left, float top, float right, float bottom,
2592        const SkPaint* p) {
2593    if (currentSnapshot()->isIgnored() || quickRejectSetupScissor(left, top, right, bottom, p) ||
2594            (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) {
2595        return DrawGlInfo::kStatusDone;
2596    }
2597
2598    if (p->getPathEffect() != 0) {
2599        mCaches.activeTexture(0);
2600        const PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p);
2601        return drawShape(left, top, texture, p);
2602    }
2603
2604    SkPath path;
2605    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2606    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2607        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2608    }
2609    path.addOval(rect);
2610    return drawConvexPath(path, p);
2611}
2612
2613status_t OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
2614        float startAngle, float sweepAngle, bool useCenter, const SkPaint* p) {
2615    if (currentSnapshot()->isIgnored() || quickRejectSetupScissor(left, top, right, bottom, p) ||
2616            (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) {
2617        return DrawGlInfo::kStatusDone;
2618    }
2619
2620    if (fabs(sweepAngle) >= 360.0f) {
2621        return drawOval(left, top, right, bottom, p);
2622    }
2623
2624    // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180)
2625    if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != 0 || useCenter) {
2626        mCaches.activeTexture(0);
2627        const PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top,
2628                startAngle, sweepAngle, useCenter, p);
2629        return drawShape(left, top, texture, p);
2630    }
2631
2632    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2633    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2634        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2635    }
2636
2637    SkPath path;
2638    if (useCenter) {
2639        path.moveTo(rect.centerX(), rect.centerY());
2640    }
2641    path.arcTo(rect, startAngle, sweepAngle, !useCenter);
2642    if (useCenter) {
2643        path.close();
2644    }
2645    return drawConvexPath(path, p);
2646}
2647
2648// See SkPaintDefaults.h
2649#define SkPaintDefaults_MiterLimit SkIntToScalar(4)
2650
2651status_t OpenGLRenderer::drawRect(float left, float top, float right, float bottom,
2652        const SkPaint* p) {
2653    if (currentSnapshot()->isIgnored() || quickRejectSetupScissor(left, top, right, bottom, p) ||
2654            (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) {
2655        return DrawGlInfo::kStatusDone;
2656    }
2657
2658    if (p->getStyle() != SkPaint::kFill_Style) {
2659        // only fill style is supported by drawConvexPath, since others have to handle joins
2660        if (p->getPathEffect() != 0 || p->getStrokeJoin() != SkPaint::kMiter_Join ||
2661                p->getStrokeMiter() != SkPaintDefaults_MiterLimit) {
2662            mCaches.activeTexture(0);
2663            const PathTexture* texture =
2664                    mCaches.pathCache.getRect(right - left, bottom - top, p);
2665            return drawShape(left, top, texture, p);
2666        }
2667
2668        SkPath path;
2669        SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2670        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2671            rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2672        }
2673        path.addRect(rect);
2674        return drawConvexPath(path, p);
2675    }
2676
2677    if (p->isAntiAlias() && !currentTransform()->isSimple()) {
2678        SkPath path;
2679        path.addRect(left, top, right, bottom);
2680        return drawConvexPath(path, p);
2681    } else {
2682        drawColorRect(left, top, right, bottom, p);
2683        return DrawGlInfo::kStatusDrew;
2684    }
2685}
2686
2687void OpenGLRenderer::drawTextShadow(const SkPaint* paint, const char* text,
2688        int bytesCount, int count, const float* positions,
2689        FontRenderer& fontRenderer, int alpha, float x, float y) {
2690    mCaches.activeTexture(0);
2691
2692    // NOTE: The drop shadow will not perform gamma correction
2693    //       if shader-based correction is enabled
2694    mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2695    const ShadowTexture* shadow = mCaches.dropShadowCache.get(
2696            paint, text, bytesCount, count, mDrawModifiers.mShadowRadius, positions);
2697    // If the drop shadow exceeds the max texture size or couldn't be
2698    // allocated, skip drawing
2699    if (!shadow) return;
2700    const AutoTexture autoCleanup(shadow);
2701
2702    const float sx = x - shadow->left + mDrawModifiers.mShadowDx;
2703    const float sy = y - shadow->top + mDrawModifiers.mShadowDy;
2704
2705    const int shadowAlpha = ((mDrawModifiers.mShadowColor >> 24) & 0xFF) * mSnapshot->alpha;
2706    int shadowColor = mDrawModifiers.mShadowColor;
2707    if (mDrawModifiers.mShader) {
2708        shadowColor = 0xffffffff;
2709    }
2710
2711    setupDraw();
2712    setupDrawWithTexture(true);
2713    setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
2714    setupDrawColorFilter(getColorFilter(paint));
2715    setupDrawShader();
2716    setupDrawBlending(paint, true);
2717    setupDrawProgram();
2718    setupDrawModelView(kModelViewMode_TranslateAndScale, false,
2719            sx, sy, sx + shadow->width, sy + shadow->height);
2720    setupDrawTexture(shadow->id);
2721    setupDrawPureColorUniforms();
2722    setupDrawColorFilterUniforms(getColorFilter(paint));
2723    setupDrawShaderUniforms();
2724    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2725
2726    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2727}
2728
2729bool OpenGLRenderer::canSkipText(const SkPaint* paint) const {
2730    float alpha = (mDrawModifiers.mHasShadow ? 1.0f : paint->getAlpha()) * mSnapshot->alpha;
2731    return alpha == 0.0f && getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode;
2732}
2733
2734status_t OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count,
2735        const float* positions, const SkPaint* paint) {
2736    if (text == NULL || count == 0 || currentSnapshot()->isIgnored() || canSkipText(paint)) {
2737        return DrawGlInfo::kStatusDone;
2738    }
2739
2740    // NOTE: Skia does not support perspective transform on drawPosText yet
2741    if (!currentTransform()->isSimple()) {
2742        return DrawGlInfo::kStatusDone;
2743    }
2744
2745    mCaches.enableScissor();
2746
2747    float x = 0.0f;
2748    float y = 0.0f;
2749    const bool pureTranslate = currentTransform()->isPureTranslate();
2750    if (pureTranslate) {
2751        x = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f);
2752        y = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f);
2753    }
2754
2755    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2756    fontRenderer.setFont(paint, mat4::identity());
2757
2758    int alpha;
2759    SkXfermode::Mode mode;
2760    getAlphaAndMode(paint, &alpha, &mode);
2761
2762    if (CC_UNLIKELY(mDrawModifiers.mHasShadow)) {
2763        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2764                alpha, 0.0f, 0.0f);
2765    }
2766
2767    // Pick the appropriate texture filtering
2768    bool linearFilter = currentTransform()->changesBounds();
2769    if (pureTranslate && !linearFilter) {
2770        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2771    }
2772    fontRenderer.setTextureFiltering(linearFilter);
2773
2774    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
2775    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2776
2777    const bool hasActiveLayer = hasLayer();
2778
2779    TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2780    if (fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2781            positions, hasActiveLayer ? &bounds : NULL, &functor)) {
2782        if (hasActiveLayer) {
2783            if (!pureTranslate) {
2784                currentTransform()->mapRect(bounds);
2785            }
2786            dirtyLayerUnchecked(bounds, getRegion());
2787        }
2788    }
2789
2790    return DrawGlInfo::kStatusDrew;
2791}
2792
2793mat4 OpenGLRenderer::findBestFontTransform(const mat4& transform) const {
2794    mat4 fontTransform;
2795    if (CC_LIKELY(transform.isPureTranslate())) {
2796        fontTransform = mat4::identity();
2797    } else {
2798        if (CC_UNLIKELY(transform.isPerspective())) {
2799            fontTransform = mat4::identity();
2800        } else {
2801            float sx, sy;
2802            currentTransform()->decomposeScale(sx, sy);
2803            fontTransform.loadScale(sx, sy, 1.0f);
2804        }
2805    }
2806    return fontTransform;
2807}
2808
2809status_t OpenGLRenderer::drawText(const char* text, int bytesCount, int count, float x, float y,
2810        const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds,
2811        DrawOpMode drawOpMode) {
2812
2813    if (drawOpMode == kDrawOpMode_Immediate) {
2814        // The checks for corner-case ignorable text and quick rejection is only done for immediate
2815        // drawing as ops from DeferredDisplayList are already filtered for these
2816        if (text == NULL || count == 0 || currentSnapshot()->isIgnored() || canSkipText(paint) ||
2817                quickRejectSetupScissor(bounds)) {
2818            return DrawGlInfo::kStatusDone;
2819        }
2820    }
2821
2822    const float oldX = x;
2823    const float oldY = y;
2824
2825    const mat4& transform = *currentTransform();
2826    const bool pureTranslate = transform.isPureTranslate();
2827
2828    if (CC_LIKELY(pureTranslate)) {
2829        x = (int) floorf(x + transform.getTranslateX() + 0.5f);
2830        y = (int) floorf(y + transform.getTranslateY() + 0.5f);
2831    }
2832
2833    int alpha;
2834    SkXfermode::Mode mode;
2835    getAlphaAndMode(paint, &alpha, &mode);
2836
2837    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2838
2839    if (CC_UNLIKELY(mDrawModifiers.mHasShadow)) {
2840        fontRenderer.setFont(paint, mat4::identity());
2841        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2842                alpha, oldX, oldY);
2843    }
2844
2845    const bool hasActiveLayer = hasLayer();
2846
2847    // We only pass a partial transform to the font renderer. That partial
2848    // matrix defines how glyphs are rasterized. Typically we want glyphs
2849    // to be rasterized at their final size on screen, which means the partial
2850    // matrix needs to take the scale factor into account.
2851    // When a partial matrix is used to transform glyphs during rasterization,
2852    // the mesh is generated with the inverse transform (in the case of scale,
2853    // the mesh is generated at 1.0 / scale for instance.) This allows us to
2854    // apply the full transform matrix at draw time in the vertex shader.
2855    // Applying the full matrix in the shader is the easiest way to handle
2856    // rotation and perspective and allows us to always generated quads in the
2857    // font renderer which greatly simplifies the code, clipping in particular.
2858    mat4 fontTransform = findBestFontTransform(transform);
2859    fontRenderer.setFont(paint, fontTransform);
2860
2861    // Pick the appropriate texture filtering
2862    bool linearFilter = !pureTranslate || fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2863    fontRenderer.setTextureFiltering(linearFilter);
2864
2865    // TODO: Implement better clipping for scaled/rotated text
2866    const Rect* clip = !pureTranslate ? NULL : currentClipRect();
2867    Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2868
2869    bool status;
2870    TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2871
2872    // don't call issuedrawcommand, do it at end of batch
2873    bool forceFinish = (drawOpMode != kDrawOpMode_Defer);
2874    if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) {
2875        SkPaint paintCopy(*paint);
2876        paintCopy.setTextAlign(SkPaint::kLeft_Align);
2877        status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y,
2878                positions, hasActiveLayer ? &layerBounds : NULL, &functor, forceFinish);
2879    } else {
2880        status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2881                positions, hasActiveLayer ? &layerBounds : NULL, &functor, forceFinish);
2882    }
2883
2884    if ((status || drawOpMode != kDrawOpMode_Immediate) && hasActiveLayer) {
2885        if (!pureTranslate) {
2886            transform.mapRect(layerBounds);
2887        }
2888        dirtyLayerUnchecked(layerBounds, getRegion());
2889    }
2890
2891    drawTextDecorations(totalAdvance, oldX, oldY, paint);
2892
2893    return DrawGlInfo::kStatusDrew;
2894}
2895
2896status_t OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count,
2897        const SkPath* path, float hOffset, float vOffset, const SkPaint* paint) {
2898    if (text == NULL || count == 0 || currentSnapshot()->isIgnored() || canSkipText(paint)) {
2899        return DrawGlInfo::kStatusDone;
2900    }
2901
2902    // TODO: avoid scissor by calculating maximum bounds using path bounds + font metrics
2903    mCaches.enableScissor();
2904
2905    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2906    fontRenderer.setFont(paint, mat4::identity());
2907    fontRenderer.setTextureFiltering(true);
2908
2909    int alpha;
2910    SkXfermode::Mode mode;
2911    getAlphaAndMode(paint, &alpha, &mode);
2912    TextSetupFunctor functor(this, 0.0f, 0.0f, false, alpha, mode, paint);
2913
2914    const Rect* clip = &mSnapshot->getLocalClip();
2915    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2916
2917    const bool hasActiveLayer = hasLayer();
2918
2919    if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path,
2920            hOffset, vOffset, hasActiveLayer ? &bounds : NULL, &functor)) {
2921        if (hasActiveLayer) {
2922            currentTransform()->mapRect(bounds);
2923            dirtyLayerUnchecked(bounds, getRegion());
2924        }
2925    }
2926
2927    return DrawGlInfo::kStatusDrew;
2928}
2929
2930status_t OpenGLRenderer::drawPath(const SkPath* path, const SkPaint* paint) {
2931    if (currentSnapshot()->isIgnored()) return DrawGlInfo::kStatusDone;
2932
2933    mCaches.activeTexture(0);
2934
2935    const PathTexture* texture = mCaches.pathCache.get(path, paint);
2936    if (!texture) return DrawGlInfo::kStatusDone;
2937    const AutoTexture autoCleanup(texture);
2938
2939    const float x = texture->left - texture->offset;
2940    const float y = texture->top - texture->offset;
2941
2942    drawPathTexture(texture, x, y, paint);
2943
2944    return DrawGlInfo::kStatusDrew;
2945}
2946
2947status_t OpenGLRenderer::drawLayer(Layer* layer, float x, float y) {
2948    if (!layer) {
2949        return DrawGlInfo::kStatusDone;
2950    }
2951
2952    mat4* transform = NULL;
2953    if (layer->isTextureLayer()) {
2954        transform = &layer->getTransform();
2955        if (!transform->isIdentity()) {
2956            save(0);
2957            concatMatrix(*transform);
2958        }
2959    }
2960
2961    bool clipRequired = false;
2962    const bool rejected = calculateQuickRejectForScissor(x, y,
2963            x + layer->layer.getWidth(), y + layer->layer.getHeight(), &clipRequired, false);
2964
2965    if (rejected) {
2966        if (transform && !transform->isIdentity()) {
2967            restore();
2968        }
2969        return DrawGlInfo::kStatusDone;
2970    }
2971
2972    updateLayer(layer, true);
2973
2974    mCaches.setScissorEnabled(mScissorOptimizationDisabled || clipRequired);
2975    mCaches.activeTexture(0);
2976
2977    if (CC_LIKELY(!layer->region.isEmpty())) {
2978        if (layer->region.isRect()) {
2979            DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
2980                    composeLayerRect(layer, layer->regionRect));
2981        } else if (layer->mesh) {
2982
2983            const float a = getLayerAlpha(layer);
2984            setupDraw();
2985            setupDrawWithTexture();
2986            setupDrawColor(a, a, a, a);
2987            setupDrawColorFilter(layer->getColorFilter());
2988            setupDrawBlending(layer);
2989            setupDrawProgram();
2990            setupDrawPureColorUniforms();
2991            setupDrawColorFilterUniforms(layer->getColorFilter());
2992            setupDrawTexture(layer->getTexture());
2993            if (CC_LIKELY(currentTransform()->isPureTranslate())) {
2994                int tx = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f);
2995                int ty = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f);
2996
2997                layer->setFilter(GL_NEAREST);
2998                setupDrawModelView(kModelViewMode_Translate, false, tx, ty,
2999                        tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true);
3000            } else {
3001                layer->setFilter(GL_LINEAR);
3002                setupDrawModelView(kModelViewMode_Translate, false, x, y,
3003                        x + layer->layer.getWidth(), y + layer->layer.getHeight());
3004            }
3005
3006            TextureVertex* mesh = &layer->mesh[0];
3007            GLsizei elementsCount = layer->meshElementCount;
3008
3009            while (elementsCount > 0) {
3010                GLsizei drawCount = min(elementsCount, (GLsizei) gMaxNumberOfQuads * 6);
3011
3012                setupDrawMeshIndices(&mesh[0].x, &mesh[0].u);
3013                DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
3014                        glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, NULL));
3015
3016                elementsCount -= drawCount;
3017                // Though there are 4 vertices in a quad, we use 6 indices per
3018                // quad to draw with GL_TRIANGLES
3019                mesh += (drawCount / 6) * 4;
3020            }
3021
3022#if DEBUG_LAYERS_AS_REGIONS
3023            drawRegionRectsDebug(layer->region);
3024#endif
3025        }
3026
3027        if (layer->debugDrawUpdate) {
3028            layer->debugDrawUpdate = false;
3029
3030            SkPaint paint;
3031            paint.setColor(0x7f00ff00);
3032            drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(), &paint);
3033        }
3034    }
3035    layer->hasDrawnSinceUpdate = true;
3036
3037    if (transform && !transform->isIdentity()) {
3038        restore();
3039    }
3040
3041    return DrawGlInfo::kStatusDrew;
3042}
3043
3044///////////////////////////////////////////////////////////////////////////////
3045// Shaders
3046///////////////////////////////////////////////////////////////////////////////
3047
3048void OpenGLRenderer::resetShader() {
3049    mDrawModifiers.mShader = NULL;
3050}
3051
3052void OpenGLRenderer::setupShader(SkiaShader* shader) {
3053    mDrawModifiers.mShader = shader;
3054    if (mDrawModifiers.mShader) {
3055        mDrawModifiers.mShader->setCaches(mCaches);
3056    }
3057}
3058
3059///////////////////////////////////////////////////////////////////////////////
3060// Drop shadow
3061///////////////////////////////////////////////////////////////////////////////
3062
3063void OpenGLRenderer::resetShadow() {
3064    mDrawModifiers.mHasShadow = false;
3065}
3066
3067void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
3068    mDrawModifiers.mHasShadow = true;
3069    mDrawModifiers.mShadowRadius = radius;
3070    mDrawModifiers.mShadowDx = dx;
3071    mDrawModifiers.mShadowDy = dy;
3072    mDrawModifiers.mShadowColor = color;
3073}
3074
3075///////////////////////////////////////////////////////////////////////////////
3076// Draw filters
3077///////////////////////////////////////////////////////////////////////////////
3078
3079void OpenGLRenderer::resetPaintFilter() {
3080    // when clearing the PaintFilter, the masks should also be cleared for simple DrawModifier
3081    // comparison, see MergingDrawBatch::canMergeWith
3082    mDrawModifiers.mHasDrawFilter = false;
3083    mDrawModifiers.mPaintFilterClearBits = 0;
3084    mDrawModifiers.mPaintFilterSetBits = 0;
3085}
3086
3087void OpenGLRenderer::setupPaintFilter(int clearBits, int setBits) {
3088    mDrawModifiers.mHasDrawFilter = true;
3089    mDrawModifiers.mPaintFilterClearBits = clearBits & SkPaint::kAllFlags;
3090    mDrawModifiers.mPaintFilterSetBits = setBits & SkPaint::kAllFlags;
3091}
3092
3093const SkPaint* OpenGLRenderer::filterPaint(const SkPaint* paint) {
3094    if (CC_LIKELY(!mDrawModifiers.mHasDrawFilter || !paint)) {
3095        return paint;
3096    }
3097
3098    uint32_t flags = paint->getFlags();
3099
3100    mFilteredPaint = *paint;
3101    mFilteredPaint.setFlags((flags & ~mDrawModifiers.mPaintFilterClearBits) |
3102            mDrawModifiers.mPaintFilterSetBits);
3103
3104    return &mFilteredPaint;
3105}
3106
3107///////////////////////////////////////////////////////////////////////////////
3108// Drawing implementation
3109///////////////////////////////////////////////////////////////////////////////
3110
3111Texture* OpenGLRenderer::getTexture(const SkBitmap* bitmap) {
3112    Texture* texture = mCaches.assetAtlas.getEntryTexture(bitmap);
3113    if (!texture) {
3114        return mCaches.textureCache.get(bitmap);
3115    }
3116    return texture;
3117}
3118
3119void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
3120        float x, float y, const SkPaint* paint) {
3121    if (quickRejectSetupScissor(x, y, x + texture->width, y + texture->height)) {
3122        return;
3123    }
3124
3125    int alpha;
3126    SkXfermode::Mode mode;
3127    getAlphaAndMode(paint, &alpha, &mode);
3128
3129    setupDraw();
3130    setupDrawWithTexture(true);
3131    setupDrawAlpha8Color(paint->getColor(), alpha);
3132    setupDrawColorFilter(getColorFilter(paint));
3133    setupDrawShader();
3134    setupDrawBlending(paint, true);
3135    setupDrawProgram();
3136    setupDrawModelView(kModelViewMode_TranslateAndScale, false,
3137            x, y, x + texture->width, y + texture->height);
3138    setupDrawTexture(texture->id);
3139    setupDrawPureColorUniforms();
3140    setupDrawColorFilterUniforms(getColorFilter(paint));
3141    setupDrawShaderUniforms();
3142    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
3143
3144    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
3145}
3146
3147// Same values used by Skia
3148#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
3149#define kStdUnderline_Offset    (1.0f / 9.0f)
3150#define kStdUnderline_Thickness (1.0f / 18.0f)
3151
3152void OpenGLRenderer::drawTextDecorations(float underlineWidth, float x, float y,
3153        const SkPaint* paint) {
3154    // Handle underline and strike-through
3155    uint32_t flags = paint->getFlags();
3156    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
3157        SkPaint paintCopy(*paint);
3158
3159        if (CC_LIKELY(underlineWidth > 0.0f)) {
3160            const float textSize = paintCopy.getTextSize();
3161            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
3162
3163            const float left = x;
3164            float top = 0.0f;
3165
3166            int linesCount = 0;
3167            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
3168            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
3169
3170            const int pointsCount = 4 * linesCount;
3171            float points[pointsCount];
3172            int currentPoint = 0;
3173
3174            if (flags & SkPaint::kUnderlineText_Flag) {
3175                top = y + textSize * kStdUnderline_Offset;
3176                points[currentPoint++] = left;
3177                points[currentPoint++] = top;
3178                points[currentPoint++] = left + underlineWidth;
3179                points[currentPoint++] = top;
3180            }
3181
3182            if (flags & SkPaint::kStrikeThruText_Flag) {
3183                top = y + textSize * kStdStrikeThru_Offset;
3184                points[currentPoint++] = left;
3185                points[currentPoint++] = top;
3186                points[currentPoint++] = left + underlineWidth;
3187                points[currentPoint++] = top;
3188            }
3189
3190            paintCopy.setStrokeWidth(strokeWidth);
3191
3192            drawLines(&points[0], pointsCount, &paintCopy);
3193        }
3194    }
3195}
3196
3197status_t OpenGLRenderer::drawRects(const float* rects, int count, const SkPaint* paint) {
3198    if (currentSnapshot()->isIgnored()) {
3199        return DrawGlInfo::kStatusDone;
3200    }
3201
3202    return drawColorRects(rects, count, paint, false, true, true);
3203}
3204
3205status_t OpenGLRenderer::drawShadow(const mat4& casterTransform, float casterAlpha,
3206        const SkPath* casterOutline) {
3207    if (currentSnapshot()->isIgnored()) return DrawGlInfo::kStatusDone;
3208
3209    // TODO: use quickRejectWithScissor. For now, always force enable scissor.
3210    mCaches.enableScissor();
3211
3212    SkPaint paint;
3213    paint.setAntiAlias(true); // want to use AlphaVertex
3214
3215    // tessellate caster outline into a 2d polygon
3216    Vector<Vertex> casterVertices2d;
3217    const float casterRefinementThresholdSquared = 20.0f; // TODO: experiment with this value
3218    PathTessellator::approximatePathOutlineVertices(*casterOutline,
3219            casterRefinementThresholdSquared, casterVertices2d);
3220
3221    if (casterVertices2d.size() == 0) {
3222        // empty caster polygon computed from path
3223        return DrawGlInfo::kStatusDone;
3224    }
3225
3226    // map 2d caster poly into 3d
3227    const int casterVertexCount = casterVertices2d.size();
3228    Vector3 casterPolygon[casterVertexCount];
3229    for (int i = 0; i < casterVertexCount; i++) {
3230        const Vertex& point2d = casterVertices2d[i];
3231        casterPolygon[i] = Vector3(point2d.x, point2d.y, 0);
3232        casterTransform.mapPoint3d(casterPolygon[i]);
3233    }
3234
3235    // draw caster's shadows
3236    if (mCaches.propertyAmbientShadowStrength > 0) {
3237        paint.setARGB(mCaches.propertyAmbientShadowStrength, 0, 0, 0);
3238        VertexBuffer ambientShadowVertexBuffer;
3239        ShadowTessellator::tessellateAmbientShadow(casterPolygon, casterVertexCount,
3240                ambientShadowVertexBuffer);
3241        drawVertexBuffer(ambientShadowVertexBuffer, &paint);
3242    }
3243
3244    if (mCaches.propertySpotShadowStrength > 0) {
3245        paint.setARGB(mCaches.propertySpotShadowStrength, 0, 0, 0);
3246        VertexBuffer spotShadowVertexBuffer;
3247        Vector3 lightPosScale(mCaches.propertyLightPosXScale,
3248                mCaches.propertyLightPosYScale, mCaches.propertyLightPosZScale);
3249        ShadowTessellator::tessellateSpotShadow(casterPolygon, casterVertexCount,
3250                lightPosScale, *currentTransform(), getWidth(), getHeight(),
3251                spotShadowVertexBuffer);
3252
3253        drawVertexBuffer(spotShadowVertexBuffer, &paint);
3254    }
3255
3256    return DrawGlInfo::kStatusDrew;
3257}
3258
3259status_t OpenGLRenderer::drawColorRects(const float* rects, int count, const SkPaint* paint,
3260        bool ignoreTransform, bool dirty, bool clip) {
3261    if (count == 0) {
3262        return DrawGlInfo::kStatusDone;
3263    }
3264
3265    int color = paint->getColor();
3266    // If a shader is set, preserve only the alpha
3267    if (mDrawModifiers.mShader) {
3268        color |= 0x00ffffff;
3269    }
3270
3271    float left = FLT_MAX;
3272    float top = FLT_MAX;
3273    float right = FLT_MIN;
3274    float bottom = FLT_MIN;
3275
3276    Vertex mesh[count];
3277    Vertex* vertex = mesh;
3278
3279    for (int index = 0; index < count; index += 4) {
3280        float l = rects[index + 0];
3281        float t = rects[index + 1];
3282        float r = rects[index + 2];
3283        float b = rects[index + 3];
3284
3285        Vertex::set(vertex++, l, t);
3286        Vertex::set(vertex++, r, t);
3287        Vertex::set(vertex++, l, b);
3288        Vertex::set(vertex++, r, b);
3289
3290        left = fminf(left, l);
3291        top = fminf(top, t);
3292        right = fmaxf(right, r);
3293        bottom = fmaxf(bottom, b);
3294    }
3295
3296    if (clip && quickRejectSetupScissor(left, top, right, bottom)) {
3297        return DrawGlInfo::kStatusDone;
3298    }
3299
3300    setupDraw();
3301    setupDrawNoTexture();
3302    setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha);
3303    setupDrawShader();
3304    setupDrawColorFilter(getColorFilter(paint));
3305    setupDrawBlending(paint);
3306    setupDrawProgram();
3307    setupDrawDirtyRegionsDisabled();
3308    setupDrawModelView(kModelViewMode_Translate, false,
3309            0.0f, 0.0f, 0.0f, 0.0f, ignoreTransform);
3310    setupDrawColorUniforms();
3311    setupDrawShaderUniforms();
3312    setupDrawColorFilterUniforms(getColorFilter(paint));
3313
3314    if (dirty && hasLayer()) {
3315        dirtyLayer(left, top, right, bottom, *currentTransform());
3316    }
3317
3318    issueIndexedQuadDraw(&mesh[0], count / 4);
3319
3320    return DrawGlInfo::kStatusDrew;
3321}
3322
3323void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
3324        const SkPaint* paint, bool ignoreTransform) {
3325    int color = paint->getColor();
3326    // If a shader is set, preserve only the alpha
3327    if (mDrawModifiers.mShader) {
3328        color |= 0x00ffffff;
3329    }
3330
3331    setupDraw();
3332    setupDrawNoTexture();
3333    setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha);
3334    setupDrawShader();
3335    setupDrawColorFilter(getColorFilter(paint));
3336    setupDrawBlending(paint);
3337    setupDrawProgram();
3338    setupDrawModelView(kModelViewMode_TranslateAndScale, false,
3339            left, top, right, bottom, ignoreTransform);
3340    setupDrawColorUniforms();
3341    setupDrawShaderUniforms(ignoreTransform);
3342    setupDrawColorFilterUniforms(getColorFilter(paint));
3343    setupDrawSimpleMesh();
3344
3345    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
3346}
3347
3348void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3349        Texture* texture, const SkPaint* paint) {
3350    texture->setWrap(GL_CLAMP_TO_EDGE, true);
3351
3352    GLvoid* vertices = (GLvoid*) NULL;
3353    GLvoid* texCoords = (GLvoid*) gMeshTextureOffset;
3354
3355    if (texture->uvMapper) {
3356        vertices = &mMeshVertices[0].x;
3357        texCoords = &mMeshVertices[0].u;
3358
3359        Rect uvs(0.0f, 0.0f, 1.0f, 1.0f);
3360        texture->uvMapper->map(uvs);
3361
3362        resetDrawTextureTexCoords(uvs.left, uvs.top, uvs.right, uvs.bottom);
3363    }
3364
3365    if (CC_LIKELY(currentTransform()->isPureTranslate())) {
3366        const float x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f);
3367        const float y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f);
3368
3369        texture->setFilter(GL_NEAREST, true);
3370        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
3371                paint, texture->blend, vertices, texCoords,
3372                GL_TRIANGLE_STRIP, gMeshCount, false, true);
3373    } else {
3374        texture->setFilter(FILTER(paint), true);
3375        drawTextureMesh(left, top, right, bottom, texture->id, paint,
3376                texture->blend, vertices, texCoords, GL_TRIANGLE_STRIP, gMeshCount);
3377    }
3378
3379    if (texture->uvMapper) {
3380        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
3381    }
3382}
3383
3384void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
3385        GLuint texture, const SkPaint* paint, bool blend,
3386        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3387        bool swapSrcDst, bool ignoreTransform, GLuint vbo,
3388        ModelViewMode modelViewMode, bool dirty) {
3389
3390    int a;
3391    SkXfermode::Mode mode;
3392    getAlphaAndMode(paint, &a, &mode);
3393    const float alpha = a / 255.0f;
3394
3395    setupDraw();
3396    setupDrawWithTexture();
3397    setupDrawColor(alpha, alpha, alpha, alpha);
3398    setupDrawColorFilter(getColorFilter(paint));
3399    setupDrawBlending(paint, blend, swapSrcDst);
3400    setupDrawProgram();
3401    if (!dirty) setupDrawDirtyRegionsDisabled();
3402    setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform);
3403    setupDrawTexture(texture);
3404    setupDrawPureColorUniforms();
3405    setupDrawColorFilterUniforms(getColorFilter(paint));
3406    setupDrawMesh(vertices, texCoords, vbo);
3407
3408    glDrawArrays(drawMode, 0, elementsCount);
3409}
3410
3411void OpenGLRenderer::drawIndexedTextureMesh(float left, float top, float right, float bottom,
3412        GLuint texture, const SkPaint* paint, bool blend,
3413        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3414        bool swapSrcDst, bool ignoreTransform, GLuint vbo,
3415        ModelViewMode modelViewMode, bool dirty) {
3416
3417    int a;
3418    SkXfermode::Mode mode;
3419    getAlphaAndMode(paint, &a, &mode);
3420    const float alpha = a / 255.0f;
3421
3422    setupDraw();
3423    setupDrawWithTexture();
3424    setupDrawColor(alpha, alpha, alpha, alpha);
3425    setupDrawColorFilter(getColorFilter(paint));
3426    setupDrawBlending(paint, blend, swapSrcDst);
3427    setupDrawProgram();
3428    if (!dirty) setupDrawDirtyRegionsDisabled();
3429    setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform);
3430    setupDrawTexture(texture);
3431    setupDrawPureColorUniforms();
3432    setupDrawColorFilterUniforms(getColorFilter(paint));
3433    setupDrawMeshIndices(vertices, texCoords, vbo);
3434
3435    glDrawElements(drawMode, elementsCount, GL_UNSIGNED_SHORT, NULL);
3436}
3437
3438void OpenGLRenderer::drawAlpha8TextureMesh(float left, float top, float right, float bottom,
3439        GLuint texture, const SkPaint* paint,
3440        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3441        bool ignoreTransform, ModelViewMode modelViewMode, bool dirty) {
3442
3443    int color = paint != NULL ? paint->getColor() : 0;
3444    int alpha;
3445    SkXfermode::Mode mode;
3446    getAlphaAndMode(paint, &alpha, &mode);
3447
3448    setupDraw();
3449    setupDrawWithTexture(true);
3450    if (paint != NULL) {
3451        setupDrawAlpha8Color(color, alpha);
3452    }
3453    setupDrawColorFilter(getColorFilter(paint));
3454    setupDrawShader();
3455    setupDrawBlending(paint, true);
3456    setupDrawProgram();
3457    if (!dirty) setupDrawDirtyRegionsDisabled();
3458    setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform);
3459    setupDrawTexture(texture);
3460    setupDrawPureColorUniforms();
3461    setupDrawColorFilterUniforms(getColorFilter(paint));
3462    setupDrawShaderUniforms(ignoreTransform);
3463    setupDrawMesh(vertices, texCoords);
3464
3465    glDrawArrays(drawMode, 0, elementsCount);
3466}
3467
3468void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
3469        ProgramDescription& description, bool swapSrcDst) {
3470    if (mCountOverdraw) {
3471        if (!mCaches.blend) glEnable(GL_BLEND);
3472        if (mCaches.lastSrcMode != GL_ONE || mCaches.lastDstMode != GL_ONE) {
3473            glBlendFunc(GL_ONE, GL_ONE);
3474        }
3475
3476        mCaches.blend = true;
3477        mCaches.lastSrcMode = GL_ONE;
3478        mCaches.lastDstMode = GL_ONE;
3479
3480        return;
3481    }
3482
3483    blend = blend || mode != SkXfermode::kSrcOver_Mode;
3484
3485    if (blend) {
3486        // These blend modes are not supported by OpenGL directly and have
3487        // to be implemented using shaders. Since the shader will perform
3488        // the blending, turn blending off here
3489        // If the blend mode cannot be implemented using shaders, fall
3490        // back to the default SrcOver blend mode instead
3491        if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) {
3492            if (CC_UNLIKELY(mExtensions.hasFramebufferFetch())) {
3493                description.framebufferMode = mode;
3494                description.swapSrcDst = swapSrcDst;
3495
3496                if (mCaches.blend) {
3497                    glDisable(GL_BLEND);
3498                    mCaches.blend = false;
3499                }
3500
3501                return;
3502            } else {
3503                mode = SkXfermode::kSrcOver_Mode;
3504            }
3505        }
3506
3507        if (!mCaches.blend) {
3508            glEnable(GL_BLEND);
3509        }
3510
3511        GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
3512        GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
3513
3514        if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
3515            glBlendFunc(sourceMode, destMode);
3516            mCaches.lastSrcMode = sourceMode;
3517            mCaches.lastDstMode = destMode;
3518        }
3519    } else if (mCaches.blend) {
3520        glDisable(GL_BLEND);
3521    }
3522    mCaches.blend = blend;
3523}
3524
3525bool OpenGLRenderer::useProgram(Program* program) {
3526    if (!program->isInUse()) {
3527        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
3528        program->use();
3529        mCaches.currentProgram = program;
3530        return false;
3531    }
3532    return true;
3533}
3534
3535void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
3536    TextureVertex* v = &mMeshVertices[0];
3537    TextureVertex::setUV(v++, u1, v1);
3538    TextureVertex::setUV(v++, u2, v1);
3539    TextureVertex::setUV(v++, u1, v2);
3540    TextureVertex::setUV(v++, u2, v2);
3541}
3542
3543void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) const {
3544    getAlphaAndModeDirect(paint, alpha,  mode);
3545    if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) {
3546        // if drawing a layer, ignore the paint's alpha
3547        *alpha = mDrawModifiers.mOverrideLayerAlpha * 255;
3548    }
3549    *alpha *= currentSnapshot()->alpha;
3550}
3551
3552float OpenGLRenderer::getLayerAlpha(const Layer* layer) const {
3553    float alpha;
3554    if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) {
3555        alpha = mDrawModifiers.mOverrideLayerAlpha;
3556    } else {
3557        alpha = layer->getAlpha() / 255.0f;
3558    }
3559    return alpha * currentSnapshot()->alpha;
3560}
3561
3562}; // namespace uirenderer
3563}; // namespace android
3564