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