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