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