OpenGLRenderer.cpp revision 054dc1840941665e32036f9523df51720ad069c8
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 "OpenGLRenderer.h"
30
31namespace android {
32namespace uirenderer {
33
34///////////////////////////////////////////////////////////////////////////////
35// Defines
36///////////////////////////////////////////////////////////////////////////////
37
38#define REQUIRED_TEXTURE_UNITS_COUNT 3
39
40// Generates simple and textured vertices
41#define FV(x, y, u, v) { { x, y }, { u, v } }
42
43#define RAD_TO_DEG (180.0f / 3.14159265f)
44#define MIN_ANGLE 0.001f
45
46// TODO: This should be set in properties
47#define ALPHA_THRESHOLD (0x7f / PANEL_BIT_DEPTH)
48
49///////////////////////////////////////////////////////////////////////////////
50// Globals
51///////////////////////////////////////////////////////////////////////////////
52
53// This array is never used directly but used as a memcpy source in the
54// OpenGLRenderer constructor
55static const TextureVertex gMeshVertices[] = {
56        FV(0.0f, 0.0f, 0.0f, 0.0f),
57        FV(1.0f, 0.0f, 1.0f, 0.0f),
58        FV(0.0f, 1.0f, 0.0f, 1.0f),
59        FV(1.0f, 1.0f, 1.0f, 1.0f)
60};
61static const GLsizei gMeshStride = sizeof(TextureVertex);
62static const GLsizei gMeshCount = 4;
63
64/**
65 * Structure mapping Skia xfermodes to OpenGL blending factors.
66 */
67struct Blender {
68    SkXfermode::Mode mode;
69    GLenum src;
70    GLenum dst;
71}; // struct Blender
72
73// In this array, the index of each Blender equals the value of the first
74// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
75static const Blender gBlends[] = {
76        { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
77        { SkXfermode::kSrc_Mode,     GL_ONE,                  GL_ZERO },
78        { SkXfermode::kDst_Mode,     GL_ZERO,                 GL_ONE },
79        { SkXfermode::kSrcOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
80        { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
81        { SkXfermode::kSrcIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
82        { SkXfermode::kDstIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
83        { SkXfermode::kSrcOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
84        { SkXfermode::kDstOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
85        { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
86        { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
87        { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
88};
89
90// This array contains the swapped version of each SkXfermode. For instance
91// this array's SrcOver blending mode is actually DstOver. You can refer to
92// createLayer() for more information on the purpose of this array.
93static const Blender gBlendsSwap[] = {
94        { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
95        { SkXfermode::kSrc_Mode,     GL_ZERO,                 GL_ONE },
96        { SkXfermode::kDst_Mode,     GL_ONE,                  GL_ZERO },
97        { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
98        { SkXfermode::kDstOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
99        { SkXfermode::kSrcIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
100        { SkXfermode::kDstIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
101        { SkXfermode::kSrcOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
102        { SkXfermode::kDstOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
103        { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
104        { SkXfermode::kDstATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
105        { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
106};
107
108static const GLenum gTextureUnits[] = {
109        GL_TEXTURE0,
110        GL_TEXTURE1,
111        GL_TEXTURE2
112};
113
114///////////////////////////////////////////////////////////////////////////////
115// Constructors/destructor
116///////////////////////////////////////////////////////////////////////////////
117
118OpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) {
119    mShader = NULL;
120    mColorFilter = NULL;
121    mHasShadow = false;
122
123    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
124
125    mFirstSnapshot = new Snapshot;
126
127    GLint maxTextureUnits;
128    glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTextureUnits);
129    if (maxTextureUnits < REQUIRED_TEXTURE_UNITS_COUNT) {
130        LOGW("At least %d texture units are required!", REQUIRED_TEXTURE_UNITS_COUNT);
131    }
132
133    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
134}
135
136OpenGLRenderer::~OpenGLRenderer() {
137    // The context has already been destroyed at this point, do not call
138    // GL APIs. All GL state should be kept in Caches.h
139}
140
141///////////////////////////////////////////////////////////////////////////////
142// Setup
143///////////////////////////////////////////////////////////////////////////////
144
145void OpenGLRenderer::setViewport(int width, int height) {
146    glViewport(0, 0, width, height);
147    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
148
149    mWidth = width;
150    mHeight = height;
151
152    mFirstSnapshot->height = height;
153    mFirstSnapshot->viewport.set(0, 0, width, height);
154}
155
156void OpenGLRenderer::prepare(bool opaque) {
157    mSnapshot = new Snapshot(mFirstSnapshot,
158            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
159    mSaveCount = 1;
160
161    glViewport(0, 0, mWidth, mHeight);
162
163    glDisable(GL_DITHER);
164    glDisable(GL_SCISSOR_TEST);
165
166    if (!opaque) {
167        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
168        glClear(GL_COLOR_BUFFER_BIT);
169    }
170
171    glEnable(GL_SCISSOR_TEST);
172    glScissor(0, 0, mWidth, mHeight);
173
174    mSnapshot->setClip(0.0f, 0.0f, mWidth, mHeight);
175}
176
177void OpenGLRenderer::finish() {
178#if DEBUG_OPENGL
179    GLenum status = GL_NO_ERROR;
180    while ((status = glGetError()) != GL_NO_ERROR) {
181        LOGD("GL error from OpenGLRenderer: 0x%x", status);
182    }
183#endif
184}
185
186void OpenGLRenderer::acquireContext() {
187    if (mCaches.currentProgram) {
188        if (mCaches.currentProgram->isInUse()) {
189            mCaches.currentProgram->remove();
190            mCaches.currentProgram = NULL;
191        }
192    }
193}
194
195void OpenGLRenderer::releaseContext() {
196    glViewport(0, 0, mSnapshot->viewport.getWidth(), mSnapshot->viewport.getHeight());
197
198    glEnable(GL_SCISSOR_TEST);
199    setScissorFromClip();
200
201    glDisable(GL_DITHER);
202
203    glBindFramebuffer(GL_FRAMEBUFFER, 0);
204
205    if (mCaches.blend) {
206        glEnable(GL_BLEND);
207        glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
208        glBlendEquation(GL_FUNC_ADD);
209    } else {
210        glDisable(GL_BLEND);
211    }
212}
213
214///////////////////////////////////////////////////////////////////////////////
215// State management
216///////////////////////////////////////////////////////////////////////////////
217
218int OpenGLRenderer::getSaveCount() const {
219    return mSaveCount;
220}
221
222int OpenGLRenderer::save(int flags) {
223    return saveSnapshot(flags);
224}
225
226void OpenGLRenderer::restore() {
227    if (mSaveCount > 1) {
228        restoreSnapshot();
229    }
230}
231
232void OpenGLRenderer::restoreToCount(int saveCount) {
233    if (saveCount < 1) saveCount = 1;
234
235    while (mSaveCount > saveCount) {
236        restoreSnapshot();
237    }
238}
239
240int OpenGLRenderer::saveSnapshot(int flags) {
241    mSnapshot = new Snapshot(mSnapshot, flags);
242    return mSaveCount++;
243}
244
245bool OpenGLRenderer::restoreSnapshot() {
246    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
247    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
248    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
249
250    sp<Snapshot> current = mSnapshot;
251    sp<Snapshot> previous = mSnapshot->previous;
252
253    if (restoreOrtho) {
254        Rect& r = previous->viewport;
255        glViewport(r.left, r.top, r.right, r.bottom);
256        mOrthoMatrix.load(current->orthoMatrix);
257    }
258
259    mSaveCount--;
260    mSnapshot = previous;
261
262    if (restoreLayer) {
263        composeLayer(current, previous);
264    }
265
266    if (restoreClip) {
267        setScissorFromClip();
268    }
269
270    return restoreClip;
271}
272
273///////////////////////////////////////////////////////////////////////////////
274// Layers
275///////////////////////////////////////////////////////////////////////////////
276
277int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
278        const SkPaint* p, int flags) {
279    const GLuint previousFbo = mSnapshot->fbo;
280    const int count = saveSnapshot(flags);
281
282    int alpha = 255;
283    SkXfermode::Mode mode;
284
285    if (p) {
286        alpha = p->getAlpha();
287        if (!mExtensions.hasFramebufferFetch()) {
288            const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
289            if (!isMode) {
290                // Assume SRC_OVER
291                mode = SkXfermode::kSrcOver_Mode;
292            }
293        } else {
294            mode = getXfermode(p->getXfermode());
295        }
296    } else {
297        mode = SkXfermode::kSrcOver_Mode;
298    }
299
300    if (!mSnapshot->previous->invisible) {
301        createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags, previousFbo);
302    }
303
304    return count;
305}
306
307int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
308        int alpha, int flags) {
309    if (alpha == 0xff) {
310        return saveLayer(left, top, right, bottom, NULL, flags);
311    } else {
312        SkPaint paint;
313        paint.setAlpha(alpha);
314        return saveLayer(left, top, right, bottom, &paint, flags);
315    }
316}
317
318/**
319 * Layers are viewed by Skia are slightly different than layers in image editing
320 * programs (for instance.) When a layer is created, previously created layers
321 * and the frame buffer still receive every drawing command. For instance, if a
322 * layer is created and a shape intersecting the bounds of the layers and the
323 * framebuffer is draw, the shape will be drawn on both (unless the layer was
324 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
325 *
326 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
327 * texture. Unfortunately, this is inefficient as it requires every primitive to
328 * be drawn n + 1 times, where n is the number of active layers. In practice this
329 * means, for every primitive:
330 *   - Switch active frame buffer
331 *   - Change viewport, clip and projection matrix
332 *   - Issue the drawing
333 *
334 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
335 * To avoid this, layers are implemented in a different way here, at least in the
336 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
337 * is set. When this flag is set we can redirect all drawing operations into a
338 * single FBO.
339 *
340 * This implementation relies on the frame buffer being at least RGBA 8888. When
341 * a layer is created, only a texture is created, not an FBO. The content of the
342 * frame buffer contained within the layer's bounds is copied into this texture
343 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
344 * buffer and drawing continues as normal. This technique therefore treats the
345 * frame buffer as a scratch buffer for the layers.
346 *
347 * To compose the layers back onto the frame buffer, each layer texture
348 * (containing the original frame buffer data) is drawn as a simple quad over
349 * the frame buffer. The trick is that the quad is set as the composition
350 * destination in the blending equation, and the frame buffer becomes the source
351 * of the composition.
352 *
353 * Drawing layers with an alpha value requires an extra step before composition.
354 * An empty quad is drawn over the layer's region in the frame buffer. This quad
355 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
356 * quad is used to multiply the colors in the frame buffer. This is achieved by
357 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
358 * GL_ZERO, GL_SRC_ALPHA.
359 *
360 * Because glCopyTexImage2D() can be slow, an alternative implementation might
361 * be use to draw a single clipped layer. The implementation described above
362 * is correct in every case.
363 *
364 * (1) The frame buffer is actually not cleared right away. To allow the GPU
365 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
366 *     buffer is left untouched until the first drawing operation. Only when
367 *     something actually gets drawn are the layers regions cleared.
368 */
369bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
370        float right, float bottom, int alpha, SkXfermode::Mode mode,
371        int flags, GLuint previousFbo) {
372    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
373    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
374
375    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
376
377    // Window coordinates of the layer
378    Rect bounds(left, top, right, bottom);
379    if (!fboLayer) {
380        mSnapshot->transform->mapRect(bounds);
381        // Layers only make sense if they are in the framebuffer's bounds
382        bounds.intersect(*mSnapshot->clipRect);
383        bounds.snapToPixelBoundaries();
384    }
385
386    if (bounds.isEmpty() || bounds.getWidth() > mMaxTextureSize ||
387            bounds.getHeight() > mMaxTextureSize) {
388        snapshot->invisible = true;
389    } else {
390        // TODO: Should take the mode into account
391        snapshot->invisible = snapshot->previous->invisible ||
392                (alpha <= ALPHA_THRESHOLD && fboLayer);
393    }
394
395    // Bail out if we won't draw in this snapshot
396    if (snapshot->invisible) {
397        return false;
398    }
399
400    glActiveTexture(GL_TEXTURE0);
401
402    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
403    if (!layer) {
404        return false;
405    }
406
407    layer->mode = mode;
408    layer->alpha = alpha;
409    layer->layer.set(bounds);
410    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->height),
411            bounds.getWidth() / float(layer->width), 0.0f);
412
413    // Save the layer in the snapshot
414    snapshot->flags |= Snapshot::kFlagIsLayer;
415    snapshot->layer = layer;
416
417    if (fboLayer) {
418        layer->fbo = mCaches.fboCache.get();
419
420        snapshot->flags |= Snapshot::kFlagIsFboLayer;
421        snapshot->fbo = layer->fbo;
422        snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
423        snapshot->resetClip(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
424        snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
425        snapshot->height = bounds.getHeight();
426        snapshot->flags |= Snapshot::kFlagDirtyOrtho;
427        snapshot->orthoMatrix.load(mOrthoMatrix);
428
429        // Bind texture to FBO
430        glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
431        glBindTexture(GL_TEXTURE_2D, layer->texture);
432
433        // Initialize the texture if needed
434        if (layer->empty) {
435            layer->empty = false;
436            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->width, layer->height, 0,
437                    GL_RGBA, GL_UNSIGNED_BYTE, NULL);
438        }
439
440        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
441                layer->texture, 0);
442
443#if DEBUG_LAYERS
444        GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
445        if (status != GL_FRAMEBUFFER_COMPLETE) {
446            LOGE("Framebuffer incomplete (GL error code 0x%x)", status);
447
448            glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
449            glDeleteTextures(1, &layer->texture);
450            mCaches.fboCache.put(layer->fbo);
451
452            delete layer;
453
454            return false;
455        }
456#endif
457
458        // Clear the FBO
459        glScissor(0.0f, 0.0f, bounds.getWidth() + 1.0f, bounds.getHeight() + 1.0f);
460        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
461        glClear(GL_COLOR_BUFFER_BIT);
462
463        setScissorFromClip();
464
465        // Change the ortho projection
466        glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
467        mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
468    } else {
469        // Copy the framebuffer into the layer
470        glBindTexture(GL_TEXTURE_2D, layer->texture);
471
472         if (layer->empty) {
473             glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left, mHeight - bounds.bottom,
474                     layer->width, layer->height, 0);
475             layer->empty = false;
476         } else {
477             glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left, mHeight - bounds.bottom,
478                     bounds.getWidth(), bounds.getHeight());
479          }
480
481        // Enqueue the buffer coordinates to clear the corresponding region later
482        mLayers.push(new Rect(bounds));
483    }
484
485    return true;
486}
487
488/**
489 * Read the documentation of createLayer() before doing anything in this method.
490 */
491void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
492    if (!current->layer) {
493        LOGE("Attempting to compose a layer that does not exist");
494        return;
495    }
496
497    const bool fboLayer = current->flags & SkCanvas::kClipToLayer_SaveFlag;
498
499    if (fboLayer) {
500        // Unbind current FBO and restore previous one
501        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
502    }
503
504    // Restore the clip from the previous snapshot
505    const Rect& clip = *previous->clipRect;
506    glScissor(clip.left, previous->height - clip.bottom, clip.getWidth(), clip.getHeight());
507
508    Layer* layer = current->layer;
509    const Rect& rect = layer->layer;
510
511    if (!fboLayer && layer->alpha < 255) {
512        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
513                layer->alpha << 24, SkXfermode::kDstIn_Mode, true);
514    }
515
516    const Rect& texCoords = layer->texCoords;
517    resetDrawTextureTexCoords(texCoords.left, texCoords.top, texCoords.right, texCoords.bottom);
518
519    if (fboLayer) {
520        drawTextureRect(rect.left, rect.top, rect.right, rect.bottom,
521                layer->texture, layer->alpha / 255.0f, layer->mode, layer->blend);
522    } else {
523        drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
524                1.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
525                &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount, true, true);
526    }
527
528    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
529
530    if (fboLayer) {
531        // Detach the texture from the FBO
532        glBindFramebuffer(GL_FRAMEBUFFER, current->fbo);
533        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
534        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
535
536        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
537        mCaches.fboCache.put(current->fbo);
538    }
539
540    // Failing to add the layer to the cache should happen only if the layer is too large
541    if (!mCaches.layerCache.put(layer)) {
542        LAYER_LOGD("Deleting layer");
543        glDeleteTextures(1, &layer->texture);
544        delete layer;
545    }
546}
547
548void OpenGLRenderer::clearLayerRegions() {
549    if (mLayers.size() == 0 || mSnapshot->invisible) return;
550
551    for (uint32_t i = 0; i < mLayers.size(); i++) {
552        Rect* bounds = mLayers.itemAt(i);
553
554        // Clear the framebuffer where the layer will draw
555        glScissor(bounds->left, mSnapshot->height - bounds->bottom,
556                bounds->getWidth(), bounds->getHeight());
557        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
558        glClear(GL_COLOR_BUFFER_BIT);
559
560        delete bounds;
561    }
562    mLayers.clear();
563
564    // Restore the clip
565    setScissorFromClip();
566}
567
568///////////////////////////////////////////////////////////////////////////////
569// Transforms
570///////////////////////////////////////////////////////////////////////////////
571
572void OpenGLRenderer::translate(float dx, float dy) {
573    mSnapshot->transform->translate(dx, dy, 0.0f);
574}
575
576void OpenGLRenderer::rotate(float degrees) {
577    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
578}
579
580void OpenGLRenderer::scale(float sx, float sy) {
581    mSnapshot->transform->scale(sx, sy, 1.0f);
582}
583
584void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
585    mSnapshot->transform->load(*matrix);
586}
587
588const float* OpenGLRenderer::getMatrix() const {
589    if (mSnapshot->fbo != 0) {
590        return &mSnapshot->transform->data[0];
591    }
592    return &mIdentity.data[0];
593}
594
595void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
596    mSnapshot->transform->copyTo(*matrix);
597}
598
599void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
600    SkMatrix transform;
601    mSnapshot->transform->copyTo(transform);
602    transform.preConcat(*matrix);
603    mSnapshot->transform->load(transform);
604}
605
606///////////////////////////////////////////////////////////////////////////////
607// Clipping
608///////////////////////////////////////////////////////////////////////////////
609
610void OpenGLRenderer::setScissorFromClip() {
611    Rect clip(*mSnapshot->clipRect);
612    clip.snapToPixelBoundaries();
613    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
614}
615
616const Rect& OpenGLRenderer::getClipBounds() {
617    return mSnapshot->getLocalClip();
618}
619
620bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
621    if (mSnapshot->invisible) {
622        return true;
623    }
624
625    Rect r(left, top, right, bottom);
626    mSnapshot->transform->mapRect(r);
627    r.snapToPixelBoundaries();
628
629    Rect clipRect(*mSnapshot->clipRect);
630    clipRect.snapToPixelBoundaries();
631
632    return !clipRect.intersects(r);
633}
634
635bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
636    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
637    if (clipped) {
638        setScissorFromClip();
639    }
640    return !mSnapshot->clipRect->isEmpty();
641}
642
643///////////////////////////////////////////////////////////////////////////////
644// Drawing
645///////////////////////////////////////////////////////////////////////////////
646
647void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, const SkPaint* paint) {
648    const float right = left + bitmap->width();
649    const float bottom = top + bitmap->height();
650
651    if (quickReject(left, top, right, bottom)) {
652        return;
653    }
654
655    glActiveTexture(GL_TEXTURE0);
656    const Texture* texture = mCaches.textureCache.get(bitmap);
657    if (!texture) return;
658    const AutoTexture autoCleanup(texture);
659
660    drawTextureRect(left, top, right, bottom, texture, paint);
661}
662
663void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, const SkMatrix* matrix, const SkPaint* paint) {
664    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
665    const mat4 transform(*matrix);
666    transform.mapRect(r);
667
668    if (quickReject(r.left, r.top, r.right, r.bottom)) {
669        return;
670    }
671
672    glActiveTexture(GL_TEXTURE0);
673    const Texture* texture = mCaches.textureCache.get(bitmap);
674    if (!texture) return;
675    const AutoTexture autoCleanup(texture);
676
677    drawTextureRect(r.left, r.top, r.right, r.bottom, texture, paint);
678}
679
680void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
681         float srcLeft, float srcTop, float srcRight, float srcBottom,
682         float dstLeft, float dstTop, float dstRight, float dstBottom,
683         const SkPaint* paint) {
684    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
685        return;
686    }
687
688    glActiveTexture(GL_TEXTURE0);
689    const Texture* texture = mCaches.textureCache.get(bitmap);
690    if (!texture) return;
691    const AutoTexture autoCleanup(texture);
692
693    const float width = texture->width;
694    const float height = texture->height;
695
696    const float u1 = srcLeft / width;
697    const float v1 = srcTop / height;
698    const float u2 = srcRight / width;
699    const float v2 = srcBottom / height;
700
701    resetDrawTextureTexCoords(u1, v1, u2, v2);
702
703    drawTextureRect(dstLeft, dstTop, dstRight, dstBottom, texture, paint);
704
705    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
706}
707
708void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
709        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
710        float left, float top, float right, float bottom, const SkPaint* paint) {
711    if (quickReject(left, top, right, bottom)) {
712        return;
713    }
714
715    glActiveTexture(GL_TEXTURE0);
716    const Texture* texture = mCaches.textureCache.get(bitmap);
717    if (!texture) return;
718    const AutoTexture autoCleanup(texture);
719
720    int alpha;
721    SkXfermode::Mode mode;
722    getAlphaAndMode(paint, &alpha, &mode);
723
724    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
725            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
726
727    if (mesh) {
728        // Specify right and bottom as +1.0f from left/top to prevent scaling since the
729        // patch mesh already defines the final size
730        drawTextureMesh(left, top, left + 1.0f, top + 1.0f, texture->id, alpha / 255.0f,
731                mode, texture->blend, &mesh->vertices[0].position[0],
732                &mesh->vertices[0].texture[0], GL_TRIANGLES, mesh->verticesCount);
733    }
734}
735
736void OpenGLRenderer::drawLines(float* points, int count, const SkPaint* paint) {
737    if (mSnapshot->invisible) return;
738
739    int alpha;
740    SkXfermode::Mode mode;
741    getAlphaAndMode(paint, &alpha, &mode);
742
743    uint32_t color = paint->getColor();
744    const GLfloat a = alpha / 255.0f;
745    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
746    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
747    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
748
749    const bool isAA = paint->isAntiAlias();
750    if (isAA) {
751        GLuint textureUnit = 0;
752        setupTextureAlpha8(mCaches.line.getTexture(), 0, 0, textureUnit, 0.0f, 0.0f, r, g, b, a,
753                mode, false, true, mCaches.line.getVertices(), mCaches.line.getTexCoords());
754    } else {
755        setupColorRect(0.0f, 0.0f, 1.0f, 1.0f, r, g, b, a, mode, false);
756    }
757
758    const float strokeWidth = paint->getStrokeWidth();
759    const GLsizei elementsCount = isAA ? mCaches.line.getElementsCount() : gMeshCount;
760    const GLenum drawMode = isAA ? GL_TRIANGLES : GL_TRIANGLE_STRIP;
761
762    for (int i = 0; i < count; i += 4) {
763        float tx = 0.0f;
764        float ty = 0.0f;
765
766        if (isAA) {
767            mCaches.line.update(points[i], points[i + 1], points[i + 2], points[i + 3],
768                    strokeWidth, tx, ty);
769        } else {
770            ty = strokeWidth <= 1.0f ? 0.0f : -strokeWidth * 0.5f;
771        }
772
773        const float dx = points[i + 2] - points[i];
774        const float dy = points[i + 3] - points[i + 1];
775        const float mag = sqrtf(dx * dx + dy * dy);
776        const float angle = acos(dx / mag);
777
778        mModelView.loadTranslate(points[i], points[i + 1], 0.0f);
779        if (angle > MIN_ANGLE || angle < -MIN_ANGLE) {
780            mModelView.rotate(angle * RAD_TO_DEG, 0.0f, 0.0f, 1.0f);
781        }
782        mModelView.translate(tx, ty, 0.0f);
783        if (!isAA) {
784            float length = mCaches.line.getLength(points[i], points[i + 1],
785                    points[i + 2], points[i + 3]);
786            mModelView.scale(length, strokeWidth, 1.0f);
787        }
788        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
789
790        if (mShader) {
791            mShader->updateTransforms(mCaches.currentProgram, mModelView, *mSnapshot);
792        }
793
794        glDrawArrays(drawMode, 0, elementsCount);
795    }
796
797    if (isAA) {
798        glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
799    }
800}
801
802void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
803    const Rect& clip = *mSnapshot->clipRect;
804    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
805}
806
807void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, const SkPaint* p) {
808    if (quickReject(left, top, right, bottom)) {
809        return;
810    }
811
812    SkXfermode::Mode mode;
813    if (!mExtensions.hasFramebufferFetch()) {
814        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
815        if (!isMode) {
816            // Assume SRC_OVER
817            mode = SkXfermode::kSrcOver_Mode;
818        }
819    } else {
820        mode = getXfermode(p->getXfermode());
821    }
822
823    // Skia draws using the color's alpha channel if < 255
824    // Otherwise, it uses the paint's alpha
825    int color = p->getColor();
826    if (((color >> 24) & 0xff) == 255) {
827        color |= p->getAlpha() << 24;
828    }
829
830    drawColorRect(left, top, right, bottom, color, mode);
831}
832
833void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
834        float x, float y, SkPaint* paint) {
835    if (text == NULL || count == 0 || (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
836        return;
837    }
838    if (mSnapshot->invisible) return;
839
840    paint->setAntiAlias(true);
841
842    float length = -1.0f;
843    switch (paint->getTextAlign()) {
844        case SkPaint::kCenter_Align:
845            length = paint->measureText(text, bytesCount);
846            x -= length / 2.0f;
847            break;
848        case SkPaint::kRight_Align:
849            length = paint->measureText(text, bytesCount);
850            x -= length;
851            break;
852        default:
853            break;
854    }
855
856    int alpha;
857    SkXfermode::Mode mode;
858    getAlphaAndMode(paint, &alpha, &mode);
859
860    uint32_t color = paint->getColor();
861    const GLfloat a = alpha / 255.0f;
862    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
863    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
864    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
865
866    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
867    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
868            paint->getTextSize());
869
870    Rect clipRect(*mSnapshot->clipRect);
871    glScissor(clipRect.left, mSnapshot->height - clipRect.bottom,
872            clipRect.getWidth(), clipRect.getHeight());
873
874    if (mHasShadow) {
875        glActiveTexture(gTextureUnits[0]);
876        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
877        const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount,
878                count, mShadowRadius);
879        const AutoTexture autoCleanup(shadow);
880
881        setupShadow(shadow, x, y, mode, a);
882
883        // Draw the mesh
884        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
885        glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
886    }
887
888    GLuint textureUnit = 0;
889    glActiveTexture(gTextureUnits[textureUnit]);
890
891    // Assume that the modelView matrix does not force scales, rotates, etc.
892    const bool linearFilter = mSnapshot->transform->changesBounds();
893    setupTextureAlpha8(fontRenderer.getTexture(linearFilter), 0, 0, textureUnit,
894            x, y, r, g, b, a, mode, false, true);
895
896    const Rect& clip = mSnapshot->getLocalClip();
897    clearLayerRegions();
898
899    fontRenderer.renderText(paint, &clip, text, 0, bytesCount, count, x, y);
900
901    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
902    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
903
904    drawTextDecorations(text, bytesCount, length, x, y, paint);
905
906    setScissorFromClip();
907}
908
909void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
910    if (mSnapshot->invisible) return;
911
912    GLuint textureUnit = 0;
913    glActiveTexture(gTextureUnits[textureUnit]);
914
915    const PathTexture* texture = mCaches.pathCache.get(path, paint);
916    if (!texture) return;
917    const AutoTexture autoCleanup(texture);
918
919    const float x = texture->left - texture->offset;
920    const float y = texture->top - texture->offset;
921
922    if (quickReject(x, y, x + texture->width, y + texture->height)) {
923        return;
924    }
925
926    int alpha;
927    SkXfermode::Mode mode;
928    getAlphaAndMode(paint, &alpha, &mode);
929
930    uint32_t color = paint->getColor();
931    const GLfloat a = alpha / 255.0f;
932    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
933    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
934    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
935
936    setupTextureAlpha8(texture, textureUnit, x, y, r, g, b, a, mode, true, true);
937
938    clearLayerRegions();
939
940    // Draw the mesh
941    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
942    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
943}
944
945///////////////////////////////////////////////////////////////////////////////
946// Shaders
947///////////////////////////////////////////////////////////////////////////////
948
949void OpenGLRenderer::resetShader() {
950    mShader = NULL;
951}
952
953void OpenGLRenderer::setupShader(SkiaShader* shader) {
954    mShader = shader;
955    if (mShader) {
956        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
957    }
958}
959
960///////////////////////////////////////////////////////////////////////////////
961// Color filters
962///////////////////////////////////////////////////////////////////////////////
963
964void OpenGLRenderer::resetColorFilter() {
965    mColorFilter = NULL;
966}
967
968void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
969    mColorFilter = filter;
970}
971
972///////////////////////////////////////////////////////////////////////////////
973// Drop shadow
974///////////////////////////////////////////////////////////////////////////////
975
976void OpenGLRenderer::resetShadow() {
977    mHasShadow = false;
978}
979
980void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
981    mHasShadow = true;
982    mShadowRadius = radius;
983    mShadowDx = dx;
984    mShadowDy = dy;
985    mShadowColor = color;
986}
987
988///////////////////////////////////////////////////////////////////////////////
989// Drawing implementation
990///////////////////////////////////////////////////////////////////////////////
991
992void OpenGLRenderer::setupShadow(const ShadowTexture* texture, float x, float y,
993        SkXfermode::Mode mode, float alpha) {
994    const float sx = x - texture->left + mShadowDx;
995    const float sy = y - texture->top + mShadowDy;
996
997    const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
998    const GLfloat a = shadowAlpha < 255 ? shadowAlpha / 255.0f : alpha;
999    const GLfloat r = a * ((mShadowColor >> 16) & 0xFF) / 255.0f;
1000    const GLfloat g = a * ((mShadowColor >>  8) & 0xFF) / 255.0f;
1001    const GLfloat b = a * ((mShadowColor      ) & 0xFF) / 255.0f;
1002
1003    GLuint textureUnit = 0;
1004    setupTextureAlpha8(texture, textureUnit, sx, sy, r, g, b, a, mode, true, false);
1005}
1006
1007void OpenGLRenderer::setupTextureAlpha8(const Texture* texture, GLuint& textureUnit,
1008        float x, float y, float r, float g, float b, float a, SkXfermode::Mode mode,
1009        bool transforms, bool applyFilters) {
1010    setupTextureAlpha8(texture->id, texture->width, texture->height, textureUnit,
1011            x, y, r, g, b, a, mode, transforms, applyFilters,
1012            &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]);
1013}
1014
1015void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
1016        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
1017        SkXfermode::Mode mode, bool transforms, bool applyFilters) {
1018    setupTextureAlpha8(texture, width, height, textureUnit,
1019            x, y, r, g, b, a, mode, transforms, applyFilters,
1020            &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]);
1021}
1022
1023void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
1024        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
1025        SkXfermode::Mode mode, bool transforms, bool applyFilters,
1026        GLvoid* vertices, GLvoid* texCoords) {
1027     // Describe the required shaders
1028     ProgramDescription description;
1029     description.hasTexture = true;
1030     description.hasAlpha8Texture = true;
1031     const bool setColor = description.setAlpha8Color(r, g, b, a);
1032
1033     if (applyFilters) {
1034         if (mShader) {
1035             mShader->describe(description, mExtensions);
1036         }
1037         if (mColorFilter) {
1038             mColorFilter->describe(description, mExtensions);
1039         }
1040     }
1041
1042     // Setup the blending mode
1043     chooseBlending(true, mode, description);
1044
1045     // Build and use the appropriate shader
1046     useProgram(mCaches.programCache.get(description));
1047
1048     bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, textureUnit);
1049     glUniform1i(mCaches.currentProgram->getUniform("sampler"), textureUnit);
1050
1051     int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1052     glEnableVertexAttribArray(texCoordsSlot);
1053
1054     // Setup attributes
1055     glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1056             gMeshStride, vertices);
1057     glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE,
1058             gMeshStride, texCoords);
1059
1060     // Setup uniforms
1061     if (transforms) {
1062         mModelView.loadTranslate(x, y, 0.0f);
1063         mModelView.scale(width, height, 1.0f);
1064     } else {
1065         mModelView.loadIdentity();
1066     }
1067     mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1068     if (setColor) {
1069         mCaches.currentProgram->setColor(r, g, b, a);
1070     }
1071
1072     textureUnit++;
1073     if (applyFilters) {
1074         // Setup attributes and uniforms required by the shaders
1075         if (mShader) {
1076             mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
1077         }
1078         if (mColorFilter) {
1079             mColorFilter->setupProgram(mCaches.currentProgram);
1080         }
1081     }
1082}
1083
1084// Same values used by Skia
1085#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
1086#define kStdUnderline_Offset    (1.0f / 9.0f)
1087#define kStdUnderline_Thickness (1.0f / 18.0f)
1088
1089void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
1090        float x, float y, SkPaint* paint) {
1091    // Handle underline and strike-through
1092    uint32_t flags = paint->getFlags();
1093    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
1094        float underlineWidth = length;
1095        // If length is > 0.0f, we already measured the text for the text alignment
1096        if (length <= 0.0f) {
1097            underlineWidth = paint->measureText(text, bytesCount);
1098        }
1099
1100        float offsetX = 0;
1101        switch (paint->getTextAlign()) {
1102            case SkPaint::kCenter_Align:
1103                offsetX = underlineWidth * 0.5f;
1104                break;
1105            case SkPaint::kRight_Align:
1106                offsetX = underlineWidth;
1107                break;
1108            default:
1109                break;
1110        }
1111
1112        if (underlineWidth > 0.0f) {
1113            const float textSize = paint->getTextSize();
1114            const float strokeWidth = textSize * kStdUnderline_Thickness;
1115
1116            const float left = x - offsetX;
1117            float top = 0.0f;
1118
1119            const int pointsCount = 4 * (flags & SkPaint::kStrikeThruText_Flag ? 2 : 1);
1120            float points[pointsCount];
1121            int currentPoint = 0;
1122
1123            if (flags & SkPaint::kUnderlineText_Flag) {
1124                top = y + textSize * kStdUnderline_Offset;
1125                points[currentPoint++] = left;
1126                points[currentPoint++] = top;
1127                points[currentPoint++] = left + underlineWidth;
1128                points[currentPoint++] = top;
1129            }
1130
1131            if (flags & SkPaint::kStrikeThruText_Flag) {
1132                top = y + textSize * kStdStrikeThru_Offset;
1133                points[currentPoint++] = left;
1134                points[currentPoint++] = top;
1135                points[currentPoint++] = left + underlineWidth;
1136                points[currentPoint++] = top;
1137            }
1138
1139            SkPaint linesPaint(*paint);
1140            linesPaint.setStrokeWidth(strokeWidth);
1141
1142            drawLines(&points[0], pointsCount, &linesPaint);
1143        }
1144    }
1145}
1146
1147void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
1148        int color, SkXfermode::Mode mode, bool ignoreTransform) {
1149    clearLayerRegions();
1150
1151    // If a shader is set, preserve only the alpha
1152    if (mShader) {
1153        color |= 0x00ffffff;
1154    }
1155
1156    // Render using pre-multiplied alpha
1157    const int alpha = (color >> 24) & 0xFF;
1158    const GLfloat a = alpha / 255.0f;
1159    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
1160    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
1161    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
1162
1163    setupColorRect(left, top, right, bottom, r, g, b, a, mode, ignoreTransform);
1164
1165    // Draw the mesh
1166    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1167}
1168
1169void OpenGLRenderer::setupColorRect(float left, float top, float right, float bottom,
1170        float r, float g, float b, float a, SkXfermode::Mode mode, bool ignoreTransform) {
1171    GLuint textureUnit = 0;
1172
1173    // Describe the required shaders
1174    ProgramDescription description;
1175    const bool setColor = description.setColor(r, g, b, a);
1176
1177    if (mShader) {
1178        mShader->describe(description, mExtensions);
1179    }
1180    if (mColorFilter) {
1181        mColorFilter->describe(description, mExtensions);
1182    }
1183
1184    // Setup the blending mode
1185    chooseBlending(a < 1.0f || (mShader && mShader->blend()), mode, description);
1186
1187    // Build and use the appropriate shader
1188    useProgram(mCaches.programCache.get(description));
1189
1190    // Setup attributes
1191    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1192            gMeshStride, &mMeshVertices[0].position[0]);
1193
1194    // Setup uniforms
1195    mModelView.loadTranslate(left, top, 0.0f);
1196    mModelView.scale(right - left, bottom - top, 1.0f);
1197    if (!ignoreTransform) {
1198        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1199    } else {
1200        mat4 identity;
1201        mCaches.currentProgram->set(mOrthoMatrix, mModelView, identity);
1202    }
1203    mCaches.currentProgram->setColor(r, g, b, a);
1204
1205    // Setup attributes and uniforms required by the shaders
1206    if (mShader) {
1207        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
1208    }
1209    if (mColorFilter) {
1210        mColorFilter->setupProgram(mCaches.currentProgram);
1211    }
1212}
1213
1214void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1215        const Texture* texture, const SkPaint* paint) {
1216    int alpha;
1217    SkXfermode::Mode mode;
1218    getAlphaAndMode(paint, &alpha, &mode);
1219
1220    drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
1221            texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1222            GL_TRIANGLE_STRIP, gMeshCount);
1223}
1224
1225void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1226        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
1227    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
1228            &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1229            GL_TRIANGLE_STRIP, gMeshCount);
1230}
1231
1232void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
1233        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
1234        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
1235        bool swapSrcDst, bool ignoreTransform) {
1236    clearLayerRegions();
1237
1238    ProgramDescription description;
1239    description.hasTexture = true;
1240    const bool setColor = description.setColor(alpha, alpha, alpha, alpha);
1241    if (mColorFilter) {
1242        mColorFilter->describe(description, mExtensions);
1243    }
1244
1245    mModelView.loadTranslate(left, top, 0.0f);
1246    mModelView.scale(right - left, bottom - top, 1.0f);
1247
1248    chooseBlending(blend || alpha < 1.0f, mode, description, swapSrcDst);
1249
1250    useProgram(mCaches.programCache.get(description));
1251    if (!ignoreTransform) {
1252        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1253    } else {
1254        mat4 m;
1255        mCaches.currentProgram->set(mOrthoMatrix, mModelView, m);
1256    }
1257
1258    // Texture
1259    bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, 0);
1260    glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0);
1261
1262    // Always premultiplied
1263    if (setColor) {
1264        mCaches.currentProgram->setColor(alpha, alpha, alpha, alpha);
1265    }
1266
1267    // Mesh
1268    int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1269    glEnableVertexAttribArray(texCoordsSlot);
1270    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1271            gMeshStride, vertices);
1272    glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1273
1274    // Color filter
1275    if (mColorFilter) {
1276        mColorFilter->setupProgram(mCaches.currentProgram);
1277    }
1278
1279    glDrawArrays(drawMode, 0, elementsCount);
1280    glDisableVertexAttribArray(texCoordsSlot);
1281}
1282
1283void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
1284        ProgramDescription& description, bool swapSrcDst) {
1285    blend = blend || mode != SkXfermode::kSrcOver_Mode;
1286    if (blend) {
1287        if (mode < SkXfermode::kPlus_Mode) {
1288            if (!mCaches.blend) {
1289                glEnable(GL_BLEND);
1290            }
1291
1292            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
1293            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
1294
1295            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
1296                glBlendFunc(sourceMode, destMode);
1297                mCaches.lastSrcMode = sourceMode;
1298                mCaches.lastDstMode = destMode;
1299            }
1300        } else {
1301            // These blend modes are not supported by OpenGL directly and have
1302            // to be implemented using shaders. Since the shader will perform
1303            // the blending, turn blending off here
1304            if (mExtensions.hasFramebufferFetch()) {
1305                description.framebufferMode = mode;
1306                description.swapSrcDst = swapSrcDst;
1307            }
1308
1309            if (mCaches.blend) {
1310                glDisable(GL_BLEND);
1311            }
1312            blend = false;
1313        }
1314    } else if (mCaches.blend) {
1315        glDisable(GL_BLEND);
1316    }
1317    mCaches.blend = blend;
1318}
1319
1320bool OpenGLRenderer::useProgram(Program* program) {
1321    if (!program->isInUse()) {
1322        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
1323        program->use();
1324        mCaches.currentProgram = program;
1325        return false;
1326    }
1327    return true;
1328}
1329
1330void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
1331    TextureVertex* v = &mMeshVertices[0];
1332    TextureVertex::setUV(v++, u1, v1);
1333    TextureVertex::setUV(v++, u2, v1);
1334    TextureVertex::setUV(v++, u1, v2);
1335    TextureVertex::setUV(v++, u2, v2);
1336}
1337
1338void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
1339    if (paint) {
1340        if (!mExtensions.hasFramebufferFetch()) {
1341            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
1342            if (!isMode) {
1343                // Assume SRC_OVER
1344                *mode = SkXfermode::kSrcOver_Mode;
1345            }
1346        } else {
1347            *mode = getXfermode(paint->getXfermode());
1348        }
1349
1350        // Skia draws using the color's alpha channel if < 255
1351        // Otherwise, it uses the paint's alpha
1352        int color = paint->getColor();
1353        *alpha = (color >> 24) & 0xFF;
1354        if (*alpha == 255) {
1355            *alpha = paint->getAlpha();
1356        }
1357    } else {
1358        *mode = SkXfermode::kSrcOver_Mode;
1359        *alpha = 255;
1360    }
1361}
1362
1363SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
1364    if (mode == NULL) {
1365        return SkXfermode::kSrcOver_Mode;
1366    }
1367    return mode->fMode;
1368}
1369
1370void OpenGLRenderer::bindTexture(GLuint texture, GLenum wrapS, GLenum wrapT, GLuint textureUnit) {
1371    glActiveTexture(gTextureUnits[textureUnit]);
1372    glBindTexture(GL_TEXTURE_2D, texture);
1373    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
1374    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
1375}
1376
1377}; // namespace uirenderer
1378}; // namespace android
1379