OpenGLRenderer.cpp revision c78b5d50f961ac8f696f8282979ae283cacd3574
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 <ui/Rect.h>
30
31#include "OpenGLRenderer.h"
32#include "DisplayListRenderer.h"
33#include "Vector.h"
34
35namespace android {
36namespace uirenderer {
37
38///////////////////////////////////////////////////////////////////////////////
39// Defines
40///////////////////////////////////////////////////////////////////////////////
41
42#define RAD_TO_DEG (180.0f / 3.14159265f)
43#define MIN_ANGLE 0.001f
44
45// TODO: This should be set in properties
46#define ALPHA_THRESHOLD (0x7f / PANEL_BIT_DEPTH)
47
48///////////////////////////////////////////////////////////////////////////////
49// Globals
50///////////////////////////////////////////////////////////////////////////////
51
52/**
53 * Structure mapping Skia xfermodes to OpenGL blending factors.
54 */
55struct Blender {
56    SkXfermode::Mode mode;
57    GLenum src;
58    GLenum dst;
59}; // struct Blender
60
61// In this array, the index of each Blender equals the value of the first
62// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
63static const Blender gBlends[] = {
64    { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
65    { SkXfermode::kSrc_Mode,     GL_ONE,                  GL_ZERO },
66    { SkXfermode::kDst_Mode,     GL_ZERO,                 GL_ONE },
67    { SkXfermode::kSrcOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
68    { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
69    { SkXfermode::kSrcIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
70    { SkXfermode::kDstIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
71    { SkXfermode::kSrcOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
72    { SkXfermode::kDstOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
73    { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
74    { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
75    { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
76};
77
78// This array contains the swapped version of each SkXfermode. For instance
79// this array's SrcOver blending mode is actually DstOver. You can refer to
80// createLayer() for more information on the purpose of this array.
81static const Blender gBlendsSwap[] = {
82    { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
83    { SkXfermode::kSrc_Mode,     GL_ZERO,                 GL_ONE },
84    { SkXfermode::kDst_Mode,     GL_ONE,                  GL_ZERO },
85    { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
86    { SkXfermode::kDstOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
87    { SkXfermode::kSrcIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
88    { SkXfermode::kDstIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
89    { SkXfermode::kSrcOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
90    { SkXfermode::kDstOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
91    { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
92    { SkXfermode::kDstATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
93    { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
94};
95
96static const GLenum gTextureUnits[] = {
97    GL_TEXTURE0,
98    GL_TEXTURE1,
99    GL_TEXTURE2
100};
101
102///////////////////////////////////////////////////////////////////////////////
103// Constructors/destructor
104///////////////////////////////////////////////////////////////////////////////
105
106OpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) {
107    mShader = NULL;
108    mColorFilter = NULL;
109    mHasShadow = false;
110
111    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
112
113    mFirstSnapshot = new Snapshot;
114}
115
116OpenGLRenderer::~OpenGLRenderer() {
117    // The context has already been destroyed at this point, do not call
118    // GL APIs. All GL state should be kept in Caches.h
119}
120
121///////////////////////////////////////////////////////////////////////////////
122// Setup
123///////////////////////////////////////////////////////////////////////////////
124
125void OpenGLRenderer::setViewport(int width, int height) {
126    glViewport(0, 0, width, height);
127    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
128
129    mWidth = width;
130    mHeight = height;
131
132    mFirstSnapshot->height = height;
133    mFirstSnapshot->viewport.set(0, 0, width, height);
134
135    mDirtyClip = false;
136}
137
138void OpenGLRenderer::prepare(bool opaque) {
139    prepareDirty(0.0f, 0.0f, mWidth, mHeight, opaque);
140}
141
142void OpenGLRenderer::prepareDirty(float left, float top, float right, float bottom, bool opaque) {
143    mCaches.clearGarbage();
144
145    mSnapshot = new Snapshot(mFirstSnapshot,
146            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
147    mSaveCount = 1;
148
149    glViewport(0, 0, mWidth, mHeight);
150
151    glDisable(GL_DITHER);
152
153    glEnable(GL_SCISSOR_TEST);
154    glScissor(left, mSnapshot->height - bottom, right - left, bottom - top);
155    mSnapshot->setClip(left, top, right, bottom);
156
157    if (!opaque) {
158        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
159        glClear(GL_COLOR_BUFFER_BIT);
160    }
161}
162
163void OpenGLRenderer::finish() {
164#if DEBUG_OPENGL
165    GLenum status = GL_NO_ERROR;
166    while ((status = glGetError()) != GL_NO_ERROR) {
167        LOGD("GL error from OpenGLRenderer: 0x%x", status);
168        switch (status) {
169            case GL_OUT_OF_MEMORY:
170                LOGE("  OpenGLRenderer is out of memory!");
171                break;
172        }
173    }
174#endif
175#if DEBUG_MEMORY_USAGE
176    mCaches.dumpMemoryUsage();
177#else
178    if (mCaches.getDebugLevel() & kDebugMemory) {
179        mCaches.dumpMemoryUsage();
180    }
181#endif
182}
183
184void OpenGLRenderer::interrupt() {
185    if (mCaches.currentProgram) {
186        if (mCaches.currentProgram->isInUse()) {
187            mCaches.currentProgram->remove();
188            mCaches.currentProgram = NULL;
189        }
190    }
191    mCaches.unbindMeshBuffer();
192}
193
194void OpenGLRenderer::resume() {
195    glViewport(0, 0, mSnapshot->viewport.getWidth(), mSnapshot->viewport.getHeight());
196
197    glEnable(GL_SCISSOR_TEST);
198    dirtyClip();
199
200    glDisable(GL_DITHER);
201
202    glBindFramebuffer(GL_FRAMEBUFFER, getTargetFbo());
203    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
204
205    mCaches.blend = true;
206    glEnable(GL_BLEND);
207    glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
208    glBlendEquation(GL_FUNC_ADD);
209}
210
211bool OpenGLRenderer::callDrawGLFunction(Functor *functor) {
212    interrupt();
213    if (mDirtyClip) {
214        setScissorFromClip();
215    }
216    status_t result = (*functor)();
217    resume();
218    return (result == 0) ? false : true;
219}
220
221///////////////////////////////////////////////////////////////////////////////
222// State management
223///////////////////////////////////////////////////////////////////////////////
224
225int OpenGLRenderer::getSaveCount() const {
226    return mSaveCount;
227}
228
229int OpenGLRenderer::save(int flags) {
230    return saveSnapshot(flags);
231}
232
233void OpenGLRenderer::restore() {
234    if (mSaveCount > 1) {
235        restoreSnapshot();
236    }
237}
238
239void OpenGLRenderer::restoreToCount(int saveCount) {
240    if (saveCount < 1) saveCount = 1;
241
242    while (mSaveCount > saveCount) {
243        restoreSnapshot();
244    }
245}
246
247int OpenGLRenderer::saveSnapshot(int flags) {
248    mSnapshot = new Snapshot(mSnapshot, flags);
249    return mSaveCount++;
250}
251
252bool OpenGLRenderer::restoreSnapshot() {
253    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
254    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
255    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
256
257    sp<Snapshot> current = mSnapshot;
258    sp<Snapshot> previous = mSnapshot->previous;
259
260    if (restoreOrtho) {
261        Rect& r = previous->viewport;
262        glViewport(r.left, r.top, r.right, r.bottom);
263        mOrthoMatrix.load(current->orthoMatrix);
264    }
265
266    mSaveCount--;
267    mSnapshot = previous;
268
269    if (restoreClip) {
270        dirtyClip();
271    }
272
273    if (restoreLayer) {
274        composeLayer(current, previous);
275    }
276
277    return restoreClip;
278}
279
280///////////////////////////////////////////////////////////////////////////////
281// Layers
282///////////////////////////////////////////////////////////////////////////////
283
284int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
285        SkPaint* p, int flags) {
286    const GLuint previousFbo = mSnapshot->fbo;
287    const int count = saveSnapshot(flags);
288
289    if (!mSnapshot->isIgnored()) {
290        int alpha = 255;
291        SkXfermode::Mode mode;
292
293        if (p) {
294            alpha = p->getAlpha();
295            if (!mCaches.extensions.hasFramebufferFetch()) {
296                const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
297                if (!isMode) {
298                    // Assume SRC_OVER
299                    mode = SkXfermode::kSrcOver_Mode;
300                }
301            } else {
302                mode = getXfermode(p->getXfermode());
303            }
304        } else {
305            mode = SkXfermode::kSrcOver_Mode;
306        }
307
308        createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags, previousFbo);
309    }
310
311    return count;
312}
313
314int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
315        int alpha, int flags) {
316    if (alpha >= 255 - ALPHA_THRESHOLD) {
317        return saveLayer(left, top, right, bottom, NULL, flags);
318    } else {
319        SkPaint paint;
320        paint.setAlpha(alpha);
321        return saveLayer(left, top, right, bottom, &paint, flags);
322    }
323}
324
325/**
326 * Layers are viewed by Skia are slightly different than layers in image editing
327 * programs (for instance.) When a layer is created, previously created layers
328 * and the frame buffer still receive every drawing command. For instance, if a
329 * layer is created and a shape intersecting the bounds of the layers and the
330 * framebuffer is draw, the shape will be drawn on both (unless the layer was
331 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
332 *
333 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
334 * texture. Unfortunately, this is inefficient as it requires every primitive to
335 * be drawn n + 1 times, where n is the number of active layers. In practice this
336 * means, for every primitive:
337 *   - Switch active frame buffer
338 *   - Change viewport, clip and projection matrix
339 *   - Issue the drawing
340 *
341 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
342 * To avoid this, layers are implemented in a different way here, at least in the
343 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
344 * is set. When this flag is set we can redirect all drawing operations into a
345 * single FBO.
346 *
347 * This implementation relies on the frame buffer being at least RGBA 8888. When
348 * a layer is created, only a texture is created, not an FBO. The content of the
349 * frame buffer contained within the layer's bounds is copied into this texture
350 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
351 * buffer and drawing continues as normal. This technique therefore treats the
352 * frame buffer as a scratch buffer for the layers.
353 *
354 * To compose the layers back onto the frame buffer, each layer texture
355 * (containing the original frame buffer data) is drawn as a simple quad over
356 * the frame buffer. The trick is that the quad is set as the composition
357 * destination in the blending equation, and the frame buffer becomes the source
358 * of the composition.
359 *
360 * Drawing layers with an alpha value requires an extra step before composition.
361 * An empty quad is drawn over the layer's region in the frame buffer. This quad
362 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
363 * quad is used to multiply the colors in the frame buffer. This is achieved by
364 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
365 * GL_ZERO, GL_SRC_ALPHA.
366 *
367 * Because glCopyTexImage2D() can be slow, an alternative implementation might
368 * be use to draw a single clipped layer. The implementation described above
369 * is correct in every case.
370 *
371 * (1) The frame buffer is actually not cleared right away. To allow the GPU
372 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
373 *     buffer is left untouched until the first drawing operation. Only when
374 *     something actually gets drawn are the layers regions cleared.
375 */
376bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
377        float right, float bottom, int alpha, SkXfermode::Mode mode,
378        int flags, GLuint previousFbo) {
379    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
380    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
381
382    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
383
384    // Window coordinates of the layer
385    Rect bounds(left, top, right, bottom);
386    if (fboLayer) {
387        // Clear the previous layer regions before we change the viewport
388        clearLayerRegions();
389    } else {
390        mSnapshot->transform->mapRect(bounds);
391
392        // Layers only make sense if they are in the framebuffer's bounds
393        bounds.intersect(*snapshot->clipRect);
394
395        // We cannot work with sub-pixels in this case
396        bounds.snapToPixelBoundaries();
397
398        // When the layer is not an FBO, we may use glCopyTexImage so we
399        // need to make sure the layer does not extend outside the bounds
400        // of the framebuffer
401        bounds.intersect(snapshot->previous->viewport);
402    }
403
404    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
405            bounds.getHeight() > mCaches.maxTextureSize) {
406        snapshot->empty = fboLayer;
407    } else {
408        snapshot->invisible = snapshot->invisible || (alpha <= ALPHA_THRESHOLD && fboLayer);
409    }
410
411    // Bail out if we won't draw in this snapshot
412    if (snapshot->invisible || snapshot->empty) {
413        return false;
414    }
415
416    glActiveTexture(gTextureUnits[0]);
417    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
418    if (!layer) {
419        return false;
420    }
421
422    layer->mode = mode;
423    layer->alpha = alpha;
424    layer->layer.set(bounds);
425    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->height),
426            bounds.getWidth() / float(layer->width), 0.0f);
427    layer->colorFilter = mColorFilter;
428
429    // Save the layer in the snapshot
430    snapshot->flags |= Snapshot::kFlagIsLayer;
431    snapshot->layer = layer;
432
433    if (fboLayer) {
434        return createFboLayer(layer, bounds, snapshot, previousFbo);
435    } else {
436        // Copy the framebuffer into the layer
437        glBindTexture(GL_TEXTURE_2D, layer->texture);
438        if (!bounds.isEmpty()) {
439            if (layer->empty) {
440                glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left,
441                        snapshot->height - bounds.bottom, layer->width, layer->height, 0);
442                layer->empty = false;
443            } else {
444                glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left,
445                        snapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight());
446            }
447            // Enqueue the buffer coordinates to clear the corresponding region later
448            mLayers.push(new Rect(bounds));
449        }
450    }
451
452    return true;
453}
454
455bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, sp<Snapshot> snapshot,
456        GLuint previousFbo) {
457    layer->fbo = mCaches.fboCache.get();
458
459#if RENDER_LAYERS_AS_REGIONS
460    snapshot->region = &snapshot->layer->region;
461    snapshot->flags |= Snapshot::kFlagFboTarget;
462#endif
463
464    Rect clip(bounds);
465    snapshot->transform->mapRect(clip);
466    clip.intersect(*snapshot->clipRect);
467    clip.snapToPixelBoundaries();
468    clip.intersect(snapshot->previous->viewport);
469
470    mat4 inverse;
471    inverse.loadInverse(*mSnapshot->transform);
472
473    inverse.mapRect(clip);
474    clip.snapToPixelBoundaries();
475    clip.intersect(bounds);
476    clip.translate(-bounds.left, -bounds.top);
477
478    snapshot->flags |= Snapshot::kFlagIsFboLayer;
479    snapshot->fbo = layer->fbo;
480    snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
481    snapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
482    snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
483    snapshot->height = bounds.getHeight();
484    snapshot->flags |= Snapshot::kFlagDirtyOrtho;
485    snapshot->orthoMatrix.load(mOrthoMatrix);
486
487    // Bind texture to FBO
488    glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
489    glBindTexture(GL_TEXTURE_2D, layer->texture);
490
491    // Initialize the texture if needed
492    if (layer->empty) {
493        layer->empty = false;
494        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->width, layer->height, 0,
495                GL_RGBA, GL_UNSIGNED_BYTE, NULL);
496    }
497
498    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
499            layer->texture, 0);
500
501#if DEBUG_LAYERS_AS_REGIONS
502    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
503    if (status != GL_FRAMEBUFFER_COMPLETE) {
504        LOGE("Framebuffer incomplete (GL error code 0x%x)", status);
505
506        glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
507        glDeleteTextures(1, &layer->texture);
508        mCaches.fboCache.put(layer->fbo);
509
510        delete layer;
511
512        return false;
513    }
514#endif
515
516    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
517    glScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
518            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
519    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
520    glClear(GL_COLOR_BUFFER_BIT);
521
522    dirtyClip();
523
524    // Change the ortho projection
525    glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
526    mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
527
528    return true;
529}
530
531/**
532 * Read the documentation of createLayer() before doing anything in this method.
533 */
534void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
535    if (!current->layer) {
536        LOGE("Attempting to compose a layer that does not exist");
537        return;
538    }
539
540    const bool fboLayer = current->flags & Snapshot::kFlagIsFboLayer;
541
542    if (fboLayer) {
543        // Unbind current FBO and restore previous one
544        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
545    }
546
547    Layer* layer = current->layer;
548    const Rect& rect = layer->layer;
549
550    if (!fboLayer && layer->alpha < 255) {
551        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
552                layer->alpha << 24, SkXfermode::kDstIn_Mode, true);
553        // Required below, composeLayerRect() will divide by 255
554        layer->alpha = 255;
555    }
556
557    mCaches.unbindMeshBuffer();
558
559    glActiveTexture(gTextureUnits[0]);
560
561    // When the layer is stored in an FBO, we can save a bit of fillrate by
562    // drawing only the dirty region
563    if (fboLayer) {
564        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform);
565        if (layer->colorFilter) {
566            setupColorFilter(layer->colorFilter);
567        }
568        composeLayerRegion(layer, rect);
569        if (layer->colorFilter) {
570            resetColorFilter();
571        }
572    } else {
573        if (!rect.isEmpty()) {
574            dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
575            composeLayerRect(layer, rect, true);
576        }
577    }
578
579    if (fboLayer) {
580        // Detach the texture from the FBO
581        glBindFramebuffer(GL_FRAMEBUFFER, current->fbo);
582        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
583        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
584
585        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
586        mCaches.fboCache.put(current->fbo);
587    }
588
589    dirtyClip();
590
591    // Failing to add the layer to the cache should happen only if the layer is too large
592    if (!mCaches.layerCache.put(layer)) {
593        LAYER_LOGD("Deleting layer");
594        glDeleteTextures(1, &layer->texture);
595        delete layer;
596    }
597}
598
599void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
600    const Rect& texCoords = layer->texCoords;
601    resetDrawTextureTexCoords(texCoords.left, texCoords.top, texCoords.right, texCoords.bottom);
602
603    drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
604            layer->alpha / 255.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
605            &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount, swap, swap);
606
607    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
608}
609
610void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
611#if RENDER_LAYERS_AS_REGIONS
612    if (layer->region.isRect()) {
613        composeLayerRect(layer, rect);
614        layer->region.clear();
615        return;
616    }
617
618    if (!layer->region.isEmpty()) {
619        size_t count;
620        const android::Rect* rects = layer->region.getArray(&count);
621
622        const float alpha = layer->alpha / 255.0f;
623        const float texX = 1.0f / float(layer->width);
624        const float texY = 1.0f / float(layer->height);
625        const float height = rect.getHeight();
626
627        TextureVertex* mesh = mCaches.getRegionMesh();
628        GLsizei numQuads = 0;
629
630        setupDraw();
631        setupDrawWithTexture();
632        setupDrawColor(alpha, alpha, alpha, alpha);
633        setupDrawColorFilter();
634        setupDrawBlending(layer->blend || layer->alpha < 255, layer->mode, false);
635        setupDrawProgram();
636        setupDrawDirtyRegionsDisabled();
637        setupDrawPureColorUniforms();
638        setupDrawColorFilterUniforms();
639        setupDrawTexture(layer->texture);
640        setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
641        setupDrawMesh(&mesh[0].position[0], &mesh[0].texture[0]);
642
643        for (size_t i = 0; i < count; i++) {
644            const android::Rect* r = &rects[i];
645
646            const float u1 = r->left * texX;
647            const float v1 = (height - r->top) * texY;
648            const float u2 = r->right * texX;
649            const float v2 = (height - r->bottom) * texY;
650
651            // TODO: Reject quads outside of the clip
652            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
653            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
654            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
655            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
656
657            numQuads++;
658
659            if (numQuads >= REGION_MESH_QUAD_COUNT) {
660                glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
661                numQuads = 0;
662                mesh = mCaches.getRegionMesh();
663            }
664        }
665
666        if (numQuads > 0) {
667            glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
668        }
669
670        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
671        finishDrawTexture();
672
673#if DEBUG_LAYERS_AS_REGIONS
674        drawRegionRects(layer->region);
675#endif
676
677        layer->region.clear();
678    }
679#else
680    composeLayerRect(layer, rect);
681#endif
682}
683
684void OpenGLRenderer::drawRegionRects(const Region& region) {
685#if DEBUG_LAYERS_AS_REGIONS
686    size_t count;
687    const android::Rect* rects = region.getArray(&count);
688
689    uint32_t colors[] = {
690            0x7fff0000, 0x7f00ff00,
691            0x7f0000ff, 0x7fff00ff,
692    };
693
694    int offset = 0;
695    int32_t top = rects[0].top;
696
697    for (size_t i = 0; i < count; i++) {
698        if (top != rects[i].top) {
699            offset ^= 0x2;
700            top = rects[i].top;
701        }
702
703        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
704        drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
705                SkXfermode::kSrcOver_Mode);
706    }
707#endif
708}
709
710void OpenGLRenderer::dirtyLayer(const float left, const float top,
711        const float right, const float bottom, const mat4 transform) {
712#if RENDER_LAYERS_AS_REGIONS
713    if (hasLayer()) {
714        Rect bounds(left, top, right, bottom);
715        transform.mapRect(bounds);
716        dirtyLayerUnchecked(bounds, getRegion());
717    }
718#endif
719}
720
721void OpenGLRenderer::dirtyLayer(const float left, const float top,
722        const float right, const float bottom) {
723#if RENDER_LAYERS_AS_REGIONS
724    if (hasLayer()) {
725        Rect bounds(left, top, right, bottom);
726        dirtyLayerUnchecked(bounds, getRegion());
727    }
728#endif
729}
730
731void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
732#if RENDER_LAYERS_AS_REGIONS
733    if (bounds.intersect(*mSnapshot->clipRect)) {
734        bounds.snapToPixelBoundaries();
735        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
736        if (!dirty.isEmpty()) {
737            region->orSelf(dirty);
738        }
739    }
740#endif
741}
742
743void OpenGLRenderer::clearLayerRegions() {
744    if (mLayers.size() == 0 || mSnapshot->isIgnored()) return;
745
746    Rect clipRect(*mSnapshot->clipRect);
747    clipRect.snapToPixelBoundaries();
748
749    for (uint32_t i = 0; i < mLayers.size(); i++) {
750        Rect* bounds = mLayers.itemAt(i);
751        if (clipRect.intersects(*bounds)) {
752            // Clear the framebuffer where the layer will draw
753            glScissor(bounds->left, mSnapshot->height - bounds->bottom,
754                    bounds->getWidth(), bounds->getHeight());
755            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
756            glClear(GL_COLOR_BUFFER_BIT);
757
758            // Restore the clip
759            dirtyClip();
760        }
761
762        delete bounds;
763    }
764
765    mLayers.clear();
766}
767
768///////////////////////////////////////////////////////////////////////////////
769// Transforms
770///////////////////////////////////////////////////////////////////////////////
771
772void OpenGLRenderer::translate(float dx, float dy) {
773    mSnapshot->transform->translate(dx, dy, 0.0f);
774}
775
776void OpenGLRenderer::rotate(float degrees) {
777    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
778}
779
780void OpenGLRenderer::scale(float sx, float sy) {
781    mSnapshot->transform->scale(sx, sy, 1.0f);
782}
783
784void OpenGLRenderer::skew(float sx, float sy) {
785    mSnapshot->transform->skew(sx, sy);
786}
787
788void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
789    mSnapshot->transform->load(*matrix);
790}
791
792const float* OpenGLRenderer::getMatrix() const {
793    if (mSnapshot->fbo != 0) {
794        return &mSnapshot->transform->data[0];
795    }
796    return &mIdentity.data[0];
797}
798
799void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
800    mSnapshot->transform->copyTo(*matrix);
801}
802
803void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
804    SkMatrix transform;
805    mSnapshot->transform->copyTo(transform);
806    transform.preConcat(*matrix);
807    mSnapshot->transform->load(transform);
808}
809
810///////////////////////////////////////////////////////////////////////////////
811// Clipping
812///////////////////////////////////////////////////////////////////////////////
813
814void OpenGLRenderer::setScissorFromClip() {
815    Rect clip(*mSnapshot->clipRect);
816    clip.snapToPixelBoundaries();
817    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
818    mDirtyClip = false;
819}
820
821const Rect& OpenGLRenderer::getClipBounds() {
822    return mSnapshot->getLocalClip();
823}
824
825bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
826    if (mSnapshot->isIgnored()) {
827        return true;
828    }
829
830    Rect r(left, top, right, bottom);
831    mSnapshot->transform->mapRect(r);
832    r.snapToPixelBoundaries();
833
834    Rect clipRect(*mSnapshot->clipRect);
835    clipRect.snapToPixelBoundaries();
836
837    return !clipRect.intersects(r);
838}
839
840bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
841    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
842    if (clipped) {
843        dirtyClip();
844    }
845    return !mSnapshot->clipRect->isEmpty();
846}
847
848///////////////////////////////////////////////////////////////////////////////
849// Drawing commands
850///////////////////////////////////////////////////////////////////////////////
851
852void OpenGLRenderer::setupDraw() {
853    clearLayerRegions();
854    if (mDirtyClip) {
855        setScissorFromClip();
856    }
857    mDescription.reset();
858    mSetShaderColor = false;
859    mColorSet = false;
860    mColorA = mColorR = mColorG = mColorB = 0.0f;
861    mTextureUnit = 0;
862    mTrackDirtyRegions = true;
863    mTexCoordsSlot = -1;
864}
865
866void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
867    mDescription.hasTexture = true;
868    mDescription.hasAlpha8Texture = isAlpha8;
869}
870
871void OpenGLRenderer::setupDrawColor(int color) {
872    setupDrawColor(color, (color >> 24) & 0xFF);
873}
874
875void OpenGLRenderer::setupDrawColor(int color, int alpha) {
876    mColorA = alpha / 255.0f;
877    const float a = mColorA / 255.0f;
878    mColorR = a * ((color >> 16) & 0xFF);
879    mColorG = a * ((color >>  8) & 0xFF);
880    mColorB = a * ((color      ) & 0xFF);
881    mColorSet = true;
882    mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA);
883}
884
885void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
886    mColorA = alpha / 255.0f;
887    const float a = mColorA / 255.0f;
888    mColorR = a * ((color >> 16) & 0xFF);
889    mColorG = a * ((color >>  8) & 0xFF);
890    mColorB = a * ((color      ) & 0xFF);
891    mColorSet = true;
892    mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
893}
894
895void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
896    mColorA = a;
897    mColorR = r;
898    mColorG = g;
899    mColorB = b;
900    mColorSet = true;
901    mSetShaderColor = mDescription.setColor(r, g, b, a);
902}
903
904void OpenGLRenderer::setupDrawAlpha8Color(float r, float g, float b, float a) {
905    mColorA = a;
906    mColorR = r;
907    mColorG = g;
908    mColorB = b;
909    mColorSet = true;
910    mSetShaderColor = mDescription.setAlpha8Color(r, g, b, a);
911}
912
913void OpenGLRenderer::setupDrawShader() {
914    if (mShader) {
915        mShader->describe(mDescription, mCaches.extensions);
916    }
917}
918
919void OpenGLRenderer::setupDrawColorFilter() {
920    if (mColorFilter) {
921        mColorFilter->describe(mDescription, mCaches.extensions);
922    }
923}
924
925void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) {
926    chooseBlending((mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
927            mDescription, swapSrcDst);
928}
929
930void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) {
931    chooseBlending(blend || (mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
932            mDescription, swapSrcDst);
933}
934
935void OpenGLRenderer::setupDrawProgram() {
936    useProgram(mCaches.programCache.get(mDescription));
937}
938
939void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
940    mTrackDirtyRegions = false;
941}
942
943void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom,
944        bool ignoreTransform) {
945    mModelView.loadTranslate(left, top, 0.0f);
946    if (!ignoreTransform) {
947        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
948        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
949    } else {
950        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
951        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
952    }
953}
954
955void OpenGLRenderer::setupDrawModelViewIdentity() {
956    mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform);
957}
958
959void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom,
960        bool ignoreTransform, bool ignoreModelView) {
961    if (!ignoreModelView) {
962        mModelView.loadTranslate(left, top, 0.0f);
963        mModelView.scale(right - left, bottom - top, 1.0f);
964    } else {
965        mModelView.loadIdentity();
966    }
967    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
968    if (!ignoreTransform) {
969        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
970        if (mTrackDirtyRegions && dirty) {
971            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
972        }
973    } else {
974        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
975        if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom);
976    }
977}
978
979void OpenGLRenderer::setupDrawColorUniforms() {
980    if (mColorSet || (mShader && mSetShaderColor)) {
981        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
982    }
983}
984
985void OpenGLRenderer::setupDrawPureColorUniforms() {
986    if (mSetShaderColor) {
987        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
988    }
989}
990
991void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
992    if (mShader) {
993        if (ignoreTransform) {
994            mModelView.loadInverse(*mSnapshot->transform);
995        }
996        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &mTextureUnit);
997    }
998}
999
1000void OpenGLRenderer::setupDrawShaderIdentityUniforms() {
1001    if (mShader) {
1002        mShader->setupProgram(mCaches.currentProgram, mIdentity, *mSnapshot, &mTextureUnit);
1003    }
1004}
1005
1006void OpenGLRenderer::setupDrawColorFilterUniforms() {
1007    if (mColorFilter) {
1008        mColorFilter->setupProgram(mCaches.currentProgram);
1009    }
1010}
1011
1012void OpenGLRenderer::setupDrawSimpleMesh() {
1013    mCaches.bindMeshBuffer();
1014    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1015            gMeshStride, 0);
1016}
1017
1018void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1019    bindTexture(texture);
1020    glUniform1i(mCaches.currentProgram->getUniform("sampler"), mTextureUnit++);
1021
1022    mTexCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1023    glEnableVertexAttribArray(mTexCoordsSlot);
1024}
1025
1026void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1027    if (!vertices) {
1028        mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1029    } else {
1030        mCaches.unbindMeshBuffer();
1031    }
1032    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1033            gMeshStride, vertices);
1034    if (mTexCoordsSlot > 0) {
1035        glVertexAttribPointer(mTexCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1036    }
1037}
1038
1039void OpenGLRenderer::finishDrawTexture() {
1040    glDisableVertexAttribArray(mTexCoordsSlot);
1041}
1042
1043///////////////////////////////////////////////////////////////////////////////
1044// Drawing
1045///////////////////////////////////////////////////////////////////////////////
1046
1047bool OpenGLRenderer::drawDisplayList(DisplayList* displayList, uint32_t level) {
1048    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1049    // will be performed by the display list itself
1050    if (displayList) {
1051        return displayList->replay(*this, level);
1052    }
1053    return false;
1054}
1055
1056void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1057    const float right = left + bitmap->width();
1058    const float bottom = top + bitmap->height();
1059
1060    if (quickReject(left, top, right, bottom)) {
1061        return;
1062    }
1063
1064    glActiveTexture(gTextureUnits[0]);
1065    Texture* texture = mCaches.textureCache.get(bitmap);
1066    if (!texture) return;
1067    const AutoTexture autoCleanup(texture);
1068
1069    drawTextureRect(left, top, right, bottom, texture, paint);
1070}
1071
1072void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
1073    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
1074    const mat4 transform(*matrix);
1075    transform.mapRect(r);
1076
1077    if (quickReject(r.left, r.top, r.right, r.bottom)) {
1078        return;
1079    }
1080
1081    glActiveTexture(gTextureUnits[0]);
1082    Texture* texture = mCaches.textureCache.get(bitmap);
1083    if (!texture) return;
1084    const AutoTexture autoCleanup(texture);
1085
1086    // This could be done in a cheaper way, all we need is pass the matrix
1087    // to the vertex shader. The save/restore is a bit overkill.
1088    save(SkCanvas::kMatrix_SaveFlag);
1089    concatMatrix(matrix);
1090    drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
1091    restore();
1092}
1093
1094void OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
1095        float* vertices, int* colors, SkPaint* paint) {
1096    // TODO: Do a quickReject
1097    if (!vertices || mSnapshot->isIgnored()) {
1098        return;
1099    }
1100
1101    glActiveTexture(gTextureUnits[0]);
1102    Texture* texture = mCaches.textureCache.get(bitmap);
1103    if (!texture) return;
1104    const AutoTexture autoCleanup(texture);
1105    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1106
1107    int alpha;
1108    SkXfermode::Mode mode;
1109    getAlphaAndMode(paint, &alpha, &mode);
1110
1111    const uint32_t count = meshWidth * meshHeight * 6;
1112
1113    // TODO: Support the colors array
1114    TextureVertex mesh[count];
1115    TextureVertex* vertex = mesh;
1116    for (int32_t y = 0; y < meshHeight; y++) {
1117        for (int32_t x = 0; x < meshWidth; x++) {
1118            uint32_t i = (y * (meshWidth + 1) + x) * 2;
1119
1120            float u1 = float(x) / meshWidth;
1121            float u2 = float(x + 1) / meshWidth;
1122            float v1 = float(y) / meshHeight;
1123            float v2 = float(y + 1) / meshHeight;
1124
1125            int ax = i + (meshWidth + 1) * 2;
1126            int ay = ax + 1;
1127            int bx = i;
1128            int by = bx + 1;
1129            int cx = i + 2;
1130            int cy = cx + 1;
1131            int dx = i + (meshWidth + 1) * 2 + 2;
1132            int dy = dx + 1;
1133
1134            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1135            TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1);
1136            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1137
1138            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1139            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1140            TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2);
1141        }
1142    }
1143
1144    drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f,
1145            mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0],
1146            GL_TRIANGLES, count);
1147}
1148
1149void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
1150         float srcLeft, float srcTop, float srcRight, float srcBottom,
1151         float dstLeft, float dstTop, float dstRight, float dstBottom,
1152         SkPaint* paint) {
1153    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
1154        return;
1155    }
1156
1157    glActiveTexture(gTextureUnits[0]);
1158    Texture* texture = mCaches.textureCache.get(bitmap);
1159    if (!texture) return;
1160    const AutoTexture autoCleanup(texture);
1161    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1162
1163    const float width = texture->width;
1164    const float height = texture->height;
1165
1166    const float u1 = srcLeft / width;
1167    const float v1 = srcTop / height;
1168    const float u2 = srcRight / width;
1169    const float v2 = srcBottom / height;
1170
1171    mCaches.unbindMeshBuffer();
1172    resetDrawTextureTexCoords(u1, v1, u2, v2);
1173
1174    int alpha;
1175    SkXfermode::Mode mode;
1176    getAlphaAndMode(paint, &alpha, &mode);
1177
1178    if (mSnapshot->transform->isPureTranslate()) {
1179        const float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f);
1180        const float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f);
1181
1182        drawTextureMesh(x, y, x + (dstRight - dstLeft), y + (dstBottom - dstTop),
1183                texture->id, alpha / 255.0f, mode, texture->blend,
1184                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1185                GL_TRIANGLE_STRIP, gMeshCount, false, true);
1186    } else {
1187        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f,
1188                mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1189                GL_TRIANGLE_STRIP, gMeshCount);
1190    }
1191
1192    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1193}
1194
1195void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
1196        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
1197        float left, float top, float right, float bottom, SkPaint* paint) {
1198    if (quickReject(left, top, right, bottom)) {
1199        return;
1200    }
1201
1202    glActiveTexture(gTextureUnits[0]);
1203    Texture* texture = mCaches.textureCache.get(bitmap);
1204    if (!texture) return;
1205    const AutoTexture autoCleanup(texture);
1206    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1207
1208    int alpha;
1209    SkXfermode::Mode mode;
1210    getAlphaAndMode(paint, &alpha, &mode);
1211
1212    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
1213            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
1214
1215    if (mesh && mesh->verticesCount > 0) {
1216        const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1217#if RENDER_LAYERS_AS_REGIONS
1218        // Mark the current layer dirty where we are going to draw the patch
1219        if (hasLayer() && mesh->hasEmptyQuads) {
1220            const float offsetX = left + mSnapshot->transform->getTranslateX();
1221            const float offsetY = top + mSnapshot->transform->getTranslateY();
1222            const size_t count = mesh->quads.size();
1223            for (size_t i = 0; i < count; i++) {
1224                const Rect& bounds = mesh->quads.itemAt(i);
1225                if (pureTranslate) {
1226                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
1227                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
1228                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
1229                } else {
1230                    dirtyLayer(left + bounds.left, top + bounds.top,
1231                            left + bounds.right, top + bounds.bottom, *mSnapshot->transform);
1232                }
1233            }
1234        }
1235#endif
1236
1237        if (pureTranslate) {
1238            const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1239            const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1240
1241            drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
1242                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1243                    GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
1244                    true, !mesh->hasEmptyQuads);
1245        } else {
1246            drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
1247                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1248                    GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
1249                    true, !mesh->hasEmptyQuads);
1250        }
1251    }
1252}
1253
1254void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
1255    if (mSnapshot->isIgnored()) return;
1256
1257    const bool isAA = paint->isAntiAlias();
1258    const float strokeWidth = paint->getStrokeWidth() * 0.5f;
1259    // A stroke width of 0 has a special meaningin Skia:
1260    // it draws an unscaled 1px wide line
1261    const bool isHairLine = paint->getStrokeWidth() == 0.0f;
1262
1263    int alpha;
1264    SkXfermode::Mode mode;
1265    getAlphaAndMode(paint, &alpha, &mode);
1266
1267    int verticesCount = count >> 2;
1268    int generatedVerticesCount = 0;
1269    if (!isHairLine) {
1270        // TODO: AA needs more vertices
1271        verticesCount *= 6;
1272    } else {
1273        // TODO: AA will be different
1274        verticesCount *= 2;
1275    }
1276
1277    TextureVertex lines[verticesCount];
1278    TextureVertex* vertex = &lines[0];
1279
1280    setupDraw();
1281    setupDrawColor(paint->getColor(), alpha);
1282    setupDrawColorFilter();
1283    setupDrawShader();
1284    setupDrawBlending(mode);
1285    setupDrawProgram();
1286    setupDrawModelViewIdentity();
1287    setupDrawColorUniforms();
1288    setupDrawColorFilterUniforms();
1289    setupDrawShaderIdentityUniforms();
1290    setupDrawMesh(vertex);
1291
1292    if (!isHairLine) {
1293        // TODO: Handle the AA case
1294        for (int i = 0; i < count; i += 4) {
1295            // a = start point, b = end point
1296            vec2 a(points[i], points[i + 1]);
1297            vec2 b(points[i + 2], points[i + 3]);
1298
1299            // Bias to snap to the same pixels as Skia
1300            a += 0.375;
1301            b += 0.375;
1302
1303            // Find the normal to the line
1304            vec2 n = (b - a).copyNormalized() * strokeWidth;
1305            float x = n.x;
1306            n.x = -n.y;
1307            n.y = x;
1308
1309            // Four corners of the rectangle defining a thick line
1310            vec2 p1 = a - n;
1311            vec2 p2 = a + n;
1312            vec2 p3 = b + n;
1313            vec2 p4 = b - n;
1314
1315            const float left = fmin(p1.x, fmin(p2.x, fmin(p3.x, p4.x)));
1316            const float right = fmax(p1.x, fmax(p2.x, fmax(p3.x, p4.x)));
1317            const float top = fmin(p1.y, fmin(p2.y, fmin(p3.y, p4.y)));
1318            const float bottom = fmax(p1.y, fmax(p2.y, fmax(p3.y, p4.y)));
1319
1320            if (!quickReject(left, top, right, bottom)) {
1321                // Draw the line as 2 triangles, could be optimized
1322                // by using only 4 vertices and the correct indices
1323                // Also we should probably used non textured vertices
1324                // when line AA is disabled to save on bandwidth
1325                TextureVertex::set(vertex++, p1.x, p1.y, 0.0f, 0.0f);
1326                TextureVertex::set(vertex++, p2.x, p2.y, 0.0f, 0.0f);
1327                TextureVertex::set(vertex++, p3.x, p3.y, 0.0f, 0.0f);
1328                TextureVertex::set(vertex++, p1.x, p1.y, 0.0f, 0.0f);
1329                TextureVertex::set(vertex++, p3.x, p3.y, 0.0f, 0.0f);
1330                TextureVertex::set(vertex++, p4.x, p4.y, 0.0f, 0.0f);
1331
1332                generatedVerticesCount += 6;
1333
1334                dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1335            }
1336        }
1337
1338        if (generatedVerticesCount > 0) {
1339            // GL_LINE does not give the result we want to match Skia
1340            glDrawArrays(GL_TRIANGLES, 0, generatedVerticesCount);
1341        }
1342    } else {
1343        // TODO: Handle the AA case
1344        for (int i = 0; i < count; i += 4) {
1345            const float left = fmin(points[i], points[i + 1]);
1346            const float right = fmax(points[i], points[i + 1]);
1347            const float top = fmin(points[i + 2], points[i + 3]);
1348            const float bottom = fmax(points[i + 2], points[i + 3]);
1349
1350            if (!quickReject(left, top, right, bottom)) {
1351                TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
1352                TextureVertex::set(vertex++, points[i + 2], points[i + 3], 0.0f, 0.0f);
1353
1354                generatedVerticesCount += 2;
1355
1356                dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1357            }
1358        }
1359
1360        if (generatedVerticesCount > 0) {
1361            glLineWidth(1.0f);
1362            glDrawArrays(GL_LINES, 0, generatedVerticesCount);
1363        }
1364    }
1365}
1366
1367void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
1368    // No need to check against the clip, we fill the clip region
1369    if (mSnapshot->isIgnored()) return;
1370
1371    Rect& clip(*mSnapshot->clipRect);
1372    clip.snapToPixelBoundaries();
1373
1374    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
1375}
1376
1377void OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture, SkPaint* paint) {
1378    if (!texture) return;
1379    const AutoTexture autoCleanup(texture);
1380
1381    const float x = left + texture->left - texture->offset;
1382    const float y = top + texture->top - texture->offset;
1383
1384    drawPathTexture(texture, x, y, paint);
1385}
1386
1387void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
1388        float rx, float ry, SkPaint* paint) {
1389    if (mSnapshot->isIgnored()) return;
1390
1391    glActiveTexture(gTextureUnits[0]);
1392    const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect(
1393            right - left, bottom - top, rx, ry, paint);
1394    drawShape(left, top, texture, paint);
1395}
1396
1397void OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* paint) {
1398    if (mSnapshot->isIgnored()) return;
1399
1400    glActiveTexture(gTextureUnits[0]);
1401    const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, paint);
1402    drawShape(x - radius, y - radius, texture, paint);
1403}
1404
1405void OpenGLRenderer::drawOval(float left, float top, float right, float bottom, SkPaint* paint) {
1406    if (mSnapshot->isIgnored()) return;
1407
1408    glActiveTexture(gTextureUnits[0]);
1409    const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, paint);
1410    drawShape(left, top, texture, paint);
1411}
1412
1413void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
1414        float startAngle, float sweepAngle, bool useCenter, SkPaint* paint) {
1415    if (mSnapshot->isIgnored()) return;
1416
1417    if (fabs(sweepAngle) >= 360.0f) {
1418        drawOval(left, top, right, bottom, paint);
1419        return;
1420    }
1421
1422    glActiveTexture(gTextureUnits[0]);
1423    const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top,
1424            startAngle, sweepAngle, useCenter, paint);
1425    drawShape(left, top, texture, paint);
1426}
1427
1428void OpenGLRenderer::drawRectAsShape(float left, float top, float right, float bottom,
1429        SkPaint* paint) {
1430    if (mSnapshot->isIgnored()) return;
1431
1432    glActiveTexture(gTextureUnits[0]);
1433    const PathTexture* texture = mCaches.rectShapeCache.getRect(right - left, bottom - top, paint);
1434    drawShape(left, top, texture, paint);
1435}
1436
1437void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
1438    if (p->getStyle() != SkPaint::kFill_Style) {
1439        drawRectAsShape(left, top, right, bottom, p);
1440        return;
1441    }
1442
1443    if (quickReject(left, top, right, bottom)) {
1444        return;
1445    }
1446
1447    SkXfermode::Mode mode;
1448    if (!mCaches.extensions.hasFramebufferFetch()) {
1449        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
1450        if (!isMode) {
1451            // Assume SRC_OVER
1452            mode = SkXfermode::kSrcOver_Mode;
1453        }
1454    } else {
1455        mode = getXfermode(p->getXfermode());
1456    }
1457
1458    int color = p->getColor();
1459    drawColorRect(left, top, right, bottom, color, mode);
1460}
1461
1462void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
1463        float x, float y, SkPaint* paint) {
1464    if (text == NULL || count == 0) {
1465        return;
1466    }
1467    if (mSnapshot->isIgnored()) return;
1468
1469    paint->setAntiAlias(true);
1470
1471    float length = -1.0f;
1472    switch (paint->getTextAlign()) {
1473        case SkPaint::kCenter_Align:
1474            length = paint->measureText(text, bytesCount);
1475            x -= length / 2.0f;
1476            break;
1477        case SkPaint::kRight_Align:
1478            length = paint->measureText(text, bytesCount);
1479            x -= length;
1480            break;
1481        default:
1482            break;
1483    }
1484
1485    // TODO: Handle paint->getTextScaleX()
1486    const float oldX = x;
1487    const float oldY = y;
1488    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1489    if (pureTranslate) {
1490        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
1491        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
1492    }
1493
1494    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
1495    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
1496            paint->getTextSize());
1497
1498    int alpha;
1499    SkXfermode::Mode mode;
1500    getAlphaAndMode(paint, &alpha, &mode);
1501
1502    if (mHasShadow) {
1503        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
1504        const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount,
1505                count, mShadowRadius);
1506        const AutoTexture autoCleanup(shadow);
1507
1508        const float sx = x - shadow->left + mShadowDx;
1509        const float sy = y - shadow->top + mShadowDy;
1510
1511        const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
1512
1513        glActiveTexture(gTextureUnits[0]);
1514        setupDraw();
1515        setupDrawWithTexture(true);
1516        setupDrawAlpha8Color(mShadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
1517        setupDrawBlending(true, mode);
1518        setupDrawProgram();
1519        setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height, pureTranslate);
1520        setupDrawTexture(shadow->id);
1521        setupDrawPureColorUniforms();
1522        setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1523
1524        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1525        finishDrawTexture();
1526    }
1527
1528    if (paint->getAlpha() == 0 && paint->getXfermode() == NULL) {
1529        return;
1530    }
1531
1532    // Pick the appropriate texture filtering
1533    bool linearFilter = mSnapshot->transform->changesBounds();
1534    if (pureTranslate && !linearFilter) {
1535        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
1536    }
1537
1538    glActiveTexture(gTextureUnits[0]);
1539    setupDraw();
1540    setupDrawDirtyRegionsDisabled();
1541    setupDrawWithTexture(true);
1542    setupDrawAlpha8Color(paint->getColor(), alpha);
1543    setupDrawColorFilter();
1544    setupDrawShader();
1545    setupDrawBlending(true, mode);
1546    setupDrawProgram();
1547    setupDrawModelView(x, y, x, y, pureTranslate, true);
1548    setupDrawTexture(fontRenderer.getTexture(linearFilter));
1549    setupDrawPureColorUniforms();
1550    setupDrawColorFilterUniforms();
1551    setupDrawShaderUniforms(pureTranslate);
1552
1553    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
1554    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
1555
1556#if RENDER_LAYERS_AS_REGIONS
1557    bool hasActiveLayer = hasLayer();
1558#else
1559    bool hasActiveLayer = false;
1560#endif
1561
1562    mCaches.unbindMeshBuffer();
1563    if (fontRenderer.renderText(paint, clip, text, 0, bytesCount, count, x, y,
1564            hasActiveLayer ? &bounds : NULL)) {
1565#if RENDER_LAYERS_AS_REGIONS
1566        if (hasActiveLayer) {
1567            if (!pureTranslate) {
1568                mSnapshot->transform->mapRect(bounds);
1569            }
1570            dirtyLayerUnchecked(bounds, getRegion());
1571        }
1572#endif
1573    }
1574
1575    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1576    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
1577
1578    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
1579}
1580
1581void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
1582    if (mSnapshot->isIgnored()) return;
1583
1584    glActiveTexture(gTextureUnits[0]);
1585
1586    const PathTexture* texture = mCaches.pathCache.get(path, paint);
1587    if (!texture) return;
1588    const AutoTexture autoCleanup(texture);
1589
1590    const float x = texture->left - texture->offset;
1591    const float y = texture->top - texture->offset;
1592
1593    drawPathTexture(texture, x, y, paint);
1594}
1595
1596void OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) {
1597    if (!layer || quickReject(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight())) {
1598        return;
1599    }
1600
1601    glActiveTexture(gTextureUnits[0]);
1602
1603    int alpha;
1604    SkXfermode::Mode mode;
1605    getAlphaAndMode(paint, &alpha, &mode);
1606
1607    layer->alpha = alpha;
1608    layer->mode = mode;
1609
1610#if RENDER_LAYERS_AS_REGIONS
1611    if (!layer->region.isEmpty()) {
1612        if (layer->region.isRect()) {
1613            const Rect r(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight());
1614            composeLayerRect(layer, r);
1615        } else if (layer->mesh) {
1616            const float a = alpha / 255.0f;
1617            const Rect& rect = layer->layer;
1618
1619            setupDraw();
1620            setupDrawWithTexture();
1621            setupDrawColor(a, a, a, a);
1622            setupDrawColorFilter();
1623            setupDrawBlending(layer->blend || layer->alpha < 255, layer->mode, false);
1624            setupDrawProgram();
1625            setupDrawPureColorUniforms();
1626            setupDrawColorFilterUniforms();
1627            setupDrawTexture(layer->texture);
1628            // TODO: The current layer, if any, will be dirtied with the bounding box
1629            //       of the layer we are drawing. Since the layer we are drawing has
1630            //       a mesh, we know the dirty region, we should use it instead
1631            setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
1632            setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]);
1633
1634            glDrawElements(GL_TRIANGLES, layer->meshElementCount,
1635                    GL_UNSIGNED_SHORT, layer->meshIndices);
1636
1637            finishDrawTexture();
1638
1639#if DEBUG_LAYERS_AS_REGIONS
1640            drawRegionRects(layer->region);
1641#endif
1642        }
1643    }
1644#else
1645    const Rect r(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight());
1646    composeLayerRect(layer, r);
1647#endif
1648}
1649
1650///////////////////////////////////////////////////////////////////////////////
1651// Shaders
1652///////////////////////////////////////////////////////////////////////////////
1653
1654void OpenGLRenderer::resetShader() {
1655    mShader = NULL;
1656}
1657
1658void OpenGLRenderer::setupShader(SkiaShader* shader) {
1659    mShader = shader;
1660    if (mShader) {
1661        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
1662    }
1663}
1664
1665///////////////////////////////////////////////////////////////////////////////
1666// Color filters
1667///////////////////////////////////////////////////////////////////////////////
1668
1669void OpenGLRenderer::resetColorFilter() {
1670    mColorFilter = NULL;
1671}
1672
1673void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
1674    mColorFilter = filter;
1675}
1676
1677///////////////////////////////////////////////////////////////////////////////
1678// Drop shadow
1679///////////////////////////////////////////////////////////////////////////////
1680
1681void OpenGLRenderer::resetShadow() {
1682    mHasShadow = false;
1683}
1684
1685void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
1686    mHasShadow = true;
1687    mShadowRadius = radius;
1688    mShadowDx = dx;
1689    mShadowDy = dy;
1690    mShadowColor = color;
1691}
1692
1693///////////////////////////////////////////////////////////////////////////////
1694// Drawing implementation
1695///////////////////////////////////////////////////////////////////////////////
1696
1697void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
1698        float x, float y, SkPaint* paint) {
1699    if (quickReject(x, y, x + texture->width, y + texture->height)) {
1700        return;
1701    }
1702
1703    int alpha;
1704    SkXfermode::Mode mode;
1705    getAlphaAndMode(paint, &alpha, &mode);
1706
1707    setupDraw();
1708    setupDrawWithTexture(true);
1709    setupDrawAlpha8Color(paint->getColor(), alpha);
1710    setupDrawColorFilter();
1711    setupDrawShader();
1712    setupDrawBlending(true, mode);
1713    setupDrawProgram();
1714    setupDrawModelView(x, y, x + texture->width, y + texture->height);
1715    setupDrawTexture(texture->id);
1716    setupDrawPureColorUniforms();
1717    setupDrawColorFilterUniforms();
1718    setupDrawShaderUniforms();
1719    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1720
1721    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1722
1723    finishDrawTexture();
1724}
1725
1726// Same values used by Skia
1727#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
1728#define kStdUnderline_Offset    (1.0f / 9.0f)
1729#define kStdUnderline_Thickness (1.0f / 18.0f)
1730
1731void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
1732        float x, float y, SkPaint* paint) {
1733    // Handle underline and strike-through
1734    uint32_t flags = paint->getFlags();
1735    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
1736        float underlineWidth = length;
1737        // If length is > 0.0f, we already measured the text for the text alignment
1738        if (length <= 0.0f) {
1739            underlineWidth = paint->measureText(text, bytesCount);
1740        }
1741
1742        float offsetX = 0;
1743        switch (paint->getTextAlign()) {
1744            case SkPaint::kCenter_Align:
1745                offsetX = underlineWidth * 0.5f;
1746                break;
1747            case SkPaint::kRight_Align:
1748                offsetX = underlineWidth;
1749                break;
1750            default:
1751                break;
1752        }
1753
1754        if (underlineWidth > 0.0f) {
1755            const float textSize = paint->getTextSize();
1756            // TODO: Support stroke width < 1.0f when we have AA lines
1757            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
1758
1759            const float left = x - offsetX;
1760            float top = 0.0f;
1761
1762            int linesCount = 0;
1763            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
1764            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
1765
1766            const int pointsCount = 4 * linesCount;
1767            float points[pointsCount];
1768            int currentPoint = 0;
1769
1770            if (flags & SkPaint::kUnderlineText_Flag) {
1771                top = y + textSize * kStdUnderline_Offset;
1772                points[currentPoint++] = left;
1773                points[currentPoint++] = top;
1774                points[currentPoint++] = left + underlineWidth;
1775                points[currentPoint++] = top;
1776            }
1777
1778            if (flags & SkPaint::kStrikeThruText_Flag) {
1779                top = y + textSize * kStdStrikeThru_Offset;
1780                points[currentPoint++] = left;
1781                points[currentPoint++] = top;
1782                points[currentPoint++] = left + underlineWidth;
1783                points[currentPoint++] = top;
1784            }
1785
1786            SkPaint linesPaint(*paint);
1787            linesPaint.setStrokeWidth(strokeWidth);
1788
1789            drawLines(&points[0], pointsCount, &linesPaint);
1790        }
1791    }
1792}
1793
1794void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
1795        int color, SkXfermode::Mode mode, bool ignoreTransform) {
1796    // If a shader is set, preserve only the alpha
1797    if (mShader) {
1798        color |= 0x00ffffff;
1799    }
1800
1801    setupDraw();
1802    setupDrawColor(color);
1803    setupDrawShader();
1804    setupDrawColorFilter();
1805    setupDrawBlending(mode);
1806    setupDrawProgram();
1807    setupDrawModelView(left, top, right, bottom, ignoreTransform);
1808    setupDrawColorUniforms();
1809    setupDrawShaderUniforms(ignoreTransform);
1810    setupDrawColorFilterUniforms();
1811    setupDrawSimpleMesh();
1812
1813    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1814}
1815
1816void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1817        Texture* texture, SkPaint* paint) {
1818    int alpha;
1819    SkXfermode::Mode mode;
1820    getAlphaAndMode(paint, &alpha, &mode);
1821
1822    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1823
1824    if (mSnapshot->transform->isPureTranslate()) {
1825        const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1826        const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1827
1828        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
1829                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
1830                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
1831    } else {
1832        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
1833                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
1834                GL_TRIANGLE_STRIP, gMeshCount);
1835    }
1836}
1837
1838void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1839        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
1840    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
1841            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
1842}
1843
1844void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
1845        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
1846        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
1847        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
1848
1849    setupDraw();
1850    setupDrawWithTexture();
1851    setupDrawColor(alpha, alpha, alpha, alpha);
1852    setupDrawColorFilter();
1853    setupDrawBlending(blend, mode, swapSrcDst);
1854    setupDrawProgram();
1855    if (!dirty) {
1856        setupDrawDirtyRegionsDisabled();
1857    }
1858    if (!ignoreScale) {
1859        setupDrawModelView(left, top, right, bottom, ignoreTransform);
1860    } else {
1861        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
1862    }
1863    setupDrawPureColorUniforms();
1864    setupDrawColorFilterUniforms();
1865    setupDrawTexture(texture);
1866    setupDrawMesh(vertices, texCoords, vbo);
1867
1868    glDrawArrays(drawMode, 0, elementsCount);
1869
1870    finishDrawTexture();
1871}
1872
1873void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
1874        ProgramDescription& description, bool swapSrcDst) {
1875    blend = blend || mode != SkXfermode::kSrcOver_Mode;
1876    if (blend) {
1877        if (mode < SkXfermode::kPlus_Mode) {
1878            if (!mCaches.blend) {
1879                glEnable(GL_BLEND);
1880            }
1881
1882            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
1883            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
1884
1885            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
1886                glBlendFunc(sourceMode, destMode);
1887                mCaches.lastSrcMode = sourceMode;
1888                mCaches.lastDstMode = destMode;
1889            }
1890        } else {
1891            // These blend modes are not supported by OpenGL directly and have
1892            // to be implemented using shaders. Since the shader will perform
1893            // the blending, turn blending off here
1894            if (mCaches.extensions.hasFramebufferFetch()) {
1895                description.framebufferMode = mode;
1896                description.swapSrcDst = swapSrcDst;
1897            }
1898
1899            if (mCaches.blend) {
1900                glDisable(GL_BLEND);
1901            }
1902            blend = false;
1903        }
1904    } else if (mCaches.blend) {
1905        glDisable(GL_BLEND);
1906    }
1907    mCaches.blend = blend;
1908}
1909
1910bool OpenGLRenderer::useProgram(Program* program) {
1911    if (!program->isInUse()) {
1912        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
1913        program->use();
1914        mCaches.currentProgram = program;
1915        return false;
1916    }
1917    return true;
1918}
1919
1920void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
1921    TextureVertex* v = &mMeshVertices[0];
1922    TextureVertex::setUV(v++, u1, v1);
1923    TextureVertex::setUV(v++, u2, v1);
1924    TextureVertex::setUV(v++, u1, v2);
1925    TextureVertex::setUV(v++, u2, v2);
1926}
1927
1928void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
1929    if (paint) {
1930        if (!mCaches.extensions.hasFramebufferFetch()) {
1931            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
1932            if (!isMode) {
1933                // Assume SRC_OVER
1934                *mode = SkXfermode::kSrcOver_Mode;
1935            }
1936        } else {
1937            *mode = getXfermode(paint->getXfermode());
1938        }
1939
1940        // Skia draws using the color's alpha channel if < 255
1941        // Otherwise, it uses the paint's alpha
1942        int color = paint->getColor();
1943        *alpha = (color >> 24) & 0xFF;
1944        if (*alpha == 255) {
1945            *alpha = paint->getAlpha();
1946        }
1947    } else {
1948        *mode = SkXfermode::kSrcOver_Mode;
1949        *alpha = 255;
1950    }
1951}
1952
1953SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
1954    if (mode == NULL) {
1955        return SkXfermode::kSrcOver_Mode;
1956    }
1957    return mode->fMode;
1958}
1959
1960void OpenGLRenderer::setTextureWrapModes(Texture* texture, GLenum wrapS, GLenum wrapT) {
1961    bool bound = false;
1962    if (wrapS != texture->wrapS) {
1963        glBindTexture(GL_TEXTURE_2D, texture->id);
1964        bound = true;
1965        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
1966        texture->wrapS = wrapS;
1967    }
1968    if (wrapT != texture->wrapT) {
1969        if (!bound) {
1970            glBindTexture(GL_TEXTURE_2D, texture->id);
1971        }
1972        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
1973        texture->wrapT = wrapT;
1974    }
1975}
1976
1977}; // namespace uirenderer
1978}; // namespace android
1979