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