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