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