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