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