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