OpenGLRenderer.cpp revision 6816972eb69ee8b294553dac92b3c1ad5b1ca1f7
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_ONE_MINUS_SRC_ALPHA },
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_ONE_MINUS_DST_ALPHA,  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    glDisable(GL_DITHER);
129    glViewport(0, 0, width, height);
130    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
131
132    mWidth = width;
133    mHeight = height;
134
135    mFirstSnapshot->height = height;
136    mFirstSnapshot->viewport.set(0, 0, width, height);
137
138    mDirtyClip = false;
139}
140
141void OpenGLRenderer::prepare(bool opaque) {
142    prepareDirty(0.0f, 0.0f, mWidth, mHeight, opaque);
143}
144
145void OpenGLRenderer::prepareDirty(float left, float top, float right, float bottom, bool opaque) {
146    mCaches.clearGarbage();
147
148    mSnapshot = new Snapshot(mFirstSnapshot,
149            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
150    mSnapshot->fbo = getTargetFbo();
151
152    mSaveCount = 1;
153
154    glViewport(0, 0, mWidth, mHeight);
155
156    glEnable(GL_SCISSOR_TEST);
157    glScissor(left, mSnapshot->height - bottom, right - left, bottom - top);
158    mSnapshot->setClip(left, top, right, bottom);
159
160    if (!opaque) {
161        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
162        glClear(GL_COLOR_BUFFER_BIT);
163    }
164}
165
166void OpenGLRenderer::finish() {
167#if DEBUG_OPENGL
168    GLenum status = GL_NO_ERROR;
169    while ((status = glGetError()) != GL_NO_ERROR) {
170        LOGD("GL error from OpenGLRenderer: 0x%x", status);
171        switch (status) {
172            case GL_OUT_OF_MEMORY:
173                LOGE("  OpenGLRenderer is out of memory!");
174                break;
175        }
176    }
177#endif
178#if DEBUG_MEMORY_USAGE
179    mCaches.dumpMemoryUsage();
180#else
181    if (mCaches.getDebugLevel() & kDebugMemory) {
182        mCaches.dumpMemoryUsage();
183    }
184#endif
185}
186
187void OpenGLRenderer::interrupt() {
188    if (mCaches.currentProgram) {
189        if (mCaches.currentProgram->isInUse()) {
190            mCaches.currentProgram->remove();
191            mCaches.currentProgram = NULL;
192        }
193    }
194    mCaches.unbindMeshBuffer();
195}
196
197void OpenGLRenderer::resume() {
198    glViewport(0, 0, mSnapshot->viewport.getWidth(), mSnapshot->viewport.getHeight());
199
200    glEnable(GL_SCISSOR_TEST);
201    dirtyClip();
202
203    glDisable(GL_DITHER);
204
205    glBindFramebuffer(GL_FRAMEBUFFER, getTargetFbo());
206    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
207
208    mCaches.blend = true;
209    glEnable(GL_BLEND);
210    glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
211    glBlendEquation(GL_FUNC_ADD);
212}
213
214bool OpenGLRenderer::callDrawGLFunction(Functor *functor, Rect& dirty) {
215    interrupt();
216    if (mDirtyClip) {
217        setScissorFromClip();
218    }
219
220    Rect clip(*mSnapshot->clipRect);
221    clip.snapToPixelBoundaries();
222
223#if RENDER_LAYERS_AS_REGIONS
224    // Since we don't know what the functor will draw, let's dirty
225    // tne entire clip region
226    if (hasLayer()) {
227        dirtyLayerUnchecked(clip, getRegion());
228    }
229#endif
230
231    DrawGlInfo info;
232    info.clipLeft = clip.left;
233    info.clipTop = clip.top;
234    info.clipRight = clip.right;
235    info.clipBottom = clip.bottom;
236    info.isLayer = hasLayer();
237    getSnapshot()->transform->copyTo(&info.transform[0]);
238
239    status_t result = (*functor)(0, &info);
240
241    if (result != 0) {
242        Rect localDirty(info.dirtyLeft, info.dirtyTop, info.dirtyRight, info.dirtyBottom);
243        dirty.unionWith(localDirty);
244    }
245
246    resume();
247    return result != 0;
248}
249
250///////////////////////////////////////////////////////////////////////////////
251// State management
252///////////////////////////////////////////////////////////////////////////////
253
254int OpenGLRenderer::getSaveCount() const {
255    return mSaveCount;
256}
257
258int OpenGLRenderer::save(int flags) {
259    return saveSnapshot(flags);
260}
261
262void OpenGLRenderer::restore() {
263    if (mSaveCount > 1) {
264        restoreSnapshot();
265    }
266}
267
268void OpenGLRenderer::restoreToCount(int saveCount) {
269    if (saveCount < 1) saveCount = 1;
270
271    while (mSaveCount > saveCount) {
272        restoreSnapshot();
273    }
274}
275
276int OpenGLRenderer::saveSnapshot(int flags) {
277    mSnapshot = new Snapshot(mSnapshot, flags);
278    return mSaveCount++;
279}
280
281bool OpenGLRenderer::restoreSnapshot() {
282    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
283    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
284    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
285
286    sp<Snapshot> current = mSnapshot;
287    sp<Snapshot> previous = mSnapshot->previous;
288
289    if (restoreOrtho) {
290        Rect& r = previous->viewport;
291        glViewport(r.left, r.top, r.right, r.bottom);
292        mOrthoMatrix.load(current->orthoMatrix);
293    }
294
295    mSaveCount--;
296    mSnapshot = previous;
297
298    if (restoreClip) {
299        dirtyClip();
300    }
301
302    if (restoreLayer) {
303        composeLayer(current, previous);
304    }
305
306    return restoreClip;
307}
308
309///////////////////////////////////////////////////////////////////////////////
310// Layers
311///////////////////////////////////////////////////////////////////////////////
312
313int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
314        SkPaint* p, int flags) {
315    const GLuint previousFbo = mSnapshot->fbo;
316    const int count = saveSnapshot(flags);
317
318    if (!mSnapshot->isIgnored()) {
319        int alpha = 255;
320        SkXfermode::Mode mode;
321
322        if (p) {
323            alpha = p->getAlpha();
324            if (!mCaches.extensions.hasFramebufferFetch()) {
325                const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
326                if (!isMode) {
327                    // Assume SRC_OVER
328                    mode = SkXfermode::kSrcOver_Mode;
329                }
330            } else {
331                mode = getXfermode(p->getXfermode());
332            }
333        } else {
334            mode = SkXfermode::kSrcOver_Mode;
335        }
336
337        createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags, previousFbo);
338    }
339
340    return count;
341}
342
343int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
344        int alpha, int flags) {
345    if (alpha >= 255 - ALPHA_THRESHOLD) {
346        return saveLayer(left, top, right, bottom, NULL, flags);
347    } else {
348        SkPaint paint;
349        paint.setAlpha(alpha);
350        return saveLayer(left, top, right, bottom, &paint, flags);
351    }
352}
353
354/**
355 * Layers are viewed by Skia are slightly different than layers in image editing
356 * programs (for instance.) When a layer is created, previously created layers
357 * and the frame buffer still receive every drawing command. For instance, if a
358 * layer is created and a shape intersecting the bounds of the layers and the
359 * framebuffer is draw, the shape will be drawn on both (unless the layer was
360 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
361 *
362 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
363 * texture. Unfortunately, this is inefficient as it requires every primitive to
364 * be drawn n + 1 times, where n is the number of active layers. In practice this
365 * means, for every primitive:
366 *   - Switch active frame buffer
367 *   - Change viewport, clip and projection matrix
368 *   - Issue the drawing
369 *
370 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
371 * To avoid this, layers are implemented in a different way here, at least in the
372 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
373 * is set. When this flag is set we can redirect all drawing operations into a
374 * single FBO.
375 *
376 * This implementation relies on the frame buffer being at least RGBA 8888. When
377 * a layer is created, only a texture is created, not an FBO. The content of the
378 * frame buffer contained within the layer's bounds is copied into this texture
379 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
380 * buffer and drawing continues as normal. This technique therefore treats the
381 * frame buffer as a scratch buffer for the layers.
382 *
383 * To compose the layers back onto the frame buffer, each layer texture
384 * (containing the original frame buffer data) is drawn as a simple quad over
385 * the frame buffer. The trick is that the quad is set as the composition
386 * destination in the blending equation, and the frame buffer becomes the source
387 * of the composition.
388 *
389 * Drawing layers with an alpha value requires an extra step before composition.
390 * An empty quad is drawn over the layer's region in the frame buffer. This quad
391 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
392 * quad is used to multiply the colors in the frame buffer. This is achieved by
393 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
394 * GL_ZERO, GL_SRC_ALPHA.
395 *
396 * Because glCopyTexImage2D() can be slow, an alternative implementation might
397 * be use to draw a single clipped layer. The implementation described above
398 * is correct in every case.
399 *
400 * (1) The frame buffer is actually not cleared right away. To allow the GPU
401 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
402 *     buffer is left untouched until the first drawing operation. Only when
403 *     something actually gets drawn are the layers regions cleared.
404 */
405bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
406        float right, float bottom, int alpha, SkXfermode::Mode mode,
407        int flags, GLuint previousFbo) {
408    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
409    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
410
411    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
412
413    // Window coordinates of the layer
414    Rect bounds(left, top, right, bottom);
415    if (!fboLayer) {
416        mSnapshot->transform->mapRect(bounds);
417
418        // Layers only make sense if they are in the framebuffer's bounds
419        if (bounds.intersect(*snapshot->clipRect)) {
420            // We cannot work with sub-pixels in this case
421            bounds.snapToPixelBoundaries();
422
423            // When the layer is not an FBO, we may use glCopyTexImage so we
424            // need to make sure the layer does not extend outside the bounds
425            // of the framebuffer
426            if (!bounds.intersect(snapshot->previous->viewport)) {
427                bounds.setEmpty();
428            }
429        } else {
430            bounds.setEmpty();
431        }
432    }
433
434    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
435            bounds.getHeight() > mCaches.maxTextureSize) {
436        snapshot->empty = fboLayer;
437    } else {
438        snapshot->invisible = snapshot->invisible || (alpha <= ALPHA_THRESHOLD && fboLayer);
439    }
440
441    // Bail out if we won't draw in this snapshot
442    if (snapshot->invisible || snapshot->empty) {
443        return false;
444    }
445
446    glActiveTexture(gTextureUnits[0]);
447    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
448    if (!layer) {
449        return false;
450    }
451
452    layer->setAlpha(alpha, mode);
453    layer->layer.set(bounds);
454    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->getHeight()),
455            bounds.getWidth() / float(layer->getWidth()), 0.0f);
456    layer->setColorFilter(mColorFilter);
457
458    // Save the layer in the snapshot
459    snapshot->flags |= Snapshot::kFlagIsLayer;
460    snapshot->layer = layer;
461
462    if (fboLayer) {
463        return createFboLayer(layer, bounds, snapshot, previousFbo);
464    } else {
465        // Copy the framebuffer into the layer
466        layer->bindTexture();
467        if (!bounds.isEmpty()) {
468            if (layer->isEmpty()) {
469                glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
470                        bounds.left, snapshot->height - bounds.bottom,
471                        layer->getWidth(), layer->getHeight(), 0);
472                layer->setEmpty(false);
473            } else {
474                glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left,
475                        snapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight());
476            }
477
478            // Enqueue the buffer coordinates to clear the corresponding region later
479            mLayers.push(new Rect(bounds));
480        }
481    }
482
483    return true;
484}
485
486bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, sp<Snapshot> snapshot,
487        GLuint previousFbo) {
488    layer->setFbo(mCaches.fboCache.get());
489
490#if RENDER_LAYERS_AS_REGIONS
491    snapshot->region = &snapshot->layer->region;
492    snapshot->flags |= Snapshot::kFlagFboTarget;
493#endif
494
495    Rect clip(bounds);
496    snapshot->transform->mapRect(clip);
497    clip.intersect(*snapshot->clipRect);
498    clip.snapToPixelBoundaries();
499    clip.intersect(snapshot->previous->viewport);
500
501    mat4 inverse;
502    inverse.loadInverse(*mSnapshot->transform);
503
504    inverse.mapRect(clip);
505    clip.snapToPixelBoundaries();
506    clip.intersect(bounds);
507    clip.translate(-bounds.left, -bounds.top);
508
509    snapshot->flags |= Snapshot::kFlagIsFboLayer;
510    snapshot->fbo = layer->getFbo();
511    snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
512    snapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
513    snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
514    snapshot->height = bounds.getHeight();
515    snapshot->flags |= Snapshot::kFlagDirtyOrtho;
516    snapshot->orthoMatrix.load(mOrthoMatrix);
517
518    // Bind texture to FBO
519    glBindFramebuffer(GL_FRAMEBUFFER, layer->getFbo());
520    layer->bindTexture();
521
522    // Initialize the texture if needed
523    if (layer->isEmpty()) {
524        layer->allocateTexture(GL_RGBA, GL_UNSIGNED_BYTE);
525        layer->setEmpty(false);
526    }
527
528    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
529            layer->getTexture(), 0);
530
531#if DEBUG_LAYERS_AS_REGIONS
532    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
533    if (status != GL_FRAMEBUFFER_COMPLETE) {
534        LOGE("Framebuffer incomplete (GL error code 0x%x)", status);
535
536        glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
537        layer->deleteTexture();
538        mCaches.fboCache.put(layer->getFbo());
539
540        delete layer;
541
542        return false;
543    }
544#endif
545
546    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
547    glScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
548            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
549    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
550    glClear(GL_COLOR_BUFFER_BIT);
551
552    dirtyClip();
553
554    // Change the ortho projection
555    glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
556    mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
557
558    return true;
559}
560
561/**
562 * Read the documentation of createLayer() before doing anything in this method.
563 */
564void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
565    if (!current->layer) {
566        LOGE("Attempting to compose a layer that does not exist");
567        return;
568    }
569
570    const bool fboLayer = current->flags & Snapshot::kFlagIsFboLayer;
571
572    if (fboLayer) {
573        // Unbind current FBO and restore previous one
574        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
575    }
576
577    Layer* layer = current->layer;
578    const Rect& rect = layer->layer;
579
580    if (!fboLayer && layer->getAlpha() < 255) {
581        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
582                layer->getAlpha() << 24, SkXfermode::kDstIn_Mode, true);
583        // Required below, composeLayerRect() will divide by 255
584        layer->setAlpha(255);
585    }
586
587    mCaches.unbindMeshBuffer();
588
589    glActiveTexture(gTextureUnits[0]);
590
591    // When the layer is stored in an FBO, we can save a bit of fillrate by
592    // drawing only the dirty region
593    if (fboLayer) {
594        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform);
595        if (layer->getColorFilter()) {
596            setupColorFilter(layer->getColorFilter());
597        }
598        composeLayerRegion(layer, rect);
599        if (layer->getColorFilter()) {
600            resetColorFilter();
601        }
602    } else if (!rect.isEmpty()) {
603        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
604        composeLayerRect(layer, rect, true);
605    }
606
607    if (fboLayer) {
608        // Detach the texture from the FBO
609        glBindFramebuffer(GL_FRAMEBUFFER, current->fbo);
610        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
611        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
612
613        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
614        mCaches.fboCache.put(current->fbo);
615    }
616
617    dirtyClip();
618
619    // Failing to add the layer to the cache should happen only if the layer is too large
620    if (!mCaches.layerCache.put(layer)) {
621        LAYER_LOGD("Deleting layer");
622        layer->deleteTexture();
623        delete layer;
624    }
625}
626
627void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) {
628    float alpha = layer->getAlpha() / 255.0f;
629
630    mat4& transform = layer->getTransform();
631    if (!transform.isIdentity()) {
632        save(0);
633        mSnapshot->transform->multiply(transform);
634    }
635
636    setupDraw();
637    if (layer->getRenderTarget() == GL_TEXTURE_2D) {
638        setupDrawWithTexture();
639    } else {
640        setupDrawWithExternalTexture();
641    }
642    setupDrawTextureTransform();
643    setupDrawColor(alpha, alpha, alpha, alpha);
644    setupDrawColorFilter();
645    setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode());
646    setupDrawProgram();
647    setupDrawPureColorUniforms();
648    setupDrawColorFilterUniforms();
649    if (layer->getRenderTarget() == GL_TEXTURE_2D) {
650        setupDrawTexture(layer->getTexture());
651    } else {
652        setupDrawExternalTexture(layer->getTexture());
653    }
654    if (mSnapshot->transform->isPureTranslate() &&
655            layer->getWidth() == (uint32_t) rect.getWidth() &&
656            layer->getHeight() == (uint32_t) rect.getHeight()) {
657        const float x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f);
658        const float y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f);
659
660        layer->setFilter(GL_NEAREST, GL_NEAREST);
661        setupDrawModelView(x, y, x + rect.getWidth(), y + rect.getHeight(), true);
662    } else {
663        layer->setFilter(GL_LINEAR, GL_LINEAR);
664        setupDrawModelView(rect.left, rect.top, rect.right, rect.bottom);
665    }
666    setupDrawTextureTransformUniforms(layer->getTexTransform());
667    setupDrawMesh(&mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]);
668
669    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
670
671    finishDrawTexture();
672
673    if (!transform.isIdentity()) {
674        restore();
675    }
676}
677
678void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
679    if (!layer->isTextureLayer()) {
680        const Rect& texCoords = layer->texCoords;
681        resetDrawTextureTexCoords(texCoords.left, texCoords.top,
682                texCoords.right, texCoords.bottom);
683
684        float x = rect.left;
685        float y = rect.top;
686        bool simpleTransform = mSnapshot->transform->isPureTranslate() &&
687                layer->getWidth() == (uint32_t) rect.getWidth() &&
688                layer->getHeight() == (uint32_t) rect.getHeight();
689
690        if (simpleTransform) {
691            // When we're swapping, the layer is already in screen coordinates
692            if (!swap) {
693                x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f);
694                y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f);
695            }
696
697            layer->setFilter(GL_NEAREST, GL_NEAREST, true);
698        } else {
699            layer->setFilter(GL_LINEAR, GL_LINEAR, true);
700        }
701
702        drawTextureMesh(x, y, x + rect.getWidth(), y + rect.getHeight(),
703                layer->getTexture(), layer->getAlpha() / 255.0f,
704                layer->getMode(), layer->isBlend(),
705                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
706                GL_TRIANGLE_STRIP, gMeshCount, swap, swap || simpleTransform);
707
708        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
709    } else {
710        resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f);
711        drawTextureLayer(layer, rect);
712        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
713    }
714}
715
716void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
717#if RENDER_LAYERS_AS_REGIONS
718    if (layer->region.isRect()) {
719        layer->setRegionAsRect();
720
721        composeLayerRect(layer, layer->regionRect);
722
723        layer->region.clear();
724        return;
725    }
726
727    if (!layer->region.isEmpty()) {
728        size_t count;
729        const android::Rect* rects = layer->region.getArray(&count);
730
731        const float alpha = layer->getAlpha() / 255.0f;
732        const float texX = 1.0f / float(layer->getWidth());
733        const float texY = 1.0f / float(layer->getHeight());
734        const float height = rect.getHeight();
735
736        TextureVertex* mesh = mCaches.getRegionMesh();
737        GLsizei numQuads = 0;
738
739        setupDraw();
740        setupDrawWithTexture();
741        setupDrawColor(alpha, alpha, alpha, alpha);
742        setupDrawColorFilter();
743        setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode(), false);
744        setupDrawProgram();
745        setupDrawDirtyRegionsDisabled();
746        setupDrawPureColorUniforms();
747        setupDrawColorFilterUniforms();
748        setupDrawTexture(layer->getTexture());
749        if (mSnapshot->transform->isPureTranslate()) {
750            const float x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f);
751            const float y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f);
752
753            layer->setFilter(GL_NEAREST, GL_NEAREST);
754            setupDrawModelViewTranslate(x, y, x + rect.getWidth(), y + rect.getHeight(), true);
755        } else {
756            layer->setFilter(GL_LINEAR, GL_LINEAR);
757            setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
758        }
759        setupDrawMesh(&mesh[0].position[0], &mesh[0].texture[0]);
760
761        for (size_t i = 0; i < count; i++) {
762            const android::Rect* r = &rects[i];
763
764            const float u1 = r->left * texX;
765            const float v1 = (height - r->top) * texY;
766            const float u2 = r->right * texX;
767            const float v2 = (height - r->bottom) * texY;
768
769            // TODO: Reject quads outside of the clip
770            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
771            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
772            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
773            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
774
775            numQuads++;
776
777            if (numQuads >= REGION_MESH_QUAD_COUNT) {
778                glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
779                numQuads = 0;
780                mesh = mCaches.getRegionMesh();
781            }
782        }
783
784        if (numQuads > 0) {
785            glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
786        }
787
788        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
789        finishDrawTexture();
790
791#if DEBUG_LAYERS_AS_REGIONS
792        drawRegionRects(layer->region);
793#endif
794
795        layer->region.clear();
796    }
797#else
798    composeLayerRect(layer, rect);
799#endif
800}
801
802void OpenGLRenderer::drawRegionRects(const Region& region) {
803#if DEBUG_LAYERS_AS_REGIONS
804    size_t count;
805    const android::Rect* rects = region.getArray(&count);
806
807    uint32_t colors[] = {
808            0x7fff0000, 0x7f00ff00,
809            0x7f0000ff, 0x7fff00ff,
810    };
811
812    int offset = 0;
813    int32_t top = rects[0].top;
814
815    for (size_t i = 0; i < count; i++) {
816        if (top != rects[i].top) {
817            offset ^= 0x2;
818            top = rects[i].top;
819        }
820
821        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
822        drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
823                SkXfermode::kSrcOver_Mode);
824    }
825#endif
826}
827
828void OpenGLRenderer::dirtyLayer(const float left, const float top,
829        const float right, const float bottom, const mat4 transform) {
830#if RENDER_LAYERS_AS_REGIONS
831    if (hasLayer()) {
832        Rect bounds(left, top, right, bottom);
833        transform.mapRect(bounds);
834        dirtyLayerUnchecked(bounds, getRegion());
835    }
836#endif
837}
838
839void OpenGLRenderer::dirtyLayer(const float left, const float top,
840        const float right, const float bottom) {
841#if RENDER_LAYERS_AS_REGIONS
842    if (hasLayer()) {
843        Rect bounds(left, top, right, bottom);
844        dirtyLayerUnchecked(bounds, getRegion());
845    }
846#endif
847}
848
849void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
850#if RENDER_LAYERS_AS_REGIONS
851    if (bounds.intersect(*mSnapshot->clipRect)) {
852        bounds.snapToPixelBoundaries();
853        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
854        if (!dirty.isEmpty()) {
855            region->orSelf(dirty);
856        }
857    }
858#endif
859}
860
861void OpenGLRenderer::clearLayerRegions() {
862    const size_t count = mLayers.size();
863    if (count == 0) return;
864
865    if (!mSnapshot->isIgnored()) {
866        // Doing several glScissor/glClear here can negatively impact
867        // GPUs with a tiler architecture, instead we draw quads with
868        // the Clear blending mode
869
870        // The list contains bounds that have already been clipped
871        // against their initial clip rect, and the current clip
872        // is likely different so we need to disable clipping here
873        glDisable(GL_SCISSOR_TEST);
874
875        Vertex mesh[count * 6];
876        Vertex* vertex = mesh;
877
878        for (uint32_t i = 0; i < count; i++) {
879            Rect* bounds = mLayers.itemAt(i);
880
881            Vertex::set(vertex++, bounds->left, bounds->bottom);
882            Vertex::set(vertex++, bounds->left, bounds->top);
883            Vertex::set(vertex++, bounds->right, bounds->top);
884            Vertex::set(vertex++, bounds->left, bounds->bottom);
885            Vertex::set(vertex++, bounds->right, bounds->top);
886            Vertex::set(vertex++, bounds->right, bounds->bottom);
887
888            delete bounds;
889        }
890
891        setupDraw(false);
892        setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f);
893        setupDrawBlending(true, SkXfermode::kClear_Mode);
894        setupDrawProgram();
895        setupDrawPureColorUniforms();
896        setupDrawModelViewTranslate(0.0f, 0.0f, 0.0f, 0.0f, true);
897
898        mCaches.unbindMeshBuffer();
899        glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
900                gVertexStride, &mesh[0].position[0]);
901        glDrawArrays(GL_TRIANGLES, 0, count * 6);
902
903        glEnable(GL_SCISSOR_TEST);
904    } else {
905        for (uint32_t i = 0; i < count; i++) {
906            delete mLayers.itemAt(i);
907        }
908    }
909
910    mLayers.clear();
911}
912
913///////////////////////////////////////////////////////////////////////////////
914// Transforms
915///////////////////////////////////////////////////////////////////////////////
916
917void OpenGLRenderer::translate(float dx, float dy) {
918    mSnapshot->transform->translate(dx, dy, 0.0f);
919}
920
921void OpenGLRenderer::rotate(float degrees) {
922    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
923}
924
925void OpenGLRenderer::scale(float sx, float sy) {
926    mSnapshot->transform->scale(sx, sy, 1.0f);
927}
928
929void OpenGLRenderer::skew(float sx, float sy) {
930    mSnapshot->transform->skew(sx, sy);
931}
932
933void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
934    mSnapshot->transform->load(*matrix);
935}
936
937void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
938    mSnapshot->transform->copyTo(*matrix);
939}
940
941void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
942    SkMatrix transform;
943    mSnapshot->transform->copyTo(transform);
944    transform.preConcat(*matrix);
945    mSnapshot->transform->load(transform);
946}
947
948///////////////////////////////////////////////////////////////////////////////
949// Clipping
950///////////////////////////////////////////////////////////////////////////////
951
952void OpenGLRenderer::setScissorFromClip() {
953    Rect clip(*mSnapshot->clipRect);
954    clip.snapToPixelBoundaries();
955    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
956    mDirtyClip = false;
957}
958
959const Rect& OpenGLRenderer::getClipBounds() {
960    return mSnapshot->getLocalClip();
961}
962
963bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
964    if (mSnapshot->isIgnored()) {
965        return true;
966    }
967
968    Rect r(left, top, right, bottom);
969    mSnapshot->transform->mapRect(r);
970    r.snapToPixelBoundaries();
971
972    Rect clipRect(*mSnapshot->clipRect);
973    clipRect.snapToPixelBoundaries();
974
975    return !clipRect.intersects(r);
976}
977
978bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
979    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
980    if (clipped) {
981        dirtyClip();
982    }
983    return !mSnapshot->clipRect->isEmpty();
984}
985
986///////////////////////////////////////////////////////////////////////////////
987// Drawing commands
988///////////////////////////////////////////////////////////////////////////////
989
990void OpenGLRenderer::setupDraw(bool clear) {
991    if (clear) clearLayerRegions();
992    if (mDirtyClip) {
993        setScissorFromClip();
994    }
995    mDescription.reset();
996    mSetShaderColor = false;
997    mColorSet = false;
998    mColorA = mColorR = mColorG = mColorB = 0.0f;
999    mTextureUnit = 0;
1000    mTrackDirtyRegions = true;
1001    mTexCoordsSlot = -1;
1002}
1003
1004void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
1005    mDescription.hasTexture = true;
1006    mDescription.hasAlpha8Texture = isAlpha8;
1007}
1008
1009void OpenGLRenderer::setupDrawWithExternalTexture() {
1010    mDescription.hasExternalTexture = true;
1011}
1012
1013void OpenGLRenderer::setupDrawAALine() {
1014    mDescription.isAA = true;
1015}
1016
1017void OpenGLRenderer::setupDrawPoint(float pointSize) {
1018    mDescription.isPoint = true;
1019    mDescription.pointSize = pointSize;
1020}
1021
1022void OpenGLRenderer::setupDrawColor(int color) {
1023    setupDrawColor(color, (color >> 24) & 0xFF);
1024}
1025
1026void OpenGLRenderer::setupDrawColor(int color, int alpha) {
1027    mColorA = alpha / 255.0f;
1028    // Second divide of a by 255 is an optimization, allowing us to simply multiply
1029    // the rgb values by a instead of also dividing by 255
1030    const float a = mColorA / 255.0f;
1031    mColorR = a * ((color >> 16) & 0xFF);
1032    mColorG = a * ((color >>  8) & 0xFF);
1033    mColorB = a * ((color      ) & 0xFF);
1034    mColorSet = true;
1035    mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA);
1036}
1037
1038void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
1039    mColorA = alpha / 255.0f;
1040    // Double-divide of a by 255 is an optimization, allowing us to simply multiply
1041    // the rgb values by a instead of also dividing by 255
1042    const float a = mColorA / 255.0f;
1043    mColorR = a * ((color >> 16) & 0xFF);
1044    mColorG = a * ((color >>  8) & 0xFF);
1045    mColorB = a * ((color      ) & 0xFF);
1046    mColorSet = true;
1047    mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
1048}
1049
1050void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
1051    mColorA = a;
1052    mColorR = r;
1053    mColorG = g;
1054    mColorB = b;
1055    mColorSet = true;
1056    mSetShaderColor = mDescription.setColor(r, g, b, a);
1057}
1058
1059void OpenGLRenderer::setupDrawAlpha8Color(float r, float g, float b, float a) {
1060    mColorA = a;
1061    mColorR = r;
1062    mColorG = g;
1063    mColorB = b;
1064    mColorSet = true;
1065    mSetShaderColor = mDescription.setAlpha8Color(r, g, b, a);
1066}
1067
1068void OpenGLRenderer::setupDrawShader() {
1069    if (mShader) {
1070        mShader->describe(mDescription, mCaches.extensions);
1071    }
1072}
1073
1074void OpenGLRenderer::setupDrawColorFilter() {
1075    if (mColorFilter) {
1076        mColorFilter->describe(mDescription, mCaches.extensions);
1077    }
1078}
1079
1080void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
1081    if (mColorSet && mode == SkXfermode::kClear_Mode) {
1082        mColorA = 1.0f;
1083        mColorR = mColorG = mColorB = 0.0f;
1084        mSetShaderColor = mDescription.modulate = true;
1085    }
1086}
1087
1088void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) {
1089    // When the blending mode is kClear_Mode, we need to use a modulate color
1090    // argb=1,0,0,0
1091    accountForClear(mode);
1092    chooseBlending((mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
1093            mDescription, swapSrcDst);
1094}
1095
1096void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) {
1097    // When the blending mode is kClear_Mode, we need to use a modulate color
1098    // argb=1,0,0,0
1099    accountForClear(mode);
1100    chooseBlending(blend || (mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
1101            mDescription, swapSrcDst);
1102}
1103
1104void OpenGLRenderer::setupDrawProgram() {
1105    useProgram(mCaches.programCache.get(mDescription));
1106}
1107
1108void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
1109    mTrackDirtyRegions = false;
1110}
1111
1112void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom,
1113        bool ignoreTransform) {
1114    mModelView.loadTranslate(left, top, 0.0f);
1115    if (!ignoreTransform) {
1116        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1117        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1118    } else {
1119        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1120        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
1121    }
1122}
1123
1124void OpenGLRenderer::setupDrawModelViewIdentity(bool offset) {
1125    mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform, offset);
1126}
1127
1128void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom,
1129        bool ignoreTransform, bool ignoreModelView) {
1130    if (!ignoreModelView) {
1131        mModelView.loadTranslate(left, top, 0.0f);
1132        mModelView.scale(right - left, bottom - top, 1.0f);
1133    } else {
1134        mModelView.loadIdentity();
1135    }
1136    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
1137    if (!ignoreTransform) {
1138        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1139        if (mTrackDirtyRegions && dirty) {
1140            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1141        }
1142    } else {
1143        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1144        if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom);
1145    }
1146}
1147
1148void OpenGLRenderer::setupDrawPointUniforms() {
1149    int slot = mCaches.currentProgram->getUniform("pointSize");
1150    glUniform1f(slot, mDescription.pointSize);
1151}
1152
1153void OpenGLRenderer::setupDrawColorUniforms() {
1154    if (mColorSet || (mShader && mSetShaderColor)) {
1155        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1156    }
1157}
1158
1159void OpenGLRenderer::setupDrawPureColorUniforms() {
1160    if (mSetShaderColor) {
1161        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1162    }
1163}
1164
1165void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
1166    if (mShader) {
1167        if (ignoreTransform) {
1168            mModelView.loadInverse(*mSnapshot->transform);
1169        }
1170        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &mTextureUnit);
1171    }
1172}
1173
1174void OpenGLRenderer::setupDrawShaderIdentityUniforms() {
1175    if (mShader) {
1176        mShader->setupProgram(mCaches.currentProgram, mIdentity, *mSnapshot, &mTextureUnit);
1177    }
1178}
1179
1180void OpenGLRenderer::setupDrawColorFilterUniforms() {
1181    if (mColorFilter) {
1182        mColorFilter->setupProgram(mCaches.currentProgram);
1183    }
1184}
1185
1186void OpenGLRenderer::setupDrawSimpleMesh() {
1187    mCaches.bindMeshBuffer();
1188    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1189            gMeshStride, 0);
1190}
1191
1192void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1193    bindTexture(texture);
1194    glUniform1i(mCaches.currentProgram->getUniform("sampler"), mTextureUnit++);
1195
1196    mTexCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1197    glEnableVertexAttribArray(mTexCoordsSlot);
1198}
1199
1200void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) {
1201    bindExternalTexture(texture);
1202    glUniform1i(mCaches.currentProgram->getUniform("sampler"), mTextureUnit++);
1203
1204    mTexCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1205    glEnableVertexAttribArray(mTexCoordsSlot);
1206}
1207
1208void OpenGLRenderer::setupDrawTextureTransform() {
1209    mDescription.hasTextureTransform = true;
1210}
1211
1212void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) {
1213    glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1,
1214            GL_FALSE, &transform.data[0]);
1215}
1216
1217void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1218    if (!vertices) {
1219        mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1220    } else {
1221        mCaches.unbindMeshBuffer();
1222    }
1223    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1224            gMeshStride, vertices);
1225    if (mTexCoordsSlot >= 0) {
1226        glVertexAttribPointer(mTexCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1227    }
1228}
1229
1230void OpenGLRenderer::setupDrawVertices(GLvoid* vertices) {
1231    mCaches.unbindMeshBuffer();
1232    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1233            gVertexStride, vertices);
1234}
1235
1236/**
1237 * Sets up the shader to draw an AA line. We draw AA lines with quads, where there is an
1238 * outer boundary that fades out to 0. The variables set in the shader define the proportion of
1239 * the width and length of the primitive occupied by the AA region. The vtxWidth and vtxLength
1240 * attributes (one per vertex) are values from zero to one that tells the fragment
1241 * shader where the fragment is in relation to the line width/length overall; these values are
1242 * then used to compute the proper color, based on whether the fragment lies in the fading AA
1243 * region of the line.
1244 * Note that we only pass down the width values in this setup function. The length coordinates
1245 * are set up for each individual segment.
1246 */
1247void OpenGLRenderer::setupDrawAALine(GLvoid* vertices, GLvoid* widthCoords,
1248        GLvoid* lengthCoords, float boundaryWidthProportion) {
1249    mCaches.unbindMeshBuffer();
1250    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1251            gAAVertexStride, vertices);
1252    int widthSlot = mCaches.currentProgram->getAttrib("vtxWidth");
1253    glEnableVertexAttribArray(widthSlot);
1254    glVertexAttribPointer(widthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, widthCoords);
1255    int lengthSlot = mCaches.currentProgram->getAttrib("vtxLength");
1256    glEnableVertexAttribArray(lengthSlot);
1257    glVertexAttribPointer(lengthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, lengthCoords);
1258    int boundaryWidthSlot = mCaches.currentProgram->getUniform("boundaryWidth");
1259    glUniform1f(boundaryWidthSlot, boundaryWidthProportion);
1260    // Setting the inverse value saves computations per-fragment in the shader
1261    int inverseBoundaryWidthSlot = mCaches.currentProgram->getUniform("inverseBoundaryWidth");
1262    glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidthProportion));
1263}
1264
1265void OpenGLRenderer::finishDrawTexture() {
1266    glDisableVertexAttribArray(mTexCoordsSlot);
1267}
1268
1269///////////////////////////////////////////////////////////////////////////////
1270// Drawing
1271///////////////////////////////////////////////////////////////////////////////
1272
1273bool OpenGLRenderer::drawDisplayList(DisplayList* displayList, uint32_t width, uint32_t height,
1274        Rect& dirty, uint32_t level) {
1275    if (quickReject(0.0f, 0.0f, width, height)) {
1276        return false;
1277    }
1278
1279    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1280    // will be performed by the display list itself
1281    if (displayList) {
1282        return displayList->replay(*this, dirty, level);
1283    }
1284
1285    return false;
1286}
1287
1288void OpenGLRenderer::outputDisplayList(DisplayList* displayList, uint32_t level) {
1289    if (displayList) {
1290        displayList->output(*this, level);
1291    }
1292}
1293
1294void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint) {
1295    int alpha;
1296    SkXfermode::Mode mode;
1297    getAlphaAndMode(paint, &alpha, &mode);
1298
1299    float x = left;
1300    float y = top;
1301
1302    GLenum filter = GL_LINEAR;
1303    bool ignoreTransform = false;
1304    if (mSnapshot->transform->isPureTranslate()) {
1305        x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1306        y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1307        ignoreTransform = true;
1308        filter = GL_NEAREST;
1309    }
1310
1311    setupDraw();
1312    setupDrawWithTexture(true);
1313    if (paint) {
1314        setupDrawAlpha8Color(paint->getColor(), alpha);
1315    }
1316    setupDrawColorFilter();
1317    setupDrawShader();
1318    setupDrawBlending(true, mode);
1319    setupDrawProgram();
1320    setupDrawModelView(x, y, x + texture->width, y + texture->height, ignoreTransform);
1321
1322    setupDrawTexture(texture->id);
1323    texture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1324    texture->setFilter(filter, filter);
1325
1326    setupDrawPureColorUniforms();
1327    setupDrawColorFilterUniforms();
1328    setupDrawShaderUniforms();
1329    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1330
1331    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1332
1333    finishDrawTexture();
1334}
1335
1336void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1337    const float right = left + bitmap->width();
1338    const float bottom = top + bitmap->height();
1339
1340    if (quickReject(left, top, right, bottom)) {
1341        return;
1342    }
1343
1344    glActiveTexture(gTextureUnits[0]);
1345    Texture* texture = mCaches.textureCache.get(bitmap);
1346    if (!texture) return;
1347    const AutoTexture autoCleanup(texture);
1348
1349    if (bitmap->getConfig() == SkBitmap::kA8_Config) {
1350        drawAlphaBitmap(texture, left, top, paint);
1351    } else {
1352        drawTextureRect(left, top, right, bottom, texture, paint);
1353    }
1354}
1355
1356void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
1357    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
1358    const mat4 transform(*matrix);
1359    transform.mapRect(r);
1360
1361    if (quickReject(r.left, r.top, r.right, r.bottom)) {
1362        return;
1363    }
1364
1365    glActiveTexture(gTextureUnits[0]);
1366    Texture* texture = mCaches.textureCache.get(bitmap);
1367    if (!texture) return;
1368    const AutoTexture autoCleanup(texture);
1369
1370    // This could be done in a cheaper way, all we need is pass the matrix
1371    // to the vertex shader. The save/restore is a bit overkill.
1372    save(SkCanvas::kMatrix_SaveFlag);
1373    concatMatrix(matrix);
1374    drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
1375    restore();
1376}
1377
1378void OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
1379        float* vertices, int* colors, SkPaint* paint) {
1380    // TODO: Do a quickReject
1381    if (!vertices || mSnapshot->isIgnored()) {
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
1390    texture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, true);
1391    texture->setFilter(GL_LINEAR, GL_LINEAR, true);
1392
1393    int alpha;
1394    SkXfermode::Mode mode;
1395    getAlphaAndMode(paint, &alpha, &mode);
1396
1397    const uint32_t count = meshWidth * meshHeight * 6;
1398
1399    float left = FLT_MAX;
1400    float top = FLT_MAX;
1401    float right = FLT_MIN;
1402    float bottom = FLT_MIN;
1403
1404#if RENDER_LAYERS_AS_REGIONS
1405    bool hasActiveLayer = hasLayer();
1406#else
1407    bool hasActiveLayer = false;
1408#endif
1409
1410    // TODO: Support the colors array
1411    TextureVertex mesh[count];
1412    TextureVertex* vertex = mesh;
1413    for (int32_t y = 0; y < meshHeight; y++) {
1414        for (int32_t x = 0; x < meshWidth; x++) {
1415            uint32_t i = (y * (meshWidth + 1) + x) * 2;
1416
1417            float u1 = float(x) / meshWidth;
1418            float u2 = float(x + 1) / meshWidth;
1419            float v1 = float(y) / meshHeight;
1420            float v2 = float(y + 1) / meshHeight;
1421
1422            int ax = i + (meshWidth + 1) * 2;
1423            int ay = ax + 1;
1424            int bx = i;
1425            int by = bx + 1;
1426            int cx = i + 2;
1427            int cy = cx + 1;
1428            int dx = i + (meshWidth + 1) * 2 + 2;
1429            int dy = dx + 1;
1430
1431            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1432            TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1);
1433            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1434
1435            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1436            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1437            TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2);
1438
1439#if RENDER_LAYERS_AS_REGIONS
1440            if (hasActiveLayer) {
1441                // TODO: This could be optimized to avoid unnecessary ops
1442                left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
1443                top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
1444                right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
1445                bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
1446            }
1447#endif
1448        }
1449    }
1450
1451#if RENDER_LAYERS_AS_REGIONS
1452    if (hasActiveLayer) {
1453        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1454    }
1455#endif
1456
1457    drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f,
1458            mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0],
1459            GL_TRIANGLES, count, false, false, 0, false, false);
1460}
1461
1462void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
1463         float srcLeft, float srcTop, float srcRight, float srcBottom,
1464         float dstLeft, float dstTop, float dstRight, float dstBottom,
1465         SkPaint* paint) {
1466    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
1467        return;
1468    }
1469
1470    glActiveTexture(gTextureUnits[0]);
1471    Texture* texture = mCaches.textureCache.get(bitmap);
1472    if (!texture) return;
1473    const AutoTexture autoCleanup(texture);
1474    texture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, true);
1475
1476    const float width = texture->width;
1477    const float height = texture->height;
1478
1479    const float u1 = fmax(0.0f, srcLeft / width);
1480    const float v1 = fmax(0.0f, srcTop / height);
1481    const float u2 = fmin(1.0f, srcRight / width);
1482    const float v2 = fmin(1.0f, srcBottom / height);
1483
1484    mCaches.unbindMeshBuffer();
1485    resetDrawTextureTexCoords(u1, v1, u2, v2);
1486
1487    int alpha;
1488    SkXfermode::Mode mode;
1489    getAlphaAndMode(paint, &alpha, &mode);
1490
1491    if (mSnapshot->transform->isPureTranslate()) {
1492        const float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f);
1493        const float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f);
1494
1495        GLenum filter = GL_NEAREST;
1496        if (u1 > 0.0f || u2 < 1.0f || v1 > 0.0f || v2 < 1.0f) {
1497            filter = GL_LINEAR;
1498        }
1499        texture->setFilter(filter, filter, true);
1500
1501        drawTextureMesh(x, y, x + (dstRight - dstLeft), y + (dstBottom - dstTop),
1502                texture->id, alpha / 255.0f, mode, texture->blend,
1503                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1504                GL_TRIANGLE_STRIP, gMeshCount, false, true);
1505    } else {
1506        texture->setFilter(GL_LINEAR, GL_LINEAR, true);
1507
1508        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f,
1509                mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1510                GL_TRIANGLE_STRIP, gMeshCount);
1511    }
1512
1513    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1514}
1515
1516void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
1517        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
1518        float left, float top, float right, float bottom, SkPaint* paint) {
1519    if (quickReject(left, top, right, bottom)) {
1520        return;
1521    }
1522
1523    glActiveTexture(gTextureUnits[0]);
1524    Texture* texture = mCaches.textureCache.get(bitmap);
1525    if (!texture) return;
1526    const AutoTexture autoCleanup(texture);
1527    texture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, true);
1528    texture->setFilter(GL_LINEAR, GL_LINEAR, true);
1529
1530    int alpha;
1531    SkXfermode::Mode mode;
1532    getAlphaAndMode(paint, &alpha, &mode);
1533
1534    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
1535            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
1536
1537    if (mesh && mesh->verticesCount > 0) {
1538        const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1539#if RENDER_LAYERS_AS_REGIONS
1540        // Mark the current layer dirty where we are going to draw the patch
1541        if (hasLayer() && mesh->hasEmptyQuads) {
1542            const float offsetX = left + mSnapshot->transform->getTranslateX();
1543            const float offsetY = top + mSnapshot->transform->getTranslateY();
1544            const size_t count = mesh->quads.size();
1545            for (size_t i = 0; i < count; i++) {
1546                const Rect& bounds = mesh->quads.itemAt(i);
1547                if (pureTranslate) {
1548                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
1549                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
1550                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
1551                } else {
1552                    dirtyLayer(left + bounds.left, top + bounds.top,
1553                            left + bounds.right, top + bounds.bottom, *mSnapshot->transform);
1554                }
1555            }
1556        }
1557#endif
1558
1559        if (pureTranslate) {
1560            const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1561            const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1562
1563            drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
1564                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1565                    GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
1566                    true, !mesh->hasEmptyQuads);
1567        } else {
1568            drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
1569                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1570                    GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
1571                    true, !mesh->hasEmptyQuads);
1572        }
1573    }
1574}
1575
1576/**
1577 * This function uses a similar approach to that of AA lines in the drawLines() function.
1578 * We expand the rectangle by a half pixel in screen space on all sides, and use a fragment
1579 * shader to compute the translucency of the color, determined by whether a given pixel is
1580 * within that boundary region and how far into the region it is.
1581 */
1582void OpenGLRenderer::drawAARect(float left, float top, float right, float bottom,
1583        int color, SkXfermode::Mode mode) {
1584    float inverseScaleX = 1.0f;
1585    float inverseScaleY = 1.0f;
1586    // The quad that we use needs to account for scaling.
1587    if (!mSnapshot->transform->isPureTranslate()) {
1588        Matrix4 *mat = mSnapshot->transform;
1589        float m00 = mat->data[Matrix4::kScaleX];
1590        float m01 = mat->data[Matrix4::kSkewY];
1591        float m02 = mat->data[2];
1592        float m10 = mat->data[Matrix4::kSkewX];
1593        float m11 = mat->data[Matrix4::kScaleX];
1594        float m12 = mat->data[6];
1595        float scaleX = sqrt(m00 * m00 + m01 * m01);
1596        float scaleY = sqrt(m10 * m10 + m11 * m11);
1597        inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0;
1598        inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0;
1599    }
1600
1601    setupDraw();
1602    setupDrawAALine();
1603    setupDrawColor(color);
1604    setupDrawColorFilter();
1605    setupDrawShader();
1606    setupDrawBlending(true, mode);
1607    setupDrawProgram();
1608    setupDrawModelViewIdentity(true);
1609    setupDrawColorUniforms();
1610    setupDrawColorFilterUniforms();
1611    setupDrawShaderIdentityUniforms();
1612
1613    AAVertex rects[4];
1614    AAVertex* aaVertices = &rects[0];
1615    void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset;
1616    void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset;
1617
1618    float boundarySizeX = .5 * inverseScaleX;
1619    float boundarySizeY = .5 * inverseScaleY;
1620
1621    // Adjust the rect by the AA boundary padding
1622    left -= boundarySizeX;
1623    right += boundarySizeX;
1624    top -= boundarySizeY;
1625    bottom += boundarySizeY;
1626
1627    float width = right - left;
1628    float height = bottom - top;
1629
1630    float boundaryWidthProportion = (width != 0) ? (2 * boundarySizeX) / width : 0;
1631    float boundaryHeightProportion = (height != 0) ? (2 * boundarySizeY) / height : 0;
1632    setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, boundaryWidthProportion);
1633    int boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength");
1634    int inverseBoundaryLengthSlot = mCaches.currentProgram->getUniform("inverseBoundaryLength");
1635    glUniform1f(boundaryLengthSlot, boundaryHeightProportion);
1636    glUniform1f(inverseBoundaryLengthSlot, (1 / boundaryHeightProportion));
1637
1638    if (!quickReject(left, top, right, bottom)) {
1639        AAVertex::set(aaVertices++, left, bottom, 1, 1);
1640        AAVertex::set(aaVertices++, left, top, 1, 0);
1641        AAVertex::set(aaVertices++, right, bottom, 0, 1);
1642        AAVertex::set(aaVertices++, right, top, 0, 0);
1643        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1644        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1645    }
1646}
1647
1648/**
1649 * We draw lines as quads (tristrips). Using GL_LINES can be difficult because the rasterization
1650 * rules for those lines produces some unexpected results, and may vary between hardware devices.
1651 * The basics of lines-as-quads is easy; we simply find the normal to the line and position the
1652 * corners of the quads on either side of each line endpoint, separated by the strokeWidth
1653 * of the line. Hairlines are more involved because we need to account for transform scaling
1654 * to end up with a one-pixel-wide line in screen space..
1655 * Anti-aliased lines add another factor to the approach. We use a specialized fragment shader
1656 * in combination with values that we calculate and pass down in this method. The basic approach
1657 * is that the quad we create contains both the core line area plus a bounding area in which
1658 * the translucent/AA pixels are drawn. The values we calculate tell the shader what
1659 * proportion of the width and the length of a given segment is represented by the boundary
1660 * region. The quad ends up being exactly .5 pixel larger in all directions than the non-AA quad.
1661 * The bounding region is actually 1 pixel wide on all sides (half pixel on the outside, half pixel
1662 * on the inside). This ends up giving the result we want, with pixels that are completely
1663 * 'inside' the line area being filled opaquely and the other pixels being filled according to
1664 * how far into the boundary region they are, which is determined by shader interpolation.
1665 */
1666void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
1667    if (mSnapshot->isIgnored()) return;
1668
1669    const bool isAA = paint->isAntiAlias();
1670    // We use half the stroke width here because we're going to position the quad
1671    // corner vertices half of the width away from the line endpoints
1672    float halfStrokeWidth = paint->getStrokeWidth() * 0.5f;
1673    // A stroke width of 0 has a special meaning in Skia:
1674    // it draws a line 1 px wide regardless of current transform
1675    bool isHairLine = paint->getStrokeWidth() == 0.0f;
1676    float inverseScaleX = 1.0f;
1677    float inverseScaleY = 1.0f;
1678    bool scaled = false;
1679    int alpha;
1680    SkXfermode::Mode mode;
1681    int generatedVerticesCount = 0;
1682    int verticesCount = count;
1683    if (count > 4) {
1684        // Polyline: account for extra vertices needed for continuous tri-strip
1685        verticesCount += (count - 4);
1686    }
1687
1688    if (isHairLine || isAA) {
1689        // The quad that we use for AA and hairlines needs to account for scaling. For hairlines
1690        // the line on the screen should always be one pixel wide regardless of scale. For
1691        // AA lines, we only want one pixel of translucent boundary around the quad.
1692        if (!mSnapshot->transform->isPureTranslate()) {
1693            Matrix4 *mat = mSnapshot->transform;
1694            float m00 = mat->data[Matrix4::kScaleX];
1695            float m01 = mat->data[Matrix4::kSkewY];
1696            float m02 = mat->data[2];
1697            float m10 = mat->data[Matrix4::kSkewX];
1698            float m11 = mat->data[Matrix4::kScaleX];
1699            float m12 = mat->data[6];
1700            float scaleX = sqrt(m00*m00 + m01*m01);
1701            float scaleY = sqrt(m10*m10 + m11*m11);
1702            inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0;
1703            inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0;
1704            if (inverseScaleX != 1.0f || inverseScaleY != 1.0f) {
1705                scaled = true;
1706            }
1707        }
1708    }
1709
1710    getAlphaAndMode(paint, &alpha, &mode);
1711    setupDraw();
1712    if (isAA) {
1713        setupDrawAALine();
1714    }
1715    setupDrawColor(paint->getColor(), alpha);
1716    setupDrawColorFilter();
1717    setupDrawShader();
1718    if (isAA) {
1719        setupDrawBlending(true, mode);
1720    } else {
1721        setupDrawBlending(mode);
1722    }
1723    setupDrawProgram();
1724    setupDrawModelViewIdentity(true);
1725    setupDrawColorUniforms();
1726    setupDrawColorFilterUniforms();
1727    setupDrawShaderIdentityUniforms();
1728
1729    if (isHairLine) {
1730        // Set a real stroke width to be used in quad construction
1731        halfStrokeWidth = isAA? 1 : .5;
1732    } else if (isAA && !scaled) {
1733        // Expand boundary to enable AA calculations on the quad border
1734        halfStrokeWidth += .5f;
1735    }
1736    Vertex lines[verticesCount];
1737    Vertex* vertices = &lines[0];
1738    AAVertex wLines[verticesCount];
1739    AAVertex* aaVertices = &wLines[0];
1740    if (!isAA) {
1741        setupDrawVertices(vertices);
1742    } else {
1743        void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset;
1744        void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset;
1745        // innerProportion is the ratio of the inner (non-AA) part of the line to the total
1746        // AA stroke width (the base stroke width expanded by a half pixel on either side).
1747        // This value is used in the fragment shader to determine how to fill fragments.
1748        // We will need to calculate the actual width proportion on each segment for
1749        // scaled non-hairlines, since the boundary proportion may differ per-axis when scaled.
1750        float boundaryWidthProportion = 1 / (2 * halfStrokeWidth);
1751        setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, boundaryWidthProportion);
1752    }
1753
1754    AAVertex* prevAAVertex = NULL;
1755    Vertex* prevVertex = NULL;
1756
1757    int boundaryLengthSlot = -1;
1758    int inverseBoundaryLengthSlot = -1;
1759    int boundaryWidthSlot = -1;
1760    int inverseBoundaryWidthSlot = -1;
1761    for (int i = 0; i < count; i += 4) {
1762        // a = start point, b = end point
1763        vec2 a(points[i], points[i + 1]);
1764        vec2 b(points[i + 2], points[i + 3]);
1765        float length = 0;
1766        float boundaryLengthProportion = 0;
1767        float boundaryWidthProportion = 0;
1768
1769        // Find the normal to the line
1770        vec2 n = (b - a).copyNormalized() * halfStrokeWidth;
1771        if (isHairLine) {
1772            if (isAA) {
1773                float wideningFactor;
1774                if (fabs(n.x) >= fabs(n.y)) {
1775                    wideningFactor = fabs(1.0f / n.x);
1776                } else {
1777                    wideningFactor = fabs(1.0f / n.y);
1778                }
1779                n *= wideningFactor;
1780            }
1781            if (scaled) {
1782                n.x *= inverseScaleX;
1783                n.y *= inverseScaleY;
1784            }
1785        } else if (scaled) {
1786            // Extend n by .5 pixel on each side, post-transform
1787            vec2 extendedN = n.copyNormalized();
1788            extendedN /= 2;
1789            extendedN.x *= inverseScaleX;
1790            extendedN.y *= inverseScaleY;
1791            float extendedNLength = extendedN.length();
1792            // We need to set this value on the shader prior to drawing
1793            boundaryWidthProportion = extendedNLength / (halfStrokeWidth + extendedNLength);
1794            n += extendedN;
1795        }
1796        float x = n.x;
1797        n.x = -n.y;
1798        n.y = x;
1799
1800        // aa lines expand the endpoint vertices to encompass the AA boundary
1801        if (isAA) {
1802            vec2 abVector = (b - a);
1803            length = abVector.length();
1804            abVector.normalize();
1805            if (scaled) {
1806                abVector.x *= inverseScaleX;
1807                abVector.y *= inverseScaleY;
1808                float abLength = abVector.length();
1809                boundaryLengthProportion = abLength / (length + abLength);
1810            } else {
1811                boundaryLengthProportion = .5 / (length + 1);
1812            }
1813            abVector /= 2;
1814            a -= abVector;
1815            b += abVector;
1816        }
1817
1818        // Four corners of the rectangle defining a thick line
1819        vec2 p1 = a - n;
1820        vec2 p2 = a + n;
1821        vec2 p3 = b + n;
1822        vec2 p4 = b - n;
1823
1824
1825        const float left = fmin(p1.x, fmin(p2.x, fmin(p3.x, p4.x)));
1826        const float right = fmax(p1.x, fmax(p2.x, fmax(p3.x, p4.x)));
1827        const float top = fmin(p1.y, fmin(p2.y, fmin(p3.y, p4.y)));
1828        const float bottom = fmax(p1.y, fmax(p2.y, fmax(p3.y, p4.y)));
1829
1830        if (!quickReject(left, top, right, bottom)) {
1831            if (!isAA) {
1832                if (prevVertex != NULL) {
1833                    // Issue two repeat vertices to create degenerate triangles to bridge
1834                    // between the previous line and the new one. This is necessary because
1835                    // we are creating a single triangle_strip which will contain
1836                    // potentially discontinuous line segments.
1837                    Vertex::set(vertices++, prevVertex->position[0], prevVertex->position[1]);
1838                    Vertex::set(vertices++, p1.x, p1.y);
1839                    generatedVerticesCount += 2;
1840                }
1841                Vertex::set(vertices++, p1.x, p1.y);
1842                Vertex::set(vertices++, p2.x, p2.y);
1843                Vertex::set(vertices++, p4.x, p4.y);
1844                Vertex::set(vertices++, p3.x, p3.y);
1845                prevVertex = vertices - 1;
1846                generatedVerticesCount += 4;
1847            } else {
1848                if (!isHairLine && scaled) {
1849                    // Must set width proportions per-segment for scaled non-hairlines to use the
1850                    // correct AA boundary dimensions
1851                    if (boundaryWidthSlot < 0) {
1852                        boundaryWidthSlot =
1853                                mCaches.currentProgram->getUniform("boundaryWidth");
1854                        inverseBoundaryWidthSlot =
1855                                mCaches.currentProgram->getUniform("inverseBoundaryWidth");
1856                    }
1857                    glUniform1f(boundaryWidthSlot, boundaryWidthProportion);
1858                    glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidthProportion));
1859                }
1860                if (boundaryLengthSlot < 0) {
1861                    boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength");
1862                    inverseBoundaryLengthSlot =
1863                            mCaches.currentProgram->getUniform("inverseBoundaryLength");
1864                }
1865                glUniform1f(boundaryLengthSlot, boundaryLengthProportion);
1866                glUniform1f(inverseBoundaryLengthSlot, (1 / boundaryLengthProportion));
1867
1868                if (prevAAVertex != NULL) {
1869                    // Issue two repeat vertices to create degenerate triangles to bridge
1870                    // between the previous line and the new one. This is necessary because
1871                    // we are creating a single triangle_strip which will contain
1872                    // potentially discontinuous line segments.
1873                    AAVertex::set(aaVertices++,prevAAVertex->position[0],
1874                            prevAAVertex->position[1], prevAAVertex->width, prevAAVertex->length);
1875                    AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1);
1876                    generatedVerticesCount += 2;
1877                }
1878                AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1);
1879                AAVertex::set(aaVertices++, p1.x, p1.y, 1, 0);
1880                AAVertex::set(aaVertices++, p3.x, p3.y, 0, 1);
1881                AAVertex::set(aaVertices++, p2.x, p2.y, 0, 0);
1882                prevAAVertex = aaVertices - 1;
1883                generatedVerticesCount += 4;
1884            }
1885            dirtyLayer(a.x == b.x ? left - 1 : left, a.y == b.y ? top - 1 : top,
1886                    a.x == b.x ? right: right, a.y == b.y ? bottom: bottom,
1887                    *mSnapshot->transform);
1888        }
1889    }
1890    if (generatedVerticesCount > 0) {
1891       glDrawArrays(GL_TRIANGLE_STRIP, 0, generatedVerticesCount);
1892    }
1893}
1894
1895void OpenGLRenderer::drawPoints(float* points, int count, SkPaint* paint) {
1896    if (mSnapshot->isIgnored()) return;
1897
1898    // TODO: The paint's cap style defines whether the points are square or circular
1899    // TODO: Handle AA for round points
1900
1901    // A stroke width of 0 has a special meaning in Skia:
1902    // it draws an unscaled 1px point
1903    float strokeWidth = paint->getStrokeWidth();
1904    const bool isHairLine = paint->getStrokeWidth() == 0.0f;
1905    if (isHairLine) {
1906        // Now that we know it's hairline, we can set the effective width, to be used later
1907        strokeWidth = 1.0f;
1908    }
1909    const float halfWidth = strokeWidth / 2;
1910    int alpha;
1911    SkXfermode::Mode mode;
1912    getAlphaAndMode(paint, &alpha, &mode);
1913
1914    int verticesCount = count >> 1;
1915    int generatedVerticesCount = 0;
1916
1917    TextureVertex pointsData[verticesCount];
1918    TextureVertex* vertex = &pointsData[0];
1919
1920    setupDraw();
1921    setupDrawPoint(strokeWidth);
1922    setupDrawColor(paint->getColor(), alpha);
1923    setupDrawColorFilter();
1924    setupDrawShader();
1925    setupDrawBlending(mode);
1926    setupDrawProgram();
1927    setupDrawModelViewIdentity(true);
1928    setupDrawColorUniforms();
1929    setupDrawColorFilterUniforms();
1930    setupDrawPointUniforms();
1931    setupDrawShaderIdentityUniforms();
1932    setupDrawMesh(vertex);
1933
1934    for (int i = 0; i < count; i += 2) {
1935        TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
1936        generatedVerticesCount++;
1937        float left = points[i] - halfWidth;
1938        float right = points[i] + halfWidth;
1939        float top = points[i + 1] - halfWidth;
1940        float bottom = points [i + 1] + halfWidth;
1941        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1942    }
1943
1944    glDrawArrays(GL_POINTS, 0, generatedVerticesCount);
1945}
1946
1947void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
1948    // No need to check against the clip, we fill the clip region
1949    if (mSnapshot->isIgnored()) return;
1950
1951    Rect& clip(*mSnapshot->clipRect);
1952    clip.snapToPixelBoundaries();
1953
1954    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
1955}
1956
1957void OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture, SkPaint* paint) {
1958    if (!texture) return;
1959    const AutoTexture autoCleanup(texture);
1960
1961    const float x = left + texture->left - texture->offset;
1962    const float y = top + texture->top - texture->offset;
1963
1964    drawPathTexture(texture, x, y, paint);
1965}
1966
1967void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
1968        float rx, float ry, SkPaint* paint) {
1969    if (mSnapshot->isIgnored()) return;
1970
1971    glActiveTexture(gTextureUnits[0]);
1972    const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect(
1973            right - left, bottom - top, rx, ry, paint);
1974    drawShape(left, top, texture, paint);
1975}
1976
1977void OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* paint) {
1978    if (mSnapshot->isIgnored()) return;
1979
1980    glActiveTexture(gTextureUnits[0]);
1981    const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, paint);
1982    drawShape(x - radius, y - radius, texture, paint);
1983}
1984
1985void OpenGLRenderer::drawOval(float left, float top, float right, float bottom, SkPaint* paint) {
1986    if (mSnapshot->isIgnored()) return;
1987
1988    glActiveTexture(gTextureUnits[0]);
1989    const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, paint);
1990    drawShape(left, top, texture, paint);
1991}
1992
1993void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
1994        float startAngle, float sweepAngle, bool useCenter, SkPaint* paint) {
1995    if (mSnapshot->isIgnored()) return;
1996
1997    if (fabs(sweepAngle) >= 360.0f) {
1998        drawOval(left, top, right, bottom, paint);
1999        return;
2000    }
2001
2002    glActiveTexture(gTextureUnits[0]);
2003    const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top,
2004            startAngle, sweepAngle, useCenter, paint);
2005    drawShape(left, top, texture, paint);
2006}
2007
2008void OpenGLRenderer::drawRectAsShape(float left, float top, float right, float bottom,
2009        SkPaint* paint) {
2010    if (mSnapshot->isIgnored()) return;
2011
2012    glActiveTexture(gTextureUnits[0]);
2013    const PathTexture* texture = mCaches.rectShapeCache.getRect(right - left, bottom - top, paint);
2014    drawShape(left, top, texture, paint);
2015}
2016
2017void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
2018    if (p->getStyle() != SkPaint::kFill_Style) {
2019        drawRectAsShape(left, top, right, bottom, p);
2020        return;
2021    }
2022
2023    if (quickReject(left, top, right, bottom)) {
2024        return;
2025    }
2026
2027    SkXfermode::Mode mode;
2028    if (!mCaches.extensions.hasFramebufferFetch()) {
2029        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
2030        if (!isMode) {
2031            // Assume SRC_OVER
2032            mode = SkXfermode::kSrcOver_Mode;
2033        }
2034    } else {
2035        mode = getXfermode(p->getXfermode());
2036    }
2037
2038    int color = p->getColor();
2039    if (p->isAntiAlias() && !mSnapshot->transform->isSimple()) {
2040        drawAARect(left, top, right, bottom, color, mode);
2041    } else {
2042        drawColorRect(left, top, right, bottom, color, mode);
2043    }
2044}
2045
2046void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
2047        float x, float y, SkPaint* paint) {
2048    if (text == NULL || count == 0) {
2049        return;
2050    }
2051    if (mSnapshot->isIgnored()) return;
2052
2053    // TODO: We should probably make a copy of the paint instead of modifying
2054    //       it; modifying the paint will change its generationID the first
2055    //       time, which might impact caches. More investigation needed to
2056    //       see if it matters.
2057    //       If we make a copy, then drawTextDecorations() should *not* make
2058    //       its own copy as it does right now.
2059    paint->setAntiAlias(true);
2060#if RENDER_TEXT_AS_GLYPHS
2061    paint->setTextEncoding(SkPaint::kGlyphID_TextEncoding);
2062#endif
2063
2064    float length = -1.0f;
2065    switch (paint->getTextAlign()) {
2066        case SkPaint::kCenter_Align:
2067            length = paint->measureText(text, bytesCount);
2068            x -= length / 2.0f;
2069            break;
2070        case SkPaint::kRight_Align:
2071            length = paint->measureText(text, bytesCount);
2072            x -= length;
2073            break;
2074        default:
2075            break;
2076    }
2077
2078    const float oldX = x;
2079    const float oldY = y;
2080    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
2081    if (pureTranslate) {
2082        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2083        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2084    }
2085
2086    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
2087    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
2088            paint->getTextSize());
2089
2090    int alpha;
2091    SkXfermode::Mode mode;
2092    getAlphaAndMode(paint, &alpha, &mode);
2093
2094    if (mHasShadow) {
2095        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2096        const ShadowTexture* shadow = mCaches.dropShadowCache.get(
2097                paint, text, bytesCount, count, mShadowRadius);
2098        const AutoTexture autoCleanup(shadow);
2099
2100        const float sx = oldX - shadow->left + mShadowDx;
2101        const float sy = oldY - shadow->top + mShadowDy;
2102
2103        const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
2104        int shadowColor = mShadowColor;
2105        if (mShader) {
2106            shadowColor = 0xffffffff;
2107        }
2108
2109        glActiveTexture(gTextureUnits[0]);
2110        setupDraw();
2111        setupDrawWithTexture(true);
2112        setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
2113        setupDrawColorFilter();
2114        setupDrawShader();
2115        setupDrawBlending(true, mode);
2116        setupDrawProgram();
2117        setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height);
2118        setupDrawTexture(shadow->id);
2119        setupDrawPureColorUniforms();
2120        setupDrawColorFilterUniforms();
2121        setupDrawShaderUniforms();
2122        setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2123
2124        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2125
2126        finishDrawTexture();
2127    }
2128
2129    if (paint->getAlpha() == 0 && paint->getXfermode() == NULL) {
2130        return;
2131    }
2132
2133    // Pick the appropriate texture filtering
2134    bool linearFilter = mSnapshot->transform->changesBounds();
2135    if (pureTranslate && !linearFilter) {
2136        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2137    }
2138
2139    glActiveTexture(gTextureUnits[0]);
2140    setupDraw();
2141    setupDrawDirtyRegionsDisabled();
2142    setupDrawWithTexture(true);
2143    setupDrawAlpha8Color(paint->getColor(), alpha);
2144    setupDrawColorFilter();
2145    setupDrawShader();
2146    setupDrawBlending(true, mode);
2147    setupDrawProgram();
2148    setupDrawModelView(x, y, x, y, pureTranslate, true);
2149    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2150    setupDrawPureColorUniforms();
2151    setupDrawColorFilterUniforms();
2152    setupDrawShaderUniforms(pureTranslate);
2153
2154    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
2155    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2156
2157#if RENDER_LAYERS_AS_REGIONS
2158    bool hasActiveLayer = hasLayer();
2159#else
2160    bool hasActiveLayer = false;
2161#endif
2162    mCaches.unbindMeshBuffer();
2163
2164    // Tell font renderer the locations of position and texture coord
2165    // attributes so it can bind its data properly
2166    int positionSlot = mCaches.currentProgram->position;
2167    fontRenderer.setAttributeBindingSlots(positionSlot, mTexCoordsSlot);
2168    if (fontRenderer.renderText(paint, clip, text, 0, bytesCount, count, x, y,
2169            hasActiveLayer ? &bounds : NULL)) {
2170#if RENDER_LAYERS_AS_REGIONS
2171        if (hasActiveLayer) {
2172            if (!pureTranslate) {
2173                mSnapshot->transform->mapRect(bounds);
2174            }
2175            dirtyLayerUnchecked(bounds, getRegion());
2176        }
2177#endif
2178    }
2179
2180    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
2181    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
2182
2183    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
2184}
2185
2186void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
2187    if (mSnapshot->isIgnored()) return;
2188
2189    glActiveTexture(gTextureUnits[0]);
2190
2191    const PathTexture* texture = mCaches.pathCache.get(path, paint);
2192    if (!texture) return;
2193    const AutoTexture autoCleanup(texture);
2194
2195    const float x = texture->left - texture->offset;
2196    const float y = texture->top - texture->offset;
2197
2198    drawPathTexture(texture, x, y, paint);
2199}
2200
2201void OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) {
2202    if (!layer || quickReject(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight())) {
2203        return;
2204    }
2205
2206    glActiveTexture(gTextureUnits[0]);
2207
2208    int alpha;
2209    SkXfermode::Mode mode;
2210    getAlphaAndMode(paint, &alpha, &mode);
2211
2212    layer->setAlpha(alpha, mode);
2213
2214#if RENDER_LAYERS_AS_REGIONS
2215    if (!layer->region.isEmpty()) {
2216        if (layer->region.isRect()) {
2217            composeLayerRect(layer, layer->regionRect);
2218        } else if (layer->mesh) {
2219            const float a = alpha / 255.0f;
2220            const Rect& rect = layer->layer;
2221
2222            setupDraw();
2223            setupDrawWithTexture();
2224            setupDrawColor(a, a, a, a);
2225            setupDrawColorFilter();
2226            setupDrawBlending(layer->isBlend() || a < 1.0f, layer->getMode(), false);
2227            setupDrawProgram();
2228            setupDrawPureColorUniforms();
2229            setupDrawColorFilterUniforms();
2230            setupDrawTexture(layer->getTexture());
2231            if (mSnapshot->transform->isPureTranslate()) {
2232                x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2233                y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2234
2235                layer->setFilter(GL_NEAREST, GL_NEAREST);
2236                setupDrawModelViewTranslate(x, y,
2237                        x + layer->layer.getWidth(), y + layer->layer.getHeight(), true);
2238            } else {
2239                layer->setFilter(GL_LINEAR, GL_LINEAR);
2240                setupDrawModelViewTranslate(x, y,
2241                        x + layer->layer.getWidth(), y + layer->layer.getHeight());
2242            }
2243            setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]);
2244
2245            glDrawElements(GL_TRIANGLES, layer->meshElementCount,
2246                    GL_UNSIGNED_SHORT, layer->meshIndices);
2247
2248            finishDrawTexture();
2249
2250#if DEBUG_LAYERS_AS_REGIONS
2251            drawRegionRects(layer->region);
2252#endif
2253        }
2254    }
2255#else
2256    const Rect r(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight());
2257    composeLayerRect(layer, r);
2258#endif
2259}
2260
2261///////////////////////////////////////////////////////////////////////////////
2262// Shaders
2263///////////////////////////////////////////////////////////////////////////////
2264
2265void OpenGLRenderer::resetShader() {
2266    mShader = NULL;
2267}
2268
2269void OpenGLRenderer::setupShader(SkiaShader* shader) {
2270    mShader = shader;
2271    if (mShader) {
2272        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
2273    }
2274}
2275
2276///////////////////////////////////////////////////////////////////////////////
2277// Color filters
2278///////////////////////////////////////////////////////////////////////////////
2279
2280void OpenGLRenderer::resetColorFilter() {
2281    mColorFilter = NULL;
2282}
2283
2284void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
2285    mColorFilter = filter;
2286}
2287
2288///////////////////////////////////////////////////////////////////////////////
2289// Drop shadow
2290///////////////////////////////////////////////////////////////////////////////
2291
2292void OpenGLRenderer::resetShadow() {
2293    mHasShadow = false;
2294}
2295
2296void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
2297    mHasShadow = true;
2298    mShadowRadius = radius;
2299    mShadowDx = dx;
2300    mShadowDy = dy;
2301    mShadowColor = color;
2302}
2303
2304///////////////////////////////////////////////////////////////////////////////
2305// Drawing implementation
2306///////////////////////////////////////////////////////////////////////////////
2307
2308void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
2309        float x, float y, SkPaint* paint) {
2310    if (quickReject(x, y, x + texture->width, y + texture->height)) {
2311        return;
2312    }
2313
2314    int alpha;
2315    SkXfermode::Mode mode;
2316    getAlphaAndMode(paint, &alpha, &mode);
2317
2318    setupDraw();
2319    setupDrawWithTexture(true);
2320    setupDrawAlpha8Color(paint->getColor(), alpha);
2321    setupDrawColorFilter();
2322    setupDrawShader();
2323    setupDrawBlending(true, mode);
2324    setupDrawProgram();
2325    setupDrawModelView(x, y, x + texture->width, y + texture->height);
2326    setupDrawTexture(texture->id);
2327    setupDrawPureColorUniforms();
2328    setupDrawColorFilterUniforms();
2329    setupDrawShaderUniforms();
2330    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2331
2332    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2333
2334    finishDrawTexture();
2335}
2336
2337// Same values used by Skia
2338#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
2339#define kStdUnderline_Offset    (1.0f / 9.0f)
2340#define kStdUnderline_Thickness (1.0f / 18.0f)
2341
2342void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
2343        float x, float y, SkPaint* paint) {
2344    // Handle underline and strike-through
2345    uint32_t flags = paint->getFlags();
2346    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
2347        SkPaint paintCopy(*paint);
2348        float underlineWidth = length;
2349        // If length is > 0.0f, we already measured the text for the text alignment
2350        if (length <= 0.0f) {
2351            underlineWidth = paintCopy.measureText(text, bytesCount);
2352        }
2353
2354        float offsetX = 0;
2355        switch (paintCopy.getTextAlign()) {
2356            case SkPaint::kCenter_Align:
2357                offsetX = underlineWidth * 0.5f;
2358                break;
2359            case SkPaint::kRight_Align:
2360                offsetX = underlineWidth;
2361                break;
2362            default:
2363                break;
2364        }
2365
2366        if (underlineWidth > 0.0f) {
2367            const float textSize = paintCopy.getTextSize();
2368            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
2369
2370            const float left = x - offsetX;
2371            float top = 0.0f;
2372
2373            int linesCount = 0;
2374            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
2375            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
2376
2377            const int pointsCount = 4 * linesCount;
2378            float points[pointsCount];
2379            int currentPoint = 0;
2380
2381            if (flags & SkPaint::kUnderlineText_Flag) {
2382                top = y + textSize * kStdUnderline_Offset;
2383                points[currentPoint++] = left;
2384                points[currentPoint++] = top;
2385                points[currentPoint++] = left + underlineWidth;
2386                points[currentPoint++] = top;
2387            }
2388
2389            if (flags & SkPaint::kStrikeThruText_Flag) {
2390                top = y + textSize * kStdStrikeThru_Offset;
2391                points[currentPoint++] = left;
2392                points[currentPoint++] = top;
2393                points[currentPoint++] = left + underlineWidth;
2394                points[currentPoint++] = top;
2395            }
2396
2397            paintCopy.setStrokeWidth(strokeWidth);
2398
2399            drawLines(&points[0], pointsCount, &paintCopy);
2400        }
2401    }
2402}
2403
2404void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
2405        int color, SkXfermode::Mode mode, bool ignoreTransform) {
2406    // If a shader is set, preserve only the alpha
2407    if (mShader) {
2408        color |= 0x00ffffff;
2409    }
2410
2411    setupDraw();
2412    setupDrawColor(color);
2413    setupDrawShader();
2414    setupDrawColorFilter();
2415    setupDrawBlending(mode);
2416    setupDrawProgram();
2417    setupDrawModelView(left, top, right, bottom, ignoreTransform);
2418    setupDrawColorUniforms();
2419    setupDrawShaderUniforms(ignoreTransform);
2420    setupDrawColorFilterUniforms();
2421    setupDrawSimpleMesh();
2422
2423    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2424}
2425
2426void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
2427        Texture* texture, SkPaint* paint) {
2428    int alpha;
2429    SkXfermode::Mode mode;
2430    getAlphaAndMode(paint, &alpha, &mode);
2431
2432    texture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, true);
2433
2434    if (mSnapshot->transform->isPureTranslate()) {
2435        const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
2436        const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
2437
2438        texture->setFilter(GL_NEAREST, GL_NEAREST, true);
2439        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
2440                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
2441                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
2442    } else {
2443        texture->setFilter(GL_LINEAR, GL_LINEAR, true);
2444        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
2445                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
2446                GL_TRIANGLE_STRIP, gMeshCount);
2447    }
2448}
2449
2450void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
2451        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
2452    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
2453            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
2454}
2455
2456void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
2457        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
2458        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
2459        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
2460
2461    setupDraw();
2462    setupDrawWithTexture();
2463    setupDrawColor(alpha, alpha, alpha, alpha);
2464    setupDrawColorFilter();
2465    setupDrawBlending(blend, mode, swapSrcDst);
2466    setupDrawProgram();
2467    if (!dirty) {
2468        setupDrawDirtyRegionsDisabled();
2469    }
2470    if (!ignoreScale) {
2471        setupDrawModelView(left, top, right, bottom, ignoreTransform);
2472    } else {
2473        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
2474    }
2475    setupDrawPureColorUniforms();
2476    setupDrawColorFilterUniforms();
2477    setupDrawTexture(texture);
2478    setupDrawMesh(vertices, texCoords, vbo);
2479
2480    glDrawArrays(drawMode, 0, elementsCount);
2481
2482    finishDrawTexture();
2483}
2484
2485void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
2486        ProgramDescription& description, bool swapSrcDst) {
2487    blend = blend || mode != SkXfermode::kSrcOver_Mode;
2488    if (blend) {
2489        if (mode < SkXfermode::kPlus_Mode) {
2490            if (!mCaches.blend) {
2491                glEnable(GL_BLEND);
2492            }
2493
2494            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
2495            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
2496
2497            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
2498                glBlendFunc(sourceMode, destMode);
2499                mCaches.lastSrcMode = sourceMode;
2500                mCaches.lastDstMode = destMode;
2501            }
2502        } else {
2503            // These blend modes are not supported by OpenGL directly and have
2504            // to be implemented using shaders. Since the shader will perform
2505            // the blending, turn blending off here
2506            if (mCaches.extensions.hasFramebufferFetch()) {
2507                description.framebufferMode = mode;
2508                description.swapSrcDst = swapSrcDst;
2509            }
2510
2511            if (mCaches.blend) {
2512                glDisable(GL_BLEND);
2513            }
2514            blend = false;
2515        }
2516    } else if (mCaches.blend) {
2517        glDisable(GL_BLEND);
2518    }
2519    mCaches.blend = blend;
2520}
2521
2522bool OpenGLRenderer::useProgram(Program* program) {
2523    if (!program->isInUse()) {
2524        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
2525        program->use();
2526        mCaches.currentProgram = program;
2527        return false;
2528    }
2529    return true;
2530}
2531
2532void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
2533    TextureVertex* v = &mMeshVertices[0];
2534    TextureVertex::setUV(v++, u1, v1);
2535    TextureVertex::setUV(v++, u2, v1);
2536    TextureVertex::setUV(v++, u1, v2);
2537    TextureVertex::setUV(v++, u2, v2);
2538}
2539
2540void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
2541    if (paint) {
2542        if (!mCaches.extensions.hasFramebufferFetch()) {
2543            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
2544            if (!isMode) {
2545                // Assume SRC_OVER
2546                *mode = SkXfermode::kSrcOver_Mode;
2547            }
2548        } else {
2549            *mode = getXfermode(paint->getXfermode());
2550        }
2551
2552        // Skia draws using the color's alpha channel if < 255
2553        // Otherwise, it uses the paint's alpha
2554        int color = paint->getColor();
2555        *alpha = (color >> 24) & 0xFF;
2556        if (*alpha == 255) {
2557            *alpha = paint->getAlpha();
2558        }
2559    } else {
2560        *mode = SkXfermode::kSrcOver_Mode;
2561        *alpha = 255;
2562    }
2563}
2564
2565SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
2566    SkXfermode::Mode resultMode;
2567    if (!SkXfermode::AsMode(mode, &resultMode)) {
2568        resultMode = SkXfermode::kSrcOver_Mode;
2569    }
2570    return resultMode;
2571}
2572
2573}; // namespace uirenderer
2574}; // namespace android
2575