OpenGLRenderer.cpp revision 9fc27819d75e24ad63d7b383d80f5cb66a577a0d
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        layer->setRegionAsRect();
651
652        composeLayerRect(layer, layer->regionRect);
653
654        layer->region.clear();
655        return;
656    }
657
658    if (!layer->region.isEmpty()) {
659        size_t count;
660        const android::Rect* rects = layer->region.getArray(&count);
661
662        const float alpha = layer->alpha / 255.0f;
663        const float texX = 1.0f / float(layer->width);
664        const float texY = 1.0f / float(layer->height);
665        const float height = rect.getHeight();
666
667        TextureVertex* mesh = mCaches.getRegionMesh();
668        GLsizei numQuads = 0;
669
670        setupDraw();
671        setupDrawWithTexture();
672        setupDrawColor(alpha, alpha, alpha, alpha);
673        setupDrawColorFilter();
674        setupDrawBlending(layer->blend || layer->alpha < 255, layer->mode, false);
675        setupDrawProgram();
676        setupDrawDirtyRegionsDisabled();
677        setupDrawPureColorUniforms();
678        setupDrawColorFilterUniforms();
679        setupDrawTexture(layer->texture);
680        setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
681        setupDrawMesh(&mesh[0].position[0], &mesh[0].texture[0]);
682
683        for (size_t i = 0; i < count; i++) {
684            const android::Rect* r = &rects[i];
685
686            const float u1 = r->left * texX;
687            const float v1 = (height - r->top) * texY;
688            const float u2 = r->right * texX;
689            const float v2 = (height - r->bottom) * texY;
690
691            // TODO: Reject quads outside of the clip
692            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
693            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
694            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
695            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
696
697            numQuads++;
698
699            if (numQuads >= REGION_MESH_QUAD_COUNT) {
700                glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
701                numQuads = 0;
702                mesh = mCaches.getRegionMesh();
703            }
704        }
705
706        if (numQuads > 0) {
707            glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
708        }
709
710        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
711        finishDrawTexture();
712
713#if DEBUG_LAYERS_AS_REGIONS
714        drawRegionRects(layer->region);
715#endif
716
717        layer->region.clear();
718    }
719#else
720    composeLayerRect(layer, rect);
721#endif
722}
723
724void OpenGLRenderer::drawRegionRects(const Region& region) {
725#if DEBUG_LAYERS_AS_REGIONS
726    size_t count;
727    const android::Rect* rects = region.getArray(&count);
728
729    uint32_t colors[] = {
730            0x7fff0000, 0x7f00ff00,
731            0x7f0000ff, 0x7fff00ff,
732    };
733
734    int offset = 0;
735    int32_t top = rects[0].top;
736
737    for (size_t i = 0; i < count; i++) {
738        if (top != rects[i].top) {
739            offset ^= 0x2;
740            top = rects[i].top;
741        }
742
743        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
744        drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
745                SkXfermode::kSrcOver_Mode);
746    }
747#endif
748}
749
750void OpenGLRenderer::dirtyLayer(const float left, const float top,
751        const float right, const float bottom, const mat4 transform) {
752#if RENDER_LAYERS_AS_REGIONS
753    if (hasLayer()) {
754        Rect bounds(left, top, right, bottom);
755        transform.mapRect(bounds);
756        dirtyLayerUnchecked(bounds, getRegion());
757    }
758#endif
759}
760
761void OpenGLRenderer::dirtyLayer(const float left, const float top,
762        const float right, const float bottom) {
763#if RENDER_LAYERS_AS_REGIONS
764    if (hasLayer()) {
765        Rect bounds(left, top, right, bottom);
766        dirtyLayerUnchecked(bounds, getRegion());
767    }
768#endif
769}
770
771void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
772#if RENDER_LAYERS_AS_REGIONS
773    if (bounds.intersect(*mSnapshot->clipRect)) {
774        bounds.snapToPixelBoundaries();
775        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
776        if (!dirty.isEmpty()) {
777            region->orSelf(dirty);
778        }
779    }
780#endif
781}
782
783///////////////////////////////////////////////////////////////////////////////
784// Transforms
785///////////////////////////////////////////////////////////////////////////////
786
787void OpenGLRenderer::translate(float dx, float dy) {
788    mSnapshot->transform->translate(dx, dy, 0.0f);
789}
790
791void OpenGLRenderer::rotate(float degrees) {
792    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
793}
794
795void OpenGLRenderer::scale(float sx, float sy) {
796    mSnapshot->transform->scale(sx, sy, 1.0f);
797}
798
799void OpenGLRenderer::skew(float sx, float sy) {
800    mSnapshot->transform->skew(sx, sy);
801}
802
803void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
804    mSnapshot->transform->load(*matrix);
805}
806
807const float* OpenGLRenderer::getMatrix() const {
808    if (mSnapshot->fbo != 0) {
809        return &mSnapshot->transform->data[0];
810    }
811    return &mIdentity.data[0];
812}
813
814void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
815    mSnapshot->transform->copyTo(*matrix);
816}
817
818void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
819    SkMatrix transform;
820    mSnapshot->transform->copyTo(transform);
821    transform.preConcat(*matrix);
822    mSnapshot->transform->load(transform);
823}
824
825///////////////////////////////////////////////////////////////////////////////
826// Clipping
827///////////////////////////////////////////////////////////////////////////////
828
829void OpenGLRenderer::setScissorFromClip() {
830    Rect clip(*mSnapshot->clipRect);
831    clip.snapToPixelBoundaries();
832    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
833    mDirtyClip = false;
834}
835
836const Rect& OpenGLRenderer::getClipBounds() {
837    return mSnapshot->getLocalClip();
838}
839
840bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
841    if (mSnapshot->isIgnored()) {
842        return true;
843    }
844
845    Rect r(left, top, right, bottom);
846    mSnapshot->transform->mapRect(r);
847    r.snapToPixelBoundaries();
848
849    Rect clipRect(*mSnapshot->clipRect);
850    clipRect.snapToPixelBoundaries();
851
852    return !clipRect.intersects(r);
853}
854
855bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
856    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
857    if (clipped) {
858        dirtyClip();
859    }
860    return !mSnapshot->clipRect->isEmpty();
861}
862
863///////////////////////////////////////////////////////////////////////////////
864// Drawing commands
865///////////////////////////////////////////////////////////////////////////////
866
867void OpenGLRenderer::setupDraw() {
868    if (mDirtyClip) {
869        setScissorFromClip();
870    }
871    mDescription.reset();
872    mSetShaderColor = false;
873    mColorSet = false;
874    mColorA = mColorR = mColorG = mColorB = 0.0f;
875    mTextureUnit = 0;
876    mTrackDirtyRegions = true;
877    mTexCoordsSlot = -1;
878}
879
880void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
881    mDescription.hasTexture = true;
882    mDescription.hasAlpha8Texture = isAlpha8;
883}
884
885void OpenGLRenderer::setupDrawAALine() {
886    mDescription.hasWidth = true;
887}
888
889void OpenGLRenderer::setupDrawPoint(float pointSize) {
890    mDescription.isPoint = true;
891    mDescription.pointSize = pointSize;
892}
893
894void OpenGLRenderer::setupDrawColor(int color) {
895    setupDrawColor(color, (color >> 24) & 0xFF);
896}
897
898void OpenGLRenderer::setupDrawColor(int color, int alpha) {
899    mColorA = alpha / 255.0f;
900    // Second divide of a by 255 is an optimization, allowing us to simply multiply
901    // the rgb values by a instead of also dividing by 255
902    const float a = mColorA / 255.0f;
903    mColorR = a * ((color >> 16) & 0xFF);
904    mColorG = a * ((color >>  8) & 0xFF);
905    mColorB = a * ((color      ) & 0xFF);
906    mColorSet = true;
907    mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA);
908}
909
910void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
911    mColorA = alpha / 255.0f;
912    // Double-divide of a by 255 is an optimization, allowing us to simply multiply
913    // the rgb values by a instead of also dividing by 255
914    const float a = mColorA / 255.0f;
915    mColorR = a * ((color >> 16) & 0xFF);
916    mColorG = a * ((color >>  8) & 0xFF);
917    mColorB = a * ((color      ) & 0xFF);
918    mColorSet = true;
919    mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
920}
921
922void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
923    mColorA = a;
924    mColorR = r;
925    mColorG = g;
926    mColorB = b;
927    mColorSet = true;
928    mSetShaderColor = mDescription.setColor(r, g, b, a);
929}
930
931void OpenGLRenderer::setupDrawAlpha8Color(float r, float g, float b, float a) {
932    mColorA = a;
933    mColorR = r;
934    mColorG = g;
935    mColorB = b;
936    mColorSet = true;
937    mSetShaderColor = mDescription.setAlpha8Color(r, g, b, a);
938}
939
940void OpenGLRenderer::setupDrawShader() {
941    if (mShader) {
942        mShader->describe(mDescription, mCaches.extensions);
943    }
944}
945
946void OpenGLRenderer::setupDrawColorFilter() {
947    if (mColorFilter) {
948        mColorFilter->describe(mDescription, mCaches.extensions);
949    }
950}
951
952void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) {
953    chooseBlending((mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
954            mDescription, swapSrcDst);
955}
956
957void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) {
958    chooseBlending(blend || (mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
959            mDescription, swapSrcDst);
960}
961
962void OpenGLRenderer::setupDrawProgram() {
963    useProgram(mCaches.programCache.get(mDescription));
964}
965
966void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
967    mTrackDirtyRegions = false;
968}
969
970void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom,
971        bool ignoreTransform) {
972    mModelView.loadTranslate(left, top, 0.0f);
973    if (!ignoreTransform) {
974        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
975        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
976    } else {
977        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
978        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
979    }
980}
981
982void OpenGLRenderer::setupDrawModelViewIdentity() {
983    mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform);
984}
985
986void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom,
987        bool ignoreTransform, bool ignoreModelView) {
988    if (!ignoreModelView) {
989        mModelView.loadTranslate(left, top, 0.0f);
990        mModelView.scale(right - left, bottom - top, 1.0f);
991    } else {
992        mModelView.loadIdentity();
993    }
994    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
995    if (!ignoreTransform) {
996        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
997        if (mTrackDirtyRegions && dirty) {
998            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
999        }
1000    } else {
1001        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1002        if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom);
1003    }
1004}
1005
1006void OpenGLRenderer::setupDrawPointUniforms() {
1007    int slot = mCaches.currentProgram->getUniform("pointSize");
1008    glUniform1f(slot, mDescription.pointSize);
1009}
1010
1011void OpenGLRenderer::setupDrawColorUniforms() {
1012    if (mColorSet || (mShader && mSetShaderColor)) {
1013        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1014    }
1015}
1016
1017void OpenGLRenderer::setupDrawPureColorUniforms() {
1018    if (mSetShaderColor) {
1019        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1020    }
1021}
1022
1023void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
1024    if (mShader) {
1025        if (ignoreTransform) {
1026            mModelView.loadInverse(*mSnapshot->transform);
1027        }
1028        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &mTextureUnit);
1029    }
1030}
1031
1032void OpenGLRenderer::setupDrawShaderIdentityUniforms() {
1033    if (mShader) {
1034        mShader->setupProgram(mCaches.currentProgram, mIdentity, *mSnapshot, &mTextureUnit);
1035    }
1036}
1037
1038void OpenGLRenderer::setupDrawColorFilterUniforms() {
1039    if (mColorFilter) {
1040        mColorFilter->setupProgram(mCaches.currentProgram);
1041    }
1042}
1043
1044void OpenGLRenderer::setupDrawSimpleMesh() {
1045    mCaches.bindMeshBuffer();
1046    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1047            gMeshStride, 0);
1048}
1049
1050void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1051    bindTexture(texture);
1052    glUniform1i(mCaches.currentProgram->getUniform("sampler"), mTextureUnit++);
1053
1054    mTexCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1055    glEnableVertexAttribArray(mTexCoordsSlot);
1056}
1057
1058void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1059    if (!vertices) {
1060        mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1061    } else {
1062        mCaches.unbindMeshBuffer();
1063    }
1064    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1065            gMeshStride, vertices);
1066    if (mTexCoordsSlot >= 0) {
1067        glVertexAttribPointer(mTexCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1068    }
1069}
1070
1071void OpenGLRenderer::setupDrawVertices(GLvoid* vertices) {
1072    mCaches.unbindMeshBuffer();
1073    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1074            gVertexStride, vertices);
1075}
1076
1077/**
1078 * Sets up the shader to draw an AA line. We draw AA lines with quads, where there is an
1079 * outer boundary that fades out to 0. The variables set in the shader define the width of the
1080 * core line primitive ("width") and the width of the fading boundary ("boundaryWidth"). The
1081 * "vtxDistance" attribute (one per vertex) is a value from zero to one that tells the fragment
1082 * shader where the fragment is in relation to the line width overall; this value is then used
1083 * to compute the proper color, based on whether the fragment lies in the fading AA region of
1084 * the line.
1085 */
1086void OpenGLRenderer::setupDrawAALine(GLvoid* vertices, GLvoid* distanceCoords, float strokeWidth) {
1087    mCaches.unbindMeshBuffer();
1088    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1089            gAlphaVertexStride, vertices);
1090    int distanceSlot = mCaches.currentProgram->getAttrib("vtxDistance");
1091    glEnableVertexAttribArray(distanceSlot);
1092    glVertexAttribPointer(distanceSlot, 1, GL_FLOAT, GL_FALSE, gAlphaVertexStride, distanceCoords);
1093    int widthSlot = mCaches.currentProgram->getUniform("width");
1094    int boundaryWidthSlot = mCaches.currentProgram->getUniform("boundaryWidth");
1095    int inverseBoundaryWidthSlot = mCaches.currentProgram->getUniform("inverseBoundaryWidth");
1096    float boundaryWidth = (1 - strokeWidth) / 2;
1097    glUniform1f(widthSlot, strokeWidth);
1098    glUniform1f(boundaryWidthSlot, boundaryWidth);
1099    glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidth));
1100}
1101
1102void OpenGLRenderer::finishDrawTexture() {
1103    glDisableVertexAttribArray(mTexCoordsSlot);
1104}
1105
1106///////////////////////////////////////////////////////////////////////////////
1107// Drawing
1108///////////////////////////////////////////////////////////////////////////////
1109
1110bool OpenGLRenderer::drawDisplayList(DisplayList* displayList, uint32_t width, uint32_t height,
1111        Rect& dirty, uint32_t level) {
1112    if (quickReject(0.0f, 0.0f, width, height)) {
1113        return false;
1114    }
1115
1116    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1117    // will be performed by the display list itself
1118    if (displayList) {
1119        return displayList->replay(*this, dirty, level);
1120    }
1121
1122    return false;
1123}
1124
1125void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint) {
1126    int alpha;
1127    SkXfermode::Mode mode;
1128    getAlphaAndMode(paint, &alpha, &mode);
1129
1130    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1131
1132    float x = left;
1133    float y = top;
1134
1135    bool ignoreTransform = false;
1136    if (mSnapshot->transform->isPureTranslate()) {
1137        x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1138        y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1139        ignoreTransform = true;
1140    }
1141
1142    setupDraw();
1143    setupDrawWithTexture(true);
1144    if (paint) {
1145        setupDrawAlpha8Color(paint->getColor(), alpha);
1146    }
1147    setupDrawColorFilter();
1148    setupDrawShader();
1149    setupDrawBlending(true, mode);
1150    setupDrawProgram();
1151    setupDrawModelView(x, y, x + texture->width, y + texture->height, ignoreTransform);
1152    setupDrawTexture(texture->id);
1153    setupDrawPureColorUniforms();
1154    setupDrawColorFilterUniforms();
1155    setupDrawShaderUniforms();
1156    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1157
1158    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1159
1160    finishDrawTexture();
1161}
1162
1163void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1164    const float right = left + bitmap->width();
1165    const float bottom = top + bitmap->height();
1166
1167    if (quickReject(left, top, right, bottom)) {
1168        return;
1169    }
1170
1171    glActiveTexture(gTextureUnits[0]);
1172    Texture* texture = mCaches.textureCache.get(bitmap);
1173    if (!texture) return;
1174    const AutoTexture autoCleanup(texture);
1175
1176    if (bitmap->getConfig() == SkBitmap::kA8_Config) {
1177        drawAlphaBitmap(texture, left, top, paint);
1178    } else {
1179        drawTextureRect(left, top, right, bottom, texture, paint);
1180    }
1181}
1182
1183void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
1184    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
1185    const mat4 transform(*matrix);
1186    transform.mapRect(r);
1187
1188    if (quickReject(r.left, r.top, r.right, r.bottom)) {
1189        return;
1190    }
1191
1192    glActiveTexture(gTextureUnits[0]);
1193    Texture* texture = mCaches.textureCache.get(bitmap);
1194    if (!texture) return;
1195    const AutoTexture autoCleanup(texture);
1196
1197    // This could be done in a cheaper way, all we need is pass the matrix
1198    // to the vertex shader. The save/restore is a bit overkill.
1199    save(SkCanvas::kMatrix_SaveFlag);
1200    concatMatrix(matrix);
1201    drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
1202    restore();
1203}
1204
1205void OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
1206        float* vertices, int* colors, SkPaint* paint) {
1207    // TODO: Do a quickReject
1208    if (!vertices || mSnapshot->isIgnored()) {
1209        return;
1210    }
1211
1212    glActiveTexture(gTextureUnits[0]);
1213    Texture* texture = mCaches.textureCache.get(bitmap);
1214    if (!texture) return;
1215    const AutoTexture autoCleanup(texture);
1216    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1217
1218    int alpha;
1219    SkXfermode::Mode mode;
1220    getAlphaAndMode(paint, &alpha, &mode);
1221
1222    const uint32_t count = meshWidth * meshHeight * 6;
1223
1224    float left = FLT_MAX;
1225    float top = FLT_MAX;
1226    float right = FLT_MIN;
1227    float bottom = FLT_MIN;
1228
1229#if RENDER_LAYERS_AS_REGIONS
1230    bool hasActiveLayer = hasLayer();
1231#else
1232    bool hasActiveLayer = false;
1233#endif
1234
1235    // TODO: Support the colors array
1236    TextureVertex mesh[count];
1237    TextureVertex* vertex = mesh;
1238    for (int32_t y = 0; y < meshHeight; y++) {
1239        for (int32_t x = 0; x < meshWidth; x++) {
1240            uint32_t i = (y * (meshWidth + 1) + x) * 2;
1241
1242            float u1 = float(x) / meshWidth;
1243            float u2 = float(x + 1) / meshWidth;
1244            float v1 = float(y) / meshHeight;
1245            float v2 = float(y + 1) / meshHeight;
1246
1247            int ax = i + (meshWidth + 1) * 2;
1248            int ay = ax + 1;
1249            int bx = i;
1250            int by = bx + 1;
1251            int cx = i + 2;
1252            int cy = cx + 1;
1253            int dx = i + (meshWidth + 1) * 2 + 2;
1254            int dy = dx + 1;
1255
1256            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1257            TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1);
1258            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1259
1260            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1261            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1262            TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2);
1263
1264#if RENDER_LAYERS_AS_REGIONS
1265            if (hasActiveLayer) {
1266                // TODO: This could be optimized to avoid unnecessary ops
1267                left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
1268                top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
1269                right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
1270                bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
1271            }
1272#endif
1273        }
1274    }
1275
1276#if RENDER_LAYERS_AS_REGIONS
1277    if (hasActiveLayer) {
1278        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1279    }
1280#endif
1281
1282    drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f,
1283            mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0],
1284            GL_TRIANGLES, count, false, false, 0, false, false);
1285}
1286
1287void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
1288         float srcLeft, float srcTop, float srcRight, float srcBottom,
1289         float dstLeft, float dstTop, float dstRight, float dstBottom,
1290         SkPaint* paint) {
1291    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
1292        return;
1293    }
1294
1295    glActiveTexture(gTextureUnits[0]);
1296    Texture* texture = mCaches.textureCache.get(bitmap);
1297    if (!texture) return;
1298    const AutoTexture autoCleanup(texture);
1299    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1300
1301    const float width = texture->width;
1302    const float height = texture->height;
1303
1304    const float u1 = srcLeft / width;
1305    const float v1 = srcTop / height;
1306    const float u2 = srcRight / width;
1307    const float v2 = srcBottom / height;
1308
1309    mCaches.unbindMeshBuffer();
1310    resetDrawTextureTexCoords(u1, v1, u2, v2);
1311
1312    int alpha;
1313    SkXfermode::Mode mode;
1314    getAlphaAndMode(paint, &alpha, &mode);
1315
1316    if (mSnapshot->transform->isPureTranslate()) {
1317        const float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f);
1318        const float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f);
1319
1320        drawTextureMesh(x, y, x + (dstRight - dstLeft), y + (dstBottom - dstTop),
1321                texture->id, alpha / 255.0f, mode, texture->blend,
1322                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1323                GL_TRIANGLE_STRIP, gMeshCount, false, true);
1324    } else {
1325        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f,
1326                mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1327                GL_TRIANGLE_STRIP, gMeshCount);
1328    }
1329
1330    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1331}
1332
1333void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
1334        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
1335        float left, float top, float right, float bottom, SkPaint* paint) {
1336    if (quickReject(left, top, right, bottom)) {
1337        return;
1338    }
1339
1340    glActiveTexture(gTextureUnits[0]);
1341    Texture* texture = mCaches.textureCache.get(bitmap);
1342    if (!texture) return;
1343    const AutoTexture autoCleanup(texture);
1344    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1345
1346    int alpha;
1347    SkXfermode::Mode mode;
1348    getAlphaAndMode(paint, &alpha, &mode);
1349
1350    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
1351            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
1352
1353    if (mesh && mesh->verticesCount > 0) {
1354        const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1355#if RENDER_LAYERS_AS_REGIONS
1356        // Mark the current layer dirty where we are going to draw the patch
1357        if (hasLayer() && mesh->hasEmptyQuads) {
1358            const float offsetX = left + mSnapshot->transform->getTranslateX();
1359            const float offsetY = top + mSnapshot->transform->getTranslateY();
1360            const size_t count = mesh->quads.size();
1361            for (size_t i = 0; i < count; i++) {
1362                const Rect& bounds = mesh->quads.itemAt(i);
1363                if (pureTranslate) {
1364                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
1365                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
1366                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
1367                } else {
1368                    dirtyLayer(left + bounds.left, top + bounds.top,
1369                            left + bounds.right, top + bounds.bottom, *mSnapshot->transform);
1370                }
1371            }
1372        }
1373#endif
1374
1375        if (pureTranslate) {
1376            const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1377            const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1378
1379            drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
1380                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1381                    GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
1382                    true, !mesh->hasEmptyQuads);
1383        } else {
1384            drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
1385                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1386                    GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
1387                    true, !mesh->hasEmptyQuads);
1388        }
1389    }
1390}
1391
1392void OpenGLRenderer::drawLinesAsQuads(float *points, int count, bool isAA, bool isHairline,
1393        float strokeWidth) {
1394    int verticesCount = count;
1395    if (count > 4) {
1396        // Polyline: account for extra vertices needed for continous tri-strip
1397        verticesCount += (count -4);
1398    }
1399    if (isAA) {
1400        // Expand boundary to enable AA calculations on the quad border
1401        strokeWidth += .5f;
1402    }
1403    Vertex lines[verticesCount];
1404    Vertex* vertices = &lines[0];
1405    AlphaVertex wLines[verticesCount];
1406    AlphaVertex* aaVertices = &wLines[0];
1407    if (!isAA) {
1408        setupDrawVertices(vertices);
1409    } else {
1410        AlphaVertex* alphaCoords = aaVertices + gVertexAlphaOffset;
1411        // innerProportion is the ratio of the inner (non-AA) port of the line to the total
1412        // AA stroke width (the base stroke width expanded by a half pixel on either side).
1413        // This value is used in the fragment shader to determine how to fill fragments.
1414        float innerProportion = fmax(strokeWidth - 1.0f, 0) / (strokeWidth + .5f);
1415        setupDrawAALine((void*) aaVertices, (void*) alphaCoords, innerProportion);
1416    }
1417
1418    int generatedVerticesCount = 0;
1419    AlphaVertex *prevAAVertex = NULL;
1420    Vertex *prevVertex = NULL;
1421    float inverseScaleX = 1.0f;
1422    float inverseScaleY = 1.0f;
1423
1424    if (isHairline) {
1425        // The quad that we use for AA hairlines needs to account for scaling because the line
1426        // should always be one pixel wide regardless of scale.
1427        inverseScaleX = 1.0f;
1428        inverseScaleY = 1.0f;
1429        if (!mSnapshot->transform->isPureTranslate()) {
1430            Matrix4 *mat = mSnapshot->transform;
1431            float m00 = mat->data[Matrix4::kScaleX];
1432            float m01 = mat->data[Matrix4::kSkewY];
1433            float m02 = mat->data[2];
1434            float m10 = mat->data[Matrix4::kSkewX];
1435            float m11 = mat->data[Matrix4::kScaleX];
1436            float m12 = mat->data[6];
1437            float scaleX = sqrt(m00*m00 + m01*m01);
1438            float scaleY = sqrt(m10*m10 + m11*m11);
1439            inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0;
1440            inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0;
1441        }
1442    }
1443
1444    for (int i = 0; i < count; i += 4) {
1445        // a = start point, b = end point
1446        vec2 a(points[i], points[i + 1]);
1447        vec2 b(points[i + 2], points[i + 3]);
1448
1449        // Bias to snap to the same pixels as Skia
1450        a += 0.375;
1451        b += 0.375;
1452
1453        // Find the normal to the line
1454        vec2 n = (b - a).copyNormalized() * strokeWidth;
1455        if (isHairline) {
1456            float wideningFactor;
1457            if (fabs(n.x) >= fabs(n.y)) {
1458                wideningFactor = fabs(1.0f / n.x);
1459            } else {
1460                wideningFactor = fabs(1.0f / n.y);
1461            }
1462            n.x *= inverseScaleX;
1463            n.y *= inverseScaleY;
1464            n *= wideningFactor;
1465        }
1466        float x = n.x;
1467        n.x = -n.y;
1468        n.y = x;
1469
1470        // Four corners of the rectangle defining a thick line
1471        vec2 p1 = a - n;
1472        vec2 p2 = a + n;
1473        vec2 p3 = b + n;
1474        vec2 p4 = b - n;
1475
1476        const float left = fmin(p1.x, fmin(p2.x, fmin(p3.x, p4.x)));
1477        const float right = fmax(p1.x, fmax(p2.x, fmax(p3.x, p4.x)));
1478        const float top = fmin(p1.y, fmin(p2.y, fmin(p3.y, p4.y)));
1479        const float bottom = fmax(p1.y, fmax(p2.y, fmax(p3.y, p4.y)));
1480
1481        if (!quickReject(left, top, right, bottom)) {
1482            // Draw the line as 2 triangles, could be optimized
1483            // by using only 4 vertices and the correct indices
1484            // Also we should probably used non textured vertices
1485            // when line AA is disabled to save on bandwidth
1486            if (!isAA) {
1487                if (prevVertex != NULL) {
1488                    // Issue two repeat vertices to create degenerate triangles to bridge
1489                    // between the previous line and the new one. This is necessary because
1490                    // we are creating a single triangle_strip which will contain
1491                    // potentially discontinuous line segments.
1492                    Vertex::set(vertices++, prevVertex->position[0], prevVertex->position[1]);
1493                    Vertex::set(vertices++, p1.x, p1.y);
1494                    generatedVerticesCount += 2;
1495                }
1496                Vertex::set(vertices++, p1.x, p1.y);
1497                Vertex::set(vertices++, p2.x, p2.y);
1498                Vertex::set(vertices++, p4.x, p4.y);
1499                Vertex::set(vertices++, p3.x, p3.y);
1500                prevVertex = vertices - 1;
1501                generatedVerticesCount += 4;
1502            } else {
1503                if (prevAAVertex != NULL) {
1504                    // Issue two repeat vertices to create degenerate triangles to bridge
1505                    // between the previous line and the new one. This is necessary because
1506                    // we are creating a single triangle_strip which will contain
1507                    // potentially discontinuous line segments.
1508                    AlphaVertex::set(aaVertices++,prevAAVertex->position[0],
1509                            prevAAVertex->position[1], prevAAVertex->alpha);
1510                    AlphaVertex::set(aaVertices++, p4.x, p4.y, 1);
1511                    generatedVerticesCount += 2;
1512                }
1513                AlphaVertex::set(aaVertices++, p4.x, p4.y, 1);
1514                AlphaVertex::set(aaVertices++, p1.x, p1.y, 1);
1515                AlphaVertex::set(aaVertices++, p3.x, p3.y, 0);
1516                AlphaVertex::set(aaVertices++, p2.x, p2.y, 0);
1517                prevAAVertex = aaVertices - 1;
1518                generatedVerticesCount += 4;
1519            }
1520            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1521        }
1522    }
1523    if (generatedVerticesCount > 0) {
1524       glDrawArrays(GL_TRIANGLE_STRIP, 0, generatedVerticesCount);
1525    }
1526}
1527
1528void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
1529    if (mSnapshot->isIgnored()) return;
1530
1531    const bool isAA = paint->isAntiAlias();
1532    const float strokeWidth = paint->getStrokeWidth() * 0.5f;
1533    // A stroke width of 0 has a special meaning in Skia:
1534    // it draws a line 1 px wide regardless of current transform
1535    bool isHairLine = paint->getStrokeWidth() == 0.0f;
1536
1537    int alpha;
1538    SkXfermode::Mode mode;
1539    getAlphaAndMode(paint, &alpha, &mode);
1540    int generatedVerticesCount = 0;
1541
1542    setupDraw();
1543    if (isAA) {
1544        setupDrawAALine();
1545    }
1546    setupDrawColor(paint->getColor(), alpha);
1547    setupDrawColorFilter();
1548    setupDrawShader();
1549    if (isAA) {
1550        setupDrawBlending(true, mode);
1551    } else {
1552        setupDrawBlending(mode);
1553    }
1554    setupDrawProgram();
1555    setupDrawModelViewIdentity();
1556    setupDrawColorUniforms();
1557    setupDrawColorFilterUniforms();
1558    setupDrawShaderIdentityUniforms();
1559
1560    if (!isHairLine) {
1561        drawLinesAsQuads(points, count, isAA, isHairLine, strokeWidth);
1562    } else {
1563        if (isAA) {
1564            drawLinesAsQuads(points, count, isAA, isHairLine, .5f);
1565        } else {
1566            int verticesCount = count >> 1;
1567            Vertex lines[verticesCount];
1568            Vertex* vertices = &lines[0];
1569            setupDrawVertices(vertices);
1570            for (int i = 0; i < count; i += 4) {
1571
1572                const float left = fmin(points[i], points[i + 2]);
1573                const float right = fmax(points[i], points[i + 2]);
1574                const float top = fmin(points[i + 1], points[i + 3]);
1575                const float bottom = fmax(points[i + 1], points[i + 3]);
1576
1577                Vertex::set(vertices++, points[i], points[i + 1]);
1578                Vertex::set(vertices++, points[i + 2], points[i + 3]);
1579                generatedVerticesCount += 2;
1580                dirtyLayer(left, top,
1581                        right == left ? left + 1 : right, bottom == top ? top + 1 : bottom,
1582                        *mSnapshot->transform);
1583            }
1584
1585            glLineWidth(1.0f);
1586            glDrawArrays(GL_LINES, 0, generatedVerticesCount);
1587        }
1588    }
1589}
1590
1591void OpenGLRenderer::drawPoints(float* points, int count, SkPaint* paint) {
1592    if (mSnapshot->isIgnored()) return;
1593
1594    // TODO: The paint's cap style defines whether the points are square or circular
1595    // TODO: Handle AA for round points
1596
1597    // A stroke width of 0 has a special meaning in Skia:
1598    // it draws an unscaled 1px point
1599    const bool isHairLine = paint->getStrokeWidth() == 0.0f;
1600
1601    int alpha;
1602    SkXfermode::Mode mode;
1603    getAlphaAndMode(paint, &alpha, &mode);
1604
1605    int verticesCount = count >> 1;
1606    int generatedVerticesCount = 0;
1607
1608    TextureVertex pointsData[verticesCount];
1609    TextureVertex* vertex = &pointsData[0];
1610
1611    setupDraw();
1612    setupDrawPoint(isHairLine ? 1.0f : paint->getStrokeWidth());
1613    setupDrawColor(paint->getColor(), alpha);
1614    setupDrawColorFilter();
1615    setupDrawShader();
1616    setupDrawBlending(mode);
1617    setupDrawProgram();
1618    setupDrawModelViewIdentity();
1619    setupDrawColorUniforms();
1620    setupDrawColorFilterUniforms();
1621    setupDrawPointUniforms();
1622    setupDrawShaderIdentityUniforms();
1623    setupDrawMesh(vertex);
1624
1625    for (int i = 0; i < count; i += 2) {
1626        TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
1627        generatedVerticesCount++;
1628    }
1629
1630    glDrawArrays(GL_POINTS, 0, generatedVerticesCount);
1631}
1632
1633void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
1634    // No need to check against the clip, we fill the clip region
1635    if (mSnapshot->isIgnored()) return;
1636
1637    Rect& clip(*mSnapshot->clipRect);
1638    clip.snapToPixelBoundaries();
1639
1640    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
1641}
1642
1643void OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture, SkPaint* paint) {
1644    if (!texture) return;
1645    const AutoTexture autoCleanup(texture);
1646
1647    const float x = left + texture->left - texture->offset;
1648    const float y = top + texture->top - texture->offset;
1649
1650    drawPathTexture(texture, x, y, paint);
1651}
1652
1653void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
1654        float rx, float ry, SkPaint* paint) {
1655    if (mSnapshot->isIgnored()) return;
1656
1657    glActiveTexture(gTextureUnits[0]);
1658    const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect(
1659            right - left, bottom - top, rx, ry, paint);
1660    drawShape(left, top, texture, paint);
1661}
1662
1663void OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* paint) {
1664    if (mSnapshot->isIgnored()) return;
1665
1666    glActiveTexture(gTextureUnits[0]);
1667    const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, paint);
1668    drawShape(x - radius, y - radius, texture, paint);
1669}
1670
1671void OpenGLRenderer::drawOval(float left, float top, float right, float bottom, SkPaint* paint) {
1672    if (mSnapshot->isIgnored()) return;
1673
1674    glActiveTexture(gTextureUnits[0]);
1675    const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, paint);
1676    drawShape(left, top, texture, paint);
1677}
1678
1679void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
1680        float startAngle, float sweepAngle, bool useCenter, SkPaint* paint) {
1681    if (mSnapshot->isIgnored()) return;
1682
1683    if (fabs(sweepAngle) >= 360.0f) {
1684        drawOval(left, top, right, bottom, paint);
1685        return;
1686    }
1687
1688    glActiveTexture(gTextureUnits[0]);
1689    const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top,
1690            startAngle, sweepAngle, useCenter, paint);
1691    drawShape(left, top, texture, paint);
1692}
1693
1694void OpenGLRenderer::drawRectAsShape(float left, float top, float right, float bottom,
1695        SkPaint* paint) {
1696    if (mSnapshot->isIgnored()) return;
1697
1698    glActiveTexture(gTextureUnits[0]);
1699    const PathTexture* texture = mCaches.rectShapeCache.getRect(right - left, bottom - top, paint);
1700    drawShape(left, top, texture, paint);
1701}
1702
1703void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
1704    if (p->getStyle() != SkPaint::kFill_Style) {
1705        drawRectAsShape(left, top, right, bottom, p);
1706        return;
1707    }
1708
1709    if (quickReject(left, top, right, bottom)) {
1710        return;
1711    }
1712
1713    SkXfermode::Mode mode;
1714    if (!mCaches.extensions.hasFramebufferFetch()) {
1715        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
1716        if (!isMode) {
1717            // Assume SRC_OVER
1718            mode = SkXfermode::kSrcOver_Mode;
1719        }
1720    } else {
1721        mode = getXfermode(p->getXfermode());
1722    }
1723
1724    int color = p->getColor();
1725    drawColorRect(left, top, right, bottom, color, mode);
1726}
1727
1728void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
1729        float x, float y, SkPaint* paint) {
1730    if (text == NULL || count == 0) {
1731        return;
1732    }
1733    if (mSnapshot->isIgnored()) return;
1734
1735    paint->setAntiAlias(true);
1736
1737    float length = -1.0f;
1738    switch (paint->getTextAlign()) {
1739        case SkPaint::kCenter_Align:
1740            length = paint->measureText(text, bytesCount);
1741            x -= length / 2.0f;
1742            break;
1743        case SkPaint::kRight_Align:
1744            length = paint->measureText(text, bytesCount);
1745            x -= length;
1746            break;
1747        default:
1748            break;
1749    }
1750
1751    const float oldX = x;
1752    const float oldY = y;
1753    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1754    if (pureTranslate) {
1755        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
1756        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
1757    }
1758
1759    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
1760    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
1761            paint->getTextSize());
1762
1763    int alpha;
1764    SkXfermode::Mode mode;
1765    getAlphaAndMode(paint, &alpha, &mode);
1766
1767    if (mHasShadow) {
1768        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
1769        const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount,
1770                count, mShadowRadius);
1771        const AutoTexture autoCleanup(shadow);
1772
1773        const float sx = oldX - shadow->left + mShadowDx;
1774        const float sy = oldY - shadow->top + mShadowDy;
1775
1776        const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
1777        int shadowColor = mShadowColor;
1778        if (mShader) {
1779            shadowColor = 0xffffffff;
1780        }
1781
1782        glActiveTexture(gTextureUnits[0]);
1783        setupDraw();
1784        setupDrawWithTexture(true);
1785        setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
1786        setupDrawColorFilter();
1787        setupDrawShader();
1788        setupDrawBlending(true, mode);
1789        setupDrawProgram();
1790        setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height);
1791        setupDrawTexture(shadow->id);
1792        setupDrawPureColorUniforms();
1793        setupDrawColorFilterUniforms();
1794        setupDrawShaderUniforms();
1795        setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1796
1797        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1798
1799        finishDrawTexture();
1800    }
1801
1802    if (paint->getAlpha() == 0 && paint->getXfermode() == NULL) {
1803        return;
1804    }
1805
1806    // Pick the appropriate texture filtering
1807    bool linearFilter = mSnapshot->transform->changesBounds();
1808    if (pureTranslate && !linearFilter) {
1809        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
1810    }
1811
1812    glActiveTexture(gTextureUnits[0]);
1813    setupDraw();
1814    setupDrawDirtyRegionsDisabled();
1815    setupDrawWithTexture(true);
1816    setupDrawAlpha8Color(paint->getColor(), alpha);
1817    setupDrawColorFilter();
1818    setupDrawShader();
1819    setupDrawBlending(true, mode);
1820    setupDrawProgram();
1821    setupDrawModelView(x, y, x, y, pureTranslate, true);
1822    setupDrawTexture(fontRenderer.getTexture(linearFilter));
1823    setupDrawPureColorUniforms();
1824    setupDrawColorFilterUniforms();
1825    setupDrawShaderUniforms(pureTranslate);
1826
1827    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
1828    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
1829
1830#if RENDER_LAYERS_AS_REGIONS
1831    bool hasActiveLayer = hasLayer();
1832#else
1833    bool hasActiveLayer = false;
1834#endif
1835    mCaches.unbindMeshBuffer();
1836
1837    // Tell font renderer the locations of position and texture coord
1838    // attributes so it can bind its data properly
1839    int positionSlot = mCaches.currentProgram->position;
1840    fontRenderer.setAttributeBindingSlots(positionSlot, mTexCoordsSlot);
1841    if (fontRenderer.renderText(paint, clip, text, 0, bytesCount, count, x, y,
1842            hasActiveLayer ? &bounds : NULL)) {
1843#if RENDER_LAYERS_AS_REGIONS
1844        if (hasActiveLayer) {
1845            if (!pureTranslate) {
1846                mSnapshot->transform->mapRect(bounds);
1847            }
1848            dirtyLayerUnchecked(bounds, getRegion());
1849        }
1850#endif
1851    }
1852
1853    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1854    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
1855
1856    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
1857}
1858
1859void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
1860    if (mSnapshot->isIgnored()) return;
1861
1862    glActiveTexture(gTextureUnits[0]);
1863
1864    const PathTexture* texture = mCaches.pathCache.get(path, paint);
1865    if (!texture) return;
1866    const AutoTexture autoCleanup(texture);
1867
1868    const float x = texture->left - texture->offset;
1869    const float y = texture->top - texture->offset;
1870
1871    drawPathTexture(texture, x, y, paint);
1872}
1873
1874void OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) {
1875    if (!layer || quickReject(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight())) {
1876        return;
1877    }
1878
1879    glActiveTexture(gTextureUnits[0]);
1880
1881    int alpha;
1882    SkXfermode::Mode mode;
1883    getAlphaAndMode(paint, &alpha, &mode);
1884
1885    layer->alpha = alpha;
1886    layer->mode = mode;
1887
1888#if RENDER_LAYERS_AS_REGIONS
1889    if (!layer->region.isEmpty()) {
1890        if (layer->region.isRect()) {
1891            composeLayerRect(layer, layer->regionRect);
1892        } else if (layer->mesh) {
1893            const float a = alpha / 255.0f;
1894            const Rect& rect = layer->layer;
1895
1896            setupDraw();
1897            setupDrawWithTexture();
1898            setupDrawColor(a, a, a, a);
1899            setupDrawColorFilter();
1900            setupDrawBlending(layer->blend || layer->alpha < 255, layer->mode, false);
1901            setupDrawProgram();
1902            setupDrawModelViewTranslate(x, y,
1903                    x + layer->layer.getWidth(), y + layer->layer.getHeight());
1904            setupDrawPureColorUniforms();
1905            setupDrawColorFilterUniforms();
1906            setupDrawTexture(layer->texture);
1907            setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]);
1908
1909            glDrawElements(GL_TRIANGLES, layer->meshElementCount,
1910                    GL_UNSIGNED_SHORT, layer->meshIndices);
1911
1912            finishDrawTexture();
1913
1914#if DEBUG_LAYERS_AS_REGIONS
1915            drawRegionRects(layer->region);
1916#endif
1917        }
1918    }
1919#else
1920    const Rect r(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight());
1921    composeLayerRect(layer, r);
1922#endif
1923}
1924
1925///////////////////////////////////////////////////////////////////////////////
1926// Shaders
1927///////////////////////////////////////////////////////////////////////////////
1928
1929void OpenGLRenderer::resetShader() {
1930    mShader = NULL;
1931}
1932
1933void OpenGLRenderer::setupShader(SkiaShader* shader) {
1934    mShader = shader;
1935    if (mShader) {
1936        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
1937    }
1938}
1939
1940///////////////////////////////////////////////////////////////////////////////
1941// Color filters
1942///////////////////////////////////////////////////////////////////////////////
1943
1944void OpenGLRenderer::resetColorFilter() {
1945    mColorFilter = NULL;
1946}
1947
1948void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
1949    mColorFilter = filter;
1950}
1951
1952///////////////////////////////////////////////////////////////////////////////
1953// Drop shadow
1954///////////////////////////////////////////////////////////////////////////////
1955
1956void OpenGLRenderer::resetShadow() {
1957    mHasShadow = false;
1958}
1959
1960void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
1961    mHasShadow = true;
1962    mShadowRadius = radius;
1963    mShadowDx = dx;
1964    mShadowDy = dy;
1965    mShadowColor = color;
1966}
1967
1968///////////////////////////////////////////////////////////////////////////////
1969// Drawing implementation
1970///////////////////////////////////////////////////////////////////////////////
1971
1972void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
1973        float x, float y, SkPaint* paint) {
1974    if (quickReject(x, y, x + texture->width, y + texture->height)) {
1975        return;
1976    }
1977
1978    int alpha;
1979    SkXfermode::Mode mode;
1980    getAlphaAndMode(paint, &alpha, &mode);
1981
1982    setupDraw();
1983    setupDrawWithTexture(true);
1984    setupDrawAlpha8Color(paint->getColor(), alpha);
1985    setupDrawColorFilter();
1986    setupDrawShader();
1987    setupDrawBlending(true, mode);
1988    setupDrawProgram();
1989    setupDrawModelView(x, y, x + texture->width, y + texture->height);
1990    setupDrawTexture(texture->id);
1991    setupDrawPureColorUniforms();
1992    setupDrawColorFilterUniforms();
1993    setupDrawShaderUniforms();
1994    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1995
1996    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1997
1998    finishDrawTexture();
1999}
2000
2001// Same values used by Skia
2002#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
2003#define kStdUnderline_Offset    (1.0f / 9.0f)
2004#define kStdUnderline_Thickness (1.0f / 18.0f)
2005
2006void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
2007        float x, float y, SkPaint* paint) {
2008    // Handle underline and strike-through
2009    uint32_t flags = paint->getFlags();
2010    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
2011        float underlineWidth = length;
2012        // If length is > 0.0f, we already measured the text for the text alignment
2013        if (length <= 0.0f) {
2014            underlineWidth = paint->measureText(text, bytesCount);
2015        }
2016
2017        float offsetX = 0;
2018        switch (paint->getTextAlign()) {
2019            case SkPaint::kCenter_Align:
2020                offsetX = underlineWidth * 0.5f;
2021                break;
2022            case SkPaint::kRight_Align:
2023                offsetX = underlineWidth;
2024                break;
2025            default:
2026                break;
2027        }
2028
2029        if (underlineWidth > 0.0f) {
2030            const float textSize = paint->getTextSize();
2031            // TODO: Support stroke width < 1.0f when we have AA lines
2032            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
2033
2034            const float left = x - offsetX;
2035            float top = 0.0f;
2036
2037            int linesCount = 0;
2038            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
2039            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
2040
2041            const int pointsCount = 4 * linesCount;
2042            float points[pointsCount];
2043            int currentPoint = 0;
2044
2045            if (flags & SkPaint::kUnderlineText_Flag) {
2046                top = y + textSize * kStdUnderline_Offset;
2047                points[currentPoint++] = left;
2048                points[currentPoint++] = top;
2049                points[currentPoint++] = left + underlineWidth;
2050                points[currentPoint++] = top;
2051            }
2052
2053            if (flags & SkPaint::kStrikeThruText_Flag) {
2054                top = y + textSize * kStdStrikeThru_Offset;
2055                points[currentPoint++] = left;
2056                points[currentPoint++] = top;
2057                points[currentPoint++] = left + underlineWidth;
2058                points[currentPoint++] = top;
2059            }
2060
2061            SkPaint linesPaint(*paint);
2062            linesPaint.setStrokeWidth(strokeWidth);
2063
2064            drawLines(&points[0], pointsCount, &linesPaint);
2065        }
2066    }
2067}
2068
2069void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
2070        int color, SkXfermode::Mode mode, bool ignoreTransform) {
2071    // If a shader is set, preserve only the alpha
2072    if (mShader) {
2073        color |= 0x00ffffff;
2074    }
2075
2076    setupDraw();
2077    setupDrawColor(color);
2078    setupDrawShader();
2079    setupDrawColorFilter();
2080    setupDrawBlending(mode);
2081    setupDrawProgram();
2082    setupDrawModelView(left, top, right, bottom, ignoreTransform);
2083    setupDrawColorUniforms();
2084    setupDrawShaderUniforms(ignoreTransform);
2085    setupDrawColorFilterUniforms();
2086    setupDrawSimpleMesh();
2087
2088    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2089}
2090
2091void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
2092        Texture* texture, SkPaint* paint) {
2093    int alpha;
2094    SkXfermode::Mode mode;
2095    getAlphaAndMode(paint, &alpha, &mode);
2096
2097    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
2098
2099    if (mSnapshot->transform->isPureTranslate()) {
2100        const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
2101        const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
2102
2103        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
2104                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
2105                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
2106    } else {
2107        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
2108                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
2109                GL_TRIANGLE_STRIP, gMeshCount);
2110    }
2111}
2112
2113void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
2114        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
2115    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
2116            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
2117}
2118
2119void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
2120        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
2121        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
2122        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
2123
2124    setupDraw();
2125    setupDrawWithTexture();
2126    setupDrawColor(alpha, alpha, alpha, alpha);
2127    setupDrawColorFilter();
2128    setupDrawBlending(blend, mode, swapSrcDst);
2129    setupDrawProgram();
2130    if (!dirty) {
2131        setupDrawDirtyRegionsDisabled();
2132    }
2133    if (!ignoreScale) {
2134        setupDrawModelView(left, top, right, bottom, ignoreTransform);
2135    } else {
2136        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
2137    }
2138    setupDrawPureColorUniforms();
2139    setupDrawColorFilterUniforms();
2140    setupDrawTexture(texture);
2141    setupDrawMesh(vertices, texCoords, vbo);
2142
2143    glDrawArrays(drawMode, 0, elementsCount);
2144
2145    finishDrawTexture();
2146}
2147
2148void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
2149        ProgramDescription& description, bool swapSrcDst) {
2150    blend = blend || mode != SkXfermode::kSrcOver_Mode;
2151    if (blend) {
2152        if (mode < SkXfermode::kPlus_Mode) {
2153            if (!mCaches.blend) {
2154                glEnable(GL_BLEND);
2155            }
2156
2157            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
2158            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
2159
2160            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
2161                glBlendFunc(sourceMode, destMode);
2162                mCaches.lastSrcMode = sourceMode;
2163                mCaches.lastDstMode = destMode;
2164            }
2165        } else {
2166            // These blend modes are not supported by OpenGL directly and have
2167            // to be implemented using shaders. Since the shader will perform
2168            // the blending, turn blending off here
2169            if (mCaches.extensions.hasFramebufferFetch()) {
2170                description.framebufferMode = mode;
2171                description.swapSrcDst = swapSrcDst;
2172            }
2173
2174            if (mCaches.blend) {
2175                glDisable(GL_BLEND);
2176            }
2177            blend = false;
2178        }
2179    } else if (mCaches.blend) {
2180        glDisable(GL_BLEND);
2181    }
2182    mCaches.blend = blend;
2183}
2184
2185bool OpenGLRenderer::useProgram(Program* program) {
2186    if (!program->isInUse()) {
2187        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
2188        program->use();
2189        mCaches.currentProgram = program;
2190        return false;
2191    }
2192    return true;
2193}
2194
2195void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
2196    TextureVertex* v = &mMeshVertices[0];
2197    TextureVertex::setUV(v++, u1, v1);
2198    TextureVertex::setUV(v++, u2, v1);
2199    TextureVertex::setUV(v++, u1, v2);
2200    TextureVertex::setUV(v++, u2, v2);
2201}
2202
2203void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
2204    if (paint) {
2205        if (!mCaches.extensions.hasFramebufferFetch()) {
2206            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
2207            if (!isMode) {
2208                // Assume SRC_OVER
2209                *mode = SkXfermode::kSrcOver_Mode;
2210            }
2211        } else {
2212            *mode = getXfermode(paint->getXfermode());
2213        }
2214
2215        // Skia draws using the color's alpha channel if < 255
2216        // Otherwise, it uses the paint's alpha
2217        int color = paint->getColor();
2218        *alpha = (color >> 24) & 0xFF;
2219        if (*alpha == 255) {
2220            *alpha = paint->getAlpha();
2221        }
2222    } else {
2223        *mode = SkXfermode::kSrcOver_Mode;
2224        *alpha = 255;
2225    }
2226}
2227
2228SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
2229    // In the future we should look at unifying the Porter-Duff modes and
2230    // SkXferModes so that we can use SkXfermode::IsMode(xfer, &mode).
2231    if (mode == NULL) {
2232        return SkXfermode::kSrcOver_Mode;
2233    }
2234    return mode->fMode;
2235}
2236
2237void OpenGLRenderer::setTextureWrapModes(Texture* texture, GLenum wrapS, GLenum wrapT) {
2238    bool bound = false;
2239    if (wrapS != texture->wrapS) {
2240        glBindTexture(GL_TEXTURE_2D, texture->id);
2241        bound = true;
2242        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
2243        texture->wrapS = wrapS;
2244    }
2245    if (wrapT != texture->wrapT) {
2246        if (!bound) {
2247            glBindTexture(GL_TEXTURE_2D, texture->id);
2248        }
2249        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
2250        texture->wrapT = wrapT;
2251    }
2252}
2253
2254}; // namespace uirenderer
2255}; // namespace android
2256