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