OpenGLRenderer.cpp revision 03ae272459869b854e5db252fc81a64a516e111f
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    float alpha = getLayerAlpha(layer);
850
851    setupDraw();
852    if (layer->getRenderTarget() == GL_TEXTURE_2D) {
853        setupDrawWithTexture();
854    } else {
855        setupDrawWithExternalTexture();
856    }
857    setupDrawTextureTransform();
858    setupDrawColor(alpha, alpha, alpha, alpha);
859    setupDrawColorFilter(layer->getColorFilter());
860    setupDrawBlending(layer);
861    setupDrawProgram();
862    setupDrawPureColorUniforms();
863    setupDrawColorFilterUniforms(layer->getColorFilter());
864    if (layer->getRenderTarget() == GL_TEXTURE_2D) {
865        setupDrawTexture(layer->getTextureId());
866    } else {
867        setupDrawExternalTexture(layer->getTextureId());
868    }
869    if (currentTransform()->isPureTranslate() &&
870            !layer->getForceFilter() &&
871            layer->getWidth() == (uint32_t) rect.getWidth() &&
872            layer->getHeight() == (uint32_t) rect.getHeight()) {
873        const float x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f);
874        const float y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f);
875
876        layer->setFilter(GL_NEAREST);
877        setupDrawModelView(kModelViewMode_TranslateAndScale, false,
878                x, y, x + rect.getWidth(), y + rect.getHeight(), true);
879    } else {
880        layer->setFilter(GL_LINEAR);
881        setupDrawModelView(kModelViewMode_TranslateAndScale, false,
882                rect.left, rect.top, rect.right, rect.bottom);
883    }
884    setupDrawTextureTransformUniforms(layer->getTexTransform());
885    setupDrawMesh(&mMeshVertices[0].x, &mMeshVertices[0].u);
886
887    glDrawArrays(GL_TRIANGLE_STRIP, 0, kUnitQuadCount);
888}
889
890void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
891    if (layer->isTextureLayer()) {
892        EVENT_LOGD("composeTextureLayerRect");
893        resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f);
894        drawTextureLayer(layer, rect);
895        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
896    } else {
897        EVENT_LOGD("composeHardwareLayerRect");
898        const Rect& texCoords = layer->texCoords;
899        resetDrawTextureTexCoords(texCoords.left, texCoords.top,
900                texCoords.right, texCoords.bottom);
901
902        float x = rect.left;
903        float y = rect.top;
904        bool simpleTransform = currentTransform()->isPureTranslate() &&
905                layer->getWidth() == (uint32_t) rect.getWidth() &&
906                layer->getHeight() == (uint32_t) rect.getHeight();
907
908        if (simpleTransform) {
909            // When we're swapping, the layer is already in screen coordinates
910            if (!swap) {
911                x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f);
912                y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f);
913            }
914
915            layer->setFilter(GL_NEAREST, true);
916        } else {
917            layer->setFilter(GL_LINEAR, true);
918        }
919
920        SkPaint layerPaint;
921        layerPaint.setAlpha(getLayerAlpha(layer) * 255);
922        layerPaint.setXfermodeMode(layer->getMode());
923        layerPaint.setColorFilter(layer->getColorFilter());
924
925        bool blend = layer->isBlend() || getLayerAlpha(layer) < 1.0f;
926        drawTextureMesh(x, y, x + rect.getWidth(), y + rect.getHeight(),
927                layer->getTextureId(), &layerPaint, blend,
928                &mMeshVertices[0].x, &mMeshVertices[0].u,
929                GL_TRIANGLE_STRIP, kUnitQuadCount, swap, swap || simpleTransform);
930
931        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
932    }
933}
934
935/**
936 * Issues the command X, and if we're composing a save layer to the fbo or drawing a newly updated
937 * hardware layer with overdraw debug on, draws again to the stencil only, so that these draw
938 * operations are correctly counted twice for overdraw. NOTE: assumes composeLayerRegion only used
939 * by saveLayer's restore
940 */
941#define DRAW_DOUBLE_STENCIL_IF(COND, DRAW_COMMAND) {                               \
942        DRAW_COMMAND;                                                              \
943        if (CC_UNLIKELY(mCaches.debugOverdraw && onGetTargetFbo() == 0 && COND)) { \
944            glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);                   \
945            DRAW_COMMAND;                                                          \
946            glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);                       \
947        }                                                                          \
948    }
949
950#define DRAW_DOUBLE_STENCIL(DRAW_COMMAND) DRAW_DOUBLE_STENCIL_IF(true, DRAW_COMMAND)
951
952// This class is purely for inspection. It inherits from SkShader, but Skia does not know how to
953// use it. The OpenGLRenderer will look at it to find its Layer and whether it is opaque.
954class LayerShader : public SkShader {
955public:
956    LayerShader(Layer* layer, const SkMatrix* localMatrix)
957    : INHERITED(localMatrix)
958    , mLayer(layer) {
959    }
960
961    virtual bool asACustomShader(void** data) const override {
962        if (data) {
963            *data = static_cast<void*>(mLayer);
964        }
965        return true;
966    }
967
968    virtual bool isOpaque() const override {
969        return !mLayer->isBlend();
970    }
971
972protected:
973    virtual void shadeSpan(int x, int y, SkPMColor[], int count) {
974        LOG_ALWAYS_FATAL("LayerShader should never be drawn with raster backend.");
975    }
976
977    virtual void flatten(SkWriteBuffer&) const override {
978        LOG_ALWAYS_FATAL("LayerShader should never be flattened.");
979    }
980
981    virtual Factory getFactory() const override {
982        LOG_ALWAYS_FATAL("LayerShader should never be created from a stream.");
983        return nullptr;
984    }
985private:
986    // Unowned.
987    Layer* mLayer;
988    typedef SkShader INHERITED;
989};
990
991void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
992    if (CC_UNLIKELY(layer->region.isEmpty())) return; // nothing to draw
993
994    if (layer->getConvexMask()) {
995        save(SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag);
996
997        // clip to the area of the layer the mask can be larger
998        clipRect(rect.left, rect.top, rect.right, rect.bottom, SkRegion::kIntersect_Op);
999
1000        SkPaint paint;
1001        paint.setAntiAlias(true);
1002        paint.setColor(SkColorSetARGB(int(getLayerAlpha(layer) * 255), 0, 0, 0));
1003
1004        // create LayerShader to map SaveLayer content into subsequent draw
1005        SkMatrix shaderMatrix;
1006        shaderMatrix.setTranslate(rect.left, rect.bottom);
1007        shaderMatrix.preScale(1, -1);
1008        LayerShader layerShader(layer, &shaderMatrix);
1009        paint.setShader(&layerShader);
1010
1011        // Since the drawing primitive is defined in local drawing space,
1012        // we don't need to modify the draw matrix
1013        const SkPath* maskPath = layer->getConvexMask();
1014        DRAW_DOUBLE_STENCIL(drawConvexPath(*maskPath, &paint));
1015
1016        paint.setShader(nullptr);
1017        restore();
1018
1019        return;
1020    }
1021
1022    if (layer->region.isRect()) {
1023        layer->setRegionAsRect();
1024
1025        DRAW_DOUBLE_STENCIL(composeLayerRect(layer, layer->regionRect));
1026
1027        layer->region.clear();
1028        return;
1029    }
1030
1031    EVENT_LOGD("composeLayerRegion");
1032    // standard Region based draw
1033    size_t count;
1034    const android::Rect* rects;
1035    Region safeRegion;
1036    if (CC_LIKELY(hasRectToRectTransform())) {
1037        rects = layer->region.getArray(&count);
1038    } else {
1039        safeRegion = Region::createTJunctionFreeRegion(layer->region);
1040        rects = safeRegion.getArray(&count);
1041    }
1042
1043    const float alpha = getLayerAlpha(layer);
1044    const float texX = 1.0f / float(layer->getWidth());
1045    const float texY = 1.0f / float(layer->getHeight());
1046    const float height = rect.getHeight();
1047
1048    setupDraw();
1049
1050    // We must get (and therefore bind) the region mesh buffer
1051    // after we setup drawing in case we need to mess with the
1052    // stencil buffer in setupDraw()
1053    TextureVertex* mesh = mCaches.getRegionMesh();
1054    uint32_t numQuads = 0;
1055
1056    setupDrawWithTexture();
1057    setupDrawColor(alpha, alpha, alpha, alpha);
1058    setupDrawColorFilter(layer->getColorFilter());
1059    setupDrawBlending(layer);
1060    setupDrawProgram();
1061    setupDrawDirtyRegionsDisabled();
1062    setupDrawPureColorUniforms();
1063    setupDrawColorFilterUniforms(layer->getColorFilter());
1064    setupDrawTexture(layer->getTextureId());
1065    if (currentTransform()->isPureTranslate()) {
1066        const float x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f);
1067        const float y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f);
1068
1069        layer->setFilter(GL_NEAREST);
1070        setupDrawModelView(kModelViewMode_Translate, false,
1071                x, y, x + rect.getWidth(), y + rect.getHeight(), true);
1072    } else {
1073        layer->setFilter(GL_LINEAR);
1074        setupDrawModelView(kModelViewMode_Translate, false,
1075                rect.left, rect.top, rect.right, rect.bottom);
1076    }
1077    setupDrawMeshIndices(&mesh[0].x, &mesh[0].u);
1078
1079    for (size_t i = 0; i < count; i++) {
1080        const android::Rect* r = &rects[i];
1081
1082        const float u1 = r->left * texX;
1083        const float v1 = (height - r->top) * texY;
1084        const float u2 = r->right * texX;
1085        const float v2 = (height - r->bottom) * texY;
1086
1087        // TODO: Reject quads outside of the clip
1088        TextureVertex::set(mesh++, r->left, r->top, u1, v1);
1089        TextureVertex::set(mesh++, r->right, r->top, u2, v1);
1090        TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
1091        TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
1092
1093        numQuads++;
1094
1095        if (numQuads >= kMaxNumberOfQuads) {
1096            DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6,
1097                    GL_UNSIGNED_SHORT, nullptr));
1098            numQuads = 0;
1099            mesh = mCaches.getRegionMesh();
1100        }
1101    }
1102
1103    if (numQuads > 0) {
1104        DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6,
1105                GL_UNSIGNED_SHORT, nullptr));
1106    }
1107
1108#if DEBUG_LAYERS_AS_REGIONS
1109    drawRegionRectsDebug(layer->region);
1110#endif
1111
1112    layer->region.clear();
1113}
1114
1115#if DEBUG_LAYERS_AS_REGIONS
1116void OpenGLRenderer::drawRegionRectsDebug(const Region& region) {
1117    size_t count;
1118    const android::Rect* rects = region.getArray(&count);
1119
1120    uint32_t colors[] = {
1121            0x7fff0000, 0x7f00ff00,
1122            0x7f0000ff, 0x7fff00ff,
1123    };
1124
1125    int offset = 0;
1126    int32_t top = rects[0].top;
1127
1128    for (size_t i = 0; i < count; i++) {
1129        if (top != rects[i].top) {
1130            offset ^= 0x2;
1131            top = rects[i].top;
1132        }
1133
1134        SkPaint paint;
1135        paint.setColor(colors[offset + (i & 0x1)]);
1136        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
1137        drawColorRect(r.left, r.top, r.right, r.bottom, paint);
1138    }
1139}
1140#endif
1141
1142void OpenGLRenderer::drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty) {
1143    Vector<float> rects;
1144
1145    SkRegion::Iterator it(region);
1146    while (!it.done()) {
1147        const SkIRect& r = it.rect();
1148        rects.push(r.fLeft);
1149        rects.push(r.fTop);
1150        rects.push(r.fRight);
1151        rects.push(r.fBottom);
1152        it.next();
1153    }
1154
1155    drawColorRects(rects.array(), rects.size(), &paint, true, dirty, false);
1156}
1157
1158void OpenGLRenderer::dirtyLayer(const float left, const float top,
1159        const float right, const float bottom, const mat4 transform) {
1160    if (hasLayer()) {
1161        Rect bounds(left, top, right, bottom);
1162        transform.mapRect(bounds);
1163        dirtyLayerUnchecked(bounds, getRegion());
1164    }
1165}
1166
1167void OpenGLRenderer::dirtyLayer(const float left, const float top,
1168        const float right, const float bottom) {
1169    if (hasLayer()) {
1170        Rect bounds(left, top, right, bottom);
1171        dirtyLayerUnchecked(bounds, getRegion());
1172    }
1173}
1174
1175void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
1176    if (bounds.intersect(mState.currentClipRect())) {
1177        bounds.snapToPixelBoundaries();
1178        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
1179        if (!dirty.isEmpty()) {
1180            region->orSelf(dirty);
1181        }
1182    }
1183}
1184
1185void OpenGLRenderer::issueIndexedQuadDraw(Vertex* mesh, GLsizei quadsCount) {
1186    GLsizei elementsCount = quadsCount * 6;
1187    while (elementsCount > 0) {
1188        GLsizei drawCount = MathUtils::min(elementsCount, (GLsizei) kMaxNumberOfQuads * 6);
1189
1190        setupDrawIndexedVertices(&mesh[0].x);
1191        glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, nullptr);
1192
1193        elementsCount -= drawCount;
1194        // Though there are 4 vertices in a quad, we use 6 indices per
1195        // quad to draw with GL_TRIANGLES
1196        mesh += (drawCount / 6) * 4;
1197    }
1198}
1199
1200void OpenGLRenderer::clearLayerRegions() {
1201    const size_t quadCount = mLayers.size();
1202    if (quadCount == 0) return;
1203
1204    if (!mState.currentlyIgnored()) {
1205        EVENT_LOGD("clearLayerRegions");
1206        // Doing several glScissor/glClear here can negatively impact
1207        // GPUs with a tiler architecture, instead we draw quads with
1208        // the Clear blending mode
1209
1210        // The list contains bounds that have already been clipped
1211        // against their initial clip rect, and the current clip
1212        // is likely different so we need to disable clipping here
1213        bool scissorChanged = mRenderState.scissor().setEnabled(false);
1214
1215        Vertex mesh[quadCount * 4];
1216        Vertex* vertex = mesh;
1217
1218        for (uint32_t i = 0; i < quadCount; i++) {
1219            const Rect& bounds = mLayers[i];
1220
1221            Vertex::set(vertex++, bounds.left, bounds.top);
1222            Vertex::set(vertex++, bounds.right, bounds.top);
1223            Vertex::set(vertex++, bounds.left, bounds.bottom);
1224            Vertex::set(vertex++, bounds.right, bounds.bottom);
1225        }
1226        // We must clear the list of dirty rects before we
1227        // call setupDraw() to prevent stencil setup to do
1228        // the same thing again
1229        mLayers.clear();
1230
1231        if (USE_GLOPS) {
1232            Glop glop;
1233            GlopBuilder aBuilder(mRenderState, mCaches, &glop);
1234            aBuilder.setMeshIndexedQuads(&mesh[0], quadCount)
1235                    .setFillClear()
1236                    .setTransform(currentSnapshot()->getOrthoMatrix(), Matrix4::identity(), false)
1237                    .setModelViewOffsetRect(0, 0, currentSnapshot()->getClipRect())
1238                    .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1239                    .build();
1240            renderGlop(glop);
1241        } else {
1242            SkPaint clearPaint;
1243            clearPaint.setXfermodeMode(SkXfermode::kClear_Mode);
1244
1245            setupDraw(false);
1246            setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f);
1247            setupDrawBlending(&clearPaint, true);
1248            setupDrawProgram();
1249            setupDrawPureColorUniforms();
1250            setupDrawModelView(kModelViewMode_Translate, false,
1251                    0.0f, 0.0f, 0.0f, 0.0f, true);
1252
1253            issueIndexedQuadDraw(&mesh[0], quadCount);
1254        }
1255
1256        if (scissorChanged) mRenderState.scissor().setEnabled(true);
1257    } else {
1258        mLayers.clear();
1259    }
1260}
1261
1262///////////////////////////////////////////////////////////////////////////////
1263// State Deferral
1264///////////////////////////////////////////////////////////////////////////////
1265
1266bool OpenGLRenderer::storeDisplayState(DeferredDisplayState& state, int stateDeferFlags) {
1267    const Rect& currentClip = mState.currentClipRect();
1268    const mat4* currentMatrix = currentTransform();
1269
1270    if (stateDeferFlags & kStateDeferFlag_Draw) {
1271        // state has bounds initialized in local coordinates
1272        if (!state.mBounds.isEmpty()) {
1273            currentMatrix->mapRect(state.mBounds);
1274            Rect clippedBounds(state.mBounds);
1275            // NOTE: if we ever want to use this clipping info to drive whether the scissor
1276            // is used, it should more closely duplicate the quickReject logic (in how it uses
1277            // snapToPixelBoundaries)
1278
1279            if (!clippedBounds.intersect(currentClip)) {
1280                // quick rejected
1281                return true;
1282            }
1283
1284            state.mClipSideFlags = kClipSide_None;
1285            if (!currentClip.contains(state.mBounds)) {
1286                int& flags = state.mClipSideFlags;
1287                // op partially clipped, so record which sides are clipped for clip-aware merging
1288                if (currentClip.left > state.mBounds.left) flags |= kClipSide_Left;
1289                if (currentClip.top > state.mBounds.top) flags |= kClipSide_Top;
1290                if (currentClip.right < state.mBounds.right) flags |= kClipSide_Right;
1291                if (currentClip.bottom < state.mBounds.bottom) flags |= kClipSide_Bottom;
1292            }
1293            state.mBounds.set(clippedBounds);
1294        } else {
1295            // Empty bounds implies size unknown. Label op as conservatively clipped to disable
1296            // overdraw avoidance (since we don't know what it overlaps)
1297            state.mClipSideFlags = kClipSide_ConservativeFull;
1298            state.mBounds.set(currentClip);
1299        }
1300    }
1301
1302    state.mClipValid = (stateDeferFlags & kStateDeferFlag_Clip);
1303    if (state.mClipValid) {
1304        state.mClip.set(currentClip);
1305    }
1306
1307    // Transform, drawModifiers, and alpha always deferred, since they are used by state operations
1308    // (Note: saveLayer/restore use colorFilter and alpha, so we just save restore everything)
1309    state.mMatrix.load(*currentMatrix);
1310    state.mDrawModifiers = mDrawModifiers;
1311    state.mAlpha = currentSnapshot()->alpha;
1312
1313    // always store/restore, since it's just a pointer
1314    state.mRoundRectClipState = currentSnapshot()->roundRectClipState;
1315    return false;
1316}
1317
1318void OpenGLRenderer::restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore) {
1319    setMatrix(state.mMatrix);
1320    writableSnapshot()->alpha = state.mAlpha;
1321    mDrawModifiers = state.mDrawModifiers;
1322    writableSnapshot()->roundRectClipState = state.mRoundRectClipState;
1323
1324    if (state.mClipValid && !skipClipRestore) {
1325        writableSnapshot()->setClip(state.mClip.left, state.mClip.top,
1326                state.mClip.right, state.mClip.bottom);
1327        dirtyClip();
1328    }
1329}
1330
1331/**
1332 * Merged multidraw (such as in drawText and drawBitmaps rely on the fact that no clipping is done
1333 * in the draw path. Instead, clipping is done ahead of time - either as a single clip rect (when at
1334 * least one op is clipped), or disabled entirely (because no merged op is clipped)
1335 *
1336 * This method should be called when restoreDisplayState() won't be restoring the clip
1337 */
1338void OpenGLRenderer::setupMergedMultiDraw(const Rect* clipRect) {
1339    if (clipRect != nullptr) {
1340        writableSnapshot()->setClip(clipRect->left, clipRect->top, clipRect->right, clipRect->bottom);
1341    } else {
1342        writableSnapshot()->setClip(0, 0, mState.getWidth(), mState.getHeight());
1343    }
1344    dirtyClip();
1345    bool enableScissor = (clipRect != nullptr) || mScissorOptimizationDisabled;
1346    mRenderState.scissor().setEnabled(enableScissor);
1347}
1348
1349///////////////////////////////////////////////////////////////////////////////
1350// Clipping
1351///////////////////////////////////////////////////////////////////////////////
1352
1353void OpenGLRenderer::setScissorFromClip() {
1354    Rect clip(mState.currentClipRect());
1355    clip.snapToPixelBoundaries();
1356
1357    if (mRenderState.scissor().set(clip.left, getViewportHeight() - clip.bottom,
1358            clip.getWidth(), clip.getHeight())) {
1359        mState.setDirtyClip(false);
1360    }
1361}
1362
1363void OpenGLRenderer::ensureStencilBuffer() {
1364    // Thanks to the mismatch between EGL and OpenGL ES FBO we
1365    // cannot attach a stencil buffer to fbo0 dynamically. Let's
1366    // just hope we have one when hasLayer() returns false.
1367    if (hasLayer()) {
1368        attachStencilBufferToLayer(currentSnapshot()->layer);
1369    }
1370}
1371
1372void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) {
1373    // The layer's FBO is already bound when we reach this stage
1374    if (!layer->getStencilRenderBuffer()) {
1375        // GL_QCOM_tiled_rendering doesn't like it if a renderbuffer
1376        // is attached after we initiated tiling. We must turn it off,
1377        // attach the new render buffer then turn tiling back on
1378        endTiling();
1379
1380        RenderBuffer* buffer = mCaches.renderBufferCache.get(
1381                Stencil::getSmallestStencilFormat(),
1382                layer->getWidth(), layer->getHeight());
1383        layer->setStencilRenderBuffer(buffer);
1384
1385        startTiling(layer->clipRect, layer->layer.getHeight());
1386    }
1387}
1388
1389static void handlePoint(std::vector<Vertex>& rectangleVertices, const Matrix4& transform,
1390        float x, float y) {
1391    Vertex v;
1392    v.x = x;
1393    v.y = y;
1394    transform.mapPoint(v.x, v.y);
1395    rectangleVertices.push_back(v);
1396}
1397
1398static void handlePointNoTransform(std::vector<Vertex>& rectangleVertices, float x, float y) {
1399    Vertex v;
1400    v.x = x;
1401    v.y = y;
1402    rectangleVertices.push_back(v);
1403}
1404
1405void OpenGLRenderer::drawRectangleList(const RectangleList& rectangleList) {
1406    int quadCount = rectangleList.getTransformedRectanglesCount();
1407    std::vector<Vertex> rectangleVertices(quadCount * 4);
1408    Rect scissorBox = rectangleList.calculateBounds();
1409    scissorBox.snapToPixelBoundaries();
1410    for (int i = 0; i < quadCount; ++i) {
1411        const TransformedRectangle& tr(rectangleList.getTransformedRectangle(i));
1412        const Matrix4& transform = tr.getTransform();
1413        Rect bounds = tr.getBounds();
1414        if (transform.rectToRect()) {
1415            transform.mapRect(bounds);
1416            if (!bounds.intersect(scissorBox)) {
1417                bounds.setEmpty();
1418            } else {
1419                handlePointNoTransform(rectangleVertices, bounds.left, bounds.top);
1420                handlePointNoTransform(rectangleVertices, bounds.right, bounds.top);
1421                handlePointNoTransform(rectangleVertices, bounds.left, bounds.bottom);
1422                handlePointNoTransform(rectangleVertices, bounds.right, bounds.bottom);
1423            }
1424        } else {
1425            handlePoint(rectangleVertices, transform, bounds.left, bounds.top);
1426            handlePoint(rectangleVertices, transform, bounds.right, bounds.top);
1427            handlePoint(rectangleVertices, transform, bounds.left, bounds.bottom);
1428            handlePoint(rectangleVertices, transform, bounds.right, bounds.bottom);
1429        }
1430    }
1431
1432    mRenderState.scissor().set(scissorBox.left, getViewportHeight() - scissorBox.bottom,
1433            scissorBox.getWidth(), scissorBox.getHeight());
1434
1435    if (USE_GLOPS) {
1436        Glop glop;
1437        GlopBuilder aBuilder(mRenderState, mCaches, &glop);
1438        aBuilder.setMeshIndexedQuads(&rectangleVertices[0], rectangleVertices.size() / 4)
1439                .setFillBlack()
1440                .setTransform(currentSnapshot()->getOrthoMatrix(), Matrix4::identity(), false)
1441                .setModelViewOffsetRect(0, 0, scissorBox)
1442                .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1443                .build();
1444        renderGlop(glop);
1445        return;
1446    }
1447
1448    const SkPaint* paint = nullptr;
1449    setupDraw();
1450    setupDrawNoTexture();
1451    setupDrawColor(0, 0xff * currentSnapshot()->alpha);
1452    setupDrawShader(getShader(paint));
1453    setupDrawColorFilter(getColorFilter(paint));
1454    setupDrawBlending(paint);
1455    setupDrawProgram();
1456    setupDrawDirtyRegionsDisabled();
1457    setupDrawModelView(kModelViewMode_Translate, false,
1458            0.0f, 0.0f, 0.0f, 0.0f, true);
1459    setupDrawColorUniforms(getShader(paint));
1460    setupDrawShaderUniforms(getShader(paint));
1461    setupDrawColorFilterUniforms(getColorFilter(paint));
1462
1463    issueIndexedQuadDraw(&rectangleVertices[0], rectangleVertices.size() / 4);
1464}
1465
1466void OpenGLRenderer::setStencilFromClip() {
1467    if (!mCaches.debugOverdraw) {
1468        if (!currentSnapshot()->clipIsSimple()) {
1469            int incrementThreshold;
1470            EVENT_LOGD("setStencilFromClip - enabling");
1471
1472            // NOTE: The order here is important, we must set dirtyClip to false
1473            //       before any draw call to avoid calling back into this method
1474            mState.setDirtyClip(false);
1475
1476            ensureStencilBuffer();
1477
1478            const ClipArea& clipArea = currentSnapshot()->getClipArea();
1479
1480            bool isRectangleList = clipArea.isRectangleList();
1481            if (isRectangleList) {
1482                incrementThreshold = clipArea.getRectangleList().getTransformedRectanglesCount();
1483            } else {
1484                incrementThreshold = 0;
1485            }
1486
1487            mRenderState.stencil().enableWrite(incrementThreshold);
1488
1489            // Clean and update the stencil, but first make sure we restrict drawing
1490            // to the region's bounds
1491            bool resetScissor = mRenderState.scissor().setEnabled(true);
1492            if (resetScissor) {
1493                // The scissor was not set so we now need to update it
1494                setScissorFromClip();
1495            }
1496
1497            mRenderState.stencil().clear();
1498
1499            // stash and disable the outline clip state, since stencil doesn't account for outline
1500            bool storedSkipOutlineClip = mSkipOutlineClip;
1501            mSkipOutlineClip = true;
1502
1503            SkPaint paint;
1504            paint.setColor(SK_ColorBLACK);
1505            paint.setXfermodeMode(SkXfermode::kSrc_Mode);
1506
1507            if (isRectangleList) {
1508                drawRectangleList(clipArea.getRectangleList());
1509            } else {
1510                // NOTE: We could use the region contour path to generate a smaller mesh
1511                //       Since we are using the stencil we could use the red book path
1512                //       drawing technique. It might increase bandwidth usage though.
1513
1514                // The last parameter is important: we are not drawing in the color buffer
1515                // so we don't want to dirty the current layer, if any
1516                drawRegionRects(clipArea.getClipRegion(), paint, false);
1517            }
1518            if (resetScissor) mRenderState.scissor().setEnabled(false);
1519            mSkipOutlineClip = storedSkipOutlineClip;
1520
1521            mRenderState.stencil().enableTest(incrementThreshold);
1522
1523            // Draw the region used to generate the stencil if the appropriate debug
1524            // mode is enabled
1525            // TODO: Implement for rectangle list clip areas
1526            if (mCaches.debugStencilClip == Caches::kStencilShowRegion &&
1527                    !clipArea.isRectangleList()) {
1528                paint.setColor(0x7f0000ff);
1529                paint.setXfermodeMode(SkXfermode::kSrcOver_Mode);
1530                drawRegionRects(currentSnapshot()->getClipRegion(), paint);
1531            }
1532        } else {
1533            EVENT_LOGD("setStencilFromClip - disabling");
1534            mRenderState.stencil().disable();
1535        }
1536    }
1537}
1538
1539/**
1540 * Returns false and sets scissor enable based upon bounds if drawing won't be clipped out.
1541 *
1542 * @param paint if not null, the bounds will be expanded to account for stroke depending on paint
1543 *         style, and tessellated AA ramp
1544 */
1545bool OpenGLRenderer::quickRejectSetupScissor(float left, float top, float right, float bottom,
1546        const SkPaint* paint) {
1547    bool snapOut = paint && paint->isAntiAlias();
1548
1549    if (paint && paint->getStyle() != SkPaint::kFill_Style) {
1550        float outset = paint->getStrokeWidth() * 0.5f;
1551        left -= outset;
1552        top -= outset;
1553        right += outset;
1554        bottom += outset;
1555    }
1556
1557    bool clipRequired = false;
1558    bool roundRectClipRequired = false;
1559    if (mState.calculateQuickRejectForScissor(left, top, right, bottom,
1560            &clipRequired, &roundRectClipRequired, snapOut)) {
1561        return true;
1562    }
1563
1564    // not quick rejected, so enable the scissor if clipRequired
1565    mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
1566    mSkipOutlineClip = !roundRectClipRequired;
1567    return false;
1568}
1569
1570void OpenGLRenderer::debugClip() {
1571#if DEBUG_CLIP_REGIONS
1572    if (!currentSnapshot()->clipRegion->isEmpty()) {
1573        SkPaint paint;
1574        paint.setColor(0x7f00ff00);
1575        drawRegionRects(*(currentSnapshot()->clipRegion, paint);
1576
1577    }
1578#endif
1579}
1580
1581void OpenGLRenderer::renderGlop(const Glop& glop) {
1582    if (mState.getDirtyClip()) {
1583        if (mRenderState.scissor().isEnabled()) {
1584            setScissorFromClip();
1585        }
1586
1587        setStencilFromClip();
1588    }
1589    mRenderState.render(glop);
1590
1591    if (!mRenderState.stencil().isWriteEnabled()) {
1592        // TODO: specify more clearly when a draw should dirty the layer.
1593        // is writing to the stencil the only time we should ignore this?
1594        dirtyLayer(glop.bounds.left, glop.bounds.top, glop.bounds.right, glop.bounds.bottom);
1595        mDirty = true;
1596    }
1597}
1598
1599///////////////////////////////////////////////////////////////////////////////
1600// Drawing commands
1601///////////////////////////////////////////////////////////////////////////////
1602
1603void OpenGLRenderer::setupDraw(bool clearLayer) {
1604    // TODO: It would be best if we could do this before quickRejectSetupScissor()
1605    //       changes the scissor test state
1606    if (clearLayer) clearLayerRegions();
1607    // Make sure setScissor & setStencil happen at the beginning of
1608    // this method
1609    if (mState.getDirtyClip()) {
1610        if (mRenderState.scissor().isEnabled()) {
1611            setScissorFromClip();
1612        }
1613
1614        setStencilFromClip();
1615    }
1616
1617    mDescription.reset();
1618
1619    mSetShaderColor = false;
1620    mColorSet = false;
1621    mColor.a = mColor.r = mColor.g = mColor.b = 0.0f;
1622    mTextureUnit = 0;
1623    mTrackDirtyRegions = true;
1624
1625    // Enable debug highlight when what we're about to draw is tested against
1626    // the stencil buffer and if stencil highlight debugging is on
1627    mDescription.hasDebugHighlight = !mCaches.debugOverdraw
1628            && mCaches.debugStencilClip == Caches::kStencilShowHighlight
1629            && mRenderState.stencil().isTestEnabled();
1630}
1631
1632void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
1633    mDescription.hasTexture = true;
1634    mDescription.hasAlpha8Texture = isAlpha8;
1635}
1636
1637void OpenGLRenderer::setupDrawWithTextureAndColor(bool isAlpha8) {
1638    mDescription.hasTexture = true;
1639    mDescription.hasColors = true;
1640    mDescription.hasAlpha8Texture = isAlpha8;
1641}
1642
1643void OpenGLRenderer::setupDrawWithExternalTexture() {
1644    mDescription.hasExternalTexture = true;
1645}
1646
1647void OpenGLRenderer::setupDrawNoTexture() {
1648    mRenderState.meshState().disableTexCoordsVertexArray();
1649}
1650
1651void OpenGLRenderer::setupDrawVertexAlpha(bool useShadowAlphaInterp) {
1652    mDescription.hasVertexAlpha = true;
1653    mDescription.useShadowAlphaInterp = useShadowAlphaInterp;
1654}
1655
1656void OpenGLRenderer::setupDrawColor(int color, int alpha) {
1657    mColor.a = alpha / 255.0f;
1658    mColor.r = mColor.a * ((color >> 16) & 0xFF) / 255.0f;
1659    mColor.g = mColor.a * ((color >>  8) & 0xFF) / 255.0f;
1660    mColor.b = mColor.a * ((color      ) & 0xFF) / 255.0f;
1661    mColorSet = true;
1662    mSetShaderColor = mDescription.setColorModulate(mColor.a);
1663}
1664
1665void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
1666    mColor.a = alpha / 255.0f;
1667    mColor.r = mColor.a * ((color >> 16) & 0xFF) / 255.0f;
1668    mColor.g = mColor.a * ((color >>  8) & 0xFF) / 255.0f;
1669    mColor.b = mColor.a * ((color      ) & 0xFF) / 255.0f;
1670    mColorSet = true;
1671    mSetShaderColor = mDescription.setAlpha8ColorModulate(mColor.r, mColor.g, mColor.b, mColor.a);
1672}
1673
1674void OpenGLRenderer::setupDrawTextGamma(const SkPaint* paint) {
1675    mCaches.fontRenderer->describe(mDescription, paint);
1676}
1677
1678void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
1679    mColor.a = a;
1680    mColor.r = r;
1681    mColor.g = g;
1682    mColor.b = b;
1683    mColorSet = true;
1684    mSetShaderColor = mDescription.setColorModulate(a);
1685}
1686
1687void OpenGLRenderer::setupDrawShader(const SkShader* shader) {
1688    if (shader != nullptr) {
1689        SkiaShader::describe(&mCaches, mDescription, mCaches.extensions(), *shader);
1690    }
1691}
1692
1693void OpenGLRenderer::setupDrawColorFilter(const SkColorFilter* filter) {
1694    if (filter == nullptr) {
1695        return;
1696    }
1697
1698    SkXfermode::Mode mode;
1699    if (filter->asColorMode(nullptr, &mode)) {
1700        mDescription.colorOp = ProgramDescription::kColorBlend;
1701        mDescription.colorMode = mode;
1702    } else if (filter->asColorMatrix(nullptr)) {
1703        mDescription.colorOp = ProgramDescription::kColorMatrix;
1704    }
1705}
1706
1707void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
1708    if (mColorSet && mode == SkXfermode::kClear_Mode) {
1709        mColor.a = 1.0f;
1710        mColor.r = mColor.g = mColor.b = 0.0f;
1711        mSetShaderColor = mDescription.modulate = true;
1712    }
1713}
1714
1715void OpenGLRenderer::setupDrawBlending(const Layer* layer, bool swapSrcDst) {
1716    SkXfermode::Mode mode = layer->getMode();
1717    // When the blending mode is kClear_Mode, we need to use a modulate color
1718    // argb=1,0,0,0
1719    accountForClear(mode);
1720    // TODO: check shader blending, once we have shader drawing support for layers.
1721    bool blend = layer->isBlend()
1722            || getLayerAlpha(layer) < 1.0f
1723            || (mColorSet && mColor.a < 1.0f)
1724            || PaintUtils::isBlendedColorFilter(layer->getColorFilter());
1725    chooseBlending(blend, mode, mDescription, swapSrcDst);
1726}
1727
1728void OpenGLRenderer::setupDrawBlending(const SkPaint* paint, bool blend, bool swapSrcDst) {
1729    SkXfermode::Mode mode = getXfermodeDirect(paint);
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    blend |= (mColorSet && mColor.a < 1.0f)
1734            || (getShader(paint) && !getShader(paint)->isOpaque())
1735            || PaintUtils::isBlendedColorFilter(getColorFilter(paint));
1736    chooseBlending(blend, mode, mDescription, swapSrcDst);
1737}
1738
1739void OpenGLRenderer::setupDrawProgram() {
1740    mCaches.setProgram(mDescription);
1741    if (mDescription.hasRoundRectClip) {
1742        // TODO: avoid doing this repeatedly, stashing state pointer in program
1743        const RoundRectClipState* state = writableSnapshot()->roundRectClipState;
1744        const Rect& innerRect = state->innerRect;
1745        glUniform4f(mCaches.program().getUniform("roundRectInnerRectLTRB"),
1746                innerRect.left, innerRect.top,
1747                innerRect.right, innerRect.bottom);
1748        glUniformMatrix4fv(mCaches.program().getUniform("roundRectInvTransform"),
1749                1, GL_FALSE, &state->matrix.data[0]);
1750
1751        // add half pixel to round out integer rect space to cover pixel centers
1752        float roundedOutRadius = state->radius + 0.5f;
1753        glUniform1f(mCaches.program().getUniform("roundRectRadius"),
1754                roundedOutRadius);
1755    }
1756}
1757
1758void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
1759    mTrackDirtyRegions = false;
1760}
1761
1762void OpenGLRenderer::setupDrawModelView(ModelViewMode mode, bool offset,
1763        float left, float top, float right, float bottom, bool ignoreTransform) {
1764    mModelViewMatrix.loadTranslate(left, top, 0.0f);
1765    if (mode == kModelViewMode_TranslateAndScale) {
1766        mModelViewMatrix.scale(right - left, bottom - top, 1.0f);
1767    }
1768
1769    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
1770    const Matrix4& transformMatrix = ignoreTransform ? Matrix4::identity() : *currentTransform();
1771
1772    mCaches.program().set(currentSnapshot()->getOrthoMatrix(),
1773            mModelViewMatrix, transformMatrix, offset);
1774    if (dirty && mTrackDirtyRegions) {
1775        if (!ignoreTransform) {
1776            dirtyLayer(left, top, right, bottom, *currentTransform());
1777        } else {
1778            dirtyLayer(left, top, right, bottom);
1779        }
1780    }
1781}
1782
1783void OpenGLRenderer::setupDrawColorUniforms(bool hasShader) {
1784    if ((mColorSet && !hasShader) || (hasShader && mSetShaderColor)) {
1785        mCaches.program().setColor(mColor);
1786    }
1787}
1788
1789void OpenGLRenderer::setupDrawPureColorUniforms() {
1790    if (mSetShaderColor) {
1791        mCaches.program().setColor(mColor);
1792    }
1793}
1794
1795void OpenGLRenderer::setupDrawShaderUniforms(const SkShader* shader, bool ignoreTransform) {
1796    if (shader == nullptr) {
1797        return;
1798    }
1799
1800    if (ignoreTransform) {
1801        // if ignoreTransform=true was passed to setupDrawModelView, undo currentTransform()
1802        // because it was built into modelView / the geometry, and the description needs to
1803        // compensate.
1804        mat4 modelViewWithoutTransform;
1805        modelViewWithoutTransform.loadInverse(*currentTransform());
1806        modelViewWithoutTransform.multiply(mModelViewMatrix);
1807        mModelViewMatrix.load(modelViewWithoutTransform);
1808    }
1809
1810    SkiaShader::setupProgram(&mCaches, mModelViewMatrix, &mTextureUnit,
1811            mCaches.extensions(), *shader);
1812}
1813
1814void OpenGLRenderer::setupDrawColorFilterUniforms(const SkColorFilter* filter) {
1815    if (nullptr == filter) {
1816        return;
1817    }
1818
1819    SkColor color;
1820    SkXfermode::Mode mode;
1821    if (filter->asColorMode(&color, &mode)) {
1822        const int alpha = SkColorGetA(color);
1823        const GLfloat a = alpha / 255.0f;
1824        const GLfloat r = a * SkColorGetR(color) / 255.0f;
1825        const GLfloat g = a * SkColorGetG(color) / 255.0f;
1826        const GLfloat b = a * SkColorGetB(color) / 255.0f;
1827        glUniform4f(mCaches.program().getUniform("colorBlend"), r, g, b, a);
1828        return;
1829    }
1830
1831    SkScalar srcColorMatrix[20];
1832    if (filter->asColorMatrix(srcColorMatrix)) {
1833
1834        float colorMatrix[16];
1835        memcpy(colorMatrix, srcColorMatrix, 4 * sizeof(float));
1836        memcpy(&colorMatrix[4], &srcColorMatrix[5], 4 * sizeof(float));
1837        memcpy(&colorMatrix[8], &srcColorMatrix[10], 4 * sizeof(float));
1838        memcpy(&colorMatrix[12], &srcColorMatrix[15], 4 * sizeof(float));
1839
1840        // Skia uses the range [0..255] for the addition vector, but we need
1841        // the [0..1] range to apply the vector in GLSL
1842        float colorVector[4];
1843        colorVector[0] = srcColorMatrix[4] / 255.0f;
1844        colorVector[1] = srcColorMatrix[9] / 255.0f;
1845        colorVector[2] = srcColorMatrix[14] / 255.0f;
1846        colorVector[3] = srcColorMatrix[19] / 255.0f;
1847
1848        glUniformMatrix4fv(mCaches.program().getUniform("colorMatrix"), 1,
1849                GL_FALSE, colorMatrix);
1850        glUniform4fv(mCaches.program().getUniform("colorMatrixVector"), 1, colorVector);
1851        return;
1852    }
1853
1854    // it is an error if we ever get here
1855}
1856
1857void OpenGLRenderer::setupDrawTextGammaUniforms() {
1858    mCaches.fontRenderer->setupProgram(mDescription, mCaches.program());
1859}
1860
1861void OpenGLRenderer::setupDrawSimpleMesh() {
1862    bool force = mRenderState.meshState().bindMeshBuffer();
1863    mRenderState.meshState().bindPositionVertexPointer(force, nullptr);
1864    mRenderState.meshState().unbindIndicesBuffer();
1865}
1866
1867void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1868    if (texture) mCaches.textureState().bindTexture(texture);
1869    mTextureUnit++;
1870    mRenderState.meshState().enableTexCoordsVertexArray();
1871}
1872
1873void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) {
1874    mCaches.textureState().bindTexture(GL_TEXTURE_EXTERNAL_OES, texture);
1875    mTextureUnit++;
1876    mRenderState.meshState().enableTexCoordsVertexArray();
1877}
1878
1879void OpenGLRenderer::setupDrawTextureTransform() {
1880    mDescription.hasTextureTransform = true;
1881}
1882
1883void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) {
1884    glUniformMatrix4fv(mCaches.program().getUniform("mainTextureTransform"), 1,
1885            GL_FALSE, &transform.data[0]);
1886}
1887
1888void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices,
1889        const GLvoid* texCoords, GLuint vbo) {
1890    bool force = false;
1891    if (!vertices || vbo) {
1892        force = mRenderState.meshState().bindMeshBuffer(vbo);
1893    } else {
1894        force = mRenderState.meshState().unbindMeshBuffer();
1895    }
1896
1897    mRenderState.meshState().bindPositionVertexPointer(force, vertices);
1898    if (mCaches.program().texCoords >= 0) {
1899        mRenderState.meshState().bindTexCoordsVertexPointer(force, texCoords);
1900    }
1901
1902    mRenderState.meshState().unbindIndicesBuffer();
1903}
1904
1905void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices,
1906        const GLvoid* texCoords, const GLvoid* colors) {
1907    bool force = mRenderState.meshState().unbindMeshBuffer();
1908    GLsizei stride = sizeof(ColorTextureVertex);
1909
1910    mRenderState.meshState().bindPositionVertexPointer(force, vertices, stride);
1911    if (mCaches.program().texCoords >= 0) {
1912        mRenderState.meshState().bindTexCoordsVertexPointer(force, texCoords, stride);
1913    }
1914    int slot = mCaches.program().getAttrib("colors");
1915    if (slot >= 0) {
1916        glEnableVertexAttribArray(slot);
1917        glVertexAttribPointer(slot, 4, GL_FLOAT, GL_FALSE, stride, colors);
1918    }
1919
1920    mRenderState.meshState().unbindIndicesBuffer();
1921}
1922
1923void OpenGLRenderer::setupDrawMeshIndices(const GLvoid* vertices,
1924        const GLvoid* texCoords, GLuint vbo) {
1925    bool force = false;
1926    // If vbo is != 0 we want to treat the vertices parameter as an offset inside
1927    // a VBO. However, if vertices is set to NULL and vbo == 0 then we want to
1928    // use the default VBO found in RenderState
1929    if (!vertices || vbo) {
1930        force = mRenderState.meshState().bindMeshBuffer(vbo);
1931    } else {
1932        force = mRenderState.meshState().unbindMeshBuffer();
1933    }
1934    mRenderState.meshState().bindQuadIndicesBuffer();
1935
1936    mRenderState.meshState().bindPositionVertexPointer(force, vertices);
1937    if (mCaches.program().texCoords >= 0) {
1938        mRenderState.meshState().bindTexCoordsVertexPointer(force, texCoords);
1939    }
1940}
1941
1942void OpenGLRenderer::setupDrawIndexedVertices(GLvoid* vertices) {
1943    bool force = mRenderState.meshState().unbindMeshBuffer();
1944    mRenderState.meshState().bindQuadIndicesBuffer();
1945    mRenderState.meshState().bindPositionVertexPointer(force, vertices, kVertexStride);
1946}
1947
1948///////////////////////////////////////////////////////////////////////////////
1949// Drawing
1950///////////////////////////////////////////////////////////////////////////////
1951
1952void OpenGLRenderer::drawRenderNode(RenderNode* renderNode, Rect& dirty, int32_t replayFlags) {
1953    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1954    // will be performed by the display list itself
1955    if (renderNode && renderNode->isRenderable()) {
1956        // compute 3d ordering
1957        renderNode->computeOrdering();
1958        if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
1959            startFrame();
1960            ReplayStateStruct replayStruct(*this, dirty, replayFlags);
1961            renderNode->replay(replayStruct, 0);
1962            return;
1963        }
1964
1965        // Don't avoid overdraw when visualizing, since that makes it harder to
1966        // debug where it's coming from, and when the problem occurs.
1967        bool avoidOverdraw = !mCaches.debugOverdraw;
1968        DeferredDisplayList deferredList(mState.currentClipRect(), avoidOverdraw);
1969        DeferStateStruct deferStruct(deferredList, *this, replayFlags);
1970        renderNode->defer(deferStruct, 0);
1971
1972        flushLayers();
1973        startFrame();
1974
1975        deferredList.flush(*this, dirty);
1976    } else {
1977        // Even if there is no drawing command(Ex: invisible),
1978        // it still needs startFrame to clear buffer and start tiling.
1979        startFrame();
1980    }
1981}
1982
1983void OpenGLRenderer::drawAlphaBitmap(Texture* texture, const SkPaint* paint) {
1984    float x = 0;
1985    float y = 0;
1986
1987    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1988
1989    bool ignoreTransform = false;
1990    if (currentTransform()->isPureTranslate()) {
1991        x = (int) floorf(currentTransform()->getTranslateX() + 0.5f);
1992        y = (int) floorf(currentTransform()->getTranslateY() + 0.5f);
1993        ignoreTransform = true;
1994
1995        texture->setFilter(GL_NEAREST, true);
1996    } else {
1997        texture->setFilter(PaintUtils::getFilter(paint), true);
1998    }
1999
2000    // No need to check for a UV mapper on the texture object, only ARGB_8888
2001    // bitmaps get packed in the atlas
2002    drawAlpha8TextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
2003            paint, (GLvoid*) nullptr, (GLvoid*) kMeshTextureOffset,
2004            GL_TRIANGLE_STRIP, kUnitQuadCount, ignoreTransform);
2005}
2006
2007/**
2008 * Important note: this method is intended to draw batches of bitmaps and
2009 * will not set the scissor enable or dirty the current layer, if any.
2010 * The caller is responsible for properly dirtying the current layer.
2011 */
2012void OpenGLRenderer::drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
2013        int bitmapCount, TextureVertex* vertices, bool pureTranslate,
2014        const Rect& bounds, const SkPaint* paint) {
2015    mCaches.textureState().activateTexture(0);
2016    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
2017    if (!texture) return;
2018
2019    const AutoTexture autoCleanup(texture);
2020
2021    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2022    texture->setFilter(pureTranslate ? GL_NEAREST : PaintUtils::getFilter(paint), true);
2023
2024    const float x = (int) floorf(bounds.left + 0.5f);
2025    const float y = (int) floorf(bounds.top + 0.5f);
2026    if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) {
2027        drawAlpha8TextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
2028                texture->id, paint, &vertices[0].x, &vertices[0].u,
2029                GL_TRIANGLES, bitmapCount * 6, true,
2030                kModelViewMode_Translate, false);
2031    } else {
2032        drawTextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
2033                texture->id, paint, texture->blend, &vertices[0].x, &vertices[0].u,
2034                GL_TRIANGLES, bitmapCount * 6, false, true, 0,
2035                kModelViewMode_Translate, false);
2036    }
2037
2038    mDirty = true;
2039}
2040
2041void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, const SkPaint* paint) {
2042    if (quickRejectSetupScissor(0, 0, bitmap->width(), bitmap->height())) {
2043        return;
2044    }
2045
2046    mCaches.textureState().activateTexture(0);
2047    Texture* texture = getTexture(bitmap);
2048    if (!texture) return;
2049    const AutoTexture autoCleanup(texture);
2050
2051    if (USE_GLOPS) {
2052        bool isAlpha8Texture = bitmap->colorType() == kAlpha_8_SkColorType;
2053        Glop glop;
2054        GlopBuilder aBuilder(mRenderState, mCaches, &glop);
2055        aBuilder.setMeshTexturedUnitQuad(texture->uvMapper)
2056                .setFillTexturePaint(*texture, isAlpha8Texture, paint, currentSnapshot()->alpha)
2057                .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false)
2058                .setModelViewMapUnitToRectSnap(Rect(0, 0, texture->width, texture->height))
2059                .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2060                .build();
2061        renderGlop(glop);
2062        return;
2063    }
2064
2065    if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) {
2066        drawAlphaBitmap(texture, paint);
2067    } else {
2068        drawTextureRect(texture, paint);
2069    }
2070
2071    mDirty = true;
2072}
2073
2074void OpenGLRenderer::drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight,
2075        const float* vertices, const int* colors, const SkPaint* paint) {
2076    if (!vertices || mState.currentlyIgnored()) {
2077        return;
2078    }
2079
2080    // TODO: use quickReject on bounds from vertices
2081    mRenderState.scissor().setEnabled(true);
2082
2083    float left = FLT_MAX;
2084    float top = FLT_MAX;
2085    float right = FLT_MIN;
2086    float bottom = FLT_MIN;
2087
2088    const uint32_t count = meshWidth * meshHeight * 6;
2089
2090    std::unique_ptr<ColorTextureVertex[]> mesh(new ColorTextureVertex[count]);
2091    ColorTextureVertex* vertex = &mesh[0];
2092
2093    std::unique_ptr<int[]> tempColors;
2094    if (!colors) {
2095        uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1);
2096        tempColors.reset(new int[colorsCount]);
2097        memset(tempColors.get(), 0xff, colorsCount * sizeof(int));
2098        colors = tempColors.get();
2099    }
2100
2101    mCaches.textureState().activateTexture(0);
2102    Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap);
2103    const UvMapper& mapper(getMapper(texture));
2104
2105    for (int32_t y = 0; y < meshHeight; y++) {
2106        for (int32_t x = 0; x < meshWidth; x++) {
2107            uint32_t i = (y * (meshWidth + 1) + x) * 2;
2108
2109            float u1 = float(x) / meshWidth;
2110            float u2 = float(x + 1) / meshWidth;
2111            float v1 = float(y) / meshHeight;
2112            float v2 = float(y + 1) / meshHeight;
2113
2114            mapper.map(u1, v1, u2, v2);
2115
2116            int ax = i + (meshWidth + 1) * 2;
2117            int ay = ax + 1;
2118            int bx = i;
2119            int by = bx + 1;
2120            int cx = i + 2;
2121            int cy = cx + 1;
2122            int dx = i + (meshWidth + 1) * 2 + 2;
2123            int dy = dx + 1;
2124
2125            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
2126            ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]);
2127            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
2128
2129            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
2130            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
2131            ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]);
2132
2133            left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
2134            top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
2135            right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
2136            bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
2137        }
2138    }
2139
2140    if (quickRejectSetupScissor(left, top, right, bottom)) {
2141        return;
2142    }
2143
2144    if (!texture) {
2145        texture = mCaches.textureCache.get(bitmap);
2146        if (!texture) {
2147            return;
2148        }
2149    }
2150    const AutoTexture autoCleanup(texture);
2151
2152    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2153    texture->setFilter(PaintUtils::getFilter(paint), true);
2154
2155    int alpha;
2156    SkXfermode::Mode mode;
2157    getAlphaAndMode(paint, &alpha, &mode);
2158
2159    float a = alpha / 255.0f;
2160
2161    if (hasLayer()) {
2162        dirtyLayer(left, top, right, bottom, *currentTransform());
2163    }
2164
2165    setupDraw();
2166    setupDrawWithTextureAndColor();
2167    setupDrawColor(a, a, a, a);
2168    setupDrawColorFilter(getColorFilter(paint));
2169    setupDrawBlending(paint, true);
2170    setupDrawProgram();
2171    setupDrawDirtyRegionsDisabled();
2172    setupDrawModelView(kModelViewMode_Translate, false, 0, 0, 0, 0);
2173    setupDrawTexture(texture->id);
2174    setupDrawPureColorUniforms();
2175    setupDrawColorFilterUniforms(getColorFilter(paint));
2176    setupDrawMesh(&mesh[0].x, &mesh[0].u, &mesh[0].r);
2177
2178    glDrawArrays(GL_TRIANGLES, 0, count);
2179
2180    int slot = mCaches.program().getAttrib("colors");
2181    if (slot >= 0) {
2182        glDisableVertexAttribArray(slot);
2183    }
2184
2185    mDirty = true;
2186}
2187
2188void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, Rect src, Rect dst, const SkPaint* paint) {
2189    if (quickRejectSetupScissor(dst)) {
2190        return;
2191    }
2192
2193    Texture* texture = getTexture(bitmap);
2194    if (!texture) return;
2195    const AutoTexture autoCleanup(texture);
2196
2197    if (USE_GLOPS) {
2198        Rect uv(fmax(0.0f, src.left / texture->width),
2199                fmax(0.0f, src.top / texture->height),
2200                fmin(1.0f, src.right / texture->width),
2201                fmin(1.0f, src.bottom / texture->height));
2202
2203        bool isAlpha8Texture = bitmap->colorType() == kAlpha_8_SkColorType;
2204        Glop glop;
2205        GlopBuilder aBuilder(mRenderState, mCaches, &glop);
2206        aBuilder.setMeshTexturedUvQuad(texture->uvMapper, uv)
2207                .setFillTexturePaint(*texture, isAlpha8Texture, paint, currentSnapshot()->alpha)
2208                .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false)
2209                .setModelViewMapUnitToRectSnap(dst)
2210                .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2211                .build();
2212        renderGlop(glop);
2213        return;
2214    }
2215
2216    mCaches.textureState().activateTexture(0);
2217
2218    const float width = texture->width;
2219    const float height = texture->height;
2220
2221    float u1 = fmax(0.0f, src.left / width);
2222    float v1 = fmax(0.0f, src.top / height);
2223    float u2 = fmin(1.0f, src.right / width);
2224    float v2 = fmin(1.0f, src.bottom / height);
2225
2226    getMapper(texture).map(u1, v1, u2, v2);
2227
2228    mRenderState.meshState().unbindMeshBuffer();
2229    resetDrawTextureTexCoords(u1, v1, u2, v2);
2230
2231    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2232
2233    float scaleX = (dst.right - dst.left) / (src.right - src.left);
2234    float scaleY = (dst.bottom - dst.top) / (src.bottom - src.top);
2235
2236    bool scaled = scaleX != 1.0f || scaleY != 1.0f;
2237    bool ignoreTransform = false;
2238
2239    if (CC_LIKELY(currentTransform()->isPureTranslate())) {
2240        float x = (int) floorf(dst.left + currentTransform()->getTranslateX() + 0.5f);
2241        float y = (int) floorf(dst.top + currentTransform()->getTranslateY() + 0.5f);
2242
2243        dst.right = x + (dst.right - dst.left);
2244        dst.bottom = y + (dst.bottom - dst.top);
2245
2246        dst.left = x;
2247        dst.top = y;
2248
2249        texture->setFilter(scaled ? PaintUtils::getFilter(paint) : GL_NEAREST, true);
2250        ignoreTransform = true;
2251    } else {
2252        texture->setFilter(PaintUtils::getFilter(paint), true);
2253    }
2254
2255    if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) {
2256        drawAlpha8TextureMesh(dst.left, dst.top, dst.right, dst.bottom,
2257                texture->id, paint,
2258                &mMeshVertices[0].x, &mMeshVertices[0].u,
2259                GL_TRIANGLE_STRIP, kUnitQuadCount, ignoreTransform);
2260    } else {
2261        drawTextureMesh(dst.left, dst.top, dst.right, dst.bottom,
2262                texture->id, paint, texture->blend,
2263                &mMeshVertices[0].x, &mMeshVertices[0].u,
2264                GL_TRIANGLE_STRIP, kUnitQuadCount, false, ignoreTransform);
2265    }
2266
2267    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
2268
2269    mDirty = true;
2270}
2271
2272void OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Res_png_9patch* patch,
2273        float left, float top, float right, float bottom, const SkPaint* paint) {
2274    if (quickRejectSetupScissor(left, top, right, bottom)) {
2275        return;
2276    }
2277
2278    AssetAtlas::Entry* entry = mRenderState.assetAtlas().getEntry(bitmap);
2279    const Patch* mesh = mCaches.patchCache.get(entry, bitmap->width(), bitmap->height(),
2280            right - left, bottom - top, patch);
2281
2282    drawPatch(bitmap, mesh, entry, left, top, right, bottom, paint);
2283}
2284
2285void OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Patch* mesh,
2286        AssetAtlas::Entry* entry, float left, float top, float right, float bottom,
2287        const SkPaint* paint) {
2288    if (quickRejectSetupScissor(left, top, right, bottom)) {
2289        return;
2290    }
2291
2292    if (CC_LIKELY(mesh && mesh->verticesCount > 0)) {
2293        mCaches.textureState().activateTexture(0);
2294        Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
2295        if (!texture) return;
2296        const AutoTexture autoCleanup(texture);
2297
2298        texture->setWrap(GL_CLAMP_TO_EDGE, true);
2299        texture->setFilter(GL_LINEAR, true);
2300
2301        const bool pureTranslate = currentTransform()->isPureTranslate();
2302        // Mark the current layer dirty where we are going to draw the patch
2303        if (hasLayer() && mesh->hasEmptyQuads) {
2304            const float offsetX = left + currentTransform()->getTranslateX();
2305            const float offsetY = top + currentTransform()->getTranslateY();
2306            const size_t count = mesh->quads.size();
2307            for (size_t i = 0; i < count; i++) {
2308                const Rect& bounds = mesh->quads.itemAt(i);
2309                if (CC_LIKELY(pureTranslate)) {
2310                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
2311                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
2312                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
2313                } else {
2314                    dirtyLayer(left + bounds.left, top + bounds.top,
2315                            left + bounds.right, top + bounds.bottom, *currentTransform());
2316                }
2317            }
2318        }
2319
2320        bool ignoreTransform = false;
2321        if (CC_LIKELY(pureTranslate)) {
2322            const float x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f);
2323            const float y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f);
2324
2325            right = x + right - left;
2326            bottom = y + bottom - top;
2327            left = x;
2328            top = y;
2329            ignoreTransform = true;
2330        }
2331        drawIndexedTextureMesh(left, top, right, bottom, texture->id, paint,
2332                texture->blend, (GLvoid*) mesh->offset, (GLvoid*) mesh->textureOffset,
2333                GL_TRIANGLES, mesh->indexCount, false, ignoreTransform,
2334                mCaches.patchCache.getMeshBuffer(), kModelViewMode_Translate, !mesh->hasEmptyQuads);
2335    }
2336
2337    mDirty = true;
2338}
2339
2340/**
2341 * Important note: this method is intended to draw batches of 9-patch objects and
2342 * will not set the scissor enable or dirty the current layer, if any.
2343 * The caller is responsible for properly dirtying the current layer.
2344 */
2345void OpenGLRenderer::drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
2346        TextureVertex* vertices, uint32_t indexCount, const SkPaint* paint) {
2347    mCaches.textureState().activateTexture(0);
2348    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
2349    if (!texture) return;
2350    const AutoTexture autoCleanup(texture);
2351
2352    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2353    texture->setFilter(GL_LINEAR, true);
2354
2355    drawIndexedTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, paint,
2356            texture->blend, &vertices[0].x, &vertices[0].u,
2357            GL_TRIANGLES, indexCount, false, true, 0, kModelViewMode_Translate, false);
2358
2359    mDirty = true;
2360}
2361
2362void OpenGLRenderer::drawVertexBuffer(float translateX, float translateY,
2363        const VertexBuffer& vertexBuffer, const SkPaint* paint, int displayFlags) {
2364    // not missing call to quickReject/dirtyLayer, always done at a higher level
2365    if (!vertexBuffer.getVertexCount()) {
2366        // no vertices to draw
2367        return;
2368    }
2369
2370    if (USE_GLOPS) {
2371        Glop glop;
2372        GlopBuilder aBuilder(mRenderState, mCaches, &glop);
2373        bool fudgeOffset = displayFlags & kVertexBuffer_Offset;
2374        bool shadowInterp = displayFlags & kVertexBuffer_ShadowInterp;
2375        aBuilder.setMeshVertexBuffer(vertexBuffer, shadowInterp)
2376                .setFillPaint(*paint, currentSnapshot()->alpha)
2377                .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), fudgeOffset)
2378                .setModelViewOffsetRect(translateX, translateY, vertexBuffer.getBounds())
2379                .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2380                .build();
2381        renderGlop(glop);
2382        return;
2383    }
2384
2385    const VertexBuffer::MeshFeatureFlags meshFeatureFlags = vertexBuffer.getMeshFeatureFlags();
2386    Rect bounds(vertexBuffer.getBounds());
2387    bounds.translate(translateX, translateY);
2388    dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, *currentTransform());
2389
2390    int color = paint->getColor();
2391    bool isAA = meshFeatureFlags & VertexBuffer::kAlpha;
2392
2393    setupDraw();
2394    setupDrawNoTexture();
2395    if (isAA) setupDrawVertexAlpha((displayFlags & kVertexBuffer_ShadowInterp));
2396    setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha);
2397    setupDrawColorFilter(getColorFilter(paint));
2398    setupDrawShader(getShader(paint));
2399    setupDrawBlending(paint, isAA);
2400    setupDrawProgram();
2401    setupDrawModelView(kModelViewMode_Translate, (displayFlags & kVertexBuffer_Offset),
2402            translateX, translateY, 0, 0);
2403    setupDrawColorUniforms(getShader(paint));
2404    setupDrawColorFilterUniforms(getColorFilter(paint));
2405    setupDrawShaderUniforms(getShader(paint));
2406
2407    const void* vertices = vertexBuffer.getBuffer();
2408    mRenderState.meshState().unbindMeshBuffer();
2409    mRenderState.meshState().bindPositionVertexPointer(true, vertices,
2410            isAA ? kAlphaVertexStride : kVertexStride);
2411    mRenderState.meshState().resetTexCoordsVertexPointer();
2412
2413    int alphaSlot = -1;
2414    if (isAA) {
2415        void* alphaCoords = ((GLbyte*) vertices) + kVertexAlphaOffset;
2416        alphaSlot = mCaches.program().getAttrib("vtxAlpha");
2417        // TODO: avoid enable/disable in back to back uses of the alpha attribute
2418        glEnableVertexAttribArray(alphaSlot);
2419        glVertexAttribPointer(alphaSlot, 1, GL_FLOAT, GL_FALSE, kAlphaVertexStride, alphaCoords);
2420    }
2421
2422    if (meshFeatureFlags & VertexBuffer::kIndices) {
2423        mRenderState.meshState().unbindIndicesBuffer();
2424        glDrawElements(GL_TRIANGLE_STRIP, vertexBuffer.getIndexCount(),
2425                GL_UNSIGNED_SHORT, vertexBuffer.getIndices());
2426    } else {
2427        mRenderState.meshState().unbindIndicesBuffer();
2428        glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexBuffer.getVertexCount());
2429    }
2430
2431    if (isAA) {
2432        glDisableVertexAttribArray(alphaSlot);
2433    }
2434
2435    mDirty = true;
2436}
2437
2438/**
2439 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to
2440 * that of AA lines in the drawLines() function.  We expand the convex path by a half pixel in
2441 * screen space in all directions. However, instead of using a fragment shader to compute the
2442 * translucency of the color from its position, we simply use a varying parameter to define how far
2443 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used.
2444 *
2445 * Doesn't yet support joins, caps, or path effects.
2446 */
2447void OpenGLRenderer::drawConvexPath(const SkPath& path, const SkPaint* paint) {
2448    VertexBuffer vertexBuffer;
2449    // TODO: try clipping large paths to viewport
2450    PathTessellator::tessellatePath(path, paint, *currentTransform(), vertexBuffer);
2451    drawVertexBuffer(vertexBuffer, paint);
2452}
2453
2454/**
2455 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha
2456 * and additional geometry for defining an alpha slope perimeter.
2457 *
2458 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some
2459 * unexpected results, and may vary between hardware devices. Previously we used a varying-base
2460 * in-shader alpha region, but found it to be taxing on some GPUs.
2461 *
2462 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce
2463 * memory transfer by removing need for degenerate vertices.
2464 */
2465void OpenGLRenderer::drawLines(const float* points, int count, const SkPaint* paint) {
2466    if (mState.currentlyIgnored() || count < 4) return;
2467
2468    count &= ~0x3; // round down to nearest four
2469
2470    VertexBuffer buffer;
2471    PathTessellator::tessellateLines(points, count, paint, *currentTransform(), buffer);
2472    const Rect& bounds = buffer.getBounds();
2473
2474    if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) {
2475        return;
2476    }
2477
2478    int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset;
2479    drawVertexBuffer(buffer, paint, displayFlags);
2480}
2481
2482void OpenGLRenderer::drawPoints(const float* points, int count, const SkPaint* paint) {
2483    if (mState.currentlyIgnored() || count < 2) return;
2484
2485    count &= ~0x1; // round down to nearest two
2486
2487    VertexBuffer buffer;
2488    PathTessellator::tessellatePoints(points, count, paint, *currentTransform(), buffer);
2489
2490    const Rect& bounds = buffer.getBounds();
2491    if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) {
2492        return;
2493    }
2494
2495    int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset;
2496    drawVertexBuffer(buffer, paint, displayFlags);
2497
2498    mDirty = true;
2499}
2500
2501void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
2502    // No need to check against the clip, we fill the clip region
2503    if (mState.currentlyIgnored()) return;
2504
2505    Rect clip(mState.currentClipRect());
2506    clip.snapToPixelBoundaries();
2507
2508    SkPaint paint;
2509    paint.setColor(color);
2510    paint.setXfermodeMode(mode);
2511
2512    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, &paint, true);
2513
2514    mDirty = true;
2515}
2516
2517void OpenGLRenderer::drawShape(float left, float top, PathTexture* texture,
2518        const SkPaint* paint) {
2519    if (!texture) return;
2520    const AutoTexture autoCleanup(texture);
2521
2522    const float x = left + texture->left - texture->offset;
2523    const float y = top + texture->top - texture->offset;
2524
2525    drawPathTexture(texture, x, y, paint);
2526
2527    mDirty = true;
2528}
2529
2530void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
2531        float rx, float ry, const SkPaint* p) {
2532    if (mState.currentlyIgnored()
2533            || quickRejectSetupScissor(left, top, right, bottom, p)
2534            || PaintUtils::paintWillNotDraw(*p)) {
2535        return;
2536    }
2537
2538    if (p->getPathEffect() != nullptr) {
2539        mCaches.textureState().activateTexture(0);
2540        PathTexture* texture = mCaches.pathCache.getRoundRect(
2541                right - left, bottom - top, rx, ry, p);
2542        drawShape(left, top, texture, p);
2543    } else {
2544        const VertexBuffer* vertexBuffer = mCaches.tessellationCache.getRoundRect(
2545                *currentTransform(), *p, right - left, bottom - top, rx, ry);
2546        drawVertexBuffer(left, top, *vertexBuffer, p);
2547    }
2548}
2549
2550void OpenGLRenderer::drawCircle(float x, float y, float radius, const SkPaint* p) {
2551    if (mState.currentlyIgnored()
2552            || quickRejectSetupScissor(x - radius, y - radius, x + radius, y + radius, p)
2553            || PaintUtils::paintWillNotDraw(*p)) {
2554        return;
2555    }
2556    if (p->getPathEffect() != nullptr) {
2557        mCaches.textureState().activateTexture(0);
2558        PathTexture* texture = mCaches.pathCache.getCircle(radius, p);
2559        drawShape(x - radius, y - radius, texture, p);
2560    } else {
2561        SkPath path;
2562        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2563            path.addCircle(x, y, radius + p->getStrokeWidth() / 2);
2564        } else {
2565            path.addCircle(x, y, radius);
2566        }
2567        drawConvexPath(path, p);
2568    }
2569}
2570
2571void OpenGLRenderer::drawOval(float left, float top, float right, float bottom,
2572        const SkPaint* p) {
2573    if (mState.currentlyIgnored()
2574            || quickRejectSetupScissor(left, top, right, bottom, p)
2575            || PaintUtils::paintWillNotDraw(*p)) {
2576        return;
2577    }
2578
2579    if (p->getPathEffect() != nullptr) {
2580        mCaches.textureState().activateTexture(0);
2581        PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p);
2582        drawShape(left, top, texture, p);
2583    } else {
2584        SkPath path;
2585        SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2586        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2587            rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2588        }
2589        path.addOval(rect);
2590        drawConvexPath(path, p);
2591    }
2592}
2593
2594void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
2595        float startAngle, float sweepAngle, bool useCenter, const SkPaint* p) {
2596    if (mState.currentlyIgnored()
2597            || quickRejectSetupScissor(left, top, right, bottom, p)
2598            || PaintUtils::paintWillNotDraw(*p)) {
2599        return;
2600    }
2601
2602    // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180)
2603    if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != nullptr || useCenter) {
2604        mCaches.textureState().activateTexture(0);
2605        PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top,
2606                startAngle, sweepAngle, useCenter, p);
2607        drawShape(left, top, texture, p);
2608        return;
2609    }
2610    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2611    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2612        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2613    }
2614
2615    SkPath path;
2616    if (useCenter) {
2617        path.moveTo(rect.centerX(), rect.centerY());
2618    }
2619    path.arcTo(rect, startAngle, sweepAngle, !useCenter);
2620    if (useCenter) {
2621        path.close();
2622    }
2623    drawConvexPath(path, p);
2624}
2625
2626// See SkPaintDefaults.h
2627#define SkPaintDefaults_MiterLimit SkIntToScalar(4)
2628
2629void OpenGLRenderer::drawRect(float left, float top, float right, float bottom,
2630        const SkPaint* p) {
2631    if (mState.currentlyIgnored()
2632            || quickRejectSetupScissor(left, top, right, bottom, p)
2633            || PaintUtils::paintWillNotDraw(*p)) {
2634        return;
2635    }
2636
2637    if (p->getStyle() != SkPaint::kFill_Style) {
2638        // only fill style is supported by drawConvexPath, since others have to handle joins
2639        if (p->getPathEffect() != nullptr || p->getStrokeJoin() != SkPaint::kMiter_Join ||
2640                p->getStrokeMiter() != SkPaintDefaults_MiterLimit) {
2641            mCaches.textureState().activateTexture(0);
2642            PathTexture* texture =
2643                    mCaches.pathCache.getRect(right - left, bottom - top, p);
2644            drawShape(left, top, texture, p);
2645        } else {
2646            SkPath path;
2647            SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2648            if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2649                rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2650            }
2651            path.addRect(rect);
2652            drawConvexPath(path, p);
2653        }
2654    } else {
2655        if (p->isAntiAlias() && !currentTransform()->isSimple()) {
2656            SkPath path;
2657            path.addRect(left, top, right, bottom);
2658            drawConvexPath(path, p);
2659        } else {
2660            drawColorRect(left, top, right, bottom, p);
2661
2662            mDirty = true;
2663        }
2664    }
2665}
2666
2667void OpenGLRenderer::drawTextShadow(const SkPaint* paint, const char* text,
2668        int bytesCount, int count, const float* positions,
2669        FontRenderer& fontRenderer, int alpha, float x, float y) {
2670    mCaches.textureState().activateTexture(0);
2671
2672    TextShadow textShadow;
2673    if (!getTextShadow(paint, &textShadow)) {
2674        LOG_ALWAYS_FATAL("failed to query shadow attributes");
2675    }
2676
2677    // NOTE: The drop shadow will not perform gamma correction
2678    //       if shader-based correction is enabled
2679    mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2680    ShadowTexture* texture = mCaches.dropShadowCache.get(
2681            paint, text, bytesCount, count, textShadow.radius, positions);
2682    // If the drop shadow exceeds the max texture size or couldn't be
2683    // allocated, skip drawing
2684    if (!texture) return;
2685    const AutoTexture autoCleanup(texture);
2686
2687    const float sx = x - texture->left + textShadow.dx;
2688    const float sy = y - texture->top + textShadow.dy;
2689
2690    if (USE_GLOPS) {
2691        Glop glop;
2692        GlopBuilder aBuilder(mRenderState, mCaches, &glop);
2693        aBuilder.setMeshTexturedUnitQuad(nullptr)
2694                .setFillShadowTexturePaint(*texture, textShadow.color, *paint, currentSnapshot()->alpha)
2695                .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false)
2696                .setModelViewMapUnitToRect(Rect(sx, sy, sx + texture->width, sy + texture->height))
2697                .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2698                .build();
2699        renderGlop(glop);
2700        return;
2701    }
2702
2703    const int shadowAlpha = ((textShadow.color >> 24) & 0xFF) * currentSnapshot()->alpha;
2704    if (getShader(paint)) {
2705        textShadow.color = SK_ColorWHITE;
2706    }
2707
2708    setupDraw();
2709    setupDrawWithTexture(true);
2710    setupDrawAlpha8Color(textShadow.color, shadowAlpha < 255 ? shadowAlpha : alpha);
2711    setupDrawColorFilter(getColorFilter(paint));
2712    setupDrawShader(getShader(paint));
2713    setupDrawBlending(paint, true);
2714    setupDrawProgram();
2715    setupDrawModelView(kModelViewMode_TranslateAndScale, false,
2716            sx, sy, sx + texture->width, sy + texture->height);
2717    setupDrawTexture(texture->id);
2718    setupDrawPureColorUniforms();
2719    setupDrawColorFilterUniforms(getColorFilter(paint));
2720    setupDrawShaderUniforms(getShader(paint));
2721    setupDrawMesh(nullptr, (GLvoid*) kMeshTextureOffset);
2722
2723    glDrawArrays(GL_TRIANGLE_STRIP, 0, kUnitQuadCount);
2724}
2725
2726bool OpenGLRenderer::canSkipText(const SkPaint* paint) const {
2727    float alpha = (hasTextShadow(paint) ? 1.0f : paint->getAlpha()) * currentSnapshot()->alpha;
2728    return MathUtils::isZero(alpha)
2729            && PaintUtils::getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode;
2730}
2731
2732void OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count,
2733        const float* positions, const SkPaint* paint) {
2734    if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) {
2735        return;
2736    }
2737
2738    // NOTE: Skia does not support perspective transform on drawPosText yet
2739    if (!currentTransform()->isSimple()) {
2740        return;
2741    }
2742
2743    mRenderState.scissor().setEnabled(true);
2744
2745    float x = 0.0f;
2746    float y = 0.0f;
2747    const bool pureTranslate = currentTransform()->isPureTranslate();
2748    if (pureTranslate) {
2749        x = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f);
2750        y = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f);
2751    }
2752
2753    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2754    fontRenderer.setFont(paint, SkMatrix::I());
2755
2756    int alpha;
2757    SkXfermode::Mode mode;
2758    getAlphaAndMode(paint, &alpha, &mode);
2759
2760    if (CC_UNLIKELY(hasTextShadow(paint))) {
2761        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2762                alpha, 0.0f, 0.0f);
2763    }
2764
2765    // Pick the appropriate texture filtering
2766    bool linearFilter = currentTransform()->changesBounds();
2767    if (pureTranslate && !linearFilter) {
2768        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2769    }
2770    fontRenderer.setTextureFiltering(linearFilter);
2771
2772    const Rect& clip(pureTranslate ? writableSnapshot()->getClipRect() : writableSnapshot()->getLocalClip());
2773    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2774
2775    const bool hasActiveLayer = hasLayer();
2776
2777    TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2778    if (fontRenderer.renderPosText(paint, &clip, text, 0, bytesCount, count, x, y,
2779            positions, hasActiveLayer ? &bounds : nullptr, &functor)) {
2780        if (hasActiveLayer) {
2781            if (!pureTranslate) {
2782                currentTransform()->mapRect(bounds);
2783            }
2784            dirtyLayerUnchecked(bounds, getRegion());
2785        }
2786    }
2787
2788    mDirty = true;
2789}
2790
2791bool OpenGLRenderer::findBestFontTransform(const mat4& transform, SkMatrix* outMatrix) const {
2792    if (CC_LIKELY(transform.isPureTranslate())) {
2793        outMatrix->setIdentity();
2794        return false;
2795    } else if (CC_UNLIKELY(transform.isPerspective())) {
2796        outMatrix->setIdentity();
2797        return true;
2798    }
2799
2800    /**
2801     * Input is a non-perspective, scaling transform. Generate a scale-only transform,
2802     * with values rounded to the nearest int.
2803     */
2804    float sx, sy;
2805    transform.decomposeScale(sx, sy);
2806    outMatrix->setScale(
2807            roundf(fmaxf(1.0f, sx)),
2808            roundf(fmaxf(1.0f, sy)));
2809    return true;
2810}
2811
2812int OpenGLRenderer::getSaveCount() const {
2813    return mState.getSaveCount();
2814}
2815
2816int OpenGLRenderer::save(int flags) {
2817    return mState.save(flags);
2818}
2819
2820void OpenGLRenderer::restore() {
2821    return mState.restore();
2822}
2823
2824void OpenGLRenderer::restoreToCount(int saveCount) {
2825    return mState.restoreToCount(saveCount);
2826}
2827
2828void OpenGLRenderer::translate(float dx, float dy, float dz) {
2829    return mState.translate(dx, dy, dz);
2830}
2831
2832void OpenGLRenderer::rotate(float degrees) {
2833    return mState.rotate(degrees);
2834}
2835
2836void OpenGLRenderer::scale(float sx, float sy) {
2837    return mState.scale(sx, sy);
2838}
2839
2840void OpenGLRenderer::skew(float sx, float sy) {
2841    return mState.skew(sx, sy);
2842}
2843
2844void OpenGLRenderer::setMatrix(const Matrix4& matrix) {
2845    mState.setMatrix(matrix);
2846}
2847
2848void OpenGLRenderer::concatMatrix(const Matrix4& matrix) {
2849    mState.concatMatrix(matrix);
2850}
2851
2852bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
2853    return mState.clipRect(left, top, right, bottom, op);
2854}
2855
2856bool OpenGLRenderer::clipPath(const SkPath* path, SkRegion::Op op) {
2857    return mState.clipPath(path, op);
2858}
2859
2860bool OpenGLRenderer::clipRegion(const SkRegion* region, SkRegion::Op op) {
2861    return mState.clipRegion(region, op);
2862}
2863
2864void OpenGLRenderer::setClippingOutline(LinearAllocator& allocator, const Outline* outline) {
2865    mState.setClippingOutline(allocator, outline);
2866}
2867
2868void OpenGLRenderer::setClippingRoundRect(LinearAllocator& allocator,
2869        const Rect& rect, float radius, bool highPriority) {
2870    mState.setClippingRoundRect(allocator, rect, radius, highPriority);
2871}
2872
2873void OpenGLRenderer::drawText(const char* text, int bytesCount, int count, float x, float y,
2874        const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds,
2875        DrawOpMode drawOpMode) {
2876
2877    if (drawOpMode == DrawOpMode::kImmediate) {
2878        // The checks for corner-case ignorable text and quick rejection is only done for immediate
2879        // drawing as ops from DeferredDisplayList are already filtered for these
2880        if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint) ||
2881                quickRejectSetupScissor(bounds)) {
2882            return;
2883        }
2884    }
2885
2886    const float oldX = x;
2887    const float oldY = y;
2888
2889    const mat4& transform = *currentTransform();
2890    const bool pureTranslate = transform.isPureTranslate();
2891
2892    if (CC_LIKELY(pureTranslate)) {
2893        x = (int) floorf(x + transform.getTranslateX() + 0.5f);
2894        y = (int) floorf(y + transform.getTranslateY() + 0.5f);
2895    }
2896
2897    int alpha;
2898    SkXfermode::Mode mode;
2899    getAlphaAndMode(paint, &alpha, &mode);
2900
2901    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2902
2903    if (CC_UNLIKELY(hasTextShadow(paint))) {
2904        fontRenderer.setFont(paint, SkMatrix::I());
2905        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2906                alpha, oldX, oldY);
2907    }
2908
2909    const bool hasActiveLayer = hasLayer();
2910
2911    // We only pass a partial transform to the font renderer. That partial
2912    // matrix defines how glyphs are rasterized. Typically we want glyphs
2913    // to be rasterized at their final size on screen, which means the partial
2914    // matrix needs to take the scale factor into account.
2915    // When a partial matrix is used to transform glyphs during rasterization,
2916    // the mesh is generated with the inverse transform (in the case of scale,
2917    // the mesh is generated at 1.0 / scale for instance.) This allows us to
2918    // apply the full transform matrix at draw time in the vertex shader.
2919    // Applying the full matrix in the shader is the easiest way to handle
2920    // rotation and perspective and allows us to always generated quads in the
2921    // font renderer which greatly simplifies the code, clipping in particular.
2922    SkMatrix fontTransform;
2923    bool linearFilter = findBestFontTransform(transform, &fontTransform)
2924            || fabs(y - (int) y) > 0.0f
2925            || fabs(x - (int) x) > 0.0f;
2926    fontRenderer.setFont(paint, fontTransform);
2927    fontRenderer.setTextureFiltering(linearFilter);
2928
2929    // TODO: Implement better clipping for scaled/rotated text
2930    const Rect* clip = !pureTranslate ? nullptr : &mState.currentClipRect();
2931    Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2932
2933    bool status;
2934    TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2935
2936    // don't call issuedrawcommand, do it at end of batch
2937    bool forceFinish = (drawOpMode != DrawOpMode::kDefer);
2938    if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) {
2939        SkPaint paintCopy(*paint);
2940        paintCopy.setTextAlign(SkPaint::kLeft_Align);
2941        status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y,
2942                positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish);
2943    } else {
2944        status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2945                positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish);
2946    }
2947
2948    if ((status || drawOpMode != DrawOpMode::kImmediate) && hasActiveLayer) {
2949        if (!pureTranslate) {
2950            transform.mapRect(layerBounds);
2951        }
2952        dirtyLayerUnchecked(layerBounds, getRegion());
2953    }
2954
2955    drawTextDecorations(totalAdvance, oldX, oldY, paint);
2956
2957    mDirty = true;
2958}
2959
2960void OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count,
2961        const SkPath* path, float hOffset, float vOffset, const SkPaint* paint) {
2962    if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) {
2963        return;
2964    }
2965
2966    // TODO: avoid scissor by calculating maximum bounds using path bounds + font metrics
2967    mRenderState.scissor().setEnabled(true);
2968
2969    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2970    fontRenderer.setFont(paint, SkMatrix::I());
2971    fontRenderer.setTextureFiltering(true);
2972
2973    int alpha;
2974    SkXfermode::Mode mode;
2975    getAlphaAndMode(paint, &alpha, &mode);
2976    TextSetupFunctor functor(this, 0.0f, 0.0f, false, alpha, mode, paint);
2977
2978    const Rect* clip = &writableSnapshot()->getLocalClip();
2979    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2980
2981    const bool hasActiveLayer = hasLayer();
2982
2983    if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path,
2984            hOffset, vOffset, hasActiveLayer ? &bounds : nullptr, &functor)) {
2985        if (hasActiveLayer) {
2986            currentTransform()->mapRect(bounds);
2987            dirtyLayerUnchecked(bounds, getRegion());
2988        }
2989    }
2990
2991    mDirty = true;
2992}
2993
2994void OpenGLRenderer::drawPath(const SkPath* path, const SkPaint* paint) {
2995    if (mState.currentlyIgnored()) return;
2996
2997    mCaches.textureState().activateTexture(0);
2998
2999    PathTexture* texture = mCaches.pathCache.get(path, paint);
3000    if (!texture) return;
3001    const AutoTexture autoCleanup(texture);
3002
3003    const float x = texture->left - texture->offset;
3004    const float y = texture->top - texture->offset;
3005
3006    drawPathTexture(texture, x, y, paint);
3007    mDirty = true;
3008}
3009
3010void OpenGLRenderer::drawLayer(Layer* layer, float x, float y) {
3011    if (!layer) {
3012        return;
3013    }
3014
3015    mat4* transform = nullptr;
3016    if (layer->isTextureLayer()) {
3017        transform = &layer->getTransform();
3018        if (!transform->isIdentity()) {
3019            save(SkCanvas::kMatrix_SaveFlag);
3020            concatMatrix(*transform);
3021        }
3022    }
3023
3024    bool clipRequired = false;
3025    const bool rejected = mState.calculateQuickRejectForScissor(
3026            x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(),
3027            &clipRequired, nullptr, false);
3028
3029    if (rejected) {
3030        if (transform && !transform->isIdentity()) {
3031            restore();
3032        }
3033        return;
3034    }
3035
3036    EVENT_LOGD("drawLayer," RECT_STRING ", clipRequired %d", x, y,
3037            x + layer->layer.getWidth(), y + layer->layer.getHeight(), clipRequired);
3038
3039    updateLayer(layer, true);
3040
3041    mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
3042    mCaches.textureState().activateTexture(0);
3043
3044    if (CC_LIKELY(!layer->region.isEmpty())) {
3045        if (layer->region.isRect()) {
3046            DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
3047                    composeLayerRect(layer, layer->regionRect));
3048        } else if (layer->mesh) {
3049            if (USE_GLOPS) {
3050                Glop glop;
3051                GlopBuilder aBuilder(mRenderState, mCaches, &glop);
3052                aBuilder.setMeshTexturedIndexedQuads(layer->mesh, layer->meshElementCount)
3053                        .setFillLayer(layer->getTexture(), layer->getColorFilter(), getLayerAlpha(layer), layer->getMode())
3054                        .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false)
3055                        .setModelViewOffsetRectSnap(x, y, Rect(0, 0, layer->layer.getWidth(), layer->layer.getHeight()))
3056                        .setRoundRectClipState(currentSnapshot()->roundRectClipState)
3057                        .build();
3058                DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, renderGlop(glop));
3059            } else {
3060                const float a = getLayerAlpha(layer);
3061                setupDraw();
3062                setupDrawWithTexture();
3063                setupDrawColor(a, a, a, a);
3064                setupDrawColorFilter(layer->getColorFilter());
3065                setupDrawBlending(layer);
3066                setupDrawProgram();
3067                setupDrawPureColorUniforms();
3068                setupDrawColorFilterUniforms(layer->getColorFilter());
3069                setupDrawTexture(layer->getTextureId());
3070                if (CC_LIKELY(currentTransform()->isPureTranslate())) {
3071                    int tx = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f);
3072                    int ty = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f);
3073
3074                    layer->setFilter(GL_NEAREST);
3075                    setupDrawModelView(kModelViewMode_Translate, false, tx, ty,
3076                            tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true);
3077                } else {
3078                    layer->setFilter(GL_LINEAR);
3079                    setupDrawModelView(kModelViewMode_Translate, false, x, y,
3080                            x + layer->layer.getWidth(), y + layer->layer.getHeight());
3081                }
3082
3083
3084                TextureVertex* mesh = &layer->mesh[0];
3085                GLsizei elementsCount = layer->meshElementCount;
3086
3087
3088                while (elementsCount > 0) {
3089                    GLsizei drawCount = MathUtils::min(elementsCount, (GLsizei) kMaxNumberOfQuads * 6);
3090
3091                    setupDrawMeshIndices(&mesh[0].x, &mesh[0].u);
3092                    DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
3093                            glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, nullptr));
3094
3095                    elementsCount -= drawCount;
3096                    // Though there are 4 vertices in a quad, we use 6 indices per
3097                    // quad to draw with GL_TRIANGLES
3098                    mesh += (drawCount / 6) * 4;
3099                }
3100            }
3101#if DEBUG_LAYERS_AS_REGIONS
3102            drawRegionRectsDebug(layer->region);
3103#endif
3104        }
3105
3106        if (layer->debugDrawUpdate) {
3107            layer->debugDrawUpdate = false;
3108
3109            SkPaint paint;
3110            paint.setColor(0x7f00ff00);
3111            drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(), &paint);
3112        }
3113    }
3114    layer->hasDrawnSinceUpdate = true;
3115
3116    if (transform && !transform->isIdentity()) {
3117        restore();
3118    }
3119
3120    mDirty = true;
3121}
3122
3123///////////////////////////////////////////////////////////////////////////////
3124// Draw filters
3125///////////////////////////////////////////////////////////////////////////////
3126void OpenGLRenderer::setDrawFilter(SkDrawFilter* filter) {
3127    // We should never get here since we apply the draw filter when stashing
3128    // the paints in the DisplayList.
3129    LOG_ALWAYS_FATAL("OpenGLRenderer does not directly support DrawFilters");
3130}
3131
3132///////////////////////////////////////////////////////////////////////////////
3133// Drawing implementation
3134///////////////////////////////////////////////////////////////////////////////
3135
3136Texture* OpenGLRenderer::getTexture(const SkBitmap* bitmap) {
3137    Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap);
3138    if (!texture) {
3139        return mCaches.textureCache.get(bitmap);
3140    }
3141    return texture;
3142}
3143
3144void OpenGLRenderer::drawPathTexture(PathTexture* texture, float x, float y,
3145        const SkPaint* paint) {
3146    if (quickRejectSetupScissor(x, y, x + texture->width, y + texture->height)) {
3147        return;
3148    }
3149
3150    if (USE_GLOPS) {
3151        Glop glop;
3152        GlopBuilder aBuilder(mRenderState, mCaches, &glop);
3153        aBuilder.setMeshTexturedUnitQuad(nullptr)
3154                .setFillPathTexturePaint(*texture, *paint, currentSnapshot()->alpha)
3155                .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false)
3156                .setModelViewMapUnitToRect(Rect(x, y, x + texture->width, y + texture->height))
3157                .setRoundRectClipState(currentSnapshot()->roundRectClipState)
3158                .build();
3159        renderGlop(glop);
3160        return;
3161    }
3162
3163
3164    int alpha;
3165    SkXfermode::Mode mode;
3166    getAlphaAndMode(paint, &alpha, &mode);
3167
3168    setupDraw();
3169    setupDrawWithTexture(true);
3170    setupDrawAlpha8Color(paint->getColor(), alpha);
3171    setupDrawColorFilter(getColorFilter(paint));
3172    setupDrawShader(getShader(paint));
3173    setupDrawBlending(paint, true);
3174    setupDrawProgram();
3175    setupDrawModelView(kModelViewMode_TranslateAndScale, false,
3176            x, y, x + texture->width, y + texture->height);
3177    setupDrawTexture(texture->id);
3178    setupDrawPureColorUniforms();
3179    setupDrawColorFilterUniforms(getColorFilter(paint));
3180    setupDrawShaderUniforms(getShader(paint));
3181    setupDrawMesh(nullptr, (GLvoid*) kMeshTextureOffset);
3182
3183    glDrawArrays(GL_TRIANGLE_STRIP, 0, kUnitQuadCount);
3184}
3185
3186// Same values used by Skia
3187#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
3188#define kStdUnderline_Offset    (1.0f / 9.0f)
3189#define kStdUnderline_Thickness (1.0f / 18.0f)
3190
3191void OpenGLRenderer::drawTextDecorations(float underlineWidth, float x, float y,
3192        const SkPaint* paint) {
3193    // Handle underline and strike-through
3194    uint32_t flags = paint->getFlags();
3195    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
3196        SkPaint paintCopy(*paint);
3197
3198        if (CC_LIKELY(underlineWidth > 0.0f)) {
3199            const float textSize = paintCopy.getTextSize();
3200            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
3201
3202            const float left = x;
3203            float top = 0.0f;
3204
3205            int linesCount = 0;
3206            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
3207            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
3208
3209            const int pointsCount = 4 * linesCount;
3210            float points[pointsCount];
3211            int currentPoint = 0;
3212
3213            if (flags & SkPaint::kUnderlineText_Flag) {
3214                top = y + textSize * kStdUnderline_Offset;
3215                points[currentPoint++] = left;
3216                points[currentPoint++] = top;
3217                points[currentPoint++] = left + underlineWidth;
3218                points[currentPoint++] = top;
3219            }
3220
3221            if (flags & SkPaint::kStrikeThruText_Flag) {
3222                top = y + textSize * kStdStrikeThru_Offset;
3223                points[currentPoint++] = left;
3224                points[currentPoint++] = top;
3225                points[currentPoint++] = left + underlineWidth;
3226                points[currentPoint++] = top;
3227            }
3228
3229            paintCopy.setStrokeWidth(strokeWidth);
3230
3231            drawLines(&points[0], pointsCount, &paintCopy);
3232        }
3233    }
3234}
3235
3236void OpenGLRenderer::drawRects(const float* rects, int count, const SkPaint* paint) {
3237    if (mState.currentlyIgnored()) {
3238        return;
3239    }
3240
3241    drawColorRects(rects, count, paint, false, true, true);
3242}
3243
3244void OpenGLRenderer::drawShadow(float casterAlpha,
3245        const VertexBuffer* ambientShadowVertexBuffer, const VertexBuffer* spotShadowVertexBuffer) {
3246    if (mState.currentlyIgnored()) return;
3247
3248    // TODO: use quickRejectWithScissor. For now, always force enable scissor.
3249    mRenderState.scissor().setEnabled(true);
3250
3251    SkPaint paint;
3252    paint.setAntiAlias(true); // want to use AlphaVertex
3253
3254    // The caller has made sure casterAlpha > 0.
3255    float ambientShadowAlpha = mAmbientShadowAlpha;
3256    if (CC_UNLIKELY(mCaches.propertyAmbientShadowStrength >= 0)) {
3257        ambientShadowAlpha = mCaches.propertyAmbientShadowStrength;
3258    }
3259    if (ambientShadowVertexBuffer && ambientShadowAlpha > 0) {
3260        paint.setARGB(casterAlpha * ambientShadowAlpha, 0, 0, 0);
3261        drawVertexBuffer(*ambientShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp);
3262    }
3263
3264    float spotShadowAlpha = mSpotShadowAlpha;
3265    if (CC_UNLIKELY(mCaches.propertySpotShadowStrength >= 0)) {
3266        spotShadowAlpha = mCaches.propertySpotShadowStrength;
3267    }
3268    if (spotShadowVertexBuffer && spotShadowAlpha > 0) {
3269        paint.setARGB(casterAlpha * spotShadowAlpha, 0, 0, 0);
3270        drawVertexBuffer(*spotShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp);
3271    }
3272
3273    mDirty=true;
3274}
3275
3276void OpenGLRenderer::drawColorRects(const float* rects, int count, const SkPaint* paint,
3277        bool ignoreTransform, bool dirty, bool clip) {
3278    if (count == 0) {
3279        return;
3280    }
3281
3282    float left = FLT_MAX;
3283    float top = FLT_MAX;
3284    float right = FLT_MIN;
3285    float bottom = FLT_MIN;
3286
3287    Vertex mesh[count];
3288    Vertex* vertex = mesh;
3289
3290    for (int index = 0; index < count; index += 4) {
3291        float l = rects[index + 0];
3292        float t = rects[index + 1];
3293        float r = rects[index + 2];
3294        float b = rects[index + 3];
3295
3296        Vertex::set(vertex++, l, t);
3297        Vertex::set(vertex++, r, t);
3298        Vertex::set(vertex++, l, b);
3299        Vertex::set(vertex++, r, b);
3300
3301        left = fminf(left, l);
3302        top = fminf(top, t);
3303        right = fmaxf(right, r);
3304        bottom = fmaxf(bottom, b);
3305    }
3306
3307    if (clip && quickRejectSetupScissor(left, top, right, bottom)) {
3308        return;
3309    }
3310
3311    if (USE_GLOPS) {
3312        const Matrix4& transform = ignoreTransform ? Matrix4::identity() : *currentTransform();
3313        Glop glop;
3314        GlopBuilder aBuilder(mRenderState, mCaches, &glop);
3315        aBuilder.setMeshIndexedQuads(&mesh[0], count / 4)
3316                .setFillPaint(*paint, currentSnapshot()->alpha)
3317                .setTransform(currentSnapshot()->getOrthoMatrix(), transform, false)
3318                .setModelViewOffsetRect(0, 0, Rect(left, top, right, bottom))
3319                .setRoundRectClipState(currentSnapshot()->roundRectClipState)
3320                .build();
3321        renderGlop(glop);
3322        return;
3323    }
3324
3325    int color = paint->getColor();
3326    // If a shader is set, preserve only the alpha
3327    if (getShader(paint)) {
3328        color |= 0x00ffffff;
3329    }
3330
3331    setupDraw();
3332    setupDrawNoTexture();
3333    setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha);
3334    setupDrawShader(getShader(paint));
3335    setupDrawColorFilter(getColorFilter(paint));
3336    setupDrawBlending(paint);
3337    setupDrawProgram();
3338    setupDrawDirtyRegionsDisabled();
3339    setupDrawModelView(kModelViewMode_Translate, false,
3340            0.0f, 0.0f, 0.0f, 0.0f, ignoreTransform);
3341    setupDrawColorUniforms(getShader(paint));
3342    setupDrawShaderUniforms(getShader(paint));
3343    setupDrawColorFilterUniforms(getColorFilter(paint));
3344
3345    if (dirty && hasLayer()) {
3346        dirtyLayer(left, top, right, bottom, *currentTransform());
3347    }
3348
3349    issueIndexedQuadDraw(&mesh[0], count / 4);
3350
3351    mDirty = true;
3352}
3353
3354void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
3355        const SkPaint* paint, bool ignoreTransform) {
3356
3357    if (USE_GLOPS) {
3358        const Matrix4& transform = ignoreTransform ? Matrix4::identity() : *currentTransform();
3359        Glop glop;
3360        GlopBuilder aBuilder(mRenderState, mCaches, &glop);
3361        aBuilder.setMeshUnitQuad()
3362                .setFillPaint(*paint, currentSnapshot()->alpha)
3363                .setTransform(currentSnapshot()->getOrthoMatrix(), transform, false)
3364                .setModelViewMapUnitToRect(Rect(left, top, right, bottom))
3365                .setRoundRectClipState(currentSnapshot()->roundRectClipState)
3366                .build();
3367        renderGlop(glop);
3368        return;
3369    }
3370
3371    int color = paint->getColor();
3372    // If a shader is set, preserve only the alpha
3373    if (getShader(paint)) {
3374        color |= 0x00ffffff;
3375    }
3376
3377    setupDraw();
3378    setupDrawNoTexture();
3379    setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha);
3380    setupDrawShader(getShader(paint));
3381    setupDrawColorFilter(getColorFilter(paint));
3382    setupDrawBlending(paint);
3383    setupDrawProgram();
3384    setupDrawModelView(kModelViewMode_TranslateAndScale, false,
3385            left, top, right, bottom, ignoreTransform);
3386    setupDrawColorUniforms(getShader(paint));
3387    setupDrawShaderUniforms(getShader(paint), ignoreTransform);
3388    setupDrawColorFilterUniforms(getColorFilter(paint));
3389    setupDrawSimpleMesh();
3390
3391    glDrawArrays(GL_TRIANGLE_STRIP, 0, kUnitQuadCount);
3392}
3393
3394void OpenGLRenderer::drawTextureRect(Texture* texture, const SkPaint* paint) {
3395    texture->setWrap(GL_CLAMP_TO_EDGE, true);
3396
3397    GLvoid* vertices = (GLvoid*) nullptr;
3398    GLvoid* texCoords = (GLvoid*) kMeshTextureOffset;
3399
3400    if (texture->uvMapper) {
3401        vertices = &mMeshVertices[0].x;
3402        texCoords = &mMeshVertices[0].u;
3403
3404        Rect uvs(0.0f, 0.0f, 1.0f, 1.0f);
3405        texture->uvMapper->map(uvs);
3406
3407        resetDrawTextureTexCoords(uvs.left, uvs.top, uvs.right, uvs.bottom);
3408    }
3409
3410    if (CC_LIKELY(currentTransform()->isPureTranslate())) {
3411        const float x = (int) floorf(currentTransform()->getTranslateX() + 0.5f);
3412        const float y = (int) floorf(currentTransform()->getTranslateY() + 0.5f);
3413
3414        texture->setFilter(GL_NEAREST, true);
3415        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
3416                paint, texture->blend, vertices, texCoords,
3417                GL_TRIANGLE_STRIP, kUnitQuadCount, false, true);
3418    } else {
3419        texture->setFilter(PaintUtils::getFilter(paint), true);
3420        drawTextureMesh(0, 0, texture->width, texture->height, texture->id, paint,
3421                texture->blend, vertices, texCoords, GL_TRIANGLE_STRIP, kUnitQuadCount);
3422    }
3423
3424    if (texture->uvMapper) {
3425        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
3426    }
3427}
3428
3429void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
3430        GLuint texture, const SkPaint* paint, bool blend,
3431        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3432        bool swapSrcDst, bool ignoreTransform, GLuint vbo,
3433        ModelViewMode modelViewMode, bool dirty) {
3434
3435    int a;
3436    SkXfermode::Mode mode;
3437    getAlphaAndMode(paint, &a, &mode);
3438    const float alpha = a / 255.0f;
3439
3440    setupDraw();
3441    setupDrawWithTexture();
3442    setupDrawColor(alpha, alpha, alpha, alpha);
3443    setupDrawColorFilter(getColorFilter(paint));
3444    setupDrawBlending(paint, blend, swapSrcDst);
3445    setupDrawProgram();
3446    if (!dirty) setupDrawDirtyRegionsDisabled();
3447    setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform);
3448    setupDrawTexture(texture);
3449    setupDrawPureColorUniforms();
3450    setupDrawColorFilterUniforms(getColorFilter(paint));
3451    setupDrawMesh(vertices, texCoords, vbo);
3452
3453    glDrawArrays(drawMode, 0, elementsCount);
3454}
3455
3456void OpenGLRenderer::drawIndexedTextureMesh(float left, float top, float right, float bottom,
3457        GLuint texture, const SkPaint* paint, bool blend,
3458        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3459        bool swapSrcDst, bool ignoreTransform, GLuint vbo,
3460        ModelViewMode modelViewMode, bool dirty) {
3461
3462    int a;
3463    SkXfermode::Mode mode;
3464    getAlphaAndMode(paint, &a, &mode);
3465    const float alpha = a / 255.0f;
3466
3467    setupDraw();
3468    setupDrawWithTexture();
3469    setupDrawColor(alpha, alpha, alpha, alpha);
3470    setupDrawColorFilter(getColorFilter(paint));
3471    setupDrawBlending(paint, blend, swapSrcDst);
3472    setupDrawProgram();
3473    if (!dirty) setupDrawDirtyRegionsDisabled();
3474    setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform);
3475    setupDrawTexture(texture);
3476    setupDrawPureColorUniforms();
3477    setupDrawColorFilterUniforms(getColorFilter(paint));
3478    setupDrawMeshIndices(vertices, texCoords, vbo);
3479
3480    glDrawElements(drawMode, elementsCount, GL_UNSIGNED_SHORT, nullptr);
3481}
3482
3483void OpenGLRenderer::drawAlpha8TextureMesh(float left, float top, float right, float bottom,
3484        GLuint texture, const SkPaint* paint,
3485        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3486        bool ignoreTransform, ModelViewMode modelViewMode, bool dirty) {
3487
3488    int color = paint != nullptr ? paint->getColor() : 0;
3489    int alpha;
3490    SkXfermode::Mode mode;
3491    getAlphaAndMode(paint, &alpha, &mode);
3492
3493    setupDraw();
3494    setupDrawWithTexture(true);
3495    if (paint != nullptr) {
3496        setupDrawAlpha8Color(color, alpha);
3497    }
3498    setupDrawColorFilter(getColorFilter(paint));
3499    setupDrawShader(getShader(paint));
3500    setupDrawBlending(paint, true);
3501    setupDrawProgram();
3502    if (!dirty) setupDrawDirtyRegionsDisabled();
3503    setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform);
3504    setupDrawTexture(texture);
3505    setupDrawPureColorUniforms();
3506    setupDrawColorFilterUniforms(getColorFilter(paint));
3507    setupDrawShaderUniforms(getShader(paint), ignoreTransform);
3508    setupDrawMesh(vertices, texCoords);
3509
3510    glDrawArrays(drawMode, 0, elementsCount);
3511}
3512
3513void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
3514        ProgramDescription& description, bool swapSrcDst) {
3515
3516    if (currentSnapshot()->roundRectClipState != nullptr /*&& !mSkipOutlineClip*/) {
3517        blend = true;
3518        mDescription.hasRoundRectClip = true;
3519    }
3520    mSkipOutlineClip = true;
3521
3522    blend = blend || mode != SkXfermode::kSrcOver_Mode;
3523
3524    if (blend) {
3525        // These blend modes are not supported by OpenGL directly and have
3526        // to be implemented using shaders. Since the shader will perform
3527        // the blending, turn blending off here
3528        // If the blend mode cannot be implemented using shaders, fall
3529        // back to the default SrcOver blend mode instead
3530        if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) {
3531            if (CC_UNLIKELY(mCaches.extensions().hasFramebufferFetch())) {
3532                description.framebufferMode = mode;
3533                description.swapSrcDst = swapSrcDst;
3534
3535                mRenderState.blend().disable();
3536                return;
3537            } else {
3538                mode = SkXfermode::kSrcOver_Mode;
3539            }
3540        }
3541        mRenderState.blend().enable(mode, swapSrcDst);
3542    } else {
3543        mRenderState.blend().disable();
3544    }
3545}
3546
3547void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
3548    TextureVertex* v = &mMeshVertices[0];
3549    TextureVertex::setUV(v++, u1, v1);
3550    TextureVertex::setUV(v++, u2, v1);
3551    TextureVertex::setUV(v++, u1, v2);
3552    TextureVertex::setUV(v++, u2, v2);
3553}
3554
3555void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha,
3556        SkXfermode::Mode* mode) const {
3557    getAlphaAndModeDirect(paint, alpha,  mode);
3558    if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) {
3559        // if drawing a layer, ignore the paint's alpha
3560        *alpha = mDrawModifiers.mOverrideLayerAlpha * 255;
3561    }
3562    *alpha *= currentSnapshot()->alpha;
3563}
3564
3565float OpenGLRenderer::getLayerAlpha(const Layer* layer) const {
3566    float alpha;
3567    if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) {
3568        alpha = mDrawModifiers.mOverrideLayerAlpha;
3569    } else {
3570        alpha = layer->getAlpha() / 255.0f;
3571    }
3572    return alpha * currentSnapshot()->alpha;
3573}
3574
3575}; // namespace uirenderer
3576}; // namespace android
3577