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