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