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