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