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