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