OpenGLRenderer.cpp revision 93d2361c6d294c390cb5c4a13bd1b88dcd465fd7
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 || alpha <= ALPHA_THRESHOLD;
392    }
393
394    // Bail out if we won't draw in this snapshot
395    if (snapshot->invisible) {
396        return false;
397    }
398
399    glActiveTexture(GL_TEXTURE0);
400
401    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
402    if (!layer) {
403        return false;
404    }
405
406    layer->mode = mode;
407    layer->alpha = alpha;
408    layer->layer.set(bounds);
409    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->height),
410            bounds.getWidth() / float(layer->width), 0.0f);
411
412    // Save the layer in the snapshot
413    snapshot->flags |= Snapshot::kFlagIsLayer;
414    snapshot->layer = layer;
415
416    if (fboLayer) {
417        layer->fbo = mCaches.fboCache.get();
418
419        snapshot->flags |= Snapshot::kFlagIsFboLayer;
420        snapshot->fbo = layer->fbo;
421        snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
422        snapshot->resetClip(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
423        snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
424        snapshot->height = bounds.getHeight();
425        snapshot->flags |= Snapshot::kFlagDirtyOrtho;
426        snapshot->orthoMatrix.load(mOrthoMatrix);
427
428        // Bind texture to FBO
429        glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
430        glBindTexture(GL_TEXTURE_2D, layer->texture);
431
432        // Initialize the texture if needed
433        if (layer->empty) {
434            layer->empty = false;
435            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->width, layer->height, 0,
436                    GL_RGBA, GL_UNSIGNED_BYTE, NULL);
437        }
438
439        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
440                layer->texture, 0);
441
442#if DEBUG_LAYERS
443        GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
444        if (status != GL_FRAMEBUFFER_COMPLETE) {
445            LOGE("Framebuffer incomplete (GL error code 0x%x)", status);
446
447            glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
448            glDeleteTextures(1, &layer->texture);
449            mCaches.fboCache.put(layer->fbo);
450
451            delete layer;
452
453            return false;
454        }
455#endif
456
457        // Clear the FBO
458        glScissor(0.0f, 0.0f, bounds.getWidth() + 1.0f, bounds.getHeight() + 1.0f);
459        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
460        glClear(GL_COLOR_BUFFER_BIT);
461
462        setScissorFromClip();
463
464        // Change the ortho projection
465        glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
466        mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
467    } else {
468        // Copy the framebuffer into the layer
469        glBindTexture(GL_TEXTURE_2D, layer->texture);
470
471         if (layer->empty) {
472             glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left, mHeight - bounds.bottom,
473                     layer->width, layer->height, 0);
474             layer->empty = false;
475         } else {
476             glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left, mHeight - bounds.bottom,
477                     bounds.getWidth(), bounds.getHeight());
478          }
479
480        // Enqueue the buffer coordinates to clear the corresponding region later
481        mLayers.push(new Rect(bounds));
482    }
483
484    return true;
485}
486
487/**
488 * Read the documentation of createLayer() before doing anything in this method.
489 */
490void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
491    if (!current->layer) {
492        LOGE("Attempting to compose a layer that does not exist");
493        return;
494    }
495
496    const bool fboLayer = current->flags & SkCanvas::kClipToLayer_SaveFlag;
497
498    if (fboLayer) {
499        // Unbind current FBO and restore previous one
500        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
501    }
502
503    // Restore the clip from the previous snapshot
504    const Rect& clip = *previous->clipRect;
505    glScissor(clip.left, previous->height - clip.bottom, clip.getWidth(), clip.getHeight());
506
507    Layer* layer = current->layer;
508    const Rect& rect = layer->layer;
509
510    if (!fboLayer && layer->alpha < 255) {
511        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
512                layer->alpha << 24, SkXfermode::kDstIn_Mode, true);
513    }
514
515    const Rect& texCoords = layer->texCoords;
516    resetDrawTextureTexCoords(texCoords.left, texCoords.top, texCoords.right, texCoords.bottom);
517
518    if (fboLayer) {
519        drawTextureRect(rect.left, rect.top, rect.right, rect.bottom,
520                layer->texture, layer->alpha / 255.0f, layer->mode, layer->blend);
521    } else {
522        drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
523                1.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
524                &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount, true, true);
525    }
526
527    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
528
529    if (fboLayer) {
530        // Detach the texture from the FBO
531        glBindFramebuffer(GL_FRAMEBUFFER, current->fbo);
532        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
533        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
534
535        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
536        mCaches.fboCache.put(current->fbo);
537    }
538
539    // Failing to add the layer to the cache should happen only if the layer is too large
540    if (!mCaches.layerCache.put(layer)) {
541        LAYER_LOGD("Deleting layer");
542        glDeleteTextures(1, &layer->texture);
543        delete layer;
544    }
545}
546
547void OpenGLRenderer::clearLayerRegions() {
548    if (mLayers.size() == 0 || mSnapshot->invisible) return;
549
550    for (uint32_t i = 0; i < mLayers.size(); i++) {
551        Rect* bounds = mLayers.itemAt(i);
552
553        // Clear the framebuffer where the layer will draw
554        glScissor(bounds->left, mHeight - bounds->bottom,
555                bounds->getWidth(), bounds->getHeight());
556        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
557        glClear(GL_COLOR_BUFFER_BIT);
558
559        delete bounds;
560    }
561    mLayers.clear();
562
563    // Restore the clip
564    setScissorFromClip();
565}
566
567///////////////////////////////////////////////////////////////////////////////
568// Transforms
569///////////////////////////////////////////////////////////////////////////////
570
571void OpenGLRenderer::translate(float dx, float dy) {
572    mSnapshot->transform->translate(dx, dy, 0.0f);
573}
574
575void OpenGLRenderer::rotate(float degrees) {
576    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
577}
578
579void OpenGLRenderer::scale(float sx, float sy) {
580    mSnapshot->transform->scale(sx, sy, 1.0f);
581}
582
583void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
584    mSnapshot->transform->load(*matrix);
585}
586
587const float* OpenGLRenderer::getMatrix() const {
588    if (mSnapshot->fbo != 0) {
589        return &mSnapshot->transform->data[0];
590    }
591    return &mIdentity.data[0];
592}
593
594void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
595    mSnapshot->transform->copyTo(*matrix);
596}
597
598void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
599    mat4 m(*matrix);
600    mSnapshot->transform->multiply(m);
601}
602
603///////////////////////////////////////////////////////////////////////////////
604// Clipping
605///////////////////////////////////////////////////////////////////////////////
606
607void OpenGLRenderer::setScissorFromClip() {
608    const Rect& clip = *mSnapshot->clipRect;
609    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
610}
611
612const Rect& OpenGLRenderer::getClipBounds() {
613    return mSnapshot->getLocalClip();
614}
615
616bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
617    if (mSnapshot->invisible) {
618        return true;
619    }
620
621    Rect r(left, top, right, bottom);
622    mSnapshot->transform->mapRect(r);
623    return !mSnapshot->clipRect->intersects(r);
624}
625
626bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
627    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
628    if (clipped) {
629        setScissorFromClip();
630    }
631    return !mSnapshot->clipRect->isEmpty();
632}
633
634///////////////////////////////////////////////////////////////////////////////
635// Drawing
636///////////////////////////////////////////////////////////////////////////////
637
638void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, const SkPaint* paint) {
639    const float right = left + bitmap->width();
640    const float bottom = top + bitmap->height();
641
642    if (quickReject(left, top, right, bottom)) {
643        return;
644    }
645
646    glActiveTexture(GL_TEXTURE0);
647    const Texture* texture = mCaches.textureCache.get(bitmap);
648    if (!texture) return;
649    const AutoTexture autoCleanup(texture);
650
651    drawTextureRect(left, top, right, bottom, texture, paint);
652}
653
654void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, const SkMatrix* matrix, const SkPaint* paint) {
655    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
656    const mat4 transform(*matrix);
657    transform.mapRect(r);
658
659    if (quickReject(r.left, r.top, r.right, r.bottom)) {
660        return;
661    }
662
663    glActiveTexture(GL_TEXTURE0);
664    const Texture* texture = mCaches.textureCache.get(bitmap);
665    if (!texture) return;
666    const AutoTexture autoCleanup(texture);
667
668    drawTextureRect(r.left, r.top, r.right, r.bottom, texture, paint);
669}
670
671void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
672         float srcLeft, float srcTop, float srcRight, float srcBottom,
673         float dstLeft, float dstTop, float dstRight, float dstBottom,
674         const SkPaint* paint) {
675    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
676        return;
677    }
678
679    glActiveTexture(GL_TEXTURE0);
680    const Texture* texture = mCaches.textureCache.get(bitmap);
681    if (!texture) return;
682    const AutoTexture autoCleanup(texture);
683
684    const float width = texture->width;
685    const float height = texture->height;
686
687    const float u1 = srcLeft / width;
688    const float v1 = srcTop / height;
689    const float u2 = srcRight / width;
690    const float v2 = srcBottom / height;
691
692    resetDrawTextureTexCoords(u1, v1, u2, v2);
693
694    drawTextureRect(dstLeft, dstTop, dstRight, dstBottom, texture, paint);
695
696    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
697}
698
699void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
700        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
701        float left, float top, float right, float bottom, const SkPaint* paint) {
702    if (quickReject(left, top, right, bottom)) {
703        return;
704    }
705
706    glActiveTexture(GL_TEXTURE0);
707    const Texture* texture = mCaches.textureCache.get(bitmap);
708    if (!texture) return;
709    const AutoTexture autoCleanup(texture);
710
711    int alpha;
712    SkXfermode::Mode mode;
713    getAlphaAndMode(paint, &alpha, &mode);
714
715    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
716            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
717
718    // Specify right and bottom as +1.0f from left/top to prevent scaling since the
719    // patch mesh already defines the final size
720    drawTextureMesh(left, top, left + 1.0f, top + 1.0f, texture->id, alpha / 255.0f,
721            mode, texture->blend, &mesh->vertices[0].position[0],
722            &mesh->vertices[0].texture[0], GL_TRIANGLES, mesh->verticesCount);
723}
724
725void OpenGLRenderer::drawLines(float* points, int count, const SkPaint* paint) {
726    if (mSnapshot->invisible) return;
727
728    int alpha;
729    SkXfermode::Mode mode;
730    getAlphaAndMode(paint, &alpha, &mode);
731
732    uint32_t color = paint->getColor();
733    const GLfloat a = alpha / 255.0f;
734    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
735    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
736    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
737
738    const bool isAA = paint->isAntiAlias();
739    if (isAA) {
740        GLuint textureUnit = 0;
741        setupTextureAlpha8(mCaches.line.getTexture(), 0, 0, textureUnit, 0.0f, 0.0f, r, g, b, a,
742                mode, false, true, mCaches.line.getVertices(), mCaches.line.getTexCoords());
743    } else {
744        setupColorRect(0.0f, 0.0f, 1.0f, 1.0f, r, g, b, a, mode, false);
745    }
746
747    const float strokeWidth = paint->getStrokeWidth();
748    const GLsizei elementsCount = isAA ? mCaches.line.getElementsCount() : gMeshCount;
749    const GLenum drawMode = isAA ? GL_TRIANGLES : GL_TRIANGLE_STRIP;
750
751    for (int i = 0; i < count; i += 4) {
752        float tx = 0.0f;
753        float ty = 0.0f;
754
755        if (isAA) {
756            mCaches.line.update(points[i], points[i + 1], points[i + 2], points[i + 3],
757                    strokeWidth, tx, ty);
758        } else {
759            ty = strokeWidth <= 1.0f ? 0.0f : -strokeWidth * 0.5f;
760        }
761
762        const float dx = points[i + 2] - points[i];
763        const float dy = points[i + 3] - points[i + 1];
764        const float mag = sqrtf(dx * dx + dy * dy);
765        const float angle = acos(dx / mag);
766
767        mModelView.loadTranslate(points[i], points[i + 1], 0.0f);
768        if (angle > MIN_ANGLE || angle < -MIN_ANGLE) {
769            mModelView.rotate(angle * RAD_TO_DEG, 0.0f, 0.0f, 1.0f);
770        }
771        mModelView.translate(tx, ty, 0.0f);
772        if (!isAA) {
773            float length = mCaches.line.getLength(points[i], points[i + 1],
774                    points[i + 2], points[i + 3]);
775            mModelView.scale(length, strokeWidth, 1.0f);
776        }
777        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
778
779        if (mShader) {
780            mShader->updateTransforms(mCaches.currentProgram, mModelView, *mSnapshot);
781        }
782
783        glDrawArrays(drawMode, 0, elementsCount);
784    }
785
786    if (isAA) {
787        glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
788    }
789}
790
791void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
792    const Rect& clip = *mSnapshot->clipRect;
793    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
794}
795
796void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, const SkPaint* p) {
797    if (quickReject(left, top, right, bottom)) {
798        return;
799    }
800
801    SkXfermode::Mode mode;
802    if (!mExtensions.hasFramebufferFetch()) {
803        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
804        if (!isMode) {
805            // Assume SRC_OVER
806            mode = SkXfermode::kSrcOver_Mode;
807        }
808    } else {
809        mode = getXfermode(p->getXfermode());
810    }
811
812    // Skia draws using the color's alpha channel if < 255
813    // Otherwise, it uses the paint's alpha
814    int color = p->getColor();
815    if (((color >> 24) & 0xff) == 255) {
816        color |= p->getAlpha() << 24;
817    }
818
819    drawColorRect(left, top, right, bottom, color, mode);
820}
821
822void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
823        float x, float y, SkPaint* paint) {
824    if (text == NULL || count == 0 || (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
825        return;
826    }
827    if (mSnapshot->invisible) return;
828
829    paint->setAntiAlias(true);
830
831    float length = -1.0f;
832    switch (paint->getTextAlign()) {
833        case SkPaint::kCenter_Align:
834            length = paint->measureText(text, bytesCount);
835            x -= length / 2.0f;
836            break;
837        case SkPaint::kRight_Align:
838            length = paint->measureText(text, bytesCount);
839            x -= length;
840            break;
841        default:
842            break;
843    }
844
845    int alpha;
846    SkXfermode::Mode mode;
847    getAlphaAndMode(paint, &alpha, &mode);
848
849    uint32_t color = paint->getColor();
850    const GLfloat a = alpha / 255.0f;
851    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
852    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
853    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
854
855    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
856    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
857            paint->getTextSize());
858
859    if (mHasShadow) {
860        glActiveTexture(gTextureUnits[0]);
861        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
862        const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount,
863                count, mShadowRadius);
864        const AutoTexture autoCleanup(shadow);
865
866        setupShadow(shadow, x, y, mode, a);
867
868        // Draw the mesh
869        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
870        glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
871    }
872
873    GLuint textureUnit = 0;
874    glActiveTexture(gTextureUnits[textureUnit]);
875
876    // Assume that the modelView matrix does not force scales, rotates, etc.
877    const bool linearFilter = mSnapshot->transform->changesBounds();
878    setupTextureAlpha8(fontRenderer.getTexture(linearFilter), 0, 0, textureUnit,
879            x, y, r, g, b, a, mode, false, true);
880
881    const Rect& clip = mSnapshot->getLocalClip();
882    clearLayerRegions();
883    fontRenderer.renderText(paint, &clip, text, 0, bytesCount, count, x, y);
884
885    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
886    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
887
888    drawTextDecorations(text, bytesCount, length, x, y, paint);
889}
890
891void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
892    if (mSnapshot->invisible) return;
893
894    GLuint textureUnit = 0;
895    glActiveTexture(gTextureUnits[textureUnit]);
896
897    const PathTexture* texture = mCaches.pathCache.get(path, paint);
898    if (!texture) return;
899    const AutoTexture autoCleanup(texture);
900
901    const float x = texture->left - texture->offset;
902    const float y = texture->top - texture->offset;
903
904    if (quickReject(x, y, x + texture->width, y + texture->height)) {
905        return;
906    }
907
908    int alpha;
909    SkXfermode::Mode mode;
910    getAlphaAndMode(paint, &alpha, &mode);
911
912    uint32_t color = paint->getColor();
913    const GLfloat a = alpha / 255.0f;
914    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
915    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
916    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
917
918    setupTextureAlpha8(texture, textureUnit, x, y, r, g, b, a, mode, true, true);
919
920    clearLayerRegions();
921
922    // Draw the mesh
923    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
924    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
925}
926
927///////////////////////////////////////////////////////////////////////////////
928// Shaders
929///////////////////////////////////////////////////////////////////////////////
930
931void OpenGLRenderer::resetShader() {
932    mShader = NULL;
933}
934
935void OpenGLRenderer::setupShader(SkiaShader* shader) {
936    mShader = shader;
937    if (mShader) {
938        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
939    }
940}
941
942///////////////////////////////////////////////////////////////////////////////
943// Color filters
944///////////////////////////////////////////////////////////////////////////////
945
946void OpenGLRenderer::resetColorFilter() {
947    mColorFilter = NULL;
948}
949
950void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
951    mColorFilter = filter;
952}
953
954///////////////////////////////////////////////////////////////////////////////
955// Drop shadow
956///////////////////////////////////////////////////////////////////////////////
957
958void OpenGLRenderer::resetShadow() {
959    mHasShadow = false;
960}
961
962void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
963    mHasShadow = true;
964    mShadowRadius = radius;
965    mShadowDx = dx;
966    mShadowDy = dy;
967    mShadowColor = color;
968}
969
970///////////////////////////////////////////////////////////////////////////////
971// Drawing implementation
972///////////////////////////////////////////////////////////////////////////////
973
974void OpenGLRenderer::setupShadow(const ShadowTexture* texture, float x, float y,
975        SkXfermode::Mode mode, float alpha) {
976    const float sx = x - texture->left + mShadowDx;
977    const float sy = y - texture->top + mShadowDy;
978
979    const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
980    const GLfloat a = shadowAlpha < 255 ? shadowAlpha / 255.0f : alpha;
981    const GLfloat r = a * ((mShadowColor >> 16) & 0xFF) / 255.0f;
982    const GLfloat g = a * ((mShadowColor >>  8) & 0xFF) / 255.0f;
983    const GLfloat b = a * ((mShadowColor      ) & 0xFF) / 255.0f;
984
985    GLuint textureUnit = 0;
986    setupTextureAlpha8(texture, textureUnit, sx, sy, r, g, b, a, mode, true, false);
987}
988
989void OpenGLRenderer::setupTextureAlpha8(const Texture* texture, GLuint& textureUnit,
990        float x, float y, float r, float g, float b, float a, SkXfermode::Mode mode,
991        bool transforms, bool applyFilters) {
992    setupTextureAlpha8(texture->id, texture->width, texture->height, textureUnit,
993            x, y, r, g, b, a, mode, transforms, applyFilters,
994            &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]);
995}
996
997void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
998        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
999        SkXfermode::Mode mode, bool transforms, bool applyFilters) {
1000    setupTextureAlpha8(texture, width, height, textureUnit,
1001            x, y, r, g, b, a, mode, transforms, applyFilters,
1002            &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]);
1003}
1004
1005void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
1006        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
1007        SkXfermode::Mode mode, bool transforms, bool applyFilters,
1008        GLvoid* vertices, GLvoid* texCoords) {
1009     // Describe the required shaders
1010     ProgramDescription description;
1011     description.hasTexture = true;
1012     description.hasAlpha8Texture = true;
1013     const bool setColor = description.setAlpha8Color(r, g, b, a);
1014
1015     if (applyFilters) {
1016         if (mShader) {
1017             mShader->describe(description, mExtensions);
1018         }
1019         if (mColorFilter) {
1020             mColorFilter->describe(description, mExtensions);
1021         }
1022     }
1023
1024     // Setup the blending mode
1025     chooseBlending(true, mode, description);
1026
1027     // Build and use the appropriate shader
1028     useProgram(mCaches.programCache.get(description));
1029
1030     bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, textureUnit);
1031     glUniform1i(mCaches.currentProgram->getUniform("sampler"), textureUnit);
1032
1033     int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1034     glEnableVertexAttribArray(texCoordsSlot);
1035
1036     // Setup attributes
1037     glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1038             gMeshStride, vertices);
1039     glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE,
1040             gMeshStride, texCoords);
1041
1042     // Setup uniforms
1043     if (transforms) {
1044         mModelView.loadTranslate(x, y, 0.0f);
1045         mModelView.scale(width, height, 1.0f);
1046     } else {
1047         mModelView.loadIdentity();
1048     }
1049     mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1050     if (setColor) {
1051         mCaches.currentProgram->setColor(r, g, b, a);
1052     }
1053
1054     textureUnit++;
1055     if (applyFilters) {
1056         // Setup attributes and uniforms required by the shaders
1057         if (mShader) {
1058             mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
1059         }
1060         if (mColorFilter) {
1061             mColorFilter->setupProgram(mCaches.currentProgram);
1062         }
1063     }
1064}
1065
1066// Same values used by Skia
1067#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
1068#define kStdUnderline_Offset    (1.0f / 9.0f)
1069#define kStdUnderline_Thickness (1.0f / 18.0f)
1070
1071void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
1072        float x, float y, SkPaint* paint) {
1073    // Handle underline and strike-through
1074    uint32_t flags = paint->getFlags();
1075    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
1076        float underlineWidth = length;
1077        // If length is > 0.0f, we already measured the text for the text alignment
1078        if (length <= 0.0f) {
1079            underlineWidth = paint->measureText(text, bytesCount);
1080        }
1081
1082        float offsetX = 0;
1083        switch (paint->getTextAlign()) {
1084            case SkPaint::kCenter_Align:
1085                offsetX = underlineWidth * 0.5f;
1086                break;
1087            case SkPaint::kRight_Align:
1088                offsetX = underlineWidth;
1089                break;
1090            default:
1091                break;
1092        }
1093
1094        if (underlineWidth > 0.0f) {
1095            const float textSize = paint->getTextSize();
1096            const float strokeWidth = textSize * kStdUnderline_Thickness;
1097
1098            const float left = x - offsetX;
1099            float top = 0.0f;
1100
1101            const int pointsCount = 4 * (flags & SkPaint::kStrikeThruText_Flag ? 2 : 1);
1102            float points[pointsCount];
1103            int currentPoint = 0;
1104
1105            if (flags & SkPaint::kUnderlineText_Flag) {
1106                top = y + textSize * kStdUnderline_Offset;
1107                points[currentPoint++] = left;
1108                points[currentPoint++] = top;
1109                points[currentPoint++] = left + underlineWidth;
1110                points[currentPoint++] = top;
1111            }
1112
1113            if (flags & SkPaint::kStrikeThruText_Flag) {
1114                top = y + textSize * kStdStrikeThru_Offset;
1115                points[currentPoint++] = left;
1116                points[currentPoint++] = top;
1117                points[currentPoint++] = left + underlineWidth;
1118                points[currentPoint++] = top;
1119            }
1120
1121            SkPaint linesPaint(*paint);
1122            linesPaint.setStrokeWidth(strokeWidth);
1123
1124            drawLines(&points[0], pointsCount, &linesPaint);
1125        }
1126    }
1127}
1128
1129void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
1130        int color, SkXfermode::Mode mode, bool ignoreTransform) {
1131    clearLayerRegions();
1132
1133    // If a shader is set, preserve only the alpha
1134    if (mShader) {
1135        color |= 0x00ffffff;
1136    }
1137
1138    // Render using pre-multiplied alpha
1139    const int alpha = (color >> 24) & 0xFF;
1140    const GLfloat a = alpha / 255.0f;
1141    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
1142    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
1143    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
1144
1145    setupColorRect(left, top, right, bottom, r, g, b, a, mode, ignoreTransform);
1146
1147    // Draw the mesh
1148    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1149}
1150
1151void OpenGLRenderer::setupColorRect(float left, float top, float right, float bottom,
1152        float r, float g, float b, float a, SkXfermode::Mode mode, bool ignoreTransform) {
1153    GLuint textureUnit = 0;
1154
1155    // Describe the required shaders
1156    ProgramDescription description;
1157    const bool setColor = description.setColor(r, g, b, a);
1158
1159    if (mShader) {
1160        mShader->describe(description, mExtensions);
1161    }
1162    if (mColorFilter) {
1163        mColorFilter->describe(description, mExtensions);
1164    }
1165
1166    // Setup the blending mode
1167    chooseBlending(a < 1.0f || (mShader && mShader->blend()), mode, description);
1168
1169    // Build and use the appropriate shader
1170    useProgram(mCaches.programCache.get(description));
1171
1172    // Setup attributes
1173    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1174            gMeshStride, &mMeshVertices[0].position[0]);
1175
1176    // Setup uniforms
1177    mModelView.loadTranslate(left, top, 0.0f);
1178    mModelView.scale(right - left, bottom - top, 1.0f);
1179    if (!ignoreTransform) {
1180        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1181    } else {
1182        mat4 identity;
1183        mCaches.currentProgram->set(mOrthoMatrix, mModelView, identity);
1184    }
1185    mCaches.currentProgram->setColor(r, g, b, a);
1186
1187    // Setup attributes and uniforms required by the shaders
1188    if (mShader) {
1189        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
1190    }
1191    if (mColorFilter) {
1192        mColorFilter->setupProgram(mCaches.currentProgram);
1193    }
1194}
1195
1196void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1197        const Texture* texture, const SkPaint* paint) {
1198    int alpha;
1199    SkXfermode::Mode mode;
1200    getAlphaAndMode(paint, &alpha, &mode);
1201
1202    drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
1203            texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1204            GL_TRIANGLE_STRIP, gMeshCount);
1205}
1206
1207void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1208        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
1209    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
1210            &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1211            GL_TRIANGLE_STRIP, gMeshCount);
1212}
1213
1214void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
1215        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
1216        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
1217        bool swapSrcDst, bool ignoreTransform) {
1218    clearLayerRegions();
1219
1220    ProgramDescription description;
1221    description.hasTexture = true;
1222    const bool setColor = description.setColor(alpha, alpha, alpha, alpha);
1223    if (mColorFilter) {
1224        mColorFilter->describe(description, mExtensions);
1225    }
1226
1227    mModelView.loadTranslate(left, top, 0.0f);
1228    mModelView.scale(right - left, bottom - top, 1.0f);
1229
1230    chooseBlending(blend || alpha < 1.0f, mode, description, swapSrcDst);
1231
1232    useProgram(mCaches.programCache.get(description));
1233    if (!ignoreTransform) {
1234        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1235    } else {
1236        mat4 m;
1237        mCaches.currentProgram->set(mOrthoMatrix, mModelView, m);
1238    }
1239
1240    // Texture
1241    bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, 0);
1242    glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0);
1243
1244    // Always premultiplied
1245    if (setColor) {
1246        mCaches.currentProgram->setColor(alpha, alpha, alpha, alpha);
1247    }
1248
1249    // Mesh
1250    int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1251    glEnableVertexAttribArray(texCoordsSlot);
1252    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1253            gMeshStride, vertices);
1254    glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1255
1256    // Color filter
1257    if (mColorFilter) {
1258        mColorFilter->setupProgram(mCaches.currentProgram);
1259    }
1260
1261    glDrawArrays(drawMode, 0, elementsCount);
1262    glDisableVertexAttribArray(texCoordsSlot);
1263}
1264
1265void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
1266        ProgramDescription& description, bool swapSrcDst) {
1267    blend = blend || mode != SkXfermode::kSrcOver_Mode;
1268    if (blend) {
1269        if (mode < SkXfermode::kPlus_Mode) {
1270            if (!mCaches.blend) {
1271                glEnable(GL_BLEND);
1272            }
1273
1274            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
1275            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
1276
1277            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
1278                glBlendFunc(sourceMode, destMode);
1279                mCaches.lastSrcMode = sourceMode;
1280                mCaches.lastDstMode = destMode;
1281            }
1282        } else {
1283            // These blend modes are not supported by OpenGL directly and have
1284            // to be implemented using shaders. Since the shader will perform
1285            // the blending, turn blending off here
1286            if (mExtensions.hasFramebufferFetch()) {
1287                description.framebufferMode = mode;
1288                description.swapSrcDst = swapSrcDst;
1289            }
1290
1291            if (mCaches.blend) {
1292                glDisable(GL_BLEND);
1293            }
1294            blend = false;
1295        }
1296    } else if (mCaches.blend) {
1297        glDisable(GL_BLEND);
1298    }
1299    mCaches.blend = blend;
1300}
1301
1302bool OpenGLRenderer::useProgram(Program* program) {
1303    if (!program->isInUse()) {
1304        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
1305        program->use();
1306        mCaches.currentProgram = program;
1307        return false;
1308    }
1309    return true;
1310}
1311
1312void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
1313    TextureVertex* v = &mMeshVertices[0];
1314    TextureVertex::setUV(v++, u1, v1);
1315    TextureVertex::setUV(v++, u2, v1);
1316    TextureVertex::setUV(v++, u1, v2);
1317    TextureVertex::setUV(v++, u2, v2);
1318}
1319
1320void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
1321    if (paint) {
1322        if (!mExtensions.hasFramebufferFetch()) {
1323            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
1324            if (!isMode) {
1325                // Assume SRC_OVER
1326                *mode = SkXfermode::kSrcOver_Mode;
1327            }
1328        } else {
1329            *mode = getXfermode(paint->getXfermode());
1330        }
1331
1332        // Skia draws using the color's alpha channel if < 255
1333        // Otherwise, it uses the paint's alpha
1334        int color = paint->getColor();
1335        *alpha = (color >> 24) & 0xFF;
1336        if (*alpha == 255) {
1337            *alpha = paint->getAlpha();
1338        }
1339    } else {
1340        *mode = SkXfermode::kSrcOver_Mode;
1341        *alpha = 255;
1342    }
1343}
1344
1345SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
1346    if (mode == NULL) {
1347        return SkXfermode::kSrcOver_Mode;
1348    }
1349    return mode->fMode;
1350}
1351
1352void OpenGLRenderer::bindTexture(GLuint texture, GLenum wrapS, GLenum wrapT, GLuint textureUnit) {
1353    glActiveTexture(gTextureUnits[textureUnit]);
1354    glBindTexture(GL_TEXTURE_2D, texture);
1355    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
1356    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
1357}
1358
1359}; // namespace uirenderer
1360}; // namespace android
1361