OpenGLRenderer.cpp revision 6c5b9be7450903762f676522c32d65f7545730df
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::kModulate_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::kModulate_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;
1026        Region safeRegion;
1027        if (CC_LIKELY(hasRectToRectTransform())) {
1028            rects = layer->region.getArray(&count);
1029        } else {
1030            safeRegion = Region::createTJunctionFreeRegion(layer->region);
1031            rects = safeRegion.getArray(&count);
1032        }
1033
1034        const float alpha = layer->getAlpha() / 255.0f;
1035        const float texX = 1.0f / float(layer->getWidth());
1036        const float texY = 1.0f / float(layer->getHeight());
1037        const float height = rect.getHeight();
1038
1039        setupDraw();
1040
1041        // We must get (and therefore bind) the region mesh buffer
1042        // after we setup drawing in case we need to mess with the
1043        // stencil buffer in setupDraw()
1044        TextureVertex* mesh = mCaches.getRegionMesh();
1045        GLsizei numQuads = 0;
1046
1047        setupDrawWithTexture();
1048        setupDrawColor(alpha, alpha, alpha, alpha);
1049        setupDrawColorFilter();
1050        setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode(), false);
1051        setupDrawProgram();
1052        setupDrawDirtyRegionsDisabled();
1053        setupDrawPureColorUniforms();
1054        setupDrawColorFilterUniforms();
1055        setupDrawTexture(layer->getTexture());
1056        if (mSnapshot->transform->isPureTranslate()) {
1057            const float x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f);
1058            const float y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f);
1059
1060            layer->setFilter(GL_NEAREST);
1061            setupDrawModelViewTranslate(x, y, x + rect.getWidth(), y + rect.getHeight(), true);
1062        } else {
1063            layer->setFilter(GL_LINEAR);
1064            setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
1065        }
1066        setupDrawMeshIndices(&mesh[0].position[0], &mesh[0].texture[0]);
1067
1068        for (size_t i = 0; i < count; i++) {
1069            const android::Rect* r = &rects[i];
1070
1071            const float u1 = r->left * texX;
1072            const float v1 = (height - r->top) * texY;
1073            const float u2 = r->right * texX;
1074            const float v2 = (height - r->bottom) * texY;
1075
1076            // TODO: Reject quads outside of the clip
1077            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
1078            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
1079            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
1080            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
1081
1082            numQuads++;
1083
1084            if (numQuads >= REGION_MESH_QUAD_COUNT) {
1085                glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
1086                numQuads = 0;
1087                mesh = mCaches.getRegionMesh();
1088            }
1089        }
1090
1091        if (numQuads > 0) {
1092            glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
1093        }
1094
1095        finishDrawTexture();
1096
1097#if DEBUG_LAYERS_AS_REGIONS
1098        drawRegionRects(layer->region);
1099#endif
1100
1101        layer->region.clear();
1102    }
1103}
1104
1105void OpenGLRenderer::drawRegionRects(const Region& region) {
1106#if DEBUG_LAYERS_AS_REGIONS
1107    size_t count;
1108    const android::Rect* rects = region.getArray(&count);
1109
1110    uint32_t colors[] = {
1111            0x7fff0000, 0x7f00ff00,
1112            0x7f0000ff, 0x7fff00ff,
1113    };
1114
1115    int offset = 0;
1116    int32_t top = rects[0].top;
1117
1118    for (size_t i = 0; i < count; i++) {
1119        if (top != rects[i].top) {
1120            offset ^= 0x2;
1121            top = rects[i].top;
1122        }
1123
1124        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
1125        drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
1126                SkXfermode::kSrcOver_Mode);
1127    }
1128#endif
1129}
1130
1131void OpenGLRenderer::drawRegionRects(const SkRegion& region, int color,
1132        SkXfermode::Mode mode, bool dirty) {
1133    int count = 0;
1134    Vector<float> rects;
1135
1136    SkRegion::Iterator it(region);
1137    while (!it.done()) {
1138        const SkIRect& r = it.rect();
1139        rects.push(r.fLeft);
1140        rects.push(r.fTop);
1141        rects.push(r.fRight);
1142        rects.push(r.fBottom);
1143        count += 4;
1144        it.next();
1145    }
1146
1147    drawColorRects(rects.array(), count, color, mode, true, dirty, false);
1148}
1149
1150void OpenGLRenderer::dirtyLayer(const float left, const float top,
1151        const float right, const float bottom, const mat4 transform) {
1152    if (hasLayer()) {
1153        Rect bounds(left, top, right, bottom);
1154        transform.mapRect(bounds);
1155        dirtyLayerUnchecked(bounds, getRegion());
1156    }
1157}
1158
1159void OpenGLRenderer::dirtyLayer(const float left, const float top,
1160        const float right, const float bottom) {
1161    if (hasLayer()) {
1162        Rect bounds(left, top, right, bottom);
1163        dirtyLayerUnchecked(bounds, getRegion());
1164    }
1165}
1166
1167void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
1168    if (bounds.intersect(*mSnapshot->clipRect)) {
1169        bounds.snapToPixelBoundaries();
1170        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
1171        if (!dirty.isEmpty()) {
1172            region->orSelf(dirty);
1173        }
1174    }
1175}
1176
1177void OpenGLRenderer::clearLayerRegions() {
1178    const size_t count = mLayers.size();
1179    if (count == 0) return;
1180
1181    if (!mSnapshot->isIgnored()) {
1182        // Doing several glScissor/glClear here can negatively impact
1183        // GPUs with a tiler architecture, instead we draw quads with
1184        // the Clear blending mode
1185
1186        // The list contains bounds that have already been clipped
1187        // against their initial clip rect, and the current clip
1188        // is likely different so we need to disable clipping here
1189        bool scissorChanged = mCaches.disableScissor();
1190
1191        Vertex mesh[count * 6];
1192        Vertex* vertex = mesh;
1193
1194        for (uint32_t i = 0; i < count; i++) {
1195            Rect* bounds = mLayers.itemAt(i);
1196
1197            Vertex::set(vertex++, bounds->left, bounds->bottom);
1198            Vertex::set(vertex++, bounds->left, bounds->top);
1199            Vertex::set(vertex++, bounds->right, bounds->top);
1200            Vertex::set(vertex++, bounds->left, bounds->bottom);
1201            Vertex::set(vertex++, bounds->right, bounds->top);
1202            Vertex::set(vertex++, bounds->right, bounds->bottom);
1203
1204            delete bounds;
1205        }
1206        // We must clear the list of dirty rects before we
1207        // call setupDraw() to prevent stencil setup to do
1208        // the same thing again
1209        mLayers.clear();
1210
1211        setupDraw(false);
1212        setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f);
1213        setupDrawBlending(true, SkXfermode::kClear_Mode);
1214        setupDrawProgram();
1215        setupDrawPureColorUniforms();
1216        setupDrawModelViewTranslate(0.0f, 0.0f, 0.0f, 0.0f, true);
1217        setupDrawVertices(&mesh[0].position[0]);
1218
1219        glDrawArrays(GL_TRIANGLES, 0, count * 6);
1220
1221        if (scissorChanged) mCaches.enableScissor();
1222    } else {
1223        for (uint32_t i = 0; i < count; i++) {
1224            delete mLayers.itemAt(i);
1225        }
1226        mLayers.clear();
1227    }
1228}
1229
1230///////////////////////////////////////////////////////////////////////////////
1231// State Deferral
1232///////////////////////////////////////////////////////////////////////////////
1233
1234bool OpenGLRenderer::storeDisplayState(DeferredDisplayState& state) {
1235    const Rect& currentClip = *(mSnapshot->clipRect);
1236    const mat4& currentMatrix = *(mSnapshot->transform);
1237
1238    // state only has bounds initialized in local coordinates
1239    if (!state.mBounds.isEmpty()) {
1240        currentMatrix.mapRect(state.mBounds);
1241        if (!state.mBounds.intersect(currentClip)) {
1242            // quick rejected
1243            return true;
1244        }
1245    } else {
1246        state.mBounds.set(currentClip);
1247    }
1248
1249    state.mClip.set(currentClip);
1250    state.mMatrix.load(currentMatrix);
1251    state.mDrawModifiers = mDrawModifiers;
1252    return false;
1253}
1254
1255void OpenGLRenderer::restoreDisplayState(const DeferredDisplayState& state) {
1256    mSnapshot->transform->load(state.mMatrix);
1257
1258    // NOTE: a clip RECT will be saved and restored, but DeferredDisplayState doesn't support
1259    // complex clips. In the future, we should add support for deferral of operations clipped by
1260    // these. for now, we don't defer with complex clips (see OpenGLRenderer::disallowDeferral())
1261    mSnapshot->setClip(state.mClip.left, state.mClip.top, state.mClip.right, state.mClip.bottom);
1262    dirtyClip();
1263    mDrawModifiers = state.mDrawModifiers;
1264}
1265
1266///////////////////////////////////////////////////////////////////////////////
1267// Transforms
1268///////////////////////////////////////////////////////////////////////////////
1269
1270void OpenGLRenderer::translate(float dx, float dy) {
1271    mSnapshot->transform->translate(dx, dy, 0.0f);
1272}
1273
1274void OpenGLRenderer::rotate(float degrees) {
1275    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
1276}
1277
1278void OpenGLRenderer::scale(float sx, float sy) {
1279    mSnapshot->transform->scale(sx, sy, 1.0f);
1280}
1281
1282void OpenGLRenderer::skew(float sx, float sy) {
1283    mSnapshot->transform->skew(sx, sy);
1284}
1285
1286void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
1287    if (matrix) {
1288        mSnapshot->transform->load(*matrix);
1289    } else {
1290        mSnapshot->transform->loadIdentity();
1291    }
1292}
1293
1294bool OpenGLRenderer::hasRectToRectTransform() {
1295    return CC_LIKELY(mSnapshot->transform->rectToRect());
1296}
1297
1298void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
1299    mSnapshot->transform->copyTo(*matrix);
1300}
1301
1302void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
1303    SkMatrix transform;
1304    mSnapshot->transform->copyTo(transform);
1305    transform.preConcat(*matrix);
1306    mSnapshot->transform->load(transform);
1307}
1308
1309///////////////////////////////////////////////////////////////////////////////
1310// Clipping
1311///////////////////////////////////////////////////////////////////////////////
1312
1313void OpenGLRenderer::setScissorFromClip() {
1314    Rect clip(*mSnapshot->clipRect);
1315    clip.snapToPixelBoundaries();
1316
1317    if (mCaches.setScissor(clip.left, mSnapshot->height - clip.bottom,
1318            clip.getWidth(), clip.getHeight())) {
1319        mDirtyClip = false;
1320    }
1321}
1322
1323void OpenGLRenderer::ensureStencilBuffer() {
1324    // Thanks to the mismatch between EGL and OpenGL ES FBO we
1325    // cannot attach a stencil buffer to fbo0 dynamically. Let's
1326    // just hope we have one when hasLayer() returns false.
1327    if (hasLayer()) {
1328        attachStencilBufferToLayer(mSnapshot->layer);
1329    }
1330}
1331
1332void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) {
1333    // The layer's FBO is already bound when we reach this stage
1334    if (!layer->getStencilRenderBuffer()) {
1335        // GL_QCOM_tiled_rendering doesn't like it if a renderbuffer
1336        // is attached after we initiated tiling. We must turn it off,
1337        // attach the new render buffer then turn tiling back on
1338        endTiling();
1339
1340        RenderBuffer* buffer = mCaches.renderBufferCache.get(
1341                Stencil::getSmallestStencilFormat(), layer->getWidth(), layer->getHeight());
1342        layer->setStencilRenderBuffer(buffer);
1343
1344        startTiling(layer->clipRect, layer->layer.getHeight());
1345    }
1346}
1347
1348void OpenGLRenderer::setStencilFromClip() {
1349    if (!mCaches.debugOverdraw) {
1350        if (!mSnapshot->clipRegion->isEmpty()) {
1351            // NOTE: The order here is important, we must set dirtyClip to false
1352            //       before any draw call to avoid calling back into this method
1353            mDirtyClip = false;
1354
1355            ensureStencilBuffer();
1356
1357            mCaches.stencil.enableWrite();
1358
1359            // Clear the stencil but first make sure we restrict drawing
1360            // to the region's bounds
1361            bool resetScissor = mCaches.enableScissor();
1362            if (resetScissor) {
1363                // The scissor was not set so we now need to update it
1364                setScissorFromClip();
1365            }
1366            mCaches.stencil.clear();
1367            if (resetScissor) mCaches.disableScissor();
1368
1369            // NOTE: We could use the region contour path to generate a smaller mesh
1370            //       Since we are using the stencil we could use the red book path
1371            //       drawing technique. It might increase bandwidth usage though.
1372
1373            // The last parameter is important: we are not drawing in the color buffer
1374            // so we don't want to dirty the current layer, if any
1375            drawRegionRects(*mSnapshot->clipRegion, 0xff000000, SkXfermode::kSrc_Mode, false);
1376
1377            mCaches.stencil.enableTest();
1378
1379            // Draw the region used to generate the stencil if the appropriate debug
1380            // mode is enabled
1381            if (mCaches.debugStencilClip == Caches::kStencilShowRegion) {
1382                drawRegionRects(*mSnapshot->clipRegion, 0x7f0000ff, SkXfermode::kSrcOver_Mode);
1383            }
1384        } else {
1385            mCaches.stencil.disable();
1386        }
1387    }
1388}
1389
1390const Rect& OpenGLRenderer::getClipBounds() {
1391    return mSnapshot->getLocalClip();
1392}
1393
1394bool OpenGLRenderer::quickRejectNoScissor(float left, float top, float right, float bottom) {
1395    if (mSnapshot->isIgnored()) {
1396        return true;
1397    }
1398
1399    Rect r(left, top, right, bottom);
1400    mSnapshot->transform->mapRect(r);
1401    r.snapToPixelBoundaries();
1402
1403    Rect clipRect(*mSnapshot->clipRect);
1404    clipRect.snapToPixelBoundaries();
1405
1406    return !clipRect.intersects(r);
1407}
1408
1409bool OpenGLRenderer::quickRejectNoScissor(float left, float top, float right, float bottom,
1410        Rect& transformed, Rect& clip) {
1411    if (mSnapshot->isIgnored()) {
1412        return true;
1413    }
1414
1415    transformed.set(left, top, right, bottom);
1416    mSnapshot->transform->mapRect(transformed);
1417    transformed.snapToPixelBoundaries();
1418
1419    clip.set(*mSnapshot->clipRect);
1420    clip.snapToPixelBoundaries();
1421
1422    return !clip.intersects(transformed);
1423}
1424
1425bool OpenGLRenderer::quickRejectPreStroke(float left, float top, float right, float bottom,
1426        SkPaint* paint) {
1427    if (paint->getStyle() != SkPaint::kFill_Style) {
1428        float outset = paint->getStrokeWidth() * 0.5f;
1429        return quickReject(left - outset, top - outset, right + outset, bottom + outset);
1430    } else {
1431        return quickReject(left, top, right, bottom);
1432    }
1433}
1434
1435bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
1436    if (mSnapshot->isIgnored() || bottom <= top || right <= left) {
1437        return true;
1438    }
1439
1440    Rect r(left, top, right, bottom);
1441    mSnapshot->transform->mapRect(r);
1442    r.snapToPixelBoundaries();
1443
1444    Rect clipRect(*mSnapshot->clipRect);
1445    clipRect.snapToPixelBoundaries();
1446
1447    bool rejected = !clipRect.intersects(r);
1448    if (!isDeferred() && !rejected) {
1449        mCaches.setScissorEnabled(mScissorOptimizationDisabled || !clipRect.contains(r));
1450    }
1451
1452    return rejected;
1453}
1454
1455void OpenGLRenderer::debugClip() {
1456#if DEBUG_CLIP_REGIONS
1457    if (!isDeferred() && !mSnapshot->clipRegion->isEmpty()) {
1458        drawRegionRects(*mSnapshot->clipRegion, 0x7f00ff00, SkXfermode::kSrcOver_Mode);
1459    }
1460#endif
1461}
1462
1463bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
1464    if (CC_LIKELY(mSnapshot->transform->rectToRect())) {
1465        bool clipped = mSnapshot->clip(left, top, right, bottom, op);
1466        if (clipped) {
1467            dirtyClip();
1468        }
1469        return !mSnapshot->clipRect->isEmpty();
1470    }
1471
1472    SkPath path;
1473    path.addRect(left, top, right, bottom);
1474
1475    return clipPath(&path, op);
1476}
1477
1478bool OpenGLRenderer::clipPath(SkPath* path, SkRegion::Op op) {
1479    SkMatrix transform;
1480    mSnapshot->transform->copyTo(transform);
1481
1482    SkPath transformed;
1483    path->transform(transform, &transformed);
1484
1485    SkRegion clip;
1486    if (!mSnapshot->clipRegion->isEmpty()) {
1487        clip.setRegion(*mSnapshot->clipRegion);
1488    } else {
1489        Rect* bounds = mSnapshot->clipRect;
1490        clip.setRect(bounds->left, bounds->top, bounds->right, bounds->bottom);
1491    }
1492
1493    SkRegion region;
1494    region.setPath(transformed, clip);
1495
1496    bool clipped = mSnapshot->clipRegionTransformed(region, op);
1497    if (clipped) {
1498        dirtyClip();
1499    }
1500    return !mSnapshot->clipRect->isEmpty();
1501}
1502
1503bool OpenGLRenderer::clipRegion(SkRegion* region, SkRegion::Op op) {
1504    bool clipped = mSnapshot->clipRegionTransformed(*region, op);
1505    if (clipped) {
1506        dirtyClip();
1507    }
1508    return !mSnapshot->clipRect->isEmpty();
1509}
1510
1511Rect* OpenGLRenderer::getClipRect() {
1512    return mSnapshot->clipRect;
1513}
1514
1515///////////////////////////////////////////////////////////////////////////////
1516// Drawing commands
1517///////////////////////////////////////////////////////////////////////////////
1518
1519void OpenGLRenderer::setupDraw(bool clear) {
1520    // TODO: It would be best if we could do this before quickReject()
1521    //       changes the scissor test state
1522    if (clear) clearLayerRegions();
1523    // Make sure setScissor & setStencil happen at the beginning of
1524    // this method
1525    if (mDirtyClip) {
1526        if (mCaches.scissorEnabled) {
1527            setScissorFromClip();
1528        }
1529        setStencilFromClip();
1530    }
1531
1532    mDescription.reset();
1533
1534    mSetShaderColor = false;
1535    mColorSet = false;
1536    mColorA = mColorR = mColorG = mColorB = 0.0f;
1537    mTextureUnit = 0;
1538    mTrackDirtyRegions = true;
1539
1540    // Enable debug highlight when what we're about to draw is tested against
1541    // the stencil buffer and if stencil highlight debugging is on
1542    mDescription.hasDebugHighlight = !mCaches.debugOverdraw &&
1543            mCaches.debugStencilClip == Caches::kStencilShowHighlight &&
1544            mCaches.stencil.isTestEnabled();
1545}
1546
1547void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
1548    mDescription.hasTexture = true;
1549    mDescription.hasAlpha8Texture = isAlpha8;
1550}
1551
1552void OpenGLRenderer::setupDrawWithTextureAndColor(bool isAlpha8) {
1553    mDescription.hasTexture = true;
1554    mDescription.hasColors = true;
1555    mDescription.hasAlpha8Texture = isAlpha8;
1556}
1557
1558void OpenGLRenderer::setupDrawWithExternalTexture() {
1559    mDescription.hasExternalTexture = true;
1560}
1561
1562void OpenGLRenderer::setupDrawNoTexture() {
1563    mCaches.disableTexCoordsVertexArray();
1564}
1565
1566void OpenGLRenderer::setupDrawAA() {
1567    mDescription.isAA = true;
1568}
1569
1570void OpenGLRenderer::setupDrawPoint(float pointSize) {
1571    mDescription.isPoint = true;
1572    mDescription.pointSize = pointSize;
1573}
1574
1575void OpenGLRenderer::setupDrawColor(int color, int alpha) {
1576    mColorA = alpha / 255.0f;
1577    mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1578    mColorG = mColorA * ((color >>  8) & 0xFF) / 255.0f;
1579    mColorB = mColorA * ((color      ) & 0xFF) / 255.0f;
1580    mColorSet = true;
1581    mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA);
1582}
1583
1584void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
1585    mColorA = alpha / 255.0f;
1586    mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1587    mColorG = mColorA * ((color >>  8) & 0xFF) / 255.0f;
1588    mColorB = mColorA * ((color      ) & 0xFF) / 255.0f;
1589    mColorSet = true;
1590    mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
1591}
1592
1593void OpenGLRenderer::setupDrawTextGamma(const SkPaint* paint) {
1594    mCaches.fontRenderer->describe(mDescription, paint);
1595}
1596
1597void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
1598    mColorA = a;
1599    mColorR = r;
1600    mColorG = g;
1601    mColorB = b;
1602    mColorSet = true;
1603    mSetShaderColor = mDescription.setColor(r, g, b, a);
1604}
1605
1606void OpenGLRenderer::setupDrawShader() {
1607    if (mDrawModifiers.mShader) {
1608        mDrawModifiers.mShader->describe(mDescription, mExtensions);
1609    }
1610}
1611
1612void OpenGLRenderer::setupDrawColorFilter() {
1613    if (mDrawModifiers.mColorFilter) {
1614        mDrawModifiers.mColorFilter->describe(mDescription, mExtensions);
1615    }
1616}
1617
1618void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
1619    if (mColorSet && mode == SkXfermode::kClear_Mode) {
1620        mColorA = 1.0f;
1621        mColorR = mColorG = mColorB = 0.0f;
1622        mSetShaderColor = mDescription.modulate = true;
1623    }
1624}
1625
1626void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) {
1627    // When the blending mode is kClear_Mode, we need to use a modulate color
1628    // argb=1,0,0,0
1629    accountForClear(mode);
1630    bool blend = (mColorSet && mColorA < 1.0f) ||
1631            (mDrawModifiers.mShader && mDrawModifiers.mShader->blend());
1632    chooseBlending(blend, mode, mDescription, swapSrcDst);
1633}
1634
1635void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) {
1636    // When the blending mode is kClear_Mode, we need to use a modulate color
1637    // argb=1,0,0,0
1638    accountForClear(mode);
1639    blend |= (mColorSet && mColorA < 1.0f) ||
1640            (mDrawModifiers.mShader && mDrawModifiers.mShader->blend()) ||
1641            (mDrawModifiers.mColorFilter && mDrawModifiers.mColorFilter->blend());
1642    chooseBlending(blend, mode, mDescription, swapSrcDst);
1643}
1644
1645void OpenGLRenderer::setupDrawProgram() {
1646    useProgram(mCaches.programCache.get(mDescription));
1647}
1648
1649void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
1650    mTrackDirtyRegions = false;
1651}
1652
1653void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom,
1654        bool ignoreTransform) {
1655    mModelView.loadTranslate(left, top, 0.0f);
1656    if (!ignoreTransform) {
1657        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1658        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1659    } else {
1660        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1661        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
1662    }
1663}
1664
1665void OpenGLRenderer::setupDrawModelViewIdentity(bool offset) {
1666    mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform, offset);
1667}
1668
1669void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom,
1670        bool ignoreTransform, bool ignoreModelView) {
1671    if (!ignoreModelView) {
1672        mModelView.loadTranslate(left, top, 0.0f);
1673        mModelView.scale(right - left, bottom - top, 1.0f);
1674    } else {
1675        mModelView.loadIdentity();
1676    }
1677    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
1678    if (!ignoreTransform) {
1679        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1680        if (mTrackDirtyRegions && dirty) {
1681            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1682        }
1683    } else {
1684        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1685        if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom);
1686    }
1687}
1688
1689void OpenGLRenderer::setupDrawPointUniforms() {
1690    int slot = mCaches.currentProgram->getUniform("pointSize");
1691    glUniform1f(slot, mDescription.pointSize);
1692}
1693
1694void OpenGLRenderer::setupDrawColorUniforms() {
1695    if ((mColorSet && !mDrawModifiers.mShader) || (mDrawModifiers.mShader && mSetShaderColor)) {
1696        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1697    }
1698}
1699
1700void OpenGLRenderer::setupDrawPureColorUniforms() {
1701    if (mSetShaderColor) {
1702        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1703    }
1704}
1705
1706void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
1707    if (mDrawModifiers.mShader) {
1708        if (ignoreTransform) {
1709            mModelView.loadInverse(*mSnapshot->transform);
1710        }
1711        mDrawModifiers.mShader->setupProgram(mCaches.currentProgram,
1712                mModelView, *mSnapshot, &mTextureUnit);
1713    }
1714}
1715
1716void OpenGLRenderer::setupDrawShaderIdentityUniforms() {
1717    if (mDrawModifiers.mShader) {
1718        mDrawModifiers.mShader->setupProgram(mCaches.currentProgram,
1719                mIdentity, *mSnapshot, &mTextureUnit);
1720    }
1721}
1722
1723void OpenGLRenderer::setupDrawColorFilterUniforms() {
1724    if (mDrawModifiers.mColorFilter) {
1725        mDrawModifiers.mColorFilter->setupProgram(mCaches.currentProgram);
1726    }
1727}
1728
1729void OpenGLRenderer::setupDrawTextGammaUniforms() {
1730    mCaches.fontRenderer->setupProgram(mDescription, mCaches.currentProgram);
1731}
1732
1733void OpenGLRenderer::setupDrawSimpleMesh() {
1734    bool force = mCaches.bindMeshBuffer();
1735    mCaches.bindPositionVertexPointer(force, 0);
1736    mCaches.unbindIndicesBuffer();
1737}
1738
1739void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1740    bindTexture(texture);
1741    mTextureUnit++;
1742    mCaches.enableTexCoordsVertexArray();
1743}
1744
1745void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) {
1746    bindExternalTexture(texture);
1747    mTextureUnit++;
1748    mCaches.enableTexCoordsVertexArray();
1749}
1750
1751void OpenGLRenderer::setupDrawTextureTransform() {
1752    mDescription.hasTextureTransform = true;
1753}
1754
1755void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) {
1756    glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1,
1757            GL_FALSE, &transform.data[0]);
1758}
1759
1760void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1761    bool force = false;
1762    if (!vertices) {
1763        force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1764    } else {
1765        force = mCaches.unbindMeshBuffer();
1766    }
1767
1768    mCaches.bindPositionVertexPointer(force, vertices);
1769    if (mCaches.currentProgram->texCoords >= 0) {
1770        mCaches.bindTexCoordsVertexPointer(force, texCoords);
1771    }
1772
1773    mCaches.unbindIndicesBuffer();
1774}
1775
1776void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLvoid* colors) {
1777    bool force = mCaches.unbindMeshBuffer();
1778    GLsizei stride = sizeof(ColorTextureVertex);
1779
1780    mCaches.bindPositionVertexPointer(force, vertices, stride);
1781    if (mCaches.currentProgram->texCoords >= 0) {
1782        mCaches.bindTexCoordsVertexPointer(force, texCoords, stride);
1783    }
1784    int slot = mCaches.currentProgram->getAttrib("colors");
1785    if (slot >= 0) {
1786        glEnableVertexAttribArray(slot);
1787        glVertexAttribPointer(slot, 4, GL_FLOAT, GL_FALSE, stride, colors);
1788    }
1789
1790    mCaches.unbindIndicesBuffer();
1791}
1792
1793void OpenGLRenderer::setupDrawMeshIndices(GLvoid* vertices, GLvoid* texCoords) {
1794    bool force = mCaches.unbindMeshBuffer();
1795    mCaches.bindPositionVertexPointer(force, vertices);
1796    if (mCaches.currentProgram->texCoords >= 0) {
1797        mCaches.bindTexCoordsVertexPointer(force, texCoords);
1798    }
1799}
1800
1801void OpenGLRenderer::setupDrawVertices(GLvoid* vertices) {
1802    bool force = mCaches.unbindMeshBuffer();
1803    mCaches.bindPositionVertexPointer(force, vertices, gVertexStride);
1804    mCaches.unbindIndicesBuffer();
1805}
1806
1807void OpenGLRenderer::finishDrawTexture() {
1808}
1809
1810///////////////////////////////////////////////////////////////////////////////
1811// Drawing
1812///////////////////////////////////////////////////////////////////////////////
1813
1814status_t OpenGLRenderer::drawDisplayList(DisplayList* displayList, Rect& dirty, int32_t flags) {
1815    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1816    // will be performed by the display list itself
1817    if (displayList && displayList->isRenderable()) {
1818        if (CC_UNLIKELY(mDrawDeferDisabled)) {
1819            return displayList->replay(*this, dirty, flags, 0);
1820        }
1821
1822        DeferredDisplayList deferredList;
1823        return displayList->replay(*this, dirty, flags, 0, &deferredList);
1824    }
1825
1826    return DrawGlInfo::kStatusDone;
1827}
1828
1829void OpenGLRenderer::outputDisplayList(DisplayList* displayList) {
1830    if (displayList) {
1831        displayList->output(1);
1832    }
1833}
1834
1835void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint) {
1836    int alpha;
1837    SkXfermode::Mode mode;
1838    getAlphaAndMode(paint, &alpha, &mode);
1839
1840    int color = paint != NULL ? paint->getColor() : 0;
1841
1842    float x = left;
1843    float y = top;
1844
1845    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1846
1847    bool ignoreTransform = false;
1848    if (mSnapshot->transform->isPureTranslate()) {
1849        x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1850        y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1851        ignoreTransform = true;
1852
1853        texture->setFilter(GL_NEAREST, true);
1854    } else {
1855        texture->setFilter(FILTER(paint), true);
1856    }
1857
1858    drawAlpha8TextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
1859            paint != NULL, color, alpha, mode, (GLvoid*) NULL,
1860            (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform);
1861}
1862
1863status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1864    const float right = left + bitmap->width();
1865    const float bottom = top + bitmap->height();
1866
1867    if (quickReject(left, top, right, bottom)) {
1868        return DrawGlInfo::kStatusDone;
1869    }
1870
1871    mCaches.activeTexture(0);
1872    Texture* texture = mCaches.textureCache.get(bitmap);
1873    if (!texture) return DrawGlInfo::kStatusDone;
1874    const AutoTexture autoCleanup(texture);
1875
1876    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
1877        drawAlphaBitmap(texture, left, top, paint);
1878    } else {
1879        drawTextureRect(left, top, right, bottom, texture, paint);
1880    }
1881
1882    return DrawGlInfo::kStatusDrew;
1883}
1884
1885status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
1886    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
1887    const mat4 transform(*matrix);
1888    transform.mapRect(r);
1889
1890    if (quickReject(r.left, r.top, r.right, r.bottom)) {
1891        return DrawGlInfo::kStatusDone;
1892    }
1893
1894    mCaches.activeTexture(0);
1895    Texture* texture = mCaches.textureCache.get(bitmap);
1896    if (!texture) return DrawGlInfo::kStatusDone;
1897    const AutoTexture autoCleanup(texture);
1898
1899    // This could be done in a cheaper way, all we need is pass the matrix
1900    // to the vertex shader. The save/restore is a bit overkill.
1901    save(SkCanvas::kMatrix_SaveFlag);
1902    concatMatrix(matrix);
1903    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
1904        drawAlphaBitmap(texture, 0.0f, 0.0f, paint);
1905    } else {
1906        drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
1907    }
1908    restore();
1909
1910    return DrawGlInfo::kStatusDrew;
1911}
1912
1913status_t OpenGLRenderer::drawBitmapData(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1914    const float right = left + bitmap->width();
1915    const float bottom = top + bitmap->height();
1916
1917    if (quickReject(left, top, right, bottom)) {
1918        return DrawGlInfo::kStatusDone;
1919    }
1920
1921    mCaches.activeTexture(0);
1922    Texture* texture = mCaches.textureCache.getTransient(bitmap);
1923    const AutoTexture autoCleanup(texture);
1924
1925    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
1926        drawAlphaBitmap(texture, left, top, paint);
1927    } else {
1928        drawTextureRect(left, top, right, bottom, texture, paint);
1929    }
1930
1931    return DrawGlInfo::kStatusDrew;
1932}
1933
1934status_t OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
1935        float* vertices, int* colors, SkPaint* paint) {
1936    if (!vertices || mSnapshot->isIgnored()) {
1937        return DrawGlInfo::kStatusDone;
1938    }
1939
1940    float left = FLT_MAX;
1941    float top = FLT_MAX;
1942    float right = FLT_MIN;
1943    float bottom = FLT_MIN;
1944
1945    const uint32_t count = meshWidth * meshHeight * 6;
1946
1947    ColorTextureVertex mesh[count];
1948    ColorTextureVertex* vertex = mesh;
1949
1950    bool cleanupColors = false;
1951    if (!colors) {
1952        uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1);
1953        colors = new int[colorsCount];
1954        memset(colors, 0xff, colorsCount * sizeof(int));
1955        cleanupColors = true;
1956    }
1957
1958    for (int32_t y = 0; y < meshHeight; y++) {
1959        for (int32_t x = 0; x < meshWidth; x++) {
1960            uint32_t i = (y * (meshWidth + 1) + x) * 2;
1961
1962            float u1 = float(x) / meshWidth;
1963            float u2 = float(x + 1) / meshWidth;
1964            float v1 = float(y) / meshHeight;
1965            float v2 = float(y + 1) / meshHeight;
1966
1967            int ax = i + (meshWidth + 1) * 2;
1968            int ay = ax + 1;
1969            int bx = i;
1970            int by = bx + 1;
1971            int cx = i + 2;
1972            int cy = cx + 1;
1973            int dx = i + (meshWidth + 1) * 2 + 2;
1974            int dy = dx + 1;
1975
1976            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
1977            ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]);
1978            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
1979
1980            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
1981            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
1982            ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]);
1983
1984            left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
1985            top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
1986            right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
1987            bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
1988        }
1989    }
1990
1991    if (quickReject(left, top, right, bottom)) {
1992        if (cleanupColors) delete[] colors;
1993        return DrawGlInfo::kStatusDone;
1994    }
1995
1996    mCaches.activeTexture(0);
1997    Texture* texture = mCaches.textureCache.get(bitmap);
1998    if (!texture) {
1999        if (cleanupColors) delete[] colors;
2000        return DrawGlInfo::kStatusDone;
2001    }
2002    const AutoTexture autoCleanup(texture);
2003
2004    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2005    texture->setFilter(FILTER(paint), true);
2006
2007    int alpha;
2008    SkXfermode::Mode mode;
2009    getAlphaAndMode(paint, &alpha, &mode);
2010
2011    float a = alpha / 255.0f;
2012
2013    if (hasLayer()) {
2014        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
2015    }
2016
2017    setupDraw();
2018    setupDrawWithTextureAndColor();
2019    setupDrawColor(a, a, a, a);
2020    setupDrawColorFilter();
2021    setupDrawBlending(true, mode, false);
2022    setupDrawProgram();
2023    setupDrawDirtyRegionsDisabled();
2024    setupDrawModelView(0.0f, 0.0f, 1.0f, 1.0f, false);
2025    setupDrawTexture(texture->id);
2026    setupDrawPureColorUniforms();
2027    setupDrawColorFilterUniforms();
2028    setupDrawMesh(&mesh[0].position[0], &mesh[0].texture[0], &mesh[0].color[0]);
2029
2030    glDrawArrays(GL_TRIANGLES, 0, count);
2031
2032    finishDrawTexture();
2033
2034    int slot = mCaches.currentProgram->getAttrib("colors");
2035    if (slot >= 0) {
2036        glDisableVertexAttribArray(slot);
2037    }
2038
2039    if (cleanupColors) delete[] colors;
2040
2041    return DrawGlInfo::kStatusDrew;
2042}
2043
2044status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
2045         float srcLeft, float srcTop, float srcRight, float srcBottom,
2046         float dstLeft, float dstTop, float dstRight, float dstBottom,
2047         SkPaint* paint) {
2048    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
2049        return DrawGlInfo::kStatusDone;
2050    }
2051
2052    mCaches.activeTexture(0);
2053    Texture* texture = mCaches.textureCache.get(bitmap);
2054    if (!texture) return DrawGlInfo::kStatusDone;
2055    const AutoTexture autoCleanup(texture);
2056
2057    const float width = texture->width;
2058    const float height = texture->height;
2059
2060    const float u1 = fmax(0.0f, srcLeft / width);
2061    const float v1 = fmax(0.0f, srcTop / height);
2062    const float u2 = fmin(1.0f, srcRight / width);
2063    const float v2 = fmin(1.0f, srcBottom / height);
2064
2065    mCaches.unbindMeshBuffer();
2066    resetDrawTextureTexCoords(u1, v1, u2, v2);
2067
2068    int alpha;
2069    SkXfermode::Mode mode;
2070    getAlphaAndMode(paint, &alpha, &mode);
2071
2072    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2073
2074    float scaleX = (dstRight - dstLeft) / (srcRight - srcLeft);
2075    float scaleY = (dstBottom - dstTop) / (srcBottom - srcTop);
2076
2077    bool scaled = scaleX != 1.0f || scaleY != 1.0f;
2078    // Apply a scale transform on the canvas only when a shader is in use
2079    // Skia handles the ratio between the dst and src rects as a scale factor
2080    // when a shader is set
2081    bool useScaleTransform = mDrawModifiers.mShader && scaled;
2082    bool ignoreTransform = false;
2083
2084    if (CC_LIKELY(mSnapshot->transform->isPureTranslate() && !useScaleTransform)) {
2085        float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f);
2086        float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f);
2087
2088        dstRight = x + (dstRight - dstLeft);
2089        dstBottom = y + (dstBottom - dstTop);
2090
2091        dstLeft = x;
2092        dstTop = y;
2093
2094        texture->setFilter(scaled ? FILTER(paint) : GL_NEAREST, true);
2095        ignoreTransform = true;
2096    } else {
2097        texture->setFilter(FILTER(paint), true);
2098    }
2099
2100    if (CC_UNLIKELY(useScaleTransform)) {
2101        save(SkCanvas::kMatrix_SaveFlag);
2102        translate(dstLeft, dstTop);
2103        scale(scaleX, scaleY);
2104
2105        dstLeft = 0.0f;
2106        dstTop = 0.0f;
2107
2108        dstRight = srcRight - srcLeft;
2109        dstBottom = srcBottom - srcTop;
2110    }
2111
2112    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
2113        int color = paint ? paint->getColor() : 0;
2114        drawAlpha8TextureMesh(dstLeft, dstTop, dstRight, dstBottom,
2115                texture->id, paint != NULL, color, alpha, mode,
2116                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
2117                GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform);
2118    } else {
2119        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom,
2120                texture->id, alpha / 255.0f, mode, texture->blend,
2121                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
2122                GL_TRIANGLE_STRIP, gMeshCount, false, ignoreTransform);
2123    }
2124
2125    if (CC_UNLIKELY(useScaleTransform)) {
2126        restore();
2127    }
2128
2129    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
2130
2131    return DrawGlInfo::kStatusDrew;
2132}
2133
2134status_t OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
2135        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
2136        float left, float top, float right, float bottom, SkPaint* paint) {
2137    int alpha;
2138    SkXfermode::Mode mode;
2139    getAlphaAndModeDirect(paint, &alpha, &mode);
2140
2141    return drawPatch(bitmap, xDivs, yDivs, colors, width, height, numColors,
2142            left, top, right, bottom, alpha, mode);
2143}
2144
2145status_t OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
2146        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
2147        float left, float top, float right, float bottom, int alpha, SkXfermode::Mode mode) {
2148    if (quickReject(left, top, right, bottom)) {
2149        return DrawGlInfo::kStatusDone;
2150    }
2151
2152    alpha *= mSnapshot->alpha;
2153
2154    mCaches.activeTexture(0);
2155    Texture* texture = mCaches.textureCache.get(bitmap);
2156    if (!texture) return DrawGlInfo::kStatusDone;
2157    const AutoTexture autoCleanup(texture);
2158    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2159    texture->setFilter(GL_LINEAR, true);
2160
2161    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
2162            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
2163
2164    if (CC_LIKELY(mesh && mesh->verticesCount > 0)) {
2165        const bool pureTranslate = mSnapshot->transform->isPureTranslate();
2166        // Mark the current layer dirty where we are going to draw the patch
2167        if (hasLayer() && mesh->hasEmptyQuads) {
2168            const float offsetX = left + mSnapshot->transform->getTranslateX();
2169            const float offsetY = top + mSnapshot->transform->getTranslateY();
2170            const size_t count = mesh->quads.size();
2171            for (size_t i = 0; i < count; i++) {
2172                const Rect& bounds = mesh->quads.itemAt(i);
2173                if (CC_LIKELY(pureTranslate)) {
2174                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
2175                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
2176                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
2177                } else {
2178                    dirtyLayer(left + bounds.left, top + bounds.top,
2179                            left + bounds.right, top + bounds.bottom, *mSnapshot->transform);
2180                }
2181            }
2182        }
2183
2184        if (CC_LIKELY(pureTranslate)) {
2185            const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
2186            const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
2187
2188            drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
2189                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
2190                    GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
2191                    true, !mesh->hasEmptyQuads);
2192        } else {
2193            drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
2194                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
2195                    GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
2196                    true, !mesh->hasEmptyQuads);
2197        }
2198    }
2199
2200    return DrawGlInfo::kStatusDrew;
2201}
2202
2203status_t OpenGLRenderer::drawVertexBuffer(const VertexBuffer& vertexBuffer, SkPaint* paint,
2204        bool useOffset) {
2205    if (!vertexBuffer.getSize()) {
2206        // no vertices to draw
2207        return DrawGlInfo::kStatusDone;
2208    }
2209
2210    int color = paint->getColor();
2211    SkXfermode::Mode mode = getXfermode(paint->getXfermode());
2212    bool isAA = paint->isAntiAlias();
2213
2214    setupDraw();
2215    setupDrawNoTexture();
2216    if (isAA) setupDrawAA();
2217    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
2218    setupDrawColorFilter();
2219    setupDrawShader();
2220    setupDrawBlending(isAA, mode);
2221    setupDrawProgram();
2222    setupDrawModelViewIdentity(useOffset);
2223    setupDrawColorUniforms();
2224    setupDrawColorFilterUniforms();
2225    setupDrawShaderIdentityUniforms();
2226
2227    void* vertices = vertexBuffer.getBuffer();
2228    bool force = mCaches.unbindMeshBuffer();
2229    mCaches.bindPositionVertexPointer(true, vertices, isAA ? gAlphaVertexStride : gVertexStride);
2230    mCaches.resetTexCoordsVertexPointer();
2231    mCaches.unbindIndicesBuffer();
2232
2233    int alphaSlot = -1;
2234    if (isAA) {
2235        void* alphaCoords = ((GLbyte*) vertices) + gVertexAlphaOffset;
2236        alphaSlot = mCaches.currentProgram->getAttrib("vtxAlpha");
2237
2238        // TODO: avoid enable/disable in back to back uses of the alpha attribute
2239        glEnableVertexAttribArray(alphaSlot);
2240        glVertexAttribPointer(alphaSlot, 1, GL_FLOAT, GL_FALSE, gAlphaVertexStride, alphaCoords);
2241    }
2242
2243    glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexBuffer.getSize());
2244
2245    if (isAA) {
2246        glDisableVertexAttribArray(alphaSlot);
2247    }
2248
2249    return DrawGlInfo::kStatusDrew;
2250}
2251
2252/**
2253 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to
2254 * that of AA lines in the drawLines() function.  We expand the convex path by a half pixel in
2255 * screen space in all directions. However, instead of using a fragment shader to compute the
2256 * translucency of the color from its position, we simply use a varying parameter to define how far
2257 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used.
2258 *
2259 * Doesn't yet support joins, caps, or path effects.
2260 */
2261status_t OpenGLRenderer::drawConvexPath(const SkPath& path, SkPaint* paint) {
2262    VertexBuffer vertexBuffer;
2263    // TODO: try clipping large paths to viewport
2264    PathTessellator::tessellatePath(path, paint, mSnapshot->transform, vertexBuffer);
2265
2266    SkRect bounds = path.getBounds();
2267    PathTessellator::expandBoundsForStroke(bounds, paint, false);
2268    dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, *mSnapshot->transform);
2269
2270    return drawVertexBuffer(vertexBuffer, paint);
2271}
2272
2273/**
2274 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha
2275 * and additional geometry for defining an alpha slope perimeter.
2276 *
2277 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some
2278 * unexpected results, and may vary between hardware devices. Previously we used a varying-base
2279 * in-shader alpha region, but found it to be taxing on some GPUs.
2280 *
2281 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce
2282 * memory transfer by removing need for degenerate vertices.
2283 */
2284status_t OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
2285    if (mSnapshot->isIgnored() || count < 4) return DrawGlInfo::kStatusDone;
2286
2287    count &= ~0x3; // round down to nearest four
2288
2289    VertexBuffer buffer;
2290    SkRect bounds;
2291    PathTessellator::tessellateLines(points, count, paint, mSnapshot->transform, bounds, buffer);
2292
2293    if (quickReject(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom)) {
2294        return DrawGlInfo::kStatusDone;
2295    }
2296
2297    dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, *mSnapshot->transform);
2298
2299    bool useOffset = !paint->isAntiAlias();
2300    return drawVertexBuffer(buffer, paint, useOffset);
2301}
2302
2303status_t OpenGLRenderer::drawPoints(float* points, int count, SkPaint* paint) {
2304    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2305
2306    // TODO: The paint's cap style defines whether the points are square or circular
2307    // TODO: Handle AA for round points
2308
2309    // A stroke width of 0 has a special meaning in Skia:
2310    // it draws an unscaled 1px point
2311    float strokeWidth = paint->getStrokeWidth();
2312    const bool isHairLine = paint->getStrokeWidth() == 0.0f;
2313    if (isHairLine) {
2314        // Now that we know it's hairline, we can set the effective width, to be used later
2315        strokeWidth = 1.0f;
2316    }
2317    const float halfWidth = strokeWidth / 2;
2318
2319    int alpha;
2320    SkXfermode::Mode mode;
2321    getAlphaAndMode(paint, &alpha, &mode);
2322
2323    int verticesCount = count >> 1;
2324    int generatedVerticesCount = 0;
2325
2326    TextureVertex pointsData[verticesCount];
2327    TextureVertex* vertex = &pointsData[0];
2328
2329    // TODO: We should optimize this method to not generate vertices for points
2330    // that lie outside of the clip.
2331    mCaches.enableScissor();
2332
2333    setupDraw();
2334    setupDrawNoTexture();
2335    setupDrawPoint(strokeWidth);
2336    setupDrawColor(paint->getColor(), alpha);
2337    setupDrawColorFilter();
2338    setupDrawShader();
2339    setupDrawBlending(mode);
2340    setupDrawProgram();
2341    setupDrawModelViewIdentity(true);
2342    setupDrawColorUniforms();
2343    setupDrawColorFilterUniforms();
2344    setupDrawPointUniforms();
2345    setupDrawShaderIdentityUniforms();
2346    setupDrawMesh(vertex);
2347
2348    for (int i = 0; i < count; i += 2) {
2349        TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
2350        generatedVerticesCount++;
2351
2352        float left = points[i] - halfWidth;
2353        float right = points[i] + halfWidth;
2354        float top = points[i + 1] - halfWidth;
2355        float bottom = points [i + 1] + halfWidth;
2356
2357        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
2358    }
2359
2360    glDrawArrays(GL_POINTS, 0, generatedVerticesCount);
2361
2362    return DrawGlInfo::kStatusDrew;
2363}
2364
2365status_t OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
2366    // No need to check against the clip, we fill the clip region
2367    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2368
2369    Rect& clip(*mSnapshot->clipRect);
2370    clip.snapToPixelBoundaries();
2371
2372    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
2373
2374    return DrawGlInfo::kStatusDrew;
2375}
2376
2377status_t OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture,
2378        SkPaint* paint) {
2379    if (!texture) return DrawGlInfo::kStatusDone;
2380    const AutoTexture autoCleanup(texture);
2381
2382    const float x = left + texture->left - texture->offset;
2383    const float y = top + texture->top - texture->offset;
2384
2385    drawPathTexture(texture, x, y, paint);
2386
2387    return DrawGlInfo::kStatusDrew;
2388}
2389
2390status_t OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
2391        float rx, float ry, SkPaint* p) {
2392    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2393        return DrawGlInfo::kStatusDone;
2394    }
2395
2396    if (p->getPathEffect() != 0) {
2397        mCaches.activeTexture(0);
2398        const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect(
2399                right - left, bottom - top, rx, ry, p);
2400        return drawShape(left, top, texture, p);
2401    }
2402
2403    SkPath path;
2404    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2405    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2406        float outset = p->getStrokeWidth() / 2;
2407        rect.outset(outset, outset);
2408        rx += outset;
2409        ry += outset;
2410    }
2411    path.addRoundRect(rect, rx, ry);
2412    return drawConvexPath(path, p);
2413}
2414
2415status_t OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* p) {
2416    if (mSnapshot->isIgnored() || quickRejectPreStroke(x - radius, y - radius,
2417            x + radius, y + radius, p)) {
2418        return DrawGlInfo::kStatusDone;
2419    }
2420    if (p->getPathEffect() != 0) {
2421        mCaches.activeTexture(0);
2422        const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, p);
2423        return drawShape(x - radius, y - radius, texture, p);
2424    }
2425
2426    SkPath path;
2427    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2428        path.addCircle(x, y, radius + p->getStrokeWidth() / 2);
2429    } else {
2430        path.addCircle(x, y, radius);
2431    }
2432    return drawConvexPath(path, p);
2433}
2434
2435status_t OpenGLRenderer::drawOval(float left, float top, float right, float bottom,
2436        SkPaint* p) {
2437    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2438        return DrawGlInfo::kStatusDone;
2439    }
2440
2441    if (p->getPathEffect() != 0) {
2442        mCaches.activeTexture(0);
2443        const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, p);
2444        return drawShape(left, top, texture, p);
2445    }
2446
2447    SkPath path;
2448    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2449    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2450        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2451    }
2452    path.addOval(rect);
2453    return drawConvexPath(path, p);
2454}
2455
2456status_t OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
2457        float startAngle, float sweepAngle, bool useCenter, SkPaint* p) {
2458    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2459        return DrawGlInfo::kStatusDone;
2460    }
2461
2462    if (fabs(sweepAngle) >= 360.0f) {
2463        return drawOval(left, top, right, bottom, p);
2464    }
2465
2466    // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180)
2467    if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != 0 || useCenter) {
2468        mCaches.activeTexture(0);
2469        const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top,
2470                startAngle, sweepAngle, useCenter, p);
2471        return drawShape(left, top, texture, p);
2472    }
2473
2474    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2475    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2476        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2477    }
2478
2479    SkPath path;
2480    if (useCenter) {
2481        path.moveTo(rect.centerX(), rect.centerY());
2482    }
2483    path.arcTo(rect, startAngle, sweepAngle, !useCenter);
2484    if (useCenter) {
2485        path.close();
2486    }
2487    return drawConvexPath(path, p);
2488}
2489
2490// See SkPaintDefaults.h
2491#define SkPaintDefaults_MiterLimit SkIntToScalar(4)
2492
2493status_t OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
2494    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2495        return DrawGlInfo::kStatusDone;
2496    }
2497
2498    if (p->getStyle() != SkPaint::kFill_Style) {
2499        // only fill style is supported by drawConvexPath, since others have to handle joins
2500        if (p->getPathEffect() != 0 || p->getStrokeJoin() != SkPaint::kMiter_Join ||
2501                p->getStrokeMiter() != SkPaintDefaults_MiterLimit) {
2502            mCaches.activeTexture(0);
2503            const PathTexture* texture =
2504                    mCaches.rectShapeCache.getRect(right - left, bottom - top, p);
2505            return drawShape(left, top, texture, p);
2506        }
2507
2508        SkPath path;
2509        SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2510        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2511            rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2512        }
2513        path.addRect(rect);
2514        return drawConvexPath(path, p);
2515    }
2516
2517    if (p->isAntiAlias() && !mSnapshot->transform->isSimple()) {
2518        SkPath path;
2519        path.addRect(left, top, right, bottom);
2520        return drawConvexPath(path, p);
2521    } else {
2522        drawColorRect(left, top, right, bottom, p->getColor(), getXfermode(p->getXfermode()));
2523        return DrawGlInfo::kStatusDrew;
2524    }
2525}
2526
2527void OpenGLRenderer::drawTextShadow(SkPaint* paint, const char* text, int bytesCount, int count,
2528        const float* positions, FontRenderer& fontRenderer, int alpha, SkXfermode::Mode mode,
2529        float x, float y) {
2530    mCaches.activeTexture(0);
2531
2532    // NOTE: The drop shadow will not perform gamma correction
2533    //       if shader-based correction is enabled
2534    mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2535    const ShadowTexture* shadow = mCaches.dropShadowCache.get(
2536            paint, text, bytesCount, count, mDrawModifiers.mShadowRadius, positions);
2537    const AutoTexture autoCleanup(shadow);
2538
2539    const float sx = x - shadow->left + mDrawModifiers.mShadowDx;
2540    const float sy = y - shadow->top + mDrawModifiers.mShadowDy;
2541
2542    const int shadowAlpha = ((mDrawModifiers.mShadowColor >> 24) & 0xFF) * mSnapshot->alpha;
2543    int shadowColor = mDrawModifiers.mShadowColor;
2544    if (mDrawModifiers.mShader) {
2545        shadowColor = 0xffffffff;
2546    }
2547
2548    setupDraw();
2549    setupDrawWithTexture(true);
2550    setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
2551    setupDrawColorFilter();
2552    setupDrawShader();
2553    setupDrawBlending(true, mode);
2554    setupDrawProgram();
2555    setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height);
2556    setupDrawTexture(shadow->id);
2557    setupDrawPureColorUniforms();
2558    setupDrawColorFilterUniforms();
2559    setupDrawShaderUniforms();
2560    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2561
2562    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2563}
2564
2565status_t OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count,
2566        const float* positions, SkPaint* paint) {
2567    if (text == NULL || count == 0 || mSnapshot->isIgnored() ||
2568            (paint->getAlpha() * mSnapshot->alpha == 0 && paint->getXfermode() == NULL)) {
2569        return DrawGlInfo::kStatusDone;
2570    }
2571
2572    // NOTE: Skia does not support perspective transform on drawPosText yet
2573    if (!mSnapshot->transform->isSimple()) {
2574        return DrawGlInfo::kStatusDone;
2575    }
2576
2577    float x = 0.0f;
2578    float y = 0.0f;
2579    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
2580    if (pureTranslate) {
2581        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2582        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2583    }
2584
2585    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2586    fontRenderer.setFont(paint, *mSnapshot->transform);
2587
2588    int alpha;
2589    SkXfermode::Mode mode;
2590    getAlphaAndMode(paint, &alpha, &mode);
2591
2592    if (CC_UNLIKELY(mDrawModifiers.mHasShadow)) {
2593        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2594                alpha, mode, 0.0f, 0.0f);
2595    }
2596
2597    // Pick the appropriate texture filtering
2598    bool linearFilter = mSnapshot->transform->changesBounds();
2599    if (pureTranslate && !linearFilter) {
2600        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2601    }
2602
2603    mCaches.activeTexture(0);
2604    setupDraw();
2605    setupDrawTextGamma(paint);
2606    setupDrawDirtyRegionsDisabled();
2607    setupDrawWithTexture(true);
2608    setupDrawAlpha8Color(paint->getColor(), alpha);
2609    setupDrawColorFilter();
2610    setupDrawShader();
2611    setupDrawBlending(true, mode);
2612    setupDrawProgram();
2613    setupDrawModelView(x, y, x, y, pureTranslate, true);
2614    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2615    setupDrawPureColorUniforms();
2616    setupDrawColorFilterUniforms();
2617    setupDrawShaderUniforms(pureTranslate);
2618    setupDrawTextGammaUniforms();
2619
2620    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
2621    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2622
2623    const bool hasActiveLayer = hasLayer();
2624
2625    if (fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2626            positions, hasActiveLayer ? &bounds : NULL)) {
2627        if (hasActiveLayer) {
2628            if (!pureTranslate) {
2629                mSnapshot->transform->mapRect(bounds);
2630            }
2631            dirtyLayerUnchecked(bounds, getRegion());
2632        }
2633    }
2634
2635    return DrawGlInfo::kStatusDrew;
2636}
2637
2638status_t OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
2639        float x, float y, const float* positions, SkPaint* paint, float length) {
2640    if (text == NULL || count == 0 || mSnapshot->isIgnored() ||
2641            (paint->getAlpha() * mSnapshot->alpha == 0 && paint->getXfermode() == NULL)) {
2642        return DrawGlInfo::kStatusDone;
2643    }
2644
2645    if (length < 0.0f) length = paint->measureText(text, bytesCount);
2646    switch (paint->getTextAlign()) {
2647        case SkPaint::kCenter_Align:
2648            x -= length / 2.0f;
2649            break;
2650        case SkPaint::kRight_Align:
2651            x -= length;
2652            break;
2653        default:
2654            break;
2655    }
2656
2657    SkPaint::FontMetrics metrics;
2658    paint->getFontMetrics(&metrics, 0.0f);
2659    if (quickReject(x, y + metrics.fTop, x + length, y + metrics.fBottom)) {
2660        return DrawGlInfo::kStatusDone;
2661    }
2662
2663#if DEBUG_GLYPHS
2664    ALOGD("OpenGLRenderer drawText() with FontID=%d",
2665            SkTypeface::UniqueID(paint->getTypeface()));
2666#endif
2667
2668    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2669    fontRenderer.setFont(paint, *mSnapshot->transform);
2670
2671    const float oldX = x;
2672    const float oldY = y;
2673    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
2674    if (CC_LIKELY(pureTranslate)) {
2675        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2676        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2677    }
2678
2679    int alpha;
2680    SkXfermode::Mode mode;
2681    getAlphaAndMode(paint, &alpha, &mode);
2682
2683    if (CC_UNLIKELY(mDrawModifiers.mHasShadow)) {
2684        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, alpha, mode,
2685                oldX, oldY);
2686    }
2687
2688    // Pick the appropriate texture filtering
2689    bool linearFilter = mSnapshot->transform->changesBounds();
2690    if (pureTranslate && !linearFilter) {
2691        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2692    }
2693
2694    // The font renderer will always use texture unit 0
2695    mCaches.activeTexture(0);
2696    setupDraw();
2697    setupDrawTextGamma(paint);
2698    setupDrawDirtyRegionsDisabled();
2699    setupDrawWithTexture(true);
2700    setupDrawAlpha8Color(paint->getColor(), alpha);
2701    setupDrawColorFilter();
2702    setupDrawShader();
2703    setupDrawBlending(true, mode);
2704    setupDrawProgram();
2705    setupDrawModelView(x, y, x, y, pureTranslate, true);
2706    // See comment above; the font renderer must use texture unit 0
2707    // assert(mTextureUnit == 0)
2708    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2709    setupDrawPureColorUniforms();
2710    setupDrawColorFilterUniforms();
2711    setupDrawShaderUniforms(pureTranslate);
2712    setupDrawTextGammaUniforms();
2713
2714    const Rect* clip = pureTranslate ? mSnapshot->clipRect :
2715            (mSnapshot->hasPerspectiveTransform() ? NULL : &mSnapshot->getLocalClip());
2716    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2717
2718    const bool hasActiveLayer = hasLayer();
2719
2720    bool status;
2721    if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) {
2722        SkPaint paintCopy(*paint);
2723        paintCopy.setTextAlign(SkPaint::kLeft_Align);
2724        status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y,
2725                positions, hasActiveLayer ? &bounds : NULL);
2726    } else {
2727        status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2728                positions, hasActiveLayer ? &bounds : NULL);
2729    }
2730
2731    if (status && hasActiveLayer) {
2732        if (!pureTranslate) {
2733            mSnapshot->transform->mapRect(bounds);
2734        }
2735        dirtyLayerUnchecked(bounds, getRegion());
2736    }
2737
2738    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
2739
2740    return DrawGlInfo::kStatusDrew;
2741}
2742
2743status_t OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count, SkPath* path,
2744        float hOffset, float vOffset, SkPaint* paint) {
2745    if (text == NULL || count == 0 || mSnapshot->isIgnored() ||
2746            (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
2747        return DrawGlInfo::kStatusDone;
2748    }
2749
2750    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2751    fontRenderer.setFont(paint, *mSnapshot->transform);
2752
2753    int alpha;
2754    SkXfermode::Mode mode;
2755    getAlphaAndMode(paint, &alpha, &mode);
2756
2757    mCaches.activeTexture(0);
2758    setupDraw();
2759    setupDrawTextGamma(paint);
2760    setupDrawDirtyRegionsDisabled();
2761    setupDrawWithTexture(true);
2762    setupDrawAlpha8Color(paint->getColor(), alpha);
2763    setupDrawColorFilter();
2764    setupDrawShader();
2765    setupDrawBlending(true, mode);
2766    setupDrawProgram();
2767    setupDrawModelView(0.0f, 0.0f, 0.0f, 0.0f, false, true);
2768    setupDrawTexture(fontRenderer.getTexture(true));
2769    setupDrawPureColorUniforms();
2770    setupDrawColorFilterUniforms();
2771    setupDrawShaderUniforms(false);
2772    setupDrawTextGammaUniforms();
2773
2774    const Rect* clip = &mSnapshot->getLocalClip();
2775    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2776
2777    const bool hasActiveLayer = hasLayer();
2778
2779    if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path,
2780            hOffset, vOffset, hasActiveLayer ? &bounds : NULL)) {
2781        if (hasActiveLayer) {
2782            mSnapshot->transform->mapRect(bounds);
2783            dirtyLayerUnchecked(bounds, getRegion());
2784        }
2785    }
2786
2787    return DrawGlInfo::kStatusDrew;
2788}
2789
2790status_t OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
2791    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2792
2793    mCaches.activeTexture(0);
2794
2795    const PathTexture* texture = mCaches.pathCache.get(path, paint);
2796    if (!texture) return DrawGlInfo::kStatusDone;
2797    const AutoTexture autoCleanup(texture);
2798
2799    const float x = texture->left - texture->offset;
2800    const float y = texture->top - texture->offset;
2801
2802    drawPathTexture(texture, x, y, paint);
2803
2804    return DrawGlInfo::kStatusDrew;
2805}
2806
2807status_t OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) {
2808    if (!layer) {
2809        return DrawGlInfo::kStatusDone;
2810    }
2811
2812    mat4* transform = NULL;
2813    if (layer->isTextureLayer()) {
2814        transform = &layer->getTransform();
2815        if (!transform->isIdentity()) {
2816            save(0);
2817            mSnapshot->transform->multiply(*transform);
2818        }
2819    }
2820
2821    Rect transformed;
2822    Rect clip;
2823    const bool rejected = quickRejectNoScissor(x, y,
2824            x + layer->layer.getWidth(), y + layer->layer.getHeight(), transformed, clip);
2825
2826    if (rejected) {
2827        if (transform && !transform->isIdentity()) {
2828            restore();
2829        }
2830        return DrawGlInfo::kStatusDone;
2831    }
2832
2833    updateLayer(layer, true);
2834
2835    mCaches.setScissorEnabled(mScissorOptimizationDisabled || !clip.contains(transformed));
2836    mCaches.activeTexture(0);
2837
2838    if (CC_LIKELY(!layer->region.isEmpty())) {
2839        SkiaColorFilter* oldFilter = mDrawModifiers.mColorFilter;
2840        mDrawModifiers.mColorFilter = layer->getColorFilter();
2841
2842        if (layer->region.isRect()) {
2843            composeLayerRect(layer, layer->regionRect);
2844        } else if (layer->mesh) {
2845            const float a = layer->getAlpha() / 255.0f;
2846            setupDraw();
2847            setupDrawWithTexture();
2848            setupDrawColor(a, a, a, a);
2849            setupDrawColorFilter();
2850            setupDrawBlending(layer->isBlend() || a < 1.0f, layer->getMode(), false);
2851            setupDrawProgram();
2852            setupDrawPureColorUniforms();
2853            setupDrawColorFilterUniforms();
2854            setupDrawTexture(layer->getTexture());
2855            if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) {
2856                int tx = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2857                int ty = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2858
2859                layer->setFilter(GL_NEAREST);
2860                setupDrawModelViewTranslate(tx, ty,
2861                        tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true);
2862            } else {
2863                layer->setFilter(GL_LINEAR);
2864                setupDrawModelViewTranslate(x, y,
2865                        x + layer->layer.getWidth(), y + layer->layer.getHeight());
2866            }
2867            setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]);
2868
2869            glDrawElements(GL_TRIANGLES, layer->meshElementCount,
2870                    GL_UNSIGNED_SHORT, layer->meshIndices);
2871
2872            finishDrawTexture();
2873
2874#if DEBUG_LAYERS_AS_REGIONS
2875            drawRegionRects(layer->region);
2876#endif
2877        }
2878
2879        mDrawModifiers.mColorFilter = oldFilter;
2880
2881        if (layer->debugDrawUpdate) {
2882            layer->debugDrawUpdate = false;
2883            drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(),
2884                    0x7f00ff00, SkXfermode::kSrcOver_Mode);
2885        }
2886    }
2887
2888    if (transform && !transform->isIdentity()) {
2889        restore();
2890    }
2891
2892    return DrawGlInfo::kStatusDrew;
2893}
2894
2895///////////////////////////////////////////////////////////////////////////////
2896// Shaders
2897///////////////////////////////////////////////////////////////////////////////
2898
2899void OpenGLRenderer::resetShader() {
2900    mDrawModifiers.mShader = NULL;
2901}
2902
2903void OpenGLRenderer::setupShader(SkiaShader* shader) {
2904    mDrawModifiers.mShader = shader;
2905    if (mDrawModifiers.mShader) {
2906        mDrawModifiers.mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
2907    }
2908}
2909
2910///////////////////////////////////////////////////////////////////////////////
2911// Color filters
2912///////////////////////////////////////////////////////////////////////////////
2913
2914void OpenGLRenderer::resetColorFilter() {
2915    mDrawModifiers.mColorFilter = NULL;
2916}
2917
2918void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
2919    mDrawModifiers.mColorFilter = filter;
2920}
2921
2922///////////////////////////////////////////////////////////////////////////////
2923// Drop shadow
2924///////////////////////////////////////////////////////////////////////////////
2925
2926void OpenGLRenderer::resetShadow() {
2927    mDrawModifiers.mHasShadow = false;
2928}
2929
2930void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
2931    mDrawModifiers.mHasShadow = true;
2932    mDrawModifiers.mShadowRadius = radius;
2933    mDrawModifiers.mShadowDx = dx;
2934    mDrawModifiers.mShadowDy = dy;
2935    mDrawModifiers.mShadowColor = color;
2936}
2937
2938///////////////////////////////////////////////////////////////////////////////
2939// Draw filters
2940///////////////////////////////////////////////////////////////////////////////
2941
2942void OpenGLRenderer::resetPaintFilter() {
2943    mDrawModifiers.mHasDrawFilter = false;
2944}
2945
2946void OpenGLRenderer::setupPaintFilter(int clearBits, int setBits) {
2947    mDrawModifiers.mHasDrawFilter = true;
2948    mDrawModifiers.mPaintFilterClearBits = clearBits & SkPaint::kAllFlags;
2949    mDrawModifiers.mPaintFilterSetBits = setBits & SkPaint::kAllFlags;
2950}
2951
2952SkPaint* OpenGLRenderer::filterPaint(SkPaint* paint) {
2953    if (CC_LIKELY(!mDrawModifiers.mHasDrawFilter || !paint)) return paint;
2954
2955    uint32_t flags = paint->getFlags();
2956
2957    mFilteredPaint = *paint;
2958    mFilteredPaint.setFlags((flags & ~mDrawModifiers.mPaintFilterClearBits) |
2959            mDrawModifiers.mPaintFilterSetBits);
2960
2961    return &mFilteredPaint;
2962}
2963
2964///////////////////////////////////////////////////////////////////////////////
2965// Drawing implementation
2966///////////////////////////////////////////////////////////////////////////////
2967
2968void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
2969        float x, float y, SkPaint* paint) {
2970    if (quickReject(x, y, x + texture->width, y + texture->height)) {
2971        return;
2972    }
2973
2974    int alpha;
2975    SkXfermode::Mode mode;
2976    getAlphaAndMode(paint, &alpha, &mode);
2977
2978    setupDraw();
2979    setupDrawWithTexture(true);
2980    setupDrawAlpha8Color(paint->getColor(), alpha);
2981    setupDrawColorFilter();
2982    setupDrawShader();
2983    setupDrawBlending(true, mode);
2984    setupDrawProgram();
2985    setupDrawModelView(x, y, x + texture->width, y + texture->height);
2986    setupDrawTexture(texture->id);
2987    setupDrawPureColorUniforms();
2988    setupDrawColorFilterUniforms();
2989    setupDrawShaderUniforms();
2990    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2991
2992    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2993
2994    finishDrawTexture();
2995}
2996
2997// Same values used by Skia
2998#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
2999#define kStdUnderline_Offset    (1.0f / 9.0f)
3000#define kStdUnderline_Thickness (1.0f / 18.0f)
3001
3002void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
3003        float x, float y, SkPaint* paint) {
3004    // Handle underline and strike-through
3005    uint32_t flags = paint->getFlags();
3006    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
3007        SkPaint paintCopy(*paint);
3008        float underlineWidth = length;
3009        // If length is > 0.0f, we already measured the text for the text alignment
3010        if (length <= 0.0f) {
3011            underlineWidth = paintCopy.measureText(text, bytesCount);
3012        }
3013
3014        if (CC_LIKELY(underlineWidth > 0.0f)) {
3015            const float textSize = paintCopy.getTextSize();
3016            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
3017
3018            const float left = x;
3019            float top = 0.0f;
3020
3021            int linesCount = 0;
3022            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
3023            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
3024
3025            const int pointsCount = 4 * linesCount;
3026            float points[pointsCount];
3027            int currentPoint = 0;
3028
3029            if (flags & SkPaint::kUnderlineText_Flag) {
3030                top = y + textSize * kStdUnderline_Offset;
3031                points[currentPoint++] = left;
3032                points[currentPoint++] = top;
3033                points[currentPoint++] = left + underlineWidth;
3034                points[currentPoint++] = top;
3035            }
3036
3037            if (flags & SkPaint::kStrikeThruText_Flag) {
3038                top = y + textSize * kStdStrikeThru_Offset;
3039                points[currentPoint++] = left;
3040                points[currentPoint++] = top;
3041                points[currentPoint++] = left + underlineWidth;
3042                points[currentPoint++] = top;
3043            }
3044
3045            paintCopy.setStrokeWidth(strokeWidth);
3046
3047            drawLines(&points[0], pointsCount, &paintCopy);
3048        }
3049    }
3050}
3051
3052status_t OpenGLRenderer::drawRects(const float* rects, int count, SkPaint* paint) {
3053    if (mSnapshot->isIgnored()) {
3054        return DrawGlInfo::kStatusDone;
3055    }
3056
3057    int color = paint->getColor();
3058    // If a shader is set, preserve only the alpha
3059    if (mDrawModifiers.mShader) {
3060        color |= 0x00ffffff;
3061    }
3062    SkXfermode::Mode mode = getXfermode(paint->getXfermode());
3063
3064    return drawColorRects(rects, count, color, mode);
3065}
3066
3067status_t OpenGLRenderer::drawColorRects(const float* rects, int count, int color,
3068        SkXfermode::Mode mode, bool ignoreTransform, bool dirty, bool clip) {
3069
3070    float left = FLT_MAX;
3071    float top = FLT_MAX;
3072    float right = FLT_MIN;
3073    float bottom = FLT_MIN;
3074
3075    int vertexCount = 0;
3076    Vertex mesh[count * 6];
3077    Vertex* vertex = mesh;
3078
3079    for (int index = 0; index < count; index += 4) {
3080        float l = rects[index + 0];
3081        float t = rects[index + 1];
3082        float r = rects[index + 2];
3083        float b = rects[index + 3];
3084
3085        if (ignoreTransform || !quickRejectNoScissor(left, top, right, bottom)) {
3086            Vertex::set(vertex++, l, b);
3087            Vertex::set(vertex++, l, t);
3088            Vertex::set(vertex++, r, t);
3089            Vertex::set(vertex++, l, b);
3090            Vertex::set(vertex++, r, t);
3091            Vertex::set(vertex++, r, b);
3092
3093            vertexCount += 6;
3094
3095            left = fminf(left, l);
3096            top = fminf(top, t);
3097            right = fmaxf(right, r);
3098            bottom = fmaxf(bottom, b);
3099        }
3100    }
3101
3102    if (count == 0 || (clip && quickReject(left, top, right, bottom))) {
3103        return DrawGlInfo::kStatusDone;
3104    }
3105
3106    setupDraw();
3107    setupDrawNoTexture();
3108    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
3109    setupDrawShader();
3110    setupDrawColorFilter();
3111    setupDrawBlending(mode);
3112    setupDrawProgram();
3113    setupDrawDirtyRegionsDisabled();
3114    setupDrawModelView(0.0f, 0.0f, 1.0f, 1.0f, ignoreTransform, true);
3115    setupDrawColorUniforms();
3116    setupDrawShaderUniforms();
3117    setupDrawColorFilterUniforms();
3118    setupDrawVertices((GLvoid*) &mesh[0].position[0]);
3119
3120    if (dirty && hasLayer()) {
3121        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
3122    }
3123
3124    glDrawArrays(GL_TRIANGLES, 0, vertexCount);
3125
3126    return DrawGlInfo::kStatusDrew;
3127}
3128
3129void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
3130        int color, SkXfermode::Mode mode, bool ignoreTransform) {
3131    // If a shader is set, preserve only the alpha
3132    if (mDrawModifiers.mShader) {
3133        color |= 0x00ffffff;
3134    }
3135
3136    setupDraw();
3137    setupDrawNoTexture();
3138    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
3139    setupDrawShader();
3140    setupDrawColorFilter();
3141    setupDrawBlending(mode);
3142    setupDrawProgram();
3143    setupDrawModelView(left, top, right, bottom, ignoreTransform);
3144    setupDrawColorUniforms();
3145    setupDrawShaderUniforms(ignoreTransform);
3146    setupDrawColorFilterUniforms();
3147    setupDrawSimpleMesh();
3148
3149    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
3150}
3151
3152void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3153        Texture* texture, SkPaint* paint) {
3154    int alpha;
3155    SkXfermode::Mode mode;
3156    getAlphaAndMode(paint, &alpha, &mode);
3157
3158    texture->setWrap(GL_CLAMP_TO_EDGE, true);
3159
3160    if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) {
3161        const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
3162        const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
3163
3164        texture->setFilter(GL_NEAREST, true);
3165        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
3166                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
3167                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
3168    } else {
3169        texture->setFilter(FILTER(paint), true);
3170        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
3171                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
3172                GL_TRIANGLE_STRIP, gMeshCount);
3173    }
3174}
3175
3176void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3177        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
3178    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
3179            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
3180}
3181
3182void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
3183        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
3184        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3185        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
3186
3187    setupDraw();
3188    setupDrawWithTexture();
3189    setupDrawColor(alpha, alpha, alpha, alpha);
3190    setupDrawColorFilter();
3191    setupDrawBlending(blend, mode, swapSrcDst);
3192    setupDrawProgram();
3193    if (!dirty) setupDrawDirtyRegionsDisabled();
3194    if (!ignoreScale) {
3195        setupDrawModelView(left, top, right, bottom, ignoreTransform);
3196    } else {
3197        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
3198    }
3199    setupDrawTexture(texture);
3200    setupDrawPureColorUniforms();
3201    setupDrawColorFilterUniforms();
3202    setupDrawMesh(vertices, texCoords, vbo);
3203
3204    glDrawArrays(drawMode, 0, elementsCount);
3205
3206    finishDrawTexture();
3207}
3208
3209void OpenGLRenderer::drawAlpha8TextureMesh(float left, float top, float right, float bottom,
3210        GLuint texture, bool hasColor, int color, int alpha, SkXfermode::Mode mode,
3211        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3212        bool ignoreTransform, bool dirty) {
3213
3214    setupDraw();
3215    setupDrawWithTexture(true);
3216    if (hasColor) {
3217        setupDrawAlpha8Color(color, alpha);
3218    }
3219    setupDrawColorFilter();
3220    setupDrawShader();
3221    setupDrawBlending(true, mode);
3222    setupDrawProgram();
3223    if (!dirty) setupDrawDirtyRegionsDisabled();
3224    setupDrawModelView(left, top, right, bottom, ignoreTransform);
3225    setupDrawTexture(texture);
3226    setupDrawPureColorUniforms();
3227    setupDrawColorFilterUniforms();
3228    setupDrawShaderUniforms();
3229    setupDrawMesh(vertices, texCoords);
3230
3231    glDrawArrays(drawMode, 0, elementsCount);
3232
3233    finishDrawTexture();
3234}
3235
3236void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
3237        ProgramDescription& description, bool swapSrcDst) {
3238    blend = blend || mode != SkXfermode::kSrcOver_Mode;
3239
3240    if (blend) {
3241        // These blend modes are not supported by OpenGL directly and have
3242        // to be implemented using shaders. Since the shader will perform
3243        // the blending, turn blending off here
3244        // If the blend mode cannot be implemented using shaders, fall
3245        // back to the default SrcOver blend mode instead
3246        if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) {
3247            if (CC_UNLIKELY(mExtensions.hasFramebufferFetch())) {
3248                description.framebufferMode = mode;
3249                description.swapSrcDst = swapSrcDst;
3250
3251                if (mCaches.blend) {
3252                    glDisable(GL_BLEND);
3253                    mCaches.blend = false;
3254                }
3255
3256                return;
3257            } else {
3258                mode = SkXfermode::kSrcOver_Mode;
3259            }
3260        }
3261
3262        if (!mCaches.blend) {
3263            glEnable(GL_BLEND);
3264        }
3265
3266        GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
3267        GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
3268
3269        if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
3270            glBlendFunc(sourceMode, destMode);
3271            mCaches.lastSrcMode = sourceMode;
3272            mCaches.lastDstMode = destMode;
3273        }
3274    } else if (mCaches.blend) {
3275        glDisable(GL_BLEND);
3276    }
3277    mCaches.blend = blend;
3278}
3279
3280bool OpenGLRenderer::useProgram(Program* program) {
3281    if (!program->isInUse()) {
3282        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
3283        program->use();
3284        mCaches.currentProgram = program;
3285        return false;
3286    }
3287    return true;
3288}
3289
3290void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
3291    TextureVertex* v = &mMeshVertices[0];
3292    TextureVertex::setUV(v++, u1, v1);
3293    TextureVertex::setUV(v++, u2, v1);
3294    TextureVertex::setUV(v++, u1, v2);
3295    TextureVertex::setUV(v++, u2, v2);
3296}
3297
3298void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
3299    getAlphaAndModeDirect(paint, alpha,  mode);
3300    *alpha *= mSnapshot->alpha;
3301}
3302
3303}; // namespace uirenderer
3304}; // namespace android
3305