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