OpenGLRenderer.cpp revision 487a92caef2eb90a62e8f8d7a6fe6315f1c1d8d8
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
1451static void handlePoint(std::vector<Vertex>& rectangleVertices, const Matrix4& transform,
1452        float x, float y) {
1453    Vertex v;
1454    v.x = x;
1455    v.y = y;
1456    transform.mapPoint(v.x, v.y);
1457    rectangleVertices.push_back(v);
1458}
1459
1460static void handlePointNoTransform(std::vector<Vertex>& rectangleVertices, float x, float y) {
1461    Vertex v;
1462    v.x = x;
1463    v.y = y;
1464    rectangleVertices.push_back(v);
1465}
1466
1467void OpenGLRenderer::drawRectangleList(const RectangleList& rectangleList) {
1468    int count = rectangleList.getTransformedRectanglesCount();
1469    std::vector<Vertex> rectangleVertices(count * 4);
1470    Rect scissorBox = rectangleList.calculateBounds();
1471    scissorBox.snapToPixelBoundaries();
1472    for (int i = 0; i < count; ++i) {
1473        const TransformedRectangle& tr(rectangleList.getTransformedRectangle(i));
1474        const Matrix4& transform = tr.getTransform();
1475        Rect bounds = tr.getBounds();
1476        if (transform.rectToRect()) {
1477            transform.mapRect(bounds);
1478            if (!bounds.intersect(scissorBox)) {
1479                bounds.setEmpty();
1480            } else {
1481                handlePointNoTransform(rectangleVertices, bounds.left, bounds.top);
1482                handlePointNoTransform(rectangleVertices, bounds.right, bounds.top);
1483                handlePointNoTransform(rectangleVertices, bounds.left, bounds.bottom);
1484                handlePointNoTransform(rectangleVertices, bounds.right, bounds.bottom);
1485            }
1486        } else {
1487            handlePoint(rectangleVertices, transform, bounds.left, bounds.top);
1488            handlePoint(rectangleVertices, transform, bounds.right, bounds.top);
1489            handlePoint(rectangleVertices, transform, bounds.left, bounds.bottom);
1490            handlePoint(rectangleVertices, transform, bounds.right, bounds.bottom);
1491        }
1492    }
1493
1494    mCaches.setScissor(scissorBox.left, getViewportHeight() - scissorBox.bottom,
1495            scissorBox.getWidth(), scissorBox.getHeight());
1496
1497    const SkPaint* paint = nullptr;
1498    setupDraw();
1499    setupDrawNoTexture();
1500    setupDrawColor(0, 0xff * currentSnapshot()->alpha);
1501    setupDrawShader(getShader(paint));
1502    setupDrawColorFilter(getColorFilter(paint));
1503    setupDrawBlending(paint);
1504    setupDrawProgram();
1505    setupDrawDirtyRegionsDisabled();
1506    setupDrawModelView(kModelViewMode_Translate, false,
1507            0.0f, 0.0f, 0.0f, 0.0f, true);
1508    setupDrawColorUniforms(getShader(paint));
1509    setupDrawShaderUniforms(getShader(paint));
1510    setupDrawColorFilterUniforms(getColorFilter(paint));
1511
1512    issueIndexedQuadDraw(&rectangleVertices[0], rectangleVertices.size() / 4);
1513}
1514
1515void OpenGLRenderer::setStencilFromClip() {
1516    if (!mCaches.debugOverdraw) {
1517        if (!currentSnapshot()->clipIsSimple()) {
1518            int incrementThreshold;
1519            EVENT_LOGD("setStencilFromClip - enabling");
1520
1521            // NOTE: The order here is important, we must set dirtyClip to false
1522            //       before any draw call to avoid calling back into this method
1523            mState.setDirtyClip(false);
1524
1525            ensureStencilBuffer();
1526
1527            const ClipArea& clipArea = currentSnapshot()->getClipArea();
1528
1529            bool isRectangleList = clipArea.isRectangleList();
1530            if (isRectangleList) {
1531                incrementThreshold = clipArea.getRectangleList().getTransformedRectanglesCount();
1532            } else {
1533                incrementThreshold = 0;
1534            }
1535
1536            mCaches.stencil.enableWrite(incrementThreshold);
1537
1538            // Clean and update the stencil, but first make sure we restrict drawing
1539            // to the region's bounds
1540            bool resetScissor = mCaches.enableScissor();
1541            if (resetScissor) {
1542                // The scissor was not set so we now need to update it
1543                setScissorFromClip();
1544            }
1545
1546            mCaches.stencil.clear();
1547
1548            // stash and disable the outline clip state, since stencil doesn't account for outline
1549            bool storedSkipOutlineClip = mSkipOutlineClip;
1550            mSkipOutlineClip = true;
1551
1552            SkPaint paint;
1553            paint.setColor(SK_ColorBLACK);
1554            paint.setXfermodeMode(SkXfermode::kSrc_Mode);
1555
1556            if (isRectangleList) {
1557                drawRectangleList(clipArea.getRectangleList());
1558            } else {
1559                // NOTE: We could use the region contour path to generate a smaller mesh
1560                //       Since we are using the stencil we could use the red book path
1561                //       drawing technique. It might increase bandwidth usage though.
1562
1563                // The last parameter is important: we are not drawing in the color buffer
1564                // so we don't want to dirty the current layer, if any
1565                drawRegionRects(clipArea.getClipRegion(), paint, false);
1566            }
1567            if (resetScissor) mCaches.disableScissor();
1568            mSkipOutlineClip = storedSkipOutlineClip;
1569
1570            mCaches.stencil.enableTest(incrementThreshold);
1571
1572            // Draw the region used to generate the stencil if the appropriate debug
1573            // mode is enabled
1574            // TODO: Implement for rectangle list clip areas
1575            if (mCaches.debugStencilClip == Caches::kStencilShowRegion &&
1576                    !clipArea.isRectangleList()) {
1577                paint.setColor(0x7f0000ff);
1578                paint.setXfermodeMode(SkXfermode::kSrcOver_Mode);
1579                drawRegionRects(currentSnapshot()->getClipRegion(), paint);
1580            }
1581        } else {
1582            EVENT_LOGD("setStencilFromClip - disabling");
1583            mCaches.stencil.disable();
1584        }
1585    }
1586}
1587
1588/**
1589 * Returns false and sets scissor enable based upon bounds if drawing won't be clipped out.
1590 *
1591 * @param paint if not null, the bounds will be expanded to account for stroke depending on paint
1592 *         style, and tessellated AA ramp
1593 */
1594bool OpenGLRenderer::quickRejectSetupScissor(float left, float top, float right, float bottom,
1595        const SkPaint* paint) {
1596    bool snapOut = paint && paint->isAntiAlias();
1597
1598    if (paint && paint->getStyle() != SkPaint::kFill_Style) {
1599        float outset = paint->getStrokeWidth() * 0.5f;
1600        left -= outset;
1601        top -= outset;
1602        right += outset;
1603        bottom += outset;
1604    }
1605
1606    bool clipRequired = false;
1607    bool roundRectClipRequired = false;
1608    if (mState.calculateQuickRejectForScissor(left, top, right, bottom,
1609            &clipRequired, &roundRectClipRequired, snapOut)) {
1610        return true;
1611    }
1612
1613    // not quick rejected, so enable the scissor if clipRequired
1614    mCaches.setScissorEnabled(mScissorOptimizationDisabled || clipRequired);
1615    mSkipOutlineClip = !roundRectClipRequired;
1616    return false;
1617}
1618
1619void OpenGLRenderer::debugClip() {
1620#if DEBUG_CLIP_REGIONS
1621    if (!currentSnapshot()->clipRegion->isEmpty()) {
1622        SkPaint paint;
1623        paint.setColor(0x7f00ff00);
1624        drawRegionRects(*(currentSnapshot()->clipRegion, paint);
1625
1626    }
1627#endif
1628}
1629
1630///////////////////////////////////////////////////////////////////////////////
1631// Drawing commands
1632///////////////////////////////////////////////////////////////////////////////
1633
1634void OpenGLRenderer::setupDraw(bool clearLayer) {
1635    // TODO: It would be best if we could do this before quickRejectSetupScissor()
1636    //       changes the scissor test state
1637    if (clearLayer) clearLayerRegions();
1638    // Make sure setScissor & setStencil happen at the beginning of
1639    // this method
1640    if (mState.getDirtyClip()) {
1641        if (mCaches.scissorEnabled) {
1642            setScissorFromClip();
1643        }
1644
1645        setStencilFromClip();
1646    }
1647
1648    mDescription.reset();
1649
1650    mSetShaderColor = false;
1651    mColorSet = false;
1652    mColorA = mColorR = mColorG = mColorB = 0.0f;
1653    mTextureUnit = 0;
1654    mTrackDirtyRegions = true;
1655
1656    // Enable debug highlight when what we're about to draw is tested against
1657    // the stencil buffer and if stencil highlight debugging is on
1658    mDescription.hasDebugHighlight = !mCaches.debugOverdraw &&
1659            mCaches.debugStencilClip == Caches::kStencilShowHighlight &&
1660            mCaches.stencil.isTestEnabled();
1661}
1662
1663void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
1664    mDescription.hasTexture = true;
1665    mDescription.hasAlpha8Texture = isAlpha8;
1666}
1667
1668void OpenGLRenderer::setupDrawWithTextureAndColor(bool isAlpha8) {
1669    mDescription.hasTexture = true;
1670    mDescription.hasColors = true;
1671    mDescription.hasAlpha8Texture = isAlpha8;
1672}
1673
1674void OpenGLRenderer::setupDrawWithExternalTexture() {
1675    mDescription.hasExternalTexture = true;
1676}
1677
1678void OpenGLRenderer::setupDrawNoTexture() {
1679    mCaches.disableTexCoordsVertexArray();
1680}
1681
1682void OpenGLRenderer::setupDrawVertexAlpha(bool useShadowAlphaInterp) {
1683    mDescription.hasVertexAlpha = true;
1684    mDescription.useShadowAlphaInterp = useShadowAlphaInterp;
1685}
1686
1687void OpenGLRenderer::setupDrawColor(int color, int alpha) {
1688    mColorA = alpha / 255.0f;
1689    mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1690    mColorG = mColorA * ((color >>  8) & 0xFF) / 255.0f;
1691    mColorB = mColorA * ((color      ) & 0xFF) / 255.0f;
1692    mColorSet = true;
1693    mSetShaderColor = mDescription.setColorModulate(mColorA);
1694}
1695
1696void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
1697    mColorA = alpha / 255.0f;
1698    mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1699    mColorG = mColorA * ((color >>  8) & 0xFF) / 255.0f;
1700    mColorB = mColorA * ((color      ) & 0xFF) / 255.0f;
1701    mColorSet = true;
1702    mSetShaderColor = mDescription.setAlpha8ColorModulate(mColorR, mColorG, mColorB, mColorA);
1703}
1704
1705void OpenGLRenderer::setupDrawTextGamma(const SkPaint* paint) {
1706    mCaches.fontRenderer->describe(mDescription, paint);
1707}
1708
1709void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
1710    mColorA = a;
1711    mColorR = r;
1712    mColorG = g;
1713    mColorB = b;
1714    mColorSet = true;
1715    mSetShaderColor = mDescription.setColorModulate(a);
1716}
1717
1718void OpenGLRenderer::setupDrawShader(const SkShader* shader) {
1719    if (shader != nullptr) {
1720        SkiaShader::describe(&mCaches, mDescription, mExtensions, *shader);
1721    }
1722}
1723
1724void OpenGLRenderer::setupDrawColorFilter(const SkColorFilter* filter) {
1725    if (filter == nullptr) {
1726        return;
1727    }
1728
1729    SkXfermode::Mode mode;
1730    if (filter->asColorMode(nullptr, &mode)) {
1731        mDescription.colorOp = ProgramDescription::kColorBlend;
1732        mDescription.colorMode = mode;
1733    } else if (filter->asColorMatrix(nullptr)) {
1734        mDescription.colorOp = ProgramDescription::kColorMatrix;
1735    }
1736}
1737
1738void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
1739    if (mColorSet && mode == SkXfermode::kClear_Mode) {
1740        mColorA = 1.0f;
1741        mColorR = mColorG = mColorB = 0.0f;
1742        mSetShaderColor = mDescription.modulate = true;
1743    }
1744}
1745
1746void OpenGLRenderer::setupDrawBlending(const Layer* layer, bool swapSrcDst) {
1747    SkXfermode::Mode mode = layer->getMode();
1748    // When the blending mode is kClear_Mode, we need to use a modulate color
1749    // argb=1,0,0,0
1750    accountForClear(mode);
1751    // TODO: check shader blending, once we have shader drawing support for layers.
1752    bool blend = layer->isBlend()
1753            || getLayerAlpha(layer) < 1.0f
1754            || (mColorSet && mColorA < 1.0f)
1755            || PaintUtils::isBlendedColorFilter(layer->getColorFilter());
1756    chooseBlending(blend, mode, mDescription, swapSrcDst);
1757}
1758
1759void OpenGLRenderer::setupDrawBlending(const SkPaint* paint, bool blend, bool swapSrcDst) {
1760    SkXfermode::Mode mode = getXfermodeDirect(paint);
1761    // When the blending mode is kClear_Mode, we need to use a modulate color
1762    // argb=1,0,0,0
1763    accountForClear(mode);
1764    blend |= (mColorSet && mColorA < 1.0f) ||
1765            (getShader(paint) && !getShader(paint)->isOpaque()) ||
1766            PaintUtils::isBlendedColorFilter(getColorFilter(paint));
1767    chooseBlending(blend, mode, mDescription, swapSrcDst);
1768}
1769
1770void OpenGLRenderer::setupDrawProgram() {
1771    useProgram(mCaches.programCache.get(mDescription));
1772    if (mDescription.hasRoundRectClip) {
1773        // TODO: avoid doing this repeatedly, stashing state pointer in program
1774        const RoundRectClipState* state = writableSnapshot()->roundRectClipState;
1775        const Rect& innerRect = state->innerRect;
1776        glUniform4f(mCaches.currentProgram->getUniform("roundRectInnerRectLTRB"),
1777                innerRect.left, innerRect.top,
1778                innerRect.right, innerRect.bottom);
1779        glUniformMatrix4fv(mCaches.currentProgram->getUniform("roundRectInvTransform"),
1780                1, GL_FALSE, &state->matrix.data[0]);
1781
1782        // add half pixel to round out integer rect space to cover pixel centers
1783        float roundedOutRadius = state->radius + 0.5f;
1784        glUniform1f(mCaches.currentProgram->getUniform("roundRectRadius"),
1785                roundedOutRadius);
1786    }
1787}
1788
1789void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
1790    mTrackDirtyRegions = false;
1791}
1792
1793void OpenGLRenderer::setupDrawModelView(ModelViewMode mode, bool offset,
1794        float left, float top, float right, float bottom, bool ignoreTransform) {
1795    mModelViewMatrix.loadTranslate(left, top, 0.0f);
1796    if (mode == kModelViewMode_TranslateAndScale) {
1797        mModelViewMatrix.scale(right - left, bottom - top, 1.0f);
1798    }
1799
1800    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
1801    const Matrix4& transformMatrix = ignoreTransform ? Matrix4::identity() : *currentTransform();
1802    mCaches.currentProgram->set(writableSnapshot()->getOrthoMatrix(),
1803            mModelViewMatrix, transformMatrix, offset);
1804    if (dirty && mTrackDirtyRegions) {
1805        if (!ignoreTransform) {
1806            dirtyLayer(left, top, right, bottom, *currentTransform());
1807        } else {
1808            dirtyLayer(left, top, right, bottom);
1809        }
1810    }
1811}
1812
1813void OpenGLRenderer::setupDrawColorUniforms(bool hasShader) {
1814    if ((mColorSet && !hasShader) || (hasShader && mSetShaderColor)) {
1815        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1816    }
1817}
1818
1819void OpenGLRenderer::setupDrawPureColorUniforms() {
1820    if (mSetShaderColor) {
1821        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1822    }
1823}
1824
1825void OpenGLRenderer::setupDrawShaderUniforms(const SkShader* shader, bool ignoreTransform) {
1826    if (shader == nullptr) {
1827        return;
1828    }
1829
1830    if (ignoreTransform) {
1831        // if ignoreTransform=true was passed to setupDrawModelView, undo currentTransform()
1832        // because it was built into modelView / the geometry, and the description needs to
1833        // compensate.
1834        mat4 modelViewWithoutTransform;
1835        modelViewWithoutTransform.loadInverse(*currentTransform());
1836        modelViewWithoutTransform.multiply(mModelViewMatrix);
1837        mModelViewMatrix.load(modelViewWithoutTransform);
1838    }
1839
1840    SkiaShader::setupProgram(&mCaches, mModelViewMatrix, &mTextureUnit, mExtensions, *shader);
1841}
1842
1843void OpenGLRenderer::setupDrawColorFilterUniforms(const SkColorFilter* filter) {
1844    if (nullptr == filter) {
1845        return;
1846    }
1847
1848    SkColor color;
1849    SkXfermode::Mode mode;
1850    if (filter->asColorMode(&color, &mode)) {
1851        const int alpha = SkColorGetA(color);
1852        const GLfloat a = alpha / 255.0f;
1853        const GLfloat r = a * SkColorGetR(color) / 255.0f;
1854        const GLfloat g = a * SkColorGetG(color) / 255.0f;
1855        const GLfloat b = a * SkColorGetB(color) / 255.0f;
1856        glUniform4f(mCaches.currentProgram->getUniform("colorBlend"), r, g, b, a);
1857        return;
1858    }
1859
1860    SkScalar srcColorMatrix[20];
1861    if (filter->asColorMatrix(srcColorMatrix)) {
1862
1863        float colorMatrix[16];
1864        memcpy(colorMatrix, srcColorMatrix, 4 * sizeof(float));
1865        memcpy(&colorMatrix[4], &srcColorMatrix[5], 4 * sizeof(float));
1866        memcpy(&colorMatrix[8], &srcColorMatrix[10], 4 * sizeof(float));
1867        memcpy(&colorMatrix[12], &srcColorMatrix[15], 4 * sizeof(float));
1868
1869        // Skia uses the range [0..255] for the addition vector, but we need
1870        // the [0..1] range to apply the vector in GLSL
1871        float colorVector[4];
1872        colorVector[0] = srcColorMatrix[4] / 255.0f;
1873        colorVector[1] = srcColorMatrix[9] / 255.0f;
1874        colorVector[2] = srcColorMatrix[14] / 255.0f;
1875        colorVector[3] = srcColorMatrix[19] / 255.0f;
1876
1877        glUniformMatrix4fv(mCaches.currentProgram->getUniform("colorMatrix"), 1,
1878                GL_FALSE, colorMatrix);
1879        glUniform4fv(mCaches.currentProgram->getUniform("colorMatrixVector"), 1, colorVector);
1880        return;
1881    }
1882
1883    // it is an error if we ever get here
1884}
1885
1886void OpenGLRenderer::setupDrawTextGammaUniforms() {
1887    mCaches.fontRenderer->setupProgram(mDescription, mCaches.currentProgram);
1888}
1889
1890void OpenGLRenderer::setupDrawSimpleMesh() {
1891    bool force = mCaches.bindMeshBuffer();
1892    mCaches.bindPositionVertexPointer(force, nullptr);
1893    mCaches.unbindIndicesBuffer();
1894}
1895
1896void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1897    if (texture) bindTexture(texture);
1898    mTextureUnit++;
1899    mCaches.enableTexCoordsVertexArray();
1900}
1901
1902void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) {
1903    bindExternalTexture(texture);
1904    mTextureUnit++;
1905    mCaches.enableTexCoordsVertexArray();
1906}
1907
1908void OpenGLRenderer::setupDrawTextureTransform() {
1909    mDescription.hasTextureTransform = true;
1910}
1911
1912void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) {
1913    glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1,
1914            GL_FALSE, &transform.data[0]);
1915}
1916
1917void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices,
1918        const GLvoid* texCoords, GLuint vbo) {
1919    bool force = false;
1920    if (!vertices || vbo) {
1921        force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1922    } else {
1923        force = mCaches.unbindMeshBuffer();
1924    }
1925
1926    mCaches.bindPositionVertexPointer(force, vertices);
1927    if (mCaches.currentProgram->texCoords >= 0) {
1928        mCaches.bindTexCoordsVertexPointer(force, texCoords);
1929    }
1930
1931    mCaches.unbindIndicesBuffer();
1932}
1933
1934void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices,
1935        const GLvoid* texCoords, const GLvoid* colors) {
1936    bool force = mCaches.unbindMeshBuffer();
1937    GLsizei stride = sizeof(ColorTextureVertex);
1938
1939    mCaches.bindPositionVertexPointer(force, vertices, stride);
1940    if (mCaches.currentProgram->texCoords >= 0) {
1941        mCaches.bindTexCoordsVertexPointer(force, texCoords, stride);
1942    }
1943    int slot = mCaches.currentProgram->getAttrib("colors");
1944    if (slot >= 0) {
1945        glEnableVertexAttribArray(slot);
1946        glVertexAttribPointer(slot, 4, GL_FLOAT, GL_FALSE, stride, colors);
1947    }
1948
1949    mCaches.unbindIndicesBuffer();
1950}
1951
1952void OpenGLRenderer::setupDrawMeshIndices(const GLvoid* vertices,
1953        const GLvoid* texCoords, GLuint vbo) {
1954    bool force = false;
1955    // If vbo is != 0 we want to treat the vertices parameter as an offset inside
1956    // a VBO. However, if vertices is set to NULL and vbo == 0 then we want to
1957    // use the default VBO found in Caches
1958    if (!vertices || vbo) {
1959        force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1960    } else {
1961        force = mCaches.unbindMeshBuffer();
1962    }
1963    mCaches.bindQuadIndicesBuffer();
1964
1965    mCaches.bindPositionVertexPointer(force, vertices);
1966    if (mCaches.currentProgram->texCoords >= 0) {
1967        mCaches.bindTexCoordsVertexPointer(force, texCoords);
1968    }
1969}
1970
1971void OpenGLRenderer::setupDrawIndexedVertices(GLvoid* vertices) {
1972    bool force = mCaches.unbindMeshBuffer();
1973    mCaches.bindQuadIndicesBuffer();
1974    mCaches.bindPositionVertexPointer(force, vertices, gVertexStride);
1975}
1976
1977///////////////////////////////////////////////////////////////////////////////
1978// Drawing
1979///////////////////////////////////////////////////////////////////////////////
1980
1981void OpenGLRenderer::drawRenderNode(RenderNode* renderNode, Rect& dirty, int32_t replayFlags) {
1982    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1983    // will be performed by the display list itself
1984    if (renderNode && renderNode->isRenderable()) {
1985        // compute 3d ordering
1986        renderNode->computeOrdering();
1987        if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
1988            startFrame();
1989            ReplayStateStruct replayStruct(*this, dirty, replayFlags);
1990            renderNode->replay(replayStruct, 0);
1991            return;
1992        }
1993
1994        // Don't avoid overdraw when visualizing, since that makes it harder to
1995        // debug where it's coming from, and when the problem occurs.
1996        bool avoidOverdraw = !mCaches.debugOverdraw;
1997        DeferredDisplayList deferredList(mState.currentClipRect(), avoidOverdraw);
1998        DeferStateStruct deferStruct(deferredList, *this, replayFlags);
1999        renderNode->defer(deferStruct, 0);
2000
2001        flushLayers();
2002        startFrame();
2003
2004        deferredList.flush(*this, dirty);
2005    } else {
2006        // Even if there is no drawing command(Ex: invisible),
2007        // it still needs startFrame to clear buffer and start tiling.
2008        startFrame();
2009    }
2010}
2011
2012void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top,
2013        const SkPaint* paint) {
2014    float x = left;
2015    float y = top;
2016
2017    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2018
2019    bool ignoreTransform = false;
2020    if (currentTransform()->isPureTranslate()) {
2021        x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f);
2022        y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f);
2023        ignoreTransform = true;
2024
2025        texture->setFilter(GL_NEAREST, true);
2026    } else {
2027        texture->setFilter(getFilter(paint), true);
2028    }
2029
2030    // No need to check for a UV mapper on the texture object, only ARGB_8888
2031    // bitmaps get packed in the atlas
2032    drawAlpha8TextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
2033            paint, (GLvoid*) nullptr, (GLvoid*) gMeshTextureOffset,
2034            GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform);
2035}
2036
2037/**
2038 * Important note: this method is intended to draw batches of bitmaps and
2039 * will not set the scissor enable or dirty the current layer, if any.
2040 * The caller is responsible for properly dirtying the current layer.
2041 */
2042void OpenGLRenderer::drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
2043        int bitmapCount, TextureVertex* vertices, bool pureTranslate,
2044        const Rect& bounds, const SkPaint* paint) {
2045    mCaches.activeTexture(0);
2046    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
2047    if (!texture) return;
2048
2049    const AutoTexture autoCleanup(texture);
2050
2051    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2052    texture->setFilter(pureTranslate ? GL_NEAREST : getFilter(paint), true);
2053
2054    const float x = (int) floorf(bounds.left + 0.5f);
2055    const float y = (int) floorf(bounds.top + 0.5f);
2056    if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) {
2057        drawAlpha8TextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
2058                texture->id, paint, &vertices[0].x, &vertices[0].u,
2059                GL_TRIANGLES, bitmapCount * 6, true,
2060                kModelViewMode_Translate, false);
2061    } else {
2062        drawTextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
2063                texture->id, paint, texture->blend, &vertices[0].x, &vertices[0].u,
2064                GL_TRIANGLES, bitmapCount * 6, false, true, 0,
2065                kModelViewMode_Translate, false);
2066    }
2067
2068    mDirty = true;
2069}
2070
2071void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, const SkPaint* paint) {
2072    if (quickRejectSetupScissor(0, 0, bitmap->width(), bitmap->height())) {
2073        return;
2074    }
2075
2076    mCaches.activeTexture(0);
2077    Texture* texture = getTexture(bitmap);
2078    if (!texture) return;
2079    const AutoTexture autoCleanup(texture);
2080
2081    if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) {
2082        drawAlphaBitmap(texture, 0, 0, paint);
2083    } else {
2084        drawTextureRect(0, 0, bitmap->width(), bitmap->height(), texture, paint);
2085    }
2086
2087    mDirty = true;
2088}
2089
2090void OpenGLRenderer::drawBitmapData(const SkBitmap* bitmap, const SkPaint* paint) {
2091    if (quickRejectSetupScissor(0, 0, bitmap->width(), bitmap->height())) {
2092        return;
2093    }
2094
2095    mCaches.activeTexture(0);
2096    Texture* texture = mCaches.textureCache.getTransient(bitmap);
2097    const AutoTexture autoCleanup(texture);
2098
2099    if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) {
2100        drawAlphaBitmap(texture, 0, 0, paint);
2101    } else {
2102        drawTextureRect(0, 0, bitmap->width(), bitmap->height(), texture, paint);
2103    }
2104
2105    mDirty = true;
2106}
2107
2108void OpenGLRenderer::drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight,
2109        const float* vertices, const int* colors, const SkPaint* paint) {
2110    if (!vertices || mState.currentlyIgnored()) {
2111        return;
2112    }
2113
2114    // TODO: use quickReject on bounds from vertices
2115    mCaches.enableScissor();
2116
2117    float left = FLT_MAX;
2118    float top = FLT_MAX;
2119    float right = FLT_MIN;
2120    float bottom = FLT_MIN;
2121
2122    const uint32_t count = meshWidth * meshHeight * 6;
2123
2124    std::unique_ptr<ColorTextureVertex[]> mesh(new ColorTextureVertex[count]);
2125    ColorTextureVertex* vertex = &mesh[0];
2126
2127    std::unique_ptr<int[]> tempColors;
2128    if (!colors) {
2129        uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1);
2130        tempColors.reset(new int[colorsCount]);
2131        memset(tempColors.get(), 0xff, colorsCount * sizeof(int));
2132        colors = tempColors.get();
2133    }
2134
2135    mCaches.activeTexture(0);
2136    Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap);
2137    const UvMapper& mapper(getMapper(texture));
2138
2139    for (int32_t y = 0; y < meshHeight; y++) {
2140        for (int32_t x = 0; x < meshWidth; x++) {
2141            uint32_t i = (y * (meshWidth + 1) + x) * 2;
2142
2143            float u1 = float(x) / meshWidth;
2144            float u2 = float(x + 1) / meshWidth;
2145            float v1 = float(y) / meshHeight;
2146            float v2 = float(y + 1) / meshHeight;
2147
2148            mapper.map(u1, v1, u2, v2);
2149
2150            int ax = i + (meshWidth + 1) * 2;
2151            int ay = ax + 1;
2152            int bx = i;
2153            int by = bx + 1;
2154            int cx = i + 2;
2155            int cy = cx + 1;
2156            int dx = i + (meshWidth + 1) * 2 + 2;
2157            int dy = dx + 1;
2158
2159            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
2160            ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]);
2161            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
2162
2163            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
2164            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
2165            ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]);
2166
2167            left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
2168            top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
2169            right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
2170            bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
2171        }
2172    }
2173
2174    if (quickRejectSetupScissor(left, top, right, bottom)) {
2175        return;
2176    }
2177
2178    if (!texture) {
2179        texture = mCaches.textureCache.get(bitmap);
2180        if (!texture) {
2181            return;
2182        }
2183    }
2184    const AutoTexture autoCleanup(texture);
2185
2186    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2187    texture->setFilter(getFilter(paint), true);
2188
2189    int alpha;
2190    SkXfermode::Mode mode;
2191    getAlphaAndMode(paint, &alpha, &mode);
2192
2193    float a = alpha / 255.0f;
2194
2195    if (hasLayer()) {
2196        dirtyLayer(left, top, right, bottom, *currentTransform());
2197    }
2198
2199    setupDraw();
2200    setupDrawWithTextureAndColor();
2201    setupDrawColor(a, a, a, a);
2202    setupDrawColorFilter(getColorFilter(paint));
2203    setupDrawBlending(paint, true);
2204    setupDrawProgram();
2205    setupDrawDirtyRegionsDisabled();
2206    setupDrawModelView(kModelViewMode_TranslateAndScale, false, 0.0f, 0.0f, 1.0f, 1.0f);
2207    setupDrawTexture(texture->id);
2208    setupDrawPureColorUniforms();
2209    setupDrawColorFilterUniforms(getColorFilter(paint));
2210    setupDrawMesh(&mesh[0].x, &mesh[0].u, &mesh[0].r);
2211
2212    glDrawArrays(GL_TRIANGLES, 0, count);
2213
2214    int slot = mCaches.currentProgram->getAttrib("colors");
2215    if (slot >= 0) {
2216        glDisableVertexAttribArray(slot);
2217    }
2218
2219    mDirty = true;
2220}
2221
2222void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap,
2223         float srcLeft, float srcTop, float srcRight, float srcBottom,
2224         float dstLeft, float dstTop, float dstRight, float dstBottom,
2225         const SkPaint* paint) {
2226    if (quickRejectSetupScissor(dstLeft, dstTop, dstRight, dstBottom)) {
2227        return;
2228    }
2229
2230    mCaches.activeTexture(0);
2231    Texture* texture = getTexture(bitmap);
2232    if (!texture) return;
2233    const AutoTexture autoCleanup(texture);
2234
2235    const float width = texture->width;
2236    const float height = texture->height;
2237
2238    float u1 = fmax(0.0f, srcLeft / width);
2239    float v1 = fmax(0.0f, srcTop / height);
2240    float u2 = fmin(1.0f, srcRight / width);
2241    float v2 = fmin(1.0f, srcBottom / height);
2242
2243    getMapper(texture).map(u1, v1, u2, v2);
2244
2245    mCaches.unbindMeshBuffer();
2246    resetDrawTextureTexCoords(u1, v1, u2, v2);
2247
2248    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2249
2250    float scaleX = (dstRight - dstLeft) / (srcRight - srcLeft);
2251    float scaleY = (dstBottom - dstTop) / (srcBottom - srcTop);
2252
2253    bool scaled = scaleX != 1.0f || scaleY != 1.0f;
2254    // Apply a scale transform on the canvas only when a shader is in use
2255    // Skia handles the ratio between the dst and src rects as a scale factor
2256    // when a shader is set
2257    bool useScaleTransform = getShader(paint) && scaled;
2258    bool ignoreTransform = false;
2259
2260    if (CC_LIKELY(currentTransform()->isPureTranslate() && !useScaleTransform)) {
2261        float x = (int) floorf(dstLeft + currentTransform()->getTranslateX() + 0.5f);
2262        float y = (int) floorf(dstTop + currentTransform()->getTranslateY() + 0.5f);
2263
2264        dstRight = x + (dstRight - dstLeft);
2265        dstBottom = y + (dstBottom - dstTop);
2266
2267        dstLeft = x;
2268        dstTop = y;
2269
2270        texture->setFilter(scaled ? getFilter(paint) : GL_NEAREST, true);
2271        ignoreTransform = true;
2272    } else {
2273        texture->setFilter(getFilter(paint), true);
2274    }
2275
2276    if (CC_UNLIKELY(useScaleTransform)) {
2277        save(SkCanvas::kMatrix_SaveFlag);
2278        translate(dstLeft, dstTop);
2279        scale(scaleX, scaleY);
2280
2281        dstLeft = 0.0f;
2282        dstTop = 0.0f;
2283
2284        dstRight = srcRight - srcLeft;
2285        dstBottom = srcBottom - srcTop;
2286    }
2287
2288    if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) {
2289        drawAlpha8TextureMesh(dstLeft, dstTop, dstRight, dstBottom,
2290                texture->id, paint,
2291                &mMeshVertices[0].x, &mMeshVertices[0].u,
2292                GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform);
2293    } else {
2294        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom,
2295                texture->id, paint, texture->blend,
2296                &mMeshVertices[0].x, &mMeshVertices[0].u,
2297                GL_TRIANGLE_STRIP, gMeshCount, false, ignoreTransform);
2298    }
2299
2300    if (CC_UNLIKELY(useScaleTransform)) {
2301        restore();
2302    }
2303
2304    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
2305
2306    mDirty = true;
2307}
2308
2309void OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Res_png_9patch* patch,
2310        float left, float top, float right, float bottom, const SkPaint* paint) {
2311    if (quickRejectSetupScissor(left, top, right, bottom)) {
2312        return;
2313    }
2314
2315    AssetAtlas::Entry* entry = mRenderState.assetAtlas().getEntry(bitmap);
2316    const Patch* mesh = mCaches.patchCache.get(entry, bitmap->width(), bitmap->height(),
2317            right - left, bottom - top, patch);
2318
2319    drawPatch(bitmap, mesh, entry, left, top, right, bottom, paint);
2320}
2321
2322void OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Patch* mesh,
2323        AssetAtlas::Entry* entry, float left, float top, float right, float bottom,
2324        const SkPaint* paint) {
2325    if (quickRejectSetupScissor(left, top, right, bottom)) {
2326        return;
2327    }
2328
2329    if (CC_LIKELY(mesh && mesh->verticesCount > 0)) {
2330        mCaches.activeTexture(0);
2331        Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
2332        if (!texture) return;
2333        const AutoTexture autoCleanup(texture);
2334
2335        texture->setWrap(GL_CLAMP_TO_EDGE, true);
2336        texture->setFilter(GL_LINEAR, true);
2337
2338        const bool pureTranslate = currentTransform()->isPureTranslate();
2339        // Mark the current layer dirty where we are going to draw the patch
2340        if (hasLayer() && mesh->hasEmptyQuads) {
2341            const float offsetX = left + currentTransform()->getTranslateX();
2342            const float offsetY = top + currentTransform()->getTranslateY();
2343            const size_t count = mesh->quads.size();
2344            for (size_t i = 0; i < count; i++) {
2345                const Rect& bounds = mesh->quads.itemAt(i);
2346                if (CC_LIKELY(pureTranslate)) {
2347                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
2348                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
2349                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
2350                } else {
2351                    dirtyLayer(left + bounds.left, top + bounds.top,
2352                            left + bounds.right, top + bounds.bottom, *currentTransform());
2353                }
2354            }
2355        }
2356
2357        bool ignoreTransform = false;
2358        if (CC_LIKELY(pureTranslate)) {
2359            const float x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f);
2360            const float y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f);
2361
2362            right = x + right - left;
2363            bottom = y + bottom - top;
2364            left = x;
2365            top = y;
2366            ignoreTransform = true;
2367        }
2368        drawIndexedTextureMesh(left, top, right, bottom, texture->id, paint,
2369                texture->blend, (GLvoid*) mesh->offset, (GLvoid*) mesh->textureOffset,
2370                GL_TRIANGLES, mesh->indexCount, false, ignoreTransform,
2371                mCaches.patchCache.getMeshBuffer(), kModelViewMode_Translate, !mesh->hasEmptyQuads);
2372    }
2373
2374    mDirty = true;
2375}
2376
2377/**
2378 * Important note: this method is intended to draw batches of 9-patch objects and
2379 * will not set the scissor enable or dirty the current layer, if any.
2380 * The caller is responsible for properly dirtying the current layer.
2381 */
2382void OpenGLRenderer::drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
2383        TextureVertex* vertices, uint32_t indexCount, const SkPaint* paint) {
2384    mCaches.activeTexture(0);
2385    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
2386    if (!texture) return;
2387    const AutoTexture autoCleanup(texture);
2388
2389    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2390    texture->setFilter(GL_LINEAR, true);
2391
2392    drawIndexedTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, paint,
2393            texture->blend, &vertices[0].x, &vertices[0].u,
2394            GL_TRIANGLES, indexCount, false, true, 0, kModelViewMode_Translate, false);
2395
2396    mDirty = true;
2397}
2398
2399void OpenGLRenderer::drawVertexBuffer(float translateX, float translateY,
2400        const VertexBuffer& vertexBuffer, const SkPaint* paint, int displayFlags) {
2401    // not missing call to quickReject/dirtyLayer, always done at a higher level
2402    if (!vertexBuffer.getVertexCount()) {
2403        // no vertices to draw
2404        return;
2405    }
2406
2407    Rect bounds(vertexBuffer.getBounds());
2408    bounds.translate(translateX, translateY);
2409    dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, *currentTransform());
2410
2411    int color = paint->getColor();
2412    bool isAA = paint->isAntiAlias();
2413
2414    setupDraw();
2415    setupDrawNoTexture();
2416    if (isAA) setupDrawVertexAlpha((displayFlags & kVertexBuffer_ShadowInterp));
2417    setupDrawColor(color, ((color >> 24) & 0xFF) * writableSnapshot()->alpha);
2418    setupDrawColorFilter(getColorFilter(paint));
2419    setupDrawShader(getShader(paint));
2420    setupDrawBlending(paint, isAA);
2421    setupDrawProgram();
2422    setupDrawModelView(kModelViewMode_Translate, (displayFlags & kVertexBuffer_Offset),
2423            translateX, translateY, 0, 0);
2424    setupDrawColorUniforms(getShader(paint));
2425    setupDrawColorFilterUniforms(getColorFilter(paint));
2426    setupDrawShaderUniforms(getShader(paint));
2427
2428    const void* vertices = vertexBuffer.getBuffer();
2429    mCaches.unbindMeshBuffer();
2430    mCaches.bindPositionVertexPointer(true, vertices, isAA ? gAlphaVertexStride : gVertexStride);
2431    mCaches.resetTexCoordsVertexPointer();
2432
2433    int alphaSlot = -1;
2434    if (isAA) {
2435        void* alphaCoords = ((GLbyte*) vertices) + gVertexAlphaOffset;
2436        alphaSlot = mCaches.currentProgram->getAttrib("vtxAlpha");
2437        // TODO: avoid enable/disable in back to back uses of the alpha attribute
2438        glEnableVertexAttribArray(alphaSlot);
2439        glVertexAttribPointer(alphaSlot, 1, GL_FLOAT, GL_FALSE, gAlphaVertexStride, alphaCoords);
2440    }
2441
2442    const VertexBuffer::Mode mode = vertexBuffer.getMode();
2443    if (mode == VertexBuffer::kStandard) {
2444        mCaches.unbindIndicesBuffer();
2445        glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexBuffer.getVertexCount());
2446    } else if (mode == VertexBuffer::kOnePolyRingShadow) {
2447        mCaches.bindShadowIndicesBuffer();
2448        glDrawElements(GL_TRIANGLE_STRIP, ONE_POLY_RING_SHADOW_INDEX_COUNT,
2449                GL_UNSIGNED_SHORT, nullptr);
2450    } else if (mode == VertexBuffer::kTwoPolyRingShadow) {
2451        mCaches.bindShadowIndicesBuffer();
2452        glDrawElements(GL_TRIANGLE_STRIP, TWO_POLY_RING_SHADOW_INDEX_COUNT,
2453                GL_UNSIGNED_SHORT, nullptr);
2454    } else if (mode == VertexBuffer::kIndices) {
2455        mCaches.unbindIndicesBuffer();
2456        glDrawElements(GL_TRIANGLE_STRIP, vertexBuffer.getIndexCount(),
2457                GL_UNSIGNED_SHORT, vertexBuffer.getIndices());
2458    }
2459
2460    if (isAA) {
2461        glDisableVertexAttribArray(alphaSlot);
2462    }
2463
2464    mDirty = true;
2465}
2466
2467/**
2468 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to
2469 * that of AA lines in the drawLines() function.  We expand the convex path by a half pixel in
2470 * screen space in all directions. However, instead of using a fragment shader to compute the
2471 * translucency of the color from its position, we simply use a varying parameter to define how far
2472 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used.
2473 *
2474 * Doesn't yet support joins, caps, or path effects.
2475 */
2476void OpenGLRenderer::drawConvexPath(const SkPath& path, const SkPaint* paint) {
2477    VertexBuffer vertexBuffer;
2478    // TODO: try clipping large paths to viewport
2479    PathTessellator::tessellatePath(path, paint, *currentTransform(), vertexBuffer);
2480    drawVertexBuffer(vertexBuffer, paint);
2481}
2482
2483/**
2484 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha
2485 * and additional geometry for defining an alpha slope perimeter.
2486 *
2487 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some
2488 * unexpected results, and may vary between hardware devices. Previously we used a varying-base
2489 * in-shader alpha region, but found it to be taxing on some GPUs.
2490 *
2491 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce
2492 * memory transfer by removing need for degenerate vertices.
2493 */
2494void OpenGLRenderer::drawLines(const float* points, int count, const SkPaint* paint) {
2495    if (mState.currentlyIgnored() || count < 4) return;
2496
2497    count &= ~0x3; // round down to nearest four
2498
2499    VertexBuffer buffer;
2500    PathTessellator::tessellateLines(points, count, paint, *currentTransform(), buffer);
2501    const Rect& bounds = buffer.getBounds();
2502
2503    if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) {
2504        return;
2505    }
2506
2507    int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset;
2508    drawVertexBuffer(buffer, paint, displayFlags);
2509}
2510
2511void OpenGLRenderer::drawPoints(const float* points, int count, const SkPaint* paint) {
2512    if (mState.currentlyIgnored() || count < 2) return;
2513
2514    count &= ~0x1; // round down to nearest two
2515
2516    VertexBuffer buffer;
2517    PathTessellator::tessellatePoints(points, count, paint, *currentTransform(), buffer);
2518
2519    const Rect& bounds = buffer.getBounds();
2520    if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) {
2521        return;
2522    }
2523
2524    int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset;
2525    drawVertexBuffer(buffer, paint, displayFlags);
2526
2527    mDirty = true;
2528}
2529
2530void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
2531    // No need to check against the clip, we fill the clip region
2532    if (mState.currentlyIgnored()) return;
2533
2534    Rect clip(mState.currentClipRect());
2535    clip.snapToPixelBoundaries();
2536
2537    SkPaint paint;
2538    paint.setColor(color);
2539    paint.setXfermodeMode(mode);
2540
2541    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, &paint, true);
2542
2543    mDirty = true;
2544}
2545
2546void OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture,
2547        const SkPaint* paint) {
2548    if (!texture) return;
2549    const AutoTexture autoCleanup(texture);
2550
2551    const float x = left + texture->left - texture->offset;
2552    const float y = top + texture->top - texture->offset;
2553
2554    drawPathTexture(texture, x, y, paint);
2555
2556    mDirty = true;
2557}
2558
2559void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
2560        float rx, float ry, 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->getPathEffect() != nullptr) {
2568        mCaches.activeTexture(0);
2569        const PathTexture* texture = mCaches.pathCache.getRoundRect(
2570                right - left, bottom - top, rx, ry, p);
2571        drawShape(left, top, texture, p);
2572    } else {
2573        const VertexBuffer* vertexBuffer = mCaches.tessellationCache.getRoundRect(
2574                *currentTransform(), *p, right - left, bottom - top, rx, ry);
2575        drawVertexBuffer(left, top, *vertexBuffer, p);
2576    }
2577}
2578
2579void OpenGLRenderer::drawCircle(float x, float y, float radius, const SkPaint* p) {
2580    if (mState.currentlyIgnored()
2581            || quickRejectSetupScissor(x - radius, y - radius, x + radius, y + radius, p)
2582            || PaintUtils::paintWillNotDraw(*p)) {
2583        return;
2584    }
2585    if (p->getPathEffect() != nullptr) {
2586        mCaches.activeTexture(0);
2587        const PathTexture* texture = mCaches.pathCache.getCircle(radius, p);
2588        drawShape(x - radius, y - radius, texture, p);
2589    } else {
2590        SkPath path;
2591        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2592            path.addCircle(x, y, radius + p->getStrokeWidth() / 2);
2593        } else {
2594            path.addCircle(x, y, radius);
2595        }
2596        drawConvexPath(path, p);
2597    }
2598}
2599
2600void OpenGLRenderer::drawOval(float left, float top, float right, float bottom,
2601        const SkPaint* p) {
2602    if (mState.currentlyIgnored()
2603            || quickRejectSetupScissor(left, top, right, bottom, p)
2604            || PaintUtils::paintWillNotDraw(*p)) {
2605        return;
2606    }
2607
2608    if (p->getPathEffect() != nullptr) {
2609        mCaches.activeTexture(0);
2610        const PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p);
2611        drawShape(left, top, texture, p);
2612    } else {
2613        SkPath path;
2614        SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2615        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2616            rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2617        }
2618        path.addOval(rect);
2619        drawConvexPath(path, p);
2620    }
2621}
2622
2623void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
2624        float startAngle, float sweepAngle, bool useCenter, const SkPaint* p) {
2625    if (mState.currentlyIgnored()
2626            || quickRejectSetupScissor(left, top, right, bottom, p)
2627            || PaintUtils::paintWillNotDraw(*p)) {
2628        return;
2629    }
2630
2631    // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180)
2632    if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != nullptr || useCenter) {
2633        mCaches.activeTexture(0);
2634        const PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top,
2635                startAngle, sweepAngle, useCenter, p);
2636        drawShape(left, top, texture, p);
2637        return;
2638    }
2639    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2640    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2641        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2642    }
2643
2644    SkPath path;
2645    if (useCenter) {
2646        path.moveTo(rect.centerX(), rect.centerY());
2647    }
2648    path.arcTo(rect, startAngle, sweepAngle, !useCenter);
2649    if (useCenter) {
2650        path.close();
2651    }
2652    drawConvexPath(path, p);
2653}
2654
2655// See SkPaintDefaults.h
2656#define SkPaintDefaults_MiterLimit SkIntToScalar(4)
2657
2658void OpenGLRenderer::drawRect(float left, float top, float right, float bottom,
2659        const SkPaint* p) {
2660    if (mState.currentlyIgnored()
2661            || quickRejectSetupScissor(left, top, right, bottom, p)
2662            || PaintUtils::paintWillNotDraw(*p)) {
2663        return;
2664    }
2665
2666    if (p->getStyle() != SkPaint::kFill_Style) {
2667        // only fill style is supported by drawConvexPath, since others have to handle joins
2668        if (p->getPathEffect() != nullptr || p->getStrokeJoin() != SkPaint::kMiter_Join ||
2669                p->getStrokeMiter() != SkPaintDefaults_MiterLimit) {
2670            mCaches.activeTexture(0);
2671            const PathTexture* texture =
2672                    mCaches.pathCache.getRect(right - left, bottom - top, p);
2673            drawShape(left, top, texture, p);
2674        } else {
2675            SkPath path;
2676            SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2677            if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2678                rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2679            }
2680            path.addRect(rect);
2681            drawConvexPath(path, p);
2682        }
2683    } else {
2684        if (p->isAntiAlias() && !currentTransform()->isSimple()) {
2685            SkPath path;
2686            path.addRect(left, top, right, bottom);
2687            drawConvexPath(path, p);
2688        } else {
2689            drawColorRect(left, top, right, bottom, p);
2690
2691            mDirty = true;
2692        }
2693    }
2694}
2695
2696void OpenGLRenderer::drawTextShadow(const SkPaint* paint, const char* text,
2697        int bytesCount, int count, const float* positions,
2698        FontRenderer& fontRenderer, int alpha, float x, float y) {
2699    mCaches.activeTexture(0);
2700
2701    TextShadow textShadow;
2702    if (!getTextShadow(paint, &textShadow)) {
2703        LOG_ALWAYS_FATAL("failed to query shadow attributes");
2704    }
2705
2706    // NOTE: The drop shadow will not perform gamma correction
2707    //       if shader-based correction is enabled
2708    mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2709    const ShadowTexture* shadow = mCaches.dropShadowCache.get(
2710            paint, text, bytesCount, count, textShadow.radius, positions);
2711    // If the drop shadow exceeds the max texture size or couldn't be
2712    // allocated, skip drawing
2713    if (!shadow) return;
2714    const AutoTexture autoCleanup(shadow);
2715
2716    const float sx = x - shadow->left + textShadow.dx;
2717    const float sy = y - shadow->top + textShadow.dy;
2718
2719    const int shadowAlpha = ((textShadow.color >> 24) & 0xFF) * writableSnapshot()->alpha;
2720    if (getShader(paint)) {
2721        textShadow.color = SK_ColorWHITE;
2722    }
2723
2724    setupDraw();
2725    setupDrawWithTexture(true);
2726    setupDrawAlpha8Color(textShadow.color, shadowAlpha < 255 ? shadowAlpha : alpha);
2727    setupDrawColorFilter(getColorFilter(paint));
2728    setupDrawShader(getShader(paint));
2729    setupDrawBlending(paint, true);
2730    setupDrawProgram();
2731    setupDrawModelView(kModelViewMode_TranslateAndScale, false,
2732            sx, sy, sx + shadow->width, sy + shadow->height);
2733    setupDrawTexture(shadow->id);
2734    setupDrawPureColorUniforms();
2735    setupDrawColorFilterUniforms(getColorFilter(paint));
2736    setupDrawShaderUniforms(getShader(paint));
2737    setupDrawMesh(nullptr, (GLvoid*) gMeshTextureOffset);
2738
2739    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2740}
2741
2742bool OpenGLRenderer::canSkipText(const SkPaint* paint) const {
2743    float alpha = (hasTextShadow(paint) ? 1.0f : paint->getAlpha()) * currentSnapshot()->alpha;
2744    return MathUtils::isZero(alpha)
2745            && PaintUtils::getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode;
2746}
2747
2748void OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count,
2749        const float* positions, const SkPaint* paint) {
2750    if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) {
2751        return;
2752    }
2753
2754    // NOTE: Skia does not support perspective transform on drawPosText yet
2755    if (!currentTransform()->isSimple()) {
2756        return;
2757    }
2758
2759    mCaches.enableScissor();
2760
2761    float x = 0.0f;
2762    float y = 0.0f;
2763    const bool pureTranslate = currentTransform()->isPureTranslate();
2764    if (pureTranslate) {
2765        x = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f);
2766        y = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f);
2767    }
2768
2769    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2770    fontRenderer.setFont(paint, SkMatrix::I());
2771
2772    int alpha;
2773    SkXfermode::Mode mode;
2774    getAlphaAndMode(paint, &alpha, &mode);
2775
2776    if (CC_UNLIKELY(hasTextShadow(paint))) {
2777        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2778                alpha, 0.0f, 0.0f);
2779    }
2780
2781    // Pick the appropriate texture filtering
2782    bool linearFilter = currentTransform()->changesBounds();
2783    if (pureTranslate && !linearFilter) {
2784        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2785    }
2786    fontRenderer.setTextureFiltering(linearFilter);
2787
2788    const Rect& clip(pureTranslate ? writableSnapshot()->getClipRect() : writableSnapshot()->getLocalClip());
2789    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2790
2791    const bool hasActiveLayer = hasLayer();
2792
2793    TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2794    if (fontRenderer.renderPosText(paint, &clip, text, 0, bytesCount, count, x, y,
2795            positions, hasActiveLayer ? &bounds : nullptr, &functor)) {
2796        if (hasActiveLayer) {
2797            if (!pureTranslate) {
2798                currentTransform()->mapRect(bounds);
2799            }
2800            dirtyLayerUnchecked(bounds, getRegion());
2801        }
2802    }
2803
2804    mDirty = true;
2805}
2806
2807bool OpenGLRenderer::findBestFontTransform(const mat4& transform, SkMatrix* outMatrix) const {
2808    if (CC_LIKELY(transform.isPureTranslate())) {
2809        outMatrix->setIdentity();
2810        return false;
2811    } else if (CC_UNLIKELY(transform.isPerspective())) {
2812        outMatrix->setIdentity();
2813        return true;
2814    }
2815
2816    /**
2817     * Input is a non-perspective, scaling transform. Generate a scale-only transform,
2818     * with values rounded to the nearest int.
2819     */
2820    float sx, sy;
2821    transform.decomposeScale(sx, sy);
2822    outMatrix->setScale(
2823            roundf(fmaxf(1.0f, sx)),
2824            roundf(fmaxf(1.0f, sy)));
2825    return true;
2826}
2827
2828int OpenGLRenderer::getSaveCount() const {
2829    return mState.getSaveCount();
2830}
2831
2832int OpenGLRenderer::save(int flags) {
2833    return mState.save(flags);
2834}
2835
2836void OpenGLRenderer::restore() {
2837    return mState.restore();
2838}
2839
2840void OpenGLRenderer::restoreToCount(int saveCount) {
2841    return mState.restoreToCount(saveCount);
2842}
2843
2844void OpenGLRenderer::translate(float dx, float dy, float dz) {
2845    return mState.translate(dx, dy, dz);
2846}
2847
2848void OpenGLRenderer::rotate(float degrees) {
2849    return mState.rotate(degrees);
2850}
2851
2852void OpenGLRenderer::scale(float sx, float sy) {
2853    return mState.scale(sx, sy);
2854}
2855
2856void OpenGLRenderer::skew(float sx, float sy) {
2857    return mState.skew(sx, sy);
2858}
2859
2860void OpenGLRenderer::setMatrix(const Matrix4& matrix) {
2861    mState.setMatrix(matrix);
2862}
2863
2864void OpenGLRenderer::concatMatrix(const Matrix4& matrix) {
2865    mState.concatMatrix(matrix);
2866}
2867
2868bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
2869    return mState.clipRect(left, top, right, bottom, op);
2870}
2871
2872bool OpenGLRenderer::clipPath(const SkPath* path, SkRegion::Op op) {
2873    return mState.clipPath(path, op);
2874}
2875
2876bool OpenGLRenderer::clipRegion(const SkRegion* region, SkRegion::Op op) {
2877    return mState.clipRegion(region, op);
2878}
2879
2880void OpenGLRenderer::setClippingOutline(LinearAllocator& allocator, const Outline* outline) {
2881    mState.setClippingOutline(allocator, outline);
2882}
2883
2884void OpenGLRenderer::setClippingRoundRect(LinearAllocator& allocator,
2885        const Rect& rect, float radius, bool highPriority) {
2886    mState.setClippingRoundRect(allocator, rect, radius, highPriority);
2887}
2888
2889
2890
2891void OpenGLRenderer::drawText(const char* text, int bytesCount, int count, float x, float y,
2892        const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds,
2893        DrawOpMode drawOpMode) {
2894
2895    if (drawOpMode == kDrawOpMode_Immediate) {
2896        // The checks for corner-case ignorable text and quick rejection is only done for immediate
2897        // drawing as ops from DeferredDisplayList are already filtered for these
2898        if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint) ||
2899                quickRejectSetupScissor(bounds)) {
2900            return;
2901        }
2902    }
2903
2904    const float oldX = x;
2905    const float oldY = y;
2906
2907    const mat4& transform = *currentTransform();
2908    const bool pureTranslate = transform.isPureTranslate();
2909
2910    if (CC_LIKELY(pureTranslate)) {
2911        x = (int) floorf(x + transform.getTranslateX() + 0.5f);
2912        y = (int) floorf(y + transform.getTranslateY() + 0.5f);
2913    }
2914
2915    int alpha;
2916    SkXfermode::Mode mode;
2917    getAlphaAndMode(paint, &alpha, &mode);
2918
2919    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2920
2921    if (CC_UNLIKELY(hasTextShadow(paint))) {
2922        fontRenderer.setFont(paint, SkMatrix::I());
2923        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2924                alpha, oldX, oldY);
2925    }
2926
2927    const bool hasActiveLayer = hasLayer();
2928
2929    // We only pass a partial transform to the font renderer. That partial
2930    // matrix defines how glyphs are rasterized. Typically we want glyphs
2931    // to be rasterized at their final size on screen, which means the partial
2932    // matrix needs to take the scale factor into account.
2933    // When a partial matrix is used to transform glyphs during rasterization,
2934    // the mesh is generated with the inverse transform (in the case of scale,
2935    // the mesh is generated at 1.0 / scale for instance.) This allows us to
2936    // apply the full transform matrix at draw time in the vertex shader.
2937    // Applying the full matrix in the shader is the easiest way to handle
2938    // rotation and perspective and allows us to always generated quads in the
2939    // font renderer which greatly simplifies the code, clipping in particular.
2940    SkMatrix fontTransform;
2941    bool linearFilter = findBestFontTransform(transform, &fontTransform)
2942            || fabs(y - (int) y) > 0.0f
2943            || fabs(x - (int) x) > 0.0f;
2944    fontRenderer.setFont(paint, fontTransform);
2945    fontRenderer.setTextureFiltering(linearFilter);
2946
2947    // TODO: Implement better clipping for scaled/rotated text
2948    const Rect* clip = !pureTranslate ? nullptr : &mState.currentClipRect();
2949    Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2950
2951    bool status;
2952    TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2953
2954    // don't call issuedrawcommand, do it at end of batch
2955    bool forceFinish = (drawOpMode != kDrawOpMode_Defer);
2956    if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) {
2957        SkPaint paintCopy(*paint);
2958        paintCopy.setTextAlign(SkPaint::kLeft_Align);
2959        status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y,
2960                positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish);
2961    } else {
2962        status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2963                positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish);
2964    }
2965
2966    if ((status || drawOpMode != kDrawOpMode_Immediate) && hasActiveLayer) {
2967        if (!pureTranslate) {
2968            transform.mapRect(layerBounds);
2969        }
2970        dirtyLayerUnchecked(layerBounds, getRegion());
2971    }
2972
2973    drawTextDecorations(totalAdvance, oldX, oldY, paint);
2974
2975    mDirty = true;
2976}
2977
2978void OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count,
2979        const SkPath* path, float hOffset, float vOffset, const SkPaint* paint) {
2980    if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) {
2981        return;
2982    }
2983
2984    // TODO: avoid scissor by calculating maximum bounds using path bounds + font metrics
2985    mCaches.enableScissor();
2986
2987    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2988    fontRenderer.setFont(paint, SkMatrix::I());
2989    fontRenderer.setTextureFiltering(true);
2990
2991    int alpha;
2992    SkXfermode::Mode mode;
2993    getAlphaAndMode(paint, &alpha, &mode);
2994    TextSetupFunctor functor(this, 0.0f, 0.0f, false, alpha, mode, paint);
2995
2996    const Rect* clip = &writableSnapshot()->getLocalClip();
2997    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2998
2999    const bool hasActiveLayer = hasLayer();
3000
3001    if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path,
3002            hOffset, vOffset, hasActiveLayer ? &bounds : nullptr, &functor)) {
3003        if (hasActiveLayer) {
3004            currentTransform()->mapRect(bounds);
3005            dirtyLayerUnchecked(bounds, getRegion());
3006        }
3007    }
3008
3009    mDirty = true;
3010}
3011
3012void OpenGLRenderer::drawPath(const SkPath* path, const SkPaint* paint) {
3013    if (mState.currentlyIgnored()) return;
3014
3015    mCaches.activeTexture(0);
3016
3017    const PathTexture* texture = mCaches.pathCache.get(path, paint);
3018    if (!texture) return;
3019    const AutoTexture autoCleanup(texture);
3020
3021    const float x = texture->left - texture->offset;
3022    const float y = texture->top - texture->offset;
3023
3024    drawPathTexture(texture, x, y, paint);
3025    mDirty = true;
3026}
3027
3028void OpenGLRenderer::drawLayer(Layer* layer, float x, float y) {
3029    if (!layer) {
3030        return;
3031    }
3032
3033    mat4* transform = nullptr;
3034    if (layer->isTextureLayer()) {
3035        transform = &layer->getTransform();
3036        if (!transform->isIdentity()) {
3037            save(SkCanvas::kMatrix_SaveFlag);
3038            concatMatrix(*transform);
3039        }
3040    }
3041
3042    bool clipRequired = false;
3043    const bool rejected = mState.calculateQuickRejectForScissor(
3044            x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(),
3045            &clipRequired, nullptr, false);
3046
3047    if (rejected) {
3048        if (transform && !transform->isIdentity()) {
3049            restore();
3050        }
3051        return;
3052    }
3053
3054    EVENT_LOGD("drawLayer," RECT_STRING ", clipRequired %d", x, y,
3055            x + layer->layer.getWidth(), y + layer->layer.getHeight(), clipRequired);
3056
3057    updateLayer(layer, true);
3058
3059    mCaches.setScissorEnabled(mScissorOptimizationDisabled || clipRequired);
3060    mCaches.activeTexture(0);
3061
3062    if (CC_LIKELY(!layer->region.isEmpty())) {
3063        if (layer->region.isRect()) {
3064            DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
3065                    composeLayerRect(layer, layer->regionRect));
3066        } else if (layer->mesh) {
3067
3068            const float a = getLayerAlpha(layer);
3069            setupDraw();
3070            setupDrawWithTexture();
3071            setupDrawColor(a, a, a, a);
3072            setupDrawColorFilter(layer->getColorFilter());
3073            setupDrawBlending(layer);
3074            setupDrawProgram();
3075            setupDrawPureColorUniforms();
3076            setupDrawColorFilterUniforms(layer->getColorFilter());
3077            setupDrawTexture(layer->getTexture());
3078            if (CC_LIKELY(currentTransform()->isPureTranslate())) {
3079                int tx = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f);
3080                int ty = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f);
3081
3082                layer->setFilter(GL_NEAREST);
3083                setupDrawModelView(kModelViewMode_Translate, false, tx, ty,
3084                        tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true);
3085            } else {
3086                layer->setFilter(GL_LINEAR);
3087                setupDrawModelView(kModelViewMode_Translate, false, x, y,
3088                        x + layer->layer.getWidth(), y + layer->layer.getHeight());
3089            }
3090
3091            TextureVertex* mesh = &layer->mesh[0];
3092            GLsizei elementsCount = layer->meshElementCount;
3093
3094            while (elementsCount > 0) {
3095                GLsizei drawCount = min(elementsCount, (GLsizei) gMaxNumberOfQuads * 6);
3096
3097                setupDrawMeshIndices(&mesh[0].x, &mesh[0].u);
3098                DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
3099                        glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, nullptr));
3100
3101                elementsCount -= drawCount;
3102                // Though there are 4 vertices in a quad, we use 6 indices per
3103                // quad to draw with GL_TRIANGLES
3104                mesh += (drawCount / 6) * 4;
3105            }
3106
3107#if DEBUG_LAYERS_AS_REGIONS
3108            drawRegionRectsDebug(layer->region);
3109#endif
3110        }
3111
3112        if (layer->debugDrawUpdate) {
3113            layer->debugDrawUpdate = false;
3114
3115            SkPaint paint;
3116            paint.setColor(0x7f00ff00);
3117            drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(), &paint);
3118        }
3119    }
3120    layer->hasDrawnSinceUpdate = true;
3121
3122    if (transform && !transform->isIdentity()) {
3123        restore();
3124    }
3125
3126    mDirty = true;
3127}
3128
3129///////////////////////////////////////////////////////////////////////////////
3130// Draw filters
3131///////////////////////////////////////////////////////////////////////////////
3132void OpenGLRenderer::setDrawFilter(SkDrawFilter* filter) {
3133    // We should never get here since we apply the draw filter when stashing
3134    // the paints in the DisplayList.
3135    LOG_ALWAYS_FATAL("OpenGLRenderer does not directly support DrawFilters");
3136}
3137
3138///////////////////////////////////////////////////////////////////////////////
3139// Drawing implementation
3140///////////////////////////////////////////////////////////////////////////////
3141
3142Texture* OpenGLRenderer::getTexture(const SkBitmap* bitmap) {
3143    Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap);
3144    if (!texture) {
3145        return mCaches.textureCache.get(bitmap);
3146    }
3147    return texture;
3148}
3149
3150void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
3151        float x, float y, const SkPaint* paint) {
3152    if (quickRejectSetupScissor(x, y, x + texture->width, y + texture->height)) {
3153        return;
3154    }
3155
3156    int alpha;
3157    SkXfermode::Mode mode;
3158    getAlphaAndMode(paint, &alpha, &mode);
3159
3160    setupDraw();
3161    setupDrawWithTexture(true);
3162    setupDrawAlpha8Color(paint->getColor(), alpha);
3163    setupDrawColorFilter(getColorFilter(paint));
3164    setupDrawShader(getShader(paint));
3165    setupDrawBlending(paint, true);
3166    setupDrawProgram();
3167    setupDrawModelView(kModelViewMode_TranslateAndScale, false,
3168            x, y, x + texture->width, y + texture->height);
3169    setupDrawTexture(texture->id);
3170    setupDrawPureColorUniforms();
3171    setupDrawColorFilterUniforms(getColorFilter(paint));
3172    setupDrawShaderUniforms(getShader(paint));
3173    setupDrawMesh(nullptr, (GLvoid*) gMeshTextureOffset);
3174
3175    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
3176}
3177
3178// Same values used by Skia
3179#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
3180#define kStdUnderline_Offset    (1.0f / 9.0f)
3181#define kStdUnderline_Thickness (1.0f / 18.0f)
3182
3183void OpenGLRenderer::drawTextDecorations(float underlineWidth, float x, float y,
3184        const SkPaint* paint) {
3185    // Handle underline and strike-through
3186    uint32_t flags = paint->getFlags();
3187    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
3188        SkPaint paintCopy(*paint);
3189
3190        if (CC_LIKELY(underlineWidth > 0.0f)) {
3191            const float textSize = paintCopy.getTextSize();
3192            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
3193
3194            const float left = x;
3195            float top = 0.0f;
3196
3197            int linesCount = 0;
3198            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
3199            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
3200
3201            const int pointsCount = 4 * linesCount;
3202            float points[pointsCount];
3203            int currentPoint = 0;
3204
3205            if (flags & SkPaint::kUnderlineText_Flag) {
3206                top = y + textSize * kStdUnderline_Offset;
3207                points[currentPoint++] = left;
3208                points[currentPoint++] = top;
3209                points[currentPoint++] = left + underlineWidth;
3210                points[currentPoint++] = top;
3211            }
3212
3213            if (flags & SkPaint::kStrikeThruText_Flag) {
3214                top = y + textSize * kStdStrikeThru_Offset;
3215                points[currentPoint++] = left;
3216                points[currentPoint++] = top;
3217                points[currentPoint++] = left + underlineWidth;
3218                points[currentPoint++] = top;
3219            }
3220
3221            paintCopy.setStrokeWidth(strokeWidth);
3222
3223            drawLines(&points[0], pointsCount, &paintCopy);
3224        }
3225    }
3226}
3227
3228void OpenGLRenderer::drawRects(const float* rects, int count, const SkPaint* paint) {
3229    if (mState.currentlyIgnored()) {
3230        return;
3231    }
3232
3233    drawColorRects(rects, count, paint, false, true, true);
3234}
3235
3236void OpenGLRenderer::drawShadow(float casterAlpha,
3237        const VertexBuffer* ambientShadowVertexBuffer, const VertexBuffer* spotShadowVertexBuffer) {
3238    if (mState.currentlyIgnored()) return;
3239
3240    // TODO: use quickRejectWithScissor. For now, always force enable scissor.
3241    mCaches.enableScissor();
3242
3243    SkPaint paint;
3244    paint.setAntiAlias(true); // want to use AlphaVertex
3245
3246    // The caller has made sure casterAlpha > 0.
3247    float ambientShadowAlpha = mAmbientShadowAlpha;
3248    if (CC_UNLIKELY(mCaches.propertyAmbientShadowStrength >= 0)) {
3249        ambientShadowAlpha = mCaches.propertyAmbientShadowStrength;
3250    }
3251    if (ambientShadowVertexBuffer && ambientShadowAlpha > 0) {
3252        paint.setARGB(casterAlpha * ambientShadowAlpha, 0, 0, 0);
3253        drawVertexBuffer(*ambientShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp);
3254    }
3255
3256    float spotShadowAlpha = mSpotShadowAlpha;
3257    if (CC_UNLIKELY(mCaches.propertySpotShadowStrength >= 0)) {
3258        spotShadowAlpha = mCaches.propertySpotShadowStrength;
3259    }
3260    if (spotShadowVertexBuffer && spotShadowAlpha > 0) {
3261        paint.setARGB(casterAlpha * spotShadowAlpha, 0, 0, 0);
3262        drawVertexBuffer(*spotShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp);
3263    }
3264
3265    mDirty=true;
3266}
3267
3268void OpenGLRenderer::drawColorRects(const float* rects, int count, const SkPaint* paint,
3269        bool ignoreTransform, bool dirty, bool clip) {
3270    if (count == 0) {
3271        return;
3272    }
3273
3274    int color = paint->getColor();
3275    // If a shader is set, preserve only the alpha
3276    if (getShader(paint)) {
3277        color |= 0x00ffffff;
3278    }
3279
3280    float left = FLT_MAX;
3281    float top = FLT_MAX;
3282    float right = FLT_MIN;
3283    float bottom = FLT_MIN;
3284
3285    Vertex mesh[count];
3286    Vertex* vertex = mesh;
3287
3288    for (int index = 0; index < count; index += 4) {
3289        float l = rects[index + 0];
3290        float t = rects[index + 1];
3291        float r = rects[index + 2];
3292        float b = rects[index + 3];
3293
3294        Vertex::set(vertex++, l, t);
3295        Vertex::set(vertex++, r, t);
3296        Vertex::set(vertex++, l, b);
3297        Vertex::set(vertex++, r, b);
3298
3299        left = fminf(left, l);
3300        top = fminf(top, t);
3301        right = fmaxf(right, r);
3302        bottom = fmaxf(bottom, b);
3303    }
3304
3305    if (clip && quickRejectSetupScissor(left, top, right, bottom)) {
3306        return;
3307    }
3308
3309    setupDraw();
3310    setupDrawNoTexture();
3311    setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha);
3312    setupDrawShader(getShader(paint));
3313    setupDrawColorFilter(getColorFilter(paint));
3314    setupDrawBlending(paint);
3315    setupDrawProgram();
3316    setupDrawDirtyRegionsDisabled();
3317    setupDrawModelView(kModelViewMode_Translate, false,
3318            0.0f, 0.0f, 0.0f, 0.0f, ignoreTransform);
3319    setupDrawColorUniforms(getShader(paint));
3320    setupDrawShaderUniforms(getShader(paint));
3321    setupDrawColorFilterUniforms(getColorFilter(paint));
3322
3323    if (dirty && hasLayer()) {
3324        dirtyLayer(left, top, right, bottom, *currentTransform());
3325    }
3326
3327    issueIndexedQuadDraw(&mesh[0], count / 4);
3328
3329    mDirty = true;
3330}
3331
3332void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
3333        const SkPaint* paint, bool ignoreTransform) {
3334    int color = paint->getColor();
3335    // If a shader is set, preserve only the alpha
3336    if (getShader(paint)) {
3337        color |= 0x00ffffff;
3338    }
3339
3340    setupDraw();
3341    setupDrawNoTexture();
3342    setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha);
3343    setupDrawShader(getShader(paint));
3344    setupDrawColorFilter(getColorFilter(paint));
3345    setupDrawBlending(paint);
3346    setupDrawProgram();
3347    setupDrawModelView(kModelViewMode_TranslateAndScale, false,
3348            left, top, right, bottom, ignoreTransform);
3349    setupDrawColorUniforms(getShader(paint));
3350    setupDrawShaderUniforms(getShader(paint), ignoreTransform);
3351    setupDrawColorFilterUniforms(getColorFilter(paint));
3352    setupDrawSimpleMesh();
3353
3354    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
3355}
3356
3357void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3358        Texture* texture, const SkPaint* paint) {
3359    texture->setWrap(GL_CLAMP_TO_EDGE, true);
3360
3361    GLvoid* vertices = (GLvoid*) nullptr;
3362    GLvoid* texCoords = (GLvoid*) gMeshTextureOffset;
3363
3364    if (texture->uvMapper) {
3365        vertices = &mMeshVertices[0].x;
3366        texCoords = &mMeshVertices[0].u;
3367
3368        Rect uvs(0.0f, 0.0f, 1.0f, 1.0f);
3369        texture->uvMapper->map(uvs);
3370
3371        resetDrawTextureTexCoords(uvs.left, uvs.top, uvs.right, uvs.bottom);
3372    }
3373
3374    if (CC_LIKELY(currentTransform()->isPureTranslate())) {
3375        const float x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f);
3376        const float y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f);
3377
3378        texture->setFilter(GL_NEAREST, true);
3379        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
3380                paint, texture->blend, vertices, texCoords,
3381                GL_TRIANGLE_STRIP, gMeshCount, false, true);
3382    } else {
3383        texture->setFilter(getFilter(paint), true);
3384        drawTextureMesh(left, top, right, bottom, texture->id, paint,
3385                texture->blend, vertices, texCoords, GL_TRIANGLE_STRIP, gMeshCount);
3386    }
3387
3388    if (texture->uvMapper) {
3389        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
3390    }
3391}
3392
3393void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
3394        GLuint texture, const SkPaint* paint, bool blend,
3395        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3396        bool swapSrcDst, bool ignoreTransform, GLuint vbo,
3397        ModelViewMode modelViewMode, bool dirty) {
3398
3399    int a;
3400    SkXfermode::Mode mode;
3401    getAlphaAndMode(paint, &a, &mode);
3402    const float alpha = a / 255.0f;
3403
3404    setupDraw();
3405    setupDrawWithTexture();
3406    setupDrawColor(alpha, alpha, alpha, alpha);
3407    setupDrawColorFilter(getColorFilter(paint));
3408    setupDrawBlending(paint, blend, swapSrcDst);
3409    setupDrawProgram();
3410    if (!dirty) setupDrawDirtyRegionsDisabled();
3411    setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform);
3412    setupDrawTexture(texture);
3413    setupDrawPureColorUniforms();
3414    setupDrawColorFilterUniforms(getColorFilter(paint));
3415    setupDrawMesh(vertices, texCoords, vbo);
3416
3417    glDrawArrays(drawMode, 0, elementsCount);
3418}
3419
3420void OpenGLRenderer::drawIndexedTextureMesh(float left, float top, float right, float bottom,
3421        GLuint texture, const SkPaint* paint, bool blend,
3422        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3423        bool swapSrcDst, bool ignoreTransform, GLuint vbo,
3424        ModelViewMode modelViewMode, bool dirty) {
3425
3426    int a;
3427    SkXfermode::Mode mode;
3428    getAlphaAndMode(paint, &a, &mode);
3429    const float alpha = a / 255.0f;
3430
3431    setupDraw();
3432    setupDrawWithTexture();
3433    setupDrawColor(alpha, alpha, alpha, alpha);
3434    setupDrawColorFilter(getColorFilter(paint));
3435    setupDrawBlending(paint, blend, swapSrcDst);
3436    setupDrawProgram();
3437    if (!dirty) setupDrawDirtyRegionsDisabled();
3438    setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform);
3439    setupDrawTexture(texture);
3440    setupDrawPureColorUniforms();
3441    setupDrawColorFilterUniforms(getColorFilter(paint));
3442    setupDrawMeshIndices(vertices, texCoords, vbo);
3443
3444    glDrawElements(drawMode, elementsCount, GL_UNSIGNED_SHORT, nullptr);
3445}
3446
3447void OpenGLRenderer::drawAlpha8TextureMesh(float left, float top, float right, float bottom,
3448        GLuint texture, const SkPaint* paint,
3449        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3450        bool ignoreTransform, ModelViewMode modelViewMode, bool dirty) {
3451
3452    int color = paint != nullptr ? paint->getColor() : 0;
3453    int alpha;
3454    SkXfermode::Mode mode;
3455    getAlphaAndMode(paint, &alpha, &mode);
3456
3457    setupDraw();
3458    setupDrawWithTexture(true);
3459    if (paint != nullptr) {
3460        setupDrawAlpha8Color(color, alpha);
3461    }
3462    setupDrawColorFilter(getColorFilter(paint));
3463    setupDrawShader(getShader(paint));
3464    setupDrawBlending(paint, true);
3465    setupDrawProgram();
3466    if (!dirty) setupDrawDirtyRegionsDisabled();
3467    setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform);
3468    setupDrawTexture(texture);
3469    setupDrawPureColorUniforms();
3470    setupDrawColorFilterUniforms(getColorFilter(paint));
3471    setupDrawShaderUniforms(getShader(paint), ignoreTransform);
3472    setupDrawMesh(vertices, texCoords);
3473
3474    glDrawArrays(drawMode, 0, elementsCount);
3475}
3476
3477void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
3478        ProgramDescription& description, bool swapSrcDst) {
3479
3480    if (writableSnapshot()->roundRectClipState != nullptr /*&& !mSkipOutlineClip*/) {
3481        blend = true;
3482        mDescription.hasRoundRectClip = true;
3483    }
3484    mSkipOutlineClip = true;
3485
3486    blend = blend || mode != SkXfermode::kSrcOver_Mode;
3487
3488    if (blend) {
3489        // These blend modes are not supported by OpenGL directly and have
3490        // to be implemented using shaders. Since the shader will perform
3491        // the blending, turn blending off here
3492        // If the blend mode cannot be implemented using shaders, fall
3493        // back to the default SrcOver blend mode instead
3494        if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) {
3495            if (CC_UNLIKELY(mExtensions.hasFramebufferFetch())) {
3496                description.framebufferMode = mode;
3497                description.swapSrcDst = swapSrcDst;
3498
3499                if (mCaches.blend) {
3500                    glDisable(GL_BLEND);
3501                    mCaches.blend = false;
3502                }
3503
3504                return;
3505            } else {
3506                mode = SkXfermode::kSrcOver_Mode;
3507            }
3508        }
3509
3510        if (!mCaches.blend) {
3511            glEnable(GL_BLEND);
3512        }
3513
3514        GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
3515        GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
3516
3517        if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
3518            glBlendFunc(sourceMode, destMode);
3519            mCaches.lastSrcMode = sourceMode;
3520            mCaches.lastDstMode = destMode;
3521        }
3522    } else if (mCaches.blend) {
3523        glDisable(GL_BLEND);
3524    }
3525    mCaches.blend = blend;
3526}
3527
3528bool OpenGLRenderer::useProgram(Program* program) {
3529    if (!program->isInUse()) {
3530        if (mCaches.currentProgram != nullptr) mCaches.currentProgram->remove();
3531        program->use();
3532        mCaches.currentProgram = program;
3533        return false;
3534    }
3535    return true;
3536}
3537
3538void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
3539    TextureVertex* v = &mMeshVertices[0];
3540    TextureVertex::setUV(v++, u1, v1);
3541    TextureVertex::setUV(v++, u2, v1);
3542    TextureVertex::setUV(v++, u1, v2);
3543    TextureVertex::setUV(v++, u2, v2);
3544}
3545
3546void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha,
3547        SkXfermode::Mode* mode) const {
3548    getAlphaAndModeDirect(paint, alpha,  mode);
3549    if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) {
3550        // if drawing a layer, ignore the paint's alpha
3551        *alpha = mDrawModifiers.mOverrideLayerAlpha * 255;
3552    }
3553    *alpha *= currentSnapshot()->alpha;
3554}
3555
3556float OpenGLRenderer::getLayerAlpha(const Layer* layer) const {
3557    float alpha;
3558    if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) {
3559        alpha = mDrawModifiers.mOverrideLayerAlpha;
3560    } else {
3561        alpha = layer->getAlpha() / 255.0f;
3562    }
3563    return alpha * currentSnapshot()->alpha;
3564}
3565
3566}; // namespace uirenderer
3567}; // namespace android
3568