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