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