OpenGLRenderer.cpp revision 67ffc36a79ce3a9a0b5da28b65123864b7d2597f
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 <SkTypeface.h>
25
26#include <utils/Log.h>
27#include <utils/StopWatch.h>
28
29#include <private/hwui/DrawGlInfo.h>
30
31#include <ui/Rect.h>
32
33#include "OpenGLRenderer.h"
34#include "DisplayListRenderer.h"
35#include "Vector.h"
36
37namespace android {
38namespace uirenderer {
39
40///////////////////////////////////////////////////////////////////////////////
41// Defines
42///////////////////////////////////////////////////////////////////////////////
43
44#define RAD_TO_DEG (180.0f / 3.14159265f)
45#define MIN_ANGLE 0.001f
46
47// TODO: This should be set in properties
48#define ALPHA_THRESHOLD (0x7f / PANEL_BIT_DEPTH)
49
50///////////////////////////////////////////////////////////////////////////////
51// Globals
52///////////////////////////////////////////////////////////////////////////////
53
54/**
55 * Structure mapping Skia xfermodes to OpenGL blending factors.
56 */
57struct Blender {
58    SkXfermode::Mode mode;
59    GLenum src;
60    GLenum dst;
61}; // struct Blender
62
63// In this array, the index of each Blender equals the value of the first
64// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
65static const Blender gBlends[] = {
66    { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
67    { SkXfermode::kSrc_Mode,     GL_ONE,                  GL_ZERO },
68    { SkXfermode::kDst_Mode,     GL_ZERO,                 GL_ONE },
69    { SkXfermode::kSrcOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
70    { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
71    { SkXfermode::kSrcIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
72    { SkXfermode::kDstIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
73    { SkXfermode::kSrcOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
74    { SkXfermode::kDstOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
75    { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
76    { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
77    { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
78};
79
80// This array contains the swapped version of each SkXfermode. For instance
81// this array's SrcOver blending mode is actually DstOver. You can refer to
82// createLayer() for more information on the purpose of this array.
83static const Blender gBlendsSwap[] = {
84    { SkXfermode::kClear_Mode,   GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
85    { SkXfermode::kSrc_Mode,     GL_ZERO,                 GL_ONE },
86    { SkXfermode::kDst_Mode,     GL_ONE,                  GL_ZERO },
87    { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
88    { SkXfermode::kDstOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
89    { SkXfermode::kSrcIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
90    { SkXfermode::kDstIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
91    { SkXfermode::kSrcOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
92    { SkXfermode::kDstOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
93    { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
94    { SkXfermode::kDstATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
95    { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
96};
97
98static const GLenum gTextureUnits[] = {
99    GL_TEXTURE0,
100    GL_TEXTURE1,
101    GL_TEXTURE2
102};
103
104///////////////////////////////////////////////////////////////////////////////
105// Constructors/destructor
106///////////////////////////////////////////////////////////////////////////////
107
108OpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) {
109    mShader = NULL;
110    mColorFilter = NULL;
111    mHasShadow = false;
112
113    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
114
115    mFirstSnapshot = new Snapshot;
116}
117
118OpenGLRenderer::~OpenGLRenderer() {
119    // The context has already been destroyed at this point, do not call
120    // GL APIs. All GL state should be kept in Caches.h
121}
122
123///////////////////////////////////////////////////////////////////////////////
124// Setup
125///////////////////////////////////////////////////////////////////////////////
126
127void OpenGLRenderer::setViewport(int width, int height) {
128    glViewport(0, 0, width, height);
129    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
130
131    mWidth = width;
132    mHeight = height;
133
134    mFirstSnapshot->height = height;
135    mFirstSnapshot->viewport.set(0, 0, width, height);
136
137    mDirtyClip = false;
138}
139
140void OpenGLRenderer::prepare(bool opaque) {
141    prepareDirty(0.0f, 0.0f, mWidth, mHeight, opaque);
142}
143
144void OpenGLRenderer::prepareDirty(float left, float top, float right, float bottom, bool opaque) {
145    mCaches.clearGarbage();
146
147    mSnapshot = new Snapshot(mFirstSnapshot,
148            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
149    mSnapshot->fbo = getTargetFbo();
150
151    mSaveCount = 1;
152
153    glViewport(0, 0, mWidth, mHeight);
154
155    glDisable(GL_DITHER);
156
157    glEnable(GL_SCISSOR_TEST);
158    glScissor(left, mSnapshot->height - bottom, right - left, bottom - top);
159    mSnapshot->setClip(left, top, right, bottom);
160
161    if (!opaque) {
162        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
163        glClear(GL_COLOR_BUFFER_BIT);
164    }
165}
166
167void OpenGLRenderer::finish() {
168#if DEBUG_OPENGL
169    GLenum status = GL_NO_ERROR;
170    while ((status = glGetError()) != GL_NO_ERROR) {
171        LOGD("GL error from OpenGLRenderer: 0x%x", status);
172        switch (status) {
173            case GL_OUT_OF_MEMORY:
174                LOGE("  OpenGLRenderer is out of memory!");
175                break;
176        }
177    }
178#endif
179#if DEBUG_MEMORY_USAGE
180    mCaches.dumpMemoryUsage();
181#else
182    if (mCaches.getDebugLevel() & kDebugMemory) {
183        mCaches.dumpMemoryUsage();
184    }
185#endif
186}
187
188void OpenGLRenderer::interrupt() {
189    if (mCaches.currentProgram) {
190        if (mCaches.currentProgram->isInUse()) {
191            mCaches.currentProgram->remove();
192            mCaches.currentProgram = NULL;
193        }
194    }
195    mCaches.unbindMeshBuffer();
196}
197
198void OpenGLRenderer::resume() {
199    glViewport(0, 0, mSnapshot->viewport.getWidth(), mSnapshot->viewport.getHeight());
200
201    glEnable(GL_SCISSOR_TEST);
202    dirtyClip();
203
204    glDisable(GL_DITHER);
205
206    glBindFramebuffer(GL_FRAMEBUFFER, getTargetFbo());
207    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
208
209    mCaches.blend = true;
210    glEnable(GL_BLEND);
211    glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
212    glBlendEquation(GL_FUNC_ADD);
213}
214
215bool OpenGLRenderer::callDrawGLFunction(Functor *functor, Rect& dirty) {
216    interrupt();
217    if (mDirtyClip) {
218        setScissorFromClip();
219    }
220
221    Rect clip(*mSnapshot->clipRect);
222    clip.snapToPixelBoundaries();
223
224#if RENDER_LAYERS_AS_REGIONS
225    // Since we don't know what the functor will draw, let's dirty
226    // tne entire clip region
227    if (hasLayer()) {
228        dirtyLayerUnchecked(clip, getRegion());
229    }
230#endif
231
232    DrawGlInfo info;
233    info.clipLeft = clip.left;
234    info.clipTop = clip.top;
235    info.clipRight = clip.right;
236    info.clipBottom = clip.bottom;
237    info.isLayer = hasLayer();
238    getSnapshot()->transform->copyTo(&info.transform[0]);
239
240    status_t result = (*functor)(0, &info);
241
242    if (result != 0) {
243        Rect localDirty(info.dirtyLeft, info.dirtyTop, info.dirtyRight, info.dirtyBottom);
244        dirty.unionWith(localDirty);
245    }
246
247    resume();
248    return result != 0;
249}
250
251///////////////////////////////////////////////////////////////////////////////
252// State management
253///////////////////////////////////////////////////////////////////////////////
254
255int OpenGLRenderer::getSaveCount() const {
256    return mSaveCount;
257}
258
259int OpenGLRenderer::save(int flags) {
260    return saveSnapshot(flags);
261}
262
263void OpenGLRenderer::restore() {
264    if (mSaveCount > 1) {
265        restoreSnapshot();
266    }
267}
268
269void OpenGLRenderer::restoreToCount(int saveCount) {
270    if (saveCount < 1) saveCount = 1;
271
272    while (mSaveCount > saveCount) {
273        restoreSnapshot();
274    }
275}
276
277int OpenGLRenderer::saveSnapshot(int flags) {
278    mSnapshot = new Snapshot(mSnapshot, flags);
279    return mSaveCount++;
280}
281
282bool OpenGLRenderer::restoreSnapshot() {
283    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
284    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
285    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
286
287    sp<Snapshot> current = mSnapshot;
288    sp<Snapshot> previous = mSnapshot->previous;
289
290    if (restoreOrtho) {
291        Rect& r = previous->viewport;
292        glViewport(r.left, r.top, r.right, r.bottom);
293        mOrthoMatrix.load(current->orthoMatrix);
294    }
295
296    mSaveCount--;
297    mSnapshot = previous;
298
299    if (restoreClip) {
300        dirtyClip();
301    }
302
303    if (restoreLayer) {
304        composeLayer(current, previous);
305    }
306
307    return restoreClip;
308}
309
310///////////////////////////////////////////////////////////////////////////////
311// Layers
312///////////////////////////////////////////////////////////////////////////////
313
314int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
315        SkPaint* p, int flags) {
316    const GLuint previousFbo = mSnapshot->fbo;
317    const int count = saveSnapshot(flags);
318
319    if (!mSnapshot->isIgnored()) {
320        int alpha = 255;
321        SkXfermode::Mode mode;
322
323        if (p) {
324            alpha = p->getAlpha();
325            if (!mCaches.extensions.hasFramebufferFetch()) {
326                const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
327                if (!isMode) {
328                    // Assume SRC_OVER
329                    mode = SkXfermode::kSrcOver_Mode;
330                }
331            } else {
332                mode = getXfermode(p->getXfermode());
333            }
334        } else {
335            mode = SkXfermode::kSrcOver_Mode;
336        }
337
338        createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags, previousFbo);
339    }
340
341    return count;
342}
343
344int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
345        int alpha, int flags) {
346    if (alpha >= 255 - ALPHA_THRESHOLD) {
347        return saveLayer(left, top, right, bottom, NULL, flags);
348    } else {
349        SkPaint paint;
350        paint.setAlpha(alpha);
351        return saveLayer(left, top, right, bottom, &paint, flags);
352    }
353}
354
355/**
356 * Layers are viewed by Skia are slightly different than layers in image editing
357 * programs (for instance.) When a layer is created, previously created layers
358 * and the frame buffer still receive every drawing command. For instance, if a
359 * layer is created and a shape intersecting the bounds of the layers and the
360 * framebuffer is draw, the shape will be drawn on both (unless the layer was
361 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
362 *
363 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
364 * texture. Unfortunately, this is inefficient as it requires every primitive to
365 * be drawn n + 1 times, where n is the number of active layers. In practice this
366 * means, for every primitive:
367 *   - Switch active frame buffer
368 *   - Change viewport, clip and projection matrix
369 *   - Issue the drawing
370 *
371 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
372 * To avoid this, layers are implemented in a different way here, at least in the
373 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
374 * is set. When this flag is set we can redirect all drawing operations into a
375 * single FBO.
376 *
377 * This implementation relies on the frame buffer being at least RGBA 8888. When
378 * a layer is created, only a texture is created, not an FBO. The content of the
379 * frame buffer contained within the layer's bounds is copied into this texture
380 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
381 * buffer and drawing continues as normal. This technique therefore treats the
382 * frame buffer as a scratch buffer for the layers.
383 *
384 * To compose the layers back onto the frame buffer, each layer texture
385 * (containing the original frame buffer data) is drawn as a simple quad over
386 * the frame buffer. The trick is that the quad is set as the composition
387 * destination in the blending equation, and the frame buffer becomes the source
388 * of the composition.
389 *
390 * Drawing layers with an alpha value requires an extra step before composition.
391 * An empty quad is drawn over the layer's region in the frame buffer. This quad
392 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
393 * quad is used to multiply the colors in the frame buffer. This is achieved by
394 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
395 * GL_ZERO, GL_SRC_ALPHA.
396 *
397 * Because glCopyTexImage2D() can be slow, an alternative implementation might
398 * be use to draw a single clipped layer. The implementation described above
399 * is correct in every case.
400 *
401 * (1) The frame buffer is actually not cleared right away. To allow the GPU
402 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
403 *     buffer is left untouched until the first drawing operation. Only when
404 *     something actually gets drawn are the layers regions cleared.
405 */
406bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
407        float right, float bottom, int alpha, SkXfermode::Mode mode,
408        int flags, GLuint previousFbo) {
409    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
410    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
411
412    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
413
414    // Window coordinates of the layer
415    Rect bounds(left, top, right, bottom);
416    if (!fboLayer) {
417        mSnapshot->transform->mapRect(bounds);
418
419        // Layers only make sense if they are in the framebuffer's bounds
420        if (bounds.intersect(*snapshot->clipRect)) {
421            // We cannot work with sub-pixels in this case
422            bounds.snapToPixelBoundaries();
423
424            // When the layer is not an FBO, we may use glCopyTexImage so we
425            // need to make sure the layer does not extend outside the bounds
426            // of the framebuffer
427            if (!bounds.intersect(snapshot->previous->viewport)) {
428                bounds.setEmpty();
429            }
430        } else {
431            bounds.setEmpty();
432        }
433    }
434
435    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
436            bounds.getHeight() > mCaches.maxTextureSize) {
437        snapshot->empty = fboLayer;
438    } else {
439        snapshot->invisible = snapshot->invisible || (alpha <= ALPHA_THRESHOLD && fboLayer);
440    }
441
442    // Bail out if we won't draw in this snapshot
443    if (snapshot->invisible || snapshot->empty) {
444        return false;
445    }
446
447    glActiveTexture(gTextureUnits[0]);
448    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
449    if (!layer) {
450        return false;
451    }
452
453    layer->mode = mode;
454    layer->alpha = alpha;
455    layer->layer.set(bounds);
456    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->height),
457            bounds.getWidth() / float(layer->width), 0.0f);
458    layer->colorFilter = mColorFilter;
459
460    // Save the layer in the snapshot
461    snapshot->flags |= Snapshot::kFlagIsLayer;
462    snapshot->layer = layer;
463
464    if (fboLayer) {
465        return createFboLayer(layer, bounds, snapshot, previousFbo);
466    } else {
467        // Copy the framebuffer into the layer
468        glBindTexture(GL_TEXTURE_2D, layer->texture);
469        if (!bounds.isEmpty()) {
470            if (layer->empty) {
471                glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left,
472                        snapshot->height - bounds.bottom, layer->width, layer->height, 0);
473                layer->empty = false;
474            } else {
475                glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left,
476                        snapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight());
477            }
478
479            // Clear the framebuffer where the layer will draw
480            glScissor(bounds.left, mSnapshot->height - bounds.bottom,
481                    bounds.getWidth(), bounds.getHeight());
482            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
483            glClear(GL_COLOR_BUFFER_BIT);
484
485            dirtyClip();
486        }
487    }
488
489    return true;
490}
491
492bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, sp<Snapshot> snapshot,
493        GLuint previousFbo) {
494    layer->fbo = mCaches.fboCache.get();
495
496#if RENDER_LAYERS_AS_REGIONS
497    snapshot->region = &snapshot->layer->region;
498    snapshot->flags |= Snapshot::kFlagFboTarget;
499#endif
500
501    Rect clip(bounds);
502    snapshot->transform->mapRect(clip);
503    clip.intersect(*snapshot->clipRect);
504    clip.snapToPixelBoundaries();
505    clip.intersect(snapshot->previous->viewport);
506
507    mat4 inverse;
508    inverse.loadInverse(*mSnapshot->transform);
509
510    inverse.mapRect(clip);
511    clip.snapToPixelBoundaries();
512    clip.intersect(bounds);
513    clip.translate(-bounds.left, -bounds.top);
514
515    snapshot->flags |= Snapshot::kFlagIsFboLayer;
516    snapshot->fbo = layer->fbo;
517    snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
518    snapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
519    snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
520    snapshot->height = bounds.getHeight();
521    snapshot->flags |= Snapshot::kFlagDirtyOrtho;
522    snapshot->orthoMatrix.load(mOrthoMatrix);
523
524    // Bind texture to FBO
525    glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
526    glBindTexture(GL_TEXTURE_2D, layer->texture);
527
528    // Initialize the texture if needed
529    if (layer->empty) {
530        layer->empty = false;
531        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->width, layer->height, 0,
532                GL_RGBA, GL_UNSIGNED_BYTE, NULL);
533    }
534
535    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
536            layer->texture, 0);
537
538#if DEBUG_LAYERS_AS_REGIONS
539    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
540    if (status != GL_FRAMEBUFFER_COMPLETE) {
541        LOGE("Framebuffer incomplete (GL error code 0x%x)", status);
542
543        glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
544        glDeleteTextures(1, &layer->texture);
545        mCaches.fboCache.put(layer->fbo);
546
547        delete layer;
548
549        return false;
550    }
551#endif
552
553    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
554    glScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
555            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
556    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
557    glClear(GL_COLOR_BUFFER_BIT);
558
559    dirtyClip();
560
561    // Change the ortho projection
562    glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
563    mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
564
565    return true;
566}
567
568/**
569 * Read the documentation of createLayer() before doing anything in this method.
570 */
571void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
572    if (!current->layer) {
573        LOGE("Attempting to compose a layer that does not exist");
574        return;
575    }
576
577    const bool fboLayer = current->flags & Snapshot::kFlagIsFboLayer;
578
579    if (fboLayer) {
580        // Unbind current FBO and restore previous one
581        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
582    }
583
584    Layer* layer = current->layer;
585    const Rect& rect = layer->layer;
586
587    if (!fboLayer && layer->alpha < 255) {
588        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
589                layer->alpha << 24, SkXfermode::kDstIn_Mode, true);
590        // Required below, composeLayerRect() will divide by 255
591        layer->alpha = 255;
592    }
593
594    mCaches.unbindMeshBuffer();
595
596    glActiveTexture(gTextureUnits[0]);
597
598    // When the layer is stored in an FBO, we can save a bit of fillrate by
599    // drawing only the dirty region
600    if (fboLayer) {
601        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform);
602        if (layer->colorFilter) {
603            setupColorFilter(layer->colorFilter);
604        }
605        composeLayerRegion(layer, rect);
606        if (layer->colorFilter) {
607            resetColorFilter();
608        }
609    } else {
610        if (!rect.isEmpty()) {
611            dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
612            composeLayerRect(layer, rect, true);
613        }
614    }
615
616    if (fboLayer) {
617        // Detach the texture from the FBO
618        glBindFramebuffer(GL_FRAMEBUFFER, current->fbo);
619        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
620        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
621
622        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
623        mCaches.fboCache.put(current->fbo);
624    }
625
626    dirtyClip();
627
628    // Failing to add the layer to the cache should happen only if the layer is too large
629    if (!mCaches.layerCache.put(layer)) {
630        LAYER_LOGD("Deleting layer");
631        glDeleteTextures(1, &layer->texture);
632        delete layer;
633    }
634}
635
636void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) {
637    float alpha = layer->alpha / 255.0f;
638
639    setupDraw();
640    if (layer->renderTarget == GL_TEXTURE_2D) {
641        setupDrawWithTexture();
642    } else {
643        setupDrawWithExternalTexture();
644    }
645    setupDrawTextureTransform();
646    setupDrawColor(alpha, alpha, alpha, alpha);
647    setupDrawColorFilter();
648    setupDrawBlending(layer->blend, layer->mode);
649    setupDrawProgram();
650    setupDrawModelView(rect.left, rect.top, rect.right, rect.bottom);
651    setupDrawPureColorUniforms();
652    setupDrawColorFilterUniforms();
653    if (layer->renderTarget == GL_TEXTURE_2D) {
654        setupDrawTexture(layer->texture);
655    } else {
656        setupDrawExternalTexture(layer->texture);
657    }
658    setupDrawTextureTransformUniforms(layer->texTransform);
659    setupDrawMesh(&mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]);
660
661    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
662
663    finishDrawTexture();
664}
665
666void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
667    if (!layer->isTextureLayer) {
668        const Rect& texCoords = layer->texCoords;
669        resetDrawTextureTexCoords(texCoords.left, texCoords.top,
670                texCoords.right, texCoords.bottom);
671
672        drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
673                layer->alpha / 255.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
674                &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount, swap, swap);
675
676        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
677    } else {
678        resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f);
679        drawTextureLayer(layer, rect);
680        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
681    }
682}
683
684void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
685#if RENDER_LAYERS_AS_REGIONS
686    if (layer->region.isRect()) {
687        layer->setRegionAsRect();
688
689        composeLayerRect(layer, layer->regionRect);
690
691        layer->region.clear();
692        return;
693    }
694
695    if (!layer->region.isEmpty()) {
696        size_t count;
697        const android::Rect* rects = layer->region.getArray(&count);
698
699        const float alpha = layer->alpha / 255.0f;
700        const float texX = 1.0f / float(layer->width);
701        const float texY = 1.0f / float(layer->height);
702        const float height = rect.getHeight();
703
704        TextureVertex* mesh = mCaches.getRegionMesh();
705        GLsizei numQuads = 0;
706
707        setupDraw();
708        setupDrawWithTexture();
709        setupDrawColor(alpha, alpha, alpha, alpha);
710        setupDrawColorFilter();
711        setupDrawBlending(layer->blend || layer->alpha < 255, layer->mode, false);
712        setupDrawProgram();
713        setupDrawDirtyRegionsDisabled();
714        setupDrawPureColorUniforms();
715        setupDrawColorFilterUniforms();
716        setupDrawTexture(layer->texture);
717        setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
718        setupDrawMesh(&mesh[0].position[0], &mesh[0].texture[0]);
719
720        for (size_t i = 0; i < count; i++) {
721            const android::Rect* r = &rects[i];
722
723            const float u1 = r->left * texX;
724            const float v1 = (height - r->top) * texY;
725            const float u2 = r->right * texX;
726            const float v2 = (height - r->bottom) * texY;
727
728            // TODO: Reject quads outside of the clip
729            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
730            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
731            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
732            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
733
734            numQuads++;
735
736            if (numQuads >= REGION_MESH_QUAD_COUNT) {
737                glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
738                numQuads = 0;
739                mesh = mCaches.getRegionMesh();
740            }
741        }
742
743        if (numQuads > 0) {
744            glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
745        }
746
747        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
748        finishDrawTexture();
749
750#if DEBUG_LAYERS_AS_REGIONS
751        drawRegionRects(layer->region);
752#endif
753
754        layer->region.clear();
755    }
756#else
757    composeLayerRect(layer, rect);
758#endif
759}
760
761void OpenGLRenderer::drawRegionRects(const Region& region) {
762#if DEBUG_LAYERS_AS_REGIONS
763    size_t count;
764    const android::Rect* rects = region.getArray(&count);
765
766    uint32_t colors[] = {
767            0x7fff0000, 0x7f00ff00,
768            0x7f0000ff, 0x7fff00ff,
769    };
770
771    int offset = 0;
772    int32_t top = rects[0].top;
773
774    for (size_t i = 0; i < count; i++) {
775        if (top != rects[i].top) {
776            offset ^= 0x2;
777            top = rects[i].top;
778        }
779
780        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
781        drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
782                SkXfermode::kSrcOver_Mode);
783    }
784#endif
785}
786
787void OpenGLRenderer::dirtyLayer(const float left, const float top,
788        const float right, const float bottom, const mat4 transform) {
789#if RENDER_LAYERS_AS_REGIONS
790    if (hasLayer()) {
791        Rect bounds(left, top, right, bottom);
792        transform.mapRect(bounds);
793        dirtyLayerUnchecked(bounds, getRegion());
794    }
795#endif
796}
797
798void OpenGLRenderer::dirtyLayer(const float left, const float top,
799        const float right, const float bottom) {
800#if RENDER_LAYERS_AS_REGIONS
801    if (hasLayer()) {
802        Rect bounds(left, top, right, bottom);
803        dirtyLayerUnchecked(bounds, getRegion());
804    }
805#endif
806}
807
808void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
809#if RENDER_LAYERS_AS_REGIONS
810    if (bounds.intersect(*mSnapshot->clipRect)) {
811        bounds.snapToPixelBoundaries();
812        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
813        if (!dirty.isEmpty()) {
814            region->orSelf(dirty);
815        }
816    }
817#endif
818}
819
820///////////////////////////////////////////////////////////////////////////////
821// Transforms
822///////////////////////////////////////////////////////////////////////////////
823
824void OpenGLRenderer::translate(float dx, float dy) {
825    mSnapshot->transform->translate(dx, dy, 0.0f);
826}
827
828void OpenGLRenderer::rotate(float degrees) {
829    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
830}
831
832void OpenGLRenderer::scale(float sx, float sy) {
833    mSnapshot->transform->scale(sx, sy, 1.0f);
834}
835
836void OpenGLRenderer::skew(float sx, float sy) {
837    mSnapshot->transform->skew(sx, sy);
838}
839
840void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
841    mSnapshot->transform->load(*matrix);
842}
843
844const float* OpenGLRenderer::getMatrix() const {
845    if (mSnapshot->fbo != 0) {
846        return &mSnapshot->transform->data[0];
847    }
848    return &mIdentity.data[0];
849}
850
851void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
852    mSnapshot->transform->copyTo(*matrix);
853}
854
855void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
856    SkMatrix transform;
857    mSnapshot->transform->copyTo(transform);
858    transform.preConcat(*matrix);
859    mSnapshot->transform->load(transform);
860}
861
862///////////////////////////////////////////////////////////////////////////////
863// Clipping
864///////////////////////////////////////////////////////////////////////////////
865
866void OpenGLRenderer::setScissorFromClip() {
867    Rect clip(*mSnapshot->clipRect);
868    clip.snapToPixelBoundaries();
869    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
870    mDirtyClip = false;
871}
872
873const Rect& OpenGLRenderer::getClipBounds() {
874    return mSnapshot->getLocalClip();
875}
876
877bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
878    if (mSnapshot->isIgnored()) {
879        return true;
880    }
881
882    Rect r(left, top, right, bottom);
883    mSnapshot->transform->mapRect(r);
884    r.snapToPixelBoundaries();
885
886    Rect clipRect(*mSnapshot->clipRect);
887    clipRect.snapToPixelBoundaries();
888
889    return !clipRect.intersects(r);
890}
891
892bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
893    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
894    if (clipped) {
895        dirtyClip();
896    }
897    return !mSnapshot->clipRect->isEmpty();
898}
899
900///////////////////////////////////////////////////////////////////////////////
901// Drawing commands
902///////////////////////////////////////////////////////////////////////////////
903
904void OpenGLRenderer::setupDraw() {
905    if (mDirtyClip) {
906        setScissorFromClip();
907    }
908    mDescription.reset();
909    mSetShaderColor = false;
910    mColorSet = false;
911    mColorA = mColorR = mColorG = mColorB = 0.0f;
912    mTextureUnit = 0;
913    mTrackDirtyRegions = true;
914    mTexCoordsSlot = -1;
915}
916
917void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
918    mDescription.hasTexture = true;
919    mDescription.hasAlpha8Texture = isAlpha8;
920}
921
922void OpenGLRenderer::setupDrawWithExternalTexture() {
923    mDescription.hasExternalTexture = true;
924}
925
926void OpenGLRenderer::setupDrawAALine() {
927    mDescription.isAA = true;
928}
929
930void OpenGLRenderer::setupDrawPoint(float pointSize) {
931    mDescription.isPoint = true;
932    mDescription.pointSize = pointSize;
933}
934
935void OpenGLRenderer::setupDrawColor(int color) {
936    setupDrawColor(color, (color >> 24) & 0xFF);
937}
938
939void OpenGLRenderer::setupDrawColor(int color, int alpha) {
940    mColorA = alpha / 255.0f;
941    // Second divide of a by 255 is an optimization, allowing us to simply multiply
942    // the rgb values by a instead of also dividing by 255
943    const float a = mColorA / 255.0f;
944    mColorR = a * ((color >> 16) & 0xFF);
945    mColorG = a * ((color >>  8) & 0xFF);
946    mColorB = a * ((color      ) & 0xFF);
947    mColorSet = true;
948    mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA);
949}
950
951void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
952    mColorA = alpha / 255.0f;
953    // Double-divide of a by 255 is an optimization, allowing us to simply multiply
954    // the rgb values by a instead of also dividing by 255
955    const float a = mColorA / 255.0f;
956    mColorR = a * ((color >> 16) & 0xFF);
957    mColorG = a * ((color >>  8) & 0xFF);
958    mColorB = a * ((color      ) & 0xFF);
959    mColorSet = true;
960    mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
961}
962
963void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
964    mColorA = a;
965    mColorR = r;
966    mColorG = g;
967    mColorB = b;
968    mColorSet = true;
969    mSetShaderColor = mDescription.setColor(r, g, b, a);
970}
971
972void OpenGLRenderer::setupDrawAlpha8Color(float r, float g, float b, float a) {
973    mColorA = a;
974    mColorR = r;
975    mColorG = g;
976    mColorB = b;
977    mColorSet = true;
978    mSetShaderColor = mDescription.setAlpha8Color(r, g, b, a);
979}
980
981void OpenGLRenderer::setupDrawShader() {
982    if (mShader) {
983        mShader->describe(mDescription, mCaches.extensions);
984    }
985}
986
987void OpenGLRenderer::setupDrawColorFilter() {
988    if (mColorFilter) {
989        mColorFilter->describe(mDescription, mCaches.extensions);
990    }
991}
992
993void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
994    if (mColorSet && mode == SkXfermode::kClear_Mode) {
995        mColorA = 1.0f;
996        mColorR = mColorG = mColorB = 0.0f;
997        mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
998    }
999}
1000
1001void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) {
1002    // When the blending mode is kClear_Mode, we need to use a modulate color
1003    // argb=1,0,0,0
1004    accountForClear(mode);
1005    chooseBlending((mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
1006            mDescription, swapSrcDst);
1007}
1008
1009void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) {
1010    // When the blending mode is kClear_Mode, we need to use a modulate color
1011    // argb=1,0,0,0
1012    accountForClear(mode);
1013    chooseBlending(blend || (mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
1014            mDescription, swapSrcDst);
1015}
1016
1017void OpenGLRenderer::setupDrawProgram() {
1018    useProgram(mCaches.programCache.get(mDescription));
1019}
1020
1021void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
1022    mTrackDirtyRegions = false;
1023}
1024
1025void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom,
1026        bool ignoreTransform) {
1027    mModelView.loadTranslate(left, top, 0.0f);
1028    if (!ignoreTransform) {
1029        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1030        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1031    } else {
1032        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1033        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
1034    }
1035}
1036
1037void OpenGLRenderer::setupDrawModelViewIdentity(bool offset) {
1038    mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform, offset);
1039}
1040
1041void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom,
1042        bool ignoreTransform, bool ignoreModelView) {
1043    if (!ignoreModelView) {
1044        mModelView.loadTranslate(left, top, 0.0f);
1045        mModelView.scale(right - left, bottom - top, 1.0f);
1046    } else {
1047        mModelView.loadIdentity();
1048    }
1049    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
1050    if (!ignoreTransform) {
1051        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1052        if (mTrackDirtyRegions && dirty) {
1053            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1054        }
1055    } else {
1056        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1057        if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom);
1058    }
1059}
1060
1061void OpenGLRenderer::setupDrawPointUniforms() {
1062    int slot = mCaches.currentProgram->getUniform("pointSize");
1063    glUniform1f(slot, mDescription.pointSize);
1064}
1065
1066void OpenGLRenderer::setupDrawColorUniforms() {
1067    if (mColorSet || (mShader && mSetShaderColor)) {
1068        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1069    }
1070}
1071
1072void OpenGLRenderer::setupDrawPureColorUniforms() {
1073    if (mSetShaderColor) {
1074        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1075    }
1076}
1077
1078void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
1079    if (mShader) {
1080        if (ignoreTransform) {
1081            mModelView.loadInverse(*mSnapshot->transform);
1082        }
1083        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &mTextureUnit);
1084    }
1085}
1086
1087void OpenGLRenderer::setupDrawShaderIdentityUniforms() {
1088    if (mShader) {
1089        mShader->setupProgram(mCaches.currentProgram, mIdentity, *mSnapshot, &mTextureUnit);
1090    }
1091}
1092
1093void OpenGLRenderer::setupDrawColorFilterUniforms() {
1094    if (mColorFilter) {
1095        mColorFilter->setupProgram(mCaches.currentProgram);
1096    }
1097}
1098
1099void OpenGLRenderer::setupDrawSimpleMesh() {
1100    mCaches.bindMeshBuffer();
1101    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1102            gMeshStride, 0);
1103}
1104
1105void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1106    bindTexture(texture);
1107    glUniform1i(mCaches.currentProgram->getUniform("sampler"), mTextureUnit++);
1108
1109    mTexCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1110    glEnableVertexAttribArray(mTexCoordsSlot);
1111}
1112
1113void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) {
1114    bindExternalTexture(texture);
1115    glUniform1i(mCaches.currentProgram->getUniform("sampler"), mTextureUnit++);
1116
1117    mTexCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1118    glEnableVertexAttribArray(mTexCoordsSlot);
1119}
1120
1121void OpenGLRenderer::setupDrawTextureTransform() {
1122    mDescription.hasTextureTransform = true;
1123}
1124
1125void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) {
1126    glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1,
1127            GL_FALSE, &transform.data[0]);
1128}
1129
1130void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1131    if (!vertices) {
1132        mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1133    } else {
1134        mCaches.unbindMeshBuffer();
1135    }
1136    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1137            gMeshStride, vertices);
1138    if (mTexCoordsSlot >= 0) {
1139        glVertexAttribPointer(mTexCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1140    }
1141}
1142
1143void OpenGLRenderer::setupDrawVertices(GLvoid* vertices) {
1144    mCaches.unbindMeshBuffer();
1145    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1146            gVertexStride, vertices);
1147}
1148
1149/**
1150 * Sets up the shader to draw an AA line. We draw AA lines with quads, where there is an
1151 * outer boundary that fades out to 0. The variables set in the shader define the proportion of
1152 * the width and length of the primitive occupied by the AA region. The vtxWidth and vtxLength
1153 * attributes (one per vertex) are values from zero to one that tells the fragment
1154 * shader where the fragment is in relation to the line width/length overall; these values are
1155 * then used to compute the proper color, based on whether the fragment lies in the fading AA
1156 * region of the line.
1157 * Note that we only pass down the width values in this setup function. The length coordinates
1158 * are set up for each individual segment.
1159 */
1160void OpenGLRenderer::setupDrawAALine(GLvoid* vertices, GLvoid* widthCoords,
1161        GLvoid* lengthCoords, float boundaryWidthProportion) {
1162    mCaches.unbindMeshBuffer();
1163    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1164            gAAVertexStride, vertices);
1165    int widthSlot = mCaches.currentProgram->getAttrib("vtxWidth");
1166    glEnableVertexAttribArray(widthSlot);
1167    glVertexAttribPointer(widthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, widthCoords);
1168    int lengthSlot = mCaches.currentProgram->getAttrib("vtxLength");
1169    glEnableVertexAttribArray(lengthSlot);
1170    glVertexAttribPointer(lengthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, lengthCoords);
1171    int boundaryWidthSlot = mCaches.currentProgram->getUniform("boundaryWidth");
1172    glUniform1f(boundaryWidthSlot, boundaryWidthProportion);
1173    // Setting the inverse value saves computations per-fragment in the shader
1174    int inverseBoundaryWidthSlot = mCaches.currentProgram->getUniform("inverseBoundaryWidth");
1175    glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidthProportion));
1176}
1177
1178void OpenGLRenderer::finishDrawTexture() {
1179    glDisableVertexAttribArray(mTexCoordsSlot);
1180}
1181
1182///////////////////////////////////////////////////////////////////////////////
1183// Drawing
1184///////////////////////////////////////////////////////////////////////////////
1185
1186bool OpenGLRenderer::drawDisplayList(DisplayList* displayList, uint32_t width, uint32_t height,
1187        Rect& dirty, uint32_t level) {
1188    if (quickReject(0.0f, 0.0f, width, height)) {
1189        return false;
1190    }
1191
1192    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1193    // will be performed by the display list itself
1194    if (displayList) {
1195        return displayList->replay(*this, dirty, level);
1196    }
1197
1198    return false;
1199}
1200
1201void OpenGLRenderer::outputDisplayList(DisplayList* displayList, uint32_t level) {
1202    if (displayList) {
1203        displayList->output(*this, level);
1204    }
1205}
1206
1207void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint) {
1208    int alpha;
1209    SkXfermode::Mode mode;
1210    getAlphaAndMode(paint, &alpha, &mode);
1211
1212    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1213
1214    float x = left;
1215    float y = top;
1216
1217    bool ignoreTransform = false;
1218    if (mSnapshot->transform->isPureTranslate()) {
1219        x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1220        y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1221        ignoreTransform = true;
1222    }
1223
1224    setupDraw();
1225    setupDrawWithTexture(true);
1226    if (paint) {
1227        setupDrawAlpha8Color(paint->getColor(), alpha);
1228    }
1229    setupDrawColorFilter();
1230    setupDrawShader();
1231    setupDrawBlending(true, mode);
1232    setupDrawProgram();
1233    setupDrawModelView(x, y, x + texture->width, y + texture->height, ignoreTransform);
1234    setupDrawTexture(texture->id);
1235    setupDrawPureColorUniforms();
1236    setupDrawColorFilterUniforms();
1237    setupDrawShaderUniforms();
1238    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1239
1240    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1241
1242    finishDrawTexture();
1243}
1244
1245void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1246    const float right = left + bitmap->width();
1247    const float bottom = top + bitmap->height();
1248
1249    if (quickReject(left, top, right, bottom)) {
1250        return;
1251    }
1252
1253    glActiveTexture(gTextureUnits[0]);
1254    Texture* texture = mCaches.textureCache.get(bitmap);
1255    if (!texture) return;
1256    const AutoTexture autoCleanup(texture);
1257
1258    if (bitmap->getConfig() == SkBitmap::kA8_Config) {
1259        drawAlphaBitmap(texture, left, top, paint);
1260    } else {
1261        drawTextureRect(left, top, right, bottom, texture, paint);
1262    }
1263}
1264
1265void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
1266    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
1267    const mat4 transform(*matrix);
1268    transform.mapRect(r);
1269
1270    if (quickReject(r.left, r.top, r.right, r.bottom)) {
1271        return;
1272    }
1273
1274    glActiveTexture(gTextureUnits[0]);
1275    Texture* texture = mCaches.textureCache.get(bitmap);
1276    if (!texture) return;
1277    const AutoTexture autoCleanup(texture);
1278
1279    // This could be done in a cheaper way, all we need is pass the matrix
1280    // to the vertex shader. The save/restore is a bit overkill.
1281    save(SkCanvas::kMatrix_SaveFlag);
1282    concatMatrix(matrix);
1283    drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
1284    restore();
1285}
1286
1287void OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
1288        float* vertices, int* colors, SkPaint* paint) {
1289    // TODO: Do a quickReject
1290    if (!vertices || mSnapshot->isIgnored()) {
1291        return;
1292    }
1293
1294    glActiveTexture(gTextureUnits[0]);
1295    Texture* texture = mCaches.textureCache.get(bitmap);
1296    if (!texture) return;
1297    const AutoTexture autoCleanup(texture);
1298    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1299
1300    int alpha;
1301    SkXfermode::Mode mode;
1302    getAlphaAndMode(paint, &alpha, &mode);
1303
1304    const uint32_t count = meshWidth * meshHeight * 6;
1305
1306    float left = FLT_MAX;
1307    float top = FLT_MAX;
1308    float right = FLT_MIN;
1309    float bottom = FLT_MIN;
1310
1311#if RENDER_LAYERS_AS_REGIONS
1312    bool hasActiveLayer = hasLayer();
1313#else
1314    bool hasActiveLayer = false;
1315#endif
1316
1317    // TODO: Support the colors array
1318    TextureVertex mesh[count];
1319    TextureVertex* vertex = mesh;
1320    for (int32_t y = 0; y < meshHeight; y++) {
1321        for (int32_t x = 0; x < meshWidth; x++) {
1322            uint32_t i = (y * (meshWidth + 1) + x) * 2;
1323
1324            float u1 = float(x) / meshWidth;
1325            float u2 = float(x + 1) / meshWidth;
1326            float v1 = float(y) / meshHeight;
1327            float v2 = float(y + 1) / meshHeight;
1328
1329            int ax = i + (meshWidth + 1) * 2;
1330            int ay = ax + 1;
1331            int bx = i;
1332            int by = bx + 1;
1333            int cx = i + 2;
1334            int cy = cx + 1;
1335            int dx = i + (meshWidth + 1) * 2 + 2;
1336            int dy = dx + 1;
1337
1338            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1339            TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1);
1340            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1341
1342            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1343            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1344            TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2);
1345
1346#if RENDER_LAYERS_AS_REGIONS
1347            if (hasActiveLayer) {
1348                // TODO: This could be optimized to avoid unnecessary ops
1349                left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
1350                top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
1351                right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
1352                bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
1353            }
1354#endif
1355        }
1356    }
1357
1358#if RENDER_LAYERS_AS_REGIONS
1359    if (hasActiveLayer) {
1360        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1361    }
1362#endif
1363
1364    drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f,
1365            mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0],
1366            GL_TRIANGLES, count, false, false, 0, false, false);
1367}
1368
1369void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
1370         float srcLeft, float srcTop, float srcRight, float srcBottom,
1371         float dstLeft, float dstTop, float dstRight, float dstBottom,
1372         SkPaint* paint) {
1373    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
1374        return;
1375    }
1376
1377    glActiveTexture(gTextureUnits[0]);
1378    Texture* texture = mCaches.textureCache.get(bitmap);
1379    if (!texture) return;
1380    const AutoTexture autoCleanup(texture);
1381    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1382
1383    const float width = texture->width;
1384    const float height = texture->height;
1385
1386    const float u1 = (srcLeft + 0.5f) / width;
1387    const float v1 = (srcTop + 0.5f)  / height;
1388    const float u2 = (srcRight - 0.5f) / width;
1389    const float v2 = (srcBottom - 0.5f) / height;
1390
1391    mCaches.unbindMeshBuffer();
1392    resetDrawTextureTexCoords(u1, v1, u2, v2);
1393
1394    int alpha;
1395    SkXfermode::Mode mode;
1396    getAlphaAndMode(paint, &alpha, &mode);
1397
1398    if (mSnapshot->transform->isPureTranslate()) {
1399        const float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f);
1400        const float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f);
1401
1402        drawTextureMesh(x, y, x + (dstRight - dstLeft), y + (dstBottom - dstTop),
1403                texture->id, alpha / 255.0f, mode, texture->blend,
1404                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1405                GL_TRIANGLE_STRIP, gMeshCount, false, true);
1406    } else {
1407        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f,
1408                mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1409                GL_TRIANGLE_STRIP, gMeshCount);
1410    }
1411
1412    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1413}
1414
1415void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
1416        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
1417        float left, float top, float right, float bottom, SkPaint* paint) {
1418    if (quickReject(left, top, right, bottom)) {
1419        return;
1420    }
1421
1422    glActiveTexture(gTextureUnits[0]);
1423    Texture* texture = mCaches.textureCache.get(bitmap);
1424    if (!texture) return;
1425    const AutoTexture autoCleanup(texture);
1426    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1427
1428    int alpha;
1429    SkXfermode::Mode mode;
1430    getAlphaAndMode(paint, &alpha, &mode);
1431
1432    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
1433            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
1434
1435    if (mesh && mesh->verticesCount > 0) {
1436        const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1437#if RENDER_LAYERS_AS_REGIONS
1438        // Mark the current layer dirty where we are going to draw the patch
1439        if (hasLayer() && mesh->hasEmptyQuads) {
1440            const float offsetX = left + mSnapshot->transform->getTranslateX();
1441            const float offsetY = top + mSnapshot->transform->getTranslateY();
1442            const size_t count = mesh->quads.size();
1443            for (size_t i = 0; i < count; i++) {
1444                const Rect& bounds = mesh->quads.itemAt(i);
1445                if (pureTranslate) {
1446                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
1447                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
1448                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
1449                } else {
1450                    dirtyLayer(left + bounds.left, top + bounds.top,
1451                            left + bounds.right, top + bounds.bottom, *mSnapshot->transform);
1452                }
1453            }
1454        }
1455#endif
1456
1457        if (pureTranslate) {
1458            const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1459            const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1460
1461            drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
1462                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1463                    GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
1464                    true, !mesh->hasEmptyQuads);
1465        } else {
1466            drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
1467                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1468                    GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
1469                    true, !mesh->hasEmptyQuads);
1470        }
1471    }
1472}
1473
1474/**
1475 * This function uses a similar approach to that of AA lines in the drawLines() function.
1476 * We expand the rectangle by a half pixel in screen space on all sides, and use a fragment
1477 * shader to compute the translucency of the color, determined by whether a given pixel is
1478 * within that boundary region and how far into the region it is.
1479 */
1480void OpenGLRenderer::drawAARect(float left, float top, float right, float bottom,
1481        int color, SkXfermode::Mode mode)
1482{
1483    float inverseScaleX = 1.0f;
1484    float inverseScaleY = 1.0f;
1485    // The quad that we use needs to account for scaling.
1486    if (!mSnapshot->transform->isPureTranslate()) {
1487        Matrix4 *mat = mSnapshot->transform;
1488        float m00 = mat->data[Matrix4::kScaleX];
1489        float m01 = mat->data[Matrix4::kSkewY];
1490        float m02 = mat->data[2];
1491        float m10 = mat->data[Matrix4::kSkewX];
1492        float m11 = mat->data[Matrix4::kScaleX];
1493        float m12 = mat->data[6];
1494        float scaleX = sqrt(m00 * m00 + m01 * m01);
1495        float scaleY = sqrt(m10 * m10 + m11 * m11);
1496        inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0;
1497        inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0;
1498    }
1499
1500    setupDraw();
1501    setupDrawAALine();
1502    setupDrawColor(color);
1503    setupDrawColorFilter();
1504    setupDrawShader();
1505    setupDrawBlending(true, mode);
1506    setupDrawProgram();
1507    setupDrawModelViewIdentity(true);
1508    setupDrawColorUniforms();
1509    setupDrawColorFilterUniforms();
1510    setupDrawShaderIdentityUniforms();
1511
1512    AAVertex rects[4];
1513    AAVertex* aaVertices = &rects[0];
1514    void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset;
1515    void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset;
1516
1517    float boundarySizeX = .5 * inverseScaleX;
1518    float boundarySizeY = .5 * inverseScaleY;
1519
1520    // Adjust the rect by the AA boundary padding
1521    left -= boundarySizeX;
1522    right += boundarySizeX;
1523    top -= boundarySizeY;
1524    bottom += boundarySizeY;
1525
1526    float width = right - left;
1527    float height = bottom - top;
1528
1529    float boundaryWidthProportion = (width != 0) ? (2 * boundarySizeX) / width : 0;
1530    float boundaryHeightProportion = (height != 0) ? (2 * boundarySizeY) / height : 0;
1531    setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, boundaryWidthProportion);
1532    int boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength");
1533    int inverseBoundaryLengthSlot = mCaches.currentProgram->getUniform("inverseBoundaryLength");
1534    glUniform1f(boundaryLengthSlot, boundaryHeightProportion);
1535    glUniform1f(inverseBoundaryLengthSlot, (1 / boundaryHeightProportion));
1536
1537    if (!quickReject(left, top, right, bottom)) {
1538        AAVertex::set(aaVertices++, left, bottom, 1, 1);
1539        AAVertex::set(aaVertices++, left, top, 1, 0);
1540        AAVertex::set(aaVertices++, right, bottom, 0, 1);
1541        AAVertex::set(aaVertices++, right, top, 0, 0);
1542        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1543        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1544    }
1545}
1546
1547/**
1548 * We draw lines as quads (tristrips). Using GL_LINES can be difficult because the rasterization
1549 * rules for those lines produces some unexpected results, and may vary between hardware devices.
1550 * The basics of lines-as-quads is easy; we simply find the normal to the line and position the
1551 * corners of the quads on either side of each line endpoint, separated by the strokeWidth
1552 * of the line. Hairlines are more involved because we need to account for transform scaling
1553 * to end up with a one-pixel-wide line in screen space..
1554 * Anti-aliased lines add another factor to the approach. We use a specialized fragment shader
1555 * in combination with values that we calculate and pass down in this method. The basic approach
1556 * is that the quad we create contains both the core line area plus a bounding area in which
1557 * the translucent/AA pixels are drawn. The values we calculate tell the shader what
1558 * proportion of the width and the length of a given segment is represented by the boundary
1559 * region. The quad ends up being exactly .5 pixel larger in all directions than the non-AA quad.
1560 * The bounding region is actually 1 pixel wide on all sides (half pixel on the outside, half pixel
1561 * on the inside). This ends up giving the result we want, with pixels that are completely
1562 * 'inside' the line area being filled opaquely and the other pixels being filled according to
1563 * how far into the boundary region they are, which is determined by shader interpolation.
1564 */
1565void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
1566    if (mSnapshot->isIgnored()) return;
1567
1568    const bool isAA = paint->isAntiAlias();
1569    // We use half the stroke width here because we're going to position the quad
1570    // corner vertices half of the width away from the line endpoints
1571    float halfStrokeWidth = paint->getStrokeWidth() * 0.5f;
1572    // A stroke width of 0 has a special meaning in Skia:
1573    // it draws a line 1 px wide regardless of current transform
1574    bool isHairLine = paint->getStrokeWidth() == 0.0f;
1575    float inverseScaleX = 1.0f;
1576    float inverseScaleY = 1.0f;
1577    bool scaled = false;
1578    int alpha;
1579    SkXfermode::Mode mode;
1580    int generatedVerticesCount = 0;
1581    int verticesCount = count;
1582    if (count > 4) {
1583        // Polyline: account for extra vertices needed for continuous tri-strip
1584        verticesCount += (count - 4);
1585    }
1586
1587    if (isHairLine || isAA) {
1588        // The quad that we use for AA and hairlines needs to account for scaling. For hairlines
1589        // the line on the screen should always be one pixel wide regardless of scale. For
1590        // AA lines, we only want one pixel of translucent boundary around the quad.
1591        if (!mSnapshot->transform->isPureTranslate()) {
1592            Matrix4 *mat = mSnapshot->transform;
1593            float m00 = mat->data[Matrix4::kScaleX];
1594            float m01 = mat->data[Matrix4::kSkewY];
1595            float m02 = mat->data[2];
1596            float m10 = mat->data[Matrix4::kSkewX];
1597            float m11 = mat->data[Matrix4::kScaleX];
1598            float m12 = mat->data[6];
1599            float scaleX = sqrt(m00*m00 + m01*m01);
1600            float scaleY = sqrt(m10*m10 + m11*m11);
1601            inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0;
1602            inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0;
1603            if (inverseScaleX != 1.0f || inverseScaleY != 1.0f) {
1604                scaled = true;
1605            }
1606        }
1607    }
1608
1609    getAlphaAndMode(paint, &alpha, &mode);
1610    setupDraw();
1611    if (isAA) {
1612        setupDrawAALine();
1613    }
1614    setupDrawColor(paint->getColor(), alpha);
1615    setupDrawColorFilter();
1616    setupDrawShader();
1617    if (isAA) {
1618        setupDrawBlending(true, mode);
1619    } else {
1620        setupDrawBlending(mode);
1621    }
1622    setupDrawProgram();
1623    setupDrawModelViewIdentity(true);
1624    setupDrawColorUniforms();
1625    setupDrawColorFilterUniforms();
1626    setupDrawShaderIdentityUniforms();
1627
1628    if (isHairLine) {
1629        // Set a real stroke width to be used in quad construction
1630        halfStrokeWidth = isAA? 1 : .5;
1631    } else if (isAA && !scaled) {
1632        // Expand boundary to enable AA calculations on the quad border
1633        halfStrokeWidth += .5f;
1634    }
1635    Vertex lines[verticesCount];
1636    Vertex* vertices = &lines[0];
1637    AAVertex wLines[verticesCount];
1638    AAVertex* aaVertices = &wLines[0];
1639    if (!isAA) {
1640        setupDrawVertices(vertices);
1641    } else {
1642        void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset;
1643        void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset;
1644        // innerProportion is the ratio of the inner (non-AA) part of the line to the total
1645        // AA stroke width (the base stroke width expanded by a half pixel on either side).
1646        // This value is used in the fragment shader to determine how to fill fragments.
1647        // We will need to calculate the actual width proportion on each segment for
1648        // scaled non-hairlines, since the boundary proportion may differ per-axis when scaled.
1649        float boundaryWidthProportion = 1 / (2 * halfStrokeWidth);
1650        setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, boundaryWidthProportion);
1651    }
1652
1653    AAVertex* prevAAVertex = NULL;
1654    Vertex* prevVertex = NULL;
1655
1656    int boundaryLengthSlot = -1;
1657    int inverseBoundaryLengthSlot = -1;
1658    int boundaryWidthSlot = -1;
1659    int inverseBoundaryWidthSlot = -1;
1660    for (int i = 0; i < count; i += 4) {
1661        // a = start point, b = end point
1662        vec2 a(points[i], points[i + 1]);
1663        vec2 b(points[i + 2], points[i + 3]);
1664        float length = 0;
1665        float boundaryLengthProportion = 0;
1666        float boundaryWidthProportion = 0;
1667
1668        // Find the normal to the line
1669        vec2 n = (b - a).copyNormalized() * halfStrokeWidth;
1670        if (isHairLine) {
1671            if (isAA) {
1672                float wideningFactor;
1673                if (fabs(n.x) >= fabs(n.y)) {
1674                    wideningFactor = fabs(1.0f / n.x);
1675                } else {
1676                    wideningFactor = fabs(1.0f / n.y);
1677                }
1678                n *= wideningFactor;
1679            }
1680            if (scaled) {
1681                n.x *= inverseScaleX;
1682                n.y *= inverseScaleY;
1683            }
1684        } else if (scaled) {
1685            // Extend n by .5 pixel on each side, post-transform
1686            vec2 extendedN = n.copyNormalized();
1687            extendedN /= 2;
1688            extendedN.x *= inverseScaleX;
1689            extendedN.y *= inverseScaleY;
1690            float extendedNLength = extendedN.length();
1691            // We need to set this value on the shader prior to drawing
1692            boundaryWidthProportion = extendedNLength / (halfStrokeWidth + extendedNLength);
1693            n += extendedN;
1694        }
1695        float x = n.x;
1696        n.x = -n.y;
1697        n.y = x;
1698
1699        // aa lines expand the endpoint vertices to encompass the AA boundary
1700        if (isAA) {
1701            vec2 abVector = (b - a);
1702            length = abVector.length();
1703            abVector.normalize();
1704            if (scaled) {
1705                abVector.x *= inverseScaleX;
1706                abVector.y *= inverseScaleY;
1707                float abLength = abVector.length();
1708                boundaryLengthProportion = abLength / (length + abLength);
1709            } else {
1710                boundaryLengthProportion = .5 / (length + 1);
1711            }
1712            abVector /= 2;
1713            a -= abVector;
1714            b += abVector;
1715        }
1716
1717        // Four corners of the rectangle defining a thick line
1718        vec2 p1 = a - n;
1719        vec2 p2 = a + n;
1720        vec2 p3 = b + n;
1721        vec2 p4 = b - n;
1722
1723
1724        const float left = fmin(p1.x, fmin(p2.x, fmin(p3.x, p4.x)));
1725        const float right = fmax(p1.x, fmax(p2.x, fmax(p3.x, p4.x)));
1726        const float top = fmin(p1.y, fmin(p2.y, fmin(p3.y, p4.y)));
1727        const float bottom = fmax(p1.y, fmax(p2.y, fmax(p3.y, p4.y)));
1728
1729        if (!quickReject(left, top, right, bottom)) {
1730            if (!isAA) {
1731                if (prevVertex != NULL) {
1732                    // Issue two repeat vertices to create degenerate triangles to bridge
1733                    // between the previous line and the new one. This is necessary because
1734                    // we are creating a single triangle_strip which will contain
1735                    // potentially discontinuous line segments.
1736                    Vertex::set(vertices++, prevVertex->position[0], prevVertex->position[1]);
1737                    Vertex::set(vertices++, p1.x, p1.y);
1738                    generatedVerticesCount += 2;
1739                }
1740                Vertex::set(vertices++, p1.x, p1.y);
1741                Vertex::set(vertices++, p2.x, p2.y);
1742                Vertex::set(vertices++, p4.x, p4.y);
1743                Vertex::set(vertices++, p3.x, p3.y);
1744                prevVertex = vertices - 1;
1745                generatedVerticesCount += 4;
1746            } else {
1747                if (!isHairLine && scaled) {
1748                    // Must set width proportions per-segment for scaled non-hairlines to use the
1749                    // correct AA boundary dimensions
1750                    if (boundaryWidthSlot < 0) {
1751                        boundaryWidthSlot =
1752                                mCaches.currentProgram->getUniform("boundaryWidth");
1753                        inverseBoundaryWidthSlot =
1754                                mCaches.currentProgram->getUniform("inverseBoundaryWidth");
1755                    }
1756                    glUniform1f(boundaryWidthSlot, boundaryWidthProportion);
1757                    glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidthProportion));
1758                }
1759                if (boundaryLengthSlot < 0) {
1760                    boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength");
1761                    inverseBoundaryLengthSlot =
1762                            mCaches.currentProgram->getUniform("inverseBoundaryLength");
1763                }
1764                glUniform1f(boundaryLengthSlot, boundaryLengthProportion);
1765                glUniform1f(inverseBoundaryLengthSlot, (1 / boundaryLengthProportion));
1766
1767                if (prevAAVertex != NULL) {
1768                    // Issue two repeat vertices to create degenerate triangles to bridge
1769                    // between the previous line and the new one. This is necessary because
1770                    // we are creating a single triangle_strip which will contain
1771                    // potentially discontinuous line segments.
1772                    AAVertex::set(aaVertices++,prevAAVertex->position[0],
1773                            prevAAVertex->position[1], prevAAVertex->width, prevAAVertex->length);
1774                    AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1);
1775                    generatedVerticesCount += 2;
1776                }
1777                AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1);
1778                AAVertex::set(aaVertices++, p1.x, p1.y, 1, 0);
1779                AAVertex::set(aaVertices++, p3.x, p3.y, 0, 1);
1780                AAVertex::set(aaVertices++, p2.x, p2.y, 0, 0);
1781                prevAAVertex = aaVertices - 1;
1782                generatedVerticesCount += 4;
1783            }
1784            dirtyLayer(a.x == b.x ? left - 1 : left, a.y == b.y ? top - 1 : top,
1785                    a.x == b.x ? right: right, a.y == b.y ? bottom: bottom,
1786                    *mSnapshot->transform);
1787        }
1788    }
1789    if (generatedVerticesCount > 0) {
1790       glDrawArrays(GL_TRIANGLE_STRIP, 0, generatedVerticesCount);
1791    }
1792}
1793
1794void OpenGLRenderer::drawPoints(float* points, int count, SkPaint* paint) {
1795    if (mSnapshot->isIgnored()) return;
1796
1797    // TODO: The paint's cap style defines whether the points are square or circular
1798    // TODO: Handle AA for round points
1799
1800    // A stroke width of 0 has a special meaning in Skia:
1801    // it draws an unscaled 1px point
1802    float strokeWidth = paint->getStrokeWidth();
1803    const bool isHairLine = paint->getStrokeWidth() == 0.0f;
1804    if (isHairLine) {
1805        // Now that we know it's hairline, we can set the effective width, to be used later
1806        strokeWidth = 1.0f;
1807    }
1808    const float halfWidth = strokeWidth / 2;
1809    int alpha;
1810    SkXfermode::Mode mode;
1811    getAlphaAndMode(paint, &alpha, &mode);
1812
1813    int verticesCount = count >> 1;
1814    int generatedVerticesCount = 0;
1815
1816    TextureVertex pointsData[verticesCount];
1817    TextureVertex* vertex = &pointsData[0];
1818
1819    setupDraw();
1820    setupDrawPoint(strokeWidth);
1821    setupDrawColor(paint->getColor(), alpha);
1822    setupDrawColorFilter();
1823    setupDrawShader();
1824    setupDrawBlending(mode);
1825    setupDrawProgram();
1826    setupDrawModelViewIdentity(true);
1827    setupDrawColorUniforms();
1828    setupDrawColorFilterUniforms();
1829    setupDrawPointUniforms();
1830    setupDrawShaderIdentityUniforms();
1831    setupDrawMesh(vertex);
1832
1833    for (int i = 0; i < count; i += 2) {
1834        TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
1835        generatedVerticesCount++;
1836        float left = points[i] - halfWidth;
1837        float right = points[i] + halfWidth;
1838        float top = points[i + 1] - halfWidth;
1839        float bottom = points [i + 1] + halfWidth;
1840        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1841    }
1842
1843    glDrawArrays(GL_POINTS, 0, generatedVerticesCount);
1844}
1845
1846void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
1847    // No need to check against the clip, we fill the clip region
1848    if (mSnapshot->isIgnored()) return;
1849
1850    Rect& clip(*mSnapshot->clipRect);
1851    clip.snapToPixelBoundaries();
1852
1853    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
1854}
1855
1856void OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture, SkPaint* paint) {
1857    if (!texture) return;
1858    const AutoTexture autoCleanup(texture);
1859
1860    const float x = left + texture->left - texture->offset;
1861    const float y = top + texture->top - texture->offset;
1862
1863    drawPathTexture(texture, x, y, paint);
1864}
1865
1866void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
1867        float rx, float ry, SkPaint* paint) {
1868    if (mSnapshot->isIgnored()) return;
1869
1870    glActiveTexture(gTextureUnits[0]);
1871    const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect(
1872            right - left, bottom - top, rx, ry, paint);
1873    drawShape(left, top, texture, paint);
1874}
1875
1876void OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* paint) {
1877    if (mSnapshot->isIgnored()) return;
1878
1879    glActiveTexture(gTextureUnits[0]);
1880    const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, paint);
1881    drawShape(x - radius, y - radius, texture, paint);
1882}
1883
1884void OpenGLRenderer::drawOval(float left, float top, float right, float bottom, SkPaint* paint) {
1885    if (mSnapshot->isIgnored()) return;
1886
1887    glActiveTexture(gTextureUnits[0]);
1888    const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, paint);
1889    drawShape(left, top, texture, paint);
1890}
1891
1892void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
1893        float startAngle, float sweepAngle, bool useCenter, SkPaint* paint) {
1894    if (mSnapshot->isIgnored()) return;
1895
1896    if (fabs(sweepAngle) >= 360.0f) {
1897        drawOval(left, top, right, bottom, paint);
1898        return;
1899    }
1900
1901    glActiveTexture(gTextureUnits[0]);
1902    const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top,
1903            startAngle, sweepAngle, useCenter, paint);
1904    drawShape(left, top, texture, paint);
1905}
1906
1907void OpenGLRenderer::drawRectAsShape(float left, float top, float right, float bottom,
1908        SkPaint* paint) {
1909    if (mSnapshot->isIgnored()) return;
1910
1911    glActiveTexture(gTextureUnits[0]);
1912    const PathTexture* texture = mCaches.rectShapeCache.getRect(right - left, bottom - top, paint);
1913    drawShape(left, top, texture, paint);
1914}
1915
1916void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
1917    if (p->getStyle() != SkPaint::kFill_Style) {
1918        drawRectAsShape(left, top, right, bottom, p);
1919        return;
1920    }
1921
1922    if (quickReject(left, top, right, bottom)) {
1923        return;
1924    }
1925
1926    SkXfermode::Mode mode;
1927    if (!mCaches.extensions.hasFramebufferFetch()) {
1928        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
1929        if (!isMode) {
1930            // Assume SRC_OVER
1931            mode = SkXfermode::kSrcOver_Mode;
1932        }
1933    } else {
1934        mode = getXfermode(p->getXfermode());
1935    }
1936
1937    int color = p->getColor();
1938    if (p->isAntiAlias()) {
1939        drawAARect(left, top, right, bottom, color, mode);
1940    } else {
1941        drawColorRect(left, top, right, bottom, color, mode);
1942    }
1943}
1944
1945void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
1946        float x, float y, SkPaint* paint) {
1947    if (text == NULL || count == 0) {
1948        return;
1949    }
1950    if (mSnapshot->isIgnored()) return;
1951
1952    // TODO: We should probably make a copy of the paint instead of modifying
1953    //       it; modifying the paint will change its generationID the first
1954    //       time, which might impact caches. More investigation needed to
1955    //       see if it matters.
1956    //       If we make a copy, then drawTextDecorations() should *not* make
1957    //       its own copy as it does right now.
1958    paint->setAntiAlias(true);
1959#if RENDER_TEXT_AS_GLYPHS
1960    paint->setTextEncoding(SkPaint::kGlyphID_TextEncoding);
1961#endif
1962
1963    float length = -1.0f;
1964    switch (paint->getTextAlign()) {
1965        case SkPaint::kCenter_Align:
1966            length = paint->measureText(text, bytesCount);
1967            x -= length / 2.0f;
1968            break;
1969        case SkPaint::kRight_Align:
1970            length = paint->measureText(text, bytesCount);
1971            x -= length;
1972            break;
1973        default:
1974            break;
1975    }
1976
1977    const float oldX = x;
1978    const float oldY = y;
1979    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1980    if (pureTranslate) {
1981        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
1982        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
1983    }
1984
1985    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
1986    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
1987            paint->getTextSize());
1988
1989    int alpha;
1990    SkXfermode::Mode mode;
1991    getAlphaAndMode(paint, &alpha, &mode);
1992
1993    if (mHasShadow) {
1994        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
1995        const ShadowTexture* shadow = mCaches.dropShadowCache.get(
1996                paint, text, bytesCount, count, mShadowRadius);
1997        const AutoTexture autoCleanup(shadow);
1998
1999        const float sx = oldX - shadow->left + mShadowDx;
2000        const float sy = oldY - shadow->top + mShadowDy;
2001
2002        const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
2003        int shadowColor = mShadowColor;
2004        if (mShader) {
2005            shadowColor = 0xffffffff;
2006        }
2007
2008        glActiveTexture(gTextureUnits[0]);
2009        setupDraw();
2010        setupDrawWithTexture(true);
2011        setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
2012        setupDrawColorFilter();
2013        setupDrawShader();
2014        setupDrawBlending(true, mode);
2015        setupDrawProgram();
2016        setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height);
2017        setupDrawTexture(shadow->id);
2018        setupDrawPureColorUniforms();
2019        setupDrawColorFilterUniforms();
2020        setupDrawShaderUniforms();
2021        setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2022
2023        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2024
2025        finishDrawTexture();
2026    }
2027
2028    if (paint->getAlpha() == 0 && paint->getXfermode() == NULL) {
2029        return;
2030    }
2031
2032    // Pick the appropriate texture filtering
2033    bool linearFilter = mSnapshot->transform->changesBounds();
2034    if (pureTranslate && !linearFilter) {
2035        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2036    }
2037
2038    glActiveTexture(gTextureUnits[0]);
2039    setupDraw();
2040    setupDrawDirtyRegionsDisabled();
2041    setupDrawWithTexture(true);
2042    setupDrawAlpha8Color(paint->getColor(), alpha);
2043    setupDrawColorFilter();
2044    setupDrawShader();
2045    setupDrawBlending(true, mode);
2046    setupDrawProgram();
2047    setupDrawModelView(x, y, x, y, pureTranslate, true);
2048    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2049    setupDrawPureColorUniforms();
2050    setupDrawColorFilterUniforms();
2051    setupDrawShaderUniforms(pureTranslate);
2052
2053    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
2054    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2055
2056#if RENDER_LAYERS_AS_REGIONS
2057    bool hasActiveLayer = hasLayer();
2058#else
2059    bool hasActiveLayer = false;
2060#endif
2061    mCaches.unbindMeshBuffer();
2062
2063    // Tell font renderer the locations of position and texture coord
2064    // attributes so it can bind its data properly
2065    int positionSlot = mCaches.currentProgram->position;
2066    fontRenderer.setAttributeBindingSlots(positionSlot, mTexCoordsSlot);
2067    if (fontRenderer.renderText(paint, clip, text, 0, bytesCount, count, x, y,
2068            hasActiveLayer ? &bounds : NULL)) {
2069#if RENDER_LAYERS_AS_REGIONS
2070        if (hasActiveLayer) {
2071            if (!pureTranslate) {
2072                mSnapshot->transform->mapRect(bounds);
2073            }
2074            dirtyLayerUnchecked(bounds, getRegion());
2075        }
2076#endif
2077    }
2078
2079    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
2080    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
2081
2082    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
2083}
2084
2085void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
2086    if (mSnapshot->isIgnored()) return;
2087
2088    glActiveTexture(gTextureUnits[0]);
2089
2090    const PathTexture* texture = mCaches.pathCache.get(path, paint);
2091    if (!texture) return;
2092    const AutoTexture autoCleanup(texture);
2093
2094    const float x = texture->left - texture->offset;
2095    const float y = texture->top - texture->offset;
2096
2097    drawPathTexture(texture, x, y, paint);
2098}
2099
2100void OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) {
2101    if (!layer || quickReject(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight())) {
2102        return;
2103    }
2104
2105    glActiveTexture(gTextureUnits[0]);
2106
2107    int alpha;
2108    SkXfermode::Mode mode;
2109    getAlphaAndMode(paint, &alpha, &mode);
2110
2111    layer->alpha = alpha;
2112    layer->mode = mode;
2113
2114#if RENDER_LAYERS_AS_REGIONS
2115    if (!layer->region.isEmpty()) {
2116        if (layer->region.isRect()) {
2117            composeLayerRect(layer, layer->regionRect);
2118        } else if (layer->mesh) {
2119            const float a = alpha / 255.0f;
2120            const Rect& rect = layer->layer;
2121
2122            setupDraw();
2123            setupDrawWithTexture();
2124            setupDrawColor(a, a, a, a);
2125            setupDrawColorFilter();
2126            setupDrawBlending(layer->blend || layer->alpha < 255, layer->mode, false);
2127            setupDrawProgram();
2128            setupDrawModelViewTranslate(x, y,
2129                    x + layer->layer.getWidth(), y + layer->layer.getHeight());
2130            setupDrawPureColorUniforms();
2131            setupDrawColorFilterUniforms();
2132            setupDrawTexture(layer->texture);
2133            setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]);
2134
2135            glDrawElements(GL_TRIANGLES, layer->meshElementCount,
2136                    GL_UNSIGNED_SHORT, layer->meshIndices);
2137
2138            finishDrawTexture();
2139
2140#if DEBUG_LAYERS_AS_REGIONS
2141            drawRegionRects(layer->region);
2142#endif
2143        }
2144    }
2145#else
2146    const Rect r(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight());
2147    composeLayerRect(layer, r);
2148#endif
2149}
2150
2151///////////////////////////////////////////////////////////////////////////////
2152// Shaders
2153///////////////////////////////////////////////////////////////////////////////
2154
2155void OpenGLRenderer::resetShader() {
2156    mShader = NULL;
2157}
2158
2159void OpenGLRenderer::setupShader(SkiaShader* shader) {
2160    mShader = shader;
2161    if (mShader) {
2162        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
2163    }
2164}
2165
2166///////////////////////////////////////////////////////////////////////////////
2167// Color filters
2168///////////////////////////////////////////////////////////////////////////////
2169
2170void OpenGLRenderer::resetColorFilter() {
2171    mColorFilter = NULL;
2172}
2173
2174void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
2175    mColorFilter = filter;
2176}
2177
2178///////////////////////////////////////////////////////////////////////////////
2179// Drop shadow
2180///////////////////////////////////////////////////////////////////////////////
2181
2182void OpenGLRenderer::resetShadow() {
2183    mHasShadow = false;
2184}
2185
2186void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
2187    mHasShadow = true;
2188    mShadowRadius = radius;
2189    mShadowDx = dx;
2190    mShadowDy = dy;
2191    mShadowColor = color;
2192}
2193
2194///////////////////////////////////////////////////////////////////////////////
2195// Drawing implementation
2196///////////////////////////////////////////////////////////////////////////////
2197
2198void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
2199        float x, float y, SkPaint* paint) {
2200    if (quickReject(x, y, x + texture->width, y + texture->height)) {
2201        return;
2202    }
2203
2204    int alpha;
2205    SkXfermode::Mode mode;
2206    getAlphaAndMode(paint, &alpha, &mode);
2207
2208    setupDraw();
2209    setupDrawWithTexture(true);
2210    setupDrawAlpha8Color(paint->getColor(), alpha);
2211    setupDrawColorFilter();
2212    setupDrawShader();
2213    setupDrawBlending(true, mode);
2214    setupDrawProgram();
2215    setupDrawModelView(x, y, x + texture->width, y + texture->height);
2216    setupDrawTexture(texture->id);
2217    setupDrawPureColorUniforms();
2218    setupDrawColorFilterUniforms();
2219    setupDrawShaderUniforms();
2220    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2221
2222    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2223
2224    finishDrawTexture();
2225}
2226
2227// Same values used by Skia
2228#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
2229#define kStdUnderline_Offset    (1.0f / 9.0f)
2230#define kStdUnderline_Thickness (1.0f / 18.0f)
2231
2232void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
2233        float x, float y, SkPaint* paint) {
2234    // Handle underline and strike-through
2235    uint32_t flags = paint->getFlags();
2236    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
2237        SkPaint paintCopy(*paint);
2238        float underlineWidth = length;
2239        // If length is > 0.0f, we already measured the text for the text alignment
2240        if (length <= 0.0f) {
2241            underlineWidth = paintCopy.measureText(text, bytesCount);
2242        }
2243
2244        float offsetX = 0;
2245        switch (paintCopy.getTextAlign()) {
2246            case SkPaint::kCenter_Align:
2247                offsetX = underlineWidth * 0.5f;
2248                break;
2249            case SkPaint::kRight_Align:
2250                offsetX = underlineWidth;
2251                break;
2252            default:
2253                break;
2254        }
2255
2256        if (underlineWidth > 0.0f) {
2257            const float textSize = paintCopy.getTextSize();
2258            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
2259
2260            const float left = x - offsetX;
2261            float top = 0.0f;
2262
2263            int linesCount = 0;
2264            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
2265            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
2266
2267            const int pointsCount = 4 * linesCount;
2268            float points[pointsCount];
2269            int currentPoint = 0;
2270
2271            if (flags & SkPaint::kUnderlineText_Flag) {
2272                top = y + textSize * kStdUnderline_Offset;
2273                points[currentPoint++] = left;
2274                points[currentPoint++] = top;
2275                points[currentPoint++] = left + underlineWidth;
2276                points[currentPoint++] = top;
2277            }
2278
2279            if (flags & SkPaint::kStrikeThruText_Flag) {
2280                top = y + textSize * kStdStrikeThru_Offset;
2281                points[currentPoint++] = left;
2282                points[currentPoint++] = top;
2283                points[currentPoint++] = left + underlineWidth;
2284                points[currentPoint++] = top;
2285            }
2286
2287            paintCopy.setStrokeWidth(strokeWidth);
2288
2289            drawLines(&points[0], pointsCount, &paintCopy);
2290        }
2291    }
2292}
2293
2294void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
2295        int color, SkXfermode::Mode mode, bool ignoreTransform) {
2296    // If a shader is set, preserve only the alpha
2297    if (mShader) {
2298        color |= 0x00ffffff;
2299    }
2300
2301    setupDraw();
2302    setupDrawColor(color);
2303    setupDrawShader();
2304    setupDrawColorFilter();
2305    setupDrawBlending(mode);
2306    setupDrawProgram();
2307    setupDrawModelView(left, top, right, bottom, ignoreTransform);
2308    setupDrawColorUniforms();
2309    setupDrawShaderUniforms(ignoreTransform);
2310    setupDrawColorFilterUniforms();
2311    setupDrawSimpleMesh();
2312
2313    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2314}
2315
2316void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
2317        Texture* texture, SkPaint* paint) {
2318    int alpha;
2319    SkXfermode::Mode mode;
2320    getAlphaAndMode(paint, &alpha, &mode);
2321
2322    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
2323
2324    if (mSnapshot->transform->isPureTranslate()) {
2325        const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
2326        const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
2327
2328        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
2329                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
2330                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
2331    } else {
2332        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
2333                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
2334                GL_TRIANGLE_STRIP, gMeshCount);
2335    }
2336}
2337
2338void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
2339        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
2340    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
2341            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
2342}
2343
2344void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
2345        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
2346        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
2347        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
2348
2349    setupDraw();
2350    setupDrawWithTexture();
2351    setupDrawColor(alpha, alpha, alpha, alpha);
2352    setupDrawColorFilter();
2353    setupDrawBlending(blend, mode, swapSrcDst);
2354    setupDrawProgram();
2355    if (!dirty) {
2356        setupDrawDirtyRegionsDisabled();
2357    }
2358    if (!ignoreScale) {
2359        setupDrawModelView(left, top, right, bottom, ignoreTransform);
2360    } else {
2361        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
2362    }
2363    setupDrawPureColorUniforms();
2364    setupDrawColorFilterUniforms();
2365    setupDrawTexture(texture);
2366    setupDrawMesh(vertices, texCoords, vbo);
2367
2368    glDrawArrays(drawMode, 0, elementsCount);
2369
2370    finishDrawTexture();
2371}
2372
2373void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
2374        ProgramDescription& description, bool swapSrcDst) {
2375    blend = blend || mode != SkXfermode::kSrcOver_Mode;
2376    if (blend) {
2377        if (mode < SkXfermode::kPlus_Mode) {
2378            if (!mCaches.blend) {
2379                glEnable(GL_BLEND);
2380            }
2381
2382            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
2383            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
2384
2385            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
2386                glBlendFunc(sourceMode, destMode);
2387                mCaches.lastSrcMode = sourceMode;
2388                mCaches.lastDstMode = destMode;
2389            }
2390        } else {
2391            // These blend modes are not supported by OpenGL directly and have
2392            // to be implemented using shaders. Since the shader will perform
2393            // the blending, turn blending off here
2394            if (mCaches.extensions.hasFramebufferFetch()) {
2395                description.framebufferMode = mode;
2396                description.swapSrcDst = swapSrcDst;
2397            }
2398
2399            if (mCaches.blend) {
2400                glDisable(GL_BLEND);
2401            }
2402            blend = false;
2403        }
2404    } else if (mCaches.blend) {
2405        glDisable(GL_BLEND);
2406    }
2407    mCaches.blend = blend;
2408}
2409
2410bool OpenGLRenderer::useProgram(Program* program) {
2411    if (!program->isInUse()) {
2412        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
2413        program->use();
2414        mCaches.currentProgram = program;
2415        return false;
2416    }
2417    return true;
2418}
2419
2420void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
2421    TextureVertex* v = &mMeshVertices[0];
2422    TextureVertex::setUV(v++, u1, v1);
2423    TextureVertex::setUV(v++, u2, v1);
2424    TextureVertex::setUV(v++, u1, v2);
2425    TextureVertex::setUV(v++, u2, v2);
2426}
2427
2428void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
2429    if (paint) {
2430        if (!mCaches.extensions.hasFramebufferFetch()) {
2431            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
2432            if (!isMode) {
2433                // Assume SRC_OVER
2434                *mode = SkXfermode::kSrcOver_Mode;
2435            }
2436        } else {
2437            *mode = getXfermode(paint->getXfermode());
2438        }
2439
2440        // Skia draws using the color's alpha channel if < 255
2441        // Otherwise, it uses the paint's alpha
2442        int color = paint->getColor();
2443        *alpha = (color >> 24) & 0xFF;
2444        if (*alpha == 255) {
2445            *alpha = paint->getAlpha();
2446        }
2447    } else {
2448        *mode = SkXfermode::kSrcOver_Mode;
2449        *alpha = 255;
2450    }
2451}
2452
2453SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
2454    SkXfermode::Mode resultMode;
2455    if (!SkXfermode::AsMode(mode, &resultMode)) {
2456        resultMode = SkXfermode::kSrcOver_Mode;
2457    }
2458    return resultMode;
2459}
2460
2461void OpenGLRenderer::setTextureWrapModes(Texture* texture, GLenum wrapS, GLenum wrapT) {
2462    bool bound = false;
2463    if (wrapS != texture->wrapS) {
2464        glBindTexture(GL_TEXTURE_2D, texture->id);
2465        bound = true;
2466        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
2467        texture->wrapS = wrapS;
2468    }
2469    if (wrapT != texture->wrapT) {
2470        if (!bound) {
2471            glBindTexture(GL_TEXTURE_2D, texture->id);
2472        }
2473        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
2474        texture->wrapT = wrapT;
2475    }
2476}
2477
2478}; // namespace uirenderer
2479}; // namespace android
2480