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