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