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