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