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