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