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