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