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