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