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