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